diff --git a/src/renderer/src/bridge/BridgeClient.ts b/src/renderer/src/bridge/BridgeClient.ts index 0b643d28c..9a3c0255c 100644 --- a/src/renderer/src/bridge/BridgeClient.ts +++ b/src/renderer/src/bridge/BridgeClient.ts @@ -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 { - return this.json(`hover?view=${encodeURIComponent(view)}&x=${worldX}&z=${worldZ}`, { signal }) + hover(layer: MapLayerQuery, worldX: number, worldZ: number, signal?: AbortSignal): Promise { + 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 { + 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 { + return this.json('regions') } entities(): Promise { @@ -61,13 +88,13 @@ export class BridgeClient { } async tile(request: TileRequest, signal: AbortSignal): Promise { - 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): 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 = '' diff --git a/src/renderer/src/bridge/tileDecoding.ts b/src/renderer/src/bridge/tileDecoding.ts index 60b0da3cd..ac5f23e90 100644 --- a/src/renderer/src/bridge/tileDecoding.ts +++ b/src/renderer/src/bridge/tileDecoding.ts @@ -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 } } diff --git a/src/renderer/src/bridge/types.ts b/src/renderer/src/bridge/types.ts index a122c6fda..97fecd342 100644 --- a/src/renderer/src/bridge/types.ts +++ b/src/renderer/src/bridge/types.ts @@ -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 diff --git a/src/renderer/src/components/ui/toggle-group.tsx b/src/renderer/src/components/ui/toggle-group.tsx new file mode 100644 index 000000000..54d3d9019 --- /dev/null +++ b/src/renderer/src/components/ui/toggle-group.tsx @@ -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>({ + size: "default", + variant: "default", +}) + +function ToggleGroup({ + className, + variant, + size, + children, + ...props +}: React.ComponentProps & + VariantProps) { + return ( + + + {children} + + + ) +} + +function ToggleGroupItem({ + className, + children, + variant, + size, + ...props +}: React.ComponentProps & + VariantProps) { + const context = React.useContext(ToggleGroupContext) + + return ( + + {children} + + ) +} + +export { ToggleGroup, ToggleGroupItem } diff --git a/src/renderer/src/map/MapController.ts b/src/renderer/src/map/MapController.ts index 1e814b01a..287bc8dd2 100644 --- a/src/renderer/src/map/MapController.ts +++ b/src/renderer/src/map/MapController.ts @@ -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) } } diff --git a/src/renderer/src/map/TileStore.ts b/src/renderer/src/map/TileStore.ts index 56d279562..9ecc91c10 100644 --- a/src/renderer/src/map/TileStore.ts +++ b/src/renderer/src/map/TileStore.ts @@ -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() diff --git a/src/renderer/src/map/map.test.ts b/src/renderer/src/map/map.test.ts index 555b304b6..79f00f37f 100644 --- a/src/renderer/src/map/map.test.ts +++ b/src/renderer/src/map/map.test.ts @@ -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', () => { diff --git a/src/renderer/src/map/tileStyle.ts b/src/renderer/src/map/tileStyle.ts index f3a6bb09f..5354d9904 100644 --- a/src/renderer/src/map/tileStyle.ts +++ b/src/renderer/src/map/tileStyle.ts @@ -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 { @@ -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 diff --git a/src/renderer/src/studio/HoverCard.tsx b/src/renderer/src/studio/HoverCard.tsx index 7b6872095..d6e11f456 100644 --- a/src/renderer/src/studio/HoverCard.tsx +++ b/src/renderer/src/studio/HoverCard.tsx @@ -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(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} > -
+
{parent !== null &&

child of {parent}

}

{ground(hover, minY)}

diff --git a/src/renderer/src/studio/Legend.tsx b/src/renderer/src/studio/Legend.tsx index 0ce53ae46..83125383f 100644 --- a/src/renderer/src/studio/Legend.tsx +++ b/src/renderer/src/studio/Legend.tsx @@ -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 ( - + ) } diff --git a/src/renderer/src/studio/MapCanvas.tsx b/src/renderer/src/studio/MapCanvas.tsx index 3a164ab80..99ad5228c 100644 --- a/src/renderer/src/studio/MapCanvas.tsx +++ b/src/renderer/src/studio/MapCanvas.tsx @@ -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 diff --git a/src/renderer/src/studio/MapStudio.tsx b/src/renderer/src/studio/MapStudio.tsx index b03ca911e..4ac806c69 100644 --- a/src/renderer/src/studio/MapStudio.tsx +++ b/src/renderer/src/studio/MapStudio.tsx @@ -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(null) const [connected, setConnected] = useState(true) + const [preview, setPreview] = useState(null) + const [pickDisplay, setPickDisplay] = useState('picks') + const [area, setArea] = useState(null) + const [packRevision, setPackRevision] = useState(0) const view = world.views.find((candidate) => candidate.id === viewId) ?? world.views[0] + const layer = useMemo(() => ({ 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} />
- + + {viewId === 'regions' && regions.length > 1 && } +
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 && ( - + )} {!connected && (
@@ -214,14 +238,26 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
)}
- setHighlight((current) => (sameSubject(current, subject) ? null : subject))} - /> +
- + ) @@ -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([]) + 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(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, 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, - 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( diff --git a/src/renderer/src/studio/NoiseChart.tsx b/src/renderer/src/studio/NoiseChart.tsx new file mode 100644 index 000000000..8ab7b37b2 --- /dev/null +++ b/src/renderer/src/studio/NoiseChart.tsx @@ -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 ( +
+ {spread.title} +
+ + Picked everywhere +
+
+ ) + } + return ( +
+ {spread.title} + + +
+ ) +} + +function ChartTitle({ children }: { children: React.ReactNode }): React.JSX.Element { + return

{children}

+} + +function Spread({ spread }: { spread: PickSpread }): React.JSX.Element { + const peak = Math.max(1, ...spread.histogram) + return ( +
+
+ {spread.histogram.map((count, bin) => ( + + ))} + {spread.bands.slice(0, -1).map((band, index) => ( + + ))} +
+
+ {spread.bands.map((band, index) => ( + + ))} +
+
+ 0 + 0.5 + 1 +
+
+ ) +} + +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 ( +
+ {optionNoun} + Weight + In view + {shown.map((share) => ( + + ))} + {long && ( + + )} +
+ ) +} + +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 ( + <> + + {percent(share.weight)} + {percent(share.inView)} + + ) +} + +// 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 ( + + + {shared ? `${share.option.name} (${share.option.key})` : share.option.name} + + ) +} + +/** 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)}%` +} diff --git a/src/renderer/src/studio/PickInspector.tsx b/src/renderer/src/studio/PickInspector.tsx new file mode 100644 index 000000000..36610ae72 --- /dev/null +++ b/src/renderer/src/studio/PickInspector.tsx @@ -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 ( +
+
+

{title}

+

{inspection?.detail ?? 'Measuring what is in view…'}

+ value !== '' && onDisplay(value as PickDisplay)} + > + + {picksLabel} + + + Noise + + + Both + + +
+ +
{inspection !== null && }
+
+
+ ) +} + +// 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 | null>(null) + if (sections.length === 1) { + return + } + 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) => ( + toggle(sectionKey(section))} /> + ))} + + ) +} + +function RegionSection({ section, open, onToggle }: { section: PickSection; open: boolean; onToggle(): void }): React.JSX.Element { + const region = section.region + return ( +
+ + {open && } +
+ ) +} + +function Charts({ section }: { section: PickSection }): React.JSX.Element { + const optionNoun = section.region === null ? 'Regions' : 'Biomes' + return ( +
+ {section.spreads.map((spread) => ( + + ))} +
+ ) +} + +function sectionKey(section: PickSection): string { + return section.region?.key ?? '' +} diff --git a/src/renderer/src/studio/PickRows.tsx b/src/renderer/src/studio/PickRows.tsx index cc2d9ded5..8ce947999 100644 --- a/src/renderer/src/studio/PickRows.tsx +++ b/src/renderer/src/studio/PickRows.tsx @@ -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> = { 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 { <> {rowLabel(step)} {step.noise === null ? ( - {step.kind === 'FOCUS' ? 'Focus' : 'Image map'} + {UNPICKED_NOTES[step.kind] ?? ''} ) : ( )} @@ -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' } } diff --git a/src/renderer/src/studio/RegionPreviewList.tsx b/src/renderer/src/studio/RegionPreviewList.tsx new file mode 100644 index 000000000..d3b1e1d2b --- /dev/null +++ b/src/renderer/src/studio/RegionPreviewList.tsx @@ -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 ( +
+

Preview a region

+ {regions.length >= SEARCHABLE_FROM_REGIONS && ( + setSearch(event.target.value)} + onKeyDown={(event) => event.key === 'Escape' && setSearch('')} + /> + )} + onSelect(null)} /> + {shown.map((region) => ( + onSelect(region.key)} + /> + ))} + {shown.length === 0 &&

No region matches

} +
+ ) +} + +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 ( + + ) +} diff --git a/src/renderer/src/studio/ViewList.tsx b/src/renderer/src/studio/ViewList.tsx index 43a57b869..362e0e074 100644 --- a/src/renderer/src/studio/ViewList.tsx +++ b/src/renderer/src/studio/ViewList.tsx @@ -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 (