mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 00:04:42 +00:00
Add the 3D world view
The terrain around where the map last looked, 1,024 blocks square, in 3D: one vertex per map pixel from the biome tiles with heights, coloured by biome, region or height, lit by slope. Walls round the rim and a see-through sea at fluid height make the square read as a solid block. The viewport now takes content with its own bounds and frames again when told to, so the scene views and the 3D world share it. The near clip follows the orbit distance, so surfaces a block apart no longer flicker when the camera is far away.
This commit is contained in:
1 parent
0732f5a9b8
commit
874cb4fe16
7 files changed
+406
-48
No files matched your search
@@ -1,16 +1,20 @@
|
||||
import { BufferAttribute, BufferGeometry } from 'three'
|
||||
import { Box3, BufferAttribute, BufferGeometry, Mesh, MeshBasicMaterial } from 'three'
|
||||
import type { ViewportContent } from '../studio/SceneViewport'
|
||||
import { cubeModel, parseState, type BlockModels, type BlockModel, type Direction, type Quad } from './blockModels'
|
||||
import { blockTint } from './blockTints'
|
||||
import { INTS_PER_BLOCK, type BlockScene } from './sceneDecoding'
|
||||
import { TextureAtlas, type ImageSource } from './textureAtlas'
|
||||
|
||||
export interface SceneMesh {
|
||||
geometry: BufferGeometry
|
||||
atlas: TextureAtlas
|
||||
content: ViewportContent
|
||||
/** Block states the client has no blockstate file for, drawn as magenta and black cubes. */
|
||||
unknownStates: string[]
|
||||
/** Frees the mesh's geometry, material and atlas. */
|
||||
dispose(): void
|
||||
}
|
||||
|
||||
const CUTOUT_ALPHA = 0.1
|
||||
|
||||
/** The light Minecraft gives each side of a block without shadows: the top brightest, the bottom darkest. */
|
||||
const FACE_LIGHT: Record<Direction, number> = { up: 1, down: 0.5, north: 0.8, south: 0.8, west: 0.6, east: 0.6 }
|
||||
const MISSING_TEXTURE = 'iris:missing'
|
||||
@@ -47,7 +51,18 @@ export async function buildSceneMesh(scene: BlockScene, models: BlockModels, ima
|
||||
const solid = model.fullCube && model.quads.every((quad) => atlas.cell(quad.texture).solid)
|
||||
return { model, name: state.name, properties: state.properties, solid }
|
||||
})
|
||||
return { geometry: geometryOf(scene, palette, atlas), atlas, unknownStates }
|
||||
const geometry = geometryOf(scene, palette, atlas)
|
||||
const material = new MeshBasicMaterial({ map: atlas.texture, vertexColors: true, alphaTest: CUTOUT_ALPHA })
|
||||
const bounds = new Box3().setFromBufferAttribute(geometry.getAttribute('position') as BufferAttribute)
|
||||
return {
|
||||
content: { object: new Mesh(geometry, material), bounds },
|
||||
unknownStates,
|
||||
dispose: () => {
|
||||
geometry.dispose()
|
||||
material.dispose()
|
||||
atlas.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The client draws chests, signs, water and the like without a block model; their break texture stands in for them.
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Group, Mesh, MeshBasicMaterial, PlaneGeometry, Vector3 } from 'three'
|
||||
import { NO_LABEL, type MapTile } from '../bridge/types'
|
||||
import { heightColor } from '../map/heightColors'
|
||||
import type { ViewportContent } from '../studio/SceneViewport'
|
||||
|
||||
export type TerrainColoring = 'biomes' | 'regions' | 'height'
|
||||
|
||||
/** A square of map tiles with heights, row by row from the north west. */
|
||||
export interface TerrainArea {
|
||||
tiles: MapTile[][]
|
||||
/** The world spot of the first tile's first pixel. */
|
||||
originX: number
|
||||
originZ: number
|
||||
}
|
||||
|
||||
export interface TerrainMesh {
|
||||
content: ViewportContent
|
||||
dispose(): void
|
||||
}
|
||||
|
||||
const WATER_COLOR = 0x3f76e4
|
||||
const WATER_OPACITY = 0.55
|
||||
const UNLABELLED_COLOR = 0x5a5f6b
|
||||
// Light from high in the south west, so slopes read as relief; the darkest side keeps some light.
|
||||
const LIGHT = new Vector3(-0.6, 1, 0.4).normalize()
|
||||
const AMBIENT_LIGHT = 0.5
|
||||
const WALL_DEPTH_BLOCKS = 8
|
||||
const WALL_TOP_LIGHT = 0.55
|
||||
const WALL_BASE_LIGHT = 0.25
|
||||
const SEA_INSET_BLOCKS = 0.05
|
||||
|
||||
/** The terrain of the area, one vertex per map pixel, with the dimension's sea as a sheet of water at fluid height. */
|
||||
export function buildTerrainMesh(area: TerrainArea, coloring: TerrainColoring, fluidHeight: number): TerrainMesh {
|
||||
const grid = TerrainGrid.of(area)
|
||||
const terrain = terrainGeometry(grid, coloring, fluidHeight)
|
||||
const base = Math.min(grid.lowestHeight(), fluidHeight) - WALL_DEPTH_BLOCKS
|
||||
const landWalls = rimWall(grid, terrain, (ground) => ground, () => base)
|
||||
const seaWalls = rimWall(grid, terrain, () => fluidHeight, (ground) => Math.min(ground, fluidHeight))
|
||||
const terrainMaterial = new MeshBasicMaterial({ vertexColors: true, side: DoubleSide })
|
||||
const sea = seaSurface(grid, fluidHeight)
|
||||
const waterMaterial = new MeshBasicMaterial({ color: WATER_COLOR, transparent: true, opacity: WATER_OPACITY, depthWrite: false, side: DoubleSide })
|
||||
const group = new Group()
|
||||
group.add(new Mesh(terrain, terrainMaterial), new Mesh(landWalls, terrainMaterial), new Mesh(sea, waterMaterial), new Mesh(seaWalls, waterMaterial))
|
||||
const geometries = [terrain, landWalls, sea, seaWalls]
|
||||
return {
|
||||
content: { object: group, bounds: new Box3().setFromObject(group) },
|
||||
dispose: () => {
|
||||
geometries.forEach((geometry) => geometry.dispose())
|
||||
terrainMaterial.dispose()
|
||||
waterMaterial.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Kept a little inside the walls, so its edge does not flicker against them.
|
||||
function seaSurface(grid: TerrainGrid, fluidHeight: number): BufferGeometry {
|
||||
const sea = new PlaneGeometry(grid.spanX - 2 * SEA_INSET_BLOCKS, grid.spanZ - 2 * SEA_INSET_BLOCKS).rotateX(-Math.PI / 2)
|
||||
return sea.translate(grid.worldX(0) + grid.spanX / 2, fluidHeight, grid.worldZ(0) + grid.spanZ / 2)
|
||||
}
|
||||
|
||||
/**
|
||||
* A wall round the terrain's rim, from {@code topAt} down to {@code bottomAt} of the ground height at each rim vertex;
|
||||
* in the terrain's colour, darkening downwards, for a material that uses vertex colours.
|
||||
*/
|
||||
function rimWall(grid: TerrainGrid, terrain: BufferGeometry, topAt: (ground: number) => number, bottomAt: (ground: number) => number): BufferGeometry {
|
||||
const rim = grid.rimVertices()
|
||||
const surface = terrain.getAttribute('position')
|
||||
const shade = terrain.getAttribute('color')
|
||||
const positions = new Float32Array(rim.length * 2 * 3)
|
||||
const colors = new Float32Array(rim.length * 2 * 3)
|
||||
rim.forEach((vertex, index) => {
|
||||
const [x, ground, z] = [surface.getX(vertex), surface.getY(vertex), surface.getZ(vertex)]
|
||||
positions.set([x, topAt(ground), z, x, bottomAt(ground), z], index * 6)
|
||||
const [red, green, blue] = [shade.getX(vertex), shade.getY(vertex), shade.getZ(vertex)]
|
||||
colors.set([red * WALL_TOP_LIGHT, green * WALL_TOP_LIGHT, blue * WALL_TOP_LIGHT], index * 6)
|
||||
colors.set([red * WALL_BASE_LIGHT, green * WALL_BASE_LIGHT, blue * WALL_BASE_LIGHT], index * 6 + 3)
|
||||
})
|
||||
const indices: number[] = []
|
||||
for (let index = 0; index < rim.length; index++) {
|
||||
const next = (index + 1) % rim.length
|
||||
const [upper, lower, nextUpper, nextLower] = [index * 2, index * 2 + 1, next * 2, next * 2 + 1]
|
||||
indices.push(upper, lower, nextUpper, nextUpper, lower, nextLower)
|
||||
}
|
||||
const geometry = new BufferGeometry()
|
||||
geometry.setAttribute('position', new BufferAttribute(positions, 3))
|
||||
geometry.setAttribute('color', new BufferAttribute(colors, 3))
|
||||
geometry.setIndex(indices)
|
||||
return geometry
|
||||
}
|
||||
|
||||
function terrainGeometry(grid: TerrainGrid, coloring: TerrainColoring, fluidHeight: number): BufferGeometry {
|
||||
const { columns, rows } = grid
|
||||
const positions = new Float32Array(columns * rows * 3)
|
||||
const colors = new Float32Array(columns * rows * 3)
|
||||
for (let row = 0; row < rows; row++) {
|
||||
for (let column = 0; column < columns; column++) {
|
||||
const vertex = row * columns + column
|
||||
const height = grid.height(column, row)
|
||||
positions.set([grid.worldX(column), height, grid.worldZ(row)], vertex * 3)
|
||||
const color = coloring === 'height' ? heightColor(height, fluidHeight) : grid.labelColor(column, row, coloring)
|
||||
const light = AMBIENT_LIGHT + (1 - AMBIENT_LIGHT) * Math.max(0, grid.normal(column, row).dot(LIGHT))
|
||||
colors.set([(((color >> 16) & 0xff) / 255) * light, (((color >> 8) & 0xff) / 255) * light, ((color & 0xff) / 255) * light], vertex * 3)
|
||||
}
|
||||
}
|
||||
const indices = new Uint32Array((columns - 1) * (rows - 1) * 6)
|
||||
let next = 0
|
||||
for (let row = 0; row < rows - 1; row++) {
|
||||
for (let column = 0; column < columns - 1; column++) {
|
||||
const northWest = row * columns + column
|
||||
const southWest = northWest + columns
|
||||
indices.set([northWest, southWest, northWest + 1, northWest + 1, southWest, southWest + 1], next)
|
||||
next += 6
|
||||
}
|
||||
}
|
||||
const geometry = new BufferGeometry()
|
||||
geometry.setAttribute('position', new BufferAttribute(positions, 3))
|
||||
geometry.setAttribute('color', new BufferAttribute(colors, 3))
|
||||
geometry.setIndex(new BufferAttribute(indices, 1))
|
||||
return geometry
|
||||
}
|
||||
|
||||
/** The area's tiles as one grid of pixels, without the ring each tile carries for its neighbours. */
|
||||
class TerrainGrid {
|
||||
readonly columns: number
|
||||
readonly rows: number
|
||||
/** How far the vertices reach, west to east and north to south, in blocks. */
|
||||
readonly spanX: number
|
||||
readonly spanZ: number
|
||||
private readonly size: number
|
||||
private readonly blocksPerPixel: number
|
||||
|
||||
private constructor(private readonly area: TerrainArea) {
|
||||
const first = area.tiles[0][0]
|
||||
this.size = first.size
|
||||
this.blocksPerPixel = first.blocksPerPixel
|
||||
this.columns = area.tiles[0].length * this.size
|
||||
this.rows = area.tiles.length * this.size
|
||||
this.spanX = (this.columns - 1) * this.blocksPerPixel
|
||||
this.spanZ = (this.rows - 1) * this.blocksPerPixel
|
||||
}
|
||||
|
||||
static of(area: TerrainArea): TerrainGrid {
|
||||
return new TerrainGrid(area)
|
||||
}
|
||||
|
||||
worldX(column: number): number {
|
||||
return this.area.originX + column * this.blocksPerPixel
|
||||
}
|
||||
|
||||
worldZ(row: number): number {
|
||||
return this.area.originZ + row * this.blocksPerPixel
|
||||
}
|
||||
|
||||
height(column: number, row: number): number {
|
||||
const { tile, cell } = this.cellAt(column, row)
|
||||
return tile.heights![cell]
|
||||
}
|
||||
|
||||
labelColor(column: number, row: number, coloring: 'biomes' | 'regions'): number {
|
||||
const { tile, cell } = this.cellAt(column, row)
|
||||
const index = coloring === 'regions' ? tile.regions[cell] : tile.subjects[cell]
|
||||
return index === NO_LABEL ? UNLABELLED_COLOR : tile.labels[index].color
|
||||
}
|
||||
|
||||
lowestHeight(): number {
|
||||
let lowest = Infinity
|
||||
for (let row = 0; row < this.rows; row++) {
|
||||
for (let column = 0; column < this.columns; column++) {
|
||||
lowest = Math.min(lowest, this.height(column, row))
|
||||
}
|
||||
}
|
||||
return lowest
|
||||
}
|
||||
|
||||
/** The vertices on the edge of the grid, once each, going round clockwise from the north west corner. */
|
||||
rimVertices(): number[] {
|
||||
const { columns, rows } = this
|
||||
const rim: number[] = []
|
||||
for (let column = 0; column < columns - 1; column++) rim.push(column)
|
||||
for (let row = 0; row < rows - 1; row++) rim.push(row * columns + columns - 1)
|
||||
for (let column = columns - 1; column > 0; column--) rim.push((rows - 1) * columns + column)
|
||||
for (let row = rows - 1; row > 0; row--) rim.push(row * columns)
|
||||
return rim
|
||||
}
|
||||
|
||||
normal(column: number, row: number): Vector3 {
|
||||
const west = this.height(Math.max(0, column - 1), row)
|
||||
const east = this.height(Math.min(this.columns - 1, column + 1), row)
|
||||
const north = this.height(column, Math.max(0, row - 1))
|
||||
const south = this.height(column, Math.min(this.rows - 1, row + 1))
|
||||
return new Vector3(west - east, 2 * this.blocksPerPixel, north - south).normalize()
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import { MapCanvas, type CanvasPoint } from './MapCanvas'
|
||||
import { PickInspector } from './PickInspector'
|
||||
import { RegionPreviewList } from './RegionPreviewList'
|
||||
import { SceneStudio } from './SceneStudio'
|
||||
import { WorldStudio3D } from './WorldStudio3D'
|
||||
import { actionForKey, viewForKey, type ShortcutAction } from './shortcuts'
|
||||
import { StatusBar } from './StatusBar'
|
||||
import { StudioToolbar } from './StudioToolbar'
|
||||
@@ -59,8 +60,9 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
const [packRevision, setPackRevision] = useState(0)
|
||||
const [sceneSummary, setSceneSummary] = useState<string | null>(null)
|
||||
const sceneViews = useSceneViews(client, packRevision)
|
||||
const views = useMemo(() => [...world.views, ...sceneViews.map(asViewInfo)], [world.views, sceneViews])
|
||||
const views = useMemo(() => [...withWorld3D(world.views), ...sceneViews.map(asViewInfo)], [world.views, sceneViews])
|
||||
const sceneView = sceneViews.find((candidate) => candidate.id === viewId) ?? null
|
||||
const showsMap = sceneView === null && viewId !== WORLD_3D.id
|
||||
const view = views.find((candidate) => candidate.id === viewId) ?? views[0]
|
||||
const layer = useMemo<MapLayerQuery>(() => ({ view: viewId, preview: viewId === 'regions' ? preview : null }), [viewId, preview])
|
||||
const regions = usePreviewableRegions(client, packRevision)
|
||||
@@ -200,7 +202,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
world={world}
|
||||
toggles={toggles}
|
||||
hasPlayers={world.hasPlayers}
|
||||
mapTools={sceneView === null}
|
||||
mapTools={showsMap}
|
||||
theme={theme}
|
||||
onToggle={toggle}
|
||||
onRefresh={() => runShortcut('refresh')}
|
||||
@@ -214,6 +216,8 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
</ViewList>
|
||||
{sceneView !== null ? (
|
||||
<SceneStudio client={client} view={sceneView} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
|
||||
) : viewId === WORLD_3D.id ? (
|
||||
<WorldStudio3D client={client} world={world} mapArea={area} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
|
||||
) : (
|
||||
<>
|
||||
<div className="relative min-w-0 flex-1">
|
||||
@@ -269,13 +273,26 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<StatusBar viewLabel={statusLabel(view.label, previewName, sceneView === null ? null : sceneSummary)} status={sceneView === null ? status : null} notice={notice} />
|
||||
<StatusBar viewLabel={statusLabel(view.label, previewName, showsMap ? null : sceneSummary)} status={showsMap ? status : null} notice={notice} />
|
||||
<HelpDialog open={helpOpen} onOpenChange={setHelpOpen} views={views} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const SCENE_GROUP = { group: 'BLOCKS', groupLabel: 'Blocks' }
|
||||
/** The app draws the 3D world from the server's biome tiles, so the server does not list it among its views. */
|
||||
const WORLD_3D: ViewInfo = {
|
||||
id: 'world3d',
|
||||
label: '3D world',
|
||||
description: 'The terrain in 3D, coloured by biome, region or height',
|
||||
group: 'WORLD',
|
||||
groupLabel: 'World'
|
||||
}
|
||||
|
||||
function withWorld3D(serverViews: ViewInfo[]): ViewInfo[] {
|
||||
const afterHeight = serverViews.findIndex((candidate) => candidate.id === 'height') + 1
|
||||
return [...serverViews.slice(0, afterHeight), WORLD_3D, ...serverViews.slice(afterHeight)]
|
||||
}
|
||||
|
||||
function asViewInfo(view: SceneViewInfo): ViewInfo {
|
||||
return { ...view, ...SCENE_GROUP }
|
||||
|
||||
@@ -47,7 +47,7 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce
|
||||
return (
|
||||
<>
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<SceneViewport mesh={mesh} />
|
||||
<SceneViewport content={mesh?.content ?? null} framing={mesh} />
|
||||
{entry !== null && entry.variants > 1 && (
|
||||
<div className="absolute top-3 left-3 flex items-center gap-1 rounded-md border border-overlay-border bg-card/90 p-1 text-[12px] tabular-nums">
|
||||
<Button variant="ghost" size="icon-sm" title="Previous variant" onClick={() => chooseVariant(variant - 1)}>
|
||||
@@ -143,8 +143,7 @@ function useSceneMesh(
|
||||
}
|
||||
|
||||
function disposeMesh(mesh: SceneMesh | null): void {
|
||||
mesh?.geometry.dispose()
|
||||
mesh?.atlas.dispose()
|
||||
mesh?.dispose()
|
||||
}
|
||||
|
||||
interface EntryBrowserProps {
|
||||
|
||||
@@ -1,21 +1,29 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { Box3, Mesh, MeshBasicMaterial, PerspectiveCamera, Scene, Sphere, Vector3, WebGLRenderer } from 'three'
|
||||
import { Box3, PerspectiveCamera, Scene, Sphere, Vector3, WebGLRenderer, type Object3D } from 'three'
|
||||
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
|
||||
import type { SceneMesh } from '../scene/sceneMesh'
|
||||
|
||||
const FIELD_OF_VIEW_DEGREES = 45
|
||||
// Looking down at the scene from the south east, as v3e's object view opens.
|
||||
const VIEW_DIRECTION = new Vector3(1, 0.8, 1.2).normalize()
|
||||
const FRAMING_MARGIN = 1.15
|
||||
const NEAREST_CLIP = 0.05
|
||||
const CUTOUT_ALPHA = 0.1
|
||||
// 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
|
||||
|
||||
interface SceneViewportProps {
|
||||
mesh: SceneMesh | null
|
||||
/** What a viewport shows: one object, and the box the camera frames when it is first shown. */
|
||||
export interface ViewportContent {
|
||||
object: Object3D
|
||||
bounds: Box3
|
||||
}
|
||||
|
||||
/** A block scene in 3D: drag to turn around it, right drag to move, scroll to come closer. Drawn only when it changes. */
|
||||
export function SceneViewport({ mesh }: SceneViewportProps): React.JSX.Element {
|
||||
interface SceneViewportProps {
|
||||
content: ViewportContent | null
|
||||
/** Changes when the camera should frame the content again; the same content keeps the camera where it is. */
|
||||
framing?: unknown
|
||||
}
|
||||
|
||||
/** Something in 3D: drag to turn around it, right drag to move, scroll to come closer. Drawn only when it changes. */
|
||||
export function SceneViewport({ content, framing }: SceneViewportProps): React.JSX.Element {
|
||||
const host = useRef<HTMLDivElement>(null)
|
||||
const stage = useRef<Stage | null>(null)
|
||||
|
||||
@@ -28,19 +36,21 @@ export function SceneViewport({ mesh }: SceneViewportProps): React.JSX.Element {
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => stage.current?.show(mesh), [mesh])
|
||||
useEffect(() => stage.current?.show(content), [content])
|
||||
useEffect(() => stage.current?.frameShown(), [framing])
|
||||
|
||||
return <div ref={host} className="absolute inset-0 bg-map-background" />
|
||||
}
|
||||
|
||||
/** The renderer, camera and controls of one viewport. */
|
||||
/** The renderer, camera and controls of one viewport. What it shows belongs to whoever built it, who frees it. */
|
||||
class Stage {
|
||||
private readonly renderer = new WebGLRenderer({ antialias: true, alpha: true })
|
||||
private readonly camera = new PerspectiveCamera(FIELD_OF_VIEW_DEGREES, 1, NEAREST_CLIP, 10_000)
|
||||
private readonly scene = new Scene()
|
||||
private readonly controls: OrbitControls
|
||||
private readonly resizes: ResizeObserver
|
||||
private shown: Mesh | null = null
|
||||
private shown: ViewportContent | null = null
|
||||
private framed = false
|
||||
private frameRequested = false
|
||||
|
||||
constructor(private readonly host: HTMLDivElement) {
|
||||
@@ -49,34 +59,36 @@ class Stage {
|
||||
host.appendChild(this.renderer.domElement)
|
||||
this.controls = new OrbitControls(this.camera, this.renderer.domElement)
|
||||
this.controls.enableDamping = true
|
||||
this.controls.addEventListener('change', () => this.requestFrame())
|
||||
this.controls.addEventListener('change', () => {
|
||||
this.fitNearClipToOrbit()
|
||||
this.requestFrame()
|
||||
})
|
||||
this.resizes = new ResizeObserver(() => this.fitToHost())
|
||||
this.resizes.observe(host)
|
||||
this.fitToHost()
|
||||
}
|
||||
|
||||
show(mesh: SceneMesh | null): void {
|
||||
this.removeShown()
|
||||
if (mesh === null) {
|
||||
this.requestFrame()
|
||||
return
|
||||
show(content: ViewportContent | null): void {
|
||||
if (this.shown !== null) {
|
||||
this.scene.remove(this.shown.object)
|
||||
}
|
||||
this.shown = content
|
||||
if (content !== null) {
|
||||
this.scene.add(content.object)
|
||||
if (!this.framed) {
|
||||
this.frameShown()
|
||||
}
|
||||
}
|
||||
const material = new MeshBasicMaterial({ map: mesh.atlas.texture, vertexColors: true, alphaTest: CUTOUT_ALPHA })
|
||||
this.shown = new Mesh(mesh.geometry, material)
|
||||
this.scene.add(this.shown)
|
||||
this.frame(new Box3().setFromBufferAttribute(mesh.geometry.getAttribute('position') as never))
|
||||
this.requestFrame()
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.removeShown()
|
||||
this.resizes.disconnect()
|
||||
this.controls.dispose()
|
||||
this.renderer.dispose()
|
||||
this.renderer.domElement.remove()
|
||||
}
|
||||
|
||||
private frame(bounds: Box3): void {
|
||||
frameShown(): void {
|
||||
if (this.shown === null) {
|
||||
this.framed = false
|
||||
return
|
||||
}
|
||||
this.framed = true
|
||||
const bounds = this.shown.bounds
|
||||
const sphere = bounds.isEmpty() ? new Sphere(new Vector3(), 1) : bounds.getBoundingSphere(new Sphere())
|
||||
const halfVertical = (FIELD_OF_VIEW_DEGREES * Math.PI) / 360
|
||||
const halfHorizontal = Math.atan(Math.tan(halfVertical) * this.camera.aspect)
|
||||
@@ -84,18 +96,24 @@ class Stage {
|
||||
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.camera.updateProjectionMatrix()
|
||||
this.controls.update()
|
||||
this.fitNearClipToOrbit()
|
||||
this.requestFrame()
|
||||
}
|
||||
|
||||
// The mesh and its atlas belong to whoever built them; only the material is the viewport's.
|
||||
private removeShown(): void {
|
||||
if (this.shown === null) {
|
||||
return
|
||||
private fitNearClipToOrbit(): void {
|
||||
this.camera.near = Math.max(NEAREST_CLIP, this.camera.position.distanceTo(this.controls.target) * NEAR_CLIP_PER_ORBIT_DISTANCE)
|
||||
this.camera.updateProjectionMatrix()
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.shown !== null) {
|
||||
this.scene.remove(this.shown.object)
|
||||
}
|
||||
this.scene.remove(this.shown)
|
||||
;(this.shown.material as MeshBasicMaterial).dispose()
|
||||
this.shown = null
|
||||
this.resizes.disconnect()
|
||||
this.controls.dispose()
|
||||
this.renderer.dispose()
|
||||
this.renderer.domElement.remove()
|
||||
}
|
||||
|
||||
private fitToHost(): void {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Box, Gem, Map as MapIcon, Mountain, Shapes, Sprout, Trees, Waves, type LucideIcon } from 'lucide-react'
|
||||
import { Box, Gem, Globe, Map as MapIcon, Mountain, Shapes, Sprout, Trees, Waves, type LucideIcon } from 'lucide-react'
|
||||
import { Kbd } from '@/components/ui/kbd'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
@@ -9,6 +9,7 @@ const VIEW_ICONS: Record<string, LucideIcon> = {
|
||||
biomes: Trees,
|
||||
regions: MapIcon,
|
||||
height: Mountain,
|
||||
world3d: Globe,
|
||||
landBiomes: Sprout,
|
||||
seaBiomes: Waves,
|
||||
caveBiomes: Gem,
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
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 { buildTerrainMesh, type TerrainArea, type TerrainColoring } from '../scene/terrainMesh'
|
||||
import { SceneViewport } from './SceneViewport'
|
||||
|
||||
const NUMBER = new Intl.NumberFormat('en-US')
|
||||
const TILES_PER_SIDE = 4
|
||||
const TILE_PIXELS = 128
|
||||
const BLOCKS_PER_PIXEL = 2
|
||||
const TILE_BLOCKS = TILE_PIXELS * BLOCKS_PER_PIXEL
|
||||
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. */
|
||||
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). */
|
||||
export function WorldStudio3D({ client, world, mapArea, packRevision, onSummary, tell }: WorldStudio3DProps): React.JSX.Element {
|
||||
const [coloring, setColoring] = useState<TerrainColoring>('biomes')
|
||||
const centre = useMemo(() => centreOf(mapArea), [mapArea])
|
||||
const area = useTerrainArea(client, centre, packRevision, tell)
|
||||
const mesh = useMemo(() => (area === null ? null : buildTerrainMesh(area, coloring, world.fluidHeight)), [area, coloring, world.fluidHeight])
|
||||
|
||||
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)}`)
|
||||
return () => onSummary(null)
|
||||
}, [centre, onSummary])
|
||||
|
||||
return (
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<SceneViewport content={mesh?.content ?? null} framing={area} />
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="absolute top-3 left-3 bg-card/90"
|
||||
value={coloring}
|
||||
onValueChange={(value) => value !== '' && setColoring(value as TerrainColoring)}
|
||||
>
|
||||
<ToggleGroupItem value="biomes" className={COLORING_ITEM}>
|
||||
Biomes
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="regions" className={COLORING_ITEM}>
|
||||
Regions
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="height" className={COLORING_ITEM}>
|
||||
Height
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
{area === null && (
|
||||
<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>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function centreOf(area: WorldRect | null): { x: number; z: number } {
|
||||
if (area === null) {
|
||||
return { x: 0, z: 0 }
|
||||
}
|
||||
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): TerrainArea | null {
|
||||
const [area, setArea] = useState<TerrainArea | 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
|
||||
}
|
||||
Reference in new issue
Block a user