subrascasse

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

Core.swift (48517B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import Foundation
      3 
      4 // A port of Subsurface's planner (`core/deco.cpp`, `core/planner.cpp`, `core/gas.cpp`, GPL-2.0) that keeps its
      5 // units and its rounding: depths in millimetres, times in whole seconds, pressures rounded to the millibar, ascent
      6 // by steps of two seconds. Staying that close is what lets the tests compare run times with Subsurface's own,
      7 // to the second. The public planner (`Planner.swift`) converts to and from these.
      8 
      9 enum CoreMode: Sendable { case openCircuit, closedCircuit, semiClosed }
     10 
     11 struct CoreEnvironment: Sendable {
     12     var surfaceMbar = 1013
     13     /// Grams per ten litres, as Subsurface stores it: 10300 for sea water, 10000 for fresh water.
     14     var salinity = 10300
     15 
     16     var specificWeight: Double { Double(salinity) * 0.981 / 100_000 }
     17     var surfaceBar: Double { Double(surfaceMbar) / 1000 }
     18     func mbar(_ depth: Int) -> Int { Int((Double(surfaceMbar) + Double(depth) * specificWeight).rounded(.toNearestOrEven)) }
     19     func bar(_ depth: Int) -> Double { Double(mbar(depth)) / 1000 }
     20     func atm(_ depth: Int) -> Double { Double(mbar(depth)) / 1013 }
     21     /// Depth for a pressure above the surface's, in millimetres.
     22     func depth(relativeMbar: Int) -> Int { Int((Double(relativeMbar) / specificWeight).rounded(.toNearestOrEven)) }
     23 }
     24 
     25 /// A gas in per mille, as Subsurface handles it.
     26 struct CoreGas: Sendable, Equatable {
     27     var o2: Int
     28     var he: Int
     29     var n2: Int { 1000 - o2 - he }
     30 }
     31 
     32 struct CorePressures { var o2 = 0.0, n2 = 0.0, he = 0.0 }
     33 
     34 /// The state of the decompression model, and the model itself. A value: copying it is Subsurface's "cache".
     35 struct DecoState: Sendable {
     36     static let n2A = Tissues.n2A, n2B = Tissues.n2B, n2HalfLife = Tissues.n2HalfLife
     37     static let heA = Tissues.heA, heB = Tissues.heB, heHalfLife = Tissues.heHalfLife
     38     static let waterVapour = 0.0627
     39     static let waterVapourSchreiner = 0.0493
     40     static let conservatismLevels = [1.0, 1.05, 1.12, 1.22, 1.35]
     41 
     42     private static func factors(_ halfLives: [Double], seconds: Double) -> [Double] {
     43         halfLives.map { 1 - exp(-seconds * 1.155245301e-02 / $0) }
     44     }
     45     static let n2Factor1 = factors(n2HalfLife, seconds: 1), n2Factor2 = factors(n2HalfLife, seconds: 2)
     46     static let heFactor1 = factors(heHalfLife, seconds: 1), heFactor2 = factors(heHalfLife, seconds: 2)
     47 
     48     // VPM-B constants.
     49     static let critRadiusN2 = 0.55, critRadiusHe = 0.45
     50     static let critVolumeLambda = 199.58
     51     static let gradientOfImperm = 8.30865
     52     static let surfaceTensionGamma = 0.18137175
     53     static let skinCompressionGammaC = 2.6040525
     54     static let regenerationTime = 20160.0
     55     static let otherGasesPressure = 0.1359888
     56 
     57     // Configuration.
     58     var vpmb = false
     59     var conservatism = 0
     60     var gfLow = 0.35, gfHigh = 0.75
     61     var environment = CoreEnvironment()
     62     /// Semi-closed rebreather: oxygen metabolised (ml/min), bottom consumption (ml/min), dump ratio (per mille).
     63     var o2Consumption = 720.0, bottomSac = 20_000.0, pscrRatio = 100.0
     64 
     65     // Tissues.
     66     var n2 = [Double](repeating: 0, count: 16)
     67     var he = [Double](repeating: 0, count: 16)
     68     var a = [Double](repeating: 0, count: 16)
     69     var b = [Double](repeating: 0, count: 16)
     70     var gfLowPressure = 0.0
     71     var guidingTissue = -1
     72 
     73     // VPM-B.
     74     var maxN2Crushing = [Double](repeating: 0, count: 16)
     75     var maxHeCrushing = [Double](repeating: 0, count: 16)
     76     var crushingOnsetTension = [Double](repeating: 0, count: 16)
     77     var n2RegenRadius = [Double](repeating: 0, count: 16)
     78     var heRegenRadius = [Double](repeating: 0, count: 16)
     79     var initialN2Gradient = [Double](repeating: 0, count: 16)
     80     var initialHeGradient = [Double](repeating: 0, count: 16)
     81     var bottomN2Gradient = [Double](repeating: 0, count: 16)
     82     var bottomHeGradient = [Double](repeating: 0, count: 16)
     83     var maxAmbientPressure = 0.0
     84     var firstCeilingMbar = 0
     85     var maxBottomCeilingMbar = 0
     86     var decoTime = 10_000_000
     87 
     88     private var wv: Double { vpmb ? Self.waterVapourSchreiner : Self.waterVapour }
     89     private var critN2: Double { Self.critRadiusN2 * Self.conservatismLevels[min(max(conservatism, 0), 4)] }
     90     private var critHe: Double { Self.critRadiusHe * Self.conservatismLevels[min(max(conservatism, 0), 4)] }
     91 
     92     /// `clear_deco`: a diver in equilibrium with air at the surface.
     93     mutating func clear() {
     94         let surface = environment.surfaceBar
     95         for index in 0..<16 {
     96             n2[index] = (surface - wv) * 0.781
     97             he[index] = 0
     98             maxN2Crushing[index] = 0
     99             maxHeCrushing[index] = 0
    100             n2RegenRadius[index] = critN2
    101             heRegenRadius[index] = critHe
    102         }
    103         gfLowPressure = surface + 1.0
    104         maxAmbientPressure = 0
    105         firstCeilingMbar = 0
    106         maxBottomCeilingMbar = 0
    107         guidingTissue = -1
    108     }
    109 
    110     /// `deco_state_cache::restore(target, keep_vpmb_state = true)`: back to `cache`, keeping what the previous
    111     /// pass of the VPM-B iteration worked out.
    112     mutating func restore(_ cache: DecoState) {
    113         var restored = cache
    114         restored.bottomN2Gradient = bottomN2Gradient
    115         restored.bottomHeGradient = bottomHeGradient
    116         restored.initialN2Gradient = initialN2Gradient
    117         restored.initialHeGradient = initialHeGradient
    118         restored.firstCeilingMbar = firstCeilingMbar
    119         restored.maxBottomCeilingMbar = maxBottomCeilingMbar
    120         restored.decoTime = decoTime
    121         self = restored
    122     }
    123 
    124     // MARK: Gas loading
    125 
    126     /// `fill_pressures`: what the diver's lungs see, for an ambient pressure already reduced by the water vapour.
    127     func pressures(ambient: Double, gas: CoreGas, setpoint: Double, mode: CoreMode) -> CorePressures {
    128         var out = CorePressures()
    129         if mode != .openCircuit, setpoint > 0 {
    130             if setpoint >= ambient {
    131                 out.o2 = ambient
    132             } else {
    133                 out.o2 = setpoint
    134                 if gas.o2 != 1000 {
    135                     out.he = (ambient - out.o2) * Double(gas.he) / Double(1000 - gas.o2)
    136                     out.n2 = ambient - out.o2 - out.he
    137                 }
    138             }
    139         } else if mode == .semiClosed {
    140             let dropped = (1 - Double(gas.o2) / 1000) * o2Consumption / (bottomSac * pscrRatio) * 1_000_000
    141             out.o2 = Double(max(0, Int(Double(gas.o2) * ambient - dropped))) / 1000
    142             if gas.o2 != 1000 {
    143                 out.he = (ambient - out.o2) * Double(gas.he) / Double(1000 - gas.o2)
    144                 out.n2 = (ambient - out.o2) * Double(gas.n2) / Double(1000 - gas.o2)
    145             }
    146         } else {
    147             out.o2 = Double(gas.o2) / 1000 * ambient
    148             out.he = Double(gas.he) / 1000 * ambient
    149             out.n2 = Double(gas.n2) / 1000 * ambient
    150         }
    151         return out
    152     }
    153 
    154     /// Partial pressure of oxygen breathed at an ambient pressure, in bar.
    155     func ppO2(pressure: Double, gas: CoreGas, setpoint: Int, mode: CoreMode) -> Double {
    156         pressures(ambient: pressure, gas: gas, setpoint: Double(setpoint) / 1000, mode: mode).o2
    157     }
    158 
    159     /// `add_segment`.
    160     mutating func addSegment(pressure: Double, gas: CoreGas, seconds: Int, setpoint: Int, mode: CoreMode) {
    161         let inspired = pressures(ambient: pressure - wv, gas: gas, setpoint: Double(setpoint) / 1000, mode: mode)
    162         // One and two seconds are what the planner asks for millions of times: their factors are kept ready.
    163         if seconds == 1 || seconds == 2 {
    164             let n2Factors = seconds == 1 ? Self.n2Factor1 : Self.n2Factor2, heFactors = seconds == 1 ? Self.heFactor1 : Self.heFactor2
    165             for index in 0..<16 {
    166                 n2[index] += (inspired.n2 - n2[index]) * n2Factors[index]
    167                 he[index] += (inspired.he - he[index]) * heFactors[index]
    168             }
    169         } else {
    170             let time = Double(seconds)
    171             for index in 0..<16 {
    172                 n2[index] += (inspired.n2 - n2[index]) * (1 - exp(-time * 1.155245301e-02 / Self.n2HalfLife[index]))
    173                 he[index] += (inspired.he - he[index]) * (1 - exp(-time * 1.155245301e-02 / Self.heHalfLife[index]))
    174             }
    175         }
    176         if vpmb { calcCrushingPressure(pressure) }
    177     }
    178 
    179     // MARK: Ceiling
    180 
    181     /// `tissue_tolerance_calc`: the lowest ambient pressure tolerated, in bar.
    182     mutating func tolerance(pressure: Double) -> Double {
    183         let surface = environment.surfaceBar
    184         var result = 0.0
    185         for index in 0..<16 {
    186             let total = n2[index] + he[index]
    187             a[index] = (Self.n2A[index] * n2[index] + Self.heA[index] * he[index]) / total
    188             b[index] = (Self.n2B[index] * n2[index] + Self.heB[index] * he[index]) / total
    189         }
    190         if !vpmb {
    191             var lowest = 0.0
    192             for index in 0..<16 {
    193                 let total = n2[index] + he[index]
    194                 let ceiling = (b[index] * total - gfLow * a[index] * b[index]) / ((1 - b[index]) * gfLow + b[index])
    195                 if ceiling > lowest { lowest = ceiling }
    196                 if lowest > gfLowPressure { gfLowPressure = lowest }
    197             }
    198             let low = gfLowPressure
    199             for index in 0..<16 {
    200                 let total = n2[index] + he[index]
    201                 var tolerated = result
    202                 if (surface / b[index] + a[index] - surface) * gfHigh + surface < (low / b[index] + a[index] - low) * gfLow + low {
    203                     tolerated = (-a[index] * b[index] * (gfHigh * low - gfLow * surface)
    204                                  - (1 - b[index]) * (gfHigh - gfLow) * low * surface
    205                                  + b[index] * (low - surface) * total)
    206                         / (-a[index] * b[index] * (gfHigh - gfLow)
    207                            + (1 - b[index]) * (gfLow * low - gfHigh * surface)
    208                            + b[index] * (low - surface))
    209                 }
    210                 if tolerated >= result {
    211                     guidingTissue = index
    212                     result = tolerated
    213                 }
    214             }
    215         } else {
    216             // The Boyle-compensated gradient depends on the ambient pressure: iterate until the ceiling is stable.
    217             result = pressure
    218             var reference = 0.0
    219             repeat {
    220                 reference = result
    221                 result = 0
    222                 for index in 0..<16 {
    223                     let tolerated = vpmbToleratedPressure(reference: reference, index)
    224                     if tolerated >= result {
    225                         guidingTissue = index
    226                         result = tolerated
    227                     }
    228                 }
    229             } while abs(result - reference) > 0.01
    230         }
    231         return result
    232     }
    233 
    234     /// `deco_allowed_depth`: the ceiling, in millimetres.
    235     func allowedDepth(tolerance: Double, smooth: Bool = true) -> Int {
    236         let delta = tolerance > environment.surfaceBar ? tolerance - environment.surfaceBar : 0
    237         var depth = environment.depth(relativeMbar: Int((delta * 1000).rounded(.toNearestOrEven)))
    238         if !smooth { depth = Int((Double(depth) / 3000).rounded(.up) * 3000) }
    239         return depth
    240     }
    241 
    242     // MARK: VPM-B
    243 
    244     private static func cube(_ x: Double) -> Double { x * x * x }
    245 
    246     /// x³ − B x − C = 0.
    247     private static func solveCubic2(_ B: Double, _ C: Double) -> Double {
    248         let discriminant = 27 * C * C - 4 * cube(B)
    249         if discriminant < 0 {
    250             return 2 * (B / 3).squareRoot() * cos(acos(3 * C * (3 / B).squareRoot() / (2 * B)) / 3)
    251         }
    252         let denominator = pow(9 * C + (3 * discriminant).squareRoot(), 1.0 / 3)
    253         return pow(2.0 / 3, 1.0 / 3) * B / denominator + denominator / pow(18, 1.0 / 3)
    254     }
    255 
    256     /// A r³ − B r² − C = 0.
    257     private static func solveCubic(_ A: Double, _ B: Double, _ C: Double) -> Double {
    258         let BA = B / A, CA = C / A
    259         let discriminant = CA * (4 * cube(BA) + 27 * CA)
    260         guard discriminant >= 0 else { return 0 }
    261         let denominator = pow(cube(BA) + 1.5 * (9 * CA + 3.0.squareRoot() * discriminant.squareRoot()), 1.0 / 3)
    262         return (BA + BA * BA / denominator + denominator) / 3
    263     }
    264 
    265     private func updateGradient(nextStopPressure: Double, firstGradient: Double) -> Double {
    266         let B = Self.cube(firstGradient) / (Double(firstCeilingMbar) / 1000 + firstGradient)
    267         return Self.solveCubic2(B, nextStopPressure * B)
    268     }
    269 
    270     private func vpmbToleratedPressure(reference: Double, _ index: Int) -> Double {
    271         var n2Gradient = bottomN2Gradient[index], heGradient = bottomHeGradient[index]
    272         if !(reference >= Double(firstCeilingMbar) / 1000 || firstCeilingMbar == 0) {
    273             n2Gradient = updateGradient(nextStopPressure: reference, firstGradient: bottomN2Gradient[index])
    274             heGradient = updateGradient(nextStopPressure: reference, firstGradient: bottomHeGradient[index])
    275         }
    276         let total = (n2Gradient * n2[index] + heGradient * he[index]) / (n2[index] + he[index])
    277         return n2[index] + he[index] + Self.otherGasesPressure - total
    278     }
    279 
    280     /// `vpmb_start_gradient`.
    281     mutating func vpmbStartGradient() {
    282         let factor = 2 * (Self.surfaceTensionGamma / Self.skinCompressionGammaC) * (Self.skinCompressionGammaC - Self.surfaceTensionGamma)
    283         for index in 0..<16 {
    284             initialN2Gradient[index] = factor / n2RegenRadius[index]
    285             bottomN2Gradient[index] = initialN2Gradient[index]
    286             initialHeGradient[index] = factor / heRegenRadius[index]
    287             bottomHeGradient[index] = initialHeGradient[index]
    288         }
    289     }
    290 
    291     private func surfacePhase(he hePressure: Double, n2 n2Pressure: Double, heConstant: Double, n2Constant: Double) -> Double {
    292         let inspired = (environment.surfaceBar - wv) * 0.79
    293         if n2Pressure > inspired {
    294             return (hePressure / heConstant + (n2Pressure - inspired) / n2Constant) / (hePressure + n2Pressure - inspired)
    295         }
    296         if hePressure + n2Pressure >= inspired {
    297             let decay = 1 / (n2Constant - heConstant) * log((inspired - n2Pressure) / hePressure)
    298             let integral = hePressure / heConstant * (1 - exp(-heConstant * decay))
    299                 + (n2Pressure - inspired) / n2Constant * (1 - exp(-n2Constant * decay))
    300             return integral / (hePressure + n2Pressure - inspired)
    301         }
    302         return 0
    303     }
    304 
    305     /// `vpmb_next_gradient`: the gradients allowed once the length of the decompression is known.
    306     mutating func vpmbNextGradient(decoTime seconds: Double) {
    307         let decoMinutes = seconds / 60
    308         let gamma = Self.surfaceTensionGamma, gammaC = Self.skinCompressionGammaC, lambda = Self.critVolumeLambda
    309         for index in 0..<16 {
    310             let desat = decoMinutes + surfacePhase(he: he[index], n2: n2[index],
    311                                                    heConstant: log(2.0) / Self.heHalfLife[index], n2Constant: log(2.0) / Self.n2HalfLife[index])
    312             let n2B = initialN2Gradient[index] + lambda * gamma / (gammaC * desat)
    313             let heB = initialHeGradient[index] + lambda * gamma / (gammaC * desat)
    314             let n2C = gamma * gamma * lambda * maxN2Crushing[index] / (gammaC * gammaC * desat)
    315             let heC = gamma * gamma * lambda * maxHeCrushing[index] / (gammaC * gammaC * desat)
    316             bottomN2Gradient[index] = 0.5 * (n2B + (n2B * n2B - 4 * n2C).squareRoot())
    317             bottomHeGradient[index] = 0.5 * (heB + (heB * heB - 4 * heC).squareRoot())
    318         }
    319     }
    320 
    321     /// `nuclear_regeneration`.
    322     mutating func nuclearRegeneration(seconds: Double) {
    323         let minutes = seconds / 60
    324         let span = 2 * (Self.skinCompressionGammaC - Self.surfaceTensionGamma)
    325         for index in 0..<16 {
    326             let crushedN2 = 1 / (maxN2Crushing[index] / span + 1 / critN2)
    327             let crushedHe = 1 / (maxHeCrushing[index] / span + 1 / critHe)
    328             n2RegenRadius[index] = crushedN2 + (critN2 - crushedN2) * (1 - exp(-minutes / Self.regenerationTime))
    329             heRegenRadius[index] = crushedHe + (critHe - crushedHe) * (1 - exp(-minutes / Self.regenerationTime))
    330         }
    331     }
    332 
    333     private func innerPressure(critRadius: Double, onsetTension: Double, ambient: Double) -> Double {
    334         let span = 2 * (Self.skinCompressionGammaC - Self.surfaceTensionGamma)
    335         let onsetRadius = 1 / (Self.gradientOfImperm / span + 1 / critRadius)
    336         let A = ambient - Self.gradientOfImperm + span / onsetRadius
    337         let C = onsetTension * pow(onsetRadius, 3)
    338         let radius = Self.solveCubic(A, span, C)
    339         return onsetTension * onsetRadius * onsetRadius * onsetRadius / (radius * radius * radius)
    340     }
    341 
    342     /// `calc_crushing_pressure`.
    343     mutating func calcCrushingPressure(_ pressure: Double) {
    344         for index in 0..<16 {
    345             let tension = n2[index] + he[index] + Self.otherGasesPressure
    346             let gradient = pressure - tension
    347             var n2Crushing = gradient, heCrushing = gradient
    348             if gradient <= Self.gradientOfImperm {
    349                 crushingOnsetTension[index] = tension
    350             } else {
    351                 if maxAmbientPressure >= pressure { return }
    352                 n2Crushing = pressure - innerPressure(critRadius: critN2, onsetTension: crushingOnsetTension[index], ambient: pressure)
    353                 heCrushing = pressure - innerPressure(critRadius: critHe, onsetTension: crushingOnsetTension[index], ambient: pressure)
    354             }
    355             maxN2Crushing[index] = max(maxN2Crushing[index], n2Crushing)
    356             maxHeCrushing[index] = max(maxHeCrushing[index], heCrushing)
    357         }
    358         maxAmbientPressure = max(pressure, maxAmbientPressure)
    359     }
    360 }
    361 
    362 // MARK: The planner
    363 
    364 struct CoreWaypoint: Sendable {
    365     /// Seconds taken to get to `depth` from the previous waypoint (or to stay there).
    366     var seconds: Int
    367     var depth: Int
    368     var cylinder: Int
    369     var setpoint = 0
    370     var mode = CoreMode.openCircuit
    371 }
    372 
    373 struct CoreCylinder: Sendable {
    374     var gas: CoreGas
    375     /// Depth from which the gas is switched to on the way up; nil for a gas that is not used for the ascent.
    376     var changeDepth: Int?
    377     /// A setpoint to switch to at `changeDepth` on a closed circuit (Subsurface's "SP" cylinders), in millibars.
    378     var setpoint = 0
    379     /// Water capacity in millilitres and filling pressure in millibars; 0 when unknown.
    380     var sizeMl = 0
    381     var startMbar = 0
    382 }
    383 
    384 /// A dive made before the one being planned: its profile, and how long before the next dive (or the plan) it ended.
    385 struct CorePriorDive: Sendable {
    386     struct Sample: Sendable {
    387         var time: Int
    388         var depth: Int
    389         var gas: CoreGas
    390         var setpoint = 0
    391         var mode = CoreMode.openCircuit
    392     }
    393     var samples: [Sample]
    394     /// Seconds between the end of this dive and the start of the next one.
    395     var surfaceInterval: Int
    396 }
    397 
    398 struct CorePrefs: Sendable {
    399     /// Ascent rates in millimetres per second: below 75 % of the average depth, down to 50 %, up to 6 m, above.
    400     var ascRate75 = 150, ascRate50 = 150, ascRateStops = 150, ascRateLast6m = 150
    401     var lastStopAt6m = false
    402     var minSwitchDuration = 60
    403     var switchAtRequiredStop = false
    404     var oxygenBreaks = false
    405     var bailout = false
    406     var problemSolvingMinutes = 4
    407     /// Millilitres per minute.
    408     var bottomSac = 20_000.0, decoSac = 17_000.0
    409     var timestep = 60
    410     /// Stops every 10 ft instead of every 3 m.
    411     var imperialStops = false
    412     /// Subsurface's recreational mode: the bottom time is extended to the no-stop limit or to what the gas
    413     /// allows, then a direct ascent with an optional safety stop.
    414     var recreational = false
    415     var safetyStop = true
    416     var reserveMbar = 40_000
    417 }
    418 
    419 struct CoreTrackPoint: Sendable, Equatable {
    420     var time: Int
    421     var depth: Int
    422     var cylinder: Int
    423     var mode: CoreMode
    424     var setpoint: Int
    425 }
    426 
    427 struct CoreStop: Sendable, Equatable {
    428     var depth: Int
    429     var seconds: Int
    430     var cylinder: Int
    431     var isGasSwitch: Bool
    432     var endTime: Int
    433 }
    434 
    435 struct CoreOutput: Sendable {
    436     var track: [CoreTrackPoint] = []
    437     var stops: [CoreStop] = []
    438     var runtime = 0
    439     var bottomTime = 0
    440     var bottomDepth = 0
    441     var bottomCylinder = 0
    442     /// Millilitres at the surface, per cylinder; and the part breathed from each cylinder after the bottom time.
    443     var gasUsed: [Double] = []
    444     var decoGasUsed: [Double] = []
    445     var cns = 0.0
    446     var otu = 0.0
    447     var firstCeilingDepth = 0
    448     var timedOut = false
    449     /// Recreational mode: the entered dive already needs decompression stops.
    450     var exceedsNoStopLimit = false
    451     /// Recreational mode: seconds added at the bottom.
    452     var bottomExtension = 0
    453     var hasSafetyStop = false
    454     var finalState: DecoState
    455 }
    456 
    457 enum CorePlanner {
    458     static let baseTimestep = 2
    459     static let decoLevels: [Int] = Array(stride(from: 0, through: 90_000, by: 3000))
    460         + [100_000, 110_000, 120_000, 130_000, 140_000, 150_000, 160_000, 170_000, 180_000, 190_000, 200_000,
    461            220_000, 240_000, 260_000, 280_000, 300_000, 320_000, 340_000, 360_000, 380_000]
    462 
    463     static let decoLevelsImperial: [Int] = (Array(stride(from: 0, through: 300, by: 10))
    464         + [333, 367, 400, 433, 467, 500, 533, 567, 600, 633, 667, 733, 800, 867, 933, 1000, 1067, 1133, 1200, 1267])
    465         .map { Int((Double($0) * 304.8).rounded(.toNearestOrEven)) }
    466 
    467     /// `init_decompression`: the tissues at the start of the plan, after the dives made before it.
    468     static func initialState(_ model: DecoState, after prior: [CorePriorDive]) -> DecoState {
    469         var state = model
    470         state.clear()
    471         let environment = state.environment
    472         let air = CoreGas(o2: 209, he: 0)
    473         for dive in prior {
    474             for (previous, sample) in zip(dive.samples, dive.samples.dropFirst()) where sample.time > previous.time {
    475                 for second in previous.time..<sample.time {
    476                     let exact = (Double(previous.depth) * Double(sample.time - second) + Double(sample.depth) * Double(second - previous.time))
    477                         / Double(sample.time - previous.time)
    478                     state.addSegment(pressure: environment.bar(Int(exact.rounded(.toNearestOrEven))), gas: previous.gas, seconds: 1,
    479                                      setpoint: previous.setpoint, mode: previous.mode)
    480                 }
    481             }
    482             state.maxN2Crushing = [Double](repeating: 0, count: 16)
    483             state.maxHeCrushing = state.maxN2Crushing
    484             state.maxAmbientPressure = 0
    485             state.firstCeilingMbar = 0
    486             state.maxBottomCeilingMbar = 0
    487             if dive.surfaceInterval > 0 {
    488                 state.addSegment(pressure: environment.surfaceBar, gas: air, seconds: dive.surfaceInterval, setpoint: 0, mode: .openCircuit)
    489             }
    490         }
    491         return state
    492     }
    493 
    494     static func ascentVelocity(depth: Int, average: Int, _ prefs: CorePrefs) -> Int {
    495         if depth * 4 > average * 3 { return prefs.ascRate75 }
    496         if depth * 2 > average { return prefs.ascRate50 }
    497         return depth > 6000 ? prefs.ascRateStops : prefs.ascRateLast6m
    498     }
    499 
    500     /// `trial_ascent`.
    501     private static func trialAscent(_ state: DecoState, wait: Int, from depth: Int, to stopLevel: Int, average: Int, gas: CoreGas,
    502                                     setpoint: Int, mode: CoreMode, prefs: CorePrefs) -> Bool {
    503         var trial = state
    504         let environment = state.environment
    505         if wait > 0 { trial.addSegment(pressure: environment.bar(depth), gas: gas, seconds: wait, setpoint: setpoint, mode: mode) }
    506         if trial.vpmb {
    507             let limit = trial.tolerance(pressure: environment.bar(stopLevel))
    508             if trial.allowedDepth(tolerance: limit) > stopLevel { return false }
    509         }
    510         var current = depth
    511         while current > stopLevel {
    512             var rise = ascentVelocity(depth: current, average: average, prefs) * baseTimestep
    513             if rise > current { rise = current }
    514             trial.addSegment(pressure: environment.bar(current), gas: gas, seconds: baseTimestep, setpoint: setpoint, mode: mode)
    515             let limit = trial.tolerance(pressure: environment.bar(current))
    516             if trial.allowedDepth(tolerance: limit) > current - rise { return false }
    517             current -= rise
    518         }
    519         return true
    520     }
    521 
    522     /// `wait_until`: the earliest whole step of run time at which the ascent to the next stop is clear.
    523     private static func waitUntil(_ state: DecoState, clock: Int, min: Int, leap: Int, step: Int, depth: Int, target: Int, average: Int,
    524                                   gas: CoreGas, setpoint: Int, mode: CoreMode, prefs: CorePrefs) -> Int {
    525         var low = min, jump = leap
    526         while true {
    527             if low >= 48 * 3600 { return 50 * 3600 }
    528             let upper = low + jump + step - 1 - (low + jump - 1) % step
    529             if !trialAscent(state, wait: upper - clock, from: depth, to: target, average: average, gas: gas, setpoint: setpoint, mode: mode, prefs: prefs) {
    530                 low = upper
    531                 continue
    532             }
    533             if upper - low <= step { return upper }
    534             jump /= 2
    535         }
    536     }
    537 
    538     /// `sort_stops`: the deco levels and the gas switch depths in one ascending list. A switch depth that is
    539     /// also a deco level appears once; the list is padded with zeros at its start.
    540     private static func sortStops(levels: [Int], count: Int, changes: [(depth: Int, cylinder: Int)]) -> [Int] {
    541         guard !changes.isEmpty else { return Array(levels[0..<count]) }
    542         let total = count + changes.count
    543         var out = [Int](repeating: 0, count: total)
    544         var index = total - 1, gi = changes.count - 1, di = count - 1
    545         while index >= 0 {
    546             if levels[di] > changes[gi].depth {
    547                 out[index] = levels[di]
    548                 di -= 1
    549             } else if levels[di] == changes[gi].depth {
    550                 out[index] = levels[di]
    551                 di -= 1
    552                 gi -= 1
    553             } else {
    554                 out[index] = changes[gi].depth
    555                 gi -= 1
    556             }
    557             index -= 1
    558             if di < 0 {
    559                 while gi >= 0 {
    560                     out[index] = changes[gi].depth
    561                     index -= 1
    562                     gi -= 1
    563                 }
    564                 break
    565             }
    566             if gi < 0 {
    567                 while di >= 0 {
    568                     out[index] = levels[di]
    569                     index -= 1
    570                     di -= 1
    571                 }
    572                 break
    573             }
    574         }
    575         while index >= 0 {
    576             out[index] = 0
    577             index -= 1
    578         }
    579         return out
    580     }
    581 
    582     static func plan(waypoints: [CoreWaypoint], cylinders: [CoreCylinder], prefs: CorePrefs, model: DecoState,
    583                      after prior: [CorePriorDive] = []) -> CoreOutput {
    584         var state = initialState(model, after: prior)
    585         let environment = state.environment
    586         var output = CoreOutput(finalState: state)
    587         output.gasUsed = [Double](repeating: 0, count: cylinders.count)
    588         output.decoGasUsed = output.gasUsed
    589         guard let last = waypoints.last, !cylinders.isEmpty else { return output }
    590         let pscrFactor = state.pscrRatio / 1000
    591 
    592         func use(_ output: inout CoreOutput, _ cylinder: Int, depth: Int, toDepth: Int, seconds: Int, sac: Double, deco: Bool, mode: CoreMode) {
    593             // A closed circuit only adds the oxygen that is metabolised: its diluent use is not planned here.
    594             guard mode != .closedCircuit else { return }
    595             let used = environment.atm((depth + toDepth) / 2) * sac / 60 * Double(seconds) * (mode == .semiClosed ? pscrFactor : 1)
    596             output.gasUsed[cylinder] += used
    597             if deco { output.decoGasUsed[cylinder] += used }
    598         }
    599         func oxygen(_ output: inout CoreOutput, _ state: DecoState, depth: Int, cylinder: Int, seconds: Int, setpoint: Int, mode: CoreMode) {
    600             let ppO2 = state.ppO2(pressure: environment.bar(depth), gas: cylinders[cylinder].gas, setpoint: setpoint, mode: mode)
    601             output.cns += OxygenExposure.cns(ppO2: ppO2, seconds: Double(seconds))
    602             output.otu += OxygenExposure.otu(ppO2: ppO2, seconds: Double(seconds))
    603         }
    604 
    605         // The part the diver entered (`tissue_at_end`), second by second along each leg.
    606         var clock = 0, depth = 0
    607         var integral = 0.0
    608         var previousSetpoint: Int?
    609         output.track.append(CoreTrackPoint(time: 0, depth: 0, cylinder: waypoints[0].cylinder, mode: waypoints[0].mode, setpoint: waypoints[0].setpoint))
    610         for waypoint in waypoints {
    611             let setpoint = previousSetpoint ?? waypoint.setpoint
    612             let gas = cylinders[waypoint.cylinder].gas
    613             if state.vpmb, depth > waypoint.depth {
    614                 // The ceiling before an ascent within the entered part can be the deepest of the dive.
    615                 state.nuclearRegeneration(seconds: Double(clock))
    616                 state.vpmbStartGradient()
    617                 let ceiling = environment.mbar(state.allowedDepth(tolerance: state.tolerance(pressure: environment.bar(depth))))
    618                 state.maxBottomCeilingMbar = max(state.maxBottomCeilingMbar, ceiling)
    619             }
    620             output.track.append(CoreTrackPoint(time: clock, depth: depth, cylinder: waypoint.cylinder, mode: waypoint.mode, setpoint: setpoint))
    621             if waypoint.seconds > 0 {
    622                 for second in 0..<waypoint.seconds {
    623                     let exact = (Double(depth) * Double(waypoint.seconds - second) + Double(waypoint.depth) * Double(second)) / Double(waypoint.seconds)
    624                     let at = Int(exact.rounded(.toNearestOrEven))
    625                     state.addSegment(pressure: environment.bar(at), gas: gas, seconds: 1, setpoint: setpoint, mode: waypoint.mode)
    626                     use(&output, waypoint.cylinder, depth: at, toDepth: at, seconds: 1, sac: prefs.bottomSac, deco: false, mode: waypoint.mode)
    627                     oxygen(&output, state, depth: at, cylinder: waypoint.cylinder, seconds: 1, setpoint: setpoint, mode: waypoint.mode)
    628                 }
    629                 if waypoint.depth > depth { state.calcCrushingPressure(environment.bar(waypoint.depth)) }
    630                 integral += Double(waypoint.depth + depth) * Double(waypoint.seconds) / 2
    631                 clock += waypoint.seconds
    632                 depth = waypoint.depth
    633             }
    634             previousSetpoint = waypoint.setpoint
    635             output.track.append(CoreTrackPoint(time: clock, depth: depth, cylinder: waypoint.cylinder, mode: waypoint.mode, setpoint: waypoint.setpoint))
    636         }
    637         let average = clock > 0 ? Int(integral / Double(clock)) : 0
    638         var bottomTime = clock
    639         var cylinder = last.cylinder
    640         var mode = last.mode
    641         var setpoint = last.setpoint
    642         output.bottomDepth = depth
    643         output.bottomCylinder = cylinder
    644 
    645         // The gases for the way up (`analyze_gaslist`): those usable from a depth above the bottom are switched
    646         // to on the way; of those usable at the bottom already, the one with the shallowest limit is taken first.
    647         let onLoop = mode == .closedCircuit && !prefs.bailout
    648         var changes = [(depth: Int, cylinder: Int)]()
    649         var firstAscentCylinder = -1
    650         do {
    651             var bestDepth = Int.max
    652             // On the loop only the setpoint switches count; off it, only the real gases.
    653             for (index, candidate) in cylinders.enumerated() where onLoop == (candidate.setpoint != 0) {
    654                 guard let change = candidate.changeDepth else { continue }
    655                 if change <= depth {
    656                     let position = changes.firstIndex { change < $0.depth } ?? changes.count
    657                     changes.insert((change, index), at: position)
    658                 } else if change < bestDepth {
    659                     bestDepth = change
    660                     firstAscentCylinder = index
    661                 }
    662             }
    663         }
    664         var breakCylinder = 0
    665         if prefs.oxygenBreaks, firstAscentCylinder != -1, cylinders[firstAscentCylinder].gas.o2 <= 320 { breakCylinder = firstAscentCylinder }
    666 
    667         var levels = prefs.imperialStops ? decoLevelsImperial : decoLevels
    668         if prefs.lastStopAt6m { levels[1] = 0 }
    669         var stopIndex = levels.firstIndex { $0 > depth } ?? levels.count
    670         if stopIndex > 0 { stopIndex -= 1 }
    671         let stopLevels = sortStops(levels: levels, count: stopIndex + 1, changes: changes)
    672         stopIndex += changes.count
    673         let bottomStopIndex = stopIndex
    674 
    675         state.nuclearRegeneration(seconds: Double(clock))
    676         state.vpmbStartGradient()
    677 
    678         if prefs.recreational {
    679             return recreational(output: output, state: state, clock: clock, depth: depth, cylinder: cylinder, mode: mode, setpoint: setpoint,
    680                                 average: average, cylinders: cylinders, prefs: prefs)
    681         }
    682 
    683         if firstAscentCylinder != -1, firstAscentCylinder != cylinder {
    684             cylinder = firstAscentCylinder
    685             output.track.append(CoreTrackPoint(time: clock, depth: depth, cylinder: cylinder, mode: mode, setpoint: setpoint))
    686         }
    687         if mode != .openCircuit, prefs.bailout {
    688             // Off the loop: time to sort the problem out at the bottom, on the bailout gas.
    689             mode = .openCircuit
    690             setpoint = 0
    691             let segment = max(prefs.minSwitchDuration, 60 * prefs.problemSolvingMinutes)
    692             state.addSegment(pressure: environment.bar(depth), gas: cylinders[cylinder].gas, seconds: segment, setpoint: setpoint, mode: mode)
    693             use(&output, cylinder, depth: depth, toDepth: depth, seconds: segment, sac: prefs.bottomSac, deco: false, mode: mode)
    694             oxygen(&output, state, depth: depth, cylinder: cylinder, seconds: segment, setpoint: setpoint, mode: mode)
    695             output.track.append(CoreTrackPoint(time: clock, depth: depth, cylinder: cylinder, mode: mode, setpoint: setpoint))
    696             bottomTime += segment
    697             output.track.append(CoreTrackPoint(time: bottomTime, depth: depth, cylinder: cylinder, mode: mode, setpoint: setpoint))
    698         }
    699         output.bottomTime = bottomTime
    700 
    701         var previousDecoTime = 100_000_000
    702         state.decoTime = 10_000_000
    703         let bottomCache = state
    704         let bottomDepth = depth
    705         let bottomCylinder = cylinder
    706         let bottomSetpoint = setpoint
    707         let entered = output
    708 
    709         // VPM-B iterates: the gradients allowed depend on the length of the decompression they produce.
    710         while true {
    711             let isFinal = !state.vpmb || previousDecoTime - state.decoTime < 10
    712             if state.decoTime != 10_000_000 { state.vpmbNextGradient(decoTime: Double(state.decoTime)) }
    713             previousDecoTime = state.decoTime
    714             state.restore(bottomCache)
    715             var pass = entered
    716             depth = bottomDepth
    717             cylinder = bottomCylinder
    718             setpoint = bottomSetpoint
    719             clock = bottomTime
    720             var gi = changes.count - 1
    721             stopIndex = bottomStopIndex
    722             state.firstCeilingMbar = environment.mbar(state.allowedDepth(tolerance: state.tolerance(pressure: environment.bar(depth))))
    723             if state.maxBottomCeilingMbar > state.firstCeilingMbar { state.firstCeilingMbar = state.maxBottomCeilingMbar }
    724             pass.firstCeilingDepth = environment.depth(relativeMbar: state.firstCeilingMbar - environment.surfaceMbar)
    725             var lastRate = ascentVelocity(depth: depth, average: average, prefs)
    726             var pendingGasChange = false
    727             var lastSegmentMinSwitch = false
    728             var lastStopTime = prefs.timestep
    729             var oxygenBreaking = false, oxygenBreakNext = false
    730             var breakFromCylinder = 0
    731             var timedOut = false
    732 
    733             func point(_ pass: inout CoreOutput, cylinder shown: Int) {
    734                 let next = CoreTrackPoint(time: clock, depth: depth, cylinder: shown, mode: mode, setpoint: setpoint)
    735                 if pass.track.last != next { pass.track.append(next) }
    736             }
    737             func hold(_ pass: inout CoreOutput, _ seconds: Int, cylinder held: Int, gasSwitch: Bool) {
    738                 use(&pass, held, depth: depth, toDepth: depth, seconds: seconds, sac: prefs.decoSac, deco: true, mode: mode)
    739                 oxygen(&pass, state, depth: depth, cylinder: held, seconds: seconds, setpoint: setpoint, mode: mode)
    740                 if var previous = pass.stops.last, previous.depth == depth, previous.cylinder == held, previous.isGasSwitch == gasSwitch,
    741                    previous.endTime == clock {
    742                     previous.seconds += seconds
    743                     previous.endTime = clock + seconds
    744                     pass.stops[pass.stops.count - 1] = previous
    745                 } else {
    746                     pass.stops.append(CoreStop(depth: depth, seconds: seconds, cylinder: held, isGasSwitch: gasSwitch, endTime: clock + seconds))
    747                 }
    748             }
    749 
    750             point(&pass, cylinder: cylinder)
    751             ascent: while true {
    752                 // Up to the next level, two seconds at a time.
    753                 repeat {
    754                     let rate = ascentVelocity(depth: depth, average: average, prefs)
    755                     var rise = rate * baseTimestep
    756                     if rate != lastRate {
    757                         point(&pass, cylinder: cylinder)
    758                         lastRate = rate
    759                     }
    760                     if depth - rise < stopLevels[stopIndex] { rise = depth - stopLevels[stopIndex] }
    761                     state.addSegment(pressure: environment.bar(depth), gas: cylinders[cylinder].gas, seconds: baseTimestep, setpoint: setpoint, mode: mode)
    762                     use(&pass, cylinder, depth: depth, toDepth: depth - rise, seconds: baseTimestep, sac: prefs.decoSac, deco: true, mode: mode)
    763                     oxygen(&pass, state, depth: depth, cylinder: cylinder, seconds: baseTimestep, setpoint: setpoint, mode: mode)
    764                     lastSegmentMinSwitch = false
    765                     clock += baseTimestep
    766                     depth -= rise
    767                 } while depth > 0 && depth > stopLevels[stopIndex]
    768                 if depth <= 0 { break }
    769                 point(&pass, cylinder: cylinder)
    770 
    771                 if gi >= 0, stopLevels[stopIndex] <= changes[gi].depth {
    772                     if cylinder != changes[gi].cylinder {
    773                         let current = cylinders[cylinder].gas
    774                         if !prefs.switchAtRequiredStop
    775                             || !trialAscent(state, wait: 0, from: depth, to: stopLevels[stopIndex - 1], average: average, gas: current,
    776                                             setpoint: setpoint, mode: mode, prefs: prefs)
    777                             || current.o2 < 160 {
    778                             cylinder = changes[gi].cylinder
    779                             if mode == .closedCircuit { setpoint = cylinders[cylinder].setpoint }
    780                             point(&pass, cylinder: cylinder)
    781                             if !lastSegmentMinSwitch, cylinders[cylinder].gas.o2 != 1000 {
    782                                 state.addSegment(pressure: environment.bar(depth), gas: cylinders[cylinder].gas, seconds: prefs.minSwitchDuration,
    783                                                  setpoint: setpoint, mode: mode)
    784                                 hold(&pass, prefs.minSwitchDuration, cylinder: cylinder, gasSwitch: true)
    785                                 clock += prefs.minSwitchDuration
    786                                 lastSegmentMinSwitch = true
    787                             }
    788                         } else {
    789                             pendingGasChange = true
    790                         }
    791                     }
    792                     gi -= 1
    793                 }
    794                 stopIndex -= 1
    795 
    796                 while true {
    797                     if trialAscent(state, wait: 0, from: depth, to: stopLevels[stopIndex], average: average, gas: cylinders[cylinder].gas,
    798                                    setpoint: setpoint, mode: mode, prefs: prefs) { break }
    799                     point(&pass, cylinder: cylinder)
    800                     if pendingGasChange {
    801                         cylinder = changes[gi + 1].cylinder
    802                         if mode == .closedCircuit { setpoint = cylinders[cylinder].setpoint }
    803                         point(&pass, cylinder: cylinder)
    804                         if !lastSegmentMinSwitch, cylinders[cylinder].gas.o2 != 1000 {
    805                             state.addSegment(pressure: environment.bar(depth), gas: cylinders[cylinder].gas, seconds: prefs.minSwitchDuration,
    806                                              setpoint: setpoint, mode: mode)
    807                             hold(&pass, prefs.minSwitchDuration, cylinder: cylinder, gasSwitch: true)
    808                             clock += prefs.minSwitchDuration
    809                         }
    810                         pendingGasChange = false
    811                     }
    812                     let newClock = waitUntil(state, clock: clock, min: clock, leap: lastStopTime * 2 + 1, step: prefs.timestep, depth: depth,
    813                                              target: stopLevels[stopIndex], average: average, gas: cylinders[cylinder].gas,
    814                                              setpoint: setpoint, mode: mode, prefs: prefs)
    815                     lastStopTime = newClock - clock
    816                     if lastStopTime >= 48 * 3600, depth >= 6000, !oxygenBreaking {
    817                         timedOut = true
    818                         break ascent
    819                     }
    820                     oxygenBreaking = false
    821                     let stopCylinder = cylinder
    822                     if prefs.oxygenBreaks {
    823                         // Twelve minutes on oxygen, then six on the break gas.
    824                         if cylinders[cylinder].gas.o2 == 1000 {
    825                             if lastStopTime >= 12 * 60 {
    826                                 lastStopTime = 12 * 60
    827                                 oxygenBreaking = true
    828                                 oxygenBreakNext = true
    829                                 breakFromCylinder = cylinder
    830                                 cylinder = breakCylinder
    831                             }
    832                         } else if oxygenBreakNext {
    833                             if lastStopTime >= 6 * 60 {
    834                                 lastStopTime = 6 * 60
    835                                 oxygenBreaking = true
    836                                 oxygenBreakNext = false
    837                                 cylinder = breakFromCylinder
    838                             }
    839                         }
    840                     }
    841                     state.addSegment(pressure: environment.bar(depth), gas: cylinders[stopCylinder].gas, seconds: lastStopTime, setpoint: setpoint, mode: mode)
    842                     hold(&pass, lastStopTime, cylinder: stopCylinder, gasSwitch: false)
    843                     lastSegmentMinSwitch = false
    844                     clock += lastStopTime
    845                     if oxygenBreaking {
    846                         // The track shows the stop on the gas it was done on, then the gas of the next part.
    847                         point(&pass, cylinder: stopCylinder)
    848                         point(&pass, cylinder: cylinder)
    849                     } else {
    850                         break
    851                     }
    852                 }
    853                 point(&pass, cylinder: cylinder)
    854             }
    855             depth = max(depth, 0)
    856             point(&pass, cylinder: cylinder)
    857             pass.timedOut = timedOut
    858             state.decoTime = clock - bottomTime - (3000 * (prefs.lastStopAt6m ? 2 : 1)) / max(lastRate, 1) + 20
    859             output = pass
    860             if isFinal || timedOut { break }
    861         }
    862         output.runtime = clock
    863         output.finalState = state
    864         return output
    865     }
    866 
    867     /// Subsurface's recreational mode (the first branch of `plan`): stay as long as a direct ascent is allowed
    868     /// and the gas lasts, then go up, with three minutes at 5 m when asked for.
    869     private static func recreational(output entered: CoreOutput, state initial: DecoState, clock start: Int, depth bottom: Int, cylinder: Int,
    870                                      mode: CoreMode, setpoint: Int, average: Int, cylinders: [CoreCylinder], prefs: CorePrefs) -> CoreOutput {
    871         var output = entered
    872         var state = initial
    873         var clock = start, depth = bottom
    874         let environment = state.environment
    875         let gas = cylinders[cylinder].gas
    876         let factor = mode == .semiClosed ? state.pscrRatio / 1000 : 1
    877         let maxDepth = output.track.map(\.depth).max() ?? depth
    878         var safetyStop = prefs.safetyStop && maxDepth >= 10_000
    879         output.hasSafetyStop = safetyStop
    880 
    881         // What the ascent takes from the cylinder (`track_ascent_gas`).
    882         var ascentGas = 0.0
    883         do {
    884             var at = depth, pending = safetyStop
    885             while at > 0 {
    886                 var rise = ascentVelocity(depth: at, average: average, prefs) * baseTimestep
    887                 if rise > at { rise = at }
    888                 ascentGas += environment.atm((at + at - rise) / 2) * prefs.decoSac / 60 * Double(baseTimestep) * factor
    889                 if at <= 5000, at >= 5000 - rise, pending {
    890                     ascentGas += environment.atm(5000) * prefs.decoSac / 60 * 180 * factor
    891                     pending = false
    892                 }
    893                 at -= rise
    894             }
    895         }
    896         /// `enough_gas`: what is above the reserve covers the ascent.
    897         func enoughGas() -> Bool {
    898             let size = cylinders[cylinder].sizeMl, start = cylinders[cylinder].startMbar
    899             guard start > 0, size > 0 else { return true }
    900             let used = output.gasUsed[cylinder]
    901             let end = Double(start) - used * 1000 / Double(size)
    902             return (end - Double(prefs.reserveMbar)) / 1000 * Double(size) > ascentGas
    903         }
    904         func perMinute() -> Double { environment.atm(depth) * prefs.bottomSac / 60 * Double(prefs.timestep) * factor }
    905         func direct(_ state: DecoState) -> Bool {
    906             trialAscent(state, wait: 0, from: depth, to: 0, average: average, gas: gas, setpoint: setpoint, mode: mode, prefs: prefs)
    907         }
    908 
    909         if direct(state) {
    910             repeat {
    911                 state.addSegment(pressure: environment.bar(depth), gas: gas, seconds: prefs.timestep, setpoint: setpoint, mode: mode)
    912                 if mode != .closedCircuit { output.gasUsed[cylinder] += perMinute() }
    913                 clock += prefs.timestep
    914             } while direct(state) && enoughGas() && clock < 6 * 3600
    915             // One step too many.
    916             if mode != .closedCircuit { output.gasUsed[cylinder] -= perMinute() }
    917             clock -= prefs.timestep
    918             output.bottomExtension = clock - start
    919             let ppO2 = state.ppO2(pressure: environment.bar(depth), gas: gas, setpoint: setpoint, mode: mode)
    920             output.cns += OxygenExposure.cns(ppO2: ppO2, seconds: Double(clock - start))
    921             output.otu += OxygenExposure.otu(ppO2: ppO2, seconds: Double(clock - start))
    922             output.track.append(CoreTrackPoint(time: clock, depth: depth, cylinder: cylinder, mode: mode, setpoint: setpoint))
    923         } else {
    924             output.exceedsNoStopLimit = true
    925         }
    926         output.bottomTime = clock
    927         if mode != .closedCircuit {
    928             output.gasUsed[cylinder] += ascentGas
    929             output.decoGasUsed[cylinder] += ascentGas
    930         }
    931 
    932         var lastRate = ascentVelocity(depth: depth, average: average, prefs)
    933         repeat {
    934             let rate = ascentVelocity(depth: depth, average: average, prefs)
    935             var rise = rate * baseTimestep
    936             if rate != lastRate {
    937                 output.track.append(CoreTrackPoint(time: clock, depth: depth, cylinder: cylinder, mode: mode, setpoint: setpoint))
    938                 lastRate = rate
    939             }
    940             if depth - rise < 0 { rise = depth }
    941             clock += baseTimestep
    942             depth -= rise
    943             if depth <= 5000, depth >= 5000 - rise, safetyStop {
    944                 output.track.append(CoreTrackPoint(time: clock, depth: 5000, cylinder: cylinder, mode: mode, setpoint: setpoint))
    945                 clock += 180
    946                 output.track.append(CoreTrackPoint(time: clock, depth: 5000, cylinder: cylinder, mode: mode, setpoint: setpoint))
    947                 safetyStop = false
    948             }
    949         } while depth > 0
    950         output.track.append(CoreTrackPoint(time: clock, depth: 0, cylinder: cylinder, mode: mode, setpoint: setpoint))
    951         output.runtime = clock
    952         output.finalState = state
    953         return output
    954     }
    955 }