mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 00:34:19 +00:00
Add the Palettes view
Pattern views from the server get a view each: entries by biome with a search over names, a depth stepper, the entry's facts, and the blocks on screen. Tiles are a pixel per column from afar and each block's tinted top texture up close; spots a layer leaves empty read as nothing at this depth. The pan and zoom tile canvas the noise view had is now TiledView and TiledCanvas, shared by noise and palettes, and the entry list is shared with the scene views.
This commit is contained in:
1 parent
8ace4ccc99
commit
1aba430153
16 files changed
+921
-346
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import type { BridgeConnection } from '../../../shared/bridge'
|
||||
import { decodeScene, type BlockScene } from '../scene/sceneDecoding'
|
||||
import { decodePattern } from './patternDecoding'
|
||||
import { decodeSavedTile } from './savedTileDecoding'
|
||||
import { decodeTile } from './tileDecoding'
|
||||
import type {
|
||||
@@ -7,14 +8,16 @@ import type {
|
||||
MapLabel,
|
||||
MapTile,
|
||||
Marker,
|
||||
ModuleViewInfo,
|
||||
NoiseSource,
|
||||
NoiseTile,
|
||||
PatternEntry,
|
||||
PatternTile,
|
||||
PickInspection,
|
||||
SavedStart,
|
||||
SavedTile,
|
||||
SavedWorldInfo,
|
||||
SceneEntry,
|
||||
SceneViewInfo,
|
||||
WorldInfo
|
||||
} from './types'
|
||||
|
||||
@@ -42,6 +45,17 @@ export interface TileRequest {
|
||||
pickNoise: boolean
|
||||
}
|
||||
|
||||
/** One tile of a pattern: tile (x, z) covers columns × blocksPerColumn blocks from x × that, z × that. */
|
||||
export interface PatternRequest {
|
||||
viewId: string
|
||||
key: string
|
||||
depth: number
|
||||
tileX: number
|
||||
tileZ: number
|
||||
blocksPerColumn: number
|
||||
columns: number
|
||||
}
|
||||
|
||||
/** What a map spot or area is asked about: a view, and the region it previews. */
|
||||
export interface MapLayerQuery {
|
||||
view: string
|
||||
@@ -120,7 +134,7 @@ export class BridgeClient {
|
||||
}
|
||||
|
||||
/** The scene views the pack's modules show, such as its objects. */
|
||||
sceneViews(): Promise<SceneViewInfo[]> {
|
||||
sceneViews(): Promise<ModuleViewInfo[]> {
|
||||
return this.json('scenes')
|
||||
}
|
||||
|
||||
@@ -133,6 +147,30 @@ export class BridgeClient {
|
||||
return decodeScene(await response.arrayBuffer())
|
||||
}
|
||||
|
||||
/** The pattern views the pack's modules show, such as its palettes. */
|
||||
patternViews(): Promise<ModuleViewInfo[]> {
|
||||
return this.json('patterns')
|
||||
}
|
||||
|
||||
patternEntries(viewId: string): Promise<PatternEntry[]> {
|
||||
return this.json(`pattern-entries?${new URLSearchParams({ view: viewId })}`)
|
||||
}
|
||||
|
||||
/** What an entry places at {@code depth} below the top across one tile, a column every {@code blocksPerColumn} blocks. */
|
||||
async pattern(request: PatternRequest, signal: AbortSignal): Promise<PatternTile> {
|
||||
const query = new URLSearchParams({
|
||||
view: request.viewId,
|
||||
key: request.key,
|
||||
depth: String(request.depth),
|
||||
x: String(request.tileX),
|
||||
z: String(request.tileZ),
|
||||
scale: String(request.blocksPerColumn),
|
||||
size: String(request.columns)
|
||||
})
|
||||
const response = await this.fetch(`pattern?${query}`, { signal })
|
||||
return decodePattern(await response.arrayBuffer())
|
||||
}
|
||||
|
||||
/** The worlds saved on the server's disk. */
|
||||
savedWorlds(): Promise<SavedWorldInfo[]> {
|
||||
return this.json('saved-worlds')
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decodePattern } from './patternDecoding'
|
||||
import { NO_PATTERN_BLOCK } from './types'
|
||||
|
||||
function encodedPattern(header: object, picks: number[]): ArrayBuffer {
|
||||
const headerBytes = new TextEncoder().encode(JSON.stringify(header))
|
||||
const picksAt = Math.ceil((4 + headerBytes.length) / 4) * 4
|
||||
const buffer = new ArrayBuffer(picksAt + picks.length * 2)
|
||||
const view = new DataView(buffer)
|
||||
view.setUint32(0, headerBytes.length, true)
|
||||
new Uint8Array(buffer, 4).set(headerBytes)
|
||||
picks.forEach((pick, index) => view.setInt16(picksAt + index * 2, pick, true))
|
||||
return buffer
|
||||
}
|
||||
|
||||
describe('decodePattern', () => {
|
||||
it('reads the picks after the padded header, row by row, with no block as -1', () => {
|
||||
const header = { columns: 2, blocksPerColumn: 4, blocks: ['minecraft:grass_block[snowy=false]', 'minecraft:dirt'], noBlock: -1 }
|
||||
const pattern = decodePattern(encodedPattern(header, [0, -1, 1, 0]))
|
||||
expect(pattern.columns).toBe(2)
|
||||
expect(pattern.blocksPerColumn).toBe(4)
|
||||
expect(pattern.blocks).toEqual(header.blocks)
|
||||
expect([...pattern.picks]).toEqual([0, NO_PATTERN_BLOCK, 1, 0])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { PatternTile } from './types'
|
||||
|
||||
const ALIGNMENT_BYTES = 4
|
||||
|
||||
interface PatternHeader {
|
||||
columns: number
|
||||
blocksPerColumn: number
|
||||
blocks: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a pattern as the bridge writes it (PatternEncoding): a u32 header length, the JSON header, then from the next
|
||||
* multiple of 4 bytes an i16 pick per column, row by row. The picks are a view into the buffer, not a copy.
|
||||
*/
|
||||
export function decodePattern(buffer: ArrayBuffer): PatternTile {
|
||||
const headerLength = new DataView(buffer).getUint32(0, true)
|
||||
const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 4, headerLength))) as PatternHeader
|
||||
const picksAt = Math.ceil((4 + headerLength) / ALIGNMENT_BYTES) * ALIGNMENT_BYTES
|
||||
return {
|
||||
columns: header.columns,
|
||||
blocksPerColumn: header.blocksPerColumn,
|
||||
blocks: header.blocks,
|
||||
picks: new Int16Array(buffer, picksAt, header.columns * header.columns)
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,8 @@ export interface ViewInfo {
|
||||
groupLabel: string
|
||||
}
|
||||
|
||||
/** A view of block scenes a module of the pack shows, such as its objects (IrisApi SceneView). */
|
||||
export interface SceneViewInfo {
|
||||
/** A studio view a module of the pack shows (IrisApi StudioView): block scenes such as its objects, or patterns such as its palettes. */
|
||||
export interface ModuleViewInfo {
|
||||
id: string
|
||||
label: string
|
||||
description: string
|
||||
@@ -33,6 +33,30 @@ export interface SceneEntry {
|
||||
variants: number
|
||||
}
|
||||
|
||||
/** Something a pattern view lays out, such as one of a biome's palettes (IrisApi PatternEntry). */
|
||||
export interface PatternEntry {
|
||||
key: string
|
||||
name: string
|
||||
/** The heading it is listed under, such as its biome. */
|
||||
group: string
|
||||
/** How many depths below the top it has a pick for; at least 1. */
|
||||
depths: number
|
||||
/** Short lines about it, such as its blocks and noise. */
|
||||
facts: string[]
|
||||
}
|
||||
|
||||
/** What a pattern entry places across a square of columns, row by row from the north west. */
|
||||
export interface PatternTile {
|
||||
columns: number
|
||||
blocksPerColumn: number
|
||||
/** The block states the picks index, as BlockState keys. */
|
||||
blocks: string[]
|
||||
/** Each column's block, or NO_PATTERN_BLOCK where the pattern places none. */
|
||||
picks: Int16Array
|
||||
}
|
||||
|
||||
export const NO_PATTERN_BLOCK = -1
|
||||
|
||||
/** A world saved on the server's disk, a dimension folder of region files. */
|
||||
export interface SavedWorldInfo {
|
||||
/** Its folder below the server's level folder. */
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import { drawVisibleTiles } from './tileDrawing'
|
||||
import { TileStore, type TileSource } from './TileStore'
|
||||
import {
|
||||
MAXIMUM_BLOCKS_PER_PIXEL,
|
||||
MINIMUM_VIEW_BLOCKS_PER_PIXEL,
|
||||
renderBlocksPerPixel,
|
||||
screenToWorldX,
|
||||
screenToWorldZ,
|
||||
type TileAddress,
|
||||
type Viewport
|
||||
} from './viewport'
|
||||
|
||||
export interface TiledViewOptions<Tile, Layer, Style> {
|
||||
source: TileSource<Tile, Layer, Style>
|
||||
tileSize: number
|
||||
defaultBlocksPerPixel: number
|
||||
/** The finest scale tiles are asked for at; closer views magnify them. */
|
||||
finestRenderBlocksPerPixel: number
|
||||
/** How far the view may zoom out. */
|
||||
coarsestBlocksPerPixel?: number
|
||||
onFrame(frame: TiledFrame): void
|
||||
onError(message: string): void
|
||||
}
|
||||
|
||||
export interface TiledFrame {
|
||||
blocksPerPixel: number
|
||||
tilesReady: number
|
||||
tilesTotal: number
|
||||
/** The world spot under the cursor, or under the middle when the cursor is away. */
|
||||
cursorX: number
|
||||
cursorZ: number
|
||||
}
|
||||
|
||||
/** A tile and the pixel of it at a world spot. */
|
||||
export interface TileSpot<Tile> {
|
||||
tile: Tile
|
||||
pixelX: number
|
||||
pixelZ: number
|
||||
}
|
||||
|
||||
/** Where a view looks and the scale its tiles are drawn at. */
|
||||
export interface TiledFraming {
|
||||
centerX: number
|
||||
centerZ: number
|
||||
renderScale: number
|
||||
}
|
||||
|
||||
/**
|
||||
* A pan and zoom view of tiles on a canvas, fetched as the view moves and drawn in the current style. Kept outside
|
||||
* React, as it redraws on every drag and wheel step.
|
||||
*/
|
||||
export class TiledView<Tile, Layer, Style> {
|
||||
private readonly context: CanvasRenderingContext2D
|
||||
private readonly store: TileStore<Tile, Layer, Style>
|
||||
private readonly view: Viewport
|
||||
private layer: Layer | null = null
|
||||
private style: Style | null = null
|
||||
private cursor: { x: number; y: number } | null = null
|
||||
private drawn = { tilesReady: 0, tilesTotal: 0 }
|
||||
private frameRequested = false
|
||||
private closed = false
|
||||
|
||||
constructor(
|
||||
private readonly canvas: HTMLCanvasElement,
|
||||
private readonly options: TiledViewOptions<Tile, Layer, Style>
|
||||
) {
|
||||
this.context = canvas.getContext('2d')!
|
||||
this.view = { centerX: 0, centerZ: 0, blocksPerPixel: options.defaultBlocksPerPixel, width: 1, height: 1 }
|
||||
this.store = new TileStore(options.source, () => this.redraw(), options.onError)
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true
|
||||
this.store.clear()
|
||||
}
|
||||
|
||||
resize(width: number, height: number): void {
|
||||
const ratio = window.devicePixelRatio
|
||||
this.canvas.width = Math.round(width * ratio)
|
||||
this.canvas.height = Math.round(height * ratio)
|
||||
this.view.width = width
|
||||
this.view.height = height
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
show(layer: Layer | null, style: Style): void {
|
||||
this.layer = layer
|
||||
this.style = style
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
panBy(screenDeltaX: number, screenDeltaZ: number): void {
|
||||
this.view.centerX -= screenDeltaX * this.view.blocksPerPixel
|
||||
this.view.centerZ -= screenDeltaZ * this.view.blocksPerPixel
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
/** Zooms by {@code factor} (above 1 zooms in) keeping the spot under the screen point where it is. */
|
||||
zoomAt(factor: number, screenX = this.view.width / 2, screenZ = this.view.height / 2): void {
|
||||
const worldX = screenToWorldX(this.view, screenX)
|
||||
const worldZ = screenToWorldZ(this.view, screenZ)
|
||||
const coarsest = this.options.coarsestBlocksPerPixel ?? MAXIMUM_BLOCKS_PER_PIXEL
|
||||
this.view.blocksPerPixel = Math.min(coarsest, Math.max(MINIMUM_VIEW_BLOCKS_PER_PIXEL, this.view.blocksPerPixel / factor))
|
||||
this.view.centerX = worldX - (screenX - this.view.width / 2) * this.view.blocksPerPixel
|
||||
this.view.centerZ = worldZ - (screenZ - this.view.height / 2) * this.view.blocksPerPixel
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
resetView(): void {
|
||||
this.view.centerX = 0
|
||||
this.view.centerZ = 0
|
||||
this.view.blocksPerPixel = this.options.defaultBlocksPerPixel
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
setCursor(cursor: { x: number; y: number } | null): void {
|
||||
this.cursor = cursor
|
||||
this.reportFrame()
|
||||
}
|
||||
|
||||
framing(): TiledFraming {
|
||||
return { centerX: this.view.centerX, centerZ: this.view.centerZ, renderScale: this.renderScale() }
|
||||
}
|
||||
|
||||
/** The tile drawn at a world spot at the current scale and its pixel there; null before it arrived. */
|
||||
spotAt(worldX: number, worldZ: number): TileSpot<Tile> | null {
|
||||
if (this.layer === null) {
|
||||
return null
|
||||
}
|
||||
const scale = this.renderScale()
|
||||
const span = this.options.tileSize * scale
|
||||
const address: TileAddress = { tileX: Math.floor(worldX / span), tileZ: Math.floor(worldZ / span), blocksPerPixel: scale }
|
||||
const tile = this.store.get(address, this.layer)
|
||||
if (tile === null) {
|
||||
return null
|
||||
}
|
||||
const last = this.options.tileSize - 1
|
||||
const pixelX = Math.min(last, Math.floor((worldX - address.tileX * span) / scale))
|
||||
const pixelZ = Math.min(last, Math.floor((worldZ - address.tileZ * span) / scale))
|
||||
return { tile, pixelX, pixelZ }
|
||||
}
|
||||
|
||||
private renderScale(): number {
|
||||
return renderBlocksPerPixel(this.view.blocksPerPixel, window.devicePixelRatio, this.options.finestRenderBlocksPerPixel)
|
||||
}
|
||||
|
||||
private redraw(): void {
|
||||
if (this.frameRequested || this.closed) {
|
||||
return
|
||||
}
|
||||
this.frameRequested = true
|
||||
requestAnimationFrame(() => {
|
||||
this.frameRequested = false
|
||||
if (!this.closed) {
|
||||
this.draw()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private draw(): void {
|
||||
const ratio = window.devicePixelRatio
|
||||
const context = this.context
|
||||
context.setTransform(ratio, 0, 0, ratio, 0, 0)
|
||||
context.fillStyle = getComputedStyle(this.canvas).getPropertyValue('--map-background') || '#16171a'
|
||||
context.fillRect(0, 0, this.view.width, this.view.height)
|
||||
const layer = this.layer
|
||||
const style = this.style
|
||||
if (layer === null || style === null) {
|
||||
this.drawn = { tilesReady: 0, tilesTotal: 0 }
|
||||
this.reportFrame()
|
||||
return
|
||||
}
|
||||
const drawn = drawVisibleTiles(context, this.view, this.renderScale(), this.options.tileSize, (address) => this.store.picture(address, layer, style))
|
||||
this.store.want(drawn.wanted, layer)
|
||||
this.drawn = { tilesReady: drawn.ready, tilesTotal: drawn.tiles.length }
|
||||
this.reportFrame()
|
||||
}
|
||||
|
||||
private reportFrame(): void {
|
||||
const cursor = this.cursor ?? { x: this.view.width / 2, y: this.view.height / 2 }
|
||||
this.options.onFrame({
|
||||
blocksPerPixel: this.view.blocksPerPixel,
|
||||
...this.drawn,
|
||||
cursorX: screenToWorldX(this.view, cursor.x),
|
||||
cursorZ: screenToWorldZ(this.view, cursor.y)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { NoiseTile } from '../bridge/types'
|
||||
import { drawVisibleTiles } from '../map/tileDrawing'
|
||||
import { TileStore, type TileSource } from '../map/TileStore'
|
||||
import { clampBlocksPerPixel, renderBlocksPerPixel, screenToWorldX, screenToWorldZ, type TileAddress, type Viewport } from '../map/viewport'
|
||||
import type { NoiseScale } from './noiseScale'
|
||||
|
||||
/** Which noise the tiles hold. */
|
||||
export interface NoiseLayer {
|
||||
sourceId: string
|
||||
/** A 64 bit seed, as text so no digit is lost. */
|
||||
seed: string
|
||||
/** Bumped when the pack is hotloaded, so older tiles are not used again. */
|
||||
revision: number
|
||||
}
|
||||
|
||||
export interface NoiseStyle {
|
||||
/** Tells styles apart, so a tile is recoloured only when its style changed. */
|
||||
key: string
|
||||
scale: NoiseScale
|
||||
}
|
||||
|
||||
export interface NoiseStatus {
|
||||
blocksPerPixel: number
|
||||
tilesReady: number
|
||||
tilesTotal: number
|
||||
cursorX: number
|
||||
cursorZ: number
|
||||
/** The noise at the cursor, or null before its tile arrived. */
|
||||
value: number | null
|
||||
}
|
||||
|
||||
export interface NoiseListener {
|
||||
onStatus(status: NoiseStatus): void
|
||||
onError(message: string): void
|
||||
}
|
||||
|
||||
export const NOISE_TILE_PIXELS = 128
|
||||
const DEFAULT_NOISE_BLOCKS_PER_PIXEL = 1
|
||||
// Noise has detail finer than a block, so it is drawn finer than the world map's one block per pixel.
|
||||
const FINEST_NOISE_BLOCKS_PER_PIXEL = 1 / 16
|
||||
|
||||
function noiseTileSource(client: BridgeClient): TileSource<NoiseTile, NoiseLayer, NoiseStyle> {
|
||||
return {
|
||||
layerKey: (layer) => `${layer.revision}/${layer.sourceId}/${layer.seed}`,
|
||||
fetch: (address, layer, signal) =>
|
||||
client.noiseTile(layer.sourceId, layer.seed, address.tileX, address.tileZ, address.blocksPerPixel, NOISE_TILE_PIXELS, signal),
|
||||
bytesOf: (tile) => tile.values.byteLength + tile.size * tile.size * 4,
|
||||
styleKey: (style) => style.key,
|
||||
pixels: (tile, style) => noisePixels(tile, style.scale)
|
||||
}
|
||||
}
|
||||
|
||||
function noisePixels(tile: NoiseTile, scale: NoiseScale): ImageData {
|
||||
const pixels = new ImageData(tile.size, tile.size)
|
||||
for (let index = 0; index < tile.values.length; index++) {
|
||||
const color = scale.colorOf(tile.values[index])
|
||||
pixels.data[index * 4] = (color >> 16) & 0xff
|
||||
pixels.data[index * 4 + 1] = (color >> 8) & 0xff
|
||||
pixels.data[index * 4 + 2] = color & 0xff
|
||||
pixels.data[index * 4 + 3] = 0xff
|
||||
}
|
||||
return pixels
|
||||
}
|
||||
|
||||
/** The noise from above on a canvas, fetched in tiles as the view moves. Kept outside React, as it redraws on every drag. */
|
||||
export class NoiseController {
|
||||
private readonly context: CanvasRenderingContext2D
|
||||
private readonly store: TileStore<NoiseTile, NoiseLayer, NoiseStyle>
|
||||
private readonly view: Viewport = { centerX: 0, centerZ: 0, blocksPerPixel: DEFAULT_NOISE_BLOCKS_PER_PIXEL, width: 1, height: 1 }
|
||||
private layer: NoiseLayer | null = null
|
||||
private style: NoiseStyle | null = null
|
||||
private cursor: { x: number; y: number } | null = null
|
||||
private lastReady = 0
|
||||
private lastTotal = 0
|
||||
private frameRequested = false
|
||||
private closed = false
|
||||
|
||||
constructor(
|
||||
private readonly canvas: HTMLCanvasElement,
|
||||
client: BridgeClient,
|
||||
private readonly listener: NoiseListener
|
||||
) {
|
||||
this.context = canvas.getContext('2d')!
|
||||
this.store = new TileStore(noiseTileSource(client), () => this.redraw(), (message) => listener.onError(message))
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true
|
||||
this.store.clear()
|
||||
}
|
||||
|
||||
resize(width: number, height: number): void {
|
||||
const ratio = window.devicePixelRatio
|
||||
this.canvas.width = Math.round(width * ratio)
|
||||
this.canvas.height = Math.round(height * ratio)
|
||||
this.view.width = width
|
||||
this.view.height = height
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
show(layer: NoiseLayer | null, style: NoiseStyle): void {
|
||||
this.layer = layer
|
||||
this.style = style
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
panBy(screenDeltaX: number, screenDeltaZ: number): void {
|
||||
this.view.centerX -= screenDeltaX * this.view.blocksPerPixel
|
||||
this.view.centerZ -= screenDeltaZ * this.view.blocksPerPixel
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
/** Zooms by {@code factor} (above 1 zooms in) keeping the spot under the screen point where it is. */
|
||||
zoomAt(factor: number, screenX = this.view.width / 2, screenZ = this.view.height / 2): void {
|
||||
const worldX = screenToWorldX(this.view, screenX)
|
||||
const worldZ = screenToWorldZ(this.view, screenZ)
|
||||
this.view.blocksPerPixel = clampBlocksPerPixel(this.view.blocksPerPixel / factor)
|
||||
this.view.centerX = worldX - (screenX - this.view.width / 2) * this.view.blocksPerPixel
|
||||
this.view.centerZ = worldZ - (screenZ - this.view.height / 2) * this.view.blocksPerPixel
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
resetView(): void {
|
||||
this.view.centerX = 0
|
||||
this.view.centerZ = 0
|
||||
this.view.blocksPerPixel = DEFAULT_NOISE_BLOCKS_PER_PIXEL
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
setCursor(cursor: { x: number; y: number } | null): void {
|
||||
this.cursor = cursor
|
||||
this.reportStatus()
|
||||
}
|
||||
|
||||
/** Where the view looks and the scale its tiles are drawn at, for the 3D view to sample the same noise. */
|
||||
framing(): { centerX: number; centerZ: number; renderScale: number } {
|
||||
return { centerX: this.view.centerX, centerZ: this.view.centerZ, renderScale: this.renderScale() }
|
||||
}
|
||||
|
||||
private renderScale(): number {
|
||||
return renderBlocksPerPixel(this.view.blocksPerPixel, window.devicePixelRatio, FINEST_NOISE_BLOCKS_PER_PIXEL)
|
||||
}
|
||||
|
||||
private redraw(): void {
|
||||
if (this.frameRequested || this.closed) {
|
||||
return
|
||||
}
|
||||
this.frameRequested = true
|
||||
requestAnimationFrame(() => {
|
||||
this.frameRequested = false
|
||||
if (!this.closed) {
|
||||
this.draw()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private draw(): void {
|
||||
const ratio = window.devicePixelRatio
|
||||
const context = this.context
|
||||
context.setTransform(ratio, 0, 0, ratio, 0, 0)
|
||||
context.fillStyle = getComputedStyle(this.canvas).getPropertyValue('--map-background') || '#16171a'
|
||||
context.fillRect(0, 0, this.view.width, this.view.height)
|
||||
const layer = this.layer
|
||||
const style = this.style
|
||||
if (layer === null || style === null) {
|
||||
this.reportStatus(0, 0)
|
||||
return
|
||||
}
|
||||
const drawn = drawVisibleTiles(context, this.view, this.renderScale(), NOISE_TILE_PIXELS, (address) => this.store.picture(address, layer, style))
|
||||
this.store.want(drawn.wanted, layer)
|
||||
this.reportStatus(drawn.ready, drawn.tiles.length)
|
||||
}
|
||||
|
||||
private valueAt(worldX: number, worldZ: number): number | null {
|
||||
if (this.layer === null) {
|
||||
return null
|
||||
}
|
||||
const scale = this.renderScale()
|
||||
const span = NOISE_TILE_PIXELS * scale
|
||||
const address: TileAddress = { tileX: Math.floor(worldX / span), tileZ: Math.floor(worldZ / span), blocksPerPixel: scale }
|
||||
const tile = this.store.get(address, this.layer)
|
||||
if (tile === null) {
|
||||
return null
|
||||
}
|
||||
const pixelX = Math.min(tile.size - 1, Math.floor((worldX - address.tileX * span) / scale))
|
||||
const pixelZ = Math.min(tile.size - 1, Math.floor((worldZ - address.tileZ * span) / scale))
|
||||
return tile.values[pixelZ * tile.size + pixelX]
|
||||
}
|
||||
|
||||
private reportStatus(ready = this.lastReady, total = this.lastTotal): void {
|
||||
this.lastReady = ready
|
||||
this.lastTotal = total
|
||||
const cursor = this.cursor ?? { x: this.view.width / 2, y: this.view.height / 2 }
|
||||
const worldX = screenToWorldX(this.view, cursor.x)
|
||||
const worldZ = screenToWorldZ(this.view, cursor.y)
|
||||
this.listener.onStatus({
|
||||
blocksPerPixel: this.view.blocksPerPixel,
|
||||
tilesReady: ready,
|
||||
tilesTotal: total,
|
||||
cursorX: worldX,
|
||||
cursorZ: worldZ,
|
||||
value: this.valueAt(worldX, worldZ)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { NoiseTile } from '../bridge/types'
|
||||
import { TiledView, type TiledFrame } from '../map/TiledView'
|
||||
import type { TileSource } from '../map/TileStore'
|
||||
import type { NoiseScale } from './noiseScale'
|
||||
|
||||
/** Which noise the tiles hold. */
|
||||
export interface NoiseLayer {
|
||||
sourceId: string
|
||||
/** A 64 bit seed, as text so no digit is lost. */
|
||||
seed: string
|
||||
/** Bumped when the pack is hotloaded, so older tiles are not used again. */
|
||||
revision: number
|
||||
}
|
||||
|
||||
export interface NoiseStyle {
|
||||
/** Tells styles apart, so a tile is recoloured only when its style changed. */
|
||||
key: string
|
||||
scale: NoiseScale
|
||||
}
|
||||
|
||||
export type NoiseView = TiledView<NoiseTile, NoiseLayer, NoiseStyle>
|
||||
|
||||
export interface NoiseStatus extends TiledFrame {
|
||||
/** The noise at the cursor, or null before its tile arrived. */
|
||||
value: number | null
|
||||
}
|
||||
|
||||
export interface NoiseListener {
|
||||
onStatus(status: NoiseStatus): void
|
||||
onError(message: string): void
|
||||
}
|
||||
|
||||
export const NOISE_TILE_PIXELS = 128
|
||||
const DEFAULT_NOISE_BLOCKS_PER_PIXEL = 1
|
||||
// Noise has detail finer than a block, so it is drawn finer than the world map's one block per pixel.
|
||||
const FINEST_NOISE_BLOCKS_PER_PIXEL = 1 / 16
|
||||
|
||||
export function createNoiseView(canvas: HTMLCanvasElement, client: BridgeClient, listener: NoiseListener): NoiseView {
|
||||
const view: NoiseView = new TiledView(canvas, {
|
||||
source: noiseTileSource(client),
|
||||
tileSize: NOISE_TILE_PIXELS,
|
||||
defaultBlocksPerPixel: DEFAULT_NOISE_BLOCKS_PER_PIXEL,
|
||||
finestRenderBlocksPerPixel: FINEST_NOISE_BLOCKS_PER_PIXEL,
|
||||
onFrame: (frame) => listener.onStatus({ ...frame, value: valueAt(view, frame.cursorX, frame.cursorZ) }),
|
||||
onError: (message) => listener.onError(message)
|
||||
})
|
||||
return view
|
||||
}
|
||||
|
||||
function valueAt(view: NoiseView, worldX: number, worldZ: number): number | null {
|
||||
const spot = view.spotAt(worldX, worldZ)
|
||||
return spot === null ? null : spot.tile.values[spot.pixelZ * spot.tile.size + spot.pixelX]
|
||||
}
|
||||
|
||||
function noiseTileSource(client: BridgeClient): TileSource<NoiseTile, NoiseLayer, NoiseStyle> {
|
||||
return {
|
||||
layerKey: (layer) => `${layer.revision}/${layer.sourceId}/${layer.seed}`,
|
||||
fetch: (address, layer, signal) =>
|
||||
client.noiseTile(layer.sourceId, layer.seed, address.tileX, address.tileZ, address.blocksPerPixel, NOISE_TILE_PIXELS, signal),
|
||||
bytesOf: (tile) => tile.values.byteLength + tile.size * tile.size * 4,
|
||||
styleKey: (style) => style.key,
|
||||
pixels: (tile, style) => noisePixels(tile, style.scale)
|
||||
}
|
||||
}
|
||||
|
||||
function noisePixels(tile: NoiseTile, scale: NoiseScale): ImageData {
|
||||
const pixels = new ImageData(tile.size, tile.size)
|
||||
for (let index = 0; index < tile.values.length; index++) {
|
||||
const color = scale.colorOf(tile.values[index])
|
||||
pixels.data[index * 4] = (color >> 16) & 0xff
|
||||
pixels.data[index * 4 + 1] = (color >> 8) & 0xff
|
||||
pixels.data[index * 4 + 2] = color & 0xff
|
||||
pixels.data[index * 4 + 3] = 0xff
|
||||
}
|
||||
return pixels
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||
import { NO_PATTERN_BLOCK, type PatternTile } from '../bridge/types'
|
||||
import { TiledView, type TiledFrame } from '../map/TiledView'
|
||||
import type { TileSource } from '../map/TileStore'
|
||||
import type { TileAddress } from '../map/viewport'
|
||||
import type { BlockColors } from '../scene/blockColors'
|
||||
|
||||
/** Which entry, at which depth, the tiles lay out. */
|
||||
export interface PatternLayer {
|
||||
viewId: string
|
||||
key: string
|
||||
depth: number
|
||||
/** Bumped when the pack is hotloaded, so older tiles are not used again. */
|
||||
revision: number
|
||||
}
|
||||
|
||||
/** A pattern tile with what it needs to be drawn: each block's colour, and its texture once a block spans pixels. */
|
||||
export interface PatternPicture {
|
||||
pattern: PatternTile
|
||||
colors: number[]
|
||||
/** Per block, its top texture; empty while a block is a pixel or smaller. */
|
||||
textures: (ImageData | null)[]
|
||||
/** How many pixels across a column is drawn; 1 when it is a pixel or smaller. */
|
||||
pixelsPerColumn: number
|
||||
}
|
||||
|
||||
/** Patterns have one look; the style only satisfies the tile store. */
|
||||
export type PatternStyle = 'blocks'
|
||||
export type PatternView = TiledView<PatternPicture, PatternLayer, PatternStyle>
|
||||
|
||||
/** What is under the cursor: a block, nothing placed there, or not known before its tile arrived. */
|
||||
export type PatternSpot = { kind: 'block'; block: string } | { kind: 'none' } | { kind: 'unknown' }
|
||||
|
||||
export interface PatternStatus extends TiledFrame {
|
||||
spot: PatternSpot
|
||||
}
|
||||
|
||||
/** The blocks a tile placed with their colours, and whether it left some columns without a block. */
|
||||
export interface PatternBlocks {
|
||||
colors: Map<string, number>
|
||||
someNone: boolean
|
||||
}
|
||||
|
||||
export interface PatternListener {
|
||||
onStatus(status: PatternStatus): void
|
||||
/** What a tile of the layer showed, for the legend. */
|
||||
onBlocks(layer: PatternLayer, blocks: PatternBlocks): void
|
||||
onError(message: string): void
|
||||
}
|
||||
|
||||
export const PATTERN_TILE_PIXELS = 128
|
||||
const DEFAULT_PATTERN_BLOCKS_PER_PIXEL = 1
|
||||
// A block texture is 16 pixels across; drawing a block that wide shows it whole.
|
||||
const FINEST_PATTERN_BLOCKS_PER_PIXEL = 1 / 16
|
||||
// The bridge lays out a column at most every 64 blocks; views stop a level short so their previews stay within it.
|
||||
const COARSEST_PATTERN_BLOCKS_PER_PIXEL = 32
|
||||
const NO_COLOR = 0x000000
|
||||
const OPAQUE = 0xff
|
||||
const OPAQUE_ENOUGH_ALPHA = 128
|
||||
|
||||
export function createPatternView(canvas: HTMLCanvasElement, client: BridgeClient, blockColors: BlockColors, listener: PatternListener): PatternView {
|
||||
const view: PatternView = new TiledView(canvas, {
|
||||
source: patternTileSource(client, blockColors, listener),
|
||||
tileSize: PATTERN_TILE_PIXELS,
|
||||
defaultBlocksPerPixel: DEFAULT_PATTERN_BLOCKS_PER_PIXEL,
|
||||
finestRenderBlocksPerPixel: FINEST_PATTERN_BLOCKS_PER_PIXEL,
|
||||
coarsestBlocksPerPixel: COARSEST_PATTERN_BLOCKS_PER_PIXEL,
|
||||
onFrame: (frame) => listener.onStatus({ ...frame, spot: spotAt(view, frame.cursorX, frame.cursorZ) }),
|
||||
onError: (message) => listener.onError(message)
|
||||
})
|
||||
return view
|
||||
}
|
||||
|
||||
function spotAt(view: PatternView, worldX: number, worldZ: number): PatternSpot {
|
||||
const spot = view.spotAt(worldX, worldZ)
|
||||
if (spot === null) {
|
||||
return { kind: 'unknown' }
|
||||
}
|
||||
const { pattern, pixelsPerColumn } = spot.tile
|
||||
const column = Math.floor(spot.pixelX / pixelsPerColumn)
|
||||
const row = Math.floor(spot.pixelZ / pixelsPerColumn)
|
||||
const pick = pattern.picks[row * pattern.columns + column]
|
||||
return pick === NO_PATTERN_BLOCK ? { kind: 'none' } : { kind: 'block', block: pattern.blocks[pick] }
|
||||
}
|
||||
|
||||
function patternTileSource(client: BridgeClient, blockColors: BlockColors, listener: PatternListener): TileSource<PatternPicture, PatternLayer, PatternStyle> {
|
||||
return {
|
||||
layerKey: (layer) => `${layer.revision}/${layer.viewId}/${layer.key}/${layer.depth}`,
|
||||
fetch: async (address, layer, signal) => {
|
||||
const picture = await fetchPicture(client, blockColors, address, layer, signal)
|
||||
listener.onBlocks(layer, {
|
||||
colors: new Map(picture.pattern.blocks.map((block, index) => [block, picture.colors[index]])),
|
||||
someNone: picture.pattern.picks.includes(NO_PATTERN_BLOCK)
|
||||
})
|
||||
return picture
|
||||
},
|
||||
bytesOf: (picture) => picture.pattern.picks.byteLength + PATTERN_TILE_PIXELS * PATTERN_TILE_PIXELS * 4,
|
||||
styleKey: (style) => style,
|
||||
pixels: (picture) => patternPixels(picture)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A tile a pixel per column where a column is a pixel or more, and otherwise a column per block, each drawn a few
|
||||
* pixels wide in its texture.
|
||||
*/
|
||||
async function fetchPicture(client: BridgeClient, blockColors: BlockColors, address: TileAddress, layer: PatternLayer, signal: AbortSignal): Promise<PatternPicture> {
|
||||
const blocksPerColumn = Math.max(1, address.blocksPerPixel)
|
||||
const pixelsPerColumn = Math.round(blocksPerColumn / address.blocksPerPixel)
|
||||
const columns = PATTERN_TILE_PIXELS / pixelsPerColumn
|
||||
const pattern = await client.pattern({ ...layer, tileX: address.tileX, tileZ: address.tileZ, blocksPerColumn, columns }, signal)
|
||||
const colors = await Promise.all(pattern.blocks.map((block) => blockColors.colorOf(block)))
|
||||
const textures = pixelsPerColumn > 1 ? await Promise.all(pattern.blocks.map((block) => blockColors.topTexture(block))) : []
|
||||
return { pattern, colors, textures, pixelsPerColumn }
|
||||
}
|
||||
|
||||
function patternPixels(picture: PatternPicture): ImageData {
|
||||
const pixels = new ImageData(PATTERN_TILE_PIXELS, PATTERN_TILE_PIXELS)
|
||||
const { pattern, pixelsPerColumn } = picture
|
||||
for (let pixelZ = 0; pixelZ < PATTERN_TILE_PIXELS; pixelZ++) {
|
||||
for (let pixelX = 0; pixelX < PATTERN_TILE_PIXELS; pixelX++) {
|
||||
const pick = pattern.picks[Math.floor(pixelZ / pixelsPerColumn) * pattern.columns + Math.floor(pixelX / pixelsPerColumn)]
|
||||
if (pick !== NO_PATTERN_BLOCK) {
|
||||
writePixel(pixels, (pixelZ * PATTERN_TILE_PIXELS + pixelX) * 4, picture, pick, pixelX % pixelsPerColumn, pixelZ % pixelsPerColumn)
|
||||
}
|
||||
}
|
||||
}
|
||||
return pixels
|
||||
}
|
||||
|
||||
/**
|
||||
* The block's texture at a spot within its column, and its colour where it has no texture or the texture is see
|
||||
* through, such as between leaves, so a palette reads as solid ground.
|
||||
*/
|
||||
function writePixel(pixels: ImageData, offset: number, picture: PatternPicture, pick: number, insideX: number, insideZ: number): void {
|
||||
const texture = picture.textures[pick] ?? null
|
||||
if (texture !== null) {
|
||||
const textureX = Math.floor((insideX * texture.width) / picture.pixelsPerColumn)
|
||||
const textureZ = Math.floor((insideZ * texture.height) / picture.pixelsPerColumn)
|
||||
const from = (textureZ * texture.width + textureX) * 4
|
||||
if (texture.data[from + 3] >= OPAQUE_ENOUGH_ALPHA) {
|
||||
pixels.data.set(texture.data.subarray(from, from + 3), offset)
|
||||
pixels.data[offset + 3] = OPAQUE
|
||||
return
|
||||
}
|
||||
}
|
||||
const color = picture.colors[pick] ?? NO_COLOR
|
||||
pixels.data[offset] = (color >> 16) & 0xff
|
||||
pixels.data[offset + 1] = (color >> 8) & 0xff
|
||||
pixels.data[offset + 2] = color & 0xff
|
||||
pixels.data[offset + 3] = OPAQUE
|
||||
}
|
||||
@@ -4,21 +4,33 @@ import { texturePath, type ImageSource } from './textureAtlas'
|
||||
|
||||
const UNKNOWN_BLOCK_COLOR = 0x7f7f7f
|
||||
const OPAQUE_ENOUGH_ALPHA = 128
|
||||
const NO_TINT = 0xffffff
|
||||
|
||||
/** Each block's colour seen from above: its top face's texture averaged and tinted as the client tints it, read once. */
|
||||
/** Each block seen from above: its top face's texture tinted as the client tints it, and that texture's average colour, read once. */
|
||||
export class BlockColors {
|
||||
private readonly known = new Map<string, Promise<number>>()
|
||||
private readonly textures = new Map<string, Promise<ImageData | null>>()
|
||||
private readonly colors = new Map<string, Promise<number>>()
|
||||
|
||||
constructor(
|
||||
private readonly models: BlockModels,
|
||||
private readonly images: ImageSource
|
||||
) {}
|
||||
|
||||
/** The first frame of the block's top face texture, tinted; null when the block has no model or texture. */
|
||||
topTexture(block: string): Promise<ImageData | null> {
|
||||
let texture = this.textures.get(block)
|
||||
if (texture === undefined) {
|
||||
texture = this.readTopTexture(block).catch(() => null)
|
||||
this.textures.set(block, texture)
|
||||
}
|
||||
return texture
|
||||
}
|
||||
|
||||
colorOf(block: string): Promise<number> {
|
||||
let color = this.known.get(block)
|
||||
let color = this.colors.get(block)
|
||||
if (color === undefined) {
|
||||
color = this.read(block).catch(() => UNKNOWN_BLOCK_COLOR)
|
||||
this.known.set(block, color)
|
||||
color = this.topTexture(block).then((texture) => (texture === null ? UNKNOWN_BLOCK_COLOR : averageColor(texture)))
|
||||
this.colors.set(block, color)
|
||||
}
|
||||
return color
|
||||
}
|
||||
@@ -30,29 +42,47 @@ export class BlockColors {
|
||||
return new Map(names.map((name, index) => [name, colors[index]]))
|
||||
}
|
||||
|
||||
private async read(block: string): Promise<number> {
|
||||
private async readTopTexture(block: string): Promise<ImageData | null> {
|
||||
const model = await this.models.model(block)
|
||||
const top = model?.quads.filter((quad) => quad.facing === 'up').at(-1)
|
||||
const texture = top?.texture ?? model?.particle
|
||||
if (texture === undefined || texture === null) {
|
||||
return UNKNOWN_BLOCK_COLOR
|
||||
return null
|
||||
}
|
||||
const bitmap = await this.images.image(texturePath(texture))
|
||||
if (bitmap === null) {
|
||||
return UNKNOWN_BLOCK_COLOR
|
||||
return null
|
||||
}
|
||||
const state = parseState(block)
|
||||
return multiplied(averageColor(bitmap), blockTint(state.name, state.properties, top?.tintIndex ?? -1))
|
||||
return tinted(firstFrame(bitmap), blockTint(state.name, state.properties, top?.tintIndex ?? -1))
|
||||
}
|
||||
}
|
||||
|
||||
// The first frame only: an animated texture stacks its frames downwards.
|
||||
function averageColor(bitmap: ImageBitmap): number {
|
||||
// An animated texture stacks its frames downwards.
|
||||
function firstFrame(bitmap: ImageBitmap): ImageData {
|
||||
const side = bitmap.width
|
||||
const canvas = new OffscreenCanvas(side, side)
|
||||
const drawing = canvas.getContext('2d', { willReadFrequently: true })!
|
||||
drawing.drawImage(bitmap, 0, 0, side, side, 0, 0, side, side)
|
||||
const pixels = drawing.getImageData(0, 0, side, side).data
|
||||
return drawing.getImageData(0, 0, side, side)
|
||||
}
|
||||
|
||||
function tinted(texture: ImageData, tint: number): ImageData {
|
||||
if (tint === NO_TINT) {
|
||||
return texture
|
||||
}
|
||||
const pixels = texture.data
|
||||
const [red, green, blue] = [(tint >> 16) & 0xff, (tint >> 8) & 0xff, tint & 0xff]
|
||||
for (let offset = 0; offset < pixels.length; offset += 4) {
|
||||
pixels[offset] = Math.round((pixels[offset] * red) / 255)
|
||||
pixels[offset + 1] = Math.round((pixels[offset + 1] * green) / 255)
|
||||
pixels[offset + 2] = Math.round((pixels[offset + 2] * blue) / 255)
|
||||
}
|
||||
return texture
|
||||
}
|
||||
|
||||
function averageColor(texture: ImageData): number {
|
||||
const pixels = texture.data
|
||||
let [red, green, blue, counted] = [0, 0, 0, 0]
|
||||
for (let offset = 0; offset < pixels.length; offset += 4) {
|
||||
if (pixels[offset + 3] >= OPAQUE_ENOUGH_ALPHA) {
|
||||
@@ -67,8 +97,3 @@ function averageColor(bitmap: ImageBitmap): number {
|
||||
}
|
||||
return (Math.round(red / counted) << 16) | (Math.round(green / counted) << 8) | Math.round(blue / counted)
|
||||
}
|
||||
|
||||
function multiplied(color: number, tint: number): number {
|
||||
const channel = (shift: number): number => Math.round((((color >> shift) & 0xff) * ((tint >> shift) & 0xff)) / 255)
|
||||
return (channel(16) << 16) | (channel(8) << 8) | channel(0)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
const NUMBER = new Intl.NumberFormat('en-US')
|
||||
|
||||
/** An entry of a module view: its key, the name it is listed by, and the heading it is listed under (empty for none). */
|
||||
export interface BrowsableEntry {
|
||||
key: string
|
||||
name: string
|
||||
group: string
|
||||
}
|
||||
|
||||
interface EntryBrowserProps {
|
||||
title: string
|
||||
entries: BrowsableEntry[]
|
||||
current: string | null
|
||||
onSelect(key: string): void
|
||||
className?: string
|
||||
}
|
||||
|
||||
/** A view's entries under their headings, with a search over keys, names and headings (v3e ObjectBrowser). */
|
||||
export function EntryBrowser({ title, entries, current, onSelect, className }: EntryBrowserProps): React.JSX.Element {
|
||||
const [search, setSearch] = useState('')
|
||||
const wanted = search.trim().toLowerCase()
|
||||
const groups = useMemo(() => groupedEntries(entries, wanted), [entries, wanted])
|
||||
return (
|
||||
<section className={cn('flex min-h-0 flex-col border-b', className)}>
|
||||
<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">{NUMBER.format(entries.length)} in the pack</p>
|
||||
<Input
|
||||
className="mt-2 h-7 text-[12px]"
|
||||
placeholder="Find by name or folder"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
onKeyDown={(event) => event.key === 'Escape' && setSearch('')}
|
||||
/>
|
||||
</header>
|
||||
<ScrollArea className="min-h-0 flex-1 border-t">
|
||||
<div className="px-2 py-1.5">
|
||||
{groups.map(([group, members]) => (
|
||||
<section key={group}>
|
||||
{group !== '' && <h3 className="truncate px-2 pt-2 pb-1 text-[11px] font-semibold text-muted-foreground">{group}</h3>}
|
||||
{members.map((entry) => (
|
||||
<button
|
||||
key={entry.key}
|
||||
title={entry.key}
|
||||
onClick={() => onSelect(entry.key)}
|
||||
className={cn('flex h-[26px] w-full items-center rounded-md px-2 text-left', entry.key === current ? 'bg-selection' : 'hover:bg-accent')}
|
||||
>
|
||||
<span className="truncate">{entry.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
{groups.length === 0 && <p className="px-2 py-1 text-[12px] text-muted-foreground">{entries.length === 0 ? 'Nothing to show' : 'Nothing matches'}</p>}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function groupedEntries<Entry extends BrowsableEntry>(entries: Entry[], wanted: string): [string, Entry[]][] {
|
||||
const groups = new Map<string, Entry[]>()
|
||||
for (const entry of entries) {
|
||||
if (wanted !== '' && ![entry.key, entry.name, entry.group].some((text) => text.toLowerCase().includes(wanted))) {
|
||||
continue
|
||||
}
|
||||
const members = groups.get(entry.group) ?? []
|
||||
members.push(entry)
|
||||
groups.set(entry.group, members)
|
||||
}
|
||||
return [...groups.entries()]
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { ThemeChoice } from '../../../shared/bridge'
|
||||
import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient'
|
||||
import type { MapHover, MapLabel, Marker, PickDisplay, PickInspection, SceneViewInfo, ViewInfo, WorldInfo } from '../bridge/types'
|
||||
import type { MapHover, MapLabel, Marker, ModuleViewInfo, PickDisplay, PickInspection, ViewInfo, WorldInfo } from '../bridge/types'
|
||||
import type { Share } from '../map/census'
|
||||
import type { MapController, MapStatus, MapToggles } from '../map/MapController'
|
||||
import type { Highlight } from '../map/tileStyle'
|
||||
@@ -12,6 +12,7 @@ import { MapCanvas, type CanvasPoint } from './MapCanvas'
|
||||
import { PickInspector } from './PickInspector'
|
||||
import { RegionPreviewList } from './RegionPreviewList'
|
||||
import { NoiseStudio } from './NoiseStudio'
|
||||
import { PatternStudio } from './PatternStudio'
|
||||
import { SavedWorldStudio } from './SavedWorldStudio'
|
||||
import { SceneStudio } from './SceneStudio'
|
||||
import { WorldStudio3D } from './WorldStudio3D'
|
||||
@@ -61,10 +62,17 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
const [area, setArea] = useState<WorldRect | null>(null)
|
||||
const [packRevision, setPackRevision] = useState(0)
|
||||
const [sceneSummary, setSceneSummary] = useState<string | null>(null)
|
||||
const sceneViews = useSceneViews(client, packRevision)
|
||||
const views = useMemo(() => [...withAppViews(world.views), ...sceneViews.map(asViewInfo), NOISE], [world.views, sceneViews])
|
||||
const loadSceneViews = useCallback(() => client.sceneViews(), [client])
|
||||
const loadPatternViews = useCallback(() => client.patternViews(), [client])
|
||||
const sceneViews = useModuleViews(loadSceneViews, packRevision)
|
||||
const patternViews = useModuleViews(loadPatternViews, packRevision)
|
||||
const views = useMemo(
|
||||
() => [...withAppViews(world.views), ...patternViews.map(asViewInfo), ...sceneViews.map(asViewInfo), NOISE],
|
||||
[world.views, patternViews, sceneViews]
|
||||
)
|
||||
const sceneView = sceneViews.find((candidate) => candidate.id === viewId) ?? null
|
||||
const showsMap = sceneView === null && !APP_VIEW_IDS.has(viewId)
|
||||
const patternView = patternViews.find((candidate) => candidate.id === viewId) ?? null
|
||||
const showsMap = sceneView === null && patternView === null && !APP_VIEW_IDS.has(viewId)
|
||||
const view = views.find((candidate) => candidate.id === viewId) ?? views[0]
|
||||
const layer = useMemo<MapLayerQuery>(() => ({ view: viewId, preview: viewId === 'regions' ? preview : null }), [viewId, preview])
|
||||
const regions = usePreviewableRegions(client, packRevision)
|
||||
@@ -218,6 +226,8 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps
|
||||
</ViewList>
|
||||
{sceneView !== null ? (
|
||||
<SceneStudio client={client} view={sceneView} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
|
||||
) : patternView !== null ? (
|
||||
<PatternStudio client={client} view={patternView} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
|
||||
) : viewId === WORLD_3D.id ? (
|
||||
<WorldStudio3D client={client} world={world} mapArea={area} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
|
||||
) : viewId === SAVED_WORLD.id ? (
|
||||
@@ -315,7 +325,7 @@ function withAppViews(serverViews: ViewInfo[]): ViewInfo[] {
|
||||
return [...serverViews.slice(0, afterHeight), WORLD_3D, SAVED_WORLD, ...serverViews.slice(afterHeight)]
|
||||
}
|
||||
|
||||
function asViewInfo(view: SceneViewInfo): ViewInfo {
|
||||
function asViewInfo(view: ModuleViewInfo): ViewInfo {
|
||||
return { ...view, ...SCENE_GROUP }
|
||||
}
|
||||
|
||||
@@ -324,19 +334,18 @@ function statusLabel(viewLabel: string, previewName: string | null, sceneSummary
|
||||
return detail === null ? viewLabel : `${viewLabel} · ${detail}`
|
||||
}
|
||||
|
||||
/** The scene views the pack's modules show, read again after the pack reloads. */
|
||||
function useSceneViews(client: BridgeClient, packRevision: number): SceneViewInfo[] {
|
||||
const [views, setViews] = useState<SceneViewInfo[]>([])
|
||||
/** Views the pack's modules show, read again after the pack reloads; keep {@code load} stable. */
|
||||
function useModuleViews(load: () => Promise<ModuleViewInfo[]>, packRevision: number): ModuleViewInfo[] {
|
||||
const [views, setViews] = useState<ModuleViewInfo[]>([])
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
client
|
||||
.sceneViews()
|
||||
load()
|
||||
.then((found) => active && setViews(found))
|
||||
.catch(() => undefined)
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [client, packRevision])
|
||||
}, [load, packRevision])
|
||||
return views
|
||||
}
|
||||
|
||||
|
||||
@@ -7,13 +7,14 @@ import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { NoiseSource, NoiseTile } from '../bridge/types'
|
||||
import { NOISE_TILE_PIXELS, type NoiseController, type NoiseStatus } from '../noise/NoiseController'
|
||||
import type { TiledFraming as TerrainFraming } from '../map/TiledView'
|
||||
import { NOISE_PALETTES, noiseScale, type NoisePaletteId, type NoiseScale } from '../noise/noiseScale'
|
||||
import { NoiseTerrain, type NoiseArea } from '../noise/noiseTerrain'
|
||||
import { createNoiseView, NOISE_TILE_PIXELS, type NoiseStatus, type NoiseView } from '../noise/noiseTiles'
|
||||
import { buildTerrainMesh } from '../scene/terrainMesh'
|
||||
import { hexColor } from './colors'
|
||||
import { NoiseCanvas } from './NoiseCanvas'
|
||||
import { SceneViewport } from './SceneViewport'
|
||||
import { TiledCanvas } from './TiledCanvas'
|
||||
|
||||
type NoiseDisplay = 'flat' | 'terrain'
|
||||
|
||||
@@ -46,9 +47,14 @@ export function NoiseStudio({ client, packRevision, onSummary, tell }: NoiseStud
|
||||
const [reliefBlocks, setReliefBlocks] = useState(DEFAULT_RELIEF_BLOCKS)
|
||||
const [status, setStatus] = useState<NoiseStatus | null>(null)
|
||||
const [terrainFraming, setTerrainFraming] = useState<TerrainFraming | null>(null)
|
||||
const controllerRef = useRef<NoiseController | null>(null)
|
||||
const controllerRef = useRef<NoiseView | null>(null)
|
||||
const scale = useMemo(() => noiseScale(paletteId, source), [paletteId, source])
|
||||
const listener = useMemo(() => ({ onStatus: setStatus, onError: tell }), [tell])
|
||||
const latestTell = useRef(tell)
|
||||
latestTell.current = tell
|
||||
const createView = useCallback(
|
||||
(canvas: HTMLCanvasElement) => createNoiseView(canvas, client, { onStatus: setStatus, onError: (message) => latestTell.current(message) }),
|
||||
[client]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const layer = source === null ? null : { sourceId: source.id, seed, revision: packRevision }
|
||||
@@ -75,10 +81,9 @@ export function NoiseStudio({ client, packRevision, onSummary, tell }: NoiseStud
|
||||
return (
|
||||
<>
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<NoiseCanvas
|
||||
client={client}
|
||||
controllerRef={controllerRef}
|
||||
listener={listener}
|
||||
<TiledCanvas
|
||||
create={createView}
|
||||
viewRef={controllerRef}
|
||||
className={cn('absolute inset-0 size-full cursor-grab active:cursor-grabbing', display !== 'flat' && 'invisible')}
|
||||
/>
|
||||
{display === 'terrain' && source !== null && terrainFraming !== null && (
|
||||
@@ -263,12 +268,6 @@ function ReliefControl({ blocks, onChange }: { blocks: number; onChange(blocks:
|
||||
)
|
||||
}
|
||||
|
||||
interface TerrainFraming {
|
||||
centerX: number
|
||||
centerZ: number
|
||||
renderScale: number
|
||||
}
|
||||
|
||||
function NoiseTerrainView({
|
||||
client,
|
||||
source,
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import { ChevronLeft, ChevronRight, RotateCcw } from 'lucide-react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { ModuleViewInfo, PatternEntry } from '../bridge/types'
|
||||
import { createPatternView, type PatternBlocks, type PatternLayer, type PatternStatus, type PatternView } from '../pattern/patternTiles'
|
||||
import { BlockColors } from '../scene/blockColors'
|
||||
import { BlockModels } from '../scene/blockModels'
|
||||
import { BridgeAssets } from '../scene/BridgeAssets'
|
||||
import { hexColor } from './colors'
|
||||
import { EntryBrowser } from './EntryBrowser'
|
||||
import { TiledCanvas } from './TiledCanvas'
|
||||
|
||||
const DEFAULT_NAMESPACE_PREFIX = 'minecraft:'
|
||||
// A layer thinner than the depth shown, or a palette with no block for the spot.
|
||||
const NONE_LABEL = 'nothing at this depth'
|
||||
|
||||
/** The blocks the shown layer's tiles placed so far by name, with their colours, and whether some spots got none. */
|
||||
interface LegendBlocks {
|
||||
colors: Map<string, number>
|
||||
someNone: boolean
|
||||
}
|
||||
|
||||
const EMPTY_LEGEND: LegendBlocks = { colors: new Map(), someNone: false }
|
||||
const PILL = 'pointer-events-none absolute rounded-md border border-overlay-border bg-card/90 px-3 py-1.5 text-[12px] text-secondary-text'
|
||||
|
||||
interface PatternStudioProps {
|
||||
client: BridgeClient
|
||||
view: ModuleViewInfo
|
||||
/** Changes when the pack reloads, so the entries and the tiles are read again. */
|
||||
packRevision: number
|
||||
onSummary(summary: string | null): void
|
||||
tell(message: string): void
|
||||
}
|
||||
|
||||
/** A pattern view: its entries on the right, what the chosen one places from above in the middle (v3e palette explorer). */
|
||||
export function PatternStudio({ client, view, packRevision, onSummary, tell }: PatternStudioProps): React.JSX.Element {
|
||||
const entries = usePatternEntries(client, view.id, packRevision, tell)
|
||||
const [chosen, setChosen] = useState<{ key: string; depth: number } | null>(null)
|
||||
const entry = entries.find((candidate) => candidate.key === chosen?.key) ?? entries[0] ?? null
|
||||
const depth = entry !== null && chosen?.key === entry.key ? Math.min(chosen.depth, entry.depths - 1) : 0
|
||||
const layer = useMemo<PatternLayer | null>(
|
||||
() => (entry === null ? null : { viewId: view.id, key: entry.key, depth, revision: packRevision }),
|
||||
[view.id, entry, depth, packRevision]
|
||||
)
|
||||
const [status, setStatus] = useState<PatternStatus | null>(null)
|
||||
const { legend, createView } = usePatternView(client, layer, setStatus, tell)
|
||||
const viewRef = useRef<PatternView | null>(null)
|
||||
|
||||
useEffect(() => viewRef.current?.show(layer, 'blocks'), [layer])
|
||||
useEffect(() => onSummary(entry === null ? null : `${entry.group} · ${entry.name}`), [entry, onSummary])
|
||||
useEffect(() => () => onSummary(null), [onSummary])
|
||||
|
||||
const chooseDepth = (next: number): void => {
|
||||
if (entry !== null) {
|
||||
setChosen({ key: entry.key, depth: (next + entry.depths) % entry.depths })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<TiledCanvas create={createView} viewRef={viewRef} className="absolute inset-0 size-full cursor-grab active:cursor-grabbing" />
|
||||
<div className="absolute top-3 left-3 flex items-center gap-1 rounded-md border border-overlay-border bg-card/90 p-1 text-[12px] tabular-nums">
|
||||
{entry !== null && entry.depths > 1 && (
|
||||
<>
|
||||
<Button variant="ghost" size="icon-sm" title="Higher" onClick={() => chooseDepth(depth - 1)}>
|
||||
<ChevronLeft />
|
||||
</Button>
|
||||
<span className="px-1">
|
||||
Depth {depth + 1} of {entry.depths}
|
||||
</span>
|
||||
<Button variant="ghost" size="icon-sm" title="Deeper" onClick={() => chooseDepth(depth + 1)}>
|
||||
<ChevronRight />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button variant="ghost" size="icon-sm" title="Back to 0, 0" onClick={() => viewRef.current?.resetView()}>
|
||||
<RotateCcw />
|
||||
</Button>
|
||||
</div>
|
||||
{status !== null && entry !== null && <div className={cn(PILL, 'right-3 bottom-3 tabular-nums')}>{readout(status)}</div>}
|
||||
</div>
|
||||
<aside className="flex w-[250px] shrink-0 flex-col border-l bg-card">
|
||||
<EntryBrowser className="flex-[6]" title={view.label} entries={entries} current={entry?.key ?? null} onSelect={(key) => setChosen({ key, depth: 0 })} />
|
||||
<EntryFacts entry={entry} />
|
||||
<Legend blocks={legend} />
|
||||
</aside>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function readout(status: PatternStatus): string {
|
||||
const spot = `${Math.floor(status.cursorX)}, ${Math.floor(status.cursorZ)}`
|
||||
switch (status.spot.kind) {
|
||||
case 'block':
|
||||
return `${spot} · ${shortName(status.spot.block)}`
|
||||
case 'none':
|
||||
return `${spot} · ${NONE_LABEL}`
|
||||
case 'unknown':
|
||||
return spot
|
||||
}
|
||||
}
|
||||
|
||||
/** The block without its namespace when that is Minecraft's, and without its state, as a builder names it. */
|
||||
function shortName(block: string): string {
|
||||
const material = block.includes('[') ? block.slice(0, block.indexOf('[')) : block
|
||||
return material.startsWith(DEFAULT_NAMESPACE_PREFIX) ? material.slice(DEFAULT_NAMESPACE_PREFIX.length) : material
|
||||
}
|
||||
|
||||
function usePatternEntries(client: BridgeClient, viewId: string, packRevision: number, tell: (message: string) => void): PatternEntry[] {
|
||||
const [entries, setEntries] = useState<PatternEntry[]>([])
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
client
|
||||
.patternEntries(viewId)
|
||||
.then((found) => active && setEntries(found))
|
||||
.catch((failure: Error) => active && tell(failure.message))
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [client, viewId, packRevision, tell])
|
||||
return entries
|
||||
}
|
||||
|
||||
/** The view's maker for the canvas, and the blocks the shown layer's tiles placed so far with their colours. */
|
||||
function usePatternView(
|
||||
client: BridgeClient,
|
||||
layer: PatternLayer | null,
|
||||
onStatus: (status: PatternStatus) => void,
|
||||
tell: (message: string) => void
|
||||
): { legend: LegendBlocks; createView(canvas: HTMLCanvasElement): PatternView } {
|
||||
const blockColors = useMemo(() => {
|
||||
const images = new BridgeAssets(client, () => {})
|
||||
return new BlockColors(new BlockModels(images), images)
|
||||
}, [client])
|
||||
const [legend, setLegend] = useState<LegendBlocks>(EMPTY_LEGEND)
|
||||
const latest = useRef({ layer, onStatus, tell })
|
||||
latest.current = { layer, onStatus, tell }
|
||||
|
||||
useEffect(() => setLegend(EMPTY_LEGEND), [layer])
|
||||
|
||||
const createView = useCallback(
|
||||
(canvas: HTMLCanvasElement) =>
|
||||
createPatternView(canvas, client, blockColors, {
|
||||
onStatus: (status) => latest.current.onStatus(status),
|
||||
onBlocks: (tileLayer, blocks) => tileLayer === latest.current.layer && setLegend((shown) => withBlocks(shown, blocks)),
|
||||
onError: (message) => latest.current.tell(message)
|
||||
}),
|
||||
[client, blockColors]
|
||||
)
|
||||
return { legend, createView }
|
||||
}
|
||||
|
||||
/** The legend with the tile's blocks added, one row per block whatever its state; unchanged when it had them all. */
|
||||
function withBlocks(shown: LegendBlocks, tile: PatternBlocks): LegendBlocks {
|
||||
const added = [...tile.colors].map(([block, color]) => [shortName(block), color] as const).filter(([name]) => !shown.colors.has(name))
|
||||
const someNone = shown.someNone || tile.someNone
|
||||
if (added.length === 0 && someNone === shown.someNone) {
|
||||
return shown
|
||||
}
|
||||
return { colors: new Map([...shown.colors, ...added]), someNone }
|
||||
}
|
||||
|
||||
function EntryFacts({ entry }: { entry: PatternEntry | null }): React.JSX.Element | null {
|
||||
if (entry === null) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<section className="border-b px-4 pt-2.5 pb-2.5">
|
||||
<h2 className="truncate text-[11px] font-semibold text-muted-foreground" title={entry.key}>
|
||||
{entry.group} · {entry.name}
|
||||
</h2>
|
||||
{entry.facts.map((fact) => (
|
||||
<p key={fact} className="pt-1 text-[12px] leading-snug text-secondary-text">
|
||||
{fact}
|
||||
</p>
|
||||
))}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** The blocks the shown tiles place, each with the colour it is drawn in from afar. */
|
||||
function Legend({ blocks }: { blocks: LegendBlocks }): React.JSX.Element {
|
||||
const sorted = [...blocks.colors.entries()].sort(([first], [second]) => first.localeCompare(second))
|
||||
return (
|
||||
<section className="flex min-h-0 flex-[3] flex-col">
|
||||
<h2 className="px-4 pt-2.5 pb-1.5 text-[11px] font-semibold text-muted-foreground">Blocks</h2>
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="px-4 pb-2">
|
||||
{sorted.map(([block, color]) => (
|
||||
<div key={block} className="flex h-[26px] items-center gap-2">
|
||||
<span className="size-3 shrink-0 rounded-[3px] border border-foreground/25" style={{ background: hexColor(color) }} />
|
||||
<span className="min-w-0 flex-1 truncate">{block}</span>
|
||||
</div>
|
||||
))}
|
||||
{blocks.someNone && (
|
||||
<div className="flex h-[26px] items-center gap-2 text-secondary-text">
|
||||
<span className="size-3 shrink-0 rounded-[3px] border border-foreground/25 bg-map-background" />
|
||||
<span className="min-w-0 flex-1 truncate">Nothing at this depth</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,15 +1,14 @@
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { SceneEntry, SceneViewInfo } from '../bridge/types'
|
||||
import type { ModuleViewInfo, SceneEntry } from '../bridge/types'
|
||||
import { BlockModels } from '../scene/blockModels'
|
||||
import { BridgeAssets } from '../scene/BridgeAssets'
|
||||
import { INTS_PER_BLOCK, type BlockScene } from '../scene/sceneDecoding'
|
||||
import { buildSceneMesh, type SceneMesh } from '../scene/sceneMesh'
|
||||
import { EntryBrowser } from './EntryBrowser'
|
||||
import { SceneViewport } from './SceneViewport'
|
||||
|
||||
const NUMBER = new Intl.NumberFormat('en-US')
|
||||
@@ -17,7 +16,7 @@ const DEFAULT_NAMESPACE_PREFIX = 'minecraft:'
|
||||
|
||||
interface SceneStudioProps {
|
||||
client: BridgeClient
|
||||
view: SceneViewInfo
|
||||
view: ModuleViewInfo
|
||||
/** Changes when the pack reloads, so the entries and the scene are read again. */
|
||||
packRevision: number
|
||||
/** What the status bar says about the scene, or null while none is shown. */
|
||||
@@ -68,7 +67,7 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce
|
||||
)}
|
||||
</div>
|
||||
<aside className="flex w-[250px] shrink-0 flex-col border-l bg-card">
|
||||
<EntryBrowser title={view.label} entries={entries} current={entry?.key ?? null} onSelect={(key) => setChosen({ key, variant: 0 })} />
|
||||
<EntryBrowser className="flex-[7]" title={view.label} entries={entries} current={entry?.key ?? null} onSelect={(key) => setChosen({ key, variant: 0 })} />
|
||||
<BlockList scene={scene} />
|
||||
</aside>
|
||||
</>
|
||||
@@ -146,68 +145,6 @@ function disposeMesh(mesh: SceneMesh | null): void {
|
||||
mesh?.dispose()
|
||||
}
|
||||
|
||||
interface EntryBrowserProps {
|
||||
title: string
|
||||
entries: SceneEntry[]
|
||||
current: string | null
|
||||
onSelect(key: string): void
|
||||
}
|
||||
|
||||
/** The view's entries under their folders, with a search over names and folders (v3e ObjectBrowser). */
|
||||
function EntryBrowser({ title, entries, current, onSelect }: EntryBrowserProps): React.JSX.Element {
|
||||
const [search, setSearch] = useState('')
|
||||
const wanted = search.trim().toLowerCase()
|
||||
const groups = useMemo(() => groupedEntries(entries, wanted), [entries, wanted])
|
||||
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">{NUMBER.format(entries.length)} in the pack</p>
|
||||
<Input
|
||||
className="mt-2 h-7 text-[12px]"
|
||||
placeholder="Find by name or folder"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
onKeyDown={(event) => event.key === 'Escape' && setSearch('')}
|
||||
/>
|
||||
</header>
|
||||
<ScrollArea className="min-h-0 flex-1 border-t">
|
||||
<div className="px-2 py-1.5">
|
||||
{groups.map(([group, members]) => (
|
||||
<section key={group}>
|
||||
{group !== '' && <h3 className="truncate px-2 pt-2 pb-1 text-[11px] font-semibold text-muted-foreground">{group}</h3>}
|
||||
{members.map((entry) => (
|
||||
<button
|
||||
key={entry.key}
|
||||
title={entry.key}
|
||||
onClick={() => onSelect(entry.key)}
|
||||
className={cn('flex h-[26px] w-full items-center rounded-md px-2 text-left', entry.key === current ? 'bg-selection' : 'hover:bg-accent')}
|
||||
>
|
||||
<span className="truncate">{entry.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
{groups.length === 0 && <p className="px-2 py-1 text-[12px] text-muted-foreground">{entries.length === 0 ? 'Nothing to show' : 'Nothing matches'}</p>}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function groupedEntries(entries: SceneEntry[], wanted: string): [string, SceneEntry[]][] {
|
||||
const groups = new Map<string, SceneEntry[]>()
|
||||
for (const entry of entries) {
|
||||
if (wanted !== '' && !entry.key.toLowerCase().includes(wanted)) {
|
||||
continue
|
||||
}
|
||||
const members = groups.get(entry.group) ?? []
|
||||
members.push(entry)
|
||||
groups.set(entry.group, members)
|
||||
}
|
||||
return [...groups.entries()]
|
||||
}
|
||||
|
||||
/** The blocks of the scene, most used first, each with its count (v3e ObjectOverviewPanel). */
|
||||
function BlockList({ scene }: { scene: BlockScene | null }): React.JSX.Element {
|
||||
const counts = useMemo(() => (scene === null ? [] : blockCounts(scene)), [scene])
|
||||
|
||||
@@ -1,45 +1,41 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||
import { NoiseController, type NoiseListener } from '../noise/NoiseController'
|
||||
import type { TiledView } from '../map/TiledView'
|
||||
|
||||
interface NoiseCanvasProps {
|
||||
client: BridgeClient
|
||||
controllerRef: React.RefObject<NoiseController | null>
|
||||
listener: NoiseListener
|
||||
type AnyTiledView = TiledView<unknown, unknown, unknown>
|
||||
|
||||
interface TiledCanvasProps<View extends AnyTiledView> {
|
||||
/** Makes the view on the canvas; called again only when it changes, so keep it stable. */
|
||||
create(canvas: HTMLCanvasElement): View
|
||||
viewRef: React.RefObject<View | null>
|
||||
className?: string
|
||||
}
|
||||
|
||||
// One wheel notch is about 100; this zooms about 15% per notch, and smoothly on touchpads.
|
||||
const WHEEL_ZOOM_PER_DELTA = 0.002
|
||||
|
||||
/** The noise from above: drag to move, wheel to zoom. */
|
||||
export function NoiseCanvas({ client, controllerRef, listener, className }: NoiseCanvasProps): React.JSX.Element {
|
||||
/** A tiled view from above: drag to move, wheel to zoom. */
|
||||
export function TiledCanvas<View extends AnyTiledView>({ create, viewRef, className }: TiledCanvasProps<View>): React.JSX.Element {
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const latestListener = useRef(listener)
|
||||
latestListener.current = listener
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current!
|
||||
const noise = new NoiseController(canvas, client, {
|
||||
onStatus: (status) => latestListener.current.onStatus(status),
|
||||
onError: (message) => latestListener.current.onError(message)
|
||||
})
|
||||
controllerRef.current = noise
|
||||
const resize = new ResizeObserver(([entry]) => noise.resize(entry.contentRect.width, entry.contentRect.height))
|
||||
const view = create(canvas)
|
||||
viewRef.current = view
|
||||
const resize = new ResizeObserver(([entry]) => view.resize(entry.contentRect.width, entry.contentRect.height))
|
||||
resize.observe(canvas)
|
||||
const stopMouse = followMouse(canvas, noise)
|
||||
const stopMouse = followMouse(canvas, view)
|
||||
return () => {
|
||||
stopMouse()
|
||||
resize.disconnect()
|
||||
noise.close()
|
||||
controllerRef.current = null
|
||||
view.close()
|
||||
viewRef.current = null
|
||||
}
|
||||
}, [client, controllerRef])
|
||||
}, [create, viewRef])
|
||||
|
||||
return <canvas ref={canvasRef} className={className} />
|
||||
}
|
||||
|
||||
function followMouse(canvas: HTMLCanvasElement, noise: NoiseController): () => void {
|
||||
function followMouse(canvas: HTMLCanvasElement, view: AnyTiledView): () => void {
|
||||
let last: { x: number; y: number } | null = null
|
||||
const pointOf = (event: MouseEvent): { x: number; y: number } => {
|
||||
const bounds = canvas.getBoundingClientRect()
|
||||
@@ -52,20 +48,20 @@ function followMouse(canvas: HTMLCanvasElement, noise: NoiseController): () => v
|
||||
}
|
||||
}
|
||||
const move = (event: PointerEvent): void => {
|
||||
noise.setCursor(pointOf(event))
|
||||
view.setCursor(pointOf(event))
|
||||
if (last !== null) {
|
||||
noise.panBy(event.clientX - last.x, event.clientY - last.y)
|
||||
view.panBy(event.clientX - last.x, event.clientY - last.y)
|
||||
last = { x: event.clientX, y: event.clientY }
|
||||
}
|
||||
}
|
||||
const up = (): void => {
|
||||
last = null
|
||||
}
|
||||
const leave = (): void => noise.setCursor(null)
|
||||
const leave = (): void => view.setCursor(null)
|
||||
const wheel = (event: WheelEvent): void => {
|
||||
event.preventDefault()
|
||||
const point = pointOf(event)
|
||||
noise.zoomAt(2 ** (-event.deltaY * WHEEL_ZOOM_PER_DELTA), point.x, point.y)
|
||||
view.zoomAt(2 ** (-event.deltaY * WHEEL_ZOOM_PER_DELTA), point.x, point.y)
|
||||
}
|
||||
canvas.addEventListener('pointerdown', down)
|
||||
canvas.addEventListener('pointermove', move)
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AudioWaveform, Box, Gem, Globe, HardDrive, Map as MapIcon, Mountain, Shapes, Sprout, Trees, Waves, type LucideIcon } from 'lucide-react'
|
||||
import { AudioWaveform, Box, Gem, Globe, HardDrive, Layers, Map as MapIcon, Mountain, Shapes, Sprout, Trees, Waves, type LucideIcon } from 'lucide-react'
|
||||
import { Kbd } from '@/components/ui/kbd'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
@@ -16,7 +16,8 @@ const VIEW_ICONS: Record<string, LucideIcon> = {
|
||||
seaBiomes: Waves,
|
||||
caveBiomes: Gem,
|
||||
'iris:objects': Box,
|
||||
'iris:objects/procedural': Shapes
|
||||
'iris:objects/procedural': Shapes,
|
||||
'iris:terrain/palettes': Layers
|
||||
}
|
||||
|
||||
interface ViewListProps {
|
||||
|
||||
Reference in new issue
Block a user