Files
voxelotl-engine/Sources/Voxelotl/World.swift

62 lines
1.6 KiB
Swift
Raw Normal View History

2024-08-25 19:23:47 +10:00
import Foundation
public class World {
private var _chunks: Dictionary<SIMD3<Int>, Chunk>
2024-08-30 21:56:39 +10:00
private var _generator: WorldGenerator
2024-08-25 19:23:47 +10:00
public init() {
self._chunks = [:]
2024-08-30 21:56:39 +10:00
self._generator = WorldGenerator()
2024-08-25 19:23:47 +10:00
}
func getBlock(at position: SIMD3<Int>) -> Block {
return if let chunk = self._chunks[position &>> Chunk.shift] {
chunk.getBlock(at: position)
} else { Block(.air) }
}
func setBlock(at position: SIMD3<Int>, type: BlockType) {
self._chunks[position &>> Chunk.shift]?.setBlock(at: position, type: type)
}
2024-09-01 21:16:05 +10:00
func getChunk(id chunkID: SIMD3<Int>) -> Chunk? {
self._chunks[chunkID]
}
public func forEachChunk(_ body: @escaping (_ id: SIMD3<Int>, _ chunk: Chunk) throws -> Void) rethrows {
for i in self._chunks {
try body(i.key, i.value)
}
}
2024-08-30 21:56:39 +10:00
func generate(width: Int, height: Int, depth: Int, seed: UInt64) {
self._generator.reset(seed: seed)
let orig = SIMD3(width, height, depth) / 2
for z in 0..<depth {
2024-08-25 19:23:47 +10:00
for y in 0..<height {
2024-08-30 21:56:39 +10:00
for x in 0..<width {
let chunkID = SIMD3(x, y, z) &- orig
self._chunks[chunkID] = self._generator.makeChunk(id: chunkID)
2024-08-25 19:23:47 +10:00
}
}
}
}
2024-08-30 18:44:55 +10:00
func generate(chunkID: SIMD3<Int>) {
2024-08-30 21:56:39 +10:00
self._chunks[chunkID] = self._generator.makeChunk(id: chunkID)
2024-08-30 18:44:55 +10:00
}
2024-08-25 19:23:47 +10:00
var instances: [Instance] {
self._chunks.values.flatMap { chunk in
chunk.compactMap { block, position in
if case let .solid(color) = block.type {
Instance(
position: SIMD3<Float>(position) + 0.5,
scale: .init(repeating: 0.5),
color: color)
} else { nil }
}
}
}
}