mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 16:54:04 +00:00
Map: pick inspector, noise display and region preview
A right-hand panel shows how the noise picks the regions or biomes in view: a histogram per noise over its pick bands, and each option's weight against its share of the view. The map can draw the picks, the settling noise, or both, and any prepared region can be previewed across the map.
This commit is contained in:
1 parent
e20bf1dd57
commit
674f9756e3
17 files changed
+718
-65
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import type { BridgeConnection } from '../../../shared/bridge'
|
||||
import { decodeTile } from './tileDecoding'
|
||||
import type { MapHover, MapTile, Marker, WorldInfo } from './types'
|
||||
import type { MapHover, MapLabel, MapTile, Marker, PickInspection, WorldInfo } from './types'
|
||||
|
||||
export class BridgeError extends Error {
|
||||
constructor(
|
||||
@@ -13,11 +13,27 @@ export class BridgeError extends Error {
|
||||
|
||||
export interface TileRequest {
|
||||
view: string
|
||||
/** The region the region view previews everywhere, or null for the world as it is. */
|
||||
preview: string | null
|
||||
tileX: number
|
||||
tileZ: number
|
||||
blocksPerPixel: number
|
||||
size: number
|
||||
heights: boolean
|
||||
pickNoise: boolean
|
||||
}
|
||||
|
||||
/** What a map spot or area is asked about: a view, and the region it previews. */
|
||||
export interface MapLayerQuery {
|
||||
view: string
|
||||
preview: string | null
|
||||
}
|
||||
|
||||
export interface WorldRect {
|
||||
minX: number
|
||||
minZ: number
|
||||
maxX: number
|
||||
maxZ: number
|
||||
}
|
||||
|
||||
export interface BridgeEvents {
|
||||
@@ -42,8 +58,19 @@ export class BridgeClient {
|
||||
return this.json('world')
|
||||
}
|
||||
|
||||
hover(view: string, worldX: number, worldZ: number, signal?: AbortSignal): Promise<MapHover> {
|
||||
return this.json(`hover?view=${encodeURIComponent(view)}&x=${worldX}&z=${worldZ}`, { signal })
|
||||
hover(layer: MapLayerQuery, worldX: number, worldZ: number, signal?: AbortSignal): Promise<MapHover> {
|
||||
return this.json(`hover?${layerQuery(layer, { x: String(worldX), z: String(worldZ) })}`, { signal })
|
||||
}
|
||||
|
||||
/** How the noise picks what the layer shows across {@code area}. */
|
||||
picks(layer: MapLayerQuery, area: WorldRect, signal?: AbortSignal): Promise<PickInspection> {
|
||||
const corners = { minX: String(area.minX), minZ: String(area.minZ), maxX: String(area.maxX), maxZ: String(area.maxZ) }
|
||||
return this.json(`picks?${layerQuery(layer, corners)}`, { signal })
|
||||
}
|
||||
|
||||
/** The regions the world picks biomes for, which the region view can preview. */
|
||||
regions(): Promise<MapLabel[]> {
|
||||
return this.json('regions')
|
||||
}
|
||||
|
||||
entities(): Promise<Marker[]> {
|
||||
@@ -61,13 +88,13 @@ export class BridgeClient {
|
||||
}
|
||||
|
||||
async tile(request: TileRequest, signal: AbortSignal): Promise<MapTile> {
|
||||
const query = new URLSearchParams({
|
||||
view: request.view,
|
||||
const query = layerQuery(request, {
|
||||
x: String(request.tileX),
|
||||
z: String(request.tileZ),
|
||||
scale: String(request.blocksPerPixel),
|
||||
size: String(request.size),
|
||||
heights: request.heights ? '1' : '0'
|
||||
heights: request.heights ? '1' : '0',
|
||||
noise: request.pickNoise ? '1' : '0'
|
||||
})
|
||||
const response = await this.fetch(`tile?${query}`, { signal })
|
||||
return decodeTile(await response.arrayBuffer())
|
||||
@@ -120,6 +147,14 @@ export class BridgeClient {
|
||||
}
|
||||
}
|
||||
|
||||
function layerQuery(layer: MapLayerQuery, rest: Record<string, string>): URLSearchParams {
|
||||
const query = new URLSearchParams({ view: layer.view, ...rest })
|
||||
if (layer.preview !== null) {
|
||||
query.set('preview', layer.preview)
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
function dispatch(block: string, events: BridgeEvents): void {
|
||||
let name = 'message'
|
||||
let data = ''
|
||||
|
||||
@@ -8,6 +8,7 @@ interface TileHeader {
|
||||
subjectKind: LabelKind
|
||||
labels: MapLabel[]
|
||||
heights: boolean
|
||||
pickNoise: boolean
|
||||
}
|
||||
|
||||
function aligned(bytes: number): number {
|
||||
@@ -16,7 +17,8 @@ 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 and height grids, each starting on a multiple of 4 bytes. The grids are views into the buffer, not copies.
|
||||
* region, height and pick noise grids, each starting on a multiple of 4 bytes. The grids are views into the buffer,
|
||||
* not copies.
|
||||
*/
|
||||
export function decodeTile(buffer: ArrayBuffer): MapTile {
|
||||
const view = new DataView(buffer)
|
||||
@@ -27,6 +29,7 @@ export function decodeTile(buffer: ArrayBuffer): MapTile {
|
||||
const subjectsAt = aligned(4 + headerLength)
|
||||
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)
|
||||
return {
|
||||
size: header.size,
|
||||
blocksPerPixel: header.blocksPerPixel,
|
||||
@@ -34,7 +37,8 @@ export function decodeTile(buffer: ArrayBuffer): MapTile {
|
||||
labels: header.labels,
|
||||
subjects: new Int16Array(buffer, subjectsAt, cells),
|
||||
regions: new Int16Array(buffer, regionsAt, cells),
|
||||
heights: header.heights ? new Float32Array(buffer, heightsAt, cells) : null
|
||||
heights: header.heights ? new Float32Array(buffer, heightsAt, cells) : null,
|
||||
pickNoise: header.pickNoise ? new Float32Array(buffer, pickNoiseAt, cells) : null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -47,8 +47,8 @@ export interface MapHover {
|
||||
pickPath: PickStep[]
|
||||
}
|
||||
|
||||
/** REGION, BIOME and CHILD were picked by noise; IMAGE_MAP and FOCUS were set without a pick. */
|
||||
export type PickKind = 'REGION' | 'BIOME' | 'CHILD' | 'IMAGE_MAP' | 'FOCUS'
|
||||
/** REGION, BIOME and CHILD were picked by noise; IMAGE_MAP, FOCUS and PREVIEW were set without a pick. */
|
||||
export type PickKind = 'REGION' | 'BIOME' | 'CHILD' | 'IMAGE_MAP' | 'FOCUS' | 'PREVIEW'
|
||||
|
||||
export interface PickStep {
|
||||
kind: PickKind
|
||||
@@ -69,6 +69,40 @@ export interface PickBand {
|
||||
to: number
|
||||
}
|
||||
|
||||
/** How the noise picks what an area of the map shows (MapPickInspection). */
|
||||
export interface PickInspection {
|
||||
detail: string
|
||||
sections: PickSection[]
|
||||
}
|
||||
|
||||
/** The picks on one region's ground; `region` is null in the region view, where the regions themselves are picked. */
|
||||
export interface PickSection {
|
||||
region: MapLabel | null
|
||||
/** How much of the area's picked ground the region holds. */
|
||||
share: number
|
||||
biomeCount: number
|
||||
spreads: PickSpread[]
|
||||
}
|
||||
|
||||
/** One noise in the area: its values in 50 equal steps from 0 to 1, and each option's share of it. */
|
||||
export interface PickSpread {
|
||||
title: string
|
||||
bands: PickBand[]
|
||||
histogram: number[]
|
||||
samples: number
|
||||
rows: PickShare[]
|
||||
}
|
||||
|
||||
/** `weight`: how much of the noise picks the option; `inView`: how much of the area's values do. */
|
||||
export interface PickShare {
|
||||
option: MapLabel
|
||||
weight: number
|
||||
inView: number
|
||||
}
|
||||
|
||||
/** How the region and biome views draw their picks: the labels, the noise that picked them, or the labels by noise. */
|
||||
export type PickDisplay = 'picks' | 'noise' | 'both'
|
||||
|
||||
export interface Marker {
|
||||
label: string
|
||||
worldX: number
|
||||
@@ -89,6 +123,8 @@ export interface MapTile {
|
||||
subjects: Int16Array
|
||||
regions: Int16Array
|
||||
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
|
||||
}
|
||||
|
||||
export const NO_LABEL = -1
|
||||
@@ -0,0 +1,69 @@
|
||||
import * as React from "react"
|
||||
import { type VariantProps } from "class-variance-authority"
|
||||
import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { toggleVariants } from "@/components/ui/toggle"
|
||||
|
||||
const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({
|
||||
size: "default",
|
||||
variant: "default",
|
||||
})
|
||||
|
||||
function ToggleGroup({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
|
||||
VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<ToggleGroupPrimitive.Root
|
||||
data-slot="toggle-group"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider value={{ variant, size }}>
|
||||
{children}
|
||||
</ToggleGroupContext.Provider>
|
||||
</ToggleGroupPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ToggleGroupItem({
|
||||
className,
|
||||
children,
|
||||
variant,
|
||||
size,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
|
||||
VariantProps<typeof toggleVariants>) {
|
||||
const context = React.useContext(ToggleGroupContext)
|
||||
|
||||
return (
|
||||
<ToggleGroupPrimitive.Item
|
||||
data-slot="toggle-group-item"
|
||||
data-variant={context.variant || variant}
|
||||
data-size={context.size || size}
|
||||
className={cn(
|
||||
toggleVariants({
|
||||
variant: context.variant || variant,
|
||||
size: context.size || size,
|
||||
}),
|
||||
"min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</ToggleGroupPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
export { ToggleGroup, ToggleGroupItem }
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { BridgeClient, WorldRect } from '../bridge/BridgeClient'
|
||||
import { gridIndex } from '../bridge/tileDecoding'
|
||||
import { NO_LABEL, type MapLabel, type Marker, type WorldInfo } from '../bridge/types'
|
||||
import { NO_LABEL, type MapLabel, type Marker, type PickDisplay, type WorldInfo } from '../bridge/types'
|
||||
import { countShares, type PlacedTile, type Share } from './census'
|
||||
import { bandIndexOf, HEIGHT_BANDS } from './heightColors'
|
||||
import type { Highlight, TileStyle } from './tileStyle'
|
||||
@@ -33,9 +33,14 @@ export interface MapStatus {
|
||||
export interface MapListener {
|
||||
onStatus(status: MapStatus): void
|
||||
onShares(shares: Share[]): void
|
||||
/** The world area on screen, reported with the shares: a few times a second while it moves, and once at rest. */
|
||||
onArea(area: WorldRect): void
|
||||
onError(message: string): void
|
||||
}
|
||||
|
||||
/** The views whose spots a noise picks, so they can draw that noise. */
|
||||
const PICK_NOISE_VIEWS = new Set(['biomes', 'regions'])
|
||||
|
||||
/** What the map shows at a spot, read from the tiles already drawn. */
|
||||
export interface SpotSubjects {
|
||||
subject: Highlight | null
|
||||
@@ -72,6 +77,7 @@ export class MapController {
|
||||
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 pickDisplay: PickDisplay = 'picks'
|
||||
private highlight: Highlight | null = null
|
||||
private players: Marker[] = []
|
||||
private entities: Marker[] = []
|
||||
@@ -89,7 +95,7 @@ export class MapController {
|
||||
private readonly listener: MapListener
|
||||
) {
|
||||
this.context = canvas.getContext('2d')!
|
||||
this.layer = { view, heights: this.needsHeights(view, this.toggles), revision: 0 }
|
||||
this.layer = { view, preview: null, heights: this.needsHeights(view, this.toggles), pickNoise: false, revision: 0 }
|
||||
this.store = new TileStore(client, world.tileSize, () => this.redraw(), (message) => listener.onError(message))
|
||||
}
|
||||
|
||||
@@ -108,11 +114,29 @@ export class MapController {
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
setView(view: string): void {
|
||||
this.layer = { ...this.layer, view, heights: this.needsHeights(view, this.toggles) }
|
||||
/** Shows a view; the region view previews {@code preview} everywhere when it is not null. */
|
||||
setView(view: string, preview: string | null = null): void {
|
||||
this.layer = {
|
||||
...this.layer,
|
||||
view,
|
||||
preview: view === 'regions' ? preview : null,
|
||||
heights: this.needsHeights(view, this.toggles),
|
||||
pickNoise: this.needsPickNoise(view, this.pickDisplay)
|
||||
}
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
setPickDisplay(display: PickDisplay): void {
|
||||
this.pickDisplay = display
|
||||
this.layer = { ...this.layer, pickNoise: this.needsPickNoise(this.layer.view, display) }
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
// Tiles only carry their pick noise while it is drawn, so drawing the picks alone costs nothing extra.
|
||||
private needsPickNoise(view: string, display: PickDisplay): boolean {
|
||||
return display !== 'picks' && PICK_NOISE_VIEWS.has(view)
|
||||
}
|
||||
|
||||
setToggles(toggles: MapToggles): void {
|
||||
this.toggles = toggles
|
||||
this.layer = { ...this.layer, heights: this.needsHeights(this.layer.view, toggles) }
|
||||
@@ -214,7 +238,8 @@ export class MapController {
|
||||
shading: this.toggles.shading,
|
||||
regionBorders: this.toggles.regionBorders,
|
||||
highlight: this.highlight,
|
||||
seaLevel: this.world.fluidHeight
|
||||
seaLevel: this.world.fluidHeight,
|
||||
pickDisplay: this.pickDisplay
|
||||
}
|
||||
}
|
||||
|
||||
@@ -375,9 +400,19 @@ export class MapController {
|
||||
this.censusTimer = window.setTimeout(() => {
|
||||
this.lastCensusMillis = performance.now()
|
||||
this.listener.onShares(this.census(tiles))
|
||||
this.listener.onArea(this.screenArea())
|
||||
}, wait)
|
||||
}
|
||||
|
||||
private screenArea(): WorldRect {
|
||||
return {
|
||||
minX: screenToWorldX(this.view, 0),
|
||||
minZ: screenToWorldZ(this.view, 0),
|
||||
maxX: screenToWorldX(this.view, this.view.width),
|
||||
maxZ: screenToWorldZ(this.view, this.view.height)
|
||||
}
|
||||
}
|
||||
|
||||
private census(tiles: TileAddress[]): Share[] {
|
||||
const placed: PlacedTile[] = []
|
||||
for (const address of tiles) {
|
||||
@@ -387,12 +422,8 @@ export class MapController {
|
||||
placed.push({ tile, worldX: address.tileX * span, worldZ: address.tileZ * span })
|
||||
}
|
||||
}
|
||||
const area = {
|
||||
minimumX: screenToWorldX(this.view, 0),
|
||||
minimumZ: screenToWorldZ(this.view, 0),
|
||||
maximumX: screenToWorldX(this.view, this.view.width),
|
||||
maximumZ: screenToWorldZ(this.view, this.view.height)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,10 @@ import type { TileAddress } from './viewport'
|
||||
/** What one tile request needs besides where the tile is. */
|
||||
export interface TileLayer {
|
||||
view: string
|
||||
/** The region the region view previews everywhere, or null for the world as it is. */
|
||||
preview: string | null
|
||||
heights: boolean
|
||||
pickNoise: boolean
|
||||
/** Bumped when the pack is hotloaded, so older tiles are not used again. */
|
||||
revision: number
|
||||
}
|
||||
@@ -44,7 +47,8 @@ export class TileStore {
|
||||
) {}
|
||||
|
||||
key(address: TileAddress, layer: TileLayer): string {
|
||||
return `${layer.revision}/${layer.view}/${layer.heights}/${address.blocksPerPixel}/${address.tileX}/${address.tileZ}`
|
||||
const parts = [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise]
|
||||
return `${parts.join('/')}/${address.blocksPerPixel}/${address.tileX}/${address.tileZ}`
|
||||
}
|
||||
|
||||
/** The tile if it has arrived, marked as just used. */
|
||||
@@ -118,7 +122,7 @@ export class TileStore {
|
||||
private fetchTile(key: string, address: TileAddress, layer: TileLayer): void {
|
||||
const controller = new AbortController()
|
||||
this.inFlight.set(key, controller)
|
||||
const request = { view: layer.view, ...address, size: this.tileSize, heights: layer.heights }
|
||||
const request = { ...layer, ...address, size: this.tileSize }
|
||||
this.client
|
||||
.tile(request, controller.signal)
|
||||
.then((tile) => this.store(key, tile))
|
||||
@@ -139,7 +143,7 @@ export class TileStore {
|
||||
}
|
||||
|
||||
private store(key: string, tile: MapTile): void {
|
||||
const bytes = tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + tile.size * tile.size * 4
|
||||
const bytes = tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + tile.size * tile.size * 4
|
||||
this.tiles.set(key, { tile, bytes, lastUsed: ++this.useClock, picture: null, pictureStyle: '' })
|
||||
this.storedBytes += bytes
|
||||
this.evictOldest()
|
||||
|
||||
@@ -9,7 +9,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 }
|
||||
const FLAT: TileStyle = { byHeight: 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 {
|
||||
@@ -25,19 +25,23 @@ function splitTile(size = 4): MapTile {
|
||||
labels: [PLAINS, DESERT, WARM],
|
||||
subjects,
|
||||
regions: new Int16Array(cells).fill(2),
|
||||
heights: new Float32Array(cells).fill(70)
|
||||
heights: new Float32Array(cells).fill(70),
|
||||
pickNoise: null
|
||||
}
|
||||
}
|
||||
|
||||
/** A tile as the bridge sends it: u32 header length, JSON header, aligned grids. */
|
||||
function encode(size: number, withHeights: boolean): ArrayBuffer {
|
||||
const header = new TextEncoder().encode(JSON.stringify({ size, blocksPerPixel: 2, subjectKind: 'BIOME', labels: [PLAINS], heights: withHeights }))
|
||||
function encode(size: number, withHeights: boolean, withPickNoise = false): ArrayBuffer {
|
||||
const header = new TextEncoder().encode(
|
||||
JSON.stringify({ size, blocksPerPixel: 2, subjectKind: 'BIOME', labels: [PLAINS], heights: withHeights, pickNoise: withPickNoise })
|
||||
)
|
||||
const cells = (size + 2) ** 2
|
||||
const align = (bytes: number): number => Math.ceil(bytes / 4) * 4
|
||||
const subjectsAt = align(4 + header.length)
|
||||
const regionsAt = align(subjectsAt + cells * 2)
|
||||
const heightsAt = align(regionsAt + cells * 2)
|
||||
const buffer = new ArrayBuffer(heightsAt + (withHeights ? cells * 4 : 0))
|
||||
const pickNoiseAt = heightsAt + (withHeights ? cells * 4 : 0)
|
||||
const buffer = new ArrayBuffer(pickNoiseAt + (withPickNoise ? cells * 4 : 0))
|
||||
new DataView(buffer).setUint32(0, header.length, true)
|
||||
new Uint8Array(buffer, 4).set(header)
|
||||
new Int16Array(buffer, subjectsAt, cells).fill(0)
|
||||
@@ -45,6 +49,9 @@ function encode(size: number, withHeights: boolean): ArrayBuffer {
|
||||
if (withHeights) {
|
||||
new Float32Array(buffer, heightsAt, cells).fill(81.5)
|
||||
}
|
||||
if (withPickNoise) {
|
||||
new Float32Array(buffer, pickNoiseAt, cells).fill(0.25)
|
||||
}
|
||||
return buffer
|
||||
}
|
||||
|
||||
@@ -63,6 +70,37 @@ describe('tile decoding', () => {
|
||||
it('has no heights when the header says so', () => {
|
||||
expect(decodeTile(encode(3, false)).heights).toBeNull()
|
||||
})
|
||||
|
||||
it('reads the pick noise after the heights, or in their place without them', () => {
|
||||
expect(decodeTile(encode(3, true, true)).pickNoise?.[24]).toBe(0.25)
|
||||
expect(decodeTile(encode(3, false, true)).pickNoise?.[0]).toBe(0.25)
|
||||
expect(decodeTile(encode(3, true)).pickNoise).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('pick noise', () => {
|
||||
function noisyTile(noise: number): MapTile {
|
||||
const tile = splitTile()
|
||||
return { ...tile, pickNoise: new Float32Array(tile.subjects.length).fill(noise) }
|
||||
}
|
||||
|
||||
it('draws the bare noise from dark to white', () => {
|
||||
const pixels = stylePixels(noisyTile(1), { ...FLAT, pickDisplay: 'noise' })
|
||||
|
||||
expect([pixels[0], pixels[1], pixels[2]]).toEqual([255, 255, 255])
|
||||
})
|
||||
|
||||
it('draws the picks darker where their noise is lower', () => {
|
||||
const pixels = stylePixels(noisyTile(0), { ...FLAT, pickDisplay: 'both' })
|
||||
|
||||
expect(pixels[1]).toBe(Math.floor(255 * 0.3))
|
||||
})
|
||||
|
||||
it('leaves a spot nothing picked in its own colour', () => {
|
||||
const pixels = stylePixels(noisyTile(Number.NaN), { ...FLAT, pickDisplay: 'noise' })
|
||||
|
||||
expect([pixels[0], pixels[1], pixels[2]]).toEqual([0, 255, 0])
|
||||
})
|
||||
})
|
||||
|
||||
describe('height colours', () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { gridIndex } from '../bridge/tileDecoding'
|
||||
import { NO_LABEL, type MapTile } from '../bridge/types'
|
||||
import { NO_LABEL, type MapTile, type PickDisplay } from '../bridge/types'
|
||||
import { bandIndexOf, blend, heightColor } from './heightColors'
|
||||
|
||||
/** What a highlight picks out: a biome or region by key, or a height band in the height view. */
|
||||
@@ -16,11 +16,13 @@ export interface TileStyle {
|
||||
regionBorders: boolean
|
||||
highlight: Highlight | null
|
||||
seaLevel: number
|
||||
/** How tiles that carry their pick noise draw it. */
|
||||
pickDisplay: PickDisplay
|
||||
}
|
||||
|
||||
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}`
|
||||
return `${style.byHeight}|${style.shading}|${style.regionBorders}|${highlight}|${style.seaLevel}|${style.pickDisplay}`
|
||||
}
|
||||
|
||||
const UNKNOWN_SUBJECT = 0x5a5c62
|
||||
@@ -43,6 +45,10 @@ const HIGHLIGHT_EDGE = 0xffffff
|
||||
const HIGHLIGHT_EDGE_STRENGTH = 0.55
|
||||
const REGION_BORDER = 0x101114
|
||||
const REGION_BORDER_STRENGTH = 0.6
|
||||
const NOISE_LOW = 0x050505
|
||||
const NOISE_HIGH = 0xffffff
|
||||
// Picks drawn by their noise keep some colour where the noise is low, so they still read as the pick.
|
||||
const DARKEST_PICK_SHADE = 0.3
|
||||
|
||||
/** The tile's pixels as RGBA, as {@code style} draws them (v3e MapTile.styledPixels). */
|
||||
export function stylePixels(tile: MapTile, style: TileStyle): Uint8ClampedArray<ArrayBuffer> {
|
||||
@@ -50,12 +56,17 @@ export function stylePixels(tile: MapTile, style: TileStyle): Uint8ClampedArray<
|
||||
const pixels = new Uint8ClampedArray(size * size * 4)
|
||||
const colors = tile.labels.map((label) => label.color)
|
||||
const byHeight = style.byHeight && heights !== null
|
||||
const shading = (style.shading || byHeight) && heights !== null
|
||||
const pickNoise = style.pickDisplay === 'picks' ? 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 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])
|
||||
if (pickNoise !== null) {
|
||||
color = byNoise(color, pickNoise[cell], style.pickDisplay)
|
||||
}
|
||||
if (shading) {
|
||||
color = shade(tile, heights, cell, color, style.seaLevel)
|
||||
}
|
||||
@@ -79,6 +90,15 @@ function labelColor(colors: number[], index: number): number {
|
||||
return index === NO_LABEL ? UNKNOWN_SUBJECT : colors[index]
|
||||
}
|
||||
|
||||
// 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)) {
|
||||
return color
|
||||
}
|
||||
const value = Math.min(1, Math.max(0, noise))
|
||||
return display === 'noise' ? blend(NOISE_LOW, NOISE_HIGH, value) : scale(color, DARKEST_PICK_SHADE + (1 - DARKEST_PICK_SHADE) * value)
|
||||
}
|
||||
|
||||
// Lit from the north west like a relief map, so slopes read as hills and valleys at a glance.
|
||||
function shade(tile: MapTile, heights: Float32Array, cell: number, color: number, seaLevel: number): number {
|
||||
const row = tile.size + 2
|
||||
|
||||
@@ -10,6 +10,8 @@ interface HoverCardProps {
|
||||
hover: MapHover
|
||||
point: CanvasPoint
|
||||
viewId: string
|
||||
/** The region view fills the map with one region's biomes, so the spot is described by its previewed biome. */
|
||||
previewing: boolean
|
||||
detailed: boolean
|
||||
minY: number
|
||||
}
|
||||
@@ -24,7 +26,7 @@ interface Row {
|
||||
}
|
||||
|
||||
/** The spot under the cursor: its biome and ground, and with Shift held, the rest of what the server knows. */
|
||||
export function HoverCard({ hover, point, viewId, detailed, minY }: HoverCardProps): React.JSX.Element {
|
||||
export function HoverCard({ hover, point, viewId, previewing, detailed, minY }: HoverCardProps): React.JSX.Element {
|
||||
const card = useRef<HTMLDivElement>(null)
|
||||
const [position, setPosition] = useState({ left: point.x + CURSOR_GAP_PIXELS, top: point.y + CURSOR_GAP_PIXELS })
|
||||
|
||||
@@ -42,7 +44,8 @@ export function HoverCard({ hover, point, viewId, detailed, minY }: HoverCardPro
|
||||
})
|
||||
}, [point, hover, detailed])
|
||||
|
||||
const subject = viewId === 'caveBiomes' ? hover.caveBiome : viewId === 'regions' ? hover.region : hover.biome
|
||||
const labelsRegions = viewId === 'regions' && !previewing
|
||||
const subject = viewId === 'caveBiomes' ? hover.caveBiome : labelsRegions ? hover.region : hover.biome
|
||||
const groups = detailed ? detailGroups(hover, viewId) : []
|
||||
const parent = replacedParent(hover.pickPath)
|
||||
return (
|
||||
@@ -51,7 +54,7 @@ export function HoverCard({ hover, point, viewId, detailed, minY }: HoverCardPro
|
||||
className="pointer-events-none absolute z-10 w-80 rounded-[10px] border border-overlay-border bg-popover px-3.5 py-3 text-popover-foreground shadow-xl backdrop-blur-sm"
|
||||
style={position}
|
||||
>
|
||||
<Header subject={subject} region={viewId === 'regions' ? null : hover.region} />
|
||||
<Header subject={subject} region={labelsRegions ? null : hover.region} />
|
||||
{parent !== null && <p className="mt-0.5 truncate text-[12px] text-secondary-text">child of {parent}</p>}
|
||||
<p className="mt-0.5 truncate text-[12px] text-secondary-text tabular-nums">{ground(hover, minY)}</p>
|
||||
<PickRows path={hover.pickPath} />
|
||||
|
||||
@@ -9,13 +9,14 @@ interface LegendProps {
|
||||
shares: Share[]
|
||||
highlight: Highlight | null
|
||||
onSelect(subject: Highlight): void
|
||||
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 }: LegendProps): React.JSX.Element {
|
||||
export function Legend({ title, shares, highlight, onSelect, className }: LegendProps): React.JSX.Element {
|
||||
const sharedNames = namesUsedMoreThanOnce(shares)
|
||||
return (
|
||||
<aside className="flex w-[250px] shrink-0 flex-col border-l bg-card">
|
||||
<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">
|
||||
@@ -44,7 +45,7 @@ export function Legend({ title, shares, highlight, onSelect }: LegendProps): Rea
|
||||
</ul>
|
||||
</ScrollArea>
|
||||
<p className="px-4 pt-1.5 pb-2 text-[11px] text-muted-foreground">Click to highlight · Esc clears</p>
|
||||
</aside>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@ export function MapCanvas(props: MapCanvasProps): React.JSX.Element {
|
||||
const map = new MapController(canvas, client, world, viewId, {
|
||||
onStatus: (status) => latest.current.listener.onStatus(status),
|
||||
onShares: (shares) => latest.current.listener.onShares(shares),
|
||||
onArea: (area) => latest.current.listener.onArea(area),
|
||||
onError: (message) => latest.current.listener.onError(message)
|
||||
})
|
||||
controllerRef.current = map
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { ThemeChoice } from '../../../shared/bridge'
|
||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { MapHover, Marker, WorldInfo } from '../bridge/types'
|
||||
import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient'
|
||||
import type { MapHover, MapLabel, Marker, PickDisplay, PickInspection, WorldInfo } from '../bridge/types'
|
||||
import type { Share } from '../map/census'
|
||||
import type { MapController, MapStatus, MapToggles } from '../map/MapController'
|
||||
import type { Highlight } from '../map/tileStyle'
|
||||
@@ -9,6 +9,8 @@ import { HelpDialog } from './HelpDialog'
|
||||
import { HoverCard } from './HoverCard'
|
||||
import { Legend } from './Legend'
|
||||
import { MapCanvas, type CanvasPoint } from './MapCanvas'
|
||||
import { PickInspector } from './PickInspector'
|
||||
import { RegionPreviewList } from './RegionPreviewList'
|
||||
import { actionForKey, viewForKey, type ShortcutAction } from './shortcuts'
|
||||
import { StatusBar } from './StatusBar'
|
||||
import { StudioToolbar } from './StudioToolbar'
|
||||
@@ -17,6 +19,10 @@ 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'])
|
||||
|
||||
interface MapStudioProps {
|
||||
client: BridgeClient
|
||||
@@ -46,7 +52,16 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
const [helpOpen, setHelpOpen] = useState(false)
|
||||
const [notice, setNotice] = useState<string | null>(null)
|
||||
const [connected, setConnected] = useState(true)
|
||||
const [preview, setPreview] = useState<string | null>(null)
|
||||
const [pickDisplay, setPickDisplay] = useState<PickDisplay>('picks')
|
||||
const [area, setArea] = useState<WorldRect | null>(null)
|
||||
const [packRevision, setPackRevision] = useState(0)
|
||||
const view = world.views.find((candidate) => candidate.id === viewId) ?? world.views[0]
|
||||
const layer = useMemo<MapLayerQuery>(() => ({ view: viewId, preview: viewId === 'regions' ? preview : null }), [viewId, preview])
|
||||
const regions = usePreviewableRegions(client, packRevision)
|
||||
const inspectsPicks = PICK_VIEWS.has(viewId)
|
||||
const inspection = usePickInspection(client, layer, area, inspectsPicks, packRevision)
|
||||
const previewName = layer.preview === null ? null : (regions.find((region) => region.key === layer.preview)?.name ?? layer.preview)
|
||||
|
||||
const tell = useCallback((message: string) => setNotice(message), [])
|
||||
|
||||
@@ -58,7 +73,8 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [notice])
|
||||
|
||||
useEffect(() => controller.current?.setView(viewId), [viewId])
|
||||
useEffect(() => controller.current?.setView(layer.view, layer.preview), [layer])
|
||||
useEffect(() => controller.current?.setPickDisplay(pickDisplay), [pickDisplay])
|
||||
useEffect(() => controller.current?.setToggles(toggles), [toggles])
|
||||
useEffect(() => controller.current?.setHighlight(highlight), [highlight])
|
||||
useEffect(() => controller.current?.setMarkers(players, toggles.entities ? entities : []), [players, entities, toggles.entities])
|
||||
@@ -69,15 +85,21 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
}
|
||||
}, [players, toggles.follow])
|
||||
|
||||
useServerEvents(client, controller, setPlayers, tell, setConnected)
|
||||
const packReloaded = useCallback(() => setPackRevision((revision) => revision + 1), [])
|
||||
useServerEvents(client, controller, setPlayers, tell, setConnected, packReloaded)
|
||||
useEntities(client, toggles.entities, setEntities)
|
||||
useHover(client, controller, viewId, pointer, setHover)
|
||||
useHover(client, controller, layer, pointer, setHover)
|
||||
|
||||
const selectView = useCallback((nextViewId: string) => {
|
||||
setViewId(nextViewId)
|
||||
setHighlight(null)
|
||||
}, [])
|
||||
|
||||
const selectPreview = useCallback((regionKey: string | null) => {
|
||||
setPreview(regionKey)
|
||||
setHighlight(null)
|
||||
}, [])
|
||||
|
||||
const toggle = useCallback((name: keyof StudioToggles) => setToggles((current) => ({ ...current, [name]: !current[name] })), [])
|
||||
|
||||
const highlightUnderCursor = useCallback(() => {
|
||||
@@ -181,14 +203,16 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
onDisconnect={onDisconnect}
|
||||
/>
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<ViewList views={world.views} current={viewId} onSelect={selectView} />
|
||||
<ViewList views={world.views} current={viewId} onSelect={selectView}>
|
||||
{viewId === 'regions' && regions.length > 1 && <RegionPreviewList regions={regions} current={layer.preview} onSelect={selectPreview} />}
|
||||
</ViewList>
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<MapCanvas
|
||||
client={client}
|
||||
world={world}
|
||||
viewId={viewId}
|
||||
controllerRef={controller}
|
||||
listener={{ onStatus: setStatus, onShares: setShares, onError: tell }}
|
||||
listener={{ onStatus: setStatus, onShares: setShares, onArea: (next) => setArea((current) => (sameRect(current, next) ? current : next)), onError: tell }}
|
||||
onPointer={setPointer}
|
||||
onDragged={() => setToggles((current) => (current.follow ? { ...current, follow: false } : current))}
|
||||
onTeleport={teleport}
|
||||
@@ -201,7 +225,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
}}
|
||||
/>
|
||||
{pointer !== null && hover !== null && (
|
||||
<HoverCard hover={hover} point={pointer} viewId={viewId} detailed={detailed} minY={world.minY} />
|
||||
<HoverCard hover={hover} point={pointer} viewId={viewId} previewing={layer.preview !== null} detailed={detailed} minY={world.minY} />
|
||||
)}
|
||||
{!connected && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/70">
|
||||
@@ -214,14 +238,26 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Legend
|
||||
title={legendTitle(viewId)}
|
||||
shares={shares}
|
||||
highlight={highlight}
|
||||
onSelect={(subject) => setHighlight((current) => (sameSubject(current, subject) ? null : subject))}
|
||||
/>
|
||||
<aside className="flex w-[250px] shrink-0 flex-col border-l bg-card">
|
||||
{inspectsPicks && (
|
||||
<PickInspector
|
||||
title={previewName ?? view.label}
|
||||
picksLabel={viewId === 'regions' && layer.preview === null ? 'Regions' : 'Biomes'}
|
||||
inspection={inspection}
|
||||
display={pickDisplay}
|
||||
onDisplay={setPickDisplay}
|
||||
/>
|
||||
)}
|
||||
<Legend
|
||||
className={inspectsPicks ? 'flex-[3]' : 'flex-1'}
|
||||
title={legendTitle(layer)}
|
||||
shares={shares}
|
||||
highlight={highlight}
|
||||
onSelect={(subject) => setHighlight((current) => (sameSubject(current, subject) ? null : subject))}
|
||||
/>
|
||||
</aside>
|
||||
</div>
|
||||
<StatusBar viewLabel={view.label} status={status} notice={notice} />
|
||||
<StatusBar viewLabel={previewName === null ? view.label : `${view.label} · ${previewName}`} status={status} notice={notice} />
|
||||
<HelpDialog open={helpOpen} onOpenChange={setHelpOpen} views={world.views} />
|
||||
</div>
|
||||
)
|
||||
@@ -231,11 +267,63 @@ function sameSubject(first: Highlight | null, second: Highlight | null): boolean
|
||||
return first !== null && second !== null && first.kind === second.kind && first.key === second.key
|
||||
}
|
||||
|
||||
function legendTitle(viewId: string): string {
|
||||
if (viewId === 'regions') {
|
||||
function sameRect(first: WorldRect | null, second: WorldRect): boolean {
|
||||
return first !== null && first.minX === second.minX && first.minZ === second.minZ && first.maxX === second.maxX && first.maxZ === second.maxZ
|
||||
}
|
||||
|
||||
function legendTitle(layer: MapLayerQuery): string {
|
||||
if (layer.view === 'regions' && layer.preview === null) {
|
||||
return 'Regions on screen'
|
||||
}
|
||||
return viewId === 'height' ? 'Heights on screen' : 'Biomes on screen'
|
||||
return layer.view === 'height' ? 'Heights on screen' : 'Biomes on screen'
|
||||
}
|
||||
|
||||
/** The regions the region view can preview, read again after the pack reloads. */
|
||||
function usePreviewableRegions(client: BridgeClient, packRevision: number): MapLabel[] {
|
||||
const [regions, setRegions] = useState<MapLabel[]>([])
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
client
|
||||
.regions()
|
||||
.then((found) => active && setRegions(found))
|
||||
.catch(() => undefined)
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [client, packRevision])
|
||||
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 and hotloads from the server; the first world event only says the world runs, which is known. */
|
||||
@@ -244,7 +332,8 @@ function useServerEvents(
|
||||
controller: React.RefObject<MapController | null>,
|
||||
setPlayers: (players: Marker[]) => void,
|
||||
tell: (message: string) => void,
|
||||
setConnected: (connected: boolean) => void
|
||||
setConnected: (connected: boolean) => void,
|
||||
onPackReloaded: () => void
|
||||
): void {
|
||||
useEffect(() => {
|
||||
const stop = new AbortController()
|
||||
@@ -258,6 +347,7 @@ function useServerEvents(
|
||||
}
|
||||
if (running) {
|
||||
controller.current?.refresh()
|
||||
onPackReloaded()
|
||||
tell('Pack reloaded, redrawing')
|
||||
} else {
|
||||
tell('The world stopped')
|
||||
@@ -269,7 +359,7 @@ function useServerEvents(
|
||||
stop.signal
|
||||
)
|
||||
return () => stop.abort()
|
||||
}, [client, controller, setPlayers, tell, setConnected])
|
||||
}, [client, controller, setPlayers, tell, setConnected, onPackReloaded])
|
||||
}
|
||||
|
||||
function useEntities(client: BridgeClient, visible: boolean, setEntities: (entities: Marker[]) => void): void {
|
||||
@@ -297,7 +387,7 @@ function useEntities(client: BridgeClient, visible: boolean, setEntities: (entit
|
||||
function useHover(
|
||||
client: BridgeClient,
|
||||
controller: React.RefObject<MapController | null>,
|
||||
viewId: string,
|
||||
layer: MapLayerQuery,
|
||||
pointer: CanvasPoint | null,
|
||||
setHover: (hover: MapHover | null) => void
|
||||
): void {
|
||||
@@ -309,11 +399,11 @@ function useHover(
|
||||
const spot = controller.current.worldAt(pointer.x, pointer.y)
|
||||
const stop = new AbortController()
|
||||
client
|
||||
.hover(viewId, Math.floor(spot.x), Math.floor(spot.z), stop.signal)
|
||||
.hover(layer, Math.floor(spot.x), Math.floor(spot.z), stop.signal)
|
||||
.then(setHover)
|
||||
.catch(() => undefined)
|
||||
return () => stop.abort()
|
||||
}, [client, controller, viewId, pointer, setHover])
|
||||
}, [client, controller, layer, pointer, setHover])
|
||||
}
|
||||
|
||||
function useKeyboard(
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { useState } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { PickShare, PickSpread } from '../bridge/types'
|
||||
import { hexColor } from './colors'
|
||||
|
||||
// A long table keeps the options with the most ground in view until asked for all.
|
||||
const SHORT_TABLE_ROWS = 6
|
||||
// An option getting under half or over twice its share of the noise stands out.
|
||||
const FAR_FROM_WEIGHT_FACTOR = 2
|
||||
|
||||
interface NoiseChartProps {
|
||||
spread: PickSpread
|
||||
/** What the noise picks, as the table's heading: "Regions" or "Biomes". */
|
||||
optionNoun: string
|
||||
}
|
||||
|
||||
/**
|
||||
* One noise that picks regions or biomes: how its values in view spread over the bands that pick each option, and a
|
||||
* table of each option's share of the noise against its share of the ground in view (v3e NoisePickChart).
|
||||
*/
|
||||
export function NoiseChart({ spread, optionNoun }: NoiseChartProps): React.JSX.Element {
|
||||
if (spread.rows.length === 1) {
|
||||
return (
|
||||
<section className="py-2.5">
|
||||
<ChartTitle>{spread.title}</ChartTitle>
|
||||
<div className="mt-1.5 flex items-center gap-2 text-[12px]">
|
||||
<OptionName share={spread.rows[0]} rows={spread.rows} />
|
||||
<span className="shrink-0 text-secondary-text">Picked everywhere</span>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<section className="py-2.5">
|
||||
<ChartTitle>{spread.title}</ChartTitle>
|
||||
<Spread spread={spread} />
|
||||
<ShareTable rows={spread.rows} optionNoun={optionNoun} />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function ChartTitle({ children }: { children: React.ReactNode }): React.JSX.Element {
|
||||
return <h4 className="truncate text-[11px] font-semibold text-muted-foreground">{children}</h4>
|
||||
}
|
||||
|
||||
function Spread({ spread }: { spread: PickSpread }): React.JSX.Element {
|
||||
const peak = Math.max(1, ...spread.histogram)
|
||||
return (
|
||||
<div className="mt-1.5">
|
||||
<div className="relative flex h-12 items-end gap-px">
|
||||
{spread.histogram.map((count, bin) => (
|
||||
<span key={bin} className="flex-1 rounded-t-[1px] bg-secondary-text/45" style={{ height: `${(count / peak) * 100}%` }} />
|
||||
))}
|
||||
{spread.bands.slice(0, -1).map((band, index) => (
|
||||
<span key={index} className="absolute inset-y-0 w-px bg-foreground/20" style={{ left: `${band.to * 100}%` }} />
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-0.5 flex h-2.5 overflow-hidden rounded-[2px]">
|
||||
{spread.bands.map((band, index) => (
|
||||
<span
|
||||
key={index}
|
||||
title={band.option.name}
|
||||
className="h-full"
|
||||
style={{ flexGrow: band.to - band.from, flexBasis: 0, backgroundColor: hexColor(band.option.color) }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-0.5 flex justify-between font-mono text-[10.5px] text-secondary-text">
|
||||
<span>0</span>
|
||||
<span>0.5</span>
|
||||
<span>1</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ShareTable({ rows, optionNoun }: { rows: PickShare[]; optionNoun: string }): React.JSX.Element {
|
||||
const [showsAll, setShowsAll] = useState(false)
|
||||
const long = rows.length > SHORT_TABLE_ROWS
|
||||
const shown = showsAll || !long ? rows : largestInView(rows)
|
||||
return (
|
||||
<div className="mt-2 grid grid-cols-[1fr_auto_auto] items-center gap-x-2.5 gap-y-0.5 text-[12px]">
|
||||
<span className="text-[11px] font-semibold text-muted-foreground">{optionNoun}</span>
|
||||
<span className="text-right text-[11px] font-semibold text-muted-foreground">Weight</span>
|
||||
<span className="text-right text-[11px] font-semibold text-muted-foreground">In view</span>
|
||||
{shown.map((share) => (
|
||||
<ShareRow key={share.option.key} share={share} rows={rows} />
|
||||
))}
|
||||
{long && (
|
||||
<button className="col-span-3 justify-self-start py-0.5 text-link hover:underline" onClick={() => setShowsAll(!showsAll)}>
|
||||
{showsAll ? 'Show fewer' : `Show all ${rows.length} ${optionNoun.toLowerCase()}`}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ShareRow({ share, rows }: { share: PickShare; rows: PickShare[] }): React.JSX.Element {
|
||||
const farFromWeight = share.inView * FAR_FROM_WEIGHT_FACTOR < share.weight || share.inView > share.weight * FAR_FROM_WEIGHT_FACTOR
|
||||
return (
|
||||
<>
|
||||
<OptionName share={share} rows={rows} />
|
||||
<span className="text-right text-secondary-text tabular-nums">{percent(share.weight)}</span>
|
||||
<span className={cn('text-right tabular-nums', farFromWeight && 'text-warning')}>{percent(share.inView)}</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// Two biomes in different folders can share a name, so their keys tell them apart.
|
||||
function OptionName({ share, rows }: { share: PickShare; rows: PickShare[] }): React.JSX.Element {
|
||||
const shared = rows.some((other) => other !== share && other.option.name === share.option.name)
|
||||
return (
|
||||
<span className="flex min-w-0 flex-1 items-center gap-1.5" title={share.option.key}>
|
||||
<span className="size-2.5 shrink-0 rounded-[3px]" style={{ backgroundColor: hexColor(share.option.color) }} />
|
||||
<span className="truncate">{shared ? `${share.option.name} (${share.option.key})` : share.option.name}</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** The rows with the most ground in view, still in the order the noise meets them. */
|
||||
export function largestInView(rows: PickShare[]): PickShare[] {
|
||||
const largest = new Set([...rows].sort((first, second) => second.inView - first.inView).slice(0, SHORT_TABLE_ROWS))
|
||||
return rows.filter((row) => largest.has(row))
|
||||
}
|
||||
|
||||
export function percent(fraction: number): string {
|
||||
if (fraction > 0 && fraction < 0.001) {
|
||||
return '<0.1%'
|
||||
}
|
||||
return `${(fraction * 100).toFixed(1)}%`
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
|
||||
import type { PickDisplay, PickInspection, PickSection } from '../bridge/types'
|
||||
import { hexColor } from './colors'
|
||||
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'
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
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>
|
||||
</header>
|
||||
<ScrollArea className="min-h-0 flex-1 border-t">
|
||||
<div className="px-4 pb-2">{inspection !== null && <Sections sections={inspection.sections} />}</div>
|
||||
</ScrollArea>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// A single section is the whole view, so its charts stand on their own; several are one region each, folded.
|
||||
function Sections({ sections }: { sections: PickSection[] }): React.JSX.Element {
|
||||
const [opened, setOpened] = useState<Set<string> | null>(null)
|
||||
if (sections.length === 1) {
|
||||
return <Charts section={sections[0]} />
|
||||
}
|
||||
const open = opened ?? new Set(sections.slice(0, 1).map(sectionKey))
|
||||
const toggle = (key: string): void => {
|
||||
const next = new Set(open)
|
||||
if (!next.delete(key)) {
|
||||
next.add(key)
|
||||
}
|
||||
setOpened(next)
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{sections.map((section) => (
|
||||
<RegionSection key={sectionKey(section)} section={section} open={open.has(sectionKey(section))} onToggle={() => toggle(sectionKey(section))} />
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function RegionSection({ section, open, onToggle }: { section: PickSection; open: boolean; onToggle(): void }): React.JSX.Element {
|
||||
const region = section.region
|
||||
return (
|
||||
<div className="border-b last:border-b-0">
|
||||
<button className="-mx-1.5 flex w-[calc(100%+12px)] items-center gap-2 rounded-md px-1.5 py-2 text-left hover:bg-accent" onClick={onToggle}>
|
||||
<ChevronRight className={`size-3.5 shrink-0 text-secondary-text transition-transform ${open ? 'rotate-90' : ''}`} />
|
||||
{region !== null && <span className="size-2.5 shrink-0 rounded-[3px]" style={{ backgroundColor: hexColor(region.color) }} />}
|
||||
<span className="min-w-0 flex-1 truncate font-medium">{region?.name ?? 'Regions'}</span>
|
||||
<span className="shrink-0 text-[11.5px] text-secondary-text tabular-nums">
|
||||
{percent(section.share)} · {section.biomeCount === 1 ? '1 biome' : `${section.biomeCount} biomes`}
|
||||
</span>
|
||||
</button>
|
||||
{open && <Charts section={section} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Charts({ section }: { section: PickSection }): React.JSX.Element {
|
||||
const optionNoun = section.region === null ? 'Regions' : 'Biomes'
|
||||
return (
|
||||
<div className="divide-y">
|
||||
{section.spreads.map((spread) => (
|
||||
<NoiseChart key={spread.title} spread={spread} optionNoun={optionNoun} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function sectionKey(section: PickSection): string {
|
||||
return section.region?.key ?? ''
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import { hexColor } from './colors'
|
||||
// Gaps between bands shrink as there are more of them, so many thin bands still read as a bar.
|
||||
const WIDE_GAP_MOST_BANDS = 18
|
||||
const NARROW_GAP_MOST_BANDS = 50
|
||||
/** Why a step that nothing picked has its label. */
|
||||
const UNPICKED_NOTES: Partial<Record<PickStep['kind'], string>> = { FOCUS: 'Focus', IMAGE_MAP: 'Image map', PREVIEW: 'Preview' }
|
||||
|
||||
/** How the spot got its region and biome: one row per pick, the noise value marked on every option's share of it. */
|
||||
export function PickRows({ path }: { path: PickStep[] }): React.JSX.Element | null {
|
||||
@@ -24,7 +26,7 @@ function PickRow({ step }: { step: PickStep }): React.JSX.Element {
|
||||
<>
|
||||
<span className="text-muted-foreground">{rowLabel(step)}</span>
|
||||
{step.noise === null ? (
|
||||
<span className="truncate text-secondary-text">{step.kind === 'FOCUS' ? 'Focus' : 'Image map'}</span>
|
||||
<span className="truncate text-secondary-text">{UNPICKED_NOTES[step.kind] ?? ''}</span>
|
||||
) : (
|
||||
<NoiseBar bands={step.bands} noise={step.noise} />
|
||||
)}
|
||||
@@ -73,6 +75,7 @@ function rowLabel(step: PickStep): string {
|
||||
return 'Child'
|
||||
case 'IMAGE_MAP':
|
||||
case 'FOCUS':
|
||||
case 'PREVIEW':
|
||||
return step.picked.kind === 'REGION' ? 'Region' : 'Biome'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { useState } from 'react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { MapLabel } from '../bridge/types'
|
||||
import { hexColor } from './colors'
|
||||
|
||||
// Short lists are scanned at a glance; longer ones get a search field.
|
||||
const SEARCHABLE_FROM_REGIONS = 8
|
||||
|
||||
interface RegionPreviewListProps {
|
||||
regions: MapLabel[]
|
||||
/** The previewed region's key, or null for all regions. */
|
||||
current: string | null
|
||||
onSelect(regionKey: string | null): void
|
||||
}
|
||||
|
||||
/** The region view's regions, any of which can fill the map with its biomes, or all of them as they are (v3e RegionNavigator). */
|
||||
export function RegionPreviewList({ regions, current, onSelect }: RegionPreviewListProps): React.JSX.Element {
|
||||
const [search, setSearch] = useState('')
|
||||
const wanted = search.trim().toLowerCase()
|
||||
const shown = wanted === '' ? regions : regions.filter((region) => `${region.name} ${region.key}`.toLowerCase().includes(wanted))
|
||||
return (
|
||||
<section>
|
||||
<h2 className="px-2 pt-1 pb-1.5 text-[11px] font-semibold text-muted-foreground">Preview a region</h2>
|
||||
{regions.length >= SEARCHABLE_FROM_REGIONS && (
|
||||
<Input
|
||||
className="mb-1 h-7 text-[12px]"
|
||||
placeholder="Find a region"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
onKeyDown={(event) => event.key === 'Escape' && setSearch('')}
|
||||
/>
|
||||
)}
|
||||
<RegionRow name="All regions" color={null} selected={current === null} onSelect={() => onSelect(null)} />
|
||||
{shown.map((region) => (
|
||||
<RegionRow
|
||||
key={region.key}
|
||||
name={region.name}
|
||||
color={region.color}
|
||||
title={region.key}
|
||||
selected={region.key === current}
|
||||
onSelect={() => onSelect(region.key)}
|
||||
/>
|
||||
))}
|
||||
{shown.length === 0 && <p className="px-2 py-1 text-[12px] text-muted-foreground">No region matches</p>}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
interface RegionRowProps {
|
||||
name: string
|
||||
color: number | null
|
||||
title?: string
|
||||
selected: boolean
|
||||
onSelect(): void
|
||||
}
|
||||
|
||||
function RegionRow({ name, color, title, selected, onSelect }: RegionRowProps): React.JSX.Element {
|
||||
return (
|
||||
<button
|
||||
onClick={onSelect}
|
||||
title={title}
|
||||
className={cn('flex h-[26px] w-full items-center gap-2 rounded-md px-2 text-left', selected ? 'bg-selection' : 'hover:bg-accent')}
|
||||
>
|
||||
<span
|
||||
className={cn('size-3 shrink-0 rounded-[3px]', color === null && 'border border-secondary-text/60')}
|
||||
style={color === null ? undefined : { backgroundColor: hexColor(color) }}
|
||||
/>
|
||||
<span className="truncate">{name}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -18,10 +18,12 @@ interface ViewListProps {
|
||||
views: ViewInfo[]
|
||||
current: string
|
||||
onSelect(view: string): void
|
||||
/** What the current view adds below the views, such as the regions it can preview. */
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
/** The views the server offers, in its groups, each with what it shows and its key. */
|
||||
export function ViewList({ views, current, onSelect }: ViewListProps): React.JSX.Element {
|
||||
export function ViewList({ views, current, onSelect, children }: ViewListProps): React.JSX.Element {
|
||||
const groups = [...new Set(views.map((view) => view.groupLabel))]
|
||||
return (
|
||||
<aside className="w-60 shrink-0 border-r bg-card">
|
||||
@@ -37,6 +39,7 @@ export function ViewList({ views, current, onSelect }: ViewListProps): React.JSX
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
{children}
|
||||
</nav>
|
||||
</ScrollArea>
|
||||
</aside>
|
||||
|
||||
Reference in new issue
Block a user