Show the blocks the world generates in the map and the 3D world, and drop the Height map view

Map tiles can carry the block on top of each column, read from chunks generated in memory through the world's own stages. The 2D map colours by them with a toolbar toggle and the 3D world gets a Blocks colouring with textures, both at a block a pixel or finer. The Height map view goes, as the 3D world shows heights; the Shading toggle keeps its icon under its own name.
This commit is contained in:
piexel committed 2026-11-11 02:45:01 +01:00
1 parent 0812c55425
commit 91f23c52b8
35 files changed
+567 -119

No files matched your search

@@ -5,6 +5,7 @@ import { decodeSavedTile } from './savedTileDecoding'
import { decodeTile } from './tileDecoding'
import type {
BakeRun,
BlockSource,
EditorState,
GraphEdit,
MapHover,
@@ -49,6 +50,8 @@ export interface TileRequest {
size: number
heights: boolean
pickNoise: boolean
/** Where the tile's blocks come from, or null for a tile without them. */
blocks: BlockSource | null
}
/** One tile of a pattern: tile (x, z) covers columns × blocksPerColumn blocks from x × that, z × that. */
@@ -136,6 +139,9 @@ export class BridgeClient {
heights: request.heights ? '1' : '0',
noise: request.pickNoise ? '1' : '0'
})
if (request.blocks !== null) {
query.set('blocks', request.blocks)
}
const response = await this.fetch(`tile?${query}`, { signal })
return decodeTile(await response.arrayBuffer())
}
+10 -2
View File
@@ -9,6 +9,8 @@ interface TileHeader {
labels: MapLabel[]
heights: boolean
pickNoise: boolean
/** The blocks the ground and cover grids index; absent or null on a tile without them. */
blocks?: string[] | null
}
function aligned(bytes: number): number {
@@ -17,7 +19,7 @@ function aligned(bytes: number): number {
/**
* Reads a tile as the bridge writes it (MapTileEncoding): a u32 header length, the JSON header, then the subject,
* region, height and pick noise grids, each starting on a multiple of 4 bytes. The grids are views into the buffer,
* region, height, pick noise, ground and cover grids, each starting on a multiple of 4 bytes. The grids are views into the buffer,
* not copies.
*/
export function decodeTile(buffer: ArrayBuffer): MapTile {
@@ -30,6 +32,8 @@ export function decodeTile(buffer: ArrayBuffer): MapTile {
const regionsAt = aligned(subjectsAt + cells * Int16Array.BYTES_PER_ELEMENT)
const heightsAt = aligned(regionsAt + cells * Int16Array.BYTES_PER_ELEMENT)
const pickNoiseAt = heightsAt + (header.heights ? cells * Float32Array.BYTES_PER_ELEMENT : 0)
const groundAt = pickNoiseAt + (header.pickNoise ? cells * Float32Array.BYTES_PER_ELEMENT : 0)
const coverAt = aligned(groundAt + cells * Int16Array.BYTES_PER_ELEMENT)
return {
size: header.size,
blocksPerPixel: header.blocksPerPixel,
@@ -38,7 +42,11 @@ export function decodeTile(buffer: ArrayBuffer): MapTile {
subjects: new Int16Array(buffer, subjectsAt, cells),
regions: new Int16Array(buffer, regionsAt, cells),
heights: header.heights ? new Float32Array(buffer, heightsAt, cells) : null,
pickNoise: header.pickNoise ? new Float32Array(buffer, pickNoiseAt, cells) : null
pickNoise: header.pickNoise ? new Float32Array(buffer, pickNoiseAt, cells) : null,
blocks:
header.blocks == null
? null
: { names: header.blocks, ground: new Int16Array(buffer, groundAt, cells), cover: new Int16Array(buffer, coverAt, cells), colors: [], looks: [] }
}
}
+22
View File
@@ -1,5 +1,7 @@
/** The shapes the Iris bridge answers with (Iris core, art.arcane.iris.core.studio). */
import type { BlockLook } from '../scene/blockLooks'
export type LabelKind = 'BIOME' | 'REGION'
export interface MapLabel {
@@ -329,6 +331,26 @@ export interface MapTile {
heights: Float32Array | null
/** The noise value that settled each cell's pick, 0 to 1 and NaN where nothing picked it; null unless asked for. */
pickNoise: Float32Array | null
/** The block on top of each cell's column; null unless asked for. */
blocks: TileBlocks | null
}
/** Where a tile's blocks come from: the chunks the server generates in memory. */
export type BlockSource = 'generated'
/** The top of each cell's column: its ground block, and the block standing on it, such as grass. */
export interface TileBlocks {
/** The block states the grids index, as BlockState keys. */
names: string[]
/** {@link NO_BLOCK} where the column holds no ground. */
ground: Int16Array
/** {@link NO_BLOCK} where nothing stands on the ground. */
cover: Int16Array
/** The colour of each named block from above, as 0xRRGGBB; the tile source fills it in. */
colors: number[]
/** What each named block looks like on a column, where the tile is fine enough to show textures; else empty. */
looks: (BlockLook | null)[]
}
export const NO_BLOCK = -1
export const NO_LABEL = -1
@@ -6,6 +6,7 @@ const DARK_SUFFIX = '_dark'
export type IdeIconName =
| 'add'
| 'blocks'
| 'checked'
| 'closeSmall'
| 'chevronLeft'
@@ -24,6 +25,7 @@ export type IdeIconName =
| 'reset'
| 'search'
| 'settings'
| 'shading'
| 'stopWatch'
| 'symlink'
| 'theme'
@@ -33,7 +35,6 @@ export type IdeIconName =
| 'zoomIn'
| 'views/biomes'
| 'views/cave-biomes'
| 'views/height'
| 'views/land-biomes'
| 'views/noise'
| 'views/objects'
+1 -1
View File
@@ -2,4 +2,4 @@ The icons in this folder and its subfolders come from the IntelliJ Platform (htt
platform/icons/src/expui, Copyright 2000-2023 JetBrains s.r.o. and contributors,
used under the Apache License 2.0 (LICENSE-APACHE-2.0.txt).
memory.svg is profileMemory.svg with its profiling badge removed.
theme.svg is the studio's own, drawn to match.
theme.svg and blocks.svg are the studio's own, drawn to match.
+4
View File
@@ -0,0 +1,4 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8 1.5L13.5 4.5V11.5L8 14.5L2.5 11.5V4.5L8 1.5Z" stroke="#6C707E" stroke-linejoin="round"/>
<path d="M2.5 4.5L8 7.5L13.5 4.5M8 7.5V14.5" stroke="#6C707E" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 292 B

@@ -0,0 +1,4 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8 1.5L13.5 4.5V11.5L8 14.5L2.5 11.5V4.5L8 1.5Z" stroke="#CED0D6" stroke-linejoin="round"/>
<path d="M2.5 4.5L8 7.5L13.5 4.5M8 7.5V14.5" stroke="#CED0D6" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 292 B

+25 -21
View File
@@ -1,9 +1,9 @@
import type { BridgeClient, WorldRect } from '../bridge/BridgeClient'
import { gridIndex } from '../bridge/tileDecoding'
import { NO_LABEL, type MapLabel, type MapTile, type Marker, type PickDisplay, type WorldInfo } from '../bridge/types'
import { NO_LABEL, type BlockSource, type MapLabel, type MapTile, type Marker, type PickDisplay, type WorldInfo } from '../bridge/types'
import { countShares, type PlacedTile, type Share } from './census'
import { bandIndexOf, HEIGHT_BANDS } from './heightColors'
import { mapTileSource, type TileLayer } from './mapTileSource'
import { blockArt, type BlockArt } from '../scene/blockArt'
import { hasBlocksAt, mapTileSource, type TileLayer } from './mapTileSource'
import { drawPlayerArrow } from './playerArrow'
import { drawVisibleTiles } from './tileDrawing'
import type { Highlight, TileStyle } from './tileStyle'
@@ -51,8 +51,12 @@ export interface MapToggles {
shading: boolean
regionBorders: boolean
grid: boolean
/** Colour the map by the block on top of each column, where it is zoomed in far enough. */
blocks: boolean
}
const BLOCK_SOURCE: BlockSource = 'generated'
const CENSUS_INTERVAL_MILLIS = 250
const CHUNK_BLOCKS = 16
const REGION_BLOCKS = 512
@@ -69,10 +73,11 @@ const ENTITY_RADIUS_PIXELS = 3
*/
export class MapController {
private readonly context: CanvasRenderingContext2D
private readonly art: BlockArt
private readonly store: TileStore<MapTile, TileLayer, TileStyle>
private readonly view: Viewport = { centerX: 0, centerZ: 0, blocksPerPixel: DEFAULT_BLOCKS_PER_PIXEL, width: 1, height: 1 }
private layer: TileLayer
private toggles: MapToggles = { shading: true, regionBorders: false, grid: false }
private toggles: MapToggles = { shading: true, regionBorders: false, grid: false, blocks: false }
private pickDisplay: PickDisplay = 'picks'
private highlight: Highlight | null = null
private players: Marker[] = []
@@ -91,12 +96,14 @@ export class MapController {
private readonly listener: MapListener
) {
this.context = canvas.getContext('2d')!
this.layer = { view, preview: null, heights: this.needsHeights(view, this.toggles), pickNoise: false, revision: 0 }
this.store = new TileStore(mapTileSource(client, world.tileSize), () => this.redraw(), (message) => listener.onError(message))
this.layer = { view, preview: null, heights: this.needsHeights(this.toggles), pickNoise: false, blocks: null, revision: 0 }
this.art = blockArt(client, false)
this.store = new TileStore(mapTileSource(client, world.tileSize, this.art), () => this.redraw(), (message) => listener.onError(message))
}
close(): void {
this.closed = true
this.art.dispose()
window.clearTimeout(this.censusTimer)
this.store.clear()
}
@@ -116,7 +123,6 @@ export class MapController {
...this.layer,
view,
preview: view === 'regions' ? preview : null,
heights: this.needsHeights(view, this.toggles),
pickNoise: this.needsPickNoise(view, this.pickDisplay)
}
this.redraw()
@@ -135,13 +141,19 @@ export class MapController {
setToggles(toggles: MapToggles): void {
this.toggles = toggles
this.layer = { ...this.layer, heights: this.needsHeights(this.layer.view, toggles) }
this.layer = { ...this.layer, heights: this.needsHeights(toggles), blocks: toggles.blocks ? BLOCK_SOURCE : null }
this.redraw()
}
// Heights are the costly part of a tile, so they are only asked for when something draws with them.
private needsHeights(view: string, toggles: MapToggles): boolean {
return toggles.shading || view === 'height'
/** Whether the map is zoomed in far enough for its tiles to carry blocks. */
showsBlocks(): boolean {
return hasBlocksAt(BLOCK_SOURCE, this.renderScale())
}
// Heights are the costly part of a tile, so they are only asked for when something draws with them: the relief, and
// the sea over the blocks.
private needsHeights(toggles: MapToggles): boolean {
return toggles.shading || toggles.blocks
}
setHighlight(highlight: Highlight | null): void {
@@ -213,24 +225,16 @@ export class MapController {
const pixelZ = Math.min(tile.size - 1, Math.floor((worldZ - address.tileZ * span) / scale))
const cell = gridIndex(tile, pixelX, pixelZ)
const region = labelAt(tile.labels, tile.regions[cell])
if (this.isHeightView() && tile.heights !== null) {
const band = HEIGHT_BANDS[bandIndexOf(tile.heights[cell], this.world.fluidHeight)]
return { subject: { kind: 'HEIGHT', key: band.key, name: band.name }, region }
}
return { subject: labelAt(tile.labels, tile.subjects[cell]), region }
}
private isHeightView(): boolean {
return this.layer.view === 'height'
}
private renderScale(): number {
return renderBlocksPerPixel(this.view.blocksPerPixel, window.devicePixelRatio)
}
private style(): TileStyle {
return {
byHeight: this.isHeightView(),
byBlock: this.toggles.blocks,
shading: this.toggles.shading,
regionBorders: this.toggles.regionBorders,
highlight: this.highlight,
@@ -369,7 +373,7 @@ export class MapController {
}
const screen = this.screenArea()
const area = { minimumX: screen.minX, minimumZ: screen.minZ, maximumX: screen.maxX, maximumZ: screen.maxZ }
return countShares(placed, area, this.isHeightView(), this.world.fluidHeight)
return countShares(placed, area)
}
}
+4 -12
View File
@@ -28,10 +28,9 @@ export interface WorldArea {
const MAXIMUM_COUNTED_PIXELS = 250_000
/**
* The shares of what the tiles show inside {@code area}, largest first: their subjects (biomes or regions), or their
* height bands when {@code byHeight} is set.
* The shares of what the tiles show inside {@code area}, largest first: their subjects, which are biomes or regions.
*/
export function countShares(tiles: PlacedTile[], area: WorldArea, byHeight: boolean, seaLevel: number): Share[] {
export function countShares(tiles: PlacedTile[], area: WorldArea): Share[] {
const counts = new Map<string, { subject: Highlight; color: number; count: number }>()
const totalPixels = tiles.reduce((sum, placed) => sum + placed.tile.size * placed.tile.size, 0)
const stride = Math.max(1, Math.ceil(Math.sqrt(totalPixels / MAXIMUM_COUNTED_PIXELS)))
@@ -44,7 +43,7 @@ export function countShares(tiles: PlacedTile[], area: WorldArea, byHeight: bool
const endZ = Math.min(tile.size, Math.ceil((area.maximumZ - worldZ) / scale))
for (let pixelZ = firstZ; pixelZ < endZ; pixelZ += stride) {
for (let pixelX = firstX; pixelX < endX; pixelX += stride) {
const subject = subjectAt(tile, gridIndex(tile, pixelX, pixelZ), byHeight, seaLevel)
const subject = subjectAt(tile, gridIndex(tile, pixelX, pixelZ))
if (subject === null) {
continue
}
@@ -76,14 +75,7 @@ export function heightBandShares(heights: readonly number[], seaLevel: number):
})
}
function subjectAt(tile: MapTile, cell: number, byHeight: boolean, seaLevel: number): { subject: Highlight; color: number } | null {
if (byHeight) {
if (tile.heights === null) {
return null
}
const band = HEIGHT_BANDS[bandIndexOf(tile.heights[cell], seaLevel)]
return { subject: { kind: 'HEIGHT', key: band.key, name: band.name }, color: band.color }
}
function subjectAt(tile: MapTile, cell: number): { subject: Highlight; color: number } | null {
const index = tile.subjects[cell]
if (index === NO_LABEL) {
return null
+21 -11
View File
@@ -10,7 +10,7 @@ import { coarserTile, previewsFor, renderBlocksPerPixel, screenToWorldX, visible
const PLAINS: MapLabel = { kind: 'BIOME', key: 'plains', name: 'Plains', color: 0x00ff00 }
const DESERT: MapLabel = { kind: 'BIOME', key: 'desert', name: 'Desert', color: 0xffff00 }
const WARM: MapLabel = { kind: 'REGION', key: 'warm', name: 'Warm', color: 0xff0000 }
const FLAT: TileStyle = { byHeight: false, shading: false, regionBorders: false, highlight: null, seaLevel: 63, pickDisplay: 'picks' }
const FLAT: TileStyle = { byBlock: false, shading: false, regionBorders: false, highlight: null, seaLevel: 63, pickDisplay: 'picks' }
/** A tile whose left half is plains and right half desert, all in one region, at height 70. */
function splitTile(size = 4): MapTile {
@@ -27,7 +27,8 @@ function splitTile(size = 4): MapTile {
subjects,
regions: new Int16Array(cells).fill(2),
heights: new Float32Array(cells).fill(70),
pickNoise: null
pickNoise: null,
blocks: null
}
}
@@ -132,6 +133,22 @@ describe('tile style', () => {
expect(pixel(pixels, 4, 3, 3)).toBe(DESERT.color)
})
it('paints each pixel in the colour of what stands on its ground, or of the ground itself', () => {
const tile = splitTile()
const cells = tile.subjects.length
const cover = new Int16Array(cells).fill(-1)
cover[gridIndex(tile, 3, 3)] = 1
const blocks = { names: ['stone', 'poppy'], ground: new Int16Array(cells).fill(0), cover, colors: [0x808080, 0xff0000], looks: [] }
const pixels = stylePixels({ ...tile, blocks }, { ...FLAT, byBlock: true })
expect(pixel(pixels, 4, 0, 0)).toBe(0x808080)
expect(pixel(pixels, 4, 3, 3)).toBe(0xff0000)
})
it('keeps the label colours of a tile without blocks', () => {
expect(pixel(stylePixels(splitTile(), { ...FLAT, byBlock: true }), 4, 0, 0)).toBe(PLAINS.color)
})
it('dims everything but the highlight, and tints the highlight edge', () => {
const pixels = stylePixels(splitTile(), { ...FLAT, highlight: { kind: 'BIOME', key: 'plains', name: 'Plains' } })
@@ -194,7 +211,7 @@ describe('viewport', () => {
describe('census', () => {
it('shares the visible pixels between the labels', () => {
const tile = splitTile(4)
const shares = countShares([{ tile, worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 4, maximumZ: 4 }, false, 63)
const shares = countShares([{ tile, worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 4, maximumZ: 4 })
expect(shares.map((share) => share.subject.key).sort()).toEqual(['desert', 'plains'])
expect(shares[0].fraction).toBeCloseTo(0.5)
@@ -202,19 +219,12 @@ describe('census', () => {
})
it('counts only the part of a tile inside the area, largest share first', () => {
const shares = countShares([{ tile: splitTile(4), worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 3, maximumZ: 4 }, false, 63)
const shares = countShares([{ tile: splitTile(4), worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 3, maximumZ: 4 })
expect(shares.map((share) => share.subject.key)).toEqual(['plains', 'desert'])
expect(shares[0].fraction).toBeCloseTo(2 / 3)
})
it('counts height bands in the height view', () => {
const shares = countShares([{ tile: splitTile(4), worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 4, maximumZ: 4 }, true, 63)
expect(shares).toHaveLength(1)
expect(shares[0].subject).toMatchObject({ kind: 'HEIGHT', name: '0–8 above sea' })
})
it('shares spot heights between their bands, highest band first', () => {
const shares = heightBandShares([64, 64, 64, 500, 30], 63)
+26 -6
View File
@@ -1,5 +1,6 @@
import type { BridgeClient } from '../bridge/BridgeClient'
import type { MapTile } from '../bridge/types'
import type { BlockSource, MapTile } from '../bridge/types'
import type { BlockArt } from '../scene/blockArt'
import { stylePixels, styleKey, type TileStyle } from './tileStyle'
import type { TileSource } from './TileStore'
@@ -10,16 +11,35 @@ export interface TileLayer {
preview: string | null
heights: boolean
pickNoise: boolean
/** Where the tiles' blocks come from, or null for tiles without them. */
blocks: BlockSource | null
/** Bumped when the pack is hotloaded, so older tiles are not used again. */
revision: number
}
/** The world map's tiles: the engine's streams, drawn in the map's styles. */
export function mapTileSource(client: BridgeClient, tileSize: number): TileSource<MapTile, TileLayer, TileStyle> {
/** The coarsest tiles a block source is asked for; coarser ones come without blocks. */
const MOST_BLOCKS_PER_PIXEL: Record<BlockSource, number> = { generated: 1 }
const TEXTURED_BLOCKS_PER_PIXEL = 1
/** Whether tiles this coarse carry blocks from {@code source}. */
export function hasBlocksAt(source: BlockSource, blocksPerPixel: number): boolean {
return blocksPerPixel <= MOST_BLOCKS_PER_PIXEL[source]
}
/** The world map's tiles: the engine's streams, drawn in the map's styles, their blocks painted with {@code art}. */
export function mapTileSource(client: BridgeClient, tileSize: number, art: BlockArt): TileSource<MapTile, TileLayer, TileStyle> {
return {
layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise].join('/'),
fetch: (address, layer, signal) => client.tile({ ...layer, ...address, size: tileSize }, signal),
bytesOf: (tile) => tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + tile.size * tile.size * 4,
layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise, layer.blocks ?? ''].join('/'),
fetch: async (address, layer, signal) => {
const blocks = layer.blocks !== null && hasBlocksAt(layer.blocks, address.blocksPerPixel) ? layer.blocks : null
const tile = await client.tile({ ...layer, ...address, size: tileSize, blocks }, signal)
if (tile.blocks !== null) {
await art.paint(tile.blocks, address.blocksPerPixel === TEXTURED_BLOCKS_PER_PIXEL)
}
return tile
},
bytesOf: (tile) =>
tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + (tile.blocks?.ground.byteLength ?? 0) * 2 + tile.size * tile.size * 4,
styleKey,
pixels: (tile, style) => new ImageData(stylePixels(tile, style), tile.size, tile.size)
}
+20 -19
View File
@@ -1,8 +1,11 @@
import { gridIndex } from '../bridge/tileDecoding'
import { NO_LABEL, type MapTile, type PickDisplay } from '../bridge/types'
import { bandIndexOf, blend, heightColor } from './heightColors'
import { NO_BLOCK, NO_LABEL, type MapTile, type PickDisplay, type TileBlocks } from '../bridge/types'
import { WATER_SURFACE_COLOR } from '../scene/waterTint'
import { blend } from './heightColors'
/** What a highlight picks out: a biome or region by key, or a height band in the height view. */
const WATER_OVER_GROUND = 0.65
/** What a highlight picks out: a biome or region by key, or a height band in the 3D world's legend. */
export interface Highlight {
kind: 'BIOME' | 'REGION' | 'HEIGHT'
key: string
@@ -10,8 +13,8 @@ export interface Highlight {
}
export interface TileStyle {
/** Colour by height instead of by label. */
byHeight: boolean
/** Colour by the block on top of each column instead of by label, where the tile carries its blocks. */
byBlock: boolean
shading: boolean
regionBorders: boolean
highlight: Highlight | null
@@ -22,7 +25,7 @@ export interface TileStyle {
export function styleKey(style: TileStyle): string {
const highlight = style.highlight === null ? '' : `${style.highlight.kind}:${style.highlight.key}`
return `${style.byHeight}|${style.shading}|${style.regionBorders}|${highlight}|${style.seaLevel}|${style.pickDisplay}`
return `${style.byBlock}|${style.shading}|${style.regionBorders}|${highlight}|${style.seaLevel}|${style.pickDisplay}`
}
const UNKNOWN_SUBJECT = 0x5a5c62
@@ -55,15 +58,15 @@ export function stylePixels(tile: MapTile, style: TileStyle): Uint8ClampedArray<
const { size, heights } = tile
const pixels = new Uint8ClampedArray(size * size * 4)
const colors = tile.labels.map((label) => label.color)
const byHeight = style.byHeight && heights !== null
const pickNoise = style.pickDisplay === 'picks' ? null : tile.pickNoise
const blocks = style.byBlock ? tile.blocks : null
const pickNoise = style.pickDisplay === 'picks' || blocks !== null ? null : tile.pickNoise
// The bare noise is read by its brightness, which relief shading would mix up.
const shading = (style.shading || byHeight) && heights !== null && !(pickNoise !== null && style.pickDisplay === 'noise')
const shading = style.shading && heights !== null && !(pickNoise !== null && style.pickDisplay === 'noise')
const highlighted = highlightCells(tile, style)
for (let pixelZ = 0; pixelZ < size; pixelZ++) {
for (let pixelX = 0; pixelX < size; pixelX++) {
const cell = gridIndex(tile, pixelX, pixelZ)
let color = byHeight ? heightColor(heights[cell], style.seaLevel) : labelColor(colors, tile.subjects[cell])
let color = blocks === null ? labelColor(colors, tile.subjects[cell]) : blockColor(blocks, cell, heights, style.seaLevel)
if (pickNoise !== null) {
color = byNoise(color, pickNoise[cell], style.pickDisplay)
}
@@ -90,6 +93,13 @@ function labelColor(colors: number[], index: number): number {
return index === NO_LABEL ? UNKNOWN_SUBJECT : colors[index]
}
// What stands on the ground is what is seen from above; ground under the sea shows through its water.
function blockColor(blocks: TileBlocks, cell: number, heights: Float32Array | null, seaLevel: number): number {
const top = blocks.cover[cell] === NO_BLOCK ? blocks.ground[cell] : blocks.cover[cell]
const color = top === NO_BLOCK ? UNKNOWN_SUBJECT : blocks.colors[top]
return heights !== null && heights[cell] < seaLevel ? blend(color, WATER_SURFACE_COLOR, WATER_OVER_GROUND) : color
}
// Where nothing picked the spot, as on an image map, it keeps its colour.
function byNoise(color: number, noise: number, display: PickDisplay): number {
if (Number.isNaN(noise)) {
@@ -122,15 +132,6 @@ function highlightCells(tile: MapTile, style: TileStyle): Uint8Array | null {
return null
}
const cells = new Uint8Array(tile.subjects.length)
if (target.kind === 'HEIGHT') {
if (tile.heights !== null) {
const band = Number(target.key)
tile.heights.forEach((height, cell) => {
cells[cell] = bandIndexOf(height, style.seaLevel) === band ? 1 : 0
})
}
return cells
}
// Every view knows its regions, so a region can be highlighted in a biome view too.
const grid = target.kind === tile.subjectKind ? tile.subjects : target.kind === 'REGION' ? tile.regions : null
const index = tile.labels.findIndex((label) => label.kind === target.kind && label.key === target.key)
+34
View File
@@ -0,0 +1,34 @@
import type { BridgeClient } from '../bridge/BridgeClient'
import type { TileBlocks } from '../bridge/types'
import { BlockColors } from './blockColors'
import { BlockLooks } from './blockLooks'
import { BlockModels } from './blockModels'
import { BridgeAssets } from './BridgeAssets'
import { TerrainAtlas } from './terrainAtlas'
/** What a tile's blocks are drawn with: each block's colour from above, and its textures where columns show them. */
export interface BlockArt {
/** The atlas the looks' pictures lie in; null for art that only colours. */
readonly atlas: TerrainAtlas | null
/** Fills in the colours of the tile's blocks, and their looks when {@code textured}. */
paint(blocks: TileBlocks, textured: boolean): Promise<void>
dispose(): void
}
/** Block art read from the Minecraft client's assets through the bridge; {@code textured} art can also show textures. */
export function blockArt(client: BridgeClient, textured: boolean): BlockArt {
const images = new BridgeAssets(client, () => {})
const models = new BlockModels(images)
const colors = new BlockColors(models, images)
const atlas = textured ? new TerrainAtlas(images) : null
const looks = atlas === null ? null : new BlockLooks(models, atlas)
return {
atlas,
paint: async (blocks, withLooks) => {
const [colorOf, lookOf] = await Promise.all([colors.colorsOf(blocks.names), withLooks && looks !== null ? looks.looksOf(blocks.names) : null])
blocks.colors = blocks.names.map((name) => colorOf.get(name)!)
blocks.looks = lookOf === null ? [] : blocks.names.map((name) => lookOf.get(name) ?? null)
},
dispose: () => atlas?.dispose()
}
}
+24 -4
View File
@@ -1,13 +1,19 @@
import { NO_LABEL, type MapTile } from '../bridge/types'
import { NO_BLOCK, NO_LABEL, type MapTile } from '../bridge/types'
import { heightColor } from '../map/heightColors'
import type { BlockLook } from './blockLooks'
import type { TerrainPictures } from './terrainAtlas'
import type { TerrainSurface } from './terrainMesh'
import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from './terrainTiles'
export type MapTerrainColoring = 'biomes' | 'regions' | 'height'
export type MapTerrainColoring = 'biomes' | 'regions' | 'height' | 'blocks'
const UNLABELLED_COLOR = 0x5a5f6b
/** 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. */
/**
* 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. Coloured by blocks, a tile that carries them shows their colours, and their textures
* where it has their looks; one too coarse to carry them keeps its biomes' colours.
*/
export class MapTerrain implements TerrainSurface {
readonly columns: number
readonly rows: number
@@ -19,7 +25,8 @@ export class MapTerrain implements TerrainSurface {
private readonly tile: MapTile,
place: TerrainTile,
private readonly coloring: MapTerrainColoring,
private readonly fluidHeight: number
private readonly fluidHeight: number,
readonly pictures?: TerrainPictures
) {
this.columns = tile.size
this.rows = tile.size
@@ -36,14 +43,27 @@ export class MapTerrain implements TerrainSurface {
return this.heightAt(column, row) < this.fluidHeight ? Math.floor(this.fluidHeight) : null
}
lookAt(column: number, row: number): BlockLook | null {
const ground = this.groundBlockAt(column, row)
return ground === NO_BLOCK ? null : (this.tile.blocks!.looks[ground] ?? null)
}
colorAt(column: number, row: number): number {
if (this.coloring === 'height') {
return heightColor(this.heightAt(column, row), this.fluidHeight)
}
const ground = this.groundBlockAt(column, row)
if (ground !== NO_BLOCK) {
return this.tile.blocks!.colors[ground]
}
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 groundBlockAt(column: number, row: number): number {
return this.coloring === 'blocks' && this.tile.blocks !== null ? this.tile.blocks.ground[this.cellAt(column, row)] : NO_BLOCK
}
private heightAt(column: number, row: number): number {
return this.tile.heights![this.cellAt(column, row)]
}
+8 -5
View File
@@ -47,7 +47,7 @@ export interface StudioToggles extends MapToggles {
export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps): React.JSX.Element {
const controller = useRef<MapController | null>(null)
const [viewId, setViewId] = useState(world.views[0]?.id ?? 'biomes')
const [toggles, setToggles] = useState<StudioToggles>({ shading: true, regionBorders: false, grid: false, follow: false, entities: false })
const [toggles, setToggles] = useState<StudioToggles>({ shading: true, regionBorders: false, grid: false, blocks: false, follow: false, entities: false })
const [highlight, setHighlight] = useState<Highlight | null>(null)
const [status, setStatus] = useState<MapStatus | null>(null)
const [shares, setShares] = useState<Share[]>([])
@@ -171,6 +171,9 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
case 'shading':
toggle('shading')
return
case 'blocks':
toggle('blocks')
return
case 'borders':
toggle('regionBorders')
return
@@ -314,7 +317,7 @@ const SCENE_GROUP = { group: 'BLOCKS', groupLabel: 'Blocks' }
const WORLD_3D: ViewInfo = {
id: 'world3d',
label: '3D world',
description: 'The terrain in 3D, coloured by biome, region or height',
description: 'The terrain in 3D, coloured by biome, region or height, or as the blocks the world generates',
group: 'WORLD',
groupLabel: 'World'
}
@@ -335,8 +338,8 @@ const NOISE: ViewInfo = {
const APP_VIEW_IDS = new Set([WORLD_3D.id, SAVED_WORLD.id, NOISE.id])
function withAppViews(serverViews: ViewInfo[]): ViewInfo[] {
const afterHeight = serverViews.findIndex((candidate) => candidate.id === 'height') + 1
return [...serverViews.slice(0, afterHeight), WORLD_3D, SAVED_WORLD, ...serverViews.slice(afterHeight)]
const afterRegions = serverViews.findIndex((candidate) => candidate.id === 'regions') + 1
return [...serverViews.slice(0, afterRegions), WORLD_3D, SAVED_WORLD, ...serverViews.slice(afterRegions)]
}
function asViewInfo(view: ModuleViewInfo): ViewInfo {
@@ -375,7 +378,7 @@ function legendTitle(layer: MapLayerQuery): string {
if (layer.view === 'regions' && layer.preview === null) {
return 'Regions on screen'
}
return layer.view === 'height' ? 'Heights on screen' : 'Biomes on screen'
return 'Biomes on screen'
}
/** The regions the region view can preview, read again after the pack reloads. */
@@ -72,7 +72,10 @@ export function MapTools({ toggles, hasPlayers, onToggle, onRefresh, onResetZoom
<IdeIcon name="views/regions" />
</ToolToggle>
<ToolToggle action="shading" hint="Shade hills and valleys" pressed={toggles.shading} onPressed={() => onToggle('shading')}>
<IdeIcon name="views/height" />
<IdeIcon name="shading" />
</ToolToggle>
<ToolToggle action="blocks" hint="Show the blocks the world generates, zoomed in to a block a pixel" pressed={toggles.blocks} onPressed={() => onToggle('blocks')}>
<IdeIcon name="blocks" />
</ToolToggle>
<Separator orientation="vertical" className="mx-1 h-4!" />
<ToolToggle action="entities" hint="Show mobs and other entities" pressed={toggles.entities} disabled={!hasPlayers} onPressed={() => onToggle('entities')}>
@@ -11,7 +11,6 @@ import { useKeyText } from './useBindings'
const VIEW_ICONS: Record<string, IdeIconName> = {
biomes: 'views/biomes',
regions: 'views/regions',
height: 'views/height',
world3d: 'views/world-3d',
savedWorld: 'views/saved-world',
landBiomes: 'views/land-biomes',
@@ -5,6 +5,7 @@ import type { MapTile, WorldInfo } from '../bridge/types'
import { heightBandShares } from '../map/census'
import { mapTileSource, type TileLayer } from '../map/mapTileSource'
import type { GroundInView } from '../scene/groundInView'
import { blockArt } from '../scene/blockArt'
import { MapTerrain, type MapTerrainColoring } from '../scene/mapTerrain'
import { focusAround, type TerrainStyle } from '../scene/terrainStream'
import { TILE_COLUMNS } from '../scene/terrainTiles'
@@ -39,26 +40,33 @@ interface WorldStudio3DProps {
export function WorldStudio3D({ title, client, world, mapArea, packRevision, onSummary, tell }: WorldStudio3DProps): React.JSX.Element {
const [coloring, setColoring] = useState<MapTerrainColoring>('biomes')
const centre = useMemo(() => centreOf(mapArea), [mapArea])
const source = useMemo(() => mapTileSource(client, TILE_COLUMNS), [client])
const art = useMemo(() => blockArt(client, true), [client])
useEffect(() => () => art.dispose(), [art])
const source = useMemo(() => mapTileSource(client, TILE_COLUMNS, art), [client, art])
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 showsBlocks = coloring === 'blocks'
const layer = useMemo<TileLayer>(
() => ({ view: 'biomes', preview: null, heights: true, pickNoise: false, blocks: showsBlocks ? 'generated' : null, revision: packRevision }),
[packRevision, showsBlocks]
)
const style = useMemo<TerrainStyle<MapTile>>(
() => ({
surfaceOf: (tile, place) => new MapTerrain(tile, place, coloring, world.fluidHeight),
surfaceOf: (tile, place) => new MapTerrain(tile, place, coloring, world.fluidHeight, art.atlas ?? undefined),
floorY: world.minY,
topY: world.minY + world.height
}),
[coloring, world.fluidHeight, world.minY, world.height]
[coloring, world.fluidHeight, world.minY, world.height, art]
)
const { content, pending, stream } = useTerrainStream(source, COARSEST_LEVEL, focus, layer, style, tell)
const sampling = useLongPending(pending)
const ground = useGroundInView(stream)
const heightShares = useMemo(() => heightBandShares(ground?.heights ?? [], world.fluidHeight), [ground, world.fluidHeight])
const inspectsPicks = coloring !== 'height'
const pickLayer = useMemo<MapLayerQuery>(() => ({ view: coloring, preview: null }), [coloring])
const pickView = coloring === 'regions' ? 'regions' : 'biomes'
const pickLayer = useMemo<MapLayerQuery>(() => ({ view: pickView, preview: null }), [pickView])
const area = useAreaOf(ground)
const inspection = usePickInspection(client, pickLayer, area, inspectsPicks, packRevision)
@@ -82,6 +90,9 @@ export function WorldStudio3D({ title, client, world, mapArea, packRevision, onS
<ToggleGroupItem value="height" className={HEADER_CHOICE}>
Height
</ToggleGroupItem>
<ToggleGroupItem value="blocks" className={HEADER_CHOICE} title="The blocks the world generates, shown close up">
Blocks
</ToggleGroupItem>
</ToggleGroup>
}
>
@@ -16,7 +16,7 @@ import {
type KeyPress
} from './shortcuts'
const DEFAULT_VIEWS = ['biomes', 'regions', 'height', 'landBiomes', 'seaBiomes', 'caveBiomes'].map((id) => ({ id, label: id }))
const DEFAULT_VIEWS = ['biomes', 'regions', 'landBiomes', 'seaBiomes', 'caveBiomes'].map((id) => ({ id, label: id }))
const ROWS = shortcutRows(DEFAULT_VIEWS)
function press(key: string, modifiers: Partial<Omit<KeyPress, 'key'>> = {}): KeyPress {
+2 -1
View File
@@ -11,6 +11,7 @@ export type ShortcutAction =
| 'entities'
| 'highlight'
| 'shading'
| 'blocks'
| 'borders'
| 'help'
| 'undo'
@@ -55,6 +56,7 @@ export const SHORTCUTS: ShortcutDefinition[] = [
{ id: 'entities', label: 'Show entities', group: 'Map', chords: ['e'] },
{ id: 'highlight', label: 'Highlight what is under the cursor', group: 'Map', chords: ['h'] },
{ id: 'shading', label: 'Terrain shading', group: 'Map', chords: ['s'] },
{ id: 'blocks', label: 'Generated blocks', group: 'Map', chords: ['k'] },
{ id: 'borders', label: 'Region borders', group: 'Map', chords: ['b'] },
{ id: 'help', label: 'Show the shortcuts', group: 'Map', chords: ['/', '?'] },
{ id: 'undo', label: 'Undo', group: 'Node editor', chords: ['ctrl+z'] },
@@ -68,7 +70,6 @@ export const SHORTCUTS: ShortcutDefinition[] = [
const VIEW_KEYS: Record<string, Chord> = {
biomes: '1',
regions: '2',
height: '3',
world3d: '4',
landBiomes: '5',
seaBiomes: '6',