Stream endless level-of-detail terrain into the studio 3D views

The world, noise and saved-world 3D views drew one fixed square. They now draw tiles of block columns around whatever the camera looks at, coarse backdrop first and then finer down to about a column per pixel, fetched through a byte-budgeted cache with cancellation. Coarser tiles stand in with holes where finer ones are ready, and ground drawn before a layer changes stays until its tiles are sampled anew. Pack, server and seed output are untouched; no pin or golden moved.

v3: 9ee539ee0 4bd06dbcc c3913e8f4 cc2caf8fa 0b9cb6156 23b98e5ff 2006e6ba8 de1e06f88
This commit is contained in:
piexel committed 2026-11-10 11:55:34 +01:00
1 parent 30c063853d
commit 6d4d14606c
26 files changed
+1447 -394

No files matched your search

+9 -3
View File
@@ -7,8 +7,9 @@ export interface TileSource<Tile, Layer, Style> {
layerKey(layer: Layer): string
fetch(address: TileAddress, layer: Layer, signal: AbortSignal): Promise<Tile>
bytesOf(tile: Tile): number
styleKey(style: Style): string
pixels(tile: Tile, style: Style): ImageData
/** Only for sources whose tiles are drawn as pictures. */
styleKey?(style: Style): string
pixels?(tile: Tile, style: Style): ImageData
}
interface StoredTile<Tile> {
@@ -56,10 +57,15 @@ export class TileStore<Tile, Layer, Style> {
return stored.tile
}
/** Whether the tile has arrived; unlike {@link get}, asking does not count as using it. */
has(address: TileAddress, layer: Layer): boolean {
return this.tiles.has(this.key(address, layer))
}
/** The tile drawn in {@code style}; restyled only when the style changed since it was last drawn. */
picture(address: TileAddress, layer: Layer, style: Style): HTMLCanvasElement | null {
const stored = this.tiles.get(this.key(address, layer))
if (stored === undefined) {
if (stored === undefined || this.source.styleKey === undefined || this.source.pixels === undefined) {
return null
}
stored.lastUsed = ++this.useClock
+10 -5
View File
@@ -30,24 +30,29 @@ describe('noise scale', () => {
})
describe('noise terrain', () => {
const area = (values: number[]) => ({ tiles: [[{ size: 2, values: Float32Array.from(values) }]], originX: 10, originZ: 20 })
const tile = (values: number[]) => ({ size: 2, values: Float32Array.from(values) })
const place = { level: 1, tileX: 1, tileZ: -2 }
it('raises noise of 0 to 1 to the relief, without water', () => {
const terrain = new NoiseTerrain(area([0, 0.5, 1, Number.NaN]), UNIT_NOISE, noiseScale('terrain', UNIT_NOISE), 64)
const terrain = new NoiseTerrain(tile([0, 0.5, 1, Number.NaN]), place, UNIT_NOISE, noiseScale('terrain', UNIT_NOISE), 64)
expect([terrain.groundAt(0, 0), terrain.groundAt(1, 0), terrain.groundAt(0, 1), terrain.groundAt(1, 1)]).toEqual([0, 32, 64, null])
expect(terrain.waterAt(0, 0)).toBeNull()
expect([terrain.originX, terrain.originZ]).toEqual([10, 20])
})
it('places its columns where the tile lies, as wide as its level', () => {
const terrain = new NoiseTerrain(tile([0, 0, 0, 0]), place, UNIT_NOISE, noiseScale('terrain', UNIT_NOISE), 64)
expect([terrain.originX, terrain.originZ, terrain.blocksPerColumn]).toEqual([256, -512, 2])
})
it('stands noise in blocks at its own height, under water below the fluid', () => {
const terrain = new NoiseTerrain(area([-5, 12, 0, 3]), BLOCK_NOISE, noiseScale('height', BLOCK_NOISE), 64)
const terrain = new NoiseTerrain(tile([-5, 12, 0, 3]), place, BLOCK_NOISE, noiseScale('height', BLOCK_NOISE), 64)
expect(terrain.groundAt(0, 0)).toBe(-5)
expect(terrain.waterAt(0, 0)).toBe(0)
expect(terrain.waterAt(1, 0)).toBeNull()
})
it('fills each column up to the block its noise reaches into', () => {
const terrain = new NoiseTerrain(area([-0.5, 12.9, 0.4, 3]), BLOCK_NOISE, noiseScale('height', BLOCK_NOISE), 64)
const terrain = new NoiseTerrain(tile([-0.5, 12.9, 0.4, 3]), place, BLOCK_NOISE, noiseScale('height', BLOCK_NOISE), 64)
expect([terrain.groundAt(0, 0), terrain.groundAt(1, 0), terrain.groundAt(0, 1)]).toEqual([-1, 12, 0])
expect(terrain.waterAt(0, 0)).toBe(0)
expect(terrain.waterAt(0, 1)).toBeNull()
+12 -18
View File
@@ -1,39 +1,34 @@
import type { NoiseSource, NoiseTile } from '../bridge/types'
import type { TerrainSurface } from '../scene/terrainMesh'
import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from '../scene/terrainTiles'
import type { NoiseScale } from './noiseScale'
/** A square of noise tiles at one block a value, row by row from the north west, and the block its first value is taken at. */
export interface NoiseArea {
tiles: NoiseTile[][]
originX: number
originZ: number
}
// The fluid of noise measured in blocks lies at its zero, as the world adds the overlay above its fluid height.
const FLUID_BLOCKS = 0
/**
* Noise as terrain (v3e's 3D noise): noise measured in blocks stands at its own height with water at the fluid;
* other noise rises from its scale's minimum to {@code reliefBlocks} at its maximum, with no water.
* One tile of noise as terrain (v3e's 3D noise): noise measured in blocks stands at its own height with water at the
* fluid; other noise rises from its scale's minimum to {@code reliefBlocks} at its maximum, with no water.
*/
export class NoiseTerrain implements TerrainSurface {
readonly columns: number
readonly rows: number
readonly originX: number
readonly originZ: number
private readonly tileSize: number
readonly blocksPerColumn: number
constructor(
private readonly area: NoiseArea,
private readonly tile: NoiseTile,
place: TerrainTile,
private readonly source: NoiseSource,
private readonly scale: NoiseScale,
private readonly reliefBlocks: number
) {
this.tileSize = area.tiles[0][0].size
this.originX = area.originX
this.originZ = area.originZ
this.rows = area.tiles.length * this.tileSize
this.columns = area.tiles[0].length * this.tileSize
this.columns = tile.size
this.rows = tile.size
this.originX = originXOf(place)
this.originZ = originZOf(place)
this.blocksPerColumn = blocksPerColumn(place.level)
}
groundAt(column: number, row: number): number | null {
@@ -62,7 +57,6 @@ export class NoiseTerrain implements TerrainSurface {
}
private valueAt(column: number, row: number): number {
const tile = this.area.tiles[Math.floor(row / this.tileSize)][Math.floor(column / this.tileSize)]
return tile.values[(row % this.tileSize) * tile.size + (column % this.tileSize)]
return this.tile.values[row * this.tile.size + column]
}
}
+1 -1
View File
@@ -53,7 +53,7 @@ function valueAt(view: NoiseView, worldX: number, worldZ: number): number | null
return spot === null ? null : spot.tile.values[spot.pixelZ * spot.tile.size + spot.pixelX]
}
function noiseTileSource(client: BridgeClient): TileSource<NoiseTile, NoiseLayer, NoiseStyle> {
export function noiseTileSource(client: BridgeClient): TileSource<NoiseTile, NoiseLayer, NoiseStyle> {
return {
layerKey: (layer) => `${layer.revision}/${layer.sourceId}/${layer.seed}`,
fetch: (address, layer, signal) =>
@@ -0,0 +1,121 @@
import { Box3, Frustum, Vector3, type PerspectiveCamera } from 'three'
import { blocksPerColumn, originXOf, originZOf, tileBlocks, tileContaining, type TerrainTile } from './terrainTiles'
/** What a camera looks through: its size in CSS pixels and how far it orbits from what is in the middle. */
export interface SightView {
camera: PerspectiveCamera
width: number
height: number
orbitDistance: number
}
const NDC_MIDDLE_DEPTH = 0.5
const NOT_BEHIND_THE_CAMERA = 0
const BEHIND_THE_CAMERA = 1e9
/**
* What the camera sees of ground that lies between {@code floorY} and {@code topY}: which terrain tiles land in the
* view, or within a margin around it, and how wide their columns look from where the camera stands.
*/
export class CameraSight {
private readonly frustums = new Map<number, Frustum>()
private readonly position = new Vector3()
constructor(
private readonly view: SightView,
readonly floorY: number,
readonly topY: number
) {
view.camera.updateMatrixWorld()
view.camera.getWorldPosition(this.position)
}
get orbitDistance(): number {
return this.view.orbitDistance
}
/** How many pixels the view has, with {@code margin} of its size added on every side. */
pixelsWithin(margin: number): number {
const widening = 1 + 2 * margin
return this.view.width * this.view.height * widening * widening
}
/** Whether any of the tile, from the floor to the top, lands in the view widened by {@code margin} of its size on every side. */
sees(tile: TerrainTile, margin: number): boolean {
return this.frustumWith(margin).intersectsBox(this.boxOf(tile))
}
/** How many pixels wide a column of the tile looks at the nearest ground of it. */
columnPixels(tile: TerrainTile): number {
const distance = Math.max(this.boxOf(tile).distanceToPoint(this.position), this.view.camera.near)
const pixelsPerBlock = this.view.height / (2 * distance * Math.tan((this.view.camera.fov * Math.PI) / 360))
return blocksPerColumn(tile.level) * pixelsPerBlock
}
/** How far the tile's middle lies from the middle of the view on the screen; tiles behind the camera lie furthest. */
distanceFromMiddle(tile: TerrainTile): number {
const middle = new Vector3(originXOf(tile) + tileBlocks(tile.level) / 2, (this.floorY + this.topY) / 2, originZOf(tile) + tileBlocks(tile.level) / 2)
const behind = middle.clone().applyMatrix4(this.view.camera.matrixWorldInverse).z > NOT_BEHIND_THE_CAMERA
if (behind) {
return BEHIND_THE_CAMERA + middle.distanceTo(this.position)
}
const onScreen = middle.project(this.view.camera)
return Math.hypot(onScreen.x, onScreen.y)
}
/** The tiles of {@code level} in sight, widened by {@code margin}. */
tilesAt(level: number, margin: number): TerrainTile[] {
const { first, last } = this.footprint(level, margin)
const inSight: TerrainTile[] = []
for (let tileZ = first.tileZ; tileZ <= last.tileZ; tileZ++) {
for (let tileX = first.tileX; tileX <= last.tileX; tileX++) {
const tile = { level, tileX, tileZ }
if (this.sees(tile, margin)) {
inSight.push(tile)
}
}
}
return inSight
}
// The corners of the widened view, cast onto the floor and the top of the ground, bound the tiles that can be in it.
private footprint(level: number, margin: number): { first: TerrainTile; last: TerrainTile } {
const { camera } = this.view
const reach = camera.far
const widening = 1 + 2 * margin
let [minX, minZ, maxX, maxZ] = [Infinity, Infinity, -Infinity, -Infinity]
for (const [cornerX, cornerY] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) {
const direction = new Vector3(cornerX * widening, cornerY * widening, NDC_MIDDLE_DEPTH).unproject(camera).sub(this.position).normalize()
for (const groundY of [this.floorY, this.topY]) {
const distance = direction.y < 0 ? Math.min(reach, (groundY - this.position.y) / direction.y) : reach
const point = direction.clone().multiplyScalar(Math.max(0, distance)).add(this.position)
minX = Math.min(minX, point.x)
maxX = Math.max(maxX, point.x)
minZ = Math.min(minZ, point.z)
maxZ = Math.max(maxZ, point.z)
}
}
return { first: tileContaining(minX, minZ, level), last: tileContaining(maxX, maxZ, level) }
}
private frustumWith(margin: number): Frustum {
let frustum = this.frustums.get(margin)
if (frustum === undefined) {
const { camera } = this.view
const widening = 1 + 2 * margin
const projection = camera.projectionMatrix.clone()
projection.elements[0] /= widening
projection.elements[5] /= widening
frustum = new Frustum().setFromProjectionMatrix(projection.multiply(camera.matrixWorldInverse))
this.frustums.set(margin, frustum)
}
return frustum
}
private boxOf(tile: TerrainTile): Box3 {
const size = tileBlocks(tile.level)
const x = originXOf(tile)
const z = originZOf(tile)
return new Box3(new Vector3(x, this.floorY, z), new Vector3(x + size, this.topY, z + size))
}
}
+16 -9
View File
@@ -52,7 +52,8 @@ export function groundFaces(field: ColumnField, base: number): QuadBatch {
/**
* The water over the ground: its top where a column holds some, and the sides where it stands above what lies next
* to it, down to its own ground. Drawn without colour; the water has one.
* to it, down to its own ground. Water at the edge of the field or beside columns where nothing is known has no side,
* as it goes on in the field next to it. Drawn without colour; the water has one.
*/
export function waterFaces(field: ColumnField): QuadBatch {
const batch = new QuadBatch(false)
@@ -73,7 +74,10 @@ export function waterFaces(field: ColumnField): QuadBatch {
return null
}
const next = field.surfaceTop(column + side.columnStep, row + side.rowStep)
const bottom = Math.max(next ?? -Infinity, field.groundTop[field.indexOf(column, row)])
if (next === null) {
return null
}
const bottom = Math.max(next, field.groundTop[field.indexOf(column, row)])
return bottom < top ? { bottom, top, color: WATER_COLOR } : null
})
return batch
@@ -82,7 +86,8 @@ export function waterFaces(field: ColumnField): QuadBatch {
function addTops(field: ColumnField, batch: QuadBatch, spanAt: (column: number, row: number) => Span | null): void {
for (let row = 0; row < field.rows; row++) {
mergeRuns(field.columns, (column) => spanAt(column, row), (first, count, span) => {
batch.add([field.originX + first, span.top, field.originZ + row], [count, 0, 0], [0, 0, 1], shaded(span.color, TOP_LIGHT))
const step = field.blocksPerColumn
batch.add([field.originX + first * step, span.top, field.originZ + row * step], [count * step, 0, 0], [0, 0, step], shaded(span.color, TOP_LIGHT))
})
}
}
@@ -104,19 +109,21 @@ function addSides(field: ColumnField, batch: QuadBatch, spanAt: (column: number,
// The corner a side starts from is the one on its left as seen from outside, so it runs and rises into view.
function sideQuad(field: ColumnField, side: Side, column: number, row: number, count: number, span: Span): [Vec3, Vec3, Vec3] {
const x = field.originX + column
const z = field.originZ + row
const step = field.blocksPerColumn
const x = field.originX + column * step
const z = field.originZ + row * step
const length = count * step
const up: Vec3 = [0, span.top - span.bottom, 0]
if (side.rowStep < 0) {
return [[x, span.bottom, z], [count, 0, 0], up]
return [[x, span.bottom, z], [length, 0, 0], up]
}
if (side.rowStep > 0) {
return [[x + count, span.bottom, z + 1], [-count, 0, 0], up]
return [[x + length, span.bottom, z + step], [-length, 0, 0], up]
}
if (side.columnStep < 0) {
return [[x, span.bottom, z + count], [0, 0, -count], up]
return [[x, span.bottom, z + length], [0, 0, -length], up]
}
return [[x + 1, span.bottom, z], [0, 0, count], up]
return [[x + step, span.bottom, z], [0, 0, length], up]
}
function mergeRuns(length: number, spanAt: (index: number) => Span | null, emit: (first: number, count: number, span: Span) => void): void {
+26 -65
View File
@@ -1,41 +1,42 @@
import { Box3, Vector3, type Ray } from 'three'
import type { TerrainSurface } from './terrainMesh'
import type { ColumnArea } from './terrainTiles'
const NO_VALUE = Number.NaN
const MARCH_STEPS_PER_BLOCK = 2
const MARCH_REFINEMENTS = 16
/**
* The surface read once into columns of one block: where each column's ground and water faces stand, and its colour.
* A top face stands one above the block's Y, so ground and water sit where a player stands on them. Where nothing is
* known, the column has no ground and no water.
* The surface read once into columns: where each column's ground and water faces stand, and its colour. A top face
* stands one above the block's Y, so ground and water sit where a player stands on them. Where nothing is known, or
* where the columns are {@code holes} left to finer ground, the column has no ground and no water.
*/
export class ColumnField {
readonly columns: number
readonly rows: number
readonly originX: number
readonly originZ: number
readonly blocksPerColumn: number
readonly groundTop: Float32Array
readonly waterTop: Float32Array
readonly color: Int32Array
constructor(surface: TerrainSurface) {
constructor(surface: TerrainSurface, holes: readonly ColumnArea[] = []) {
this.columns = surface.columns
this.rows = surface.rows
this.originX = surface.originX
this.originZ = surface.originZ
this.blocksPerColumn = surface.blocksPerColumn
const count = this.columns * this.rows
this.groundTop = new Float32Array(count).fill(NO_VALUE)
this.waterTop = new Float32Array(count).fill(NO_VALUE)
this.color = new Int32Array(count)
const inHole = this.holeMask(holes)
for (let row = 0; row < this.rows; row++) {
for (let column = 0; column < this.columns; column++) {
const ground = surface.groundAt(column, row)
const index = this.indexOf(column, row)
const ground = inHole[index] === 1 ? null : surface.groundAt(column, row)
if (ground === null) {
continue
}
const water = surface.waterAt(column, row)
const index = this.indexOf(column, row)
this.groundTop[index] = ground + 1
this.waterTop[index] = water === null ? NO_VALUE : water + 1
this.color[index] = surface.colorAt(column, row)
@@ -55,6 +56,11 @@ export class ColumnField {
return this.contains(column, row) && !Number.isNaN(this.groundTop[this.indexOf(column, row)])
}
/** Whether any column has ground. */
hasAnyGround(): boolean {
return this.groundTop.some((top) => !Number.isNaN(top))
}
/** The face the column shows to the sky: its water where it has some, else its ground; null where nothing is known. */
surfaceTop(column: number, row: number): number | null {
if (!this.hasGround(column, row)) {
@@ -64,65 +70,20 @@ export class ColumnField {
return Number.isNaN(this.waterTop[index]) ? this.groundTop[index] : this.waterTop[index]
}
lowestTop(): number {
let lowest = Infinity
for (const top of this.groundTop) {
if (!Number.isNaN(top)) {
lowest = Math.min(lowest, top)
}
}
return Number.isFinite(lowest) ? lowest : 0
/** The face shown to the sky over the world block, or null where the field has none. */
surfaceTopOver(worldX: number, worldZ: number): number | null {
const column = Math.floor((worldX - this.originX) / this.blocksPerColumn)
const row = Math.floor((worldZ - this.originZ) / this.blocksPerColumn)
return this.surfaceTop(column, row)
}
/** The box round the field from {@code base} to its highest ground or water. */
bounds(base: number): Box3 {
let highest = base
for (const tops of [this.groundTop, this.waterTop]) {
for (const top of tops) {
if (!Number.isNaN(top)) {
highest = Math.max(highest, top)
}
private holeMask(holes: readonly ColumnArea[]): Uint8Array {
const mask = new Uint8Array(this.columns * this.rows)
for (const hole of holes) {
for (let row = hole.fromRow; row < hole.toRow; row++) {
mask.fill(1, this.indexOf(hole.fromColumn, row), this.indexOf(hole.toColumn - 1, row) + 1)
}
}
return new Box3(new Vector3(this.originX, base, this.originZ), new Vector3(this.originX + this.columns, highest, this.originZ + this.rows))
}
/**
* Where the ray first comes down onto the ground or the water over it, found by marching along it through the
* {@code bounds}, so a pick does not have to test every face. A ray that starts below the surface inside the bounds,
* or runs over columns where nothing is known and out of the field, finds nothing there.
*/
surfaceAlong(ray: Ray, bounds: Box3): Vector3 | null {
const start = bounds.containsPoint(ray.origin) ? ray.origin.clone() : ray.intersectBox(bounds, new Vector3())
if (start === null) {
return null
}
const step = 1 / MARCH_STEPS_PER_BLOCK
const reach = bounds.getSize(new Vector3()).length()
const pointAt = (distance: number): Vector3 => ray.direction.clone().multiplyScalar(distance).add(start)
const isBelow = (point: Vector3): boolean => {
const top = this.surfaceTop(Math.floor(point.x - this.originX), Math.floor(point.z - this.originZ))
return top !== null && point.y <= top
}
if (isBelow(start)) {
return bounds.containsPoint(ray.origin) ? null : start
}
for (let distance = step; distance <= reach; distance += step) {
if (!isBelow(pointAt(distance))) {
continue
}
let above = distance - step
let below = distance
for (let refinement = 0; refinement < MARCH_REFINEMENTS; refinement++) {
const middle = (above + below) / 2
if (isBelow(pointAt(middle))) {
below = middle
} else {
above = middle
}
}
return pointAt(below)
}
return null
return mask
}
}
+16 -25
View File
@@ -1,37 +1,31 @@
import { NO_LABEL, type MapTile } from '../bridge/types'
import { heightColor } from '../map/heightColors'
import type { TerrainSurface } from './terrainMesh'
import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from './terrainTiles'
export type MapTerrainColoring = 'biomes' | 'regions' | 'height'
/** A square of map tiles with heights at one block a pixel, row by row from the north west. */
export interface MapTerrainArea {
tiles: MapTile[][]
/** The world block of the first tile's first pixel. */
originX: number
originZ: number
}
const UNLABELLED_COLOR = 0x5a5f6b
/** The area's tiles as one surface, a column to a pixel, without the ring each tile carries for its neighbours; the sea fills up to fluid height. */
/** One map tile with heights as a surface, a column to a pixel, without the ring the tile carries for its neighbours; the sea fills up to fluid height. */
export class MapTerrain implements TerrainSurface {
readonly columns: number
readonly rows: number
readonly originX: number
readonly originZ: number
private readonly size: number
readonly blocksPerColumn: number
constructor(
private readonly area: MapTerrainArea,
private readonly tile: MapTile,
place: TerrainTile,
private readonly coloring: MapTerrainColoring,
private readonly fluidHeight: number
) {
this.size = area.tiles[0][0].size
this.originX = area.originX
this.originZ = area.originZ
this.columns = area.tiles[0].length * this.size
this.rows = area.tiles.length * this.size
this.columns = tile.size
this.rows = tile.size
this.originX = originXOf(place)
this.originZ = originZOf(place)
this.blocksPerColumn = blocksPerColumn(place.level)
}
groundAt(column: number, row: number): number {
@@ -46,19 +40,16 @@ export class MapTerrain implements TerrainSurface {
if (this.coloring === 'height') {
return heightColor(this.heightAt(column, row), this.fluidHeight)
}
const { tile, cell } = this.cellAt(column, row)
const index = this.coloring === 'regions' ? tile.regions[cell] : tile.subjects[cell]
return index === NO_LABEL ? UNLABELLED_COLOR : tile.labels[index].color
const index = this.coloring === 'regions' ? this.tile.regions[this.cellAt(column, row)] : this.tile.subjects[this.cellAt(column, row)]
return index === NO_LABEL ? UNLABELLED_COLOR : this.tile.labels[index].color
}
private heightAt(column: number, row: number): number {
const { tile, cell } = this.cellAt(column, row)
return tile.heights![cell]
return this.tile.heights![this.cellAt(column, row)]
}
private cellAt(column: number, row: number): { tile: MapTile; cell: number } {
const tile = this.area.tiles[Math.floor(row / this.size)][Math.floor(column / this.size)]
const gridSize = this.size + 2
return { tile, cell: ((row % this.size) + 1) * gridSize + (column % this.size) + 1 }
private cellAt(column: number, row: number): number {
const gridSize = this.tile.size + 2
return (row + 1) * gridSize + column + 1
}
}
+24 -29
View File
@@ -1,70 +1,65 @@
import type { SavedTile } from '../bridge/types'
import { heightColor } from '../map/heightColors'
import type { TerrainSurface } from './terrainMesh'
import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from './terrainTiles'
export type SavedTerrainColoring = 'biomes' | 'blocks' | 'height'
/** A square of saved tiles at one block a pixel, row by row from the north west. */
export interface SavedTerrainArea {
tiles: SavedTile[][]
/** The world block of the first tile's first pixel. */
originX: number
originZ: number
/** A saved tile and the colour of every block it holds. */
export interface ReadSavedTile {
tile: SavedTile
blockColors: Map<string, number>
}
// A world without water is measured from where vanilla's sea would be.
const VANILLA_SEA_LEVEL = 63
const UNKNOWN_BLOCK_COLOR = 0x7f7f7f
/**
* The saved columns as one surface, a column to a pixel, so each is the block it was read from.
*/
/** One saved tile as a surface, a column to a pixel, so each is the block it was read from. */
export class SavedTerrain implements TerrainSurface {
readonly columns: number
readonly rows: number
readonly originX: number
readonly originZ: number
private readonly size: number
readonly blocksPerColumn: number
constructor(
private readonly area: SavedTerrainArea,
private readonly read: ReadSavedTile,
place: TerrainTile,
private readonly coloring: SavedTerrainColoring,
private readonly seaLevel: number | null,
private readonly blockColors: Map<string, number>
private readonly seaLevel: number | null
) {
this.size = area.tiles[0][0].size
this.originX = area.originX
this.originZ = area.originZ
this.columns = area.tiles[0].length * this.size
this.rows = area.tiles.length * this.size
this.columns = read.tile.size
this.rows = read.tile.size
this.originX = originXOf(place)
this.originZ = originZOf(place)
this.blocksPerColumn = blocksPerColumn(place.level)
}
groundAt(column: number, row: number): number | null {
const { tile, pixel } = this.pixelAt(column, row)
const ground = tile.groundY[pixel]
return ground === tile.noGround ? null : ground
const ground = this.read.tile.groundY[this.pixelAt(column, row)]
return ground === this.read.tile.noGround ? null : ground
}
waterAt(column: number, row: number): number | null {
const { tile, pixel } = this.pixelAt(column, row)
const water = tile.waterSurfaceY[pixel]
return water === tile.noWater ? null : water
const water = this.read.tile.waterSurfaceY[this.pixelAt(column, row)]
return water === this.read.tile.noWater ? null : water
}
colorAt(column: number, row: number): number {
const { tile, pixel } = this.pixelAt(column, row)
const { tile, blockColors } = this.read
const pixel = this.pixelAt(column, row)
switch (this.coloring) {
case 'height':
return heightColor(tile.groundY[pixel], this.seaLevel ?? VANILLA_SEA_LEVEL)
case 'blocks':
return this.blockColors.get(tile.blockNames[tile.blocks[pixel]]) ?? UNKNOWN_BLOCK_COLOR
return blockColors.get(tile.blockNames[tile.blocks[pixel]]) ?? UNKNOWN_BLOCK_COLOR
case 'biomes':
return tile.biomeLabels[tile.biomes[pixel]].color
}
}
private pixelAt(column: number, row: number): { tile: SavedTile; pixel: number } {
const tile = this.area.tiles[Math.floor(row / this.size)][Math.floor(column / this.size)]
return { tile, pixel: (row % this.size) * this.size + (column % this.size) }
private pixelAt(column: number, row: number): number {
return row * this.read.tile.size + column
}
}
@@ -0,0 +1,28 @@
import type { BridgeClient } from '../bridge/BridgeClient'
import type { TileSource } from '../map/TileStore'
import type { BlockColors } from './blockColors'
import type { ReadSavedTile } from './savedTerrain'
import { TILE_COLUMNS } from './terrainTiles'
/** Which saved world the tiles are read from. */
export interface SavedLayer {
worldId: string
/** Bumped to read the region files again, so older tiles are not used again. */
readings: number
}
// The block and biome names and colours a tile carries, as far as they add up.
const ESTIMATED_EXTRA_BYTES_PER_COLUMN = 4
/** A saved world's tiles, each with the colour of every block in it. */
export function savedTileSource(client: BridgeClient, blockColors: BlockColors): TileSource<ReadSavedTile, SavedLayer, never> {
return {
layerKey: (layer) => `${layer.worldId}/${layer.readings}`,
fetch: async (address, layer, signal) => {
const tile = await client.savedTile(layer.worldId, address.tileX, address.tileZ, address.blocksPerPixel, TILE_COLUMNS, signal)
return { tile, blockColors: await blockColors.colorsOf(tile.blockNames) }
},
bytesOf: ({ tile }) =>
tile.groundY.byteLength + tile.waterSurfaceY.byteLength + tile.blocks.byteLength + tile.biomes.byteLength + tile.size * tile.size * ESTIMATED_EXTRA_BYTES_PER_COLUMN
}
}
@@ -0,0 +1,72 @@
import { Ray, Vector3 } from 'three'
import { describe, expect, it } from 'vitest'
import { ColumnField } from './columnField'
import { marchOntoSurface } from './surfaceMarch'
const GROUND = 10
const POND_GROUND = 7
const WATER = 9
const REACH = 500
const CEILING = 100
// Three by three columns from (100, 200): nothing known at the north west corner, a pond at the middle column.
const field = new ColumnField({
columns: 3,
rows: 3,
originX: 100,
originZ: 200,
blocksPerColumn: 1,
groundAt: (column, row) => (column === 0 && row === 0 ? null : column === 1 && row === 1 ? POND_GROUND : GROUND),
waterAt: (column, row) => (column === 1 && row === 1 ? WATER : null),
colorAt: () => 0
})
function pick(origin: Vector3, direction: Vector3): Vector3 | null {
return marchOntoSurface(new Ray(origin, direction.normalize()), REACH, CEILING, (x, z) => field.surfaceTopOver(x, z))
}
describe('marching onto the surface', () => {
it('finds the water over the pond and the top of the ground beside it', () => {
const water = pick(new Vector3(101.5, 30, 201.5), new Vector3(0, -1, 0))!
expect(water.x).toBeCloseTo(101.5, 3)
expect(water.y).toBeCloseTo(WATER + 1, 3)
expect(water.z).toBeCloseTo(201.5, 3)
expect(pick(new Vector3(102.5, 30, 201.5), new Vector3(0, -1, 0))!.y).toBeCloseTo(GROUND + 1, 3)
})
it('finds where a slanted ray meets the side of a column', () => {
expect(pick(new Vector3(95, GROUND, 202.5), new Vector3(1, -0.01, 0))!.x).toBeCloseTo(100, 1)
})
it('finds nothing over an unknown column, beside the field, or from below the ground', () => {
expect(pick(new Vector3(100.5, 30, 200.5), new Vector3(0, -1, 0))).toBeNull()
expect(pick(new Vector3(300, 30, 202.5), new Vector3(0, -1, 0))).toBeNull()
expect(pick(new Vector3(102.5, GROUND - 2, 202.5), new Vector3(0, 1, 0))).toBeNull()
})
it('meets the side where a ray comes in from the side below the top', () => {
const hit = pick(new Vector3(90, GROUND - 1, 202.5), new Vector3(1, 0, 0))!
expect(hit.x).toBeCloseTo(100, 3)
expect(hit.y).toBeCloseTo(GROUND - 1, 3)
})
it('gives up on a ray that climbs above the highest ground', () => {
expect(pick(new Vector3(95, 50, 202.5), new Vector3(1, 1, 0))).toBeNull()
})
it('reaches ground far away, where it steps further at a time', () => {
const far = new ColumnField({
columns: 1,
rows: 1,
originX: 400,
originZ: 0,
blocksPerColumn: 64,
groundAt: () => GROUND,
waterAt: () => null,
colorAt: () => 0
})
const hit = marchOntoSurface(new Ray(new Vector3(0, 100, 30), new Vector3(1, -0.2, 0).normalize()), 5000, CEILING, (x, z) => far.surfaceTopOver(x, z))!
expect(hit.y).toBeCloseTo(GROUND + 1, 2)
expect(hit.x).toBeGreaterThan(400)
})
})
@@ -0,0 +1,47 @@
import { Vector3, type Ray } from 'three'
const FINEST_STEP_BLOCKS = 0.5
// Further off, a step is longer: what lies there is drawn in coarser columns.
const STEP_PER_DISTANCE = 0.01
const REFINEMENTS = 16
/**
* Where the ray first comes down onto the surface within {@code reach}, found by marching along it, so a pick does not
* have to test every face. {@code surfaceTopOver} says where the surface stands over a block, or null where nothing is
* known. A ray that starts below the surface, or leaves above {@code ceilingY}, finds nothing.
*/
export function marchOntoSurface(ray: Ray, reach: number, ceilingY: number, surfaceTopOver: (worldX: number, worldZ: number) => number | null): Vector3 | null {
const pointAt = (distance: number): Vector3 => ray.direction.clone().multiplyScalar(distance).add(ray.origin)
const isBelow = (point: Vector3): boolean => {
const top = surfaceTopOver(point.x, point.z)
return top !== null && point.y <= top
}
if (isBelow(ray.origin)) {
return null
}
let above = 0
while (above < reach) {
const below = Math.min(reach, above + Math.max(FINEST_STEP_BLOCKS, above * STEP_PER_DISTANCE))
const point = pointAt(below)
if (isBelow(point)) {
return refined(above, below, pointAt, isBelow)
}
if (point.y > ceilingY && ray.direction.y >= 0) {
return null
}
above = below
}
return null
}
function refined(above: number, below: number, pointAt: (distance: number) => Vector3, isBelow: (point: Vector3) => boolean): Vector3 {
for (let refinement = 0; refinement < REFINEMENTS; refinement++) {
const middle = (above + below) / 2
if (isBelow(pointAt(middle))) {
below = middle
} else {
above = middle
}
}
return pointAt(below)
}
+1 -1
View File
@@ -4,7 +4,7 @@ import type { ViewportContent } from '../studio/SceneViewport'
/** Where the ray first meets what the content draws within {@code reach}, or null when it passes by. */
export function surfaceAlong(content: ViewportContent, ray: Ray, reach: number): Vector3 | null {
if (content.surfaceAlong !== undefined) {
return content.surfaceAlong(ray)
return content.surfaceAlong(ray, reach)
}
const caster = new Raycaster(ray.origin, ray.direction, 0, reach)
const [nearest] = caster.intersectObject(content.object, true)
@@ -0,0 +1,124 @@
import { PerspectiveCamera, Vector3 } from 'three'
import { describe, expect, it } from 'vitest'
import { CameraSight } from './cameraSight'
import { planCover, type DrawnTile, type TileState } from './terrainCover'
import { addressOf, blocksPerColumn, columnsUnder, isInside, originXOf, originZOf, tileBlocks, tileKey, type TerrainTile } from './terrainTiles'
const COARSEST_LEVEL = 12
const LOOKED_AT = new Vector3(0, 64, 0)
const SAMPLE_RADIUS_BLOCKS = 300
const SAMPLE_STEP_BLOCKS = 23
// Looks down at the ground around the origin from {@code height} blocks above it, from the south.
function sightFrom(height: number): CameraSight {
const camera = new PerspectiveCamera(45, 1.6, height * 0.01, height * 20)
camera.position.set(0, 64 + height, height * 0.6)
camera.lookAt(LOOKED_AT)
camera.updateMatrixWorld()
return new CameraSight({ camera, width: 1280, height: 800, orbitDistance: camera.position.distanceTo(LOOKED_AT) }, 0, 128)
}
const nothingReady = (): TileState => 'none'
const everythingReady = (): TileState => 'fresh'
function holeContains(draw: DrawnTile, x: number, z: number): boolean {
const step = blocksPerColumn(draw.tile.level)
const column = Math.floor((x - originXOf(draw.tile)) / step)
const row = Math.floor((z - originZOf(draw.tile)) / step)
return draw.holes.some((hole) => column >= hole.fromColumn && column < hole.toColumn && row >= hole.fromRow && row < hole.toRow)
}
// How many drawn tiles show the ground at the block: one when finer tiles take over exactly where coarser ones have holes.
function drawnOver(draws: DrawnTile[], x: number, z: number): number {
return draws.filter((draw) => {
const size = tileBlocks(draw.tile.level)
const inside = x >= originXOf(draw.tile) && x < originXOf(draw.tile) + size && z >= originZOf(draw.tile) && z < originZOf(draw.tile) + size
return inside && !holeContains(draw, x, z)
}).length
}
function expectEverySpotDrawnOnce(draws: DrawnTile[]): void {
for (let x = -SAMPLE_RADIUS_BLOCKS; x <= SAMPLE_RADIUS_BLOCKS; x += SAMPLE_STEP_BLOCKS) {
for (let z = -SAMPLE_RADIUS_BLOCKS; z <= SAMPLE_RADIUS_BLOCKS; z += SAMPLE_STEP_BLOCKS) {
expect(drawnOver(draws, x + 0.5, z + 0.5), `${x}, ${z}`).toBe(1)
}
}
}
describe('terrain cover', () => {
it('asks for the coarse backdrop first, once for each tile', () => {
const { draws, wanted } = planCover(sightFrom(2000), nothingReady, COARSEST_LEVEL)
expect(draws).toEqual([])
expect(wanted[0].level).toBe(Math.max(...wanted.map((tile) => tile.level)))
expect(new Set(wanted.map(tileKey)).size).toBe(wanted.length)
expect(Math.min(...wanted.map((tile) => tile.level))).toBeLessThan(wanted[0].level)
})
it('wants nothing once every tile it needs is sampled', () => {
expect(planCover(sightFrom(2000), everythingReady, COARSEST_LEVEL).wanted).toEqual([])
})
it('draws ground close to the camera in single blocks and far above it in wider columns', () => {
const near = planCover(sightFrom(150), everythingReady, COARSEST_LEVEL).draws
const far = planCover(sightFrom(30_000), everythingReady, COARSEST_LEVEL).draws
expect(Math.min(...near.map((draw) => draw.tile.level))).toBe(0)
expect(Math.min(...far.map((draw) => draw.tile.level))).toBeGreaterThanOrEqual(3)
})
it('never asks for more than a backdrop, a preview and detail of 64 tiles each', () => {
for (const height of [60, 600, 6000, 600_000]) {
const { wanted } = planCover(sightFrom(height), nothingReady, COARSEST_LEVEL)
expect(wanted.length).toBeLessThanOrEqual(3 * 64)
}
})
it('leaves a hole in each coarser tile where a finer one is drawn, so every spot is drawn once', () => {
const { draws } = planCover(sightFrom(2000), everythingReady, COARSEST_LEVEL)
for (const coarse of draws) {
for (const finer of draws.filter((other) => isInside(other.tile, coarse.tile))) {
expect(coarse.holes).toContainEqual(columnsUnder(coarse.tile, finer.tile))
}
}
expectEverySpotDrawnOnce(draws)
})
it('shows the backdrop alone until finer tiles are sampled', () => {
const wanted = planCover(sightFrom(2000), nothingReady, COARSEST_LEVEL).wanted
const backdropLevel = wanted[0].level
const state = (tile: TerrainTile): TileState => (tile.level === backdropLevel ? 'fresh' : 'none')
const { draws } = planCover(sightFrom(2000), state, COARSEST_LEVEL)
expect(draws.length).toBeGreaterThan(0)
expect(draws.every((draw) => draw.tile.level === backdropLevel && draw.holes.length === 0)).toBe(true)
expectEverySpotDrawnOnce(draws)
})
it('lets any tiles that are sampled stand in for the rest without gaps or overlaps', () => {
const wanted = planCover(sightFrom(2000), nothingReady, COARSEST_LEVEL).wanted
const backdropLevel = wanted[0].level
const sampled = new Set(wanted.filter((_, index) => index % 3 === 0).map(tileKey))
const state = (tile: TerrainTile): TileState => (tile.level === backdropLevel || sampled.has(tileKey(tile)) ? 'fresh' : 'none')
expectEverySpotDrawnOnce(planCover(sightFrom(2000), state, COARSEST_LEVEL).draws)
})
it('draws finer tiles left over from before in place of one not sampled yet', () => {
const wanted = planCover(sightFrom(2000), nothingReady, COARSEST_LEVEL).wanted
const backdropLevel = wanted[0].level
const leaf = wanted.find((tile) => tile.level > 0 && tile.level < backdropLevel)!
const leftOver = new Set([tileKey({ level: leaf.level - 1, tileX: leaf.tileX * 2, tileZ: leaf.tileZ * 2 })])
const state = (tile: TerrainTile): TileState => (tile.level === backdropLevel || leftOver.has(tileKey(tile)) ? 'standIn' : 'none')
const { draws } = planCover(sightFrom(2000), state, COARSEST_LEVEL)
expect(draws.map((draw) => tileKey(draw.tile))).toContain([...leftOver][0])
expectEverySpotDrawnOnce(draws)
})
it('asks again for ground that only stands in', () => {
const standIn = (): TileState => 'standIn'
const { wanted } = planCover(sightFrom(2000), standIn, COARSEST_LEVEL)
expect(wanted.length).toBeGreaterThan(0)
})
it('addresses each wanted tile by the blocks it holds', () => {
const { wanted } = planCover(sightFrom(2000), nothingReady, COARSEST_LEVEL)
expect(wanted.map(addressOf).every((address) => Number.isInteger(Math.log2(address.blocksPerPixel)))).toBe(true)
})
})
@@ -0,0 +1,138 @@
import type { CameraSight } from './cameraSight'
import {
ancestorAt,
childrenOf,
columnsUnder,
isInside,
MOST_LEVELS_FINER,
TILE_COLUMNS,
tileKey,
type ColumnArea,
type TerrainTile
} from './terrainTiles'
/** What is known of a tile: its ground, ground left over from before the layer changed that stands in until it is sampled anew, or nothing. */
export type TileState = 'none' | 'standIn' | 'fresh'
export interface DrawnTile {
tile: TerrainTile
/** The columns finer tiles draw instead. */
holes: ColumnArea[]
}
export interface Cover {
draws: DrawnTile[]
/** What to sample, most needed first: the backdrop, then a level finer than the detail, then the detail. */
wanted: TerrainTile[]
}
// A column is drawn at most this many pixels wide, as wider ones show their blockiness; coarser ones only where there are too many.
const MOST_COLUMN_PIXELS = 1
// A little above one, as tiles in sight stick out past the view's edges; beyond it, columns only add faces no one can tell apart.
const MOST_COLUMNS_PER_PIXEL = 1.25
const MOST_TILES_IN_SIGHT = 64
const DETAIL_MARGIN = 0.15
const BACKDROP_MARGIN = 0.5
const PREVIEW_LEVELS_ABOVE_DETAIL = 1
const MOST_LEVELS_FINER_LEFT_OVER = 2
const BACKDROP_TILE_BLOCKS_PER_ORBIT_BLOCK = 1
const COLUMNS_PER_TILE = TILE_COLUMNS * TILE_COLUMNS
type StateOf = (tile: TerrainTile) => TileState
/**
* What to draw for one camera, and which tiles it still needs. Detail tiles in sight have columns about a pixel wide,
* nearer ground finer than far ground; backdrop tiles cover the view and more with coarser columns. Until detail is
* sampled the nearest sampled tile of a coarser level stands in, with holes where finer tiles are ready, and detail
* left over from before zooming out stands in for the coarser tile that is not sampled yet.
*
* @param coarsestLevel the coarsest level the source can sample
*/
export function planCover(sight: CameraSight, stateOf: StateOf, coarsestLevel: number): Cover {
const backdropLevel = backdropLevelFor(sight, coarsestLevel)
const finestLevel = Math.max(0, backdropLevel - MOST_LEVELS_FINER)
const backdrop = sight.tilesAt(backdropLevel, BACKDROP_MARGIN).sort(nearestFirst(sight)).slice(0, MOST_TILES_IN_SIGHT)
const detail = detailTiles(sight, backdrop, backdropLevel, finestLevel)
const ready = candidatesOf(backdrop, detail, backdropLevel, finestLevel, stateOf).filter((tile) => stateOf(tile) !== 'none')
return {
draws: ready.map((tile) => ({ tile, holes: ready.filter((finer) => isInside(finer, tile)).map((finer) => columnsUnder(tile, finer)) })),
wanted: wantedInOrder(sight, backdrop, detail, backdropLevel, stateOf)
}
}
// The backdrop tiles are about as wide as the camera is far from what is in the middle, which puts a few of them in sight.
function backdropLevelFor(sight: CameraSight, coarsestLevel: number): number {
const wanted = Math.ceil(Math.log2(Math.max(1, (sight.orbitDistance * BACKDROP_TILE_BLOCKS_PER_ORBIT_BLOCK) / TILE_COLUMNS)))
let level = Math.min(coarsestLevel, Math.max(0, wanted))
while (level < coarsestLevel && sight.tilesAt(level, BACKDROP_MARGIN).length > MOST_TILES_IN_SIGHT) {
level++
}
return level
}
// Each backdrop tile is split into finer tiles while their columns would look wider than the threshold, and the
// threshold is raised until there are no more columns than the view has pixels to show.
function detailTiles(sight: CameraSight, backdrop: TerrainTile[], backdropLevel: number, finestLevel: number): TerrainTile[] {
const mostColumns = Math.min(sight.pixelsWithin(DETAIL_MARGIN) * MOST_COLUMNS_PER_PIXEL, MOST_TILES_IN_SIGHT * COLUMNS_PER_TILE)
let threshold = MOST_COLUMN_PIXELS
for (;;) {
const detail = backdrop.flatMap((tile) => splitWhileCoarse(sight, tile, threshold, finestLevel))
const nothingToCoarsen = detail.every((tile) => tile.level === backdropLevel)
if (nothingToCoarsen || (detail.length * COLUMNS_PER_TILE <= mostColumns && detail.length <= MOST_TILES_IN_SIGHT)) {
return detail
}
threshold *= 2
}
}
function splitWhileCoarse(sight: CameraSight, tile: TerrainTile, threshold: number, finestLevel: number): TerrainTile[] {
if (tile.level <= finestLevel || sight.columnPixels(tile) <= threshold) {
return [tile]
}
return childrenOf(tile)
.filter((child) => sight.sees(child, DETAIL_MARGIN))
.flatMap((child) => splitWhileCoarse(sight, child, threshold, finestLevel))
}
// Everything that may be drawn for the view: the backdrop, the detail and the levels between that happen to be there,
// and, where detail is missing, finer tiles left over from before. None is finer than a backdrop tile can be cut a hole for.
function candidatesOf(backdrop: TerrainTile[], detail: TerrainTile[], backdropLevel: number, finestLevel: number, stateOf: StateOf): TerrainTile[] {
const candidates = new Map<string, TerrainTile>()
const add = (tile: TerrainTile): void => void candidates.set(tileKey(tile), tile)
backdrop.forEach(add)
for (const tile of detail) {
add(tile)
for (let level = tile.level + 1; level <= backdropLevel; level++) {
add(ancestorAt(tile, level))
}
if (stateOf(tile) === 'none') {
finerLeftOver(tile, finestLevel, stateOf, MOST_LEVELS_FINER_LEFT_OVER).forEach(add)
}
}
return [...candidates.values()]
}
function finerLeftOver(tile: TerrainTile, finestLevel: number, stateOf: StateOf, levels: number): TerrainTile[] {
if (levels === 0 || tile.level <= finestLevel) {
return []
}
return childrenOf(tile).flatMap((child) => [...(stateOf(child) === 'none' ? [] : [child]), ...finerLeftOver(child, finestLevel, stateOf, levels - 1)])
}
function wantedInOrder(sight: CameraSight, backdrop: TerrainTile[], detail: TerrainTile[], backdropLevel: number, stateOf: StateOf): TerrainTile[] {
const previews = detail
.filter((tile) => tile.level + PREVIEW_LEVELS_ABOVE_DETAIL < backdropLevel)
.map((tile) => ancestorAt(tile, tile.level + PREVIEW_LEVELS_ABOVE_DETAIL))
const wanted = new Map<string, TerrainTile>()
for (const group of [backdrop, previews, detail]) {
group
.filter((tile) => stateOf(tile) !== 'fresh')
.sort(nearestFirst(sight))
.forEach((tile) => wanted.set(tileKey(tile), wanted.get(tileKey(tile)) ?? tile))
}
return [...wanted.values()]
}
function nearestFirst(sight: CameraSight): (first: TerrainTile, second: TerrainTile) => number {
return (first, second) => sight.distanceFromMiddle(first) - sight.distanceFromMiddle(second)
}
@@ -1,4 +1,4 @@
import { Ray, Vector3, type BufferGeometry, type Mesh } from 'three'
import { Vector3, type BufferGeometry, type Mesh } from 'three'
import { describe, expect, it } from 'vitest'
import { buildTerrainMesh, type TerrainSurface } from './terrainMesh'
@@ -6,6 +6,7 @@ const GROUND = 10
const POND_GROUND = 7
const WATER = 9
const BASE_DEPTH = 8
const BASE = POND_GROUND + 1 - BASE_DEPTH
const GREY = 0x808080
const RED = 0xff0000
@@ -16,6 +17,7 @@ function surfaceOf(colorAt: TerrainSurface['colorAt'] = () => GREY): TerrainSurf
rows: 3,
originX: 100,
originZ: 200,
blocksPerColumn: 1,
groundAt: (column, row) => {
if (column === 0 && row === 0) {
return null
@@ -30,7 +32,7 @@ function surfaceOf(colorAt: TerrainSurface['colorAt'] = () => GREY): TerrainSurf
const surface = surfaceOf()
function meshes(terrain: TerrainSurface = surface): { ground: Mesh; water: Mesh } {
const [ground, water] = buildTerrainMesh(terrain).content.object.children as Mesh[]
const [ground, water] = buildTerrainMesh(terrain, BASE).object.children as Mesh[]
return { ground, water }
}
@@ -90,52 +92,45 @@ describe('terrain mesh', () => {
expect([...lights].sort()).toEqual([0.6, 0.8, 1])
})
it('frames the known columns from below their sides to the highest water or ground', () => {
const bounds = buildTerrainMesh(surface).content.bounds
expect(bounds.min.toArray()).toEqual([100, POND_GROUND + 1 - BASE_DEPTH, 200])
expect(bounds.max.toArray()).toEqual([103, GROUND + 1, 203])
})
it('draws the water of a column as its top, and no side where the ground beside it stands higher', () => {
const { water } = meshes()
expect(quads(water)).toBe(1)
expect(faces(water.geometry)[0].middle.toArray()).toEqual([101.5, WATER + 1, 201.5])
})
it('draws a water side where the water stands above what lies beside it', () => {
const lake = { ...surface, groundAt: (column: number, row: number) => (column === 1 && row === 1 ? POND_GROUND : column === 0 && row === 0 ? null : WATER - 3) }
it('draws a water side where the water stands above what lies beside it, but not beside nothing known', () => {
const lake = { ...surface, groundAt: (column: number, row: number) => (column === 1 && row === 1 ? POND_GROUND : column === 0 && row === 1 ? null : WATER - 3) }
const sides = faces(meshes(lake).water.geometry).filter((face) => face.normal.y === 0)
expect(sides).toHaveLength(4)
expect(sides).toHaveLength(3)
expect(sides.every((side) => side.middle.y === (POND_GROUND + 1 + WATER + 1) / 2)).toBe(true)
})
})
describe('terrain surface picking', () => {
const content = buildTerrainMesh(surface).content
const pick = (origin: Vector3, direction: Vector3): Vector3 | null => content.surfaceAlong!(new Ray(origin, direction.normalize()))
it('finds the water over the pond and the top of the ground beside it', () => {
const water = pick(new Vector3(101.5, 30, 201.5), new Vector3(0, -1, 0))!
expect(water.x).toBeCloseTo(101.5, 3)
expect(water.y).toBeCloseTo(WATER + 1, 3)
expect(water.z).toBeCloseTo(201.5, 3)
expect(pick(new Vector3(102.5, 30, 201.5), new Vector3(0, -1, 0))!.y).toBeCloseTo(GROUND + 1, 3)
it('draws no water side at the edge of the field, where the water goes on in the next one', () => {
const shore = { ...surface, groundAt: () => WATER - 3, waterAt: () => WATER }
const sides = faces(meshes(shore).water.geometry).filter((face) => face.normal.y === 0)
expect(sides).toHaveLength(0)
})
it('finds where a slanted ray meets the side of a column', () => {
const hit = pick(new Vector3(95, GROUND, 202.5), new Vector3(1, -0.01, 0))!
expect(hit.x).toBeCloseTo(100, 1)
it('spreads columns over as many blocks as they are wide', () => {
const coarse = { ...surface, blocksPerColumn: 4 }
const tops = faces(meshes(coarse).ground.geometry).filter((face) => face.normal.y === 1)
const xs = tops.map((top) => top.middle.x)
expect(Math.min(...xs)).toBeGreaterThanOrEqual(100)
expect(Math.max(...xs)).toBeLessThanOrEqual(112)
expect(faces(meshes(coarse).water.geometry)[0].middle.toArray()).toEqual([106, WATER + 1, 206])
})
it('finds nothing over an unknown column, beside the field, or from below the ground', () => {
expect(pick(new Vector3(100.5, 30, 200.5), new Vector3(0, -1, 0))).toBeNull()
expect(pick(new Vector3(300, 30, 202.5), new Vector3(0, -1, 0))).toBeNull()
expect(pick(new Vector3(102.5, GROUND - 2, 202.5), new Vector3(0, 1, 0))).toBeNull()
it('leaves out the columns of a hole and walls what stands beside it', () => {
const holed = buildTerrainMesh(surface, BASE, [{ fromColumn: 2, fromRow: 2, toColumn: 3, toRow: 3 }])
const [ground] = holed.object.children as Mesh[]
const tops = faces(ground.geometry).filter((face) => face.normal.y === 1)
expect(tops.every((top) => !(top.middle.x === 102.5 && top.middle.z === 202.5))).toBe(true)
expect(holed.field.surfaceTop(2, 2)).toBeNull()
expect(faces(ground.geometry).filter((face) => face.normal.y === 0 && face.middle.x === 102.5 && face.middle.z === 202)).toHaveLength(1)
})
it('meets the side where a ray comes in from the side below the rim', () => {
const hit = pick(new Vector3(90, GROUND - 1, 202.5), new Vector3(1, 0, 0))!
expect(hit.x).toBeCloseTo(100, 3)
expect(hit.y).toBeCloseTo(GROUND - 1, 3)
it('has no mesh where no column has ground', () => {
const nothing = buildTerrainMesh({ ...surface, groundAt: () => null }, BASE)
expect(nothing.object.children).toHaveLength(0)
})
})
+19 -15
View File
@@ -1,12 +1,12 @@
import { DoubleSide, FrontSide, Group, Mesh, MeshBasicMaterial } from 'three'
import type { ViewportContent } from '../studio/SceneViewport'
import { groundFaces, waterFaces } from './columnFaces'
import { ColumnField } from './columnField'
import type { ColumnArea } from './terrainTiles'
/**
* Terrain to draw as columns, one block each, row by row from the north west: the ground, the water over it, and the
* ground's colour. Heights are the Y of the top block, so a column of 64 has its top face at 65. Where nothing is
* known, the ground is null and the column is left out.
* Terrain to draw as columns, row by row from the north west: the ground, the water over it, and the ground's colour.
* Heights are the Y of the top block, so a column of 64 has its top face at 65. Where nothing is known, the ground is
* null and the column is left out.
*/
export interface TerrainSurface {
readonly columns: number
@@ -14,6 +14,8 @@ export interface TerrainSurface {
/** The world block of the first column and of the first row. */
readonly originX: number
readonly originZ: number
/** How many blocks wide and deep a column is. */
readonly blocksPerColumn: number
groundAt(column: number, row: number): number | null
/** The Y of the water's top block over the column, or null where it is dry. */
waterAt(column: number, row: number): number | null
@@ -21,31 +23,33 @@ export interface TerrainSurface {
}
export interface TerrainMesh {
content: ViewportContent
object: Group
field: ColumnField
dispose(): void
}
const WATER_COLOR = 0x3f76e4
const WATER_OPACITY = 0.55
const BASE_DEPTH_BLOCKS = 8
/**
* The surface as block columns with their faces merged where neighbours show the same one, flat-shaded as Minecraft
* shades blocks, with see-through water over them. Sides on the rim reach down to below the lowest ground, so the
* square reads as a solid block cut from the world.
* The surface as columns with their faces merged where neighbours show the same one, flat-shaded as Minecraft shades
* blocks, with see-through water over them. Sides on the edge reach down to {@code base}, so tiles of ground next to
* each other leave no cracks. The columns in {@code holes} are left out, for finer ground to fill.
*/
export function buildTerrainMesh(surface: TerrainSurface): TerrainMesh {
const field = new ColumnField(surface)
const base = field.lowestTop() - BASE_DEPTH_BLOCKS
export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: readonly ColumnArea[] = []): TerrainMesh {
const field = new ColumnField(surface, holes)
const group = new Group()
if (!field.hasAnyGround()) {
return { object: group, field, dispose: () => {} }
}
const ground = groundFaces(field, base).geometry()
const water = waterFaces(field).geometry()
const groundMaterial = new MeshBasicMaterial({ vertexColors: true, side: FrontSide })
const waterMaterial = new MeshBasicMaterial({ color: WATER_COLOR, transparent: true, opacity: WATER_OPACITY, depthWrite: false, side: DoubleSide })
const group = new Group()
group.add(new Mesh(ground, groundMaterial), new Mesh(water, waterMaterial))
const bounds = field.bounds(base)
return {
content: { object: group, bounds, surfaceAlong: (ray) => field.surfaceAlong(ray, bounds) },
object: group,
field,
dispose: () => {
ground.dispose()
water.dispose()
@@ -0,0 +1,179 @@
import { PerspectiveCamera, Ray, Vector3, type Mesh } from 'three'
import { describe, expect, it, vi } from 'vitest'
import type { TileSource } from '../map/TileStore'
import type { CameraLink } from '../studio/SceneViewport'
import { focusAround, TerrainStream, type TerrainStyle } from './terrainStream'
interface FlatTile {
height: number
}
interface FlatLayer {
name: string
height: number
/** Resolves the tiles of the layer once called; they stay on their way until then. */
gate: Promise<void>
}
const COARSEST_LEVEL = 8
const LOOKED_AT = new Vector3(0, 64, 0)
const open = Promise.resolve()
const flatStyle: TerrainStyle<FlatTile> = {
surfaceOf: (tile, place) => ({
columns: 128,
rows: 128,
originX: place.tileX * 128 * 2 ** place.level,
originZ: place.tileZ * 128 * 2 ** place.level,
blocksPerColumn: 2 ** place.level,
groundAt: () => tile.height,
waterAt: () => null,
colorAt: () => 0x808080
}),
floorY: 0,
topY: 128
}
function setUp(): {
stream: TerrainStream<FlatTile, FlatLayer>
camera: PerspectiveCamera
moved(): void
requested: number[]
pendingCounts: number[]
stopFollowing: () => void
} {
const requested: number[] = []
const pendingCounts: number[] = []
const source: TileSource<FlatTile, FlatLayer, never> = {
layerKey: (layer) => layer.name,
fetch: async (address, layer) => {
requested.push(address.blocksPerPixel)
await layer.gate
return { height: layer.height }
},
bytesOf: () => 1
}
const stream = new TerrainStream({
source,
coarsestLevel: COARSEST_LEVEL,
focus: focusAround(0, 0, 0, 128),
onPending: (pending) => pendingCounts.push(pending),
onError: (message) => {
throw new Error(message)
}
})
const camera = new PerspectiveCamera(45, 1.6, 4, 40_000)
camera.position.set(0, 664, 360)
camera.lookAt(LOOKED_AT)
const listeners = new Set<() => void>()
const link: CameraLink = {
view: () => ({ camera, width: 1280, height: 800, orbitDistance: camera.position.distanceTo(LOOKED_AT) }),
onMoved: (listener) => {
listeners.add(listener)
return () => listeners.delete(listener)
},
redraw: vi.fn()
}
const stopFollowing = stream.content.follow!(link)
return { stream, camera, moved: () => listeners.forEach((listener) => listener()), requested, pendingCounts, stopFollowing }
}
async function settle(): Promise<void> {
for (let turn = 0; turn < 30; turn++) {
await new Promise((resolve) => setTimeout(resolve, 0))
}
}
const meshesOf = (stream: TerrainStream<FlatTile, FlatLayer>): Mesh[] => stream.content.object.children.flatMap((tile) => tile.children as Mesh[])
describe('terrain stream', () => {
it('draws nothing until it has a layer and a style, then the tiles in sight as they arrive', async () => {
const { stream, requested } = setUp()
await settle()
expect(requested).toEqual([])
stream.restyle(flatStyle)
stream.showLayer({ name: 'one', height: 70, gate: open })
await settle()
expect(requested.length).toBeGreaterThan(0)
expect(stream.content.object.children.length).toBeGreaterThan(0)
})
it('asks for the coarsest tiles first and reports what is still on its way', async () => {
const { stream, requested, pendingCounts } = setUp()
stream.restyle(flatStyle)
stream.showLayer({ name: 'one', height: 70, gate: open })
await settle()
expect(requested[0]).toBe(Math.max(...requested))
expect(pendingCounts[0]).toBeGreaterThan(0)
expect(pendingCounts.at(-1)).toBe(0)
})
it('keeps the ground it drew while the tiles of another layer are on their way', async () => {
const { stream } = setUp()
stream.restyle(flatStyle)
stream.showLayer({ name: 'one', height: 70, gate: open })
await settle()
const drawn = stream.content.object.children.length
let release = (): void => {}
stream.showLayer({ name: 'two', height: 90, gate: new Promise<void>((resolve) => (release = resolve)) })
await settle()
expect(stream.content.object.children.length).toBe(drawn)
const ray = new Ray(new Vector3(10, 300, 10), new Vector3(0, -1, 0))
expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(71, 3)
release()
await settle()
expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(91, 3)
})
it('draws the tiles again in another style without asking for them again', async () => {
const { stream, requested } = setUp()
stream.restyle(flatStyle)
stream.showLayer({ name: 'one', height: 70, gate: open })
await settle()
const asked = requested.length
stream.restyle({ ...flatStyle, surfaceOf: (tile, place) => ({ ...flatStyle.surfaceOf(tile, place), groundAt: () => tile.height + 10 }) })
await settle()
expect(requested.length).toBe(asked)
const ray = new Ray(new Vector3(10, 300, 10), new Vector3(0, -1, 0))
expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(81, 3)
})
it('finds the ground a ray meets, and nothing where it passes by', async () => {
const { stream } = setUp()
stream.restyle(flatStyle)
stream.showLayer({ name: 'one', height: 70, gate: open })
await settle()
const down = new Ray(new Vector3(10, 300, 10), new Vector3(0, -1, 0))
expect(stream.content.surfaceAlong!(down, 1000)!.toArray().map(Math.round)).toEqual([10, 71, 10])
const up = new Ray(new Vector3(10, 300, 10), new Vector3(0, 1, 0))
expect(stream.content.surfaceAlong!(up, 1000)).toBeNull()
})
it('draws more tiles when the camera moves to ground it has not drawn', async () => {
const { stream, camera, moved } = setUp()
stream.restyle(flatStyle)
stream.showLayer({ name: 'one', height: 70, gate: open })
await settle()
const ray = new Ray(new Vector3(40_000, 300, 0), new Vector3(0, -1, 0))
expect(stream.content.surfaceAlong!(ray, 1000)).toBeNull()
camera.position.set(40_000, 664, 360)
camera.lookAt(new Vector3(40_000, 64, 0))
moved()
await settle()
expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(71, 3)
})
it('stops drawing when it is let go', async () => {
const { stream, stopFollowing, requested } = setUp()
stream.restyle(flatStyle)
stream.showLayer({ name: 'one', height: 70, gate: open })
await settle()
stopFollowing()
stream.dispose()
const asked = requested.length
stream.showLayer({ name: 'two', height: 90, gate: open })
await settle()
expect(requested.length).toBe(asked)
expect(meshesOf(stream)).toHaveLength(0)
})
})
@@ -0,0 +1,225 @@
import { Box3, Group, Vector3 } from 'three'
import { TileStore, type TileSource } from '../map/TileStore'
import type { CameraLink, ViewportContent } from '../studio/SceneViewport'
import { CameraSight } from './cameraSight'
import { marchOntoSurface } from './surfaceMarch'
import { planCover, type Cover, type DrawnTile, type TileState } from './terrainCover'
import { buildTerrainMesh, type TerrainMesh, type TerrainSurface } from './terrainMesh'
import { addressOf, tileContaining, tileKey, type TerrainTile } from './terrainTiles'
/** How the tiles of a source look as ground, and how low and high that ground can reach. */
export interface TerrainStyle<Tile> {
surfaceOf(tile: Tile, place: TerrainTile): TerrainSurface
floorY: number
topY: number
}
export interface TerrainStreamOptions<Tile, Layer> {
source: TileSource<Tile, Layer, never>
/** The coarsest level the source samples: tiles of level n have columns 2^n blocks wide. */
coarsestLevel: number
/** The box the camera frames when the terrain is first shown. */
focus: Box3
/** Told how many tiles are still on their way, whenever that changes. */
onPending(pending: number): void
onError(message: string): void
}
interface DrawnMesh<Tile> {
tile: TerrainTile
data: Tile
signature: string
mesh: TerrainMesh
}
const MESH_BUILD_BUDGET_MILLISECONDS = 12
const ABOVE_TOP_BLOCKS = 1
const FOCUS_HALF_SIDE_BLOCKS = 256
/** The box the camera first frames: a square of blocks around the spot, from {@code lowY} to {@code highY}. */
export function focusAround(centerX: number, centerZ: number, lowY: number, highY: number): Box3 {
return new Box3(
new Vector3(centerX - FOCUS_HALF_SIDE_BLOCKS, lowY, centerZ - FOCUS_HALF_SIDE_BLOCKS),
new Vector3(centerX + FOCUS_HALF_SIDE_BLOCKS, highY, centerZ + FOCUS_HALF_SIDE_BLOCKS)
)
}
/**
* Endless terrain drawn where the camera looks: tiles of one layer of a source, coarse ones first and then finer ones
* down to a column per pixel, fetched as the camera moves and kept within a memory budget, so going back is instant.
* Ground that was drawn before the layer changed stands in until its tile is sampled anew, and coarser tiles stand in
* for finer ones that are not there yet, so the view never empties while it catches up.
*/
export class TerrainStream<Tile, Layer> {
readonly content: ViewportContent
private readonly group = new Group()
private readonly store: TileStore<Tile, Layer, never>
private readonly drawn = new Map<string, DrawnMesh<Tile>>()
private standIns = new Map<string, Tile>()
private layer: Layer | null = null
private style: TerrainStyle<Tile> | null = null
private styleVersion = 0
private camera: CameraLink | null = null
private reportedPending = -1
private continuation: ReturnType<typeof setTimeout> | null = null
private disposed = false
constructor(private readonly options: TerrainStreamOptions<Tile, Layer>) {
this.store = new TileStore(options.source, () => this.replan(), options.onError)
this.content = {
object: this.group,
bounds: options.focus,
surfaceAlong: (ray, reach) => marchOntoSurface(ray, reach, (this.style?.topY ?? 0) + ABOVE_TOP_BLOCKS, (x, z) => this.surfaceTopOver(x, z)),
follow: (camera) => this.follow(camera)
}
}
/** Draws another layer of the source; what is drawn now stays until the new layer's tiles replace it. */
showLayer(layer: Layer): void {
if (this.layer !== null && this.options.source.layerKey(this.layer) === this.options.source.layerKey(layer)) {
this.layer = layer
return
}
this.standIns = new Map([...this.drawn].map(([key, drawn]) => [key, drawn.data]))
this.layer = layer
this.replan()
}
/** Draws the tiles another way, without sampling them again. */
restyle(style: TerrainStyle<Tile>): void {
this.style = style
this.styleVersion++
this.replan()
}
dispose(): void {
this.disposed = true
if (this.continuation !== null) {
clearTimeout(this.continuation)
}
this.drawn.forEach((drawn) => drawn.mesh.dispose())
this.drawn.clear()
this.group.clear()
this.store.clear()
}
private follow(camera: CameraLink): () => void {
this.camera = camera
const stop = camera.onMoved(() => this.replan())
this.replan()
return () => {
stop()
this.camera = null
}
}
private replan(): void {
if (this.disposed || this.layer === null || this.style === null || this.camera === null) {
return
}
const sight = new CameraSight(this.camera.view(), this.style.floorY, this.style.topY)
const layer = this.layer
const cover = planCover(sight, (tile) => this.stateOf(tile, layer), this.options.coarsestLevel)
this.store.want(cover.wanted.map(addressOf), layer)
this.draw(cover, layer, this.style)
this.reportPending()
}
private stateOf(tile: TerrainTile, layer: Layer): TileState {
if (this.store.has(addressOf(tile), layer)) {
return 'fresh'
}
return this.standIns.has(tileKey(tile)) ? 'standIn' : 'none'
}
private dataOf(tile: TerrainTile, layer: Layer): Tile | null {
const key = tileKey(tile)
const fresh = this.store.get(addressOf(tile), layer)
if (fresh !== null) {
this.standIns.delete(key)
return fresh
}
return this.standIns.get(key) ?? null
}
private draw(cover: Cover, layer: Layer, style: TerrainStyle<Tile>): void {
const deadline = performance.now() + MESH_BUILD_BUDGET_MILLISECONDS
const stillDrawn = new Set<string>()
let behind = false
for (const draw of cover.draws) {
const key = tileKey(draw.tile)
stillDrawn.add(key)
const data = this.dataOf(draw.tile, layer)
if (data === null || this.isCurrent(this.drawn.get(key), data, draw)) {
continue
}
if (performance.now() > deadline) {
behind = true
continue
}
this.show(key, draw, data, style)
}
for (const [key, drawn] of [...this.drawn]) {
if (!stillDrawn.has(key)) {
this.hide(key, drawn)
}
}
this.camera?.redraw()
if (behind) {
this.continueLater()
}
}
private isCurrent(drawn: DrawnMesh<Tile> | undefined, data: Tile, draw: DrawnTile): boolean {
return drawn !== undefined && drawn.data === data && drawn.signature === this.signatureOf(draw)
}
private signatureOf(draw: DrawnTile): string {
const holes = draw.holes.map((hole) => `${hole.fromColumn},${hole.fromRow},${hole.toColumn},${hole.toRow}`).sort()
return `${this.styleVersion}/${holes.join(';')}`
}
private show(key: string, draw: DrawnTile, data: Tile, style: TerrainStyle<Tile>): void {
const previous = this.drawn.get(key)
if (previous !== undefined) {
this.hide(key, previous)
}
const mesh = buildTerrainMesh(style.surfaceOf(data, draw.tile), style.floorY, draw.holes)
this.group.add(mesh.object)
this.drawn.set(key, { tile: draw.tile, data, signature: this.signatureOf(draw), mesh })
}
private hide(key: string, drawn: DrawnMesh<Tile>): void {
this.group.remove(drawn.mesh.object)
drawn.mesh.dispose()
this.drawn.delete(key)
}
private continueLater(): void {
if (this.continuation !== null) {
return
}
this.continuation = setTimeout(() => {
this.continuation = null
this.replan()
}, 0)
}
private reportPending(): void {
const pending = this.store.pending()
if (pending !== this.reportedPending) {
this.reportedPending = pending
this.options.onPending(pending)
}
}
private surfaceTopOver(worldX: number, worldZ: number): number | null {
for (let level = 0; level <= this.options.coarsestLevel; level++) {
const top = this.drawn.get(tileKey(tileContaining(worldX, worldZ, level)))?.mesh.field.surfaceTopOver(worldX, worldZ) ?? null
if (top !== null) {
return top
}
}
return null
}
}
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest'
import { addressOf, ancestorAt, childrenOf, columnsUnder, isInside, originXOf, originZOf, tileBlocks, tileContaining, tileKey } from './terrainTiles'
describe('terrain tiles', () => {
it('lie edge to edge at every level, 128 columns of 2^level blocks across', () => {
expect(tileBlocks(0)).toBe(128)
expect(tileBlocks(3)).toBe(1024)
expect([originXOf({ level: 2, tileX: -1, tileZ: 3 }), originZOf({ level: 2, tileX: -1, tileZ: 3 })]).toEqual([-512, 1536])
})
it('are found by the block they hold, also left and above the origin', () => {
expect(tileContaining(127.9, 128, 0)).toEqual({ level: 0, tileX: 0, tileZ: 1 })
expect(tileContaining(-0.5, -128.5, 0)).toEqual({ level: 0, tileX: -1, tileZ: -2 })
expect(tileContaining(1000, -1000, 3)).toEqual({ level: 3, tileX: 0, tileZ: -1 })
})
it('ask the server for the same blocks a column to a pixel', () => {
expect(addressOf({ level: 3, tileX: -2, tileZ: 5 })).toEqual({ tileX: -2, tileZ: 5, blocksPerPixel: 8 })
})
it('split into the four tiles of the level below that cover them', () => {
const tile = { level: 2, tileX: -1, tileZ: 1 }
const children = childrenOf(tile)
expect(children.map(tileKey)).toEqual(['1/-2/2', '1/-1/2', '1/-2/3', '1/-1/3'])
expect(children.every((child) => ancestorAt(child, 2).tileX === -1 && isInside(child, tile))).toBe(true)
})
it('belong to the coarser tile that holds them, however many levels up', () => {
expect(ancestorAt({ level: 0, tileX: -1, tileZ: 5 }, 3)).toEqual({ level: 3, tileX: -1, tileZ: 0 })
expect(isInside({ level: 1, tileX: 3, tileZ: 3 }, { level: 2, tileX: 1, tileZ: 1 })).toBe(true)
expect(isInside({ level: 1, tileX: 4, tileZ: 3 }, { level: 2, tileX: 1, tileZ: 1 })).toBe(false)
expect(isInside({ level: 2, tileX: 1, tileZ: 1 }, { level: 2, tileX: 1, tileZ: 1 })).toBe(false)
})
it('cover the columns of a coarser tile that line up with them', () => {
const coarse = { level: 2, tileX: 1, tileZ: -1 }
expect(columnsUnder(coarse, { level: 1, tileX: 3, tileZ: -1 })).toEqual({ fromColumn: 64, fromRow: 64, toColumn: 128, toRow: 128 })
expect(columnsUnder(coarse, { level: 1, tileX: 2, tileZ: -2 })).toEqual({ fromColumn: 0, fromRow: 0, toColumn: 64, toRow: 64 })
expect(columnsUnder(coarse, { level: 0, tileX: 7, tileZ: -3 })).toEqual({ fromColumn: 96, fromRow: 32, toColumn: 128, toRow: 64 })
})
it('cover one column of a tile seven levels coarser, and no less', () => {
const coarse = { level: 7, tileX: 0, tileZ: 0 }
expect(columnsUnder(coarse, { level: 0, tileX: 5, tileZ: 9 })).toEqual({ fromColumn: 5, fromRow: 9, toColumn: 6, toRow: 10 })
})
})
@@ -0,0 +1,93 @@
import type { TileAddress } from '../map/viewport'
/** Columns along one side of a terrain tile, at every level. */
export const TILE_COLUMNS = 128
/**
* A square of terrain sampled in one go: {@link TILE_COLUMNS} by {@link TILE_COLUMNS} columns, each 2^level blocks wide.
* Tiles of a level lie edge to edge and each covers exactly four of the level below, so finer tiles can stand in for
* parts of a coarser one.
*/
export interface TerrainTile {
level: number
tileX: number
tileZ: number
}
/** Past this many levels finer, a tile covers less than one column of a coarser one, which cannot be cut a hole. */
export const MOST_LEVELS_FINER = Math.log2(TILE_COLUMNS)
/** Columns of a tile, from the first up to but not including the last. */
export interface ColumnArea {
fromColumn: number
fromRow: number
toColumn: number
toRow: number
}
export function blocksPerColumn(level: number): number {
return 2 ** level
}
export function tileBlocks(level: number): number {
return TILE_COLUMNS * blocksPerColumn(level)
}
export function tileKey(tile: TerrainTile): string {
return `${tile.level}/${tile.tileX}/${tile.tileZ}`
}
export function sameTile(first: TerrainTile, second: TerrainTile): boolean {
return first.level === second.level && first.tileX === second.tileX && first.tileZ === second.tileZ
}
export function originXOf(tile: TerrainTile): number {
return tile.tileX * tileBlocks(tile.level)
}
export function originZOf(tile: TerrainTile): number {
return tile.tileZ * tileBlocks(tile.level)
}
/** The tile of {@code level} that holds the block. */
export function tileContaining(worldX: number, worldZ: number, level: number): TerrainTile {
const blocks = tileBlocks(level)
return { level, tileX: Math.floor(worldX / blocks), tileZ: Math.floor(worldZ / blocks) }
}
/** What to ask the bridge for: tile (x, z) of a layer sampled a column per pixel covers the same blocks. */
export function addressOf(tile: TerrainTile): TileAddress {
return { tileX: tile.tileX, tileZ: tile.tileZ, blocksPerPixel: blocksPerColumn(tile.level) }
}
/** The four tiles of the level below that cover this one. */
export function childrenOf(tile: TerrainTile): TerrainTile[] {
const level = tile.level - 1
const tileX = tile.tileX * 2
const tileZ = tile.tileZ * 2
return [
{ level, tileX, tileZ },
{ level, tileX: tileX + 1, tileZ },
{ level, tileX, tileZ: tileZ + 1 },
{ level, tileX: tileX + 1, tileZ: tileZ + 1 }
]
}
/** The tile of a coarser level that this one lies inside. */
export function ancestorAt(tile: TerrainTile, level: number): TerrainTile {
const levelsUp = level - tile.level
return { level, tileX: tile.tileX >> levelsUp, tileZ: tile.tileZ >> levelsUp }
}
export function isInside(tile: TerrainTile, coarser: TerrainTile): boolean {
return tile.level < coarser.level && sameTile(ancestorAt(tile, coarser.level), coarser)
}
/** The columns of {@code coarser} that the finer tile inside it covers. */
export function columnsUnder(coarser: TerrainTile, finer: TerrainTile): ColumnArea {
const levelsDown = coarser.level - finer.level
const across = TILE_COLUMNS >> levelsDown
const fromColumn = (finer.tileX - coarser.tileX * 2 ** levelsDown) * across
const fromRow = (finer.tileZ - coarser.tileZ * 2 ** levelsDown) * across
return { fromColumn, fromRow, toColumn: fromColumn + across, toRow: fromRow + across }
}
+21 -41
View File
@@ -9,19 +9,21 @@ import type { BridgeClient } from '../bridge/BridgeClient'
import type { NoiseSource, NoiseTile } from '../bridge/types'
import type { TiledFraming as TerrainFraming } from '../map/TiledView'
import { NOISE_PALETTES, noiseScale, type NoisePaletteId, type NoiseScale } from '../noise/noiseScale'
import { NoiseTerrain, type NoiseArea } from '../noise/noiseTerrain'
import { createNoiseView, NOISE_TILE_PIXELS, type NoiseStatus, type NoiseView } from '../noise/noiseTiles'
import { buildTerrainMesh } from '../scene/terrainMesh'
import { NoiseTerrain } from '../noise/noiseTerrain'
import { createNoiseView, noiseTileSource, type NoiseLayer, type NoiseStatus, type NoiseView } from '../noise/noiseTiles'
import { focusAround, type TerrainStyle } from '../scene/terrainStream'
import { hexColor } from './colors'
import { SceneViewport } from './SceneViewport'
import { TiledCanvas } from './TiledCanvas'
import { useTerrainStream } from './useTerrainStream'
type NoiseDisplay = 'flat' | 'terrain'
const NUMBER = new Intl.NumberFormat('en-US', { maximumFractionDigits: 3 })
const DEFAULT_SEED = '12345'
const TERRAIN_TILES_PER_SIDE = 4
const TERRAIN_BLOCKS_PER_VALUE = 1
// Noise tiles are asked for down to 4096 blocks a value, which is level 12.
const COARSEST_NOISE_LEVEL = 12
const LOWEST_FOCUS_BLOCKS = -32
const LOWEST_RELIEF_BLOCKS = 1
const TALLEST_RELIEF_BLOCKS = 4064
const DEFAULT_RELIEF_BLOCKS = 64
@@ -288,48 +290,26 @@ function NoiseTerrainView({
reliefBlocks: number
tell(message: string): void
}): React.JSX.Element {
const area = useNoiseArea(client, source.id, seed, revision, framing, tell)
const mesh = useMemo(() => (area === null ? null : buildTerrainMesh(new NoiseTerrain(area, source, scale, reliefBlocks))), [area, source, scale, reliefBlocks])
useEffect(() => () => mesh?.dispose(), [mesh])
const tileSource = useMemo(() => noiseTileSource(client), [client])
const focus = useMemo(() => focusAround(framing.centerX, framing.centerZ, LOWEST_FOCUS_BLOCKS, DEFAULT_RELIEF_BLOCKS), [framing])
const layer = useMemo<NoiseLayer>(() => ({ sourceId: source.id, seed, revision }), [source.id, seed, revision])
const style = useMemo<TerrainStyle<NoiseTile>>(
() => ({
surfaceOf: (tile, place) => new NoiseTerrain(tile, place, source, scale, reliefBlocks),
floorY: source.blockRange?.lowest ?? 0,
topY: source.blockRange?.highest ?? reliefBlocks
}),
[source, scale, reliefBlocks]
)
const { content, pending } = useTerrainStream(tileSource, COARSEST_NOISE_LEVEL, focus, layer, style, tell)
return (
<div className="absolute inset-0">
<SceneViewport content={mesh?.content ?? null} framing={area} />
{area === null && <div className={cn(PILL, 'top-3 left-1/2 -translate-x-1/2')}>Sampling {source.name}</div>}
<SceneViewport content={content} framing={content} />
{pending > 0 && <div className={cn(PILL, 'top-3 left-1/2 -translate-x-1/2')}>Sampling {source.name}</div>}
</div>
)
}
/** The square of tiles around where the 2D view looked, one block a value; every tile arrives before it is shown. */
function useNoiseArea(
client: BridgeClient,
sourceId: string,
seed: string,
revision: number,
framing: TerrainFraming,
tell: (message: string) => void
): NoiseArea | null {
const [area, setArea] = useState<NoiseArea | null>(null)
useEffect(() => {
const stop = new AbortController()
const tileBlocks = NOISE_TILE_PIXELS * TERRAIN_BLOCKS_PER_VALUE
const firstTileX = Math.floor(framing.centerX / tileBlocks - TERRAIN_TILES_PER_SIDE / 2)
const firstTileZ = Math.floor(framing.centerZ / tileBlocks - TERRAIN_TILES_PER_SIDE / 2)
const rows = Array.from({ length: TERRAIN_TILES_PER_SIDE }, (_, row) =>
Promise.all(
Array.from({ length: TERRAIN_TILES_PER_SIDE }, (_, column) =>
client.noiseTile(sourceId, seed, firstTileX + column, firstTileZ + row, TERRAIN_BLOCKS_PER_VALUE, NOISE_TILE_PIXELS, stop.signal)
)
)
)
setArea(null)
Promise.all(rows)
.then((tiles: NoiseTile[][]) => setArea({ tiles, originX: firstTileX * tileBlocks, originZ: firstTileZ * tileBlocks }))
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
return () => stop.abort()
}, [client, sourceId, seed, revision, framing, tell])
return area
}
function useNoiseSources(client: BridgeClient, packRevision: number, tell: (message: string) => void): NoiseSource[] {
const [sources, setSources] = useState<NoiseSource[]>([])
useEffect(() => {
@@ -5,20 +5,19 @@ import { ScrollArea } from '@/components/ui/scroll-area'
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
import { cn } from '@/lib/utils'
import { BridgeError, STATUS_NOT_FOUND, type BridgeClient } from '../bridge/BridgeClient'
import type { SavedStart, SavedTile, SavedWorldInfo, WorldInfo } from '../bridge/types'
import type { SavedStart, SavedWorldInfo, WorldInfo } from '../bridge/types'
import { BlockColors } from '../scene/blockColors'
import { BlockModels } from '../scene/blockModels'
import { BridgeAssets } from '../scene/BridgeAssets'
import { SavedTerrain, type SavedTerrainArea, type SavedTerrainColoring } from '../scene/savedTerrain'
import { buildTerrainMesh } from '../scene/terrainMesh'
import { SavedTerrain, type ReadSavedTile, type SavedTerrainColoring } from '../scene/savedTerrain'
import { savedTileSource, type SavedLayer } from '../scene/savedTileSource'
import { focusAround, type TerrainStyle } from '../scene/terrainStream'
import { SceneViewport } from './SceneViewport'
import { useTerrainStream } from './useTerrainStream'
const NUMBER = new Intl.NumberFormat('en-US')
const TILES_PER_SIDE = 4
const TILE_PIXELS = 128
const BLOCKS_PER_PIXEL = 1
const TILE_BLOCKS = TILE_PIXELS * BLOCKS_PER_PIXEL
const NO_COLORS = new Map<string, number>()
// Saved tiles are read at up to 16 blocks a pixel, which is level 4.
const COARSEST_SAVED_LEVEL = 4
const COLORING_ITEM = 'h-7 px-3 text-[12px] data-[state=on]:bg-selection data-[state=on]:text-foreground'
const PILL = 'pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 rounded-md border border-overlay-border bg-card/90 px-3 py-1.5 text-[12px] text-secondary-text'
@@ -37,30 +36,42 @@ export function SavedWorldStudio({ client, world, onSummary, tell }: SavedWorldS
const chosen = worlds.find((candidate) => candidate.id === chosenId) ?? ownWorldAmong(worlds, world) ?? worlds[0] ?? null
const [coloring, setColoring] = useState<SavedTerrainColoring>('biomes')
const [readings, setReadings] = useState(0)
const { start, area, reading } = useSavedArea(client, chosen?.id ?? null, readings, tell)
const blockColors = useBlockColors(client, coloring === 'blocks' ? area : null)
const mesh = useMemo(() => {
if (area === null || start === null || (coloring === 'blocks' && blockColors === null)) {
return null
}
return buildTerrainMesh(new SavedTerrain(area, coloring, start.seaLevel, blockColors ?? NO_COLORS))
}, [area, start, coloring, blockColors])
const { start, looking } = useSavedStart(client, chosen?.id ?? null, readings, tell)
const tileSource = useMemo(() => {
const images = new BridgeAssets(client, () => {})
return savedTileSource(client, new BlockColors(new BlockModels(images), images))
}, [client])
const centerX = start?.centerX ?? 0
const centerZ = start?.centerZ ?? 0
const lowestGround = start?.lowestGround ?? 0
const highestGround = start?.highestGround ?? 0
const focus = useMemo(() => focusAround(centerX, centerZ, lowestGround, highestGround), [centerX, centerZ, lowestGround, highestGround])
const layer = useMemo<SavedLayer | null>(() => (start === null || chosen === null ? null : { worldId: chosen.id, readings }), [start, chosen, readings])
const seaLevel = start?.seaLevel ?? null
const minY = start?.minY ?? null
const style = useMemo<TerrainStyle<ReadSavedTile> | null>(
() =>
minY === null
? null
: { surfaceOf: (read, place) => new SavedTerrain(read, place, coloring, seaLevel), floorY: minY, topY: minY + world.height },
[minY, seaLevel, coloring, world.height]
)
const { content, pending } = useTerrainStream(tileSource, COARSEST_SAVED_LEVEL, focus, layer, style, tell)
const reading = looking || pending > 0
useEffect(() => () => mesh?.dispose(), [mesh])
useEffect(() => {
if (chosen === null || start === null) {
onSummary(null)
return
}
const side = NUMBER.format(TILES_PER_SIDE * TILE_BLOCKS)
onSummary(`${chosen.name} · ${side} × ${side} blocks around ${NUMBER.format(start.centerX)}, ${NUMBER.format(start.centerZ)}`)
onSummary(`${chosen.name} · around ${NUMBER.format(start.centerX)}, ${NUMBER.format(start.centerZ)}`)
}, [chosen, start, onSummary])
useEffect(() => () => onSummary(null), [onSummary])
return (
<>
<div className="relative min-w-0 flex-1">
<SceneViewport content={mesh?.content ?? null} framing={area} />
<SceneViewport content={content} framing={content} />
<div className="absolute top-3 left-3 flex items-center gap-2">
<ToggleGroup
type="single"
@@ -146,78 +157,35 @@ function useSavedWorlds(client: BridgeClient, tell: (message: string) => void):
return worlds
}
/** Where the chosen world's view opens and the square of tiles around it; every tile arrives before it is shown. */
function useSavedArea(
client: BridgeClient,
worldId: string | null,
readings: number,
tell: (message: string) => void
): { start: SavedStart | null; area: SavedTerrainArea | null; reading: boolean } {
/**
* Where the chosen world's view opens, null while it is looked up and where nothing finished is saved. Reading again
* keeps the old start until the new one arrives, so the ground drawn stays.
*/
function useSavedStart(client: BridgeClient, worldId: string | null, readings: number, tell: (message: string) => void): { start: SavedStart | null; looking: boolean } {
const [start, setStart] = useState<SavedStart | null>(null)
const [area, setArea] = useState<SavedTerrainArea | null>(null)
const [reading, setReading] = useState(false)
const [looking, setLooking] = useState(false)
useEffect(() => setStart(null), [worldId])
useEffect(() => {
if (worldId === null) {
return
}
const stop = new AbortController()
setReading(true)
setStart(null)
setArea(null)
readSavedArea(client, worldId, stop.signal)
.then((found) => {
setStart(found?.start ?? null)
setArea(found?.area ?? null)
setLooking(true)
client
.savedStart(worldId, stop.signal)
.then(setStart)
.catch((failure: unknown) => {
if (stop.signal.aborted) {
return
}
if (failure instanceof BridgeError && failure.status === STATUS_NOT_FOUND) {
setStart(null)
return
}
tell(failure instanceof Error ? failure.message : 'The server did not answer')
})
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
.finally(() => !stop.signal.aborted && setReading(false))
.finally(() => !stop.signal.aborted && setLooking(false))
return () => stop.abort()
}, [client, worldId, readings, tell])
return { start, area, reading }
}
async function readSavedArea(client: BridgeClient, worldId: string, signal: AbortSignal): Promise<{ start: SavedStart; area: SavedTerrainArea } | null> {
let start: SavedStart
try {
start = await client.savedStart(worldId, signal)
} catch (failure) {
if (failure instanceof BridgeError && failure.status === STATUS_NOT_FOUND) {
return null
}
throw failure
}
const firstTileX = Math.floor(start.centerX / TILE_BLOCKS - TILES_PER_SIDE / 2)
const firstTileZ = Math.floor(start.centerZ / TILE_BLOCKS - TILES_PER_SIDE / 2)
const tiles: SavedTile[][] = await Promise.all(
Array.from({ length: TILES_PER_SIDE }, (_, row) =>
Promise.all(
Array.from({ length: TILES_PER_SIDE }, (_, column) =>
client.savedTile(worldId, firstTileX + column, firstTileZ + row, BLOCKS_PER_PIXEL, TILE_PIXELS, signal)
)
)
)
)
return { start, area: { tiles, originX: firstTileX * TILE_BLOCKS, originZ: firstTileZ * TILE_BLOCKS } }
}
/** The colour of every block in the area, read from the client's textures, or null until they are read. */
function useBlockColors(client: BridgeClient, area: SavedTerrainArea | null): Map<string, number> | null {
const colors = useMemo(() => {
const images = new BridgeAssets(client, () => {})
return new BlockColors(new BlockModels(images), images)
}, [client])
const [read, setRead] = useState<Map<string, number> | null>(null)
useEffect(() => {
setRead(null)
if (area === null) {
return
}
let active = true
const blocks = area.tiles.flat().flatMap((tile) => tile.blockNames)
colors.colorsOf(blocks).then((found) => active && setRead(found))
return () => {
active = false
}
}, [colors, area])
return read
return { start, looking }
}
@@ -1,6 +1,7 @@
import { useEffect, useRef } from 'react'
import { Box3, MOUSE, PerspectiveCamera, Ray, Scene, Sphere, Vector3, WebGLRenderer, type Object3D } from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
import type { SightView } from '../scene/cameraSight'
import { surfaceAlong } from '../scene/surfacePick'
const FIELD_OF_VIEW_DEGREES = 45
@@ -10,13 +11,27 @@ const FRAMING_MARGIN = 1.15
const NEAREST_CLIP = 0.05
// The near plane follows the orbit distance: a fixed tiny one leaves too little depth precision far away, so surfaces a block apart flicker.
const NEAR_CLIP_PER_ORBIT_DISTANCE = 0.01
// The far plane keeps up with zooming out, so ground reaching to the horizon stays in view.
const FAR_CLIP_PER_ORBIT_DISTANCE = 20
/** The camera of a viewport, for content that draws only what the camera looks at. */
export interface CameraLink {
/** Where the camera is and how it looks now. */
view(): SightView
/** Tells the listener whenever the camera moves or the viewport changes size; returns how to stop. */
onMoved(listener: () => void): () => void
/** Draws the viewport again, after the content changed by itself. */
redraw(): void
}
/** What a viewport shows: one object, and the box the camera frames when it is first shown. */
export interface ViewportContent {
object: Object3D
bounds: Box3
/** Where a ray first meets what is drawn, or null; without it the viewport casts the ray at the object's meshes. */
surfaceAlong?(ray: Ray): Vector3 | null
/** Where a ray first meets what is drawn within {@code reach}, or null; without it the viewport casts the ray at the object's meshes. */
surfaceAlong?(ray: Ray, reach: number): Vector3 | null
/** Called when the content is shown, so it can follow the camera; returns how to stop following when it goes. */
follow?(camera: CameraLink): () => void
}
interface SceneViewportProps {
@@ -52,8 +67,11 @@ class Stage {
private readonly scene = new Scene()
private readonly controls: OrbitControls
private readonly resizes: ResizeObserver
private readonly moveListeners = new Set<() => void>()
private shown: ViewportContent | null = null
private stopFollowing: (() => void) | null = null
private framed = false
private framedFar = this.camera.far
private frameRequested = false
constructor(private readonly host: HTMLDivElement) {
@@ -66,7 +84,8 @@ class Stage {
this.controls.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.PAN, RIGHT: MOUSE.PAN }
this.renderer.domElement.addEventListener('pointerdown', (event) => this.pivotOnSurfaceInMiddle(event))
this.controls.addEventListener('change', () => {
this.fitNearClipToOrbit()
this.fitClipToOrbit()
this.notifyMoved()
this.requestFrame()
})
this.resizes = new ResizeObserver(() => this.fitToHost())
@@ -75,19 +94,46 @@ class Stage {
}
show(content: ViewportContent | null): void {
if (this.shown !== null) {
this.scene.remove(this.shown.object)
}
this.removeShown()
this.shown = content
if (content !== null) {
this.scene.add(content.object)
if (!this.framed) {
this.frameShown()
}
this.stopFollowing = content.follow?.(this.cameraLink()) ?? null
}
this.requestFrame()
}
private removeShown(): void {
this.stopFollowing?.()
this.stopFollowing = null
if (this.shown !== null) {
this.scene.remove(this.shown.object)
}
}
private cameraLink(): CameraLink {
return {
view: () => ({
camera: this.camera,
width: this.host.clientWidth,
height: this.host.clientHeight,
orbitDistance: this.camera.position.distanceTo(this.controls.target)
}),
onMoved: (listener) => {
this.moveListeners.add(listener)
return () => this.moveListeners.delete(listener)
},
redraw: () => this.requestFrame()
}
}
private notifyMoved(): void {
this.moveListeners.forEach((listener) => listener())
}
frameShown(): void {
if (this.shown === null) {
this.framed = false
@@ -101,9 +147,10 @@ class Stage {
const distance = (sphere.radius * FRAMING_MARGIN) / Math.sin(Math.min(halfVertical, halfHorizontal))
this.controls.target.copy(sphere.center)
this.camera.position.copy(sphere.center).addScaledVector(VIEW_DIRECTION, distance)
this.camera.far = distance * 10 + sphere.radius * 4
this.framedFar = distance * 10 + sphere.radius * 4
this.controls.update()
this.fitNearClipToOrbit()
this.fitClipToOrbit()
this.notifyMoved()
this.requestFrame()
}
@@ -119,19 +166,20 @@ class Stage {
return
}
this.controls.target.copy(hit)
this.fitNearClipToOrbit()
this.fitClipToOrbit()
this.notifyMoved()
this.requestFrame()
}
private fitNearClipToOrbit(): void {
this.camera.near = Math.max(NEAREST_CLIP, this.camera.position.distanceTo(this.controls.target) * NEAR_CLIP_PER_ORBIT_DISTANCE)
private fitClipToOrbit(): void {
const orbitDistance = this.camera.position.distanceTo(this.controls.target)
this.camera.near = Math.max(NEAREST_CLIP, orbitDistance * NEAR_CLIP_PER_ORBIT_DISTANCE)
this.camera.far = Math.max(this.framedFar, orbitDistance * FAR_CLIP_PER_ORBIT_DISTANCE)
this.camera.updateProjectionMatrix()
}
dispose(): void {
if (this.shown !== null) {
this.scene.remove(this.shown.object)
}
this.removeShown()
this.resizes.disconnect()
this.controls.dispose()
this.renderer.dispose()
@@ -144,6 +192,7 @@ class Stage {
this.renderer.setSize(width, height)
this.camera.aspect = width / height
this.camera.updateProjectionMatrix()
this.notifyMoved()
this.requestFrame()
}
@@ -2,44 +2,58 @@ import { useEffect, useMemo, useState } from 'react'
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
import type { BridgeClient, WorldRect } from '../bridge/BridgeClient'
import type { MapTile, WorldInfo } from '../bridge/types'
import { MapTerrain, type MapTerrainArea, type MapTerrainColoring } from '../scene/mapTerrain'
import { buildTerrainMesh } from '../scene/terrainMesh'
import { mapTileSource, type TileLayer } from '../map/mapTileSource'
import { MapTerrain, type MapTerrainColoring } from '../scene/mapTerrain'
import { focusAround, type TerrainStyle } from '../scene/terrainStream'
import { TILE_COLUMNS } from '../scene/terrainTiles'
import { SceneViewport } from './SceneViewport'
import { useTerrainStream } from './useTerrainStream'
const NUMBER = new Intl.NumberFormat('en-US')
const TILES_PER_SIDE = 4
const TILE_PIXELS = 128
const BLOCKS_PER_PIXEL = 1
const TILE_BLOCKS = TILE_PIXELS * BLOCKS_PER_PIXEL
// The map's coarsest tiles are 4096 blocks a pixel, which is level 12.
const COARSEST_LEVEL = 12
const BLOCKS_ABOVE_FLUID_IN_FOCUS = 96
const BLOCKS_BELOW_FLUID_IN_FOCUS = 32
const COLORING_ITEM = 'h-7 px-3 text-[12px] data-[state=on]:bg-selection data-[state=on]:text-foreground'
interface WorldStudio3DProps {
client: BridgeClient
world: WorldInfo
/** Where the map last looked; the terrain is the square around its middle, or around the world's centre. */
/** Where the map last looked; the terrain opens around its middle, or around the world's centre. */
mapArea: WorldRect | null
packRevision: number
onSummary(summary: string | null): void
tell(message: string): void
}
/** The terrain around where the map looked, in 3D, coloured by biome, region or height (v3e's 3D world view). */
/** The terrain around where the map looked, in 3D and without an edge, coloured by biome, region or height (v3e's 3D world view). */
export function WorldStudio3D({ client, world, mapArea, packRevision, onSummary, tell }: WorldStudio3DProps): React.JSX.Element {
const [coloring, setColoring] = useState<MapTerrainColoring>('biomes')
const centre = useMemo(() => centreOf(mapArea), [mapArea])
const area = useTerrainArea(client, centre, packRevision, tell)
const mesh = useMemo(() => (area === null ? null : buildTerrainMesh(new MapTerrain(area, coloring, world.fluidHeight))), [area, coloring, world.fluidHeight])
const source = useMemo(() => mapTileSource(client, TILE_COLUMNS), [client])
const focus = useMemo(
() => focusAround(centre.x, centre.z, world.fluidHeight - BLOCKS_BELOW_FLUID_IN_FOCUS, world.fluidHeight + BLOCKS_ABOVE_FLUID_IN_FOCUS),
[centre, world.fluidHeight]
)
const layer = useMemo<TileLayer>(() => ({ view: 'biomes', preview: null, heights: true, pickNoise: false, revision: packRevision }), [packRevision])
const style = useMemo<TerrainStyle<MapTile>>(
() => ({
surfaceOf: (tile, place) => new MapTerrain(tile, place, coloring, world.fluidHeight),
floorY: world.minY,
topY: world.minY + world.height
}),
[coloring, world.fluidHeight, world.minY, world.height]
)
const { content, pending } = useTerrainStream(source, COARSEST_LEVEL, focus, layer, style, tell)
useEffect(() => () => mesh?.dispose(), [mesh])
useEffect(() => {
const side = NUMBER.format(TILES_PER_SIDE * TILE_BLOCKS)
onSummary(`${side} × ${side} blocks around ${NUMBER.format(centre.x)}, ${NUMBER.format(centre.z)}`)
onSummary(`Around ${NUMBER.format(centre.x)}, ${NUMBER.format(centre.z)}`)
return () => onSummary(null)
}, [centre, onSummary])
return (
<div className="relative min-w-0 flex-1">
<SceneViewport content={mesh?.content ?? null} framing={area} />
<SceneViewport content={content} framing={content} />
<ToggleGroup
type="single"
variant="outline"
@@ -58,7 +72,7 @@ export function WorldStudio3D({ client, world, mapArea, packRevision, onSummary,
Height
</ToggleGroupItem>
</ToggleGroup>
{area === null && (
{pending > 0 && (
<div className="pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 rounded-md border border-overlay-border bg-card/90 px-3 py-1.5 text-[12px] text-secondary-text">
Sampling the terrain
</div>
@@ -73,38 +87,3 @@ function centreOf(area: WorldRect | null): { x: number; z: number } {
}
return { x: Math.round((area.minX + area.maxX) / 2), z: Math.round((area.minZ + area.maxZ) / 2) }
}
/** The tiles of the square around {@code centre}, with heights; every tile arrives before the square is shown. */
function useTerrainArea(client: BridgeClient, centre: { x: number; z: number }, packRevision: number, tell: (message: string) => void): MapTerrainArea | null {
const [area, setArea] = useState<MapTerrainArea | null>(null)
useEffect(() => {
const stop = new AbortController()
const firstTileX = Math.floor(centre.x / TILE_BLOCKS - TILES_PER_SIDE / 2)
const firstTileZ = Math.floor(centre.z / TILE_BLOCKS - TILES_PER_SIDE / 2)
const rows = Array.from({ length: TILES_PER_SIDE }, (_, row) =>
Promise.all(
Array.from({ length: TILES_PER_SIDE }, (_, column) =>
client.tile(
{
view: 'biomes',
preview: null,
tileX: firstTileX + column,
tileZ: firstTileZ + row,
blocksPerPixel: BLOCKS_PER_PIXEL,
size: TILE_PIXELS,
heights: true,
pickNoise: false
},
stop.signal
)
)
)
)
setArea(null)
Promise.all(rows)
.then((tiles: MapTile[][]) => setArea({ tiles, originX: firstTileX * TILE_BLOCKS, originZ: firstTileZ * TILE_BLOCKS }))
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
return () => stop.abort()
}, [client, centre, packRevision, tell])
return area
}
@@ -0,0 +1,46 @@
import { useEffect, useRef, useState } from 'react'
import type { Box3 } from 'three'
import type { TileSource } from '../map/TileStore'
import { TerrainStream, type TerrainStyle } from '../scene/terrainStream'
import type { ViewportContent } from './SceneViewport'
/**
* Endless terrain around {@code focus} for a viewport: the tiles of {@code layer} drawn in {@code style}, where the
* camera looks. A new layer keeps the ground drawn until its tiles arrive; a new source or focus starts again.
*
* @return what to show, or null before there is any, and how many tiles are still on their way
*/
export function useTerrainStream<Tile, Layer>(
source: TileSource<Tile, Layer, never>,
coarsestLevel: number,
focus: Box3,
layer: Layer | null,
style: TerrainStyle<Tile> | null,
tell: (message: string) => void
): { content: ViewportContent | null; pending: number } {
const [stream, setStream] = useState<TerrainStream<Tile, Layer> | null>(null)
const [pending, setPending] = useState(0)
const latestTell = useRef(tell)
latestTell.current = tell
useEffect(() => {
const created = new TerrainStream({ source, coarsestLevel, focus, onPending: setPending, onError: (message) => latestTell.current(message) })
setStream(created)
return () => {
created.dispose()
setStream(null)
}
}, [source, coarsestLevel, focus])
useEffect(() => {
if (layer !== null) {
stream?.showLayer(layer)
}
}, [stream, layer])
useEffect(() => {
if (style !== null) {
stream?.restyle(style)
}
}, [stream, style])
return { content: stream?.content ?? null, pending }
}