Show noise pick charts and a height legend beside the studio 3D world

The 3D world view had no side panel. Biomes and Regions colourings now show how the noise picks what the camera sees, measured over the box around the ground in view; Height shows how much of that ground lies in each height band, highest first.

v3: e5c4b0958 a223dd603
This commit is contained in:
piexel committed 2026-11-10 12:00:58 +01:00
1 parent 6d4d14606c
commit 69b0303148
13 files changed
+419 -122

No files matched your search

+15
View File
@@ -61,6 +61,21 @@ export function countShares(tiles: PlacedTile[], area: WorldArea, byHeight: bool
.sort((first, second) => second.fraction - first.fraction)
}
/** The shares of the height bands the {@code heights} fall in, highest band first. */
export function heightBandShares(heights: readonly number[], seaLevel: number): Share[] {
const counts = new Map<number, number>()
for (const height of heights) {
const band = bandIndexOf(height, seaLevel)
counts.set(band, (counts.get(band) ?? 0) + 1)
}
return [...counts]
.sort(([firstBand], [secondBand]) => secondBand - firstBand)
.map(([band, count]) => {
const { key, name, color } = HEIGHT_BANDS[band]
return { subject: { kind: 'HEIGHT', key, name }, color, fraction: count / heights.length }
})
}
function subjectAt(tile: MapTile, cell: number, byHeight: boolean, seaLevel: number): { subject: Highlight; color: number } | null {
if (byHeight) {
if (tile.heights === null) {
+13 -1
View File
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import { decodeTile, gridIndex } from '../bridge/tileDecoding'
import type { MapLabel, MapTile } from '../bridge/types'
import { countShares } from './census'
import { countShares, heightBandShares } from './census'
import { bandIndexOf, HEIGHT_BANDS, heightColor } from './heightColors'
import { arrowCorners } from './playerArrow'
import { stylePixels, type TileStyle } from './tileStyle'
@@ -214,6 +214,18 @@ describe('census', () => {
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)
expect(shares.map((share) => share.subject.name)).toEqual(['300+ above sea', '0–8 above sea', '10–40 below sea'])
expect(shares.map((share) => share.fraction)).toEqual([0.2, 0.6, 0.2])
expect(shares[1].color).toBe(HEIGHT_BANDS[bandIndexOf(64, 63)].color)
})
it('has no shares for no heights', () => {
expect(heightBandShares([], 63)).toEqual([])
})
})
describe('player arrow', () => {
+16 -3
View File
@@ -72,9 +72,22 @@ export class ColumnField {
/** 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)
return this.surfaceTop(this.columnOf(worldX), this.rowOf(worldZ))
}
/** The top face of the ground under any water over the world block, or null where the field has none. */
groundTopOver(worldX: number, worldZ: number): number | null {
const column = this.columnOf(worldX)
const row = this.rowOf(worldZ)
return this.hasGround(column, row) ? this.groundTop[this.indexOf(column, row)] : null
}
private columnOf(worldX: number): number {
return Math.floor((worldX - this.originX) / this.blocksPerColumn)
}
private rowOf(worldZ: number): number {
return Math.floor((worldZ - this.originZ) / this.blocksPerColumn)
}
private holeMask(holes: readonly ColumnArea[]): Uint8Array {
@@ -0,0 +1,62 @@
import { PerspectiveCamera, Vector3 } from 'three'
import { describe, expect, it } from 'vitest'
import { ColumnField } from './columnField'
import { groundInView } from './groundInView'
const GROUND = 70
const CEILING = 128
const FIELD_BLOCKS = 4000
const BLOCKS_PER_COLUMN = 8
const VIEW_WIDTH = 1280
const VIEW_HEIGHT = 800
// A square of flat ground from the origin, with a ridge ten blocks higher along its eastern edge.
const RIDGE_FROM_X = 3000
const ground = new ColumnField({
columns: FIELD_BLOCKS / BLOCKS_PER_COLUMN,
rows: FIELD_BLOCKS / BLOCKS_PER_COLUMN,
originX: 0,
originZ: 0,
blocksPerColumn: BLOCKS_PER_COLUMN,
groundAt: (column) => (column * BLOCKS_PER_COLUMN >= RIDGE_FROM_X ? GROUND + 10 : GROUND),
waterAt: () => null,
colorAt: () => 0
})
function lookDownFrom(position: Vector3, lookedAt: Vector3): { camera: PerspectiveCamera; width: number; height: number; orbitDistance: number } {
const camera = new PerspectiveCamera(45, VIEW_WIDTH / VIEW_HEIGHT, 1, 20_000)
camera.position.copy(position)
camera.lookAt(lookedAt)
camera.updateMatrixWorld()
return { camera, width: VIEW_WIDTH, height: VIEW_HEIGHT, orbitDistance: position.distanceTo(lookedAt) }
}
const drawn = {
surfaceTopOver: (x: number, z: number) => ground.surfaceTopOver(x, z),
groundTopOver: (x: number, z: number) => ground.groundTopOver(x, z)
}
describe('ground in view', () => {
it('boxes the ground the camera looks down at and reads its height', () => {
const seen = groundInView(lookDownFrom(new Vector3(1000, 400, 1400), new Vector3(1000, GROUND, 1000)), CEILING, drawn)!
expect(seen.heights.length).toBeGreaterThan(100)
expect(new Set(seen.heights)).toEqual(new Set([GROUND]))
expect(seen.area.minX).toBeLessThan(1000)
expect(seen.area.maxX).toBeGreaterThan(1000)
expect(seen.area.minZ).toBeLessThan(1000)
expect(seen.area.maxZ).toBeGreaterThan(1000)
expect(seen.area.maxX).toBeLessThan(FIELD_BLOCKS)
})
it('reads the height of every kind of ground in view', () => {
const seen = groundInView(lookDownFrom(new Vector3(3000, 400, 1400), new Vector3(3000, GROUND, 1000)), CEILING, drawn)!
expect(new Set(seen.heights)).toEqual(new Set([GROUND, GROUND + 10]))
})
it('sees no ground over where nothing is drawn, or when looking at the sky', () => {
expect(groundInView(lookDownFrom(new Vector3(9000, 400, 1400), new Vector3(9000, GROUND, 1000)), CEILING, drawn)).toBeNull()
expect(groundInView(lookDownFrom(new Vector3(1000, 400, 1400), new Vector3(1000, 900, 1000)), CEILING, drawn)).toBeNull()
})
})
@@ -0,0 +1,66 @@
import { Ray, Vector3 } from 'three'
import type { WorldRect } from '../bridge/BridgeClient'
import type { SightView } from './cameraSight'
import { marchOntoSurface } from './surfaceMarch'
/** Where the ground drawn so far stands: over a block, what the sky sees there, and the ground under any water. Null where nothing is known. */
export interface DrawnGround {
surfaceTopOver(worldX: number, worldZ: number): number | null
groundTopOver(worldX: number, worldZ: number): number | null
}
/** The ground the camera looks at: the box around it, and the height of the ground at each spot looked at. */
export interface GroundInView {
area: WorldRect
heights: number[]
}
// The spots are laid across the longer side of the view, as many along the shorter side as keeps them evenly apart.
const SPOTS_ALONG_LONGER_SIDE = 32
const NDC_MIDDLE_DEPTH = 0.5
const NDC_SPAN = 2
const SMALLEST_AREA_SIDE_BLOCKS = 1
/**
* What the camera sees of {@code ground}: rays through an even grid of spots on the screen, each met where it comes
* down onto the ground, and the box around the places they meet. Null when no ray meets any ground.
*
* @param ceilingY the height above which no ground stands
*/
export function groundInView(view: SightView, ceilingY: number, ground: DrawnGround): GroundInView | null {
const { camera } = view
camera.updateMatrixWorld()
const eye = camera.getWorldPosition(new Vector3())
const longer = Math.max(view.width, view.height)
const spotsAcross = Math.max(1, Math.round((SPOTS_ALONG_LONGER_SIDE * view.width) / longer))
const spotsDown = Math.max(1, Math.round((SPOTS_ALONG_LONGER_SIDE * view.height) / longer))
const heights: number[] = []
let [minX, minZ, maxX, maxZ] = [Infinity, Infinity, -Infinity, -Infinity]
for (let spotZ = 0; spotZ < spotsDown; spotZ++) {
for (let spotX = 0; spotX < spotsAcross; spotX++) {
const through = new Vector3(centreOf(spotX, spotsAcross), -centreOf(spotZ, spotsDown), NDC_MIDDLE_DEPTH).unproject(camera)
const ray = new Ray(eye, through.sub(eye).normalize())
const hit = marchOntoSurface(ray, camera.far, ceilingY, (x, z) => ground.surfaceTopOver(x, z))
const groundTop = hit === null ? null : ground.groundTopOver(hit.x, hit.z)
if (hit === null || groundTop === null) {
continue
}
heights.push(groundTop - 1)
minX = Math.min(minX, hit.x)
maxX = Math.max(maxX, hit.x)
minZ = Math.min(minZ, hit.z)
maxZ = Math.max(maxZ, hit.z)
}
}
if (heights.length === 0) {
return null
}
return {
area: { minX, minZ, maxX: Math.max(maxX, minX + SMALLEST_AREA_SIDE_BLOCKS), maxZ: Math.max(maxZ, minZ + SMALLEST_AREA_SIDE_BLOCKS) },
heights
}
}
function centreOf(spot: number, spots: number): number {
return -1 + ((spot + 0.5) * NDC_SPAN) / spots
}
@@ -163,6 +163,26 @@ describe('terrain stream', () => {
expect(stream.content.surfaceAlong!(ray, 1000)!.y).toBeCloseTo(71, 3)
})
it('reads the height of the ground the camera looks at once it is drawn, and tells when the view may have changed', async () => {
const { stream, camera, moved } = setUp()
const sightChanges = vi.fn()
stream.onSightChanged(sightChanges)
stream.restyle(flatStyle)
expect(stream.groundInView()).toBeNull()
stream.showLayer({ name: 'one', height: 70, gate: open })
await settle()
expect(sightChanges).toHaveBeenCalled()
const seen = stream.groundInView()!
expect(new Set(seen.heights)).toEqual(new Set([70]))
expect(seen.area.maxX).toBeGreaterThan(seen.area.minX)
camera.position.set(40_000, 664, 360)
camera.lookAt(new Vector3(40_000, 64, 0))
moved()
await settle()
expect(stream.groundInView()!.area.minX).toBeGreaterThan(seen.area.maxX)
})
it('stops drawing when it is let go', async () => {
const { stream, stopFollowing, requested } = setUp()
stream.restyle(flatStyle)
+27 -3
View File
@@ -2,6 +2,8 @@ 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 type { ColumnField } from './columnField'
import { groundInView, type GroundInView } from './groundInView'
import { marchOntoSurface } from './surfaceMarch'
import { planCover, type Cover, type DrawnTile, type TileState } from './terrainCover'
import { buildTerrainMesh, type TerrainMesh, type TerrainSurface } from './terrainMesh'
@@ -55,6 +57,7 @@ export class TerrainStream<Tile, Layer> {
private readonly group = new Group()
private readonly store: TileStore<Tile, Layer, never>
private readonly drawn = new Map<string, DrawnMesh<Tile>>()
private readonly sightListeners = new Set<() => void>()
private standIns = new Map<string, Tile>()
private layer: Layer | null = null
private style: TerrainStyle<Tile> | null = null
@@ -69,7 +72,7 @@ export class TerrainStream<Tile, Layer> {
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)),
surfaceAlong: (ray, reach) => marchOntoSurface(ray, reach, (this.style?.topY ?? 0) + ABOVE_TOP_BLOCKS, (x, z) => this.finestTopOver(x, z, (field) => field.surfaceTopOver(x, z))),
follow: (camera) => this.follow(camera)
}
}
@@ -85,6 +88,23 @@ export class TerrainStream<Tile, Layer> {
this.replan()
}
/** Tells the listener whenever what the camera sees may have changed: it moved, or ground arrived; returns how to stop. */
onSightChanged(listener: () => void): () => void {
this.sightListeners.add(listener)
return () => this.sightListeners.delete(listener)
}
/** The ground the camera looks at now, or null while none is drawn there. */
groundInView(): GroundInView | null {
if (this.camera === null || this.style === null) {
return null
}
return groundInView(this.camera.view(), this.style.topY + ABOVE_TOP_BLOCKS, {
surfaceTopOver: (x, z) => this.finestTopOver(x, z, (field) => field.surfaceTopOver(x, z)),
groundTopOver: (x, z) => this.finestTopOver(x, z, (field) => field.groundTopOver(x, z))
})
}
/** Draws the tiles another way, without sampling them again. */
restyle(style: TerrainStyle<Tile>): void {
this.style = style
@@ -94,6 +114,7 @@ export class TerrainStream<Tile, Layer> {
dispose(): void {
this.disposed = true
this.sightListeners.clear()
if (this.continuation !== null) {
clearTimeout(this.continuation)
}
@@ -123,6 +144,7 @@ export class TerrainStream<Tile, Layer> {
this.store.want(cover.wanted.map(addressOf), layer)
this.draw(cover, layer, this.style)
this.reportPending()
this.sightListeners.forEach((listener) => listener())
}
private stateOf(tile: TerrainTile, layer: Layer): TileState {
@@ -213,9 +235,11 @@ export class TerrainStream<Tile, Layer> {
}
}
private surfaceTopOver(worldX: number, worldZ: number): number | null {
// The finest drawn tile that knows the block answers; coarser ones have holes where finer ones are drawn.
private finestTopOver(worldX: number, worldZ: number, topOf: (field: ColumnField) => number | null): 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
const field = this.drawn.get(tileKey(tileContaining(worldX, worldZ, level)))?.mesh.field
const top = field === undefined ? null : topOf(field)
if (top !== null) {
return top
}
+39 -20
View File
@@ -4,47 +4,66 @@ import type { Share } from '../map/census'
import type { Highlight } from '../map/tileStyle'
import { hexColor } from './colors'
const ROW = 'flex h-[26px] w-full items-center gap-2 rounded-md px-2.5 text-left'
/** What highlighting does in a view that can highlight. */
export interface LegendSelection {
highlight: Highlight | null
onSelect(subject: Highlight): void
}
interface LegendProps {
title: string
shares: Share[]
highlight: Highlight | null
onSelect(subject: Highlight): void
/** Absent in a view with nothing to highlight, such as the 3D world, where the legend only lists. */
selection?: LegendSelection
/** What to say while there is nothing to list. */
emptyText?: string
className?: string
}
/** What is on screen and how much of it each covers; clicking one highlights it on the map. */
export function Legend({ title, shares, highlight, onSelect, className }: LegendProps): React.JSX.Element {
export function Legend({ title, shares, selection, emptyText = 'Drawing the map…', className }: LegendProps): React.JSX.Element {
const sharedNames = namesUsedMoreThanOnce(shares)
return (
<section className={cn('flex min-h-0 flex-col', className)}>
<h2 className="px-4 pt-2.5 pb-1.5 text-[11px] font-semibold text-muted-foreground">{title}</h2>
<ScrollArea className="min-h-0 flex-1">
<ul className="px-1.5 pb-1">
{shares.length === 0 && <li className="px-2.5 py-1 text-muted-foreground">Drawing the map…</li>}
{shares.length === 0 && <li className="px-2.5 py-1 text-muted-foreground">{emptyText}</li>}
{shares.map((share) => {
const selected = highlight !== null && highlight.kind === share.subject.kind && highlight.key === share.subject.key
const row = (
<>
<span className="size-3 shrink-0 rounded-[3px]" style={{ backgroundColor: hexColor(share.color) }} />
<span className="flex min-w-0 flex-1 items-baseline gap-1.5">
<span className={cn('truncate', sharedNames.has(share.subject.name) && 'max-w-[60%] shrink-0')}>{share.subject.name}</span>
{sharedNames.has(share.subject.name) && (
<span className="min-w-0 truncate text-[11.5px] text-secondary-text">{fileName(share.subject.key)}</span>
)}
</span>
<span className="w-[42px] shrink-0 text-right text-[11.5px] text-secondary-text tabular-nums">{percent(share.fraction)}</span>
</>
)
const selected = selection?.highlight != null && selection.highlight.kind === share.subject.kind && selection.highlight.key === share.subject.key
return (
<li key={`${share.subject.kind}:${share.subject.key}`}>
<button
onClick={() => onSelect(share.subject)}
title={share.subject.key}
className={cn('flex h-[26px] w-full items-center gap-2 rounded-md px-2.5 text-left', selected ? 'bg-selection' : 'hover:bg-accent')}
>
<span className="size-3 shrink-0 rounded-[3px]" style={{ backgroundColor: hexColor(share.color) }} />
<span className="flex min-w-0 flex-1 items-baseline gap-1.5">
<span className={cn('truncate', sharedNames.has(share.subject.name) && 'max-w-[60%] shrink-0')}>{share.subject.name}</span>
{sharedNames.has(share.subject.name) && (
<span className="min-w-0 truncate text-[11.5px] text-secondary-text">{fileName(share.subject.key)}</span>
)}
</span>
<span className="w-[42px] shrink-0 text-right text-[11.5px] text-secondary-text tabular-nums">{percent(share.fraction)}</span>
</button>
{selection === undefined ? (
<div className={ROW}>{row}</div>
) : (
<button
onClick={() => selection.onSelect(share.subject)}
title={share.subject.key}
className={cn(ROW, selected ? 'bg-selection' : 'hover:bg-accent')}
>
{row}
</button>
)}
</li>
)
})}
</ul>
</ScrollArea>
<p className="px-4 pt-1.5 pb-2 text-[11px] text-muted-foreground">Click to highlight · Esc clears</p>
{selection !== undefined && <p className="px-4 pt-1.5 pb-2 text-[11px] text-muted-foreground">Click to highlight · Esc clears</p>}
</section>
)
}
+4 -40
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { ThemeChoice } from '../../../shared/bridge'
import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient'
import type { MapHover, MapLabel, Marker, ModuleViewInfo, PickDisplay, PickInspection, ServerUsage, ViewInfo, WorldInfo } from '../bridge/types'
import type { MapHover, MapLabel, Marker, ModuleViewInfo, PickDisplay, ServerUsage, ViewInfo, WorldInfo } from '../bridge/types'
import type { Share } from '../map/census'
import type { MapController, MapStatus, MapToggles } from '../map/MapController'
import type { Highlight } from '../map/tileStyle'
@@ -19,13 +19,12 @@ import { WorldStudio3D } from './WorldStudio3D'
import { actionForKey, isTypingInto, viewForKey, type ShortcutAction } from './shortcuts'
import { StatusBar } from './StatusBar'
import { StudioToolbar } from './StudioToolbar'
import { usePickInspection } from './usePickInspection'
import { ViewList } from './ViewList'
const KEYBOARD_ZOOM_FACTOR = 2 ** 0.25
const ENTITY_POLL_MILLIS = 2000
const NOTICE_MILLIS = 4000
// Measuring the picks in view samples thousands of spots, so it waits for the map to rest.
const INSPECTION_REST_MILLIS = 350
/** The views whose spots a noise picks, which the pick inspector explains. */
const PICK_VIEWS = new Set(['biomes', 'regions'])
@@ -273,18 +272,15 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
{inspectsPicks && (
<PickInspector
title={previewName ?? view.label}
picksLabel={viewId === 'regions' && layer.preview === null ? 'Regions' : 'Biomes'}
inspection={inspection}
display={pickDisplay}
onDisplay={setPickDisplay}
display={{ picksLabel: viewId === 'regions' && layer.preview === null ? 'Regions' : 'Biomes', value: pickDisplay, onChange: setPickDisplay }}
/>
)}
<Legend
className={inspectsPicks ? 'flex-[3]' : 'flex-1'}
title={legendTitle(layer)}
shares={shares}
highlight={highlight}
onSelect={(subject) => setHighlight((current) => (sameSubject(current, subject) ? null : subject))}
selection={{ highlight, onSelect: (subject) => setHighlight((current) => (sameSubject(current, subject) ? null : subject)) }}
/>
</aside>
</>
@@ -381,38 +377,6 @@ function usePreviewableRegions(client: BridgeClient, packRevision: number): MapL
return regions
}
/**
* Measures how the noise picks what the view shows, once the map has rested on an area for a moment; the last
* measurement stays up until the next one arrives, so panning does not blank the panel.
*/
function usePickInspection(
client: BridgeClient,
layer: MapLayerQuery,
area: WorldRect | null,
enabled: boolean,
packRevision: number
): PickInspection | null {
const [inspection, setInspection] = useState<PickInspection | null>(null)
useEffect(() => setInspection(null), [layer, packRevision])
useEffect(() => {
if (!enabled || area === null) {
return
}
const stop = new AbortController()
const timer = window.setTimeout(() => {
client
.picks(layer, area, stop.signal)
.then(setInspection)
.catch(() => undefined)
}, INSPECTION_REST_MILLIS)
return () => {
window.clearTimeout(timer)
stop.abort()
}
}, [client, layer, area, enabled, packRevision])
return inspection
}
/** Players, usage and hotloads from the server; the first world event only says the world runs, which is known. */
function useServerEvents(
client: BridgeClient,
@@ -9,45 +9,53 @@ import { NoiseChart, percent } from './NoiseChart'
// The chosen display reads like the toolbar's switched-on toggles.
const DISPLAY_ITEM = 'h-7 text-[12px] data-[state=on]:bg-selection data-[state=on]:text-foreground'
/** How the map draws the picks, for a view that recolours its tiles. */
export interface PickDisplayChoice {
/** What the map shows when it draws the picks: "Regions" or "Biomes". */
picksLabel: string
value: PickDisplay
onChange(display: PickDisplay): void
}
interface PickInspectorProps {
/** What is inspected: "Regions", "Biomes", or the previewed region's name. */
title: string
/** What the map shows when it draws the picks: "Regions" or "Biomes". */
picksLabel: string
/** The latest measurement of the view; null until the first one arrives. */
inspection: PickInspection | null
display: PickDisplay
onDisplay(display: PickDisplay): void
/** Absent in a view that draws no map tiles, such as the 3D world. */
display?: PickDisplayChoice
}
/**
* How noise picks the regions or biomes in view, measured against what is in view, with a switch for how the map
* draws the picks (v3e PickInspectorPanel).
*/
export function PickInspector({ title, picksLabel, inspection, display, onDisplay }: PickInspectorProps): React.JSX.Element {
export function PickInspector({ title, inspection, display }: PickInspectorProps): React.JSX.Element {
return (
<section className="flex min-h-0 flex-[7] flex-col border-b">
<header className="px-4 pt-2.5 pb-2.5">
<h2 className="truncate text-[13px] font-semibold">{title}</h2>
<p className="truncate text-[11.5px] text-secondary-text">{inspection?.detail ?? 'Measuring what is in view…'}</p>
<ToggleGroup
type="single"
variant="outline"
size="sm"
className="mt-2 w-full"
value={display}
onValueChange={(value) => value !== '' && onDisplay(value as PickDisplay)}
>
<ToggleGroupItem value="picks" className={DISPLAY_ITEM}>
{picksLabel}
</ToggleGroupItem>
<ToggleGroupItem value="noise" className={DISPLAY_ITEM}>
Noise
</ToggleGroupItem>
<ToggleGroupItem value="both" className={DISPLAY_ITEM}>
Both
</ToggleGroupItem>
</ToggleGroup>
{display !== undefined && (
<ToggleGroup
type="single"
variant="outline"
size="sm"
className="mt-2 w-full"
value={display.value}
onValueChange={(value) => value !== '' && display.onChange(value as PickDisplay)}
>
<ToggleGroupItem value="picks" className={DISPLAY_ITEM}>
{display.picksLabel}
</ToggleGroupItem>
<ToggleGroupItem value="noise" className={DISPLAY_ITEM}>
Noise
</ToggleGroupItem>
<ToggleGroupItem value="both" className={DISPLAY_ITEM}>
Both
</ToggleGroupItem>
</ToggleGroup>
)}
</header>
<ScrollArea className="min-h-0 flex-1 border-t">
<div className="px-4 pb-2">{inspection !== null && <Sections sections={inspection.sections} />}</div>
@@ -1,13 +1,18 @@
import { useEffect, useMemo, useState } from 'react'
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
import type { BridgeClient, WorldRect } from '../bridge/BridgeClient'
import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient'
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 { MapTerrain, type MapTerrainColoring } from '../scene/mapTerrain'
import { focusAround, type TerrainStyle } from '../scene/terrainStream'
import { TILE_COLUMNS } from '../scene/terrainTiles'
import { Legend } from './Legend'
import { PickInspector } from './PickInspector'
import { SceneViewport } from './SceneViewport'
import { useTerrainStream } from './useTerrainStream'
import { usePickInspection } from './usePickInspection'
import { useGroundInView, useTerrainStream } from './useTerrainStream'
const NUMBER = new Intl.NumberFormat('en-US')
// The map's coarsest tiles are 4096 blocks a pixel, which is level 12.
@@ -26,7 +31,10 @@ interface WorldStudio3DProps {
tell(message: string): void
}
/** The terrain around where the map looked, in 3D and without an edge, 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, beside how
* the noise picks the biomes or regions the camera sees, or how much of that ground lies at each 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])
@@ -44,7 +52,13 @@ export function WorldStudio3D({ client, world, mapArea, packRevision, onSummary,
}),
[coloring, world.fluidHeight, world.minY, world.height]
)
const { content, pending } = useTerrainStream(source, COARSEST_LEVEL, focus, layer, style, tell)
const { content, pending, stream } = useTerrainStream(source, COARSEST_LEVEL, focus, layer, style, tell)
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 area = useAreaOf(ground)
const inspection = usePickInspection(client, pickLayer, area, inspectsPicks, packRevision)
useEffect(() => {
onSummary(`Around ${NUMBER.format(centre.x)}, ${NUMBER.format(centre.z)}`)
@@ -52,35 +66,53 @@ export function WorldStudio3D({ client, world, mapArea, packRevision, onSummary,
}, [centre, onSummary])
return (
<div className="relative min-w-0 flex-1">
<SceneViewport content={content} framing={content} />
<ToggleGroup
type="single"
variant="outline"
size="sm"
className="absolute top-3 left-3 bg-card/90"
value={coloring}
onValueChange={(value) => value !== '' && setColoring(value as MapTerrainColoring)}
>
<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>
{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>
)}
</div>
<>
<div className="relative min-w-0 flex-1">
<SceneViewport content={content} framing={content} />
<ToggleGroup
type="single"
variant="outline"
size="sm"
className="absolute top-3 left-3 bg-card/90"
value={coloring}
onValueChange={(value) => value !== '' && setColoring(value as MapTerrainColoring)}
>
<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>
{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>
)}
</div>
<aside className="flex w-[250px] shrink-0 flex-col border-l bg-card">
{inspectsPicks ? (
<PickInspector title={coloring === 'regions' ? 'Regions' : 'Biomes'} inspection={inspection} />
) : (
<Legend title="Heights in view" shares={heightShares} emptyText="Looking at the ground…" className="flex-1" />
)}
</aside>
</>
)
}
// The same box is the same area, so the measurement is not asked for again while only the heights in it change.
function useAreaOf(ground: GroundInView | null): WorldRect | null {
const minX = ground?.area.minX
const minZ = ground?.area.minZ
const maxX = ground?.area.maxX
const maxZ = ground?.area.maxZ
return useMemo(() => (minX === undefined || minZ === undefined || maxX === undefined || maxZ === undefined ? null : { minX, minZ, maxX, maxZ }), [minX, minZ, maxX, maxZ])
}
function centreOf(area: WorldRect | null): { x: number; z: number } {
if (area === null) {
return { x: 0, z: 0 }
@@ -0,0 +1,38 @@
import { useEffect, useState } from 'react'
import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient'
import type { PickInspection } from '../bridge/types'
// Measuring the picks in view samples thousands of spots, so it waits for the view to rest.
const INSPECTION_REST_MILLIS = 350
/**
* Measures how the noise picks what the view shows, once the view has rested on an area for a moment; the last
* measurement stays up until the next one arrives, so panning does not blank the panel.
*/
export function usePickInspection(
client: BridgeClient,
layer: MapLayerQuery,
area: WorldRect | null,
enabled: boolean,
packRevision: number
): PickInspection | null {
const [inspection, setInspection] = useState<PickInspection | null>(null)
useEffect(() => setInspection(null), [layer, packRevision])
useEffect(() => {
if (!enabled || area === null) {
return
}
const stop = new AbortController()
const timer = window.setTimeout(() => {
client
.picks(layer, area, stop.signal)
.then(setInspection)
.catch(() => undefined)
}, INSPECTION_REST_MILLIS)
return () => {
window.clearTimeout(timer)
stop.abort()
}
}, [client, layer, area, enabled, packRevision])
return inspection
}
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react'
import type { Box3 } from 'three'
import type { TileSource } from '../map/TileStore'
import type { GroundInView } from '../scene/groundInView'
import { TerrainStream, type TerrainStyle } from '../scene/terrainStream'
import type { ViewportContent } from './SceneViewport'
@@ -17,7 +18,7 @@ export function useTerrainStream<Tile, Layer>(
layer: Layer | null,
style: TerrainStyle<Tile> | null,
tell: (message: string) => void
): { content: ViewportContent | null; pending: number } {
): { content: ViewportContent | null; pending: number; stream: TerrainStream<Tile, Layer> | null } {
const [stream, setStream] = useState<TerrainStream<Tile, Layer> | null>(null)
const [pending, setPending] = useState(0)
const latestTell = useRef(tell)
@@ -42,5 +43,28 @@ export function useTerrainStream<Tile, Layer>(
}
}, [stream, style])
return { content: stream?.content ?? null, pending }
return { content: stream?.content ?? null, pending, stream }
}
// The camera drifts and tiles arrive in bursts; the ground it sees is read once they have rested this long.
const GROUND_REST_MILLIS = 250
/** The ground the camera of a stream looks at, read once the view has rested; the last reading stays until the next one. */
export function useGroundInView<Tile, Layer>(stream: TerrainStream<Tile, Layer> | null): GroundInView | null {
const [ground, setGround] = useState<GroundInView | null>(null)
useEffect(() => {
if (stream === null) {
return
}
let timer: number | undefined
const stopWatching = stream.onSightChanged(() => {
window.clearTimeout(timer)
timer = window.setTimeout(() => setGround(stream.groundInView()), GROUND_REST_MILLIS)
})
return () => {
stopWatching()
window.clearTimeout(timer)
}
}, [stream])
return ground
}