Repository Public License
1// ORIX Arcade2// File: Games/DigToCore/DigGenerator.swift3// Description: Dig to Core — seeded chunk generation with a guaranteed hazard-free route, validation, and the bounded chunk store.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89nonisolated struct DigChunk: Sendable, Equatable {10 let index: Int11 /// Row-major, `DigConfig.chunkRows` × `DigConfig.cols`.12 var tiles: [DigTile]13 /// Cells of the guaranteed route: never a boulder, lava or gas.14 let route: [Bool]15 /// True if validation had to clear the route after generation (never expected; asserted in tests).16 let repaired: Bool1718 var firstRow: Int { index * DigConfig.chunkRows }1920 func tile(col: Int, localRow: Int) -> DigTile { tiles[localRow * DigConfig.cols + col] }21}2223nonisolated enum DigGenerator {24 private static let cols = DigConfig.cols25 private static let rows = DigConfig.chunkRows2627 /// Column where the guaranteed route crosses the top of chunk `boundary`. Adjacent chunks agree on it.28 static func boundaryColumn(seed: UInt64, boundary: Int) -> Int {29 guard boundary > 0 else { return cols / 2 }30 var rng = SeededRNG.derive(seed ^ 0xA5A5_5A5A_1234_4321, boundary)31 return rng.int(in: 1...(cols - 2))32 }3334 static func chunk(seed: UInt64, index: Int) -> DigChunk {35 var rng = SeededRNG.derive(seed, index)36 let base = index * rows37 var tiles = [DigTile](repeating: .ground, count: rows * cols)38 var route = [Bool](repeating: false, count: rows * cols)39 var locked = [Bool](repeating: false, count: rows * cols)40 func at(_ r: Int, _ c: Int) -> Int { r * cols + c }41 func inside(_ r: Int, _ c: Int) -> Bool { r >= 0 && r < rows && c >= 0 && c < cols }42 func count(_ average: Double, _ rng: inout SeededRNG) -> Int { Int(average) + (rng.chance(average - average.rounded(.down)) ? 1 : 0) }43 /// The opening stretch of the very first chunk stays gentle: plain soil and a little ore.44 func gentle(_ r: Int) -> Bool { index == 0 && r < 8 }4546 // 1. Guaranteed route: a meandering path from the entry column to the exit column.47 let entry = boundaryColumn(seed: seed, boundary: index)48 let exit = boundaryColumn(seed: seed, boundary: index + 1)49 var col = entry50 for r in 0..<rows {51 route[at(r, col)] = true52 let target: Int53 if r == rows - 1 { target = exit }54 else if !gentle(r), rng.chance(0.4) { target = min(max(col + rng.int(in: -3...3), 1), cols - 2) }55 else { target = col }56 while col != target {57 col += target > col ? 1 : -158 route[at(r, col)] = true59 }60 }6162 let midBiome = DigBiome.at(row: base + rows / 2)6364 // 2. Treasure room: a hard-rock vault around a chest.65 if base >= 48, rng.chance(0.16) {66 let cr = rng.int(in: 3...(rows - 4)), cc = rng.int(in: 2...(cols - 3))67 for dr in -2...2 {68 for dc in -2...2 where inside(cr + dr, cc + dc) {69 let i = at(cr + dr, cc + dc)70 locked[i] = true71 let ring = abs(dr) == 2 || abs(dc) == 272 if ring { if !route[i] { tiles[i] = .hardRock } } else { tiles[i] = .air }73 }74 }75 tiles[at(cr, cc)] = .chest76 }7778 // 3. Caves.79 var caveCenters: [(Int, Int)] = []80 for _ in 0..<count(midBiome.caves, &rng) {81 let cr = rng.int(in: 2...(rows - 3)), cc = rng.int(in: 1...(cols - 2))82 let rx = rng.double(in: 1.2...3.2), ry = rng.double(in: 0.9...2.2)83 guard !gentle(cr - Int(ry) - 1) else { continue }84 caveCenters.append((cr, cc))85 for r in (cr - 3)...(cr + 3) {86 for c in (cc - 4)...(cc + 4) where inside(r, c) && !locked[at(r, c)] {87 let dx = Double(c - cc) / rx, dy = Double(r - cr) / ry88 if dx * dx + dy * dy <= 1 + rng.double(in: -0.25...0.2) { tiles[at(r, c)] = .air }89 }90 }91 }9293 // 4. Hard-rock veins (slow, never on the route).94 for _ in 0..<count(midBiome.hardVeins, &rng) {95 var r = rng.int(in: 0...(rows - 1)), c = rng.int(in: 0...(cols - 1))96 for _ in 0..<rng.int(in: 2...5) {97 if inside(r, c), !gentle(r), !route[at(r, c)], !locked[at(r, c)], tiles[at(r, c)] == .ground { tiles[at(r, c)] = .hardRock }98 if rng.chance(0.5) { c += rng.chance(0.5) ? 1 : -1 } else { r += rng.chance(0.5) ? 1 : -1 }99 }100 }101102 // 5. Ore pockets.103 for _ in 0..<count(midBiome.orePockets, &rng) {104 var r = rng.int(in: 0...(rows - 1)), c = rng.int(in: 0...(cols - 1))105 let biome = DigBiome.at(row: base + r)106 let table = biome.oreTable107 var roll = rng.double(in: 0...table.reduce(0) { $0 + $1.1 })108 var ore = table[0].0109 for (kind, weight) in table {110 if roll <= weight { ore = kind; break }111 roll -= weight112 }113 for _ in 0..<rng.int(in: 2...5) {114 if inside(r, c), !locked[at(r, c)], tiles[at(r, c)] == .ground { tiles[at(r, c)] = ore }115 if rng.chance(0.55) { c += rng.chance(0.5) ? 1 : -1 } else { r += rng.chance(0.5) ? 1 : -1 }116 }117 }118 if index == 0 {119 // Tutorial ore right under the spawn point.120 let c0 = cols / 2121 tiles[at(3, c0)] = .coal122 tiles[at(4, c0)] = .coal123 tiles[at(6, c0 + 1)] = .copper124 tiles[at(6, c0 - 1)] = .copper125 }126127 // 6. Fossil.128 if rng.chance(midBiome.fossilChance) {129 let r = rng.int(in: 8...(rows - 1)), c = rng.int(in: 0...(cols - 1))130 if !locked[at(r, c)], tiles[at(r, c)] == .ground { tiles[at(r, c)] = .fossil }131 }132133 // Fair hazard placement: a row never holds more blockers and hazards than this.134 let rowCap = cols - 5135 func hazardsInRow(_ r: Int) -> Int { (0..<cols).reduce(0) { $0 + (tiles[at(r, $1)].blocksRoute ? 1 : 0) } }136137 // 7. Boulders: single-row bars, never on consecutive rows, so the drill can always slide around them.138 var boulderRows = Set<Int>()139 for _ in 0..<count(midBiome.boulderRows, &rng) {140 let r = rng.int(in: 2...(rows - 3))141 guard !gentle(r), !boulderRows.contains(r - 1), !boulderRows.contains(r), !boulderRows.contains(r + 1) else { continue }142 let start = rng.int(in: 0...(cols - 1)), length = rng.int(in: 1...3)143 var placed = false144 for c in start..<min(start + length, cols) where !route[at(r, c)] && !locked[at(r, c)] && tiles[at(r, c)] != .air {145 tiles[at(r, c)] = .boulder146 placed = true147 }148 if placed { boulderRows.insert(r) }149 }150151 // 8. Lava pools.152 for _ in 0..<count(midBiome.lavaPools, &rng) {153 let r = rng.int(in: 1...(rows - 1)), start = rng.int(in: 0...(cols - 1)), length = rng.int(in: 1...3)154 guard !gentle(r), DigBiome.at(row: base + r).lavaPools > 0 else { continue }155 for c in start..<min(start + length, cols) where !route[at(r, c)] && !locked[at(r, c)] && !tiles[at(r, c)].isUnbreakable {156 if hazardsInRow(r) < rowCap { tiles[at(r, c)] = .lava }157 }158 }159160 // 9. Gas pockets.161 for _ in 0..<count(midBiome.gasPockets, &rng) {162 let r = rng.int(in: 1...(rows - 1)), c = rng.int(in: 0...(cols - 1))163 guard !gentle(r), DigBiome.at(row: base + r).gasPockets > 0 else { continue }164 if !route[at(r, c)], !locked[at(r, c)], tiles[at(r, c)] == .ground, hazardsInRow(r) < rowCap { tiles[at(r, c)] = .gas }165 }166167 // 10. Fuel cells sit on the guaranteed route so they are always obtainable.168 if index == 0 || rng.chance(0.2) {169 let r = rng.int(in: (index == 0 ? 14 : 5)...(rows - 3))170 if let c = (0..<cols).first(where: { route[at(r, $0)] }), !locked[at(r, c)] { tiles[at(r, c)] = .fuelCell }171 }172 for (cr, cc) in caveCenters where rng.chance(0.25) && !locked[at(cr, cc)] && tiles[at(cr, cc)] == .air {173 tiles[at(cr, cc)] = .fuelCell174 }175176 // 11. Repair kit beside the route.177 if rng.chance(midBiome.repairChance) {178 let r = rng.int(in: 4...(rows - 2))179 if let rc = (0..<cols).first(where: { route[at(r, $0)] }) {180 let c = min(max(rc + (rng.chance(0.5) ? 1 : -1) * rng.int(in: 1...2), 0), cols - 1)181 if !locked[at(r, c)], !tiles[at(r, c)].isUnbreakable, !route[at(r, c)] { tiles[at(r, c)] = .repairKit }182 }183 }184185 // 12. The core.186 for r in 0..<rows where base + r >= DigConfig.coreRow {187 for c in 0..<cols { tiles[at(r, c)] = .core }188 }189190 // 13. Validate; repair if anything ever slipped onto the route.191 var chunk = DigChunk(index: index, tiles: tiles, route: route, repaired: false)192 if !isTraversable(chunk, seed: seed) {193 for i in tiles.indices where route[i] && tiles[i].blocksRoute { tiles[i] = .ground }194 chunk = DigChunk(index: index, tiles: tiles, route: route, repaired: true)195 }196 return chunk197 }198199 /// True when a drill entering at the chunk's entry column can reach its exit column moving only down, left and right200 /// through cells that are neither unbreakable nor hazardous.201 static func isTraversable(_ chunk: DigChunk, seed: UInt64) -> Bool {202 let entry = boundaryColumn(seed: seed, boundary: chunk.index)203 let exit = boundaryColumn(seed: seed, boundary: chunk.index + 1)204 func open(_ r: Int, _ c: Int) -> Bool { !chunk.tiles[r * cols + c].blocksRoute }205 guard open(0, entry) else { return false }206 var reachable = [Bool](repeating: false, count: cols)207 reachable[entry] = true208 for r in 0..<rows {209 if r > 0 {210 for c in 0..<cols { reachable[c] = reachable[c] && open(r, c) }211 }212 // Spread sideways along the row.213 var changed = true214 while changed {215 changed = false216 for c in 0..<cols where reachable[c] {217 if c > 0, !reachable[c - 1], open(r, c - 1) { reachable[c - 1] = true; changed = true }218 if c < cols - 1, !reachable[c + 1], open(r, c + 1) { reachable[c + 1] = true; changed = true }219 }220 }221 if !reachable.contains(true) { return false }222 }223 return reachable[exit]224 }225}226227/// Mutable terrain for one run. Chunks are generated on demand and evicted once left behind, so memory stays bounded.228nonisolated final class DigWorld {229 let seed: UInt64230 private var chunks: [Int: DigChunk] = [:]231 private(set) var generatedCount = 0232233 init(seed: UInt64) { self.seed = seed }234235 var loadedChunkCount: Int { chunks.count }236237 private func chunk(_ index: Int) -> DigChunk {238 if let existing = chunks[index] { return existing }239 let created = DigGenerator.chunk(seed: seed, index: index)240 chunks[index] = created241 generatedCount += 1242 return created243 }244245 /// Rows above the surface are open air; columns outside the shaft are solid wall.246 func tile(col: Int, row: Int) -> DigTile {247 guard col >= 0, col < DigConfig.cols else { return .boulder }248 guard row >= 0 else { return .air }249 let index = row / DigConfig.chunkRows250 return chunk(index).tiles[(row - index * DigConfig.chunkRows) * DigConfig.cols + col]251 }252253 func set(col: Int, row: Int, _ tile: DigTile) {254 guard col >= 0, col < DigConfig.cols, row >= 0 else { return }255 let index = row / DigConfig.chunkRows256 _ = chunk(index)257 chunks[index]?.tiles[(row - index * DigConfig.chunkRows) * DigConfig.cols + col] = tile258 }259260 /// Pre-generates the chunks around `row` and drops the ones far above it.261 func ensure(row: Int) {262 let current = max(row, 0) / DigConfig.chunkRows263 for index in max(0, current - 1)...(current + 2) { _ = chunk(index) }264 for index in chunks.keys where index < current - 1 { chunks[index] = nil }265 }266}267