mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 00:04:42 +00:00
Merge IrisStudio into studio/ with its history
git-subtree-dir: studio git-subtree-mainline:68ae3c8d3agit-subtree-split:1c50eaf776
This commit is contained in:
commit
4e226b93f4
92 files changed
+14197
No files matched your search
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
out/
|
||||
dist/
|
||||
*.log
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/renderer/src/styles.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { resolve } from 'node:path'
|
||||
import { defineConfig } from 'electron-vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
export default defineConfig({
|
||||
main: {},
|
||||
preload: {
|
||||
build: {
|
||||
rollupOptions: {
|
||||
output: { format: 'cjs', entryFileNames: '[name].cjs' }
|
||||
}
|
||||
}
|
||||
},
|
||||
renderer: {
|
||||
resolve: {
|
||||
alias: { '@': resolve(import.meta.dirname, 'src/renderer/src') }
|
||||
},
|
||||
plugins: [react(), tailwindcss()]
|
||||
}
|
||||
})
|
||||
Generated
+4590
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "iris-studio",
|
||||
"productName": "Iris Studio",
|
||||
"version": "0.1.0",
|
||||
"description": "The studio app for Iris worlds: maps, objects and editors, connected to a running server",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "out/main/index.js",
|
||||
"scripts": {
|
||||
"dev": "electron-vite dev",
|
||||
"build": "electron-vite build",
|
||||
"start": "electron-vite preview",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.4",
|
||||
"@types/node": "^26.6.6",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@types/three": "^0.187.0",
|
||||
"@vitejs/plugin-react": "^6.2.1",
|
||||
"electron": "^45.2.3",
|
||||
"electron-vite": "^6.0.0",
|
||||
"tailwindcss": "^4.3.4",
|
||||
"typescript": "^7.0.2",
|
||||
"vite": "^8.3.6",
|
||||
"vitest": "^5.1.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cn": "^0.5.2",
|
||||
"lucide-react": "^1.69.0",
|
||||
"radix-ui": "^1.8.1",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"tailwind-merge": "^3.7.0",
|
||||
"three": "^0.187.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { app, BrowserWindow, clipboard, ipcMain, nativeTheme, shell } from 'electron'
|
||||
import { readdir, readFile } from 'node:fs/promises'
|
||||
import { homedir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import type { BridgeConnection, ThemeChoice } from '../shared/bridge'
|
||||
|
||||
const CONNECTION_FOLDER = join(homedir(), '.iris', 'studio', 'bridges')
|
||||
const LINK_PREFIX = 'iris-studio://'
|
||||
const DARK_BACKGROUND = '#1e1f22'
|
||||
const WINDOW_SIZE = { width: 1440, height: 880, minWidth: 820, minHeight: 520 }
|
||||
|
||||
let window: BrowserWindow | null = null
|
||||
let pendingLink: string | null = findLink(process.argv)
|
||||
|
||||
function findLink(argv: string[]): string | null {
|
||||
return argv.find((argument) => argument.startsWith(LINK_PREFIX)) ?? null
|
||||
}
|
||||
|
||||
function isRunning(pid: unknown): boolean {
|
||||
if (typeof pid !== 'number') {
|
||||
return true
|
||||
}
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
return true
|
||||
} catch (error) {
|
||||
return (error as NodeJS.ErrnoException).code === 'EPERM'
|
||||
}
|
||||
}
|
||||
|
||||
/** The bridges announced on this machine whose server still runs, newest first. */
|
||||
async function listBridges(): Promise<BridgeConnection[]> {
|
||||
let files: string[]
|
||||
try {
|
||||
files = (await readdir(CONNECTION_FOLDER)).filter((name) => name.endsWith('.json'))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
const bridges = await Promise.all(files.map(readConnection))
|
||||
return bridges
|
||||
.filter((bridge): bridge is BridgeConnection => bridge !== null)
|
||||
.sort((first, second) => (second.startedMillis ?? 0) - (first.startedMillis ?? 0))
|
||||
}
|
||||
|
||||
async function readConnection(name: string): Promise<BridgeConnection | null> {
|
||||
try {
|
||||
const file = JSON.parse(await readFile(join(CONNECTION_FOLDER, name), 'utf8'))
|
||||
if (!isRunning(file.pid) || typeof file.port !== 'number' || typeof file.token !== 'string') {
|
||||
return null
|
||||
}
|
||||
return { world: String(file.world ?? ''), port: file.port, token: file.token, startedMillis: file.startedMillis }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function createWindow(): void {
|
||||
window = new BrowserWindow({
|
||||
...WINDOW_SIZE,
|
||||
title: 'Iris Studio',
|
||||
backgroundColor: DARK_BACKGROUND,
|
||||
autoHideMenuBar: true,
|
||||
show: false,
|
||||
webPreferences: {
|
||||
preload: join(import.meta.dirname, '../preload/index.cjs'),
|
||||
sandbox: true,
|
||||
contextIsolation: true
|
||||
}
|
||||
})
|
||||
window.once('ready-to-show', () => window?.show())
|
||||
window.webContents.setWindowOpenHandler(({ url }) => {
|
||||
void shell.openExternal(url)
|
||||
return { action: 'deny' }
|
||||
})
|
||||
if (process.env.ELECTRON_RENDERER_URL) {
|
||||
void window.loadURL(process.env.ELECTRON_RENDERER_URL)
|
||||
} else {
|
||||
void window.loadFile(join(import.meta.dirname, '../renderer/index.html'))
|
||||
}
|
||||
}
|
||||
|
||||
function deliverLink(link: string): void {
|
||||
if (window === null) {
|
||||
pendingLink = link
|
||||
return
|
||||
}
|
||||
window.webContents.send('studio:link', link)
|
||||
if (window.isMinimized()) {
|
||||
window.restore()
|
||||
}
|
||||
window.focus()
|
||||
}
|
||||
|
||||
if (!app.requestSingleInstanceLock()) {
|
||||
app.quit()
|
||||
} else {
|
||||
app.setAsDefaultProtocolClient('iris-studio')
|
||||
app.on('second-instance', (_event, argv) => {
|
||||
const link = findLink(argv)
|
||||
if (link !== null) {
|
||||
deliverLink(link)
|
||||
} else {
|
||||
window?.focus()
|
||||
}
|
||||
})
|
||||
app.on('open-url', (event, url) => {
|
||||
event.preventDefault()
|
||||
deliverLink(url)
|
||||
})
|
||||
|
||||
ipcMain.handle('studio:list-bridges', listBridges)
|
||||
ipcMain.handle('studio:initial-link', () => {
|
||||
const link = pendingLink
|
||||
pendingLink = null
|
||||
return link
|
||||
})
|
||||
ipcMain.on('studio:set-theme', (_event, theme: ThemeChoice) => {
|
||||
nativeTheme.themeSource = theme
|
||||
})
|
||||
ipcMain.on('studio:copy-text', (_event, text: string) => clipboard.writeText(text))
|
||||
|
||||
void app.whenReady().then(createWindow)
|
||||
app.on('window-all-closed', () => app.quit())
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { contextBridge, ipcRenderer, type IpcRendererEvent } from 'electron'
|
||||
import type { StudioHost, ThemeChoice } from '../shared/bridge'
|
||||
|
||||
const host: StudioHost = {
|
||||
listBridges: () => ipcRenderer.invoke('studio:list-bridges'),
|
||||
initialLink: () => ipcRenderer.invoke('studio:initial-link'),
|
||||
onLink: (listener) => {
|
||||
const forward = (_event: IpcRendererEvent, link: string): void => listener(link)
|
||||
ipcRenderer.on('studio:link', forward)
|
||||
return () => ipcRenderer.removeListener('studio:link', forward)
|
||||
},
|
||||
setTheme: (theme: ThemeChoice) => ipcRenderer.send('studio:set-theme', theme),
|
||||
copyText: (text: string) => ipcRenderer.send('studio:copy-text', text)
|
||||
}
|
||||
|
||||
contextBridge.exposeInMainWorld('studio', host)
|
||||
@@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta
|
||||
http-equiv="Content-Security-Policy"
|
||||
content="default-src 'self'; connect-src 'self' http://127.0.0.1:* ws://localhost:*; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'"
|
||||
/>
|
||||
<title>Iris Studio</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { parseStudioLink, type BridgeConnection } from '../../shared/bridge'
|
||||
import { BridgeClient } from './bridge/BridgeClient'
|
||||
import type { WorldInfo } from './bridge/types'
|
||||
import { ConnectScreen } from './studio/ConnectScreen'
|
||||
import { MapStudio } from './studio/MapStudio'
|
||||
import { useTheme } from './studio/theme'
|
||||
|
||||
interface Session {
|
||||
client: BridgeClient
|
||||
world: WorldInfo
|
||||
}
|
||||
|
||||
/** The studio: a connect screen until a bridge answers, then the map of its world. */
|
||||
export function App(): React.JSX.Element {
|
||||
const theme = useTheme()
|
||||
const [session, setSession] = useState<Session | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [connecting, setConnecting] = useState(false)
|
||||
|
||||
const connect = useCallback(async (connection: BridgeConnection) => {
|
||||
setConnecting(true)
|
||||
setError(null)
|
||||
const client = new BridgeClient(connection)
|
||||
try {
|
||||
setSession({ client, world: await client.world() })
|
||||
} catch (failure) {
|
||||
setError(failure instanceof Error ? failure.message : String(failure))
|
||||
} finally {
|
||||
setConnecting(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const connectLink = useCallback(
|
||||
(link: string) => {
|
||||
const connection = parseStudioLink(link)
|
||||
if (connection === null) {
|
||||
setError('That is not a studio link')
|
||||
return
|
||||
}
|
||||
void connect(connection)
|
||||
},
|
||||
[connect]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
void window.studio.initialLink().then((link) => link !== null && connectLink(link))
|
||||
return window.studio.onLink(connectLink)
|
||||
}, [connectLink])
|
||||
|
||||
if (session === null) {
|
||||
return <ConnectScreen connecting={connecting} error={error} onConnect={connect} onLink={connectLink} />
|
||||
}
|
||||
return (
|
||||
<MapStudio
|
||||
key={`${session.client.connection.port}`}
|
||||
client={session.client}
|
||||
world={session.world}
|
||||
theme={theme}
|
||||
onDisconnect={() => setSession(null)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
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 {
|
||||
EditorState,
|
||||
GraphEdit,
|
||||
MapHover,
|
||||
MapLabel,
|
||||
MapTile,
|
||||
Marker,
|
||||
ModuleViewInfo,
|
||||
NoiseSource,
|
||||
NoiseTile,
|
||||
PatternEntry,
|
||||
PatternTile,
|
||||
PickInspection,
|
||||
SavedStart,
|
||||
SavedTile,
|
||||
SavedWorldInfo,
|
||||
SceneEntry,
|
||||
SceneViewInfo,
|
||||
WorldInfo
|
||||
} from './types'
|
||||
|
||||
export const STATUS_NOT_FOUND = 404
|
||||
export const STATUS_CONFLICT = 409
|
||||
export const STATUS_UNAVAILABLE = 503
|
||||
|
||||
export class BridgeError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
message: string
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
/** 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
|
||||
preview: string | null
|
||||
}
|
||||
|
||||
export interface WorldRect {
|
||||
minX: number
|
||||
minZ: number
|
||||
maxX: number
|
||||
maxZ: number
|
||||
}
|
||||
|
||||
export interface BridgeEvents {
|
||||
onWorld(running: boolean): void
|
||||
onPlayers(players: Marker[]): void
|
||||
onClosed(): void
|
||||
}
|
||||
|
||||
const EVENT_SEPARATOR = '\n\n'
|
||||
|
||||
/** One connection to a world's bridge, over HTTP on the loopback interface. */
|
||||
export class BridgeClient {
|
||||
private readonly base: string
|
||||
private readonly authorization: string
|
||||
|
||||
constructor(readonly connection: BridgeConnection) {
|
||||
this.base = `http://127.0.0.1:${connection.port}/v1/`
|
||||
this.authorization = `Bearer ${connection.token}`
|
||||
}
|
||||
|
||||
world(): Promise<WorldInfo> {
|
||||
return this.json('world')
|
||||
}
|
||||
|
||||
hover(layer: MapLayerQuery, worldX: number, worldZ: number, signal?: AbortSignal): Promise<MapHover> {
|
||||
return this.json(`hover?${layerQuery(layer, { x: String(worldX), z: String(worldZ) })}`, { signal })
|
||||
}
|
||||
|
||||
/** How the noise picks what the layer shows across {@code area}. */
|
||||
picks(layer: MapLayerQuery, area: WorldRect, signal?: AbortSignal): Promise<PickInspection> {
|
||||
const corners = { minX: String(area.minX), minZ: String(area.minZ), maxX: String(area.maxX), maxZ: String(area.maxZ) }
|
||||
return this.json(`picks?${layerQuery(layer, corners)}`, { signal })
|
||||
}
|
||||
|
||||
/** The regions the world picks biomes for, which the region view can preview. */
|
||||
regions(): Promise<MapLabel[]> {
|
||||
return this.json('regions')
|
||||
}
|
||||
|
||||
entities(): Promise<Marker[]> {
|
||||
return this.json('entities')
|
||||
}
|
||||
|
||||
async teleport(worldX: number, worldZ: number): Promise<void> {
|
||||
await this.json(`teleport?x=${worldX}&z=${worldZ}`, { method: 'POST' })
|
||||
}
|
||||
|
||||
/** Opens the file of the biome or region at a spot on the server's machine; the server's answer, if any. */
|
||||
async openInEditor(worldX: number, worldZ: number, view: string): Promise<string | null> {
|
||||
const answer = await this.json<{ message: string | null }>(`open?x=${worldX}&z=${worldZ}&view=${view}`, { method: 'POST' })
|
||||
return answer.message
|
||||
}
|
||||
|
||||
async tile(request: TileRequest, signal: AbortSignal): Promise<MapTile> {
|
||||
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',
|
||||
noise: request.pickNoise ? '1' : '0'
|
||||
})
|
||||
const response = await this.fetch(`tile?${query}`, { signal })
|
||||
return decodeTile(await response.arrayBuffer())
|
||||
}
|
||||
|
||||
/** The scene views the pack's modules show, such as its objects. */
|
||||
sceneViews(): Promise<SceneViewInfo[]> {
|
||||
return this.json('scenes')
|
||||
}
|
||||
|
||||
/** An editable entry's file, as nodes. */
|
||||
sceneFile(viewId: string, key: string, signal?: AbortSignal): Promise<EditorState> {
|
||||
return this.json(`scene-file?${new URLSearchParams({ view: viewId, key })}`, { signal })
|
||||
}
|
||||
|
||||
/** Makes {@code edit} on the file as it was at {@code revision} and saves it; refused with STATUS_CONFLICT when it changed since. */
|
||||
sceneEdit(viewId: string, key: string, revision: string, edit: GraphEdit): Promise<EditorState> {
|
||||
return this.json(`scene-edit?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST', body: JSON.stringify({ revision, edit }) })
|
||||
}
|
||||
|
||||
/** Replaces the whole file, as undoing does; refused with STATUS_CONFLICT when it changed since {@code revision}. */
|
||||
sceneWrite(viewId: string, key: string, revision: string, text: string): Promise<EditorState> {
|
||||
return this.json(`scene-write?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST', body: JSON.stringify({ revision, text }) })
|
||||
}
|
||||
|
||||
sceneEntries(viewId: string): Promise<SceneEntry[]> {
|
||||
return this.json(`scene-entries?${new URLSearchParams({ view: viewId })}`)
|
||||
}
|
||||
|
||||
async scene(viewId: string, key: string, variant: number, signal?: AbortSignal): Promise<BlockScene> {
|
||||
const response = await this.fetch(`scene?${new URLSearchParams({ view: viewId, key, variant: String(variant) })}`, { signal })
|
||||
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')
|
||||
}
|
||||
|
||||
/** Where a saved world's view opens; reads the region nearest the origin whole, so it can take a second or two. */
|
||||
savedStart(worldId: string, signal?: AbortSignal): Promise<SavedStart> {
|
||||
return this.json(`saved-start?${new URLSearchParams({ world: worldId })}`, { signal })
|
||||
}
|
||||
|
||||
async savedTile(worldId: string, tileX: number, tileZ: number, blocksPerPixel: number, size: number, signal: AbortSignal): Promise<SavedTile> {
|
||||
const query = new URLSearchParams({ world: worldId, x: String(tileX), z: String(tileZ), scale: String(blocksPerPixel), size: String(size) })
|
||||
const response = await this.fetch(`saved-tile?${query}`, { signal })
|
||||
return decodeSavedTile(await response.arrayBuffer())
|
||||
}
|
||||
|
||||
/** The pack's generators and expressions, the dimension's overlay noise, and the built-in noise styles. */
|
||||
noiseSources(): Promise<NoiseSource[]> {
|
||||
return this.json('noise-sources')
|
||||
}
|
||||
|
||||
async noiseTile(sourceId: string, seed: string, tileX: number, tileZ: number, blocksPerPixel: number, size: number, signal: AbortSignal): Promise<NoiseTile> {
|
||||
const query = new URLSearchParams({ source: sourceId, seed, x: String(tileX), z: String(tileZ), scale: String(blocksPerPixel), size: String(size) })
|
||||
const response = await this.fetch(`noise-tile?${query}`, { signal })
|
||||
return { size, values: new Float32Array(await response.arrayBuffer()) }
|
||||
}
|
||||
|
||||
/** A file of the Minecraft client's assets, such as {@code minecraft/blockstates/stone.json}; null when there is none. */
|
||||
async asset(path: string): Promise<Response | null> {
|
||||
try {
|
||||
return await this.fetch(`assets/${path}`, {})
|
||||
} catch (error) {
|
||||
if (error instanceof BridgeError && error.status === STATUS_NOT_FOUND) {
|
||||
return null
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/** Streams the bridge's events until {@code signal} aborts or the bridge goes away. */
|
||||
async listen(events: BridgeEvents, signal: AbortSignal): Promise<void> {
|
||||
try {
|
||||
const response = await this.fetch('events', { signal })
|
||||
const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader()
|
||||
let pending = ''
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read()
|
||||
if (done) {
|
||||
break
|
||||
}
|
||||
pending += value
|
||||
let end: number
|
||||
while ((end = pending.indexOf(EVENT_SEPARATOR)) >= 0) {
|
||||
dispatch(pending.slice(0, end), events)
|
||||
pending = pending.slice(end + EVENT_SEPARATOR.length)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (signal.aborted) {
|
||||
return
|
||||
}
|
||||
console.warn('Studio events stopped', error)
|
||||
}
|
||||
if (!signal.aborted) {
|
||||
events.onClosed()
|
||||
}
|
||||
}
|
||||
|
||||
private async json<T>(endpoint: string, init: RequestInit = {}): Promise<T> {
|
||||
const response = await this.fetch(endpoint, init)
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
private async fetch(endpoint: string, init: RequestInit): Promise<Response> {
|
||||
const response = await fetch(this.base + endpoint, {
|
||||
...init,
|
||||
headers: { Authorization: this.authorization }
|
||||
})
|
||||
if (!response.ok) {
|
||||
const body = await response.json().catch(() => ({ error: response.statusText }))
|
||||
throw new BridgeError(response.status, String(body.error ?? response.statusText))
|
||||
}
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
function layerQuery(layer: MapLayerQuery, rest: Record<string, string>): URLSearchParams {
|
||||
const query = new URLSearchParams({ view: layer.view, ...rest })
|
||||
if (layer.preview !== null) {
|
||||
query.set('preview', layer.preview)
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
function dispatch(block: string, events: BridgeEvents): void {
|
||||
let name = 'message'
|
||||
let data = ''
|
||||
for (const line of block.split('\n')) {
|
||||
if (line.startsWith('event: ')) {
|
||||
name = line.slice('event: '.length)
|
||||
} else if (line.startsWith('data: ')) {
|
||||
data += line.slice('data: '.length)
|
||||
}
|
||||
}
|
||||
if (data === '') {
|
||||
return
|
||||
}
|
||||
if (name === 'world') {
|
||||
events.onWorld((JSON.parse(data) as { running: boolean }).running)
|
||||
} else if (name === 'players') {
|
||||
events.onPlayers(JSON.parse(data) as Marker[])
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { MapLabel, SavedTile } from './types'
|
||||
|
||||
const ALIGNMENT_BYTES = 4
|
||||
|
||||
interface SavedTileHeader {
|
||||
size: number
|
||||
blocksPerPixel: number
|
||||
blocks: string[]
|
||||
biomes: MapLabel[]
|
||||
noGround: number
|
||||
noWater: number
|
||||
}
|
||||
|
||||
function aligned(bytes: number): number {
|
||||
return Math.ceil(bytes / ALIGNMENT_BYTES) * ALIGNMENT_BYTES
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a saved tile as the bridge writes it (SavedTileEncoding): a u32 header length, the JSON header, then the ground,
|
||||
* water, block and biome grids, each starting on a multiple of 4 bytes. The grids are views into the buffer.
|
||||
*/
|
||||
export function decodeSavedTile(buffer: ArrayBuffer): SavedTile {
|
||||
const headerLength = new DataView(buffer).getUint32(0, true)
|
||||
const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 4, headerLength))) as SavedTileHeader
|
||||
const pixels = header.size * header.size
|
||||
const gridBytes = aligned(pixels * Int16Array.BYTES_PER_ELEMENT)
|
||||
const gridAt = (index: number): Int16Array => new Int16Array(buffer, aligned(4 + headerLength) + index * gridBytes, pixels)
|
||||
return {
|
||||
size: header.size,
|
||||
blocksPerPixel: header.blocksPerPixel,
|
||||
groundY: gridAt(0),
|
||||
waterSurfaceY: gridAt(1),
|
||||
blocks: gridAt(2),
|
||||
biomes: gridAt(3),
|
||||
blockNames: header.blocks,
|
||||
biomeLabels: header.biomes,
|
||||
noGround: header.noGround,
|
||||
noWater: header.noWater
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { LabelKind, MapLabel, MapTile } from './types'
|
||||
|
||||
const ALIGNMENT_BYTES = 4
|
||||
|
||||
interface TileHeader {
|
||||
size: number
|
||||
blocksPerPixel: number
|
||||
subjectKind: LabelKind
|
||||
labels: MapLabel[]
|
||||
heights: boolean
|
||||
pickNoise: boolean
|
||||
}
|
||||
|
||||
function aligned(bytes: number): number {
|
||||
return Math.ceil(bytes / ALIGNMENT_BYTES) * ALIGNMENT_BYTES
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a tile as the bridge writes it (MapTileEncoding): a u32 header length, the JSON header, then the subject,
|
||||
* region, height and pick noise grids, each starting on a multiple of 4 bytes. The grids are views into the buffer,
|
||||
* not copies.
|
||||
*/
|
||||
export function decodeTile(buffer: ArrayBuffer): MapTile {
|
||||
const view = new DataView(buffer)
|
||||
const headerLength = view.getUint32(0, true)
|
||||
const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 4, headerLength))) as TileHeader
|
||||
const gridSize = header.size + 2
|
||||
const cells = gridSize * gridSize
|
||||
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,
|
||||
subjectKind: header.subjectKind,
|
||||
labels: header.labels,
|
||||
subjects: new Int16Array(buffer, subjectsAt, cells),
|
||||
regions: new Int16Array(buffer, regionsAt, cells),
|
||||
heights: header.heights ? new Float32Array(buffer, heightsAt, cells) : null,
|
||||
pickNoise: header.pickNoise ? new Float32Array(buffer, pickNoiseAt, cells) : null
|
||||
}
|
||||
}
|
||||
|
||||
/** The grid index of a pixel; pixel coordinates run from -1 to size, the ring being the neighbours'. */
|
||||
export function gridIndex(tile: MapTile, pixelX: number, pixelZ: number): number {
|
||||
return (pixelZ + 1) * (tile.size + 2) + pixelX + 1
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
/** The shapes the Iris bridge answers with (Iris core, art.arcane.iris.core.studio). */
|
||||
|
||||
export type LabelKind = 'BIOME' | 'REGION'
|
||||
|
||||
export interface MapLabel {
|
||||
kind: LabelKind
|
||||
key: string
|
||||
name: string
|
||||
/** 0xRRGGBB */
|
||||
color: number
|
||||
}
|
||||
|
||||
export interface ViewInfo {
|
||||
id: string
|
||||
label: string
|
||||
description: string
|
||||
group: string
|
||||
groupLabel: string
|
||||
}
|
||||
|
||||
/** 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
|
||||
}
|
||||
|
||||
export interface SceneEntry {
|
||||
key: string
|
||||
name: string
|
||||
/** The folder it is listed under; empty for none. */
|
||||
group: string
|
||||
variants: number
|
||||
}
|
||||
|
||||
/** A scene view as the server lists it; `editable` when its entries can be edited as nodes. */
|
||||
export interface SceneViewInfo extends ModuleViewInfo {
|
||||
editable: boolean
|
||||
}
|
||||
|
||||
/** Where a value sits in a JSON file: member names and element indices from the root. */
|
||||
export type JsonPath = (string | number)[]
|
||||
|
||||
/** An entry's file as the node editor shows it (StudioEditors.EditorState). */
|
||||
export interface EditorState {
|
||||
/** Where it is below the pack folder. */
|
||||
file: string
|
||||
/** Tells this text from any other; an edit sent with an older one is refused. */
|
||||
revision: string
|
||||
text: string
|
||||
/** The file as nodes, or null when it can't be read as nodes and `problem` says why. */
|
||||
roots: GraphNode[] | null
|
||||
problem: string | null
|
||||
/** Why the file can't be edited here, such as outside a studio world; null when it can. */
|
||||
locked: string | null
|
||||
types: Record<string, SettingsType>
|
||||
}
|
||||
|
||||
export interface GraphNode {
|
||||
kind: string
|
||||
title: string
|
||||
path: JsonPath
|
||||
/** The scene part it draws, or NO_PART. */
|
||||
partId: number
|
||||
roles: string[]
|
||||
settings: NodeSettings[]
|
||||
children: { wire: string; node: GraphNode }[]
|
||||
/** The array a node moved under this one joins; null when nothing can move here. */
|
||||
childList: JsonPath | null
|
||||
movable: boolean
|
||||
duplicable: boolean
|
||||
additions: { label: string; list: JsonPath; literal: string }[]
|
||||
}
|
||||
|
||||
export const NO_PART = -1
|
||||
|
||||
/** The settings of the object at `path`, of schema type `type`, without the members shown as nodes. */
|
||||
export interface NodeSettings {
|
||||
title: string
|
||||
path: JsonPath
|
||||
type: string
|
||||
shownAsNodes: string[]
|
||||
}
|
||||
|
||||
/** A settings type of the pack's schema (SchemaTypes.TypeWire). */
|
||||
export interface SettingsType {
|
||||
description: string
|
||||
options: SettingOption[]
|
||||
}
|
||||
|
||||
export interface SettingOption {
|
||||
name: string
|
||||
description: string
|
||||
required: boolean
|
||||
minimum: number | null
|
||||
maximum: number | null
|
||||
minItems: number | null
|
||||
defaultValue: unknown
|
||||
kind: ValueKind
|
||||
}
|
||||
|
||||
export type ValueKind =
|
||||
| { kind: 'boolean' }
|
||||
| { kind: 'integer' }
|
||||
| { kind: 'decimal' }
|
||||
| { kind: 'text'; format: string }
|
||||
| { kind: 'reference'; reference: string; format: string }
|
||||
| { kind: 'resource'; resource: string }
|
||||
| { kind: 'enum'; constants: { name: string; description: string }[] }
|
||||
| { kind: 'list'; element: ValueKind; unique: boolean }
|
||||
| { kind: 'map'; value: ValueKind }
|
||||
| { kind: 'object'; type: string }
|
||||
| { kind: 'host'; type: string }
|
||||
| { kind: 'any' }
|
||||
|
||||
/** One change the node editor makes (GraphEditRequest). */
|
||||
export type GraphEdit =
|
||||
| { op: 'set'; object: JsonPath; key: string; literal: string }
|
||||
| { op: 'unset'; object: JsonPath; key: string }
|
||||
| { op: 'append'; list: JsonPath; literal: string }
|
||||
| { op: 'addItem'; list: JsonPath }
|
||||
| { op: 'delete'; path: JsonPath }
|
||||
| { op: 'duplicate'; path: JsonPath }
|
||||
| { op: 'move'; path: JsonPath; toList: JsonPath }
|
||||
|
||||
/** 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. */
|
||||
id: string
|
||||
name: string
|
||||
/** Who added the dimension, such as minecraft or iris. */
|
||||
namespace: string
|
||||
}
|
||||
|
||||
/** One noise the noise view can show. */
|
||||
export interface NoiseSource {
|
||||
id: string
|
||||
name: string
|
||||
category: string
|
||||
/** Whether the view's seed changes it; the dimension's overlay keeps the world's. */
|
||||
usesSeed: boolean
|
||||
/** What the noise spans where it is measured in blocks above the fluid; null for noise of 0 to 1. */
|
||||
blockRange: { lowest: number; highest: number } | null
|
||||
}
|
||||
|
||||
/** A square of noise values, a pixel's value taken at its north west corner, row by row from the north west. */
|
||||
export interface NoiseTile {
|
||||
size: number
|
||||
values: Float32Array
|
||||
}
|
||||
|
||||
/** Where a saved world's view opens: the middle of the region nearest the origin, and how its ground lies there. */
|
||||
export interface SavedStart {
|
||||
centerX: number
|
||||
centerZ: number
|
||||
minY: number
|
||||
lowestGround: number
|
||||
highestGround: number
|
||||
/** The water surface most water lies at, or null where the region holds none. */
|
||||
seaLevel: number | null
|
||||
}
|
||||
|
||||
/** A square of a saved world, one column per pixel, row by row from the north west. */
|
||||
export interface SavedTile {
|
||||
size: number
|
||||
blocksPerPixel: number
|
||||
/** The top block of the ground under any water; {@link noGround} where nothing finished is saved. */
|
||||
groundY: Int16Array
|
||||
/** The top water block over the ground; {@link noWater} where it is dry. */
|
||||
waterSurfaceY: Int16Array
|
||||
/** Indices into {@link blockNames} and {@link biomes}. */
|
||||
blocks: Int16Array
|
||||
biomes: Int16Array
|
||||
blockNames: string[]
|
||||
biomeLabels: MapLabel[]
|
||||
noGround: number
|
||||
noWater: number
|
||||
}
|
||||
|
||||
export interface WorldInfo {
|
||||
world: string
|
||||
dimension: string
|
||||
dimensionName: string
|
||||
seed: string
|
||||
minY: number
|
||||
height: number
|
||||
fluidHeight: number
|
||||
tileSize: number
|
||||
hasPlayers: boolean
|
||||
views: ViewInfo[]
|
||||
}
|
||||
|
||||
export interface MapHover {
|
||||
worldX: number
|
||||
worldZ: number
|
||||
biome: MapLabel | null
|
||||
caveBiome: MapLabel | null
|
||||
region: MapLabel | null
|
||||
vanillaBiome: string | null
|
||||
height: number
|
||||
fluidHeight: number
|
||||
slopeDegrees: number
|
||||
biomeFile: string | null
|
||||
regionFile: string | null
|
||||
/** How the spot got its region and the biome the view shows, region first. */
|
||||
pickPath: PickStep[]
|
||||
}
|
||||
|
||||
/** 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
|
||||
picked: MapLabel
|
||||
/** The biome list a BIOME step picked from, such as "land". */
|
||||
list: string | null
|
||||
/** The parent name a CHILD step replaced; null when the parent kept the spot. */
|
||||
replaced: string | null
|
||||
/** 0 to 1; null when nothing was picked. */
|
||||
noise: number | null
|
||||
bands: PickBand[]
|
||||
}
|
||||
|
||||
/** One option's share of a pick noise: picked from `from` up to `to`. */
|
||||
export interface PickBand {
|
||||
option: MapLabel
|
||||
from: number
|
||||
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
|
||||
worldY: number
|
||||
worldZ: number
|
||||
health: number
|
||||
maxHealth: number
|
||||
}
|
||||
|
||||
/**
|
||||
* A decoded map tile. Grids hold (size + 2)² cells, the tile's pixels inside a ring of its neighbours' edge pixels.
|
||||
*/
|
||||
export interface MapTile {
|
||||
size: number
|
||||
blocksPerPixel: number
|
||||
subjectKind: LabelKind
|
||||
labels: MapLabel[]
|
||||
subjects: Int16Array
|
||||
regions: Int16Array
|
||||
heights: Float32Array | null
|
||||
/** The noise value that settled each cell's pick, 0 to 1 and NaN where nothing picked it; null unless asked for. */
|
||||
pickNoise: Float32Array | null
|
||||
}
|
||||
|
||||
export const NO_LABEL = -1
|
||||
@@ -0,0 +1,63 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Slot } from "radix-ui"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40",
|
||||
outline:
|
||||
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost:
|
||||
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||
sm: "h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
|
||||
"icon-sm": "size-8",
|
||||
"icon-lg": "size-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot.Root : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,252 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
import { ContextMenu as ContextMenuPrimitive } from "radix-ui"
|
||||
|
||||
function ContextMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioGroup
|
||||
data-slot="context-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubTrigger
|
||||
data-slot="context-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto" />
|
||||
</ContextMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||
// Portalled like the menu itself: inside it, the menu's blur and scrolling would clip the submenu away.
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.SubContent
|
||||
data-slot="context-menu-sub-content"
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 backdrop-blur-sm text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
data-slot="context-menu-content"
|
||||
className={cn(
|
||||
"z-50 max-h-(--radix-context-menu-content-available-height) min-w-[8rem] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground backdrop-blur-sm shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Item
|
||||
data-slot="context-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.CheckboxItem
|
||||
data-slot="context-menu-checkbox-item"
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioItem
|
||||
data-slot="context-menu-radio-item"
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Label
|
||||
data-slot="context-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium text-foreground data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Separator
|
||||
data-slot="context-menu-separator"
|
||||
className={cn("-mx-1 my-1 h-px bg-border", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="context-menu-shortcut"
|
||||
className={cn(
|
||||
"ml-auto text-xs tracking-widest text-muted-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
ContextMenu,
|
||||
ContextMenuTrigger,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuCheckboxItem,
|
||||
ContextMenuRadioItem,
|
||||
ContextMenuLabel,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuShortcut,
|
||||
ContextMenuGroup,
|
||||
ContextMenuPortal,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuRadioGroup,
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { XIcon } from "lucide-react"
|
||||
import { Dialog as DialogPrimitive } from "radix-ui"
|
||||
|
||||
import { Button } from "@/components/ui/button"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||
>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({
|
||||
className,
|
||||
showCloseButton = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close asChild>
|
||||
<Button variant="outline">Close</Button>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-sm text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
|
||||
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
||||
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
@@ -0,0 +1,28 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Kbd({ className, ...props }: React.ComponentProps<"kbd">) {
|
||||
return (
|
||||
<kbd
|
||||
data-slot="kbd"
|
||||
className={cn(
|
||||
"pointer-events-none inline-flex h-5 w-fit min-w-5 items-center justify-center gap-1 rounded-sm bg-muted px-1 font-sans text-xs font-medium text-muted-foreground select-none",
|
||||
"[&_svg:not([class*='size-'])]:size-3",
|
||||
"[[data-slot=tooltip-content]_&]:bg-background/20 [[data-slot=tooltip-content]_&]:text-background dark:[[data-slot=tooltip-content]_&]:bg-background/10",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function KbdGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<kbd
|
||||
data-slot="kbd-group"
|
||||
className={cn("inline-flex items-center gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Kbd, KbdGroup }
|
||||
@@ -0,0 +1,57 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { ScrollArea as ScrollAreaPrimitive } from "radix-ui"
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
data-slot="scroll-area-viewport"
|
||||
className="size-full rounded-[inherit] [&>div]:block! transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="relative flex-1 rounded-full bg-border"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
)
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
@@ -0,0 +1,25 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Separator as SeparatorPrimitive } from "radix-ui"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
@@ -0,0 +1,69 @@
|
||||
import * as React from "react"
|
||||
import { type VariantProps } from "class-variance-authority"
|
||||
import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { toggleVariants } from "@/components/ui/toggle"
|
||||
|
||||
const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({
|
||||
size: "default",
|
||||
variant: "default",
|
||||
})
|
||||
|
||||
function ToggleGroup({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
|
||||
VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<ToggleGroupPrimitive.Root
|
||||
data-slot="toggle-group"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider value={{ variant, size }}>
|
||||
{children}
|
||||
</ToggleGroupContext.Provider>
|
||||
</ToggleGroupPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ToggleGroupItem({
|
||||
className,
|
||||
children,
|
||||
variant,
|
||||
size,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
|
||||
VariantProps<typeof toggleVariants>) {
|
||||
const context = React.useContext(ToggleGroupContext)
|
||||
|
||||
return (
|
||||
<ToggleGroupPrimitive.Item
|
||||
data-slot="toggle-group-item"
|
||||
data-variant={context.variant || variant}
|
||||
data-size={context.size || size}
|
||||
className={cn(
|
||||
toggleVariants({
|
||||
variant: context.variant || variant,
|
||||
size: context.size || size,
|
||||
}),
|
||||
"min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</ToggleGroupPrimitive.Item>
|
||||
)
|
||||
}
|
||||
|
||||
export { ToggleGroup, ToggleGroupItem }
|
||||
@@ -0,0 +1,44 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Toggle as TogglePrimitive } from "radix-ui"
|
||||
|
||||
const toggleVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-[color,box-shadow] outline-none hover:bg-muted hover:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
outline:
|
||||
"border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 min-w-9 px-2",
|
||||
sm: "h-8 min-w-8 px-1.5",
|
||||
lg: "h-10 min-w-10 px-2.5",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Toggle({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TogglePrimitive.Root> &
|
||||
VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<TogglePrimitive.Root
|
||||
data-slot="toggle"
|
||||
className={cn(toggleVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toggle, toggleVariants }
|
||||
@@ -0,0 +1,56 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Tooltip as TooltipPrimitive } from "radix-ui"
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
declare module '*.css'
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { EditHistory } from './EditHistory'
|
||||
|
||||
describe('EditHistory', () => {
|
||||
it('undoes back to the text before an edit and redoes forward again', () => {
|
||||
const history = new EditHistory()
|
||||
history.edited('a')
|
||||
|
||||
expect(history.nextUndo()).toBe('a')
|
||||
history.undone('b')
|
||||
expect(history.canUndo).toBe(false)
|
||||
expect(history.nextRedo()).toBe('b')
|
||||
history.redone('a')
|
||||
expect(history.nextUndo()).toBe('a')
|
||||
})
|
||||
|
||||
it('forgets what could be redone once a new edit is made', () => {
|
||||
const history = new EditHistory()
|
||||
history.edited('a')
|
||||
history.undone('b')
|
||||
|
||||
history.edited('a')
|
||||
|
||||
expect(history.canRedo).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the history as it was when an undo is never written', () => {
|
||||
const history = new EditHistory()
|
||||
history.edited('a')
|
||||
|
||||
history.nextUndo()
|
||||
|
||||
expect(history.canUndo).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
const KEPT_STEPS = 100
|
||||
|
||||
/**
|
||||
* The texts a file had before each edit, so undoing writes an earlier text back whole. A step is only taken once its
|
||||
* write succeeded, so a refused undo leaves the history as it was.
|
||||
*/
|
||||
export class EditHistory {
|
||||
private readonly undos: string[] = []
|
||||
private readonly redos: string[] = []
|
||||
|
||||
get canUndo(): boolean {
|
||||
return this.undos.length > 0
|
||||
}
|
||||
|
||||
get canRedo(): boolean {
|
||||
return this.redos.length > 0
|
||||
}
|
||||
|
||||
edited(before: string): void {
|
||||
this.undos.push(before)
|
||||
if (this.undos.length > KEPT_STEPS) {
|
||||
this.undos.shift()
|
||||
}
|
||||
this.redos.length = 0
|
||||
}
|
||||
|
||||
/** The text undoing writes, if there is one. */
|
||||
nextUndo(): string | undefined {
|
||||
return this.undos.at(-1)
|
||||
}
|
||||
|
||||
undone(before: string): void {
|
||||
this.undos.pop()
|
||||
this.redos.push(before)
|
||||
}
|
||||
|
||||
nextRedo(): string | undefined {
|
||||
return this.redos.at(-1)
|
||||
}
|
||||
|
||||
redone(before: string): void {
|
||||
this.redos.pop()
|
||||
this.undos.push(before)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { JsonPath } from '../bridge/types'
|
||||
|
||||
/** The value at {@code path} in a parsed file; undefined where nothing is written. */
|
||||
export function valueAt(root: unknown, path: JsonPath): unknown {
|
||||
let current = root
|
||||
for (const step of path) {
|
||||
if (current === null || typeof current !== 'object') {
|
||||
return undefined
|
||||
}
|
||||
current = (current as Record<string | number, unknown>)[step]
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
/** The file parsed, or undefined when it is not JSON (the editor then shows why instead). */
|
||||
export function parsedText(text: string): unknown {
|
||||
try {
|
||||
return JSON.parse(text)
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { GraphNode, JsonPath } from '../bridge/types'
|
||||
import { NO_PART } from '../bridge/types'
|
||||
import { isWithin, layoutNodes, NODE_WIDTH } from './nodeLayout'
|
||||
|
||||
function node(path: JsonPath, children: GraphNode[] = []): GraphNode {
|
||||
return {
|
||||
kind: 'Stem',
|
||||
title: 'Stem',
|
||||
path,
|
||||
partId: NO_PART,
|
||||
roles: [],
|
||||
settings: [],
|
||||
children: children.map((child) => ({ wire: '', node: child })),
|
||||
childList: null,
|
||||
movable: true,
|
||||
duplicable: true,
|
||||
additions: []
|
||||
}
|
||||
}
|
||||
|
||||
describe('layoutNodes', () => {
|
||||
it('sets a parent level with the middle of its children, a column to their left', () => {
|
||||
const layout = layoutNodes([node([], [node(['parts', 0]), node(['parts', 1]), node(['parts', 2])])])
|
||||
const [first, , last, parent] = layout.nodes
|
||||
|
||||
expect(parent.y).toBe((first.y + last.y) / 2)
|
||||
expect(first.x - parent.x).toBeGreaterThan(NODE_WIDTH)
|
||||
expect(layout.wires).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('lays the next root out under the tree before it', () => {
|
||||
const layout = layoutNodes([node([], [node(['parts', 0])]), node(['materials', 0])])
|
||||
const material = layout.nodes.find((placed) => placed.id === JSON.stringify(['materials', 0]))!
|
||||
|
||||
expect(material.x).toBe(0)
|
||||
expect(material.y).toBeGreaterThan(Math.max(...layout.nodes.filter((placed) => placed !== material).map((placed) => placed.y)))
|
||||
})
|
||||
})
|
||||
|
||||
describe('isWithin', () => {
|
||||
it('holds for the path itself and what sits inside it, not for a sibling', () => {
|
||||
expect(isWithin(['parts', 0, 'children', 1], ['parts', 0])).toBe(true)
|
||||
expect(isWithin(['parts', 0], ['parts', 0])).toBe(true)
|
||||
expect(isWithin(['parts', 1], ['parts', 0])).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { GraphNode, JsonPath } from '../bridge/types'
|
||||
|
||||
export const NODE_WIDTH = 168
|
||||
export const NODE_HEIGHT = 46
|
||||
const COLUMN_GAP = 64
|
||||
const ROW_GAP = 10
|
||||
const TREE_GAP = 26
|
||||
|
||||
/** A node where the canvas draws it, by its top left corner; `id` tells it from every other node of the file. */
|
||||
export interface PlacedNode {
|
||||
id: string
|
||||
node: GraphNode
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
export interface PlacedWire {
|
||||
from: PlacedNode
|
||||
to: PlacedNode
|
||||
label: string
|
||||
}
|
||||
|
||||
export interface NodeLayout {
|
||||
nodes: PlacedNode[]
|
||||
wires: PlacedWire[]
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export function idOf(path: JsonPath): string {
|
||||
return JSON.stringify(path)
|
||||
}
|
||||
|
||||
/** The node at {@code path} among the trees of {@code roots}, or null when there is none, such as after it was deleted. */
|
||||
export function nodeWithPath(roots: GraphNode[], path: JsonPath): GraphNode | null {
|
||||
const id = idOf(path)
|
||||
for (const root of roots) {
|
||||
if (idOf(root.path) === id) {
|
||||
return root
|
||||
}
|
||||
const found = nodeWithPath(
|
||||
root.children.map((link) => link.node),
|
||||
path
|
||||
)
|
||||
if (found !== null) {
|
||||
return found
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Whether {@code path} is {@code ancestor} or sits inside it. */
|
||||
export function isWithin(path: JsonPath, ancestor: JsonPath): boolean {
|
||||
return ancestor.length <= path.length && ancestor.every((step, index) => path[index] === step)
|
||||
}
|
||||
|
||||
/**
|
||||
* Lays each root's tree out from left to right, a column per generation, one tree under the other. Leaves take a row
|
||||
* each and a parent sits level with the middle of its children, so wires never cross.
|
||||
*/
|
||||
export function layoutNodes(roots: GraphNode[]): NodeLayout {
|
||||
const nodes: PlacedNode[] = []
|
||||
const wires: PlacedWire[] = []
|
||||
let nextTop = 0
|
||||
let width = 0
|
||||
|
||||
const place = (node: GraphNode, depth: number): PlacedNode => {
|
||||
const x = depth * (NODE_WIDTH + COLUMN_GAP)
|
||||
width = Math.max(width, x + NODE_WIDTH)
|
||||
const children = node.children.map((link) => ({ label: link.wire, placed: place(link.node, depth + 1) }))
|
||||
const y = children.length === 0 ? takeRow() : (children[0].placed.y + children[children.length - 1].placed.y) / 2
|
||||
const placed: PlacedNode = { id: idOf(node.path), node, x, y }
|
||||
nodes.push(placed)
|
||||
for (const child of children) {
|
||||
wires.push({ from: placed, to: child.placed, label: child.label })
|
||||
}
|
||||
return placed
|
||||
}
|
||||
|
||||
const takeRow = (): number => {
|
||||
const top = nextTop
|
||||
nextTop += NODE_HEIGHT + ROW_GAP
|
||||
return top
|
||||
}
|
||||
|
||||
for (const root of roots) {
|
||||
place(root, 0)
|
||||
nextTop += TREE_GAP
|
||||
}
|
||||
return { nodes, wires, width, height: Math.max(0, nextTop - ROW_GAP - TREE_GAP) }
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { BridgeError, STATUS_CONFLICT, type BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { EditorState, GraphEdit } from '../bridge/types'
|
||||
import { EditHistory } from './EditHistory'
|
||||
|
||||
export interface NodeEditor {
|
||||
/** The entry's file as it is now; null while it is read. */
|
||||
state: EditorState | null
|
||||
saving: boolean
|
||||
canUndo: boolean
|
||||
canRedo: boolean
|
||||
edit(edit: GraphEdit): void
|
||||
undo(): void
|
||||
redo(): void
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads an entry's file as nodes and edits it. Edits are sent one after another, each on the text the one before left,
|
||||
* so quick edits never refuse each other; one refused because the file changed elsewhere reads the file again.
|
||||
*/
|
||||
export function useNodeEditor(client: BridgeClient, viewId: string, key: string | null, packRevision: number, tell: (message: string) => void): NodeEditor {
|
||||
const [state, setState] = useState<EditorState | null>(null)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [, setHistoryChanges] = useState(0)
|
||||
const history = useRef(new EditHistory())
|
||||
const shown = useRef<EditorState | null>(null)
|
||||
const queue = useRef<Promise<void>>(Promise.resolve())
|
||||
const entry = useRef({ viewId, key })
|
||||
|
||||
const run = useCallback(
|
||||
(task: (current: EditorState | null) => Promise<EditorState | null>): void => {
|
||||
const asked = entry.current
|
||||
queue.current = queue.current.then(async () => {
|
||||
if (entry.current !== asked) {
|
||||
return
|
||||
}
|
||||
setSaving(true)
|
||||
try {
|
||||
const next = await task(shown.current)
|
||||
if (entry.current === asked && next !== null) {
|
||||
shown.current = next
|
||||
setState(next)
|
||||
}
|
||||
} catch (failure) {
|
||||
if (entry.current !== asked) {
|
||||
return
|
||||
}
|
||||
tell((failure as Error).message)
|
||||
if (failure instanceof BridgeError && failure.status === STATUS_CONFLICT && asked.key !== null) {
|
||||
const reread = await client.sceneFile(asked.viewId, asked.key).catch(() => null)
|
||||
if (reread !== null && entry.current === asked) {
|
||||
shown.current = reread
|
||||
setState(reread)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setSaving(false)
|
||||
setHistoryChanges((changes) => changes + 1)
|
||||
}
|
||||
})
|
||||
},
|
||||
[client, tell]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
entry.current = { viewId, key }
|
||||
history.current = new EditHistory()
|
||||
shown.current = null
|
||||
setState(null)
|
||||
}, [viewId, key])
|
||||
|
||||
useEffect(() => {
|
||||
if (key !== null) {
|
||||
run(() => client.sceneFile(viewId, key))
|
||||
}
|
||||
}, [client, viewId, key, packRevision, run])
|
||||
|
||||
const edit = useCallback(
|
||||
(change: GraphEdit) =>
|
||||
run(async (current) => {
|
||||
if (current === null || key === null) {
|
||||
return null
|
||||
}
|
||||
const next = await client.sceneEdit(viewId, key, current.revision, change)
|
||||
if (next.text !== current.text) {
|
||||
history.current.edited(current.text)
|
||||
}
|
||||
return next
|
||||
}),
|
||||
[client, viewId, key, run]
|
||||
)
|
||||
|
||||
const undo = useCallback(
|
||||
() =>
|
||||
run(async (current) => {
|
||||
const earlier = history.current.nextUndo()
|
||||
if (current === null || key === null || earlier === undefined) {
|
||||
return null
|
||||
}
|
||||
const next = await client.sceneWrite(viewId, key, current.revision, earlier)
|
||||
history.current.undone(current.text)
|
||||
return next
|
||||
}),
|
||||
[client, viewId, key, run]
|
||||
)
|
||||
|
||||
const redo = useCallback(
|
||||
() =>
|
||||
run(async (current) => {
|
||||
const later = history.current.nextRedo()
|
||||
if (current === null || key === null || later === undefined) {
|
||||
return null
|
||||
}
|
||||
const next = await client.sceneWrite(viewId, key, current.revision, later)
|
||||
history.current.redone(current.text)
|
||||
return next
|
||||
}),
|
||||
[client, viewId, key, run]
|
||||
)
|
||||
|
||||
return { state, saving, canUndo: history.current.canUndo, canRedo: history.current.canRedo, edit, undo, redo }
|
||||
}
|
||||
Vendored
+9
@@ -0,0 +1,9 @@
|
||||
import type { StudioHost } from '../../shared/bridge'
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
studio: StudioHost
|
||||
}
|
||||
}
|
||||
|
||||
export {}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from 'clsx'
|
||||
import { twMerge } from 'tailwind-merge'
|
||||
|
||||
export function cn(...inputs: ClassValue[]): string {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
import { App } from './App'
|
||||
import './styles.css'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<TooltipProvider delayDuration={400}>
|
||||
<App />
|
||||
</TooltipProvider>
|
||||
</StrictMode>
|
||||
)
|
||||
@@ -0,0 +1,395 @@
|
||||
import type { BridgeClient, WorldRect } from '../bridge/BridgeClient'
|
||||
import { gridIndex } from '../bridge/tileDecoding'
|
||||
import { NO_LABEL, type MapLabel, type MapTile, type Marker, type PickDisplay, type WorldInfo } from '../bridge/types'
|
||||
import { countShares, type PlacedTile, type Share } from './census'
|
||||
import { bandIndexOf, HEIGHT_BANDS } from './heightColors'
|
||||
import { mapTileSource, type TileLayer } from './mapTileSource'
|
||||
import { drawVisibleTiles } from './tileDrawing'
|
||||
import type { Highlight, TileStyle } from './tileStyle'
|
||||
import { TileStore } from './TileStore'
|
||||
import {
|
||||
clampBlocksPerPixel,
|
||||
DEFAULT_BLOCKS_PER_PIXEL,
|
||||
renderBlocksPerPixel,
|
||||
screenToWorldX,
|
||||
screenToWorldZ,
|
||||
worldToScreenX,
|
||||
worldToScreenZ,
|
||||
type TileAddress,
|
||||
type Viewport
|
||||
} from './viewport'
|
||||
|
||||
export interface MapStatus {
|
||||
blocksPerPixel: number
|
||||
widthBlocks: number
|
||||
heightBlocks: number
|
||||
tilesReady: number
|
||||
tilesTotal: number
|
||||
cursorX: number
|
||||
cursorZ: number
|
||||
}
|
||||
|
||||
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
|
||||
region: Highlight | null
|
||||
}
|
||||
|
||||
export interface MapToggles {
|
||||
shading: boolean
|
||||
regionBorders: boolean
|
||||
grid: boolean
|
||||
}
|
||||
|
||||
const CENSUS_INTERVAL_MILLIS = 250
|
||||
const CHUNK_BLOCKS = 16
|
||||
const REGION_BLOCKS = 512
|
||||
const SMALLEST_GRID_GAP_PIXELS = 8
|
||||
const CHUNK_LINE = 'rgba(255, 255, 255, 0.14)'
|
||||
const REGION_LINE = 'rgba(255, 255, 255, 0.38)'
|
||||
const PLAYER_FILL = '#3574f0'
|
||||
const ENTITY_FILL = '#f75464'
|
||||
const MARKER_OUTLINE = '#ffffff'
|
||||
const PLAYER_RADIUS_PIXELS = 6
|
||||
const ENTITY_RADIUS_PIXELS = 3
|
||||
|
||||
/**
|
||||
* The 2D map on a canvas: which tiles to fetch for the view, drawing them in the current style, and the grid and
|
||||
* markers on top. Kept outside React, as it redraws on every drag and wheel step.
|
||||
*/
|
||||
export class MapController {
|
||||
private readonly context: CanvasRenderingContext2D
|
||||
private readonly store: TileStore<MapTile, TileLayer, TileStyle>
|
||||
private readonly view: Viewport = { centerX: 0, centerZ: 0, blocksPerPixel: DEFAULT_BLOCKS_PER_PIXEL, width: 1, height: 1 }
|
||||
private layer: TileLayer
|
||||
private toggles: MapToggles = { shading: true, regionBorders: false, grid: false }
|
||||
private pickDisplay: PickDisplay = 'picks'
|
||||
private highlight: Highlight | null = null
|
||||
private players: Marker[] = []
|
||||
private entities: Marker[] = []
|
||||
private cursor: { x: number; y: number } | null = null
|
||||
private frameRequested = false
|
||||
private lastCensusMillis = 0
|
||||
private censusTimer: number | undefined
|
||||
private closed = false
|
||||
|
||||
constructor(
|
||||
private readonly canvas: HTMLCanvasElement,
|
||||
client: BridgeClient,
|
||||
private readonly world: WorldInfo,
|
||||
view: string,
|
||||
private readonly listener: MapListener
|
||||
) {
|
||||
this.context = canvas.getContext('2d')!
|
||||
this.layer = { view, preview: null, heights: this.needsHeights(view, this.toggles), pickNoise: false, revision: 0 }
|
||||
this.store = new TileStore(mapTileSource(client, world.tileSize), () => this.redraw(), (message) => listener.onError(message))
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true
|
||||
window.clearTimeout(this.censusTimer)
|
||||
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()
|
||||
}
|
||||
|
||||
/** 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) }
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
// Heights are the costly part of a tile, so they are only asked for when something draws with them.
|
||||
private needsHeights(view: string, toggles: MapToggles): boolean {
|
||||
return toggles.shading || view === 'height'
|
||||
}
|
||||
|
||||
setHighlight(highlight: Highlight | null): void {
|
||||
this.highlight = highlight
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
setMarkers(players: Marker[], entities: Marker[]): void {
|
||||
this.players = players
|
||||
this.entities = entities
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
setCursor(cursor: { x: number; y: number } | null): void {
|
||||
this.cursor = cursor
|
||||
this.reportStatus()
|
||||
}
|
||||
|
||||
/** Draws everything again from the server, after the pack changed. */
|
||||
refresh(): void {
|
||||
this.store.clear()
|
||||
this.layer = { ...this.layer, revision: this.layer.revision + 1 }
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
panBy(screenDeltaX: number, screenDeltaZ: number): void {
|
||||
this.view.centerX -= screenDeltaX * this.view.blocksPerPixel
|
||||
this.view.centerZ -= screenDeltaZ * this.view.blocksPerPixel
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
centerOn(worldX: number, worldZ: number): void {
|
||||
this.view.centerX = worldX
|
||||
this.view.centerZ = worldZ
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
/** Zooms by {@code factor} (above 1 zooms in) keeping the world 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()
|
||||
}
|
||||
|
||||
resetZoom(): void {
|
||||
this.view.blocksPerPixel = DEFAULT_BLOCKS_PER_PIXEL
|
||||
this.redraw()
|
||||
}
|
||||
|
||||
worldAt(screenX: number, screenZ: number): { x: number; z: number } {
|
||||
return { x: screenToWorldX(this.view, screenX), z: screenToWorldZ(this.view, screenZ) }
|
||||
}
|
||||
|
||||
/** The biome or region and the region at a screen point, from the tile drawn there; nulls before it arrived. */
|
||||
subjectsAt(screenX: number, screenZ: number): SpotSubjects {
|
||||
const worldX = screenToWorldX(this.view, screenX)
|
||||
const worldZ = screenToWorldZ(this.view, screenZ)
|
||||
const scale = this.renderScale()
|
||||
const span = this.world.tileSize * scale
|
||||
const address = { tileX: Math.floor(worldX / span), tileZ: Math.floor(worldZ / span), blocksPerPixel: scale }
|
||||
const tile = this.store.get(address, this.layer)
|
||||
if (tile === null) {
|
||||
return { subject: null, region: 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))
|
||||
const cell = gridIndex(tile, pixelX, pixelZ)
|
||||
const region = labelAt(tile.labels, tile.regions[cell])
|
||||
if (this.isHeightView() && tile.heights !== null) {
|
||||
const band = HEIGHT_BANDS[bandIndexOf(tile.heights[cell], this.world.fluidHeight)]
|
||||
return { subject: { kind: 'HEIGHT', key: band.key, name: band.name }, region }
|
||||
}
|
||||
return { subject: labelAt(tile.labels, tile.subjects[cell]), region }
|
||||
}
|
||||
|
||||
private isHeightView(): boolean {
|
||||
return this.layer.view === 'height'
|
||||
}
|
||||
|
||||
private renderScale(): number {
|
||||
return renderBlocksPerPixel(this.view.blocksPerPixel, window.devicePixelRatio)
|
||||
}
|
||||
|
||||
private style(): TileStyle {
|
||||
return {
|
||||
byHeight: this.isHeightView(),
|
||||
shading: this.toggles.shading,
|
||||
regionBorders: this.toggles.regionBorders,
|
||||
highlight: this.highlight,
|
||||
seaLevel: this.world.fluidHeight,
|
||||
pickDisplay: this.pickDisplay
|
||||
}
|
||||
}
|
||||
|
||||
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 style = this.style()
|
||||
const drawn = drawVisibleTiles(context, this.view, this.renderScale(), this.world.tileSize, (address) =>
|
||||
this.store.picture(address, this.layer, style)
|
||||
)
|
||||
this.store.want(drawn.wanted, this.layer)
|
||||
if (this.toggles.grid) {
|
||||
this.drawGrid()
|
||||
}
|
||||
this.drawMarkers()
|
||||
this.reportStatus(drawn.ready, drawn.tiles.length)
|
||||
this.scheduleCensus(drawn.tiles)
|
||||
}
|
||||
|
||||
private drawGrid(): void {
|
||||
this.drawLines(CHUNK_BLOCKS, CHUNK_LINE, 1)
|
||||
this.drawLines(REGION_BLOCKS, REGION_LINE, 1.5)
|
||||
}
|
||||
|
||||
private drawLines(gapBlocks: number, color: string, width: number): void {
|
||||
if (gapBlocks / this.view.blocksPerPixel < SMALLEST_GRID_GAP_PIXELS) {
|
||||
return
|
||||
}
|
||||
const context = this.context
|
||||
context.strokeStyle = color
|
||||
context.lineWidth = width
|
||||
context.beginPath()
|
||||
const firstX = Math.ceil(screenToWorldX(this.view, 0) / gapBlocks) * gapBlocks
|
||||
for (let worldX = firstX; worldX <= screenToWorldX(this.view, this.view.width); worldX += gapBlocks) {
|
||||
const screenX = Math.round(worldToScreenX(this.view, worldX)) + 0.5
|
||||
context.moveTo(screenX, 0)
|
||||
context.lineTo(screenX, this.view.height)
|
||||
}
|
||||
const firstZ = Math.ceil(screenToWorldZ(this.view, 0) / gapBlocks) * gapBlocks
|
||||
for (let worldZ = firstZ; worldZ <= screenToWorldZ(this.view, this.view.height); worldZ += gapBlocks) {
|
||||
const screenZ = Math.round(worldToScreenZ(this.view, worldZ)) + 0.5
|
||||
context.moveTo(0, screenZ)
|
||||
context.lineTo(this.view.width, screenZ)
|
||||
}
|
||||
context.stroke()
|
||||
}
|
||||
|
||||
private drawMarkers(): void {
|
||||
for (const entity of this.entities) {
|
||||
this.drawMarker(entity, ENTITY_FILL, ENTITY_RADIUS_PIXELS, false)
|
||||
}
|
||||
for (const player of this.players) {
|
||||
this.drawMarker(player, PLAYER_FILL, PLAYER_RADIUS_PIXELS, true)
|
||||
}
|
||||
}
|
||||
|
||||
private drawMarker(marker: Marker, fill: string, radius: number, named: boolean): void {
|
||||
const context = this.context
|
||||
const x = worldToScreenX(this.view, marker.worldX)
|
||||
const z = worldToScreenZ(this.view, marker.worldZ)
|
||||
context.beginPath()
|
||||
context.arc(x, z, radius, 0, Math.PI * 2)
|
||||
context.fillStyle = fill
|
||||
context.fill()
|
||||
context.lineWidth = 2
|
||||
context.strokeStyle = MARKER_OUTLINE
|
||||
context.stroke()
|
||||
if (!named) {
|
||||
return
|
||||
}
|
||||
context.font = '600 12px Inter, "Segoe UI", system-ui, sans-serif'
|
||||
context.textAlign = 'center'
|
||||
context.lineWidth = 3
|
||||
context.strokeStyle = 'rgba(0, 0, 0, 0.7)'
|
||||
context.strokeText(marker.label, x, z - radius - 6)
|
||||
context.fillStyle = MARKER_OUTLINE
|
||||
context.fillText(marker.label, x, z - radius - 6)
|
||||
}
|
||||
|
||||
private lastReady = 0
|
||||
private lastTotal = 0
|
||||
|
||||
private reportStatus(ready = this.lastReady, total = this.lastTotal): void {
|
||||
this.lastReady = ready
|
||||
this.lastTotal = total
|
||||
const cursor = this.cursor === null ? { x: this.view.width / 2, y: this.view.height / 2 } : this.cursor
|
||||
this.listener.onStatus({
|
||||
blocksPerPixel: this.view.blocksPerPixel,
|
||||
widthBlocks: Math.round(this.view.width * this.view.blocksPerPixel),
|
||||
heightBlocks: Math.round(this.view.height * this.view.blocksPerPixel),
|
||||
tilesReady: ready,
|
||||
tilesTotal: total,
|
||||
cursorX: Math.floor(screenToWorldX(this.view, cursor.x)),
|
||||
cursorZ: Math.floor(screenToWorldZ(this.view, cursor.y))
|
||||
})
|
||||
}
|
||||
|
||||
// Counting what is on screen is cheap but not free, so it runs at most a few times a second and once more at rest.
|
||||
private scheduleCensus(tiles: TileAddress[]): void {
|
||||
window.clearTimeout(this.censusTimer)
|
||||
const wait = Math.max(0, this.lastCensusMillis + CENSUS_INTERVAL_MILLIS - performance.now())
|
||||
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) {
|
||||
const tile = this.store.get(address, this.layer)
|
||||
if (tile !== null) {
|
||||
const span = this.world.tileSize * address.blocksPerPixel
|
||||
placed.push({ tile, worldX: address.tileX * span, worldZ: address.tileZ * span })
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
function labelAt(labels: MapLabel[], index: number): Highlight | null {
|
||||
if (index === NO_LABEL) {
|
||||
return null
|
||||
}
|
||||
const label = labels[index]
|
||||
return { kind: label.kind, key: label.key, name: label.name }
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
import { BridgeError } from '../bridge/BridgeClient'
|
||||
import type { TileAddress } from './viewport'
|
||||
|
||||
/** What a store's tiles are, where they come from, and how one is drawn in a style. */
|
||||
export interface TileSource<Tile, Layer, Style> {
|
||||
/** Tells layers apart; a layer that changes on hotload carries its revision here, so older tiles are not used again. */
|
||||
layerKey(layer: Layer): string
|
||||
fetch(address: TileAddress, layer: Layer, signal: AbortSignal): Promise<Tile>
|
||||
bytesOf(tile: Tile): number
|
||||
styleKey(style: Style): string
|
||||
pixels(tile: Tile, style: Style): ImageData
|
||||
}
|
||||
|
||||
interface StoredTile<Tile> {
|
||||
tile: Tile
|
||||
bytes: number
|
||||
lastUsed: number
|
||||
picture: HTMLCanvasElement | null
|
||||
pictureStyle: string
|
||||
}
|
||||
|
||||
// Drawing a few hundred tiles at once only queues them on the server; a handful in flight keeps it busy.
|
||||
const MAXIMUM_IN_FLIGHT = 6
|
||||
const CACHE_BYTES = 256 * 1024 * 1024
|
||||
|
||||
/**
|
||||
* Tiles fetched from the bridge as a view needs them, kept within a memory budget, and drawn as the current style
|
||||
* asks. A tile that leaves the view before it arrives is not fetched.
|
||||
*/
|
||||
export class TileStore<Tile, Layer, Style> {
|
||||
private readonly tiles = new Map<string, StoredTile<Tile>>()
|
||||
private readonly inFlight = new Map<string, AbortController>()
|
||||
/** Asked for again only after a refresh, which changes every key, so a broken tile is not fetched on every frame. */
|
||||
private readonly failed = new Set<string>()
|
||||
private wanted: { key: string; address: TileAddress; layer: Layer }[] = []
|
||||
private storedBytes = 0
|
||||
private useClock = 0
|
||||
|
||||
constructor(
|
||||
private readonly source: TileSource<Tile, Layer, Style>,
|
||||
private readonly onChange: () => void,
|
||||
private readonly onError: (message: string) => void
|
||||
) {}
|
||||
|
||||
key(address: TileAddress, layer: Layer): string {
|
||||
return `${this.source.layerKey(layer)}/${address.blocksPerPixel}/${address.tileX}/${address.tileZ}`
|
||||
}
|
||||
|
||||
/** The tile if it has arrived, marked as just used. */
|
||||
get(address: TileAddress, layer: Layer): Tile | null {
|
||||
const stored = this.tiles.get(this.key(address, layer))
|
||||
if (stored === undefined) {
|
||||
return null
|
||||
}
|
||||
stored.lastUsed = ++this.useClock
|
||||
return stored.tile
|
||||
}
|
||||
|
||||
/** The tile drawn in {@code style}; restyled only when the style changed since it was last drawn. */
|
||||
picture(address: TileAddress, layer: Layer, style: Style): HTMLCanvasElement | null {
|
||||
const stored = this.tiles.get(this.key(address, layer))
|
||||
if (stored === undefined) {
|
||||
return null
|
||||
}
|
||||
stored.lastUsed = ++this.useClock
|
||||
const wantedStyle = this.source.styleKey(style)
|
||||
if (stored.picture === null || stored.pictureStyle !== wantedStyle) {
|
||||
stored.picture = stored.picture ?? document.createElement('canvas')
|
||||
paint(stored.picture, this.source.pixels(stored.tile, style))
|
||||
stored.pictureStyle = wantedStyle
|
||||
}
|
||||
return stored.picture
|
||||
}
|
||||
|
||||
/** Fetches the tiles the view shows, in the order given, and gives up on the ones it no longer shows. */
|
||||
want(addresses: TileAddress[], layer: Layer): void {
|
||||
this.wanted = addresses
|
||||
.map((address) => ({ key: this.key(address, layer), address, layer }))
|
||||
.filter((entry) => !this.tiles.has(entry.key) && !this.failed.has(entry.key))
|
||||
const stillWanted = new Set(this.wanted.map((entry) => entry.key))
|
||||
for (const [key, controller] of this.inFlight) {
|
||||
if (!stillWanted.has(key)) {
|
||||
controller.abort()
|
||||
this.inFlight.delete(key)
|
||||
}
|
||||
}
|
||||
this.startRequests()
|
||||
}
|
||||
|
||||
/** How many of the wanted tiles are still on their way. */
|
||||
pending(): number {
|
||||
return this.wanted.length
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
for (const controller of this.inFlight.values()) {
|
||||
controller.abort()
|
||||
}
|
||||
this.inFlight.clear()
|
||||
this.failed.clear()
|
||||
this.tiles.clear()
|
||||
this.wanted = []
|
||||
this.storedBytes = 0
|
||||
}
|
||||
|
||||
private startRequests(): void {
|
||||
for (const entry of this.wanted) {
|
||||
if (this.inFlight.size >= MAXIMUM_IN_FLIGHT) {
|
||||
return
|
||||
}
|
||||
if (!this.inFlight.has(entry.key)) {
|
||||
this.fetchTile(entry.key, entry.address, entry.layer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fetchTile(key: string, address: TileAddress, layer: Layer): void {
|
||||
const controller = new AbortController()
|
||||
this.inFlight.set(key, controller)
|
||||
this.source
|
||||
.fetch(address, layer, controller.signal)
|
||||
.then((tile) => this.store(key, tile))
|
||||
.catch((error: unknown) => {
|
||||
if (!controller.signal.aborted) {
|
||||
this.failed.add(key)
|
||||
this.onError(error instanceof BridgeError ? error.message : 'The server did not answer')
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (this.inFlight.get(key) === controller) {
|
||||
this.inFlight.delete(key)
|
||||
}
|
||||
this.wanted = this.wanted.filter((entry) => entry.key !== key)
|
||||
this.startRequests()
|
||||
this.onChange()
|
||||
})
|
||||
}
|
||||
|
||||
private store(key: string, tile: Tile): void {
|
||||
const bytes = this.source.bytesOf(tile)
|
||||
this.tiles.set(key, { tile, bytes, lastUsed: ++this.useClock, picture: null, pictureStyle: '' })
|
||||
this.storedBytes += bytes
|
||||
this.evictOldest()
|
||||
}
|
||||
|
||||
private evictOldest(): void {
|
||||
if (this.storedBytes <= CACHE_BYTES) {
|
||||
return
|
||||
}
|
||||
const byAge = [...this.tiles.entries()].sort((first, second) => first[1].lastUsed - second[1].lastUsed)
|
||||
for (const [key, stored] of byAge) {
|
||||
if (this.storedBytes <= CACHE_BYTES * 0.8) {
|
||||
return
|
||||
}
|
||||
this.tiles.delete(key)
|
||||
this.storedBytes -= stored.bytes
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function paint(canvas: HTMLCanvasElement, pixels: ImageData): void {
|
||||
canvas.width = pixels.width
|
||||
canvas.height = pixels.height
|
||||
canvas.getContext('2d')!.putImageData(pixels, 0, 0)
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { gridIndex } from '../bridge/tileDecoding'
|
||||
import { NO_LABEL, type MapTile } from '../bridge/types'
|
||||
import { bandIndexOf, HEIGHT_BANDS } from './heightColors'
|
||||
import type { Highlight } from './tileStyle'
|
||||
|
||||
/** How much of the screen one biome, region or height band covers. */
|
||||
export interface Share {
|
||||
subject: Highlight
|
||||
color: number
|
||||
fraction: number
|
||||
}
|
||||
|
||||
/** A loaded tile and where its top left pixel lies in the world. */
|
||||
export interface PlacedTile {
|
||||
tile: MapTile
|
||||
worldX: number
|
||||
worldZ: number
|
||||
}
|
||||
|
||||
export interface WorldArea {
|
||||
minimumX: number
|
||||
minimumZ: number
|
||||
maximumX: number
|
||||
maximumZ: number
|
||||
}
|
||||
|
||||
// Enough samples that a share is right to a fraction of a percent, few enough to count every frame the map settles.
|
||||
const MAXIMUM_COUNTED_PIXELS = 250_000
|
||||
|
||||
/**
|
||||
* The shares of what the tiles show inside {@code area}, largest first: their subjects (biomes or regions), or their
|
||||
* height bands when {@code byHeight} is set.
|
||||
*/
|
||||
export function countShares(tiles: PlacedTile[], area: WorldArea, byHeight: boolean, seaLevel: number): Share[] {
|
||||
const counts = new Map<string, { subject: Highlight; color: number; count: number }>()
|
||||
const totalPixels = tiles.reduce((sum, placed) => sum + placed.tile.size * placed.tile.size, 0)
|
||||
const stride = Math.max(1, Math.ceil(Math.sqrt(totalPixels / MAXIMUM_COUNTED_PIXELS)))
|
||||
let counted = 0
|
||||
for (const { tile, worldX, worldZ } of tiles) {
|
||||
const scale = tile.blocksPerPixel
|
||||
const firstX = Math.max(0, Math.ceil((area.minimumX - worldX) / scale))
|
||||
const endX = Math.min(tile.size, Math.ceil((area.maximumX - worldX) / scale))
|
||||
const firstZ = Math.max(0, Math.ceil((area.minimumZ - worldZ) / scale))
|
||||
const endZ = Math.min(tile.size, Math.ceil((area.maximumZ - worldZ) / scale))
|
||||
for (let pixelZ = firstZ; pixelZ < endZ; pixelZ += stride) {
|
||||
for (let pixelX = firstX; pixelX < endX; pixelX += stride) {
|
||||
const subject = subjectAt(tile, gridIndex(tile, pixelX, pixelZ), byHeight, seaLevel)
|
||||
if (subject === null) {
|
||||
continue
|
||||
}
|
||||
const id = `${subject.subject.kind}:${subject.subject.key}`
|
||||
const entry = counts.get(id) ?? { ...subject, count: 0 }
|
||||
entry.count++
|
||||
counts.set(id, entry)
|
||||
counted++
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...counts.values()]
|
||||
.map((entry) => ({ subject: entry.subject, color: entry.color, fraction: entry.count / Math.max(1, counted) }))
|
||||
.sort((first, second) => second.fraction - first.fraction)
|
||||
}
|
||||
|
||||
function subjectAt(tile: MapTile, cell: number, byHeight: boolean, seaLevel: number): { subject: Highlight; color: number } | null {
|
||||
if (byHeight) {
|
||||
if (tile.heights === null) {
|
||||
return null
|
||||
}
|
||||
const band = HEIGHT_BANDS[bandIndexOf(tile.heights[cell], seaLevel)]
|
||||
return { subject: { kind: 'HEIGHT', key: band.key, name: band.name }, color: band.color }
|
||||
}
|
||||
const index = tile.subjects[cell]
|
||||
if (index === NO_LABEL) {
|
||||
return null
|
||||
}
|
||||
const label = tile.labels[index]
|
||||
return { subject: { kind: label.kind, key: label.key, name: label.name }, color: label.color }
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/** The height scale of the map, from deep water to snowy peaks, measured from sea level (v3e HeightColors). */
|
||||
|
||||
export const DEEPEST_BELOW_SEA_BLOCKS = 90
|
||||
export const HIGHEST_ABOVE_SEA_BLOCKS = 300
|
||||
const DEPTH_BLOCKS = [0, 10, 40, DEEPEST_BELOW_SEA_BLOCKS]
|
||||
const DEPTH_COLORS = [0x7db8d8, 0x4c8dba, 0x2a5e8f, 0x15304f]
|
||||
const ABOVE_SEA_BLOCKS = [0, 8, 30, 70, 130, 200, HIGHEST_ABOVE_SEA_BLOCKS]
|
||||
const LAND_COLORS = [0x7fa35a, 0x5e8c44, 0x8fa65a, 0xc2ae78, 0x8e7663, 0xa9a6a2, 0xf4f4f4]
|
||||
// Where each band ends, in blocks above sea; they follow the colour stops, merging the deepest two.
|
||||
const BAND_TOPS_ABOVE_SEA = [-40, -10, 0, 8, 30, 70, 130, 200, 300, Number.POSITIVE_INFINITY]
|
||||
|
||||
/** A stretch of heights between two of the scale's stops, for telling how much ground lies at each height. */
|
||||
export interface HeightBand {
|
||||
/** The band's place from the deepest, as text that sorts the same way. */
|
||||
key: string
|
||||
name: string
|
||||
color: number
|
||||
}
|
||||
|
||||
export function heightColor(height: number, seaLevel: number): number {
|
||||
if (height <= seaLevel) {
|
||||
return along(DEPTH_BLOCKS, DEPTH_COLORS, seaLevel - height)
|
||||
}
|
||||
return along(ABOVE_SEA_BLOCKS, LAND_COLORS, height - seaLevel)
|
||||
}
|
||||
|
||||
export const HEIGHT_BANDS: readonly HeightBand[] = createBands()
|
||||
|
||||
export function bandIndexOf(height: number, seaLevel: number): number {
|
||||
const aboveSea = height - seaLevel
|
||||
const index = BAND_TOPS_ABOVE_SEA.findIndex((top) => aboveSea <= top)
|
||||
return index < 0 ? BAND_TOPS_ABOVE_SEA.length - 1 : index
|
||||
}
|
||||
|
||||
function createBands(): HeightBand[] {
|
||||
const bands: HeightBand[] = []
|
||||
let bottom = -DEEPEST_BELOW_SEA_BLOCKS
|
||||
BAND_TOPS_ABOVE_SEA.forEach((top, band) => {
|
||||
const colorHeight = Number.isFinite(top) ? (bottom + top) / 2 : bottom
|
||||
bands.push({ key: String(band).padStart(2, '0'), name: bandName(band, bottom, top), color: heightColor(colorHeight, 0) })
|
||||
bottom = top
|
||||
})
|
||||
return bands
|
||||
}
|
||||
|
||||
function bandName(band: number, bottom: number, top: number): string {
|
||||
if (band === 0) {
|
||||
return `${Math.round(-top)}+ below sea`
|
||||
}
|
||||
if (!Number.isFinite(top)) {
|
||||
return `${Math.round(bottom)}+ above sea`
|
||||
}
|
||||
if (top <= 0) {
|
||||
return `${Math.round(-top)}–${Math.round(-bottom)} below sea`
|
||||
}
|
||||
return `${Math.round(bottom)}–${Math.round(top)} above sea`
|
||||
}
|
||||
|
||||
function along(stops: number[], colors: number[], blocks: number): number {
|
||||
if (blocks <= stops[0]) {
|
||||
return colors[0]
|
||||
}
|
||||
for (let stop = 1; stop < stops.length; stop++) {
|
||||
if (blocks <= stops[stop]) {
|
||||
return blend(colors[stop - 1], colors[stop], (blocks - stops[stop - 1]) / (stops[stop] - stops[stop - 1]))
|
||||
}
|
||||
}
|
||||
return colors[colors.length - 1]
|
||||
}
|
||||
|
||||
export function blend(first: number, second: number, amount: number): number {
|
||||
const red = Math.round(((first >> 16) & 0xff) * (1 - amount) + ((second >> 16) & 0xff) * amount)
|
||||
const green = Math.round(((first >> 8) & 0xff) * (1 - amount) + ((second >> 8) & 0xff) * amount)
|
||||
const blue = Math.round((first & 0xff) * (1 - amount) + (second & 0xff) * amount)
|
||||
return (red << 16) | (green << 8) | blue
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decodeTile, gridIndex } from '../bridge/tileDecoding'
|
||||
import type { MapLabel, MapTile } from '../bridge/types'
|
||||
import { countShares } from './census'
|
||||
import { bandIndexOf, HEIGHT_BANDS, heightColor } from './heightColors'
|
||||
import { stylePixels, type TileStyle } from './tileStyle'
|
||||
import { coarserTile, previewsFor, renderBlocksPerPixel, screenToWorldX, visibleTiles, worldToScreenX, type Viewport } from './viewport'
|
||||
|
||||
const PLAINS: MapLabel = { kind: 'BIOME', key: 'plains', name: 'Plains', color: 0x00ff00 }
|
||||
const DESERT: MapLabel = { kind: 'BIOME', key: 'desert', name: 'Desert', color: 0xffff00 }
|
||||
const WARM: MapLabel = { kind: 'REGION', key: 'warm', name: 'Warm', color: 0xff0000 }
|
||||
const FLAT: TileStyle = { byHeight: false, shading: false, regionBorders: false, highlight: null, seaLevel: 63, pickDisplay: 'picks' }
|
||||
|
||||
/** A tile whose left half is plains and right half desert, all in one region, at height 70. */
|
||||
function splitTile(size = 4): MapTile {
|
||||
const cells = (size + 2) ** 2
|
||||
const subjects = new Int16Array(cells)
|
||||
for (let cell = 0; cell < cells; cell++) {
|
||||
subjects[cell] = cell % (size + 2) <= size / 2 ? 0 : 1
|
||||
}
|
||||
return {
|
||||
size,
|
||||
blocksPerPixel: 1,
|
||||
subjectKind: 'BIOME',
|
||||
labels: [PLAINS, DESERT, WARM],
|
||||
subjects,
|
||||
regions: new Int16Array(cells).fill(2),
|
||||
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, 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 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)
|
||||
new Int16Array(buffer, regionsAt, cells).fill(-1)
|
||||
if (withHeights) {
|
||||
new Float32Array(buffer, heightsAt, cells).fill(81.5)
|
||||
}
|
||||
if (withPickNoise) {
|
||||
new Float32Array(buffer, pickNoiseAt, cells).fill(0.25)
|
||||
}
|
||||
return buffer
|
||||
}
|
||||
|
||||
describe('tile decoding', () => {
|
||||
it('reads the header and views each grid where the bridge put it', () => {
|
||||
const tile = decodeTile(encode(3, true))
|
||||
|
||||
expect(tile.size).toBe(3)
|
||||
expect(tile.blocksPerPixel).toBe(2)
|
||||
expect(tile.labels[0].key).toBe('plains')
|
||||
expect(tile.subjects.length).toBe(25)
|
||||
expect(tile.regions[0]).toBe(-1)
|
||||
expect(tile.heights?.[24]).toBe(81.5)
|
||||
})
|
||||
|
||||
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', () => {
|
||||
it('runs from deep water to snow and stays at the ends beyond them', () => {
|
||||
expect(heightColor(63, 63)).toBe(0x7db8d8)
|
||||
expect(heightColor(-1000, 63)).toBe(0x15304f)
|
||||
expect(heightColor(1000, 63)).toBe(0xf4f4f4)
|
||||
})
|
||||
|
||||
it('puts each height in the band the legend names', () => {
|
||||
expect(HEIGHT_BANDS[bandIndexOf(63, 63)].name).toBe('0–10 below sea')
|
||||
expect(HEIGHT_BANDS[bandIndexOf(64, 63)].name).toBe('0–8 above sea')
|
||||
expect(HEIGHT_BANDS[bandIndexOf(500, 63)].name).toBe('300+ above sea')
|
||||
expect(HEIGHT_BANDS[bandIndexOf(-500, 63)].name).toBe('40+ below sea')
|
||||
})
|
||||
})
|
||||
|
||||
describe('tile style', () => {
|
||||
const pixel = (pixels: Uint8ClampedArray, size: number, x: number, z: number): number => {
|
||||
const at = (z * size + x) * 4
|
||||
return (pixels[at] << 16) | (pixels[at + 1] << 8) | pixels[at + 2]
|
||||
}
|
||||
|
||||
it('paints each pixel in its label colour', () => {
|
||||
const pixels = stylePixels(splitTile(), FLAT)
|
||||
|
||||
expect(pixel(pixels, 4, 0, 0)).toBe(PLAINS.color)
|
||||
expect(pixel(pixels, 4, 3, 3)).toBe(DESERT.color)
|
||||
})
|
||||
|
||||
it('dims everything but the highlight, and tints the highlight edge', () => {
|
||||
const pixels = stylePixels(splitTile(), { ...FLAT, highlight: { kind: 'BIOME', key: 'plains', name: 'Plains' } })
|
||||
|
||||
expect(pixel(pixels, 4, 3, 3)).not.toBe(DESERT.color)
|
||||
expect(pixel(pixels, 4, 0, 1)).toBe(PLAINS.color)
|
||||
expect(pixel(pixels, 4, 1, 1)).not.toBe(PLAINS.color)
|
||||
})
|
||||
|
||||
it('leaves flat ground almost as it is when shading', () => {
|
||||
const pixels = stylePixels(splitTile(), { ...FLAT, shading: true })
|
||||
const green = (pixel(pixels, 4, 0, 0) >> 8) & 0xff
|
||||
|
||||
expect(green).toBeGreaterThan(200)
|
||||
})
|
||||
})
|
||||
|
||||
describe('viewport', () => {
|
||||
const view: Viewport = { centerX: 100, centerZ: -50, blocksPerPixel: 2, width: 800, height: 600 }
|
||||
|
||||
it('maps screen and world both ways', () => {
|
||||
expect(screenToWorldX(view, 400)).toBe(100)
|
||||
expect(worldToScreenX(view, screenToWorldX(view, 123))).toBe(123)
|
||||
})
|
||||
|
||||
it('draws tiles at the power of two nearest a device pixel, never finer than a block', () => {
|
||||
expect(renderBlocksPerPixel(4, 1)).toBe(4)
|
||||
expect(renderBlocksPerPixel(4, 2)).toBe(2)
|
||||
expect(renderBlocksPerPixel(0.25, 1)).toBe(1)
|
||||
expect(renderBlocksPerPixel(5.5, 1)).toBe(4)
|
||||
})
|
||||
|
||||
it('covers the screen, starting from the middle', () => {
|
||||
const tiles = visibleTiles(view, 2, 128)
|
||||
|
||||
// 1600 × 1200 blocks around (100, -50) in tiles of 256 blocks: x -3 to 3, z -3 to 2.
|
||||
expect(tiles.length).toBe(7 * 6)
|
||||
expect(tiles[0]).toEqual({ tileX: 0, tileZ: -1, blocksPerPixel: 2 })
|
||||
})
|
||||
|
||||
it('finds the coarser tile that covers a tile', () => {
|
||||
expect(coarserTile({ tileX: -3, tileZ: 5, blocksPerPixel: 2 }, 2)).toEqual({ tileX: -1, tileZ: 1, blocksPerPixel: 8 })
|
||||
})
|
||||
|
||||
it('previews four blank tiles with one tile a level out, never past the coarsest scale', () => {
|
||||
const blank = [
|
||||
{ tileX: 0, tileZ: 0, blocksPerPixel: 2 },
|
||||
{ tileX: 1, tileZ: 0, blocksPerPixel: 2 },
|
||||
{ tileX: 0, tileZ: 1, blocksPerPixel: 2 },
|
||||
{ tileX: -1, tileZ: 0, blocksPerPixel: 2 },
|
||||
{ tileX: 0, tileZ: 0, blocksPerPixel: 4096 }
|
||||
]
|
||||
|
||||
expect(previewsFor(blank)).toEqual([
|
||||
{ tileX: 0, tileZ: 0, blocksPerPixel: 4 },
|
||||
{ tileX: -1, tileZ: 0, blocksPerPixel: 4 }
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('census', () => {
|
||||
it('shares the visible pixels between the labels', () => {
|
||||
const tile = splitTile(4)
|
||||
const shares = countShares([{ tile, worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 4, maximumZ: 4 }, false, 63)
|
||||
|
||||
expect(shares.map((share) => share.subject.key).sort()).toEqual(['desert', 'plains'])
|
||||
expect(shares[0].fraction).toBeCloseTo(0.5)
|
||||
expect(gridIndex(tile, -1, -1)).toBe(0)
|
||||
})
|
||||
|
||||
it('counts only the part of a tile inside the area, largest share first', () => {
|
||||
const shares = countShares([{ tile: splitTile(4), worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 3, maximumZ: 4 }, false, 63)
|
||||
|
||||
expect(shares.map((share) => share.subject.key)).toEqual(['plains', 'desert'])
|
||||
expect(shares[0].fraction).toBeCloseTo(2 / 3)
|
||||
})
|
||||
|
||||
it('counts height bands in the height view', () => {
|
||||
const shares = countShares([{ tile: splitTile(4), worldX: 0, worldZ: 0 }], { minimumX: 0, minimumZ: 0, maximumX: 4, maximumZ: 4 }, true, 63)
|
||||
|
||||
expect(shares).toHaveLength(1)
|
||||
expect(shares[0].subject).toMatchObject({ kind: 'HEIGHT', name: '0–8 above sea' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { MapTile } from '../bridge/types'
|
||||
import { stylePixels, styleKey, type TileStyle } from './tileStyle'
|
||||
import type { TileSource } from './TileStore'
|
||||
|
||||
/** What one map 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
|
||||
}
|
||||
|
||||
/** The world map's tiles: the engine's streams, drawn in the map's styles. */
|
||||
export function mapTileSource(client: BridgeClient, tileSize: number): TileSource<MapTile, TileLayer, TileStyle> {
|
||||
return {
|
||||
layerKey: (layer) => [layer.revision, layer.view, layer.preview ?? '', layer.heights, layer.pickNoise].join('/'),
|
||||
fetch: (address, layer, signal) => client.tile({ ...layer, ...address, size: tileSize }, signal),
|
||||
bytesOf: (tile) => tile.subjects.byteLength * 2 + (tile.heights?.byteLength ?? 0) + (tile.pickNoise?.byteLength ?? 0) + tile.size * tile.size * 4,
|
||||
styleKey,
|
||||
pixels: (tile, style) => new ImageData(stylePixels(tile, style), tile.size, tile.size)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { coarserTile, previewsFor, visibleTiles, worldToScreenX, worldToScreenZ, type TileAddress, type Viewport } from './viewport'
|
||||
|
||||
// While a tile is on its way, a coarser one already drawn stands in, up to this many zoom levels out.
|
||||
const COARSER_FALLBACK_LEVELS = 6
|
||||
|
||||
export interface DrawnTiles {
|
||||
/** Every tile the view covers, nearest the centre first. */
|
||||
tiles: TileAddress[]
|
||||
ready: number
|
||||
/** What to fetch, in order: a coarser preview for each blank stretch first, then the tiles themselves. */
|
||||
wanted: TileAddress[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws the tiles covering the view at {@code renderScale}, from {@code pictureOf}; where one hasn't arrived, the part
|
||||
* of a coarser one that covers it.
|
||||
*/
|
||||
export function drawVisibleTiles(
|
||||
context: CanvasRenderingContext2D,
|
||||
view: Viewport,
|
||||
renderScale: number,
|
||||
tileSize: number,
|
||||
pictureOf: (address: TileAddress) => HTMLCanvasElement | null
|
||||
): DrawnTiles {
|
||||
const tiles = visibleTiles(view, renderScale, tileSize)
|
||||
context.imageSmoothingEnabled = view.blocksPerPixel > renderScale
|
||||
let ready = 0
|
||||
const blank: TileAddress[] = []
|
||||
for (const address of tiles) {
|
||||
const picture = pictureOf(address)
|
||||
if (picture !== null) {
|
||||
drawTile(context, view, tileSize, picture, address, 0, 0, picture.width)
|
||||
ready++
|
||||
} else if (!drawFallback(context, view, tileSize, address, pictureOf)) {
|
||||
blank.push(address)
|
||||
}
|
||||
}
|
||||
return { tiles, ready, wanted: [...previewsFor(blank), ...tiles] }
|
||||
}
|
||||
|
||||
/** Draws the part of a tile picture from (sourceX, sourceZ), {@code sourceSize} pixels wide, over {@code address}. */
|
||||
function drawTile(
|
||||
context: CanvasRenderingContext2D,
|
||||
view: Viewport,
|
||||
tileSize: number,
|
||||
picture: HTMLCanvasElement,
|
||||
address: TileAddress,
|
||||
sourceX: number,
|
||||
sourceZ: number,
|
||||
sourceSize: number
|
||||
): void {
|
||||
const span = tileSize * address.blocksPerPixel
|
||||
const left = Math.round(worldToScreenX(view, address.tileX * span))
|
||||
const top = Math.round(worldToScreenZ(view, address.tileZ * span))
|
||||
const right = Math.round(worldToScreenX(view, (address.tileX + 1) * span))
|
||||
const bottom = Math.round(worldToScreenZ(view, (address.tileZ + 1) * span))
|
||||
context.drawImage(picture, sourceX, sourceZ, sourceSize, sourceSize, left, top, right - left, bottom - top)
|
||||
}
|
||||
|
||||
/** Draws the part of a coarser tile that covers {@code address}; false when no coarser tile has arrived either. */
|
||||
function drawFallback(
|
||||
context: CanvasRenderingContext2D,
|
||||
view: Viewport,
|
||||
tileSize: number,
|
||||
address: TileAddress,
|
||||
pictureOf: (address: TileAddress) => HTMLCanvasElement | null
|
||||
): boolean {
|
||||
for (let levels = 1; levels <= COARSER_FALLBACK_LEVELS; levels++) {
|
||||
const coarser = coarserTile(address, levels)
|
||||
const picture = pictureOf(coarser)
|
||||
if (picture === null) {
|
||||
continue
|
||||
}
|
||||
const factor = 2 ** levels
|
||||
const sourceSize = picture.width / factor
|
||||
const sourceX = (address.tileX - coarser.tileX * factor) * sourceSize
|
||||
const sourceZ = (address.tileZ - coarser.tileZ * factor) * sourceSize
|
||||
drawTile(context, view, tileSize, picture, address, sourceX, sourceZ, sourceSize)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import { gridIndex } from '../bridge/tileDecoding'
|
||||
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. */
|
||||
export interface Highlight {
|
||||
kind: 'BIOME' | 'REGION' | 'HEIGHT'
|
||||
key: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface TileStyle {
|
||||
/** Colour by height instead of by label. */
|
||||
byHeight: boolean
|
||||
shading: boolean
|
||||
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}|${style.pickDisplay}`
|
||||
}
|
||||
|
||||
const UNKNOWN_SUBJECT = 0x5a5c62
|
||||
const SHADING_EXAGGERATION = 2
|
||||
const LIGHT_X = -0.5
|
||||
const LIGHT_Y = 0.7
|
||||
const LIGHT_Z = -0.5
|
||||
const LIGHT_LENGTH = Math.sqrt(LIGHT_X * LIGHT_X + LIGHT_Y * LIGHT_Y + LIGHT_Z * LIGHT_Z)
|
||||
const AMBIENT_LIGHT = 0.35
|
||||
const DIRECT_LIGHT = 0.75
|
||||
const DARKEST_SHADE = 0.25
|
||||
const BRIGHTEST_SHADE = 1.15
|
||||
// Water lies flat over the seafloor, so only a hint of the relief beneath shows through.
|
||||
const UNDERWATER_RELIEF = 0.15
|
||||
const DIM_TARGET = 0x1e1f22
|
||||
const DIM_AMOUNT = 0.72
|
||||
const DIM_DESATURATION = 0.6
|
||||
const HIGHLIGHT_EDGE = 0xffffff
|
||||
// A solid outline turns biomes that are scattered pixel by pixel into white noise, so the edge only tints.
|
||||
const HIGHLIGHT_EDGE_STRENGTH = 0.55
|
||||
const REGION_BORDER = 0x101114
|
||||
const REGION_BORDER_STRENGTH = 0.6
|
||||
const NOISE_LOW = 0x050505
|
||||
const NOISE_HIGH = 0xffffff
|
||||
// Picks drawn by their noise keep some colour where the noise is low, so they still read as the pick.
|
||||
const DARKEST_PICK_SHADE = 0.3
|
||||
|
||||
/** The tile's pixels as RGBA, as {@code style} draws them (v3e MapTile.styledPixels). */
|
||||
export function stylePixels(tile: MapTile, style: TileStyle): Uint8ClampedArray<ArrayBuffer> {
|
||||
const { size, heights } = tile
|
||||
const pixels = new Uint8ClampedArray(size * size * 4)
|
||||
const colors = tile.labels.map((label) => label.color)
|
||||
const byHeight = style.byHeight && heights !== null
|
||||
const pickNoise = style.pickDisplay === 'picks' ? null : tile.pickNoise
|
||||
// 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)
|
||||
}
|
||||
if (highlighted !== null) {
|
||||
color = highlight(tile, highlighted, cell, color)
|
||||
}
|
||||
if (style.regionBorders && isRegionEdge(tile, cell)) {
|
||||
color = blend(color, REGION_BORDER, REGION_BORDER_STRENGTH)
|
||||
}
|
||||
const at = (pixelZ * size + pixelX) * 4
|
||||
pixels[at] = (color >> 16) & 0xff
|
||||
pixels[at + 1] = (color >> 8) & 0xff
|
||||
pixels[at + 2] = color & 0xff
|
||||
pixels[at + 3] = 0xff
|
||||
}
|
||||
}
|
||||
return pixels
|
||||
}
|
||||
|
||||
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
|
||||
const slopeX = (heights[cell + 1] - heights[cell - 1]) / (2 * tile.blocksPerPixel)
|
||||
const slopeZ = (heights[cell + row] - heights[cell - row]) / (2 * tile.blocksPerPixel)
|
||||
const normalX = -slopeX * SHADING_EXAGGERATION
|
||||
const normalZ = -slopeZ * SHADING_EXAGGERATION
|
||||
const normalLength = Math.sqrt(normalX * normalX + 1 + normalZ * normalZ)
|
||||
const light = (normalX * LIGHT_X + LIGHT_Y + normalZ * LIGHT_Z) / (normalLength * LIGHT_LENGTH)
|
||||
let factor = Math.min(BRIGHTEST_SHADE, Math.max(DARKEST_SHADE, AMBIENT_LIGHT + DIRECT_LIGHT * light))
|
||||
if (heights[cell] <= seaLevel) {
|
||||
factor = 1 - (1 - factor) * UNDERWATER_RELIEF
|
||||
}
|
||||
return scale(color, factor)
|
||||
}
|
||||
|
||||
/** Which cells the highlight covers, as one flag per grid cell; null when nothing is highlighted. */
|
||||
function highlightCells(tile: MapTile, style: TileStyle): Uint8Array | null {
|
||||
const target = style.highlight
|
||||
if (target === null) {
|
||||
return null
|
||||
}
|
||||
const cells = new Uint8Array(tile.subjects.length)
|
||||
if (target.kind === 'HEIGHT') {
|
||||
if (tile.heights !== null) {
|
||||
const band = Number(target.key)
|
||||
tile.heights.forEach((height, cell) => {
|
||||
cells[cell] = bandIndexOf(height, style.seaLevel) === band ? 1 : 0
|
||||
})
|
||||
}
|
||||
return cells
|
||||
}
|
||||
// Every view knows its regions, so a region can be highlighted in a biome view too.
|
||||
const grid = target.kind === tile.subjectKind ? tile.subjects : target.kind === 'REGION' ? tile.regions : null
|
||||
const index = tile.labels.findIndex((label) => label.kind === target.kind && label.key === target.key)
|
||||
if (grid !== null && index >= 0) {
|
||||
grid.forEach((label, cell) => {
|
||||
cells[cell] = label === index ? 1 : 0
|
||||
})
|
||||
}
|
||||
return cells
|
||||
}
|
||||
|
||||
function highlight(tile: MapTile, highlighted: Uint8Array, cell: number, color: number): number {
|
||||
if (highlighted[cell] === 0) {
|
||||
return dim(color)
|
||||
}
|
||||
const row = tile.size + 2
|
||||
const edge = highlighted[cell + 1] === 0 || highlighted[cell - 1] === 0 || highlighted[cell + row] === 0 || highlighted[cell - row] === 0
|
||||
return edge ? blend(color, HIGHLIGHT_EDGE, HIGHLIGHT_EDGE_STRENGTH) : color
|
||||
}
|
||||
|
||||
function isRegionEdge(tile: MapTile, cell: number): boolean {
|
||||
const region = tile.regions[cell]
|
||||
return tile.regions[cell + 1] !== region || tile.regions[cell + tile.size + 2] !== region
|
||||
}
|
||||
|
||||
function dim(color: number): number {
|
||||
const gray = Math.floor((((color >> 16) & 0xff) + ((color >> 8) & 0xff) + (color & 0xff)) / 3)
|
||||
const desaturated = blend(color, (gray << 16) | (gray << 8) | gray, DIM_DESATURATION)
|
||||
return blend(desaturated, DIM_TARGET, DIM_AMOUNT)
|
||||
}
|
||||
|
||||
function scale(color: number, factor: number): number {
|
||||
const red = Math.min(255, Math.floor(((color >> 16) & 0xff) * factor))
|
||||
const green = Math.min(255, Math.floor(((color >> 8) & 0xff) * factor))
|
||||
const blue = Math.min(255, Math.floor((color & 0xff) * factor))
|
||||
return (red << 16) | (green << 8) | blue
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/** Where the map looks and how far it is zoomed; screen sizes are CSS pixels. */
|
||||
export interface Viewport {
|
||||
centerX: number
|
||||
centerZ: number
|
||||
blocksPerPixel: number
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export interface TileAddress {
|
||||
tileX: number
|
||||
tileZ: number
|
||||
blocksPerPixel: number
|
||||
}
|
||||
|
||||
export const MINIMUM_VIEW_BLOCKS_PER_PIXEL = 1 / 8
|
||||
export const MAXIMUM_BLOCKS_PER_PIXEL = 4096
|
||||
export const DEFAULT_BLOCKS_PER_PIXEL = 4
|
||||
// Iris has nothing finer than a block, so closer views magnify the block-sized tiles.
|
||||
const MINIMUM_RENDER_BLOCKS_PER_PIXEL = 1
|
||||
|
||||
export function clampBlocksPerPixel(blocksPerPixel: number): number {
|
||||
return Math.min(MAXIMUM_BLOCKS_PER_PIXEL, Math.max(MINIMUM_VIEW_BLOCKS_PER_PIXEL, blocksPerPixel))
|
||||
}
|
||||
|
||||
export function screenToWorldX(view: Viewport, screenX: number): number {
|
||||
return view.centerX + (screenX - view.width / 2) * view.blocksPerPixel
|
||||
}
|
||||
|
||||
export function screenToWorldZ(view: Viewport, screenZ: number): number {
|
||||
return view.centerZ + (screenZ - view.height / 2) * view.blocksPerPixel
|
||||
}
|
||||
|
||||
export function worldToScreenX(view: Viewport, worldX: number): number {
|
||||
return (worldX - view.centerX) / view.blocksPerPixel + view.width / 2
|
||||
}
|
||||
|
||||
export function worldToScreenZ(view: Viewport, worldZ: number): number {
|
||||
return (worldZ - view.centerZ) / view.blocksPerPixel + view.height / 2
|
||||
}
|
||||
|
||||
/**
|
||||
* The scale tiles are drawn at for a view: the nearest power of two to one tile pixel per device pixel, so tiles stay
|
||||
* sharp on dense screens and every zoom between two levels reuses the same tiles.
|
||||
*/
|
||||
export function renderBlocksPerPixel(
|
||||
viewBlocksPerPixel: number,
|
||||
devicePixelRatio: number,
|
||||
finestBlocksPerPixel = MINIMUM_RENDER_BLOCKS_PER_PIXEL
|
||||
): number {
|
||||
const level = 2 ** Math.round(Math.log2(viewBlocksPerPixel / devicePixelRatio))
|
||||
return Math.min(MAXIMUM_BLOCKS_PER_PIXEL, Math.max(finestBlocksPerPixel, level))
|
||||
}
|
||||
|
||||
/** The tiles covering the view, nearest the centre first so the middle of the screen fills in first. */
|
||||
export function visibleTiles(view: Viewport, renderScale: number, tileSize: number): TileAddress[] {
|
||||
const span = tileSize * renderScale
|
||||
const firstX = Math.floor(screenToWorldX(view, 0) / span)
|
||||
const lastX = Math.floor(screenToWorldX(view, view.width) / span)
|
||||
const firstZ = Math.floor(screenToWorldZ(view, 0) / span)
|
||||
const lastZ = Math.floor(screenToWorldZ(view, view.height) / span)
|
||||
const middleX = view.centerX / span - 0.5
|
||||
const middleZ = view.centerZ / span - 0.5
|
||||
const tiles: TileAddress[] = []
|
||||
for (let tileZ = firstZ; tileZ <= lastZ; tileZ++) {
|
||||
for (let tileX = firstX; tileX <= lastX; tileX++) {
|
||||
tiles.push({ tileX, tileZ, blocksPerPixel: renderScale })
|
||||
}
|
||||
}
|
||||
const distance = (tile: TileAddress): number => (tile.tileX - middleX) ** 2 + (tile.tileZ - middleZ) ** 2
|
||||
return tiles.sort((first, second) => distance(first) - distance(second))
|
||||
}
|
||||
|
||||
/**
|
||||
* One tile a level out for each group of blank tiles, in their order: a quarter of the pixels, so the screen fills
|
||||
* about four times sooner and sharpens as the tiles themselves arrive.
|
||||
*/
|
||||
export function previewsFor(blankTiles: TileAddress[]): TileAddress[] {
|
||||
const previews = new Map<string, TileAddress>()
|
||||
for (const tile of blankTiles) {
|
||||
const preview = coarserTile(tile, 1)
|
||||
if (preview.blocksPerPixel <= MAXIMUM_BLOCKS_PER_PIXEL) {
|
||||
previews.set(`${preview.tileX}/${preview.tileZ}/${preview.blocksPerPixel}`, preview)
|
||||
}
|
||||
}
|
||||
return [...previews.values()]
|
||||
}
|
||||
|
||||
/** The coarser tile that covers {@code tile}, {@code levels} zoom levels out. */
|
||||
export function coarserTile(tile: TileAddress, levels: number): TileAddress {
|
||||
const factor = 2 ** levels
|
||||
return {
|
||||
tileX: Math.floor(tile.tileX / factor),
|
||||
tileZ: Math.floor(tile.tileZ / factor),
|
||||
blocksPerPixel: tile.blocksPerPixel * factor
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { NoiseSource } from '../bridge/types'
|
||||
import { heightColor } from '../map/heightColors'
|
||||
import { INVALID_NOISE_COLOR, noiseScale } from './noiseScale'
|
||||
import { NoiseTerrain } from './noiseTerrain'
|
||||
|
||||
const UNIT_NOISE: NoiseSource = { id: 'style:SIMPLEX', name: 'Simplex', category: 'Simplex', usesSeed: true, blockRange: null }
|
||||
const BLOCK_NOISE: NoiseSource = { id: 'world:overlay', name: 'Overlay noise', category: 'Pack generators', usesSeed: false, blockRange: { lowest: -20, highest: 40 } }
|
||||
|
||||
describe('noise scale', () => {
|
||||
it('spans the palette for noise of 0 to 1 and takes its end colours past it', () => {
|
||||
const terrain = noiseScale('terrain', UNIT_NOISE)
|
||||
expect([terrain.minimum, terrain.maximum]).toEqual([0, 1])
|
||||
expect(terrain.colorOf(0)).toBe(0x071a2f)
|
||||
expect(terrain.colorOf(1)).toBe(0xf4f1de)
|
||||
expect(terrain.colorOf(7)).toBe(0xf4f1de)
|
||||
expect(noiseScale('signed', UNIT_NOISE).minimum).toBe(-1)
|
||||
})
|
||||
|
||||
it('spans the block range for noise in blocks, coloured as heights above the fluid', () => {
|
||||
const height = noiseScale('height', BLOCK_NOISE)
|
||||
expect([height.minimum, height.maximum]).toEqual([-20, 40])
|
||||
expect(height.colorOf(-20)).toBe(heightColor(-20, 0))
|
||||
expect(height.colorOf(40)).toBe(heightColor(40, 0))
|
||||
})
|
||||
|
||||
it('marks a value the noise could not give', () => {
|
||||
expect(noiseScale('grayscale', UNIT_NOISE).colorOf(Number.NaN)).toBe(INVALID_NOISE_COLOR)
|
||||
})
|
||||
})
|
||||
|
||||
describe('noise terrain', () => {
|
||||
const area = (values: number[]) => ({ tiles: [[{ size: 2, values: Float32Array.from(values) }]], originX: 10, originZ: 20, blocksPerValue: 4 })
|
||||
|
||||
it('raises noise of 0 to 1 to the relief, without water', () => {
|
||||
const terrain = new NoiseTerrain(area([0, 0.5, 1, Number.NaN]), UNIT_NOISE, noiseScale('terrain', UNIT_NOISE), 64)
|
||||
expect([terrain.groundAt(0, 0), terrain.groundAt(1, 0), terrain.groundAt(0, 1), terrain.groundAt(1, 1)]).toEqual([0, 32, 64, null])
|
||||
expect(terrain.waterAt(0, 0)).toBeNull()
|
||||
expect([terrain.worldX(1), terrain.worldZ(1)]).toEqual([14, 24])
|
||||
})
|
||||
|
||||
it('stands noise in blocks at its own height, under water below the fluid', () => {
|
||||
const terrain = new NoiseTerrain(area([-5, 12, 0, 3]), BLOCK_NOISE, noiseScale('height', BLOCK_NOISE), 64)
|
||||
expect(terrain.groundAt(0, 0)).toBe(-5)
|
||||
expect(terrain.waterAt(0, 0)).toBe(0)
|
||||
expect(terrain.waterAt(1, 0)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { NoiseSource } from '../bridge/types'
|
||||
import { DEEPEST_BELOW_SEA_BLOCKS, heightColor, HIGHEST_ABOVE_SEA_BLOCKS } from '../map/heightColors'
|
||||
|
||||
export type NoisePaletteId = 'terrain' | 'signed' | 'grayscale' | 'height' | 'green'
|
||||
|
||||
interface NoisePalette {
|
||||
id: NoisePaletteId
|
||||
label: string
|
||||
minimum: number
|
||||
maximum: number
|
||||
/** Colours from the minimum to the maximum, evenly spaced; null for the map's height colours. */
|
||||
stops: number[] | null
|
||||
}
|
||||
|
||||
/** v3e's noise palettes, each with the values it spans when the noise is not measured in blocks. */
|
||||
export const NOISE_PALETTES: readonly NoisePalette[] = [
|
||||
{ id: 'terrain', label: 'Terrain', minimum: 0, maximum: 1, stops: [0x071a2f, 0x155e75, 0x2a9d8f, 0xe9c46a, 0xf4f1de] },
|
||||
{ id: 'signed', label: 'Signed', minimum: -1, maximum: 1, stops: [0x173b66, 0x4f86c6, 0xe7edf3, 0xe89555, 0x9d3b35] },
|
||||
{ id: 'grayscale', label: 'Grayscale', minimum: 0, maximum: 1, stops: [0x050505, 0xffffff] },
|
||||
{ id: 'height', label: 'Height', minimum: 0, maximum: 1, stops: null },
|
||||
{ id: 'green', label: 'Green', minimum: 0, maximum: 1, stops: [0x2a3330, 0x5fd3a8] }
|
||||
]
|
||||
|
||||
/** The colour of a value the noise couldn't give, so it stands out from every palette. */
|
||||
export const INVALID_NOISE_COLOR = 0xff2daa
|
||||
const LOOKUP_SIZE = 256
|
||||
|
||||
/** How values become colours: the span the palette covers, and the colour of a value. */
|
||||
export interface NoiseScale {
|
||||
minimum: number
|
||||
maximum: number
|
||||
/** Over and under the span take the end colours. */
|
||||
colorOf(value: number): number
|
||||
/** The colour a fraction of the way along the span, for the legend. */
|
||||
colorAlong(fraction: number): number
|
||||
}
|
||||
|
||||
/**
|
||||
* The scale for a palette and a source: noise of 0 to 1 spans the palette's own range; noise in blocks spans its block
|
||||
* range, and the height palette then colours it as the map colours heights above the fluid.
|
||||
*/
|
||||
export function noiseScale(paletteId: NoisePaletteId, source: NoiseSource | null): NoiseScale {
|
||||
const palette = NOISE_PALETTES.find((candidate) => candidate.id === paletteId)!
|
||||
const blocks = source?.blockRange ?? null
|
||||
const minimum = blocks?.lowest ?? palette.minimum
|
||||
const maximum = blocks?.highest ?? palette.maximum
|
||||
const colorAlong = paletteColors(palette, blocks === null ? null : [blocks.lowest, blocks.highest])
|
||||
const span = maximum - minimum
|
||||
return {
|
||||
minimum,
|
||||
maximum,
|
||||
colorAlong,
|
||||
colorOf: (value) => (Number.isFinite(value) ? colorAlong(span <= 0 ? 0.5 : (value - minimum) / span) : INVALID_NOISE_COLOR)
|
||||
}
|
||||
}
|
||||
|
||||
function paletteColors(palette: NoisePalette, blockSpan: [number, number] | null): (fraction: number) => number {
|
||||
if (palette.stops === null) {
|
||||
const [lowest, highest] = blockSpan ?? [-DEEPEST_BELOW_SEA_BLOCKS, HIGHEST_ABOVE_SEA_BLOCKS]
|
||||
return (fraction) => heightColor(lowest + (highest - lowest) * clampUnit(fraction), 0)
|
||||
}
|
||||
const lookup = lookupOf(palette.stops)
|
||||
return (fraction) => lookup[Math.round(clampUnit(fraction) * (LOOKUP_SIZE - 1))]
|
||||
}
|
||||
|
||||
function lookupOf(stops: number[]): number[] {
|
||||
return Array.from({ length: LOOKUP_SIZE }, (_, index) => {
|
||||
const position = (index / (LOOKUP_SIZE - 1)) * (stops.length - 1)
|
||||
const lower = Math.min(stops.length - 2, Math.floor(position))
|
||||
return mix(stops[lower], stops[lower + 1], position - lower)
|
||||
})
|
||||
}
|
||||
|
||||
function mix(from: number, to: number, fraction: number): number {
|
||||
const channel = (shift: number): number => Math.round(((from >>> shift) & 0xff) + (((to >>> shift) & 0xff) - ((from >>> shift) & 0xff)) * fraction)
|
||||
return (channel(16) << 16) | (channel(8) << 8) | channel(0)
|
||||
}
|
||||
|
||||
function clampUnit(fraction: number): number {
|
||||
return Math.min(1, Math.max(0, fraction))
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { NoiseSource, NoiseTile } from '../bridge/types'
|
||||
import type { TerrainSurface } from '../scene/terrainMesh'
|
||||
import type { NoiseScale } from './noiseScale'
|
||||
|
||||
/** A square of noise tiles, row by row from the north west, and the block its first value is taken at. */
|
||||
export interface NoiseArea {
|
||||
tiles: NoiseTile[][]
|
||||
originX: number
|
||||
originZ: number
|
||||
blocksPerValue: number
|
||||
}
|
||||
|
||||
// The fluid of noise measured in blocks lies at its zero, as the world adds the overlay above its fluid height.
|
||||
const FLUID_BLOCKS = 0
|
||||
|
||||
/**
|
||||
* Noise as terrain (v3e's 3D noise): noise measured in blocks stands at its own height with water at the fluid;
|
||||
* other noise rises from its scale's minimum to {@code reliefBlocks} at its maximum, with no water.
|
||||
*/
|
||||
export class NoiseTerrain implements TerrainSurface {
|
||||
readonly columns: number
|
||||
readonly rows: number
|
||||
private readonly tileSize: number
|
||||
|
||||
constructor(
|
||||
private readonly area: NoiseArea,
|
||||
private readonly source: NoiseSource,
|
||||
private readonly scale: NoiseScale,
|
||||
private readonly reliefBlocks: number
|
||||
) {
|
||||
this.tileSize = area.tiles[0][0].size
|
||||
this.rows = area.tiles.length * this.tileSize
|
||||
this.columns = area.tiles[0].length * this.tileSize
|
||||
}
|
||||
|
||||
worldX(column: number): number {
|
||||
return this.area.originX + column * this.area.blocksPerValue
|
||||
}
|
||||
|
||||
worldZ(row: number): number {
|
||||
return this.area.originZ + row * this.area.blocksPerValue
|
||||
}
|
||||
|
||||
groundAt(column: number, row: number): number | null {
|
||||
const value = this.valueAt(column, row)
|
||||
return Number.isFinite(value) ? this.heightOf(value) : null
|
||||
}
|
||||
|
||||
waterAt(column: number, row: number): number | null {
|
||||
if (this.source.blockRange === null) {
|
||||
return null
|
||||
}
|
||||
const ground = this.groundAt(column, row)
|
||||
return ground !== null && ground < FLUID_BLOCKS ? FLUID_BLOCKS : null
|
||||
}
|
||||
|
||||
colorAt(column: number, row: number): number {
|
||||
return this.scale.colorOf(this.valueAt(column, row))
|
||||
}
|
||||
|
||||
private heightOf(value: number): number {
|
||||
if (this.source.blockRange !== null) {
|
||||
return value
|
||||
}
|
||||
const span = this.scale.maximum - this.scale.minimum
|
||||
return ((value - this.scale.minimum) / span) * this.reliefBlocks
|
||||
}
|
||||
|
||||
private valueAt(column: number, row: number): number {
|
||||
const tile = this.area.tiles[Math.floor(row / this.tileSize)][Math.floor(column / this.tileSize)]
|
||||
return tile.values[(row % this.tileSize) * tile.size + (column % this.tileSize)]
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { BridgeError, STATUS_UNAVAILABLE, type BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { AssetSource } from './blockModels'
|
||||
import type { ImageSource } from './textureAtlas'
|
||||
|
||||
const RETRY_MILLIS = 2000
|
||||
const LONGEST_WAIT_MILLIS = 10 * 60 * 1000
|
||||
|
||||
/**
|
||||
* The Minecraft client's assets through the bridge. The server fetches the client the first time anyone asks, so
|
||||
* until it has it every request waits, telling {@code onWaiting} why.
|
||||
*/
|
||||
export class BridgeAssets implements AssetSource, ImageSource {
|
||||
constructor(
|
||||
private readonly client: BridgeClient,
|
||||
private readonly onWaiting: (reason: string | null) => void
|
||||
) {}
|
||||
|
||||
async json(path: string): Promise<unknown> {
|
||||
const response = await this.fetch(path)
|
||||
return response === null ? null : response.json()
|
||||
}
|
||||
|
||||
async image(path: string): Promise<ImageBitmap | null> {
|
||||
const response = await this.fetch(path)
|
||||
return response === null ? null : createImageBitmap(await response.blob())
|
||||
}
|
||||
|
||||
private async fetch(path: string): Promise<Response | null> {
|
||||
const giveUpAt = Date.now() + LONGEST_WAIT_MILLIS
|
||||
for (;;) {
|
||||
try {
|
||||
const response = await this.client.asset(path)
|
||||
this.onWaiting(null)
|
||||
return response
|
||||
} catch (error) {
|
||||
if (!(error instanceof BridgeError) || error.status !== STATUS_UNAVAILABLE || Date.now() > giveUpAt) {
|
||||
throw error
|
||||
}
|
||||
this.onWaiting(error.message)
|
||||
await new Promise((resume) => window.setTimeout(resume, RETRY_MILLIS))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { blockTint } from './blockTints'
|
||||
import { parseState, type BlockModels } from './blockModels'
|
||||
import { texturePath, type ImageSource } from './textureAtlas'
|
||||
|
||||
const UNKNOWN_BLOCK_COLOR = 0x7f7f7f
|
||||
const OPAQUE_ENOUGH_ALPHA = 128
|
||||
const NO_TINT = 0xffffff
|
||||
|
||||
/** 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 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.colors.get(block)
|
||||
if (color === undefined) {
|
||||
color = this.topTexture(block).then((texture) => (texture === null ? UNKNOWN_BLOCK_COLOR : averageColor(texture)))
|
||||
this.colors.set(block, color)
|
||||
}
|
||||
return color
|
||||
}
|
||||
|
||||
/** Every block's colour, by name. */
|
||||
async colorsOf(blocks: Iterable<string>): Promise<Map<string, number>> {
|
||||
const names = [...new Set(blocks)]
|
||||
const colors = await Promise.all(names.map((name) => this.colorOf(name)))
|
||||
return new Map(names.map((name, index) => [name, colors[index]]))
|
||||
}
|
||||
|
||||
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 null
|
||||
}
|
||||
const bitmap = await this.images.image(texturePath(texture))
|
||||
if (bitmap === null) {
|
||||
return null
|
||||
}
|
||||
const state = parseState(block)
|
||||
return tinted(firstFrame(bitmap), blockTint(state.name, state.properties, top?.tintIndex ?? -1))
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
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) {
|
||||
red += pixels[offset]
|
||||
green += pixels[offset + 1]
|
||||
blue += pixels[offset + 2]
|
||||
counted++
|
||||
}
|
||||
}
|
||||
if (counted === 0) {
|
||||
return UNKNOWN_BLOCK_COLOR
|
||||
}
|
||||
return (Math.round(red / counted) << 16) | (Math.round(green / counted) << 8) | Math.round(blue / counted)
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { BlockModels, parseState, type AssetSource } from './blockModels'
|
||||
|
||||
const CUBE_ALL = {
|
||||
textures: { particle: '#all' },
|
||||
elements: [
|
||||
{
|
||||
from: [0, 0, 0],
|
||||
to: [16, 16, 16],
|
||||
faces: Object.fromEntries(['down', 'up', 'north', 'south', 'west', 'east'].map((side) => [side, { texture: '#all', cullface: side }]))
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
const FILES: Record<string, unknown> = {
|
||||
'minecraft/blockstates/stone.json': { variants: { '': { model: 'minecraft:block/stone' } } },
|
||||
'minecraft/models/block/stone.json': { parent: 'block/cube_all', textures: { all: 'minecraft:block/stone' } },
|
||||
'minecraft/models/block/cube_all.json': CUBE_ALL,
|
||||
'minecraft/blockstates/oak_log.json': {
|
||||
variants: { 'axis=y': { model: 'block/oak_log' }, 'axis=x': { model: 'block/oak_log', x: 90, y: 90 } }
|
||||
},
|
||||
'minecraft/models/block/oak_log.json': { parent: 'block/cube_all', textures: { all: 'block/oak_log' } },
|
||||
'minecraft/blockstates/fence.json': {
|
||||
multipart: [{ apply: { model: 'block/stone' } }, { when: { north: 'true' }, apply: { model: 'block/stone' } }, { when: { OR: [{ east: 'true' }, { west: 'true|x' }] }, apply: { model: 'block/stone' } }]
|
||||
},
|
||||
'minecraft/blockstates/chest.json': { variants: { '': { model: 'block/chest' } } },
|
||||
'minecraft/models/block/chest.json': { textures: { particle: 'block/oak_planks' } }
|
||||
}
|
||||
|
||||
const assets: AssetSource = { json: async (path) => FILES[path] ?? null }
|
||||
|
||||
describe('block models', () => {
|
||||
it('reads a block state key', () => {
|
||||
expect(parseState('minecraft:oak_log[axis=y]')).toEqual({ namespace: 'minecraft', name: 'oak_log', properties: { axis: 'y' } })
|
||||
expect(parseState('stone')).toEqual({ namespace: 'minecraft', name: 'stone', properties: {} })
|
||||
})
|
||||
|
||||
it('fills a model from its parents and keeps its six faces culled by their sides', async () => {
|
||||
const stone = (await new BlockModels(assets).model('minecraft:stone'))!
|
||||
|
||||
expect(stone.fullCube).toBe(true)
|
||||
expect(stone.particle).toBe('minecraft:block/stone')
|
||||
expect(stone.quads.map((quad) => quad.texture)).toEqual(Array(6).fill('minecraft:block/stone'))
|
||||
expect(stone.quads.find((quad) => quad.facing === 'up')!.corners.every(([, y]) => y === 1)).toBe(true)
|
||||
})
|
||||
|
||||
it('turns a variant: x first, then y, so a log lying along x shows its top to the east', async () => {
|
||||
const log = (await new BlockModels(assets).model('minecraft:oak_log[axis=x]'))!
|
||||
const top = log.quads.find((quad) => quad.cullFace === 'east')!
|
||||
|
||||
expect(top.facing).toBe('east')
|
||||
expect(top.corners.every(([x]) => Math.abs(x - 1) < 1e-9)).toBe(true)
|
||||
})
|
||||
|
||||
it('applies the multipart pieces whose conditions the state meets', async () => {
|
||||
const models = new BlockModels(assets)
|
||||
|
||||
expect((await models.model('minecraft:fence[east=false,north=false,west=false]'))!.quads).toHaveLength(6)
|
||||
expect((await models.model('minecraft:fence[east=false,north=true,west=x]'))!.quads).toHaveLength(18)
|
||||
})
|
||||
|
||||
it('knows a model without elements, and no model at all', async () => {
|
||||
const models = new BlockModels(assets)
|
||||
|
||||
expect(await models.model('minecraft:chest')).toEqual({ quads: [], fullCube: false, particle: 'minecraft:block/oak_planks' })
|
||||
expect(await models.model('minecraft:nothing')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,389 @@
|
||||
/**
|
||||
* Minecraft's block models, read the way the client reads them: a block state picks variants or multipart pieces from
|
||||
* its blockstate file, each a model whose parents fill in textures and elements, turned in steps of 90 degrees.
|
||||
*/
|
||||
|
||||
export type Direction = 'down' | 'up' | 'north' | 'south' | 'west' | 'east'
|
||||
export type Vec3 = [number, number, number]
|
||||
|
||||
/** Where a block model's files come from: the bridge's copy of the client's assets. */
|
||||
export interface AssetSource {
|
||||
/** The JSON file at {@code path} below the assets folder, or null when there is none. */
|
||||
json(path: string): Promise<unknown>
|
||||
}
|
||||
|
||||
/** One textured face of a block, in block units from its lowest corner (0 to 1 on each axis). */
|
||||
export interface Quad {
|
||||
/** Top left, bottom left, bottom right, top right as the texture lies on the face, seen from outside. */
|
||||
corners: [Vec3, Vec3, Vec3, Vec3]
|
||||
/** The texture's coordinates at each corner, 0 to 1 from its top left. */
|
||||
uvs: [[number, number], [number, number], [number, number], [number, number]]
|
||||
/** Such as minecraft:block/stone. */
|
||||
texture: string
|
||||
/** Which of the block's tints colours the face, or -1 for none. */
|
||||
tintIndex: number
|
||||
/** The side whose neighbour, when it is a solid block, hides the face; null when nothing hides it. */
|
||||
cullFace: Direction | null
|
||||
/** The side the face looks toward, for its light. */
|
||||
facing: Direction
|
||||
shade: boolean
|
||||
}
|
||||
|
||||
export interface BlockModel {
|
||||
quads: Quad[]
|
||||
/** A single element filling the whole block on every side, which hides the faces it touches if its textures are solid. */
|
||||
fullCube: boolean
|
||||
/** The texture the client breaks the block with, which stands in for blocks the client draws without a model. */
|
||||
particle: string | null
|
||||
}
|
||||
|
||||
export interface ParsedState {
|
||||
namespace: string
|
||||
name: string
|
||||
properties: Record<string, string>
|
||||
}
|
||||
|
||||
type Json = Record<string, unknown>
|
||||
|
||||
interface Variant {
|
||||
model: string
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
interface ModelFile {
|
||||
parent?: string
|
||||
textures?: Record<string, string>
|
||||
elements?: ElementJson[]
|
||||
}
|
||||
|
||||
interface ElementJson {
|
||||
from: Vec3
|
||||
to: Vec3
|
||||
rotation?: { origin: Vec3; axis: 'x' | 'y' | 'z'; angle: number; rescale?: boolean }
|
||||
shade?: boolean
|
||||
faces: Partial<Record<Direction, FaceJson>>
|
||||
}
|
||||
|
||||
interface FaceJson {
|
||||
uv?: [number, number, number, number]
|
||||
texture: string
|
||||
cullface?: Direction
|
||||
rotation?: number
|
||||
tintindex?: number
|
||||
}
|
||||
|
||||
const PIXELS = 16
|
||||
const DEFAULT_NAMESPACE = 'minecraft'
|
||||
const MAX_PARENT_DEPTH = 32
|
||||
const DIRECTIONS: Direction[] = ['down', 'up', 'north', 'south', 'west', 'east']
|
||||
const DIRECTION_VECTORS: Record<Direction, Vec3> = {
|
||||
down: [0, -1, 0],
|
||||
up: [0, 1, 0],
|
||||
north: [0, 0, -1],
|
||||
south: [0, 0, 1],
|
||||
west: [-1, 0, 0],
|
||||
east: [1, 0, 0]
|
||||
}
|
||||
|
||||
/** Reads {@code minecraft:oak_log[axis=y]}. */
|
||||
export function parseState(key: string): ParsedState {
|
||||
const open = key.indexOf('[')
|
||||
const id = open < 0 ? key : key.slice(0, open)
|
||||
const colon = id.indexOf(':')
|
||||
const properties: Record<string, string> = {}
|
||||
if (open >= 0) {
|
||||
for (const pair of key.slice(open + 1, -1).split(',')) {
|
||||
const equals = pair.indexOf('=')
|
||||
if (equals > 0) {
|
||||
properties[pair.slice(0, equals)] = pair.slice(equals + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
return colon < 0
|
||||
? { namespace: DEFAULT_NAMESPACE, name: id, properties }
|
||||
: { namespace: id.slice(0, colon), name: id.slice(colon + 1), properties }
|
||||
}
|
||||
|
||||
/** Resolves and keeps the models of block states; one per connection, as its assets are one Minecraft version's. */
|
||||
export class BlockModels {
|
||||
private readonly models = new Map<string, Promise<BlockModel | null>>()
|
||||
private readonly files = new Map<string, Promise<ModelFile | null>>()
|
||||
|
||||
constructor(private readonly assets: AssetSource) {}
|
||||
|
||||
/** The model of a block state, or null when the client has no blockstate file for the block. */
|
||||
model(stateKey: string): Promise<BlockModel | null> {
|
||||
let model = this.models.get(stateKey)
|
||||
if (model === undefined) {
|
||||
model = this.resolve(parseState(stateKey))
|
||||
this.models.set(stateKey, model)
|
||||
}
|
||||
return model
|
||||
}
|
||||
|
||||
private async resolve(state: ParsedState): Promise<BlockModel | null> {
|
||||
const blockstate = (await this.assets.json(`${state.namespace}/blockstates/${state.name}.json`)) as Json | null
|
||||
if (blockstate === null) {
|
||||
return null
|
||||
}
|
||||
const variants = pickVariants(blockstate, state.properties)
|
||||
const pieces = await Promise.all(variants.map((variant) => this.piece(variant)))
|
||||
const quads = pieces.flatMap((piece) => piece.quads)
|
||||
return { quads, fullCube: pieces.length === 1 && pieces[0].fullCube, particle: pieces[0]?.particle ?? null }
|
||||
}
|
||||
|
||||
private async piece(variant: Variant): Promise<BlockModel> {
|
||||
const chain = await this.parentChain(variant.model)
|
||||
const textures: Record<string, string> = {}
|
||||
for (const file of [...chain].reverse()) {
|
||||
Object.assign(textures, file.textures ?? {})
|
||||
}
|
||||
const elements = chain.find((file) => file.elements !== undefined)?.elements ?? []
|
||||
const quads = elements.flatMap((element) => elementQuads(element, textures))
|
||||
const turned = quads.map((quad) => turn(quad, variant.x, variant.y))
|
||||
return { quads: turned, fullCube: elements.length === 1 && isFullCube(elements[0]), particle: textureOf('#particle', textures) }
|
||||
}
|
||||
|
||||
private async parentChain(modelId: string): Promise<ModelFile[]> {
|
||||
const chain: ModelFile[] = []
|
||||
let next: string | undefined = modelId
|
||||
while (next !== undefined && chain.length < MAX_PARENT_DEPTH) {
|
||||
const file = await this.file(next)
|
||||
if (file === null) {
|
||||
break
|
||||
}
|
||||
chain.push(file)
|
||||
next = file.parent
|
||||
}
|
||||
return chain
|
||||
}
|
||||
|
||||
private file(modelId: string): Promise<ModelFile | null> {
|
||||
let file = this.files.get(modelId)
|
||||
if (file === undefined) {
|
||||
const { namespace, path } = splitId(modelId)
|
||||
file = this.assets.json(`${namespace}/models/${path}.json`) as Promise<ModelFile | null>
|
||||
this.files.set(modelId, file)
|
||||
}
|
||||
return file
|
||||
}
|
||||
}
|
||||
|
||||
/** A whole block with {@code texture} on every side, for blocks the client draws without a model. */
|
||||
export function cubeModel(texture: string): BlockModel {
|
||||
const faces = Object.fromEntries(DIRECTIONS.map((direction) => [direction, { texture: '#all', cullface: direction }]))
|
||||
const quads = elementQuads({ from: [0, 0, 0], to: [PIXELS, PIXELS, PIXELS], faces }, { all: texture })
|
||||
return { quads, fullCube: true, particle: texture }
|
||||
}
|
||||
|
||||
/** The variant a block state picks, or the multipart pieces whose conditions it meets; the first of weighted choices. */
|
||||
function pickVariants(blockstate: Json, properties: Record<string, string>): Variant[] {
|
||||
const variants = blockstate.variants as Record<string, unknown> | undefined
|
||||
if (variants !== undefined) {
|
||||
for (const [condition, choice] of Object.entries(variants)) {
|
||||
if (matchesVariantKey(condition, properties)) {
|
||||
return [variantOf(choice)]
|
||||
}
|
||||
}
|
||||
return []
|
||||
}
|
||||
const multipart = blockstate.multipart as { when?: Json; apply: unknown }[] | undefined
|
||||
return (multipart ?? []).filter((part) => part.when === undefined || meets(part.when, properties)).map((part) => variantOf(part.apply))
|
||||
}
|
||||
|
||||
function matchesVariantKey(condition: string, properties: Record<string, string>): boolean {
|
||||
if (condition === '') {
|
||||
return true
|
||||
}
|
||||
return condition.split(',').every((pair) => {
|
||||
const [name, value] = pair.split('=')
|
||||
return properties[name] === value
|
||||
})
|
||||
}
|
||||
|
||||
function meets(condition: Json, properties: Record<string, string>): boolean {
|
||||
if (Array.isArray(condition.OR)) {
|
||||
return (condition.OR as Json[]).some((part) => meets(part, properties))
|
||||
}
|
||||
if (Array.isArray(condition.AND)) {
|
||||
return (condition.AND as Json[]).every((part) => meets(part, properties))
|
||||
}
|
||||
return Object.entries(condition).every(([name, allowed]) => String(allowed).split('|').includes(properties[name]))
|
||||
}
|
||||
|
||||
function variantOf(choice: unknown): Variant {
|
||||
const picked = (Array.isArray(choice) ? choice[0] : choice) as Json
|
||||
return { model: String(picked.model), x: Number(picked.x ?? 0), y: Number(picked.y ?? 0) }
|
||||
}
|
||||
|
||||
function splitId(id: string): { namespace: string; path: string } {
|
||||
const colon = id.indexOf(':')
|
||||
return colon < 0 ? { namespace: DEFAULT_NAMESPACE, path: id } : { namespace: id.slice(0, colon), path: id.slice(colon + 1) }
|
||||
}
|
||||
|
||||
function isFullCube(element: ElementJson): boolean {
|
||||
const fills = element.from.every((value) => value === 0) && element.to.every((value) => value === PIXELS)
|
||||
return fills && element.rotation === undefined && DIRECTIONS.every((direction) => element.faces[direction] !== undefined)
|
||||
}
|
||||
|
||||
function elementQuads(element: ElementJson, textures: Record<string, string>): Quad[] {
|
||||
const quads: Quad[] = []
|
||||
for (const direction of DIRECTIONS) {
|
||||
const face = element.faces[direction]
|
||||
if (face === undefined) {
|
||||
continue
|
||||
}
|
||||
const texture = textureOf(face.texture, textures)
|
||||
if (texture === null) {
|
||||
continue
|
||||
}
|
||||
const corners = faceCorners(direction, element.from, element.to).map((corner) => rotateInElement(corner, element)) as Quad['corners']
|
||||
quads.push({
|
||||
corners,
|
||||
uvs: faceUvs(face, direction, element.from, element.to),
|
||||
texture,
|
||||
tintIndex: face.tintindex ?? -1,
|
||||
cullFace: face.cullface ?? null,
|
||||
facing: direction,
|
||||
shade: element.shade ?? true
|
||||
})
|
||||
}
|
||||
return quads
|
||||
}
|
||||
|
||||
/** Follows {@code #name} references through the model's textures to a texture id. */
|
||||
function textureOf(reference: string, textures: Record<string, string>): string | null {
|
||||
let current = reference
|
||||
for (let step = 0; step < MAX_PARENT_DEPTH && current.startsWith('#'); step++) {
|
||||
const next = textures[current.slice(1)]
|
||||
if (next === undefined) {
|
||||
return null
|
||||
}
|
||||
current = next
|
||||
}
|
||||
if (current.startsWith('#')) {
|
||||
return null
|
||||
}
|
||||
const { namespace, path } = splitId(current)
|
||||
return `${namespace}:${path}`
|
||||
}
|
||||
|
||||
/** A face's corners in pixels, top left first and counter-clockwise seen from outside, as {@link Quad#corners}. */
|
||||
function faceCorners(direction: Direction, from: Vec3, to: Vec3): Vec3[] {
|
||||
const [x1, y1, z1] = from.map((value) => value / PIXELS)
|
||||
const [x2, y2, z2] = to.map((value) => value / PIXELS)
|
||||
switch (direction) {
|
||||
case 'north':
|
||||
return [[x2, y2, z1], [x2, y1, z1], [x1, y1, z1], [x1, y2, z1]]
|
||||
case 'south':
|
||||
return [[x1, y2, z2], [x1, y1, z2], [x2, y1, z2], [x2, y2, z2]]
|
||||
case 'west':
|
||||
return [[x1, y2, z1], [x1, y1, z1], [x1, y1, z2], [x1, y2, z2]]
|
||||
case 'east':
|
||||
return [[x2, y2, z2], [x2, y1, z2], [x2, y1, z1], [x2, y2, z1]]
|
||||
case 'up':
|
||||
return [[x1, y2, z1], [x1, y2, z2], [x2, y2, z2], [x2, y2, z1]]
|
||||
case 'down':
|
||||
return [[x1, y1, z2], [x1, y1, z1], [x2, y1, z1], [x2, y1, z2]]
|
||||
}
|
||||
}
|
||||
|
||||
function faceUvs(face: FaceJson, direction: Direction, from: Vec3, to: Vec3): Quad['uvs'] {
|
||||
const [u1, v1, u2, v2] = (face.uv ?? defaultUv(direction, from, to)).map((value) => value / PIXELS)
|
||||
const uvs: Quad['uvs'] = [[u1, v1], [u1, v2], [u2, v2], [u2, v1]]
|
||||
const steps = (((face.rotation ?? 0) / 90) % 4 + 4) % 4
|
||||
return uvs.map((_, corner) => uvs[(corner + steps) % 4]) as Quad['uvs']
|
||||
}
|
||||
|
||||
// Minecraft's own default: the face shows the part of the texture its element covers, seen from outside.
|
||||
function defaultUv(direction: Direction, [x1, y1, z1]: Vec3, [x2, y2, z2]: Vec3): [number, number, number, number] {
|
||||
switch (direction) {
|
||||
case 'down':
|
||||
return [x1, PIXELS - z2, x2, PIXELS - z1]
|
||||
case 'up':
|
||||
return [x1, z1, x2, z2]
|
||||
case 'north':
|
||||
return [PIXELS - x2, PIXELS - y2, PIXELS - x1, PIXELS - y1]
|
||||
case 'south':
|
||||
return [x1, PIXELS - y2, x2, PIXELS - y1]
|
||||
case 'west':
|
||||
return [z1, PIXELS - y2, z2, PIXELS - y1]
|
||||
case 'east':
|
||||
return [PIXELS - z2, PIXELS - y2, PIXELS - z1, PIXELS - y1]
|
||||
}
|
||||
}
|
||||
|
||||
function rotateInElement(corner: Vec3, element: ElementJson): Vec3 {
|
||||
const rotation = element.rotation
|
||||
if (rotation === undefined || rotation.angle === 0) {
|
||||
return corner
|
||||
}
|
||||
const origin = rotation.origin.map((value) => value / PIXELS) as Vec3
|
||||
const radians = (rotation.angle * Math.PI) / 180
|
||||
const relative: Vec3 = [corner[0] - origin[0], corner[1] - origin[1], corner[2] - origin[2]]
|
||||
const turned = rotateAboutAxis(relative, rotation.axis, radians)
|
||||
if (rotation.rescale === true) {
|
||||
const stretch = 1 / Math.cos(Math.abs(radians))
|
||||
for (const axis of [0, 1, 2]) {
|
||||
if (axis !== 'xyz'.indexOf(rotation.axis)) {
|
||||
turned[axis] *= stretch
|
||||
}
|
||||
}
|
||||
}
|
||||
return [turned[0] + origin[0], turned[1] + origin[1], turned[2] + origin[2]]
|
||||
}
|
||||
|
||||
function rotateAboutAxis([x, y, z]: Vec3, axis: 'x' | 'y' | 'z', radians: number): Vec3 {
|
||||
const cos = Math.cos(radians)
|
||||
const sin = Math.sin(radians)
|
||||
switch (axis) {
|
||||
case 'x':
|
||||
return [x, y * cos - z * sin, y * sin + z * cos]
|
||||
case 'y':
|
||||
return [x * cos + z * sin, y, -x * sin + z * cos]
|
||||
case 'z':
|
||||
return [x * cos - y * sin, x * sin + y * cos, z]
|
||||
}
|
||||
}
|
||||
|
||||
/** A variant's turn: {@code x} first, then {@code y}, each in steps of 90 degrees about the block's centre. */
|
||||
function turn(quad: Quad, xDegrees: number, yDegrees: number): Quad {
|
||||
const xSteps = quarterTurns(xDegrees)
|
||||
const ySteps = quarterTurns(yDegrees)
|
||||
if (xSteps === 0 && ySteps === 0) {
|
||||
return quad
|
||||
}
|
||||
const turnPoint = (point: Vec3): Vec3 => offsetFromCentre(turnVector(offsetFromCentre(point, -0.5), xSteps, ySteps), 0.5)
|
||||
return {
|
||||
...quad,
|
||||
corners: quad.corners.map(turnPoint) as Quad['corners'],
|
||||
cullFace: quad.cullFace === null ? null : directionOf(turnVector(DIRECTION_VECTORS[quad.cullFace], xSteps, ySteps)),
|
||||
facing: directionOf(turnVector(DIRECTION_VECTORS[quad.facing], xSteps, ySteps))
|
||||
}
|
||||
}
|
||||
|
||||
function quarterTurns(degrees: number): number {
|
||||
return ((Math.round(degrees / 90) % 4) + 4) % 4
|
||||
}
|
||||
|
||||
function offsetFromCentre([x, y, z]: Vec3, by: number): Vec3 {
|
||||
return [x + by, y + by, z + by]
|
||||
}
|
||||
|
||||
// A quarter turn about x takes north to down; one about y takes north to east, as Minecraft turns its variants.
|
||||
function turnVector(vector: Vec3, xSteps: number, ySteps: number): Vec3 {
|
||||
let [x, y, z] = vector
|
||||
for (let step = 0; step < xSteps; step++) {
|
||||
;[y, z] = [z, -y]
|
||||
}
|
||||
for (let step = 0; step < ySteps; step++) {
|
||||
;[x, z] = [-z, x]
|
||||
}
|
||||
return [x, y, z]
|
||||
}
|
||||
|
||||
function directionOf([x, y, z]: Vec3): Direction {
|
||||
const rounded = [Math.round(x), Math.round(y), Math.round(z)].join(',')
|
||||
return DIRECTIONS.find((direction) => DIRECTION_VECTORS[direction].join(',') === rounded) ?? 'up'
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* The colour each tinted face of a block is multiplied with, as Minecraft's BlockColors give it (v3e
|
||||
* MinecraftBlockTints). Scenes stand in no biome, so the biome tints are the plains' colours.
|
||||
*/
|
||||
|
||||
const NO_TINT = 0xffffff
|
||||
const PLAINS_GRASS = 0x91bd59
|
||||
const PLAINS_FOLIAGE = 0x77ab2f
|
||||
const PLAINS_DRY_FOLIAGE = 0xa0804b
|
||||
const PLAINS_WATER = 0x3f76e4
|
||||
|
||||
const GRASS_TINTED = new Set(['grass_block', 'short_grass', 'fern', 'potted_fern', 'bush', 'tall_grass', 'large_fern', 'sugar_cane'])
|
||||
const GRASS_TINTED_ON_SECOND_LAYER = new Set(['pink_petals', 'wildflowers'])
|
||||
const FOLIAGE_TINTED = new Set(['oak_leaves', 'jungle_leaves', 'acacia_leaves', 'dark_oak_leaves', 'vine', 'mangrove_leaves'])
|
||||
const WATER_TINTED = new Set(['water', 'bubble_column', 'water_cauldron'])
|
||||
const GROWING_STEMS = new Set(['melon_stem', 'pumpkin_stem'])
|
||||
const FIXED_TINTS: Record<string, number> = {
|
||||
spruce_leaves: 0x619961,
|
||||
birch_leaves: 0x80a755,
|
||||
attached_melon_stem: 0xe0c71c,
|
||||
attached_pumpkin_stem: 0xe0c71c,
|
||||
lily_pad: 0x208030
|
||||
}
|
||||
|
||||
/** The tint of one face of block {@code name}, as 0xRRGGBB; white for an untinted face. */
|
||||
export function blockTint(name: string, properties: Record<string, string>, tintIndex: number): number {
|
||||
// The client tints water when it draws the fluid, which has no model, so its stand-in is tinted whole.
|
||||
if (WATER_TINTED.has(name)) {
|
||||
return PLAINS_WATER
|
||||
}
|
||||
if (GRASS_TINTED_ON_SECOND_LAYER.has(name)) {
|
||||
return tintIndex === 1 ? PLAINS_GRASS : NO_TINT
|
||||
}
|
||||
if (tintIndex !== 0) {
|
||||
return NO_TINT
|
||||
}
|
||||
if (GRASS_TINTED.has(name)) {
|
||||
return PLAINS_GRASS
|
||||
}
|
||||
if (FOLIAGE_TINTED.has(name)) {
|
||||
return PLAINS_FOLIAGE
|
||||
}
|
||||
if (name === 'leaf_litter') {
|
||||
return PLAINS_DRY_FOLIAGE
|
||||
}
|
||||
if (GROWING_STEMS.has(name)) {
|
||||
const age = Number(properties.age ?? '0')
|
||||
return ((age * 32) << 16) | ((255 - age * 8) << 8) | (age * 4)
|
||||
}
|
||||
return FIXED_TINTS[name] ?? NO_TINT
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { NO_LABEL, type MapTile } from '../bridge/types'
|
||||
import { heightColor } from '../map/heightColors'
|
||||
import type { TerrainSurface } from './terrainMesh'
|
||||
|
||||
export type MapTerrainColoring = 'biomes' | 'regions' | 'height'
|
||||
|
||||
/** A square of map tiles with heights, row by row from the north west. */
|
||||
export interface MapTerrainArea {
|
||||
tiles: MapTile[][]
|
||||
/** The world spot of the first tile's first pixel. */
|
||||
originX: number
|
||||
originZ: number
|
||||
}
|
||||
|
||||
const UNLABELLED_COLOR = 0x5a5f6b
|
||||
|
||||
/** The area's tiles as one surface, without the ring each tile carries for its neighbours; the sea fills up to fluid height. */
|
||||
export class MapTerrain implements TerrainSurface {
|
||||
readonly columns: number
|
||||
readonly rows: number
|
||||
private readonly size: number
|
||||
private readonly blocksPerPixel: number
|
||||
|
||||
constructor(
|
||||
private readonly area: MapTerrainArea,
|
||||
private readonly coloring: MapTerrainColoring,
|
||||
private readonly fluidHeight: number
|
||||
) {
|
||||
const first = area.tiles[0][0]
|
||||
this.size = first.size
|
||||
this.blocksPerPixel = first.blocksPerPixel
|
||||
this.columns = area.tiles[0].length * this.size
|
||||
this.rows = area.tiles.length * this.size
|
||||
}
|
||||
|
||||
worldX(column: number): number {
|
||||
return this.area.originX + column * this.blocksPerPixel
|
||||
}
|
||||
|
||||
worldZ(row: number): number {
|
||||
return this.area.originZ + row * this.blocksPerPixel
|
||||
}
|
||||
|
||||
groundAt(column: number, row: number): number {
|
||||
const { tile, cell } = this.cellAt(column, row)
|
||||
return tile.heights![cell]
|
||||
}
|
||||
|
||||
waterAt(column: number, row: number): number | null {
|
||||
return this.groundAt(column, row) < this.fluidHeight ? this.fluidHeight : null
|
||||
}
|
||||
|
||||
colorAt(column: number, row: number): number {
|
||||
if (this.coloring === 'height') {
|
||||
return heightColor(this.groundAt(column, row), this.fluidHeight)
|
||||
}
|
||||
const { tile, cell } = this.cellAt(column, row)
|
||||
const index = this.coloring === 'regions' ? tile.regions[cell] : tile.subjects[cell]
|
||||
return index === NO_LABEL ? UNLABELLED_COLOR : tile.labels[index].color
|
||||
}
|
||||
|
||||
private cellAt(column: number, row: number): { tile: MapTile; cell: number } {
|
||||
const tile = this.area.tiles[Math.floor(row / this.size)][Math.floor(column / this.size)]
|
||||
const gridSize = this.size + 2
|
||||
return { tile, cell: ((row % this.size) + 1) * gridSize + (column % this.size) + 1 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import type { SavedTile } from '../bridge/types'
|
||||
import { heightColor } from '../map/heightColors'
|
||||
import type { TerrainSurface } from './terrainMesh'
|
||||
|
||||
export type SavedTerrainColoring = 'biomes' | 'blocks' | 'height'
|
||||
|
||||
/** A square of saved tiles, row by row from the north west. */
|
||||
export interface SavedTerrainArea {
|
||||
tiles: SavedTile[][]
|
||||
/** The world spot of the first tile's first pixel. */
|
||||
originX: number
|
||||
originZ: number
|
||||
}
|
||||
|
||||
// A world without water is measured from where vanilla's sea would be.
|
||||
const VANILLA_SEA_LEVEL = 63
|
||||
const UNKNOWN_BLOCK_COLOR = 0x7f7f7f
|
||||
|
||||
/**
|
||||
* The saved columns as one surface. Heights are the tops of the blocks, one above their Y, so ground and water sit
|
||||
* where a player stands on them.
|
||||
*/
|
||||
export class SavedTerrain implements TerrainSurface {
|
||||
readonly columns: number
|
||||
readonly rows: number
|
||||
private readonly size: number
|
||||
private readonly blocksPerPixel: number
|
||||
|
||||
constructor(
|
||||
private readonly area: SavedTerrainArea,
|
||||
private readonly coloring: SavedTerrainColoring,
|
||||
private readonly seaLevel: number | null,
|
||||
private readonly blockColors: Map<string, number>
|
||||
) {
|
||||
const first = area.tiles[0][0]
|
||||
this.size = first.size
|
||||
this.blocksPerPixel = first.blocksPerPixel
|
||||
this.columns = area.tiles[0].length * this.size
|
||||
this.rows = area.tiles.length * this.size
|
||||
}
|
||||
|
||||
worldX(column: number): number {
|
||||
return this.area.originX + column * this.blocksPerPixel
|
||||
}
|
||||
|
||||
worldZ(row: number): number {
|
||||
return this.area.originZ + row * this.blocksPerPixel
|
||||
}
|
||||
|
||||
groundAt(column: number, row: number): number | null {
|
||||
const { tile, pixel } = this.pixelAt(column, row)
|
||||
const ground = tile.groundY[pixel]
|
||||
return ground === tile.noGround ? null : ground + 1
|
||||
}
|
||||
|
||||
waterAt(column: number, row: number): number | null {
|
||||
const { tile, pixel } = this.pixelAt(column, row)
|
||||
const water = tile.waterSurfaceY[pixel]
|
||||
return water === tile.noWater ? null : water + 1
|
||||
}
|
||||
|
||||
colorAt(column: number, row: number): number {
|
||||
const { tile, pixel } = this.pixelAt(column, row)
|
||||
switch (this.coloring) {
|
||||
case 'height':
|
||||
return heightColor(tile.groundY[pixel], this.seaLevel ?? VANILLA_SEA_LEVEL)
|
||||
case 'blocks':
|
||||
return this.blockColors.get(tile.blockNames[tile.blocks[pixel]]) ?? UNKNOWN_BLOCK_COLOR
|
||||
case 'biomes':
|
||||
return tile.biomeLabels[tile.biomes[pixel]].color
|
||||
}
|
||||
}
|
||||
|
||||
private pixelAt(column: number, row: number): { tile: SavedTile; pixel: number } {
|
||||
const tile = this.area.tiles[Math.floor(row / this.size)][Math.floor(column / this.size)]
|
||||
return { tile, pixel: (row % this.size) * this.size + (column % this.size) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/** A block scene as the bridge encodes it (Iris SceneEncoding). */
|
||||
export interface BlockScene {
|
||||
/** The block states the scene uses, once each. */
|
||||
palette: string[]
|
||||
/** Four numbers per block: x, y, z from the scene's anchor, then the index of its state in the palette. */
|
||||
blocks: Int32Array
|
||||
/** The lowest corner from the anchor, inclusive; {@code max} the highest, exclusive. */
|
||||
min: [number, number, number]
|
||||
max: [number, number, number]
|
||||
}
|
||||
|
||||
interface Header {
|
||||
palette: string[]
|
||||
blockCount: number
|
||||
min: [number, number, number]
|
||||
max: [number, number, number]
|
||||
}
|
||||
|
||||
export const INTS_PER_BLOCK = 4
|
||||
const ALIGNMENT_BYTES = 4
|
||||
|
||||
export function decodeScene(buffer: ArrayBuffer): BlockScene {
|
||||
const headerLength = new DataView(buffer).getUint32(0, true)
|
||||
const header = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 4, headerLength))) as Header
|
||||
const blocksAt = Math.ceil((4 + headerLength) / ALIGNMENT_BYTES) * ALIGNMENT_BYTES
|
||||
return {
|
||||
palette: header.palette,
|
||||
blocks: new Int32Array(buffer, blocksAt, header.blockCount * INTS_PER_BLOCK),
|
||||
min: header.min,
|
||||
max: header.max
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { Box3, BufferAttribute, BufferGeometry, Mesh, MeshBasicMaterial } from 'three'
|
||||
import type { ViewportContent } from '../studio/SceneViewport'
|
||||
import { cubeModel, parseState, type BlockModels, type BlockModel, type Direction, type Quad } from './blockModels'
|
||||
import { blockTint } from './blockTints'
|
||||
import { INTS_PER_BLOCK, type BlockScene } from './sceneDecoding'
|
||||
import { TextureAtlas, type ImageSource } from './textureAtlas'
|
||||
|
||||
export interface SceneMesh {
|
||||
content: ViewportContent
|
||||
/** Block states the client has no blockstate file for, drawn as magenta and black cubes. */
|
||||
unknownStates: string[]
|
||||
/** Frees the mesh's geometry, material and atlas. */
|
||||
dispose(): void
|
||||
}
|
||||
|
||||
const CUTOUT_ALPHA = 0.1
|
||||
|
||||
/** The light Minecraft gives each side of a block without shadows: the top brightest, the bottom darkest. */
|
||||
const FACE_LIGHT: Record<Direction, number> = { up: 1, down: 0.5, north: 0.8, south: 0.8, west: 0.6, east: 0.6 }
|
||||
const MISSING_TEXTURE = 'iris:missing'
|
||||
const NEIGHBOUR_OFFSETS: Record<Direction, [number, number, number]> = {
|
||||
down: [0, -1, 0],
|
||||
up: [0, 1, 0],
|
||||
north: [0, 0, -1],
|
||||
south: [0, 0, 1],
|
||||
west: [-1, 0, 0],
|
||||
east: [1, 0, 0]
|
||||
}
|
||||
const CORNERS_PER_QUAD = 4
|
||||
const INDICES_PER_QUAD = 6
|
||||
|
||||
interface PaletteEntry {
|
||||
model: BlockModel
|
||||
name: string
|
||||
properties: Record<string, string>
|
||||
/** Hides the faces of its neighbours that touch it. */
|
||||
solid: boolean
|
||||
}
|
||||
|
||||
/** One geometry for the whole scene, its faces against solid neighbours left out, textured from one atlas. */
|
||||
export async function buildSceneMesh(scene: BlockScene, models: BlockModels, images: ImageSource): Promise<SceneMesh> {
|
||||
const resolved = await Promise.all(scene.palette.map((state) => models.model(state)))
|
||||
const unknownStates = scene.palette.filter((_, index) => resolved[index] === null)
|
||||
const drawn = resolved.map((model) => drawnModel(model))
|
||||
const atlas = await TextureAtlas.of(
|
||||
drawn.flatMap((model) => model.quads.map((quad) => quad.texture)),
|
||||
images
|
||||
)
|
||||
const palette = drawn.map((model, index): PaletteEntry => {
|
||||
const state = parseState(scene.palette[index])
|
||||
const solid = model.fullCube && model.quads.every((quad) => atlas.cell(quad.texture).solid)
|
||||
return { model, name: state.name, properties: state.properties, solid }
|
||||
})
|
||||
const geometry = geometryOf(scene, palette, atlas)
|
||||
const material = new MeshBasicMaterial({ map: atlas.texture, vertexColors: true, alphaTest: CUTOUT_ALPHA })
|
||||
const bounds = new Box3().setFromBufferAttribute(geometry.getAttribute('position') as BufferAttribute)
|
||||
return {
|
||||
content: { object: new Mesh(geometry, material), bounds },
|
||||
unknownStates,
|
||||
dispose: () => {
|
||||
geometry.dispose()
|
||||
material.dispose()
|
||||
atlas.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The client draws chests, signs, water and the like without a block model; their break texture stands in for them.
|
||||
function drawnModel(model: BlockModel | null): BlockModel {
|
||||
if (model === null) {
|
||||
return cubeModel(MISSING_TEXTURE)
|
||||
}
|
||||
if (model.quads.length === 0) {
|
||||
return cubeModel(model.particle ?? MISSING_TEXTURE)
|
||||
}
|
||||
return model
|
||||
}
|
||||
|
||||
function geometryOf(scene: BlockScene, palette: PaletteEntry[], atlas: TextureAtlas): BufferGeometry {
|
||||
const solids = new SolidBlocks(scene, palette)
|
||||
const visible: { quad: Quad; entry: PaletteEntry; x: number; y: number; z: number }[] = []
|
||||
const blocks = scene.blocks
|
||||
for (let offset = 0; offset < blocks.length; offset += INTS_PER_BLOCK) {
|
||||
const [x, y, z, paletteIndex] = [blocks[offset], blocks[offset + 1], blocks[offset + 2], blocks[offset + 3]]
|
||||
const entry = palette[paletteIndex]
|
||||
for (const quad of entry.model.quads) {
|
||||
if (quad.cullFace !== null && solids.besides(x, y, z, quad.cullFace)) {
|
||||
continue
|
||||
}
|
||||
visible.push({ quad, entry, x, y, z })
|
||||
}
|
||||
}
|
||||
const positions = new Float32Array(visible.length * CORNERS_PER_QUAD * 3)
|
||||
const uvs = new Float32Array(visible.length * CORNERS_PER_QUAD * 2)
|
||||
const colors = new Float32Array(visible.length * CORNERS_PER_QUAD * 3)
|
||||
const indices = new Uint32Array(visible.length * INDICES_PER_QUAD)
|
||||
visible.forEach(({ quad, entry, x, y, z }, quadIndex) => {
|
||||
const cell = atlas.cell(quad.texture)
|
||||
const light = quad.shade ? FACE_LIGHT[quad.facing] : 1
|
||||
const tint = blockTint(entry.name, entry.properties, quad.tintIndex)
|
||||
const [red, green, blue] = [((tint >> 16) & 0xff) / 255, ((tint >> 8) & 0xff) / 255, (tint & 0xff) / 255]
|
||||
for (let corner = 0; corner < CORNERS_PER_QUAD; corner++) {
|
||||
const vertex = quadIndex * CORNERS_PER_QUAD + corner
|
||||
const [cornerX, cornerY, cornerZ] = quad.corners[corner]
|
||||
positions.set([x + cornerX, y + cornerY, z + cornerZ], vertex * 3)
|
||||
uvs.set([cell.u + quad.uvs[corner][0] * cell.width, cell.v + quad.uvs[corner][1] * cell.height], vertex * 2)
|
||||
colors.set([red * light, green * light, blue * light], vertex * 3)
|
||||
}
|
||||
const first = quadIndex * CORNERS_PER_QUAD
|
||||
indices.set([first, first + 1, first + 2, first, first + 2, first + 3], quadIndex * INDICES_PER_QUAD)
|
||||
})
|
||||
const geometry = new BufferGeometry()
|
||||
geometry.setAttribute('position', new BufferAttribute(positions, 3))
|
||||
geometry.setAttribute('uv', new BufferAttribute(uvs, 2))
|
||||
geometry.setAttribute('color', new BufferAttribute(colors, 3))
|
||||
geometry.setIndex(new BufferAttribute(indices, 1))
|
||||
geometry.computeBoundingSphere()
|
||||
return geometry
|
||||
}
|
||||
|
||||
/** Which spots of the scene hold a solid block, in a grid over its bounds. */
|
||||
class SolidBlocks {
|
||||
private readonly solid: Uint8Array
|
||||
private readonly sizeX: number
|
||||
private readonly sizeY: number
|
||||
private readonly sizeZ: number
|
||||
|
||||
constructor(private readonly scene: BlockScene, palette: PaletteEntry[]) {
|
||||
;[this.sizeX, this.sizeY, this.sizeZ] = [0, 1, 2].map((axis) => scene.max[axis] - scene.min[axis])
|
||||
this.solid = new Uint8Array(this.sizeX * this.sizeY * this.sizeZ)
|
||||
const blocks = scene.blocks
|
||||
for (let offset = 0; offset < blocks.length; offset += INTS_PER_BLOCK) {
|
||||
if (palette[blocks[offset + 3]].solid) {
|
||||
this.solid[this.indexOf(blocks[offset], blocks[offset + 1], blocks[offset + 2])] = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
besides(x: number, y: number, z: number, side: Direction): boolean {
|
||||
const [dx, dy, dz] = NEIGHBOUR_OFFSETS[side]
|
||||
const index = this.indexOf(x + dx, y + dy, z + dz)
|
||||
return index >= 0 && this.solid[index] === 1
|
||||
}
|
||||
|
||||
private indexOf(x: number, y: number, z: number): number {
|
||||
const [localX, localY, localZ] = [x - this.scene.min[0], y - this.scene.min[1], z - this.scene.min[2]]
|
||||
if (localX < 0 || localY < 0 || localZ < 0 || localX >= this.sizeX || localY >= this.sizeY || localZ >= this.sizeZ) {
|
||||
return -1
|
||||
}
|
||||
return (localX * this.sizeY + localY) * this.sizeZ + localZ
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { Mesh } from 'three'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { buildTerrainMesh, type TerrainSurface } from './terrainMesh'
|
||||
|
||||
const GROUND = 10
|
||||
const WATER = 12
|
||||
const BLOCKS_PER_VERTEX = 2
|
||||
|
||||
// Three by three vertices: nothing known at the north west corner, a pond at the middle vertex.
|
||||
const surface: TerrainSurface = {
|
||||
columns: 3,
|
||||
rows: 3,
|
||||
worldX: (column) => column * BLOCKS_PER_VERTEX,
|
||||
worldZ: (row) => row * BLOCKS_PER_VERTEX,
|
||||
groundAt: (column, row) => (column === 0 && row === 0 ? null : GROUND),
|
||||
waterAt: (column, row) => (column === 1 && row === 1 ? WATER : null),
|
||||
colorAt: () => 0x808080
|
||||
}
|
||||
|
||||
function meshes(): Mesh[] {
|
||||
return buildTerrainMesh(surface).content.object.children as Mesh[]
|
||||
}
|
||||
|
||||
function triangles(mesh: Mesh): number {
|
||||
return mesh.geometry.getIndex()!.count / 3
|
||||
}
|
||||
|
||||
describe('terrain mesh', () => {
|
||||
it('leaves out the squares that touch a hole', () => {
|
||||
const [ground] = meshes()
|
||||
expect(triangles(ground)).toBe(3 * 2)
|
||||
})
|
||||
|
||||
it('frames the known surface from below its walls to its highest water, not the unused vertices', () => {
|
||||
const bounds = buildTerrainMesh(surface).content.bounds
|
||||
expect(bounds.min.toArray()).toEqual([0, GROUND - 8, 0])
|
||||
expect(bounds.max.toArray()).toEqual([2 * BLOCKS_PER_VERTEX, WATER, 2 * BLOCKS_PER_VERTEX])
|
||||
})
|
||||
|
||||
it('carries the water out to the shore around the vertex that holds it, except into the hole', () => {
|
||||
const [, , water] = meshes()
|
||||
expect(triangles(water)).toBe(3 * 2)
|
||||
})
|
||||
|
||||
it('stands walls only between rim vertices that both have ground', () => {
|
||||
const [, landWalls] = meshes()
|
||||
// The rim has eight segments; the two at the hole's corner fall away.
|
||||
expect(triangles(landWalls)).toBe(6 * 2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,254 @@
|
||||
import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Group, Mesh, MeshBasicMaterial, Vector3 } from 'three'
|
||||
import type { ViewportContent } from '../studio/SceneViewport'
|
||||
|
||||
/**
|
||||
* A height field to draw, one vertex per map pixel, row by row from the north west: the ground, the water over it,
|
||||
* and the ground's colour. Where nothing is known, the ground is null and the field has a hole.
|
||||
*/
|
||||
export interface TerrainSurface {
|
||||
readonly columns: number
|
||||
readonly rows: number
|
||||
worldX(column: number): number
|
||||
worldZ(row: number): number
|
||||
groundAt(column: number, row: number): number | null
|
||||
/** The water's surface over the vertex, or null where it is dry. */
|
||||
waterAt(column: number, row: number): number | null
|
||||
colorAt(column: number, row: number): number
|
||||
}
|
||||
|
||||
export interface TerrainMesh {
|
||||
content: ViewportContent
|
||||
dispose(): void
|
||||
}
|
||||
|
||||
const WATER_COLOR = 0x3f76e4
|
||||
const WATER_OPACITY = 0.55
|
||||
// Light from high in the south west, so slopes read as relief; the darkest side keeps some light.
|
||||
const LIGHT = new Vector3(-0.6, 1, 0.4).normalize()
|
||||
const AMBIENT_LIGHT = 0.5
|
||||
const WALL_DEPTH_BLOCKS = 8
|
||||
const WALL_TOP_LIGHT = 0.55
|
||||
const WALL_BASE_LIGHT = 0.25
|
||||
const NO_VALUE = Number.NaN
|
||||
|
||||
/**
|
||||
* The surface as ground lit by its slopes, see-through water over it, and walls round the rim down to below the lowest
|
||||
* ground, so the square reads as a solid block cut from the world.
|
||||
*/
|
||||
export function buildTerrainMesh(surface: TerrainSurface): TerrainMesh {
|
||||
const field = HeightField.of(surface)
|
||||
const base = field.lowest() - WALL_DEPTH_BLOCKS
|
||||
const ground = groundGeometry(field)
|
||||
const water = waterGeometry(field)
|
||||
const landWalls = rimWall(field, (vertex) => field.ground[vertex], () => base)
|
||||
const seaWalls = rimWall(field, (vertex) => field.water[vertex], (vertex) => Math.min(field.ground[vertex], field.water[vertex]))
|
||||
const groundMaterial = new MeshBasicMaterial({ vertexColors: true, side: DoubleSide })
|
||||
const waterMaterial = new MeshBasicMaterial({ color: WATER_COLOR, transparent: true, opacity: WATER_OPACITY, depthWrite: false, side: DoubleSide })
|
||||
const group = new Group()
|
||||
group.add(new Mesh(ground, groundMaterial), new Mesh(landWalls, groundMaterial), new Mesh(water, waterMaterial), new Mesh(seaWalls, waterMaterial))
|
||||
const geometries = [ground, water, landWalls, seaWalls]
|
||||
return {
|
||||
content: { object: group, bounds: field.bounds(base) },
|
||||
dispose: () => {
|
||||
geometries.forEach((geometry) => geometry.dispose())
|
||||
groundMaterial.dispose()
|
||||
waterMaterial.dispose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function groundGeometry(field: HeightField): BufferGeometry {
|
||||
const { surface, ground } = field
|
||||
const positions = new Float32Array(ground.length * 3)
|
||||
const colors = new Float32Array(ground.length * 3)
|
||||
for (let vertex = 0; vertex < ground.length; vertex++) {
|
||||
if (Number.isNaN(ground[vertex])) {
|
||||
continue
|
||||
}
|
||||
const [column, row] = field.columnAndRow(vertex)
|
||||
positions.set([surface.worldX(column), ground[vertex], surface.worldZ(row)], vertex * 3)
|
||||
const light = AMBIENT_LIGHT + (1 - AMBIENT_LIGHT) * Math.max(0, field.normal(column, row).dot(LIGHT))
|
||||
colors.set(rgb(surface.colorAt(column, row), light), vertex * 3)
|
||||
}
|
||||
return indexedGeometry(positions, colors, field.quadsWhere((corners) => corners.every((vertex) => !Number.isNaN(ground[vertex]))))
|
||||
}
|
||||
|
||||
// Only quads holding water of their own; the vertices next to water carry its level, so it meets the shore.
|
||||
function waterGeometry(field: HeightField): BufferGeometry {
|
||||
const { surface, water, ownWater } = field
|
||||
const positions = new Float32Array(water.length * 3)
|
||||
for (let vertex = 0; vertex < water.length; vertex++) {
|
||||
if (!Number.isNaN(water[vertex])) {
|
||||
const [column, row] = field.columnAndRow(vertex)
|
||||
positions.set([surface.worldX(column), water[vertex], surface.worldZ(row)], vertex * 3)
|
||||
}
|
||||
}
|
||||
const quads = field.quadsWhere((corners) => corners.every((vertex) => !Number.isNaN(water[vertex])) && corners.some((vertex) => ownWater[vertex]))
|
||||
return indexedGeometry(positions, null, quads)
|
||||
}
|
||||
|
||||
/** A wall round the field's rim from {@code topOf} down to {@code bottomOf} each rim vertex, darkening downwards. */
|
||||
function rimWall(field: HeightField, topOf: (vertex: number) => number, bottomOf: (vertex: number) => number): BufferGeometry {
|
||||
const rim = field.rimVertices()
|
||||
const positions = new Float32Array(rim.length * 2 * 3)
|
||||
const colors = new Float32Array(rim.length * 2 * 3)
|
||||
// A rim vertex without a top or a bottom, such as dry land for the water's wall, holds no wall and keeps the origin.
|
||||
const standing = rim.map((vertex) => !Number.isNaN(topOf(vertex)) && !Number.isNaN(bottomOf(vertex)))
|
||||
rim.forEach((vertex, index) => {
|
||||
if (!standing[index]) {
|
||||
return
|
||||
}
|
||||
const [column, row] = field.columnAndRow(vertex)
|
||||
const [x, z] = [field.surface.worldX(column), field.surface.worldZ(row)]
|
||||
positions.set([x, topOf(vertex), z, x, bottomOf(vertex), z], index * 6)
|
||||
const color = field.surface.colorAt(column, row)
|
||||
colors.set([...rgb(color, WALL_TOP_LIGHT), ...rgb(color, WALL_BASE_LIGHT)], index * 6)
|
||||
})
|
||||
const indices: number[] = []
|
||||
for (let index = 0; index < rim.length; index++) {
|
||||
const next = (index + 1) % rim.length
|
||||
if (standing[index] && standing[next]) {
|
||||
const [upper, lower, nextUpper, nextLower] = [index * 2, index * 2 + 1, next * 2, next * 2 + 1]
|
||||
indices.push(upper, lower, nextUpper, nextUpper, lower, nextLower)
|
||||
}
|
||||
}
|
||||
return indexedGeometry(positions, colors, indices)
|
||||
}
|
||||
|
||||
function indexedGeometry(positions: Float32Array, colors: Float32Array | null, indices: number[] | Uint32Array): BufferGeometry {
|
||||
const geometry = new BufferGeometry()
|
||||
geometry.setAttribute('position', new BufferAttribute(positions, 3))
|
||||
if (colors !== null) {
|
||||
geometry.setAttribute('color', new BufferAttribute(colors, 3))
|
||||
}
|
||||
geometry.setIndex(new BufferAttribute(indices instanceof Uint32Array ? indices : Uint32Array.from(indices), 1))
|
||||
return geometry
|
||||
}
|
||||
|
||||
function rgb(color: number, light: number): [number, number, number] {
|
||||
return [(((color >> 16) & 0xff) / 255) * light, (((color >> 8) & 0xff) / 255) * light, ((color & 0xff) / 255) * light]
|
||||
}
|
||||
|
||||
/** The surface's ground and water read once per vertex, with no value as NaN, and how its vertices stand together. */
|
||||
class HeightField {
|
||||
readonly ground: Float32Array
|
||||
readonly water: Float32Array
|
||||
readonly ownWater: Uint8Array
|
||||
|
||||
private constructor(readonly surface: TerrainSurface) {
|
||||
const count = surface.columns * surface.rows
|
||||
this.ground = new Float32Array(count)
|
||||
this.water = new Float32Array(count)
|
||||
this.ownWater = new Uint8Array(count)
|
||||
for (let vertex = 0; vertex < count; vertex++) {
|
||||
const [column, row] = this.columnAndRow(vertex)
|
||||
const ground = surface.groundAt(column, row)
|
||||
const water = ground === null ? null : surface.waterAt(column, row)
|
||||
this.ground[vertex] = ground ?? NO_VALUE
|
||||
this.water[vertex] = water ?? NO_VALUE
|
||||
this.ownWater[vertex] = water === null ? 0 : 1
|
||||
}
|
||||
this.extendWaterToShores()
|
||||
}
|
||||
|
||||
static of(surface: TerrainSurface): HeightField {
|
||||
return new HeightField(surface)
|
||||
}
|
||||
|
||||
columnAndRow(vertex: number): [number, number] {
|
||||
return [vertex % this.surface.columns, Math.floor(vertex / this.surface.columns)]
|
||||
}
|
||||
|
||||
lowest(): number {
|
||||
let lowest = Infinity
|
||||
for (let vertex = 0; vertex < this.ground.length; vertex++) {
|
||||
if (!Number.isNaN(this.ground[vertex])) {
|
||||
lowest = Math.min(lowest, this.ground[vertex], Number.isNaN(this.water[vertex]) ? Infinity : this.water[vertex])
|
||||
}
|
||||
}
|
||||
return Number.isFinite(lowest) ? lowest : 0
|
||||
}
|
||||
|
||||
/** The box round the field from {@code base} to its highest ground or water; vertices left out of it do not count. */
|
||||
bounds(base: number): Box3 {
|
||||
let highest = base
|
||||
for (let vertex = 0; vertex < this.ground.length; vertex++) {
|
||||
for (const height of [this.ground[vertex], this.water[vertex]]) {
|
||||
if (!Number.isNaN(height)) {
|
||||
highest = Math.max(highest, height)
|
||||
}
|
||||
}
|
||||
}
|
||||
const { columns, rows } = this.surface
|
||||
return new Box3(
|
||||
new Vector3(this.surface.worldX(0), base, this.surface.worldZ(0)),
|
||||
new Vector3(this.surface.worldX(columns - 1), highest, this.surface.worldZ(rows - 1))
|
||||
)
|
||||
}
|
||||
|
||||
/** The two triangles of each grid square whose four corners pass {@code wanted}. */
|
||||
quadsWhere(wanted: (corners: [number, number, number, number]) => boolean): Uint32Array {
|
||||
const { columns, rows } = this.surface
|
||||
const indices: number[] = []
|
||||
for (let row = 0; row < rows - 1; row++) {
|
||||
for (let column = 0; column < columns - 1; column++) {
|
||||
const northWest = row * columns + column
|
||||
const southWest = northWest + columns
|
||||
if (wanted([northWest, northWest + 1, southWest, southWest + 1])) {
|
||||
indices.push(northWest, southWest, northWest + 1, northWest + 1, southWest, southWest + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
return Uint32Array.from(indices)
|
||||
}
|
||||
|
||||
normal(column: number, row: number): Vector3 {
|
||||
const { columns, rows } = this.surface
|
||||
const here = this.ground[row * columns + column]
|
||||
const at = (atColumn: number, atRow: number): number => {
|
||||
const height = this.ground[Math.min(rows - 1, Math.max(0, atRow)) * columns + Math.min(columns - 1, Math.max(0, atColumn))]
|
||||
return Number.isNaN(height) ? here : height
|
||||
}
|
||||
const spacing = Math.abs(this.surface.worldX(Math.min(columns - 1, 1)) - this.surface.worldX(0)) || 1
|
||||
return new Vector3(at(column - 1, row) - at(column + 1, row), 2 * spacing, at(column, row - 1) - at(column, row + 1)).normalize()
|
||||
}
|
||||
|
||||
/** The vertices on the edge of the field, once each, going round clockwise from the north west corner. */
|
||||
rimVertices(): number[] {
|
||||
const { columns, rows } = this.surface
|
||||
const rim: number[] = []
|
||||
for (let column = 0; column < columns - 1; column++) rim.push(column)
|
||||
for (let row = 0; row < rows - 1; row++) rim.push(row * columns + columns - 1)
|
||||
for (let column = columns - 1; column > 0; column--) rim.push((rows - 1) * columns + column)
|
||||
for (let row = rows - 1; row > 0; row--) rim.push(row * columns)
|
||||
return rim
|
||||
}
|
||||
|
||||
// A dry vertex next to water takes the highest water beside it, so the water's edge runs under the shore.
|
||||
private extendWaterToShores(): void {
|
||||
const { columns, rows } = this.surface
|
||||
const own = Float32Array.from(this.water)
|
||||
for (let row = 0; row < rows; row++) {
|
||||
for (let column = 0; column < columns; column++) {
|
||||
const vertex = row * columns + column
|
||||
if (this.ownWater[vertex] === 1 || Number.isNaN(this.ground[vertex])) {
|
||||
continue
|
||||
}
|
||||
let highest = NO_VALUE
|
||||
for (let offsetRow = -1; offsetRow <= 1; offsetRow++) {
|
||||
for (let offsetColumn = -1; offsetColumn <= 1; offsetColumn++) {
|
||||
const [nearColumn, nearRow] = [column + offsetColumn, row + offsetRow]
|
||||
if (nearColumn < 0 || nearRow < 0 || nearColumn >= columns || nearRow >= rows) {
|
||||
continue
|
||||
}
|
||||
const near = own[nearRow * columns + nearColumn]
|
||||
if (!Number.isNaN(near) && (Number.isNaN(highest) || near > highest)) {
|
||||
highest = near
|
||||
}
|
||||
}
|
||||
}
|
||||
this.water[vertex] = highest
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { CanvasTexture, NearestFilter, SRGBColorSpace } from 'three'
|
||||
|
||||
/** Where block textures come from: the bridge's copy of the client's assets. */
|
||||
export interface ImageSource {
|
||||
/** The PNG at {@code path} below the assets folder, or null when there is none. */
|
||||
image(path: string): Promise<ImageBitmap | null>
|
||||
}
|
||||
|
||||
/** Where one texture lies in the atlas, as a rectangle of the atlas from 0 to 1. */
|
||||
export interface AtlasCell {
|
||||
u: number
|
||||
v: number
|
||||
width: number
|
||||
height: number
|
||||
/** Whether every pixel is fully opaque, so a block made of it hides its neighbours' faces. */
|
||||
solid: boolean
|
||||
}
|
||||
|
||||
const CELL_PIXELS = 16
|
||||
const CELLS_PER_ROW = 32
|
||||
const OPAQUE_ALPHA = 255
|
||||
const MISSING_TEXTURE_COLORS = ['#f800f8', '#000000']
|
||||
|
||||
/**
|
||||
* The block textures of one scene in one image, each scaled to 16 pixels; an animated texture shows its first frame,
|
||||
* and a missing one Minecraft's magenta and black checks.
|
||||
*/
|
||||
export class TextureAtlas {
|
||||
readonly texture: CanvasTexture
|
||||
|
||||
private constructor(
|
||||
private readonly cells: Map<string, AtlasCell>,
|
||||
canvas: HTMLCanvasElement
|
||||
) {
|
||||
this.texture = new CanvasTexture(canvas)
|
||||
this.texture.magFilter = NearestFilter
|
||||
this.texture.minFilter = NearestFilter
|
||||
this.texture.generateMipmaps = false
|
||||
this.texture.flipY = false
|
||||
this.texture.colorSpace = SRGBColorSpace
|
||||
}
|
||||
|
||||
static async of(textureIds: string[], images: ImageSource): Promise<TextureAtlas> {
|
||||
const unique = [...new Set(textureIds)]
|
||||
const bitmaps = await Promise.all(unique.map((id) => images.image(texturePath(id)).catch(() => null)))
|
||||
const rows = Math.max(1, Math.ceil(unique.length / CELLS_PER_ROW))
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = CELLS_PER_ROW * CELL_PIXELS
|
||||
canvas.height = rows * CELL_PIXELS
|
||||
const drawing = canvas.getContext('2d', { willReadFrequently: true })!
|
||||
drawing.imageSmoothingEnabled = false
|
||||
const cells = new Map<string, AtlasCell>()
|
||||
unique.forEach((id, index) => {
|
||||
const left = (index % CELLS_PER_ROW) * CELL_PIXELS
|
||||
const top = Math.floor(index / CELLS_PER_ROW) * CELL_PIXELS
|
||||
const bitmap = bitmaps[index]
|
||||
if (bitmap === null) {
|
||||
drawMissing(drawing, left, top)
|
||||
} else {
|
||||
drawing.drawImage(bitmap, 0, 0, bitmap.width, Math.min(bitmap.width, bitmap.height), left, top, CELL_PIXELS, CELL_PIXELS)
|
||||
}
|
||||
cells.set(id, {
|
||||
u: left / canvas.width,
|
||||
v: top / canvas.height,
|
||||
width: CELL_PIXELS / canvas.width,
|
||||
height: CELL_PIXELS / canvas.height,
|
||||
solid: isSolid(drawing.getImageData(left, top, CELL_PIXELS, CELL_PIXELS).data)
|
||||
})
|
||||
})
|
||||
return new TextureAtlas(cells, canvas)
|
||||
}
|
||||
|
||||
cell(textureId: string): AtlasCell {
|
||||
return this.cells.get(textureId)!
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.texture.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
/** {@code minecraft:block/stone} lies at {@code minecraft/textures/block/stone.png}. */
|
||||
export function texturePath(textureId: string): string {
|
||||
const colon = textureId.indexOf(':')
|
||||
return `${textureId.slice(0, colon)}/textures/${textureId.slice(colon + 1)}.png`
|
||||
}
|
||||
|
||||
function drawMissing(drawing: CanvasRenderingContext2D, left: number, top: number): void {
|
||||
const half = CELL_PIXELS / 2
|
||||
for (let quarter = 0; quarter < 4; quarter++) {
|
||||
const column = quarter % 2
|
||||
const row = Math.floor(quarter / 2)
|
||||
drawing.fillStyle = MISSING_TEXTURE_COLORS[(column + row) % 2]
|
||||
drawing.fillRect(left + column * half, top + row * half, half, half)
|
||||
}
|
||||
}
|
||||
|
||||
function isSolid(pixels: Uint8ClampedArray): boolean {
|
||||
for (let alpha = 3; alpha < pixels.length; alpha += 4) {
|
||||
if (pixels[alpha] < OPAQUE_ALPHA) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Globe2, Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import type { BridgeConnection } from '../../../shared/bridge'
|
||||
|
||||
const BRIDGE_POLL_MILLIS = 2000
|
||||
|
||||
interface ConnectScreenProps {
|
||||
connecting: boolean
|
||||
error: string | null
|
||||
onConnect(connection: BridgeConnection): void
|
||||
onLink(link: string): void
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the worlds servers on this machine opened to the studio, and takes a pasted link for any other. A single
|
||||
* world is opened right away, once.
|
||||
*/
|
||||
export function ConnectScreen({ connecting, error, onConnect, onLink }: ConnectScreenProps): React.JSX.Element {
|
||||
const [bridges, setBridges] = useState<BridgeConnection[]>([])
|
||||
const [link, setLink] = useState('')
|
||||
const openedOnItsOwn = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
const refresh = (): void => {
|
||||
void window.studio.listBridges().then((found) => {
|
||||
if (!active) {
|
||||
return
|
||||
}
|
||||
setBridges(found)
|
||||
if (found.length === 1 && !openedOnItsOwn.current) {
|
||||
openedOnItsOwn.current = true
|
||||
onConnect(found[0])
|
||||
}
|
||||
})
|
||||
}
|
||||
refresh()
|
||||
const timer = window.setInterval(refresh, BRIDGE_POLL_MILLIS)
|
||||
return () => {
|
||||
active = false
|
||||
window.clearInterval(timer)
|
||||
}
|
||||
}, [onConnect])
|
||||
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center bg-background">
|
||||
<div className="w-[440px] rounded-xl border border-overlay-border bg-card p-6 shadow-lg">
|
||||
<h1 className="text-[15px] font-semibold">Open a world</h1>
|
||||
<p className="mt-1 text-secondary-text">
|
||||
Run <code className="rounded bg-secondary px-1 font-mono text-[12px]">/iris studio map</code> in game or in the
|
||||
server console.
|
||||
</p>
|
||||
|
||||
<div className="mt-4 flex flex-col gap-1">
|
||||
{bridges.length === 0 ? (
|
||||
<div className="flex items-center gap-2 rounded-md px-3 py-2 text-muted-foreground">
|
||||
<Loader2 className="size-4 animate-spin" /> Waiting for a server on this machine
|
||||
</div>
|
||||
) : (
|
||||
bridges.map((bridge) => (
|
||||
<button
|
||||
key={bridge.port}
|
||||
disabled={connecting}
|
||||
onClick={() => onConnect(bridge)}
|
||||
className="flex items-center gap-3 rounded-md px-3 py-2 text-left hover:bg-accent disabled:opacity-60"
|
||||
>
|
||||
<Globe2 className="size-4 text-secondary-text" />
|
||||
<span className="flex-1 truncate font-medium">{bridge.world}</span>
|
||||
<span className="text-[11px] text-muted-foreground">port {bridge.port}</span>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<form
|
||||
className="mt-4 flex gap-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
onLink(link)
|
||||
}}
|
||||
>
|
||||
<Input value={link} onChange={(event) => setLink(event.target.value)} placeholder="iris-studio://…" className="h-8" />
|
||||
<Button type="submit" size="sm" disabled={connecting || link.trim() === ''}>
|
||||
{connecting ? <Loader2 className="animate-spin" /> : 'Connect'}
|
||||
</Button>
|
||||
</form>
|
||||
{error !== null && <p className="mt-2 text-[12px] text-destructive">{error}</p>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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()]
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { Kbd } from '@/components/ui/kbd'
|
||||
import type { ViewInfo } from '../bridge/types'
|
||||
import { MOUSE_HINTS, SHORTCUTS, VIEW_KEYS } from './shortcuts'
|
||||
|
||||
interface HelpDialogProps {
|
||||
open: boolean
|
||||
onOpenChange(open: boolean): void
|
||||
views: ViewInfo[]
|
||||
}
|
||||
|
||||
/** Every key and mouse gesture of the map. */
|
||||
export function HelpDialog({ open, onOpenChange, views }: HelpDialogProps): React.JSX.Element {
|
||||
const viewRows = views.filter((view) => VIEW_KEYS[view.id] !== undefined).map((view) => ({ key: VIEW_KEYS[view.id], label: view.label }))
|
||||
const groups = [
|
||||
{ title: 'Views', rows: [...viewRows, ...rowsOf('Views')] },
|
||||
{ title: 'Everywhere', rows: rowsOf('Everywhere') },
|
||||
{ title: 'Map', rows: rowsOf('Map') },
|
||||
{ title: 'Mouse', rows: MOUSE_HINTS.map((hint) => ({ key: hint.gesture, label: hint.label })) }
|
||||
]
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-[640px] bg-card">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-[15px]">Shortcuts</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="grid grid-cols-2 gap-x-8 gap-y-4">
|
||||
{groups.map((group) => (
|
||||
<section key={group.title}>
|
||||
<h3 className="mb-1.5 text-[11px] font-semibold text-muted-foreground">{group.title}</h3>
|
||||
<ul className="flex flex-col gap-1">
|
||||
{group.rows.map((row) => (
|
||||
<li key={row.label} className="flex items-center justify-between gap-3">
|
||||
<span className="text-secondary-text">{row.label}</span>
|
||||
<Kbd>{row.key}</Kbd>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function rowsOf(group: 'Views' | 'Everywhere' | 'Map'): { key: string; label: string }[] {
|
||||
return SHORTCUTS.filter((shortcut) => shortcut.group === group).map((shortcut) => ({ key: shortcut.keyText, label: shortcut.label }))
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { useLayoutEffect, useRef, useState } from 'react'
|
||||
import { Kbd } from '@/components/ui/kbd'
|
||||
import type { MapHover, MapLabel } from '../bridge/types'
|
||||
import { hexColor } from './colors'
|
||||
import type { CanvasPoint } from './MapCanvas'
|
||||
import { PickRows, replacedParent } from './PickRows'
|
||||
import { shortcutFor } from './shortcuts'
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
const CURSOR_GAP_PIXELS = 18
|
||||
const EDGE_MARGIN_PIXELS = 8
|
||||
|
||||
interface Row {
|
||||
label: string
|
||||
value: string
|
||||
mono?: boolean
|
||||
}
|
||||
|
||||
/** 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, previewing, detailed, minY }: HoverCardProps): React.JSX.Element {
|
||||
const card = useRef<HTMLDivElement>(null)
|
||||
const [position, setPosition] = useState({ left: point.x + CURSOR_GAP_PIXELS, top: point.y + CURSOR_GAP_PIXELS })
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element = card.current
|
||||
const parent = element?.parentElement
|
||||
if (!element || !parent) {
|
||||
return
|
||||
}
|
||||
const fitsRight = point.x + CURSOR_GAP_PIXELS + element.offsetWidth + EDGE_MARGIN_PIXELS <= parent.clientWidth
|
||||
const fitsBelow = point.y + CURSOR_GAP_PIXELS + element.offsetHeight + EDGE_MARGIN_PIXELS <= parent.clientHeight
|
||||
setPosition({
|
||||
left: fitsRight ? point.x + CURSOR_GAP_PIXELS : Math.max(EDGE_MARGIN_PIXELS, point.x - CURSOR_GAP_PIXELS - element.offsetWidth),
|
||||
top: fitsBelow ? point.y + CURSOR_GAP_PIXELS : Math.max(EDGE_MARGIN_PIXELS, point.y - CURSOR_GAP_PIXELS - element.offsetHeight)
|
||||
})
|
||||
}, [point, hover, detailed])
|
||||
|
||||
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 (
|
||||
<div
|
||||
ref={card}
|
||||
className="pointer-events-none absolute z-10 w-80 rounded-[10px] border border-overlay-border bg-popover px-3.5 py-3 text-popover-foreground shadow-xl backdrop-blur-sm"
|
||||
style={position}
|
||||
>
|
||||
<Header subject={subject} region={labelsRegions ? null : hover.region} />
|
||||
{parent !== null && <p className="mt-0.5 truncate text-[12px] text-secondary-text">child of {parent}</p>}
|
||||
<p className="mt-0.5 truncate text-[12px] text-secondary-text tabular-nums">{ground(hover, minY)}</p>
|
||||
<PickRows path={hover.pickPath} />
|
||||
{groups.map((group) => (
|
||||
<section key={group.title} className="mt-2.5">
|
||||
<h3 className="text-[11px] font-semibold text-muted-foreground">{group.title}</h3>
|
||||
<dl className="mt-1 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-[12px]">
|
||||
{group.rows.map((row) => (
|
||||
<div key={row.label} className="contents">
|
||||
<dt className="text-secondary-text">{row.label}</dt>
|
||||
<dd className={row.mono ? 'truncate font-mono text-[11.5px]' : 'truncate'}>{row.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
))}
|
||||
<div className="mt-2.5 flex flex-wrap gap-x-3 gap-y-1 text-[11px] text-muted-foreground">
|
||||
{!detailed && <Hint keyText="Shift" label="More" />}
|
||||
<Hint keyText={shortcutFor('highlight').keyText} label="Highlight" />
|
||||
<Hint keyText="Alt+Click" label="Open file" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Header({ subject, region }: { subject: MapLabel | null; region: MapLabel | null }): React.JSX.Element {
|
||||
return (
|
||||
<div className="flex items-baseline gap-2">
|
||||
{subject !== null && <span className="size-2.5 shrink-0 translate-y-[1px] rounded-[3px]" style={{ backgroundColor: hexColor(subject.color) }} />}
|
||||
<span className="min-w-0 flex-1 truncate text-[13.5px] font-semibold">{subject?.name ?? 'Nothing here'}</span>
|
||||
{region !== null && <span className="shrink-0 truncate text-[12px] text-secondary-text">{region.name}</span>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Hint({ keyText, label }: { keyText: string; label: string }): React.JSX.Element {
|
||||
return (
|
||||
<span className="flex items-center gap-1">
|
||||
<Kbd className="h-4 min-w-4 text-[10.5px]">{keyText}</Kbd>
|
||||
{label}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** Height as the world's Y, how far above or below the water, and how steep. */
|
||||
function ground(hover: MapHover, minY: number): string {
|
||||
const aboveWater = Math.round(hover.height - hover.fluidHeight)
|
||||
const signed = aboveWater > 0 ? `+${aboveWater}` : String(aboveWater)
|
||||
return `Y ${Math.round(hover.height + minY)} · ${signed} from water · ${Math.round(hover.slopeDegrees)}°`
|
||||
}
|
||||
|
||||
function detailGroups(hover: MapHover, viewId: string): { title: string; rows: Row[] }[] {
|
||||
const groups: { title: string; rows: Row[] }[] = []
|
||||
const terrain: Row[] = []
|
||||
if (viewId === 'caveBiomes' && hover.biome !== null) {
|
||||
terrain.push({ label: 'Surface biome', value: hover.biome.name })
|
||||
} else if (hover.caveBiome !== null && hover.caveBiome.key !== hover.biome?.key) {
|
||||
terrain.push({ label: 'Cave biome', value: hover.caveBiome.name })
|
||||
}
|
||||
if (hover.vanillaBiome !== null) {
|
||||
terrain.push({ label: 'Minecraft', value: hover.vanillaBiome.replace('minecraft:', '').replaceAll('_', ' ') })
|
||||
}
|
||||
if (terrain.length > 0) {
|
||||
groups.push({ title: 'Terrain', rows: terrain })
|
||||
}
|
||||
const blockX = Math.floor(hover.worldX)
|
||||
const blockZ = Math.floor(hover.worldZ)
|
||||
groups.push({
|
||||
title: 'Location',
|
||||
rows: [
|
||||
{ label: 'Block', value: `${blockX}, ${blockZ}` },
|
||||
{ label: 'Chunk', value: `${blockX >> 4}, ${blockZ >> 4}` },
|
||||
{ label: 'Region file', value: `r.${blockX >> 9}.${blockZ >> 9}.mca`, mono: true }
|
||||
]
|
||||
})
|
||||
const files: Row[] = []
|
||||
if (hover.biomeFile !== null) {
|
||||
files.push({ label: 'Biome', value: hover.biomeFile, mono: true })
|
||||
}
|
||||
if (hover.regionFile !== null) {
|
||||
files.push({ label: 'Region', value: hover.regionFile, mono: true })
|
||||
}
|
||||
if (files.length > 0) {
|
||||
groups.push({ title: 'Files', rows: files })
|
||||
}
|
||||
return groups
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { Share } from '../map/census'
|
||||
import type { Highlight } from '../map/tileStyle'
|
||||
import { hexColor } from './colors'
|
||||
|
||||
interface LegendProps {
|
||||
title: string
|
||||
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, className }: LegendProps): React.JSX.Element {
|
||||
const sharedNames = namesUsedMoreThanOnce(shares)
|
||||
return (
|
||||
<section className={cn('flex min-h-0 flex-col', className)}>
|
||||
<h2 className="px-4 pt-2.5 pb-1.5 text-[11px] font-semibold text-muted-foreground">{title}</h2>
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<ul className="px-1.5 pb-1">
|
||||
{shares.length === 0 && <li className="px-2.5 py-1 text-muted-foreground">Drawing the map…</li>}
|
||||
{shares.map((share) => {
|
||||
const selected = highlight !== null && highlight.kind === share.subject.kind && highlight.key === share.subject.key
|
||||
return (
|
||||
<li key={`${share.subject.kind}:${share.subject.key}`}>
|
||||
<button
|
||||
onClick={() => onSelect(share.subject)}
|
||||
title={share.subject.key}
|
||||
className={cn('flex h-[26px] w-full items-center gap-2 rounded-md px-2.5 text-left', selected ? 'bg-selection' : 'hover:bg-accent')}
|
||||
>
|
||||
<span className="size-3 shrink-0 rounded-[3px]" style={{ backgroundColor: hexColor(share.color) }} />
|
||||
<span className="flex min-w-0 flex-1 items-baseline gap-1.5">
|
||||
<span className={cn('truncate', sharedNames.has(share.subject.name) && 'max-w-[60%] shrink-0')}>{share.subject.name}</span>
|
||||
{sharedNames.has(share.subject.name) && (
|
||||
<span className="min-w-0 truncate text-[11.5px] text-secondary-text">{fileName(share.subject.key)}</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="w-[42px] shrink-0 text-right text-[11.5px] text-secondary-text tabular-nums">{percent(share.fraction)}</span>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</ScrollArea>
|
||||
<p className="px-4 pt-1.5 pb-2 text-[11px] text-muted-foreground">Click to highlight · Esc clears</p>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function namesUsedMoreThanOnce(shares: Share[]): Set<string> {
|
||||
const seen = new Set<string>()
|
||||
const repeated = new Set<string>()
|
||||
for (const share of shares) {
|
||||
if (seen.has(share.subject.name)) {
|
||||
repeated.add(share.subject.name)
|
||||
}
|
||||
seen.add(share.subject.name)
|
||||
}
|
||||
return repeated
|
||||
}
|
||||
|
||||
function fileName(key: string): string {
|
||||
return key.slice(key.lastIndexOf('/') + 1)
|
||||
}
|
||||
|
||||
function percent(fraction: number): string {
|
||||
if (fraction < 0.001) {
|
||||
return '<0.1%'
|
||||
}
|
||||
return fraction < 0.1 ? `${(fraction * 100).toFixed(1)}%` : `${Math.round(fraction * 100)}%`
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuTrigger
|
||||
} from '@/components/ui/context-menu'
|
||||
import type { BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { WorldInfo } from '../bridge/types'
|
||||
import { MapController, type MapListener, type SpotSubjects } from '../map/MapController'
|
||||
import type { Highlight } from '../map/tileStyle'
|
||||
|
||||
export interface CanvasPoint {
|
||||
x: number
|
||||
y: number
|
||||
}
|
||||
|
||||
interface MapCanvasProps {
|
||||
client: BridgeClient
|
||||
world: WorldInfo
|
||||
viewId: string
|
||||
controllerRef: React.RefObject<MapController | null>
|
||||
listener: MapListener
|
||||
highlight: Highlight | null
|
||||
onPointer(point: CanvasPoint | null): void
|
||||
onDragged(): void
|
||||
onTeleport(point: CanvasPoint): void
|
||||
onOpenFile(point: CanvasPoint): void
|
||||
onHighlight(subject: Highlight): void
|
||||
onCopy(text: string): void
|
||||
}
|
||||
|
||||
// A press that moves less than this is a click, not a drag.
|
||||
const CLICK_SLOP_PIXELS = 4
|
||||
// One wheel notch is about 100; this zooms about 15% per notch, and smoothly on touchpads.
|
||||
const WHEEL_ZOOM_PER_DELTA = 0.002
|
||||
|
||||
interface ContextSpot {
|
||||
point: CanvasPoint
|
||||
subjects: SpotSubjects
|
||||
blockX: number
|
||||
blockZ: number
|
||||
}
|
||||
|
||||
/** The map canvas and its mouse: drag to move, wheel to zoom, Ctrl+click to teleport, Alt+click to open a file. */
|
||||
export function MapCanvas(props: MapCanvasProps): React.JSX.Element {
|
||||
const { client, world, viewId, controllerRef } = props
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
const latest = useRef(props)
|
||||
latest.current = props
|
||||
const [contextSpot, setContextSpot] = useState<ContextSpot | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current!
|
||||
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
|
||||
const resize = new ResizeObserver(([entry]) => map.resize(entry.contentRect.width, entry.contentRect.height))
|
||||
resize.observe(canvas)
|
||||
return () => {
|
||||
resize.disconnect()
|
||||
map.close()
|
||||
controllerRef.current = null
|
||||
}
|
||||
// The controller lives as long as the connection; later view changes go through setView, not a new controller.
|
||||
}, [client, world, controllerRef])
|
||||
|
||||
useMouse(canvasRef, controllerRef, latest)
|
||||
|
||||
return (
|
||||
<ContextMenu
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setContextSpot(null)
|
||||
}
|
||||
}}
|
||||
>
|
||||
<ContextMenuTrigger asChild>
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
className="absolute inset-0 size-full cursor-grab active:cursor-grabbing"
|
||||
onContextMenu={(event) => {
|
||||
const map = controllerRef.current
|
||||
if (map === null) {
|
||||
return
|
||||
}
|
||||
const point = canvasPoint(event)
|
||||
const spot = map.worldAt(point.x, point.y)
|
||||
setContextSpot({ point, subjects: map.subjectsAt(point.x, point.y), blockX: Math.floor(spot.x), blockZ: Math.floor(spot.z) })
|
||||
}}
|
||||
/>
|
||||
</ContextMenuTrigger>
|
||||
<ContextMenuContent className="min-w-56">
|
||||
{contextSpot !== null && <SpotMenu spot={contextSpot} viewId={viewId} props={props} />}
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
|
||||
function SpotMenu({ spot, viewId, props }: { spot: ContextSpot; viewId: string; props: MapCanvasProps }): React.JSX.Element {
|
||||
const { subject, region } = spot.subjects
|
||||
const coordinates = `${spot.blockX}, ${spot.blockZ}`
|
||||
return (
|
||||
<>
|
||||
{subject !== null && <ContextMenuItem onSelect={() => props.onHighlight(subject)}>{highlightText(subject, props.highlight)}</ContextMenuItem>}
|
||||
{region !== null && subject?.kind !== 'REGION' && (
|
||||
<ContextMenuItem onSelect={() => props.onHighlight(region)}>{highlightText(region, props.highlight)}</ContextMenuItem>
|
||||
)}
|
||||
<ContextMenuItem onSelect={() => props.onTeleport(spot.point)}>Teleport here</ContextMenuItem>
|
||||
<ContextMenuItem onSelect={() => props.onOpenFile(spot.point)}>{viewId === 'regions' ? 'Open region file' : 'Open biome file'}</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem onSelect={() => props.onCopy(coordinates)}>Copy coordinates ({coordinates})</ContextMenuItem>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function highlightText(subject: Highlight, current: Highlight | null): string {
|
||||
const highlighted = current !== null && current.kind === subject.kind && current.key === subject.key
|
||||
return `${highlighted ? 'Clear highlight of' : 'Highlight'} ${subject.name}`
|
||||
}
|
||||
|
||||
function canvasPoint(event: { clientX: number; clientY: number; currentTarget: Element }): CanvasPoint {
|
||||
const bounds = event.currentTarget.getBoundingClientRect()
|
||||
return { x: event.clientX - bounds.left, y: event.clientY - bounds.top }
|
||||
}
|
||||
|
||||
function useMouse(
|
||||
canvasRef: React.RefObject<HTMLCanvasElement | null>,
|
||||
controllerRef: React.RefObject<MapController | null>,
|
||||
latest: React.RefObject<MapCanvasProps>
|
||||
): void {
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current!
|
||||
let press: { x: number; y: number; lastX: number; lastY: number; dragged: boolean } | null = null
|
||||
|
||||
const down = (event: PointerEvent): void => {
|
||||
if (event.button !== 0) {
|
||||
return
|
||||
}
|
||||
canvas.setPointerCapture(event.pointerId)
|
||||
press = { x: event.clientX, y: event.clientY, lastX: event.clientX, lastY: event.clientY, dragged: false }
|
||||
}
|
||||
const move = (event: PointerEvent): void => {
|
||||
const point = canvasPoint({ clientX: event.clientX, clientY: event.clientY, currentTarget: canvas })
|
||||
controllerRef.current?.setCursor(point)
|
||||
latest.current.onPointer(point)
|
||||
if (press === null) {
|
||||
return
|
||||
}
|
||||
if (!press.dragged && Math.hypot(event.clientX - press.x, event.clientY - press.y) >= CLICK_SLOP_PIXELS) {
|
||||
press.dragged = true
|
||||
latest.current.onDragged()
|
||||
}
|
||||
if (press.dragged) {
|
||||
controllerRef.current?.panBy(event.clientX - press.lastX, event.clientY - press.lastY)
|
||||
}
|
||||
press.lastX = event.clientX
|
||||
press.lastY = event.clientY
|
||||
}
|
||||
const up = (event: PointerEvent): void => {
|
||||
if (press === null || event.button !== 0) {
|
||||
return
|
||||
}
|
||||
const wasClick = !press.dragged
|
||||
press = null
|
||||
if (!wasClick) {
|
||||
return
|
||||
}
|
||||
const point = canvasPoint({ clientX: event.clientX, clientY: event.clientY, currentTarget: canvas })
|
||||
if (event.ctrlKey || event.metaKey) {
|
||||
latest.current.onTeleport(point)
|
||||
} else if (event.altKey) {
|
||||
latest.current.onOpenFile(point)
|
||||
}
|
||||
}
|
||||
const leave = (): void => {
|
||||
controllerRef.current?.setCursor(null)
|
||||
latest.current.onPointer(null)
|
||||
}
|
||||
const wheel = (event: WheelEvent): void => {
|
||||
event.preventDefault()
|
||||
const point = canvasPoint({ clientX: event.clientX, clientY: event.clientY, currentTarget: canvas })
|
||||
controllerRef.current?.zoomAt(2 ** (-event.deltaY * WHEEL_ZOOM_PER_DELTA), point.x, point.y)
|
||||
}
|
||||
|
||||
canvas.addEventListener('pointerdown', down)
|
||||
canvas.addEventListener('pointermove', move)
|
||||
canvas.addEventListener('pointerup', up)
|
||||
canvas.addEventListener('pointerleave', leave)
|
||||
canvas.addEventListener('wheel', wheel, { passive: false })
|
||||
return () => {
|
||||
canvas.removeEventListener('pointerdown', down)
|
||||
canvas.removeEventListener('pointermove', move)
|
||||
canvas.removeEventListener('pointerup', up)
|
||||
canvas.removeEventListener('pointerleave', leave)
|
||||
canvas.removeEventListener('wheel', wheel)
|
||||
}
|
||||
}, [canvasRef, controllerRef, latest])
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { ThemeChoice } from '../../../shared/bridge'
|
||||
import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient'
|
||||
import type { MapHover, MapLabel, Marker, ModuleViewInfo, PickDisplay, PickInspection, 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'
|
||||
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 { NoiseStudio } from './NoiseStudio'
|
||||
import { PatternStudio } from './PatternStudio'
|
||||
import { SavedWorldStudio } from './SavedWorldStudio'
|
||||
import { SceneStudio } from './SceneStudio'
|
||||
import { WorldStudio3D } from './WorldStudio3D'
|
||||
import { actionForKey, isTypingInto, viewForKey, type ShortcutAction } from './shortcuts'
|
||||
import { StatusBar } from './StatusBar'
|
||||
import { StudioToolbar } from './StudioToolbar'
|
||||
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
|
||||
world: WorldInfo
|
||||
theme: { choice: ThemeChoice; next: () => void }
|
||||
onDisconnect(): void
|
||||
}
|
||||
|
||||
export interface StudioToggles extends MapToggles {
|
||||
follow: boolean
|
||||
entities: boolean
|
||||
}
|
||||
|
||||
/** The map of one world: views on the left, the map in the middle, what is on screen on the right. */
|
||||
export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps): React.JSX.Element {
|
||||
const controller = useRef<MapController | null>(null)
|
||||
const [viewId, setViewId] = useState(world.views[0]?.id ?? 'biomes')
|
||||
const [toggles, setToggles] = useState<StudioToggles>({ shading: true, regionBorders: false, grid: false, follow: false, entities: false })
|
||||
const [highlight, setHighlight] = useState<Highlight | null>(null)
|
||||
const [status, setStatus] = useState<MapStatus | null>(null)
|
||||
const [shares, setShares] = useState<Share[]>([])
|
||||
const [players, setPlayers] = useState<Marker[]>([])
|
||||
const [entities, setEntities] = useState<Marker[]>([])
|
||||
const [pointer, setPointer] = useState<CanvasPoint | null>(null)
|
||||
const [hover, setHover] = useState<MapHover | null>(null)
|
||||
const [detailed, setDetailed] = useState(false)
|
||||
const [helpOpen, setHelpOpen] = useState(false)
|
||||
const [notice, setNotice] = useState<string | null>(null)
|
||||
const [connected, setConnected] = useState(true)
|
||||
const [preview, setPreview] = useState<string | null>(null)
|
||||
const [pickDisplay, setPickDisplay] = useState<PickDisplay>('picks')
|
||||
const [area, setArea] = useState<WorldRect | null>(null)
|
||||
const [packRevision, setPackRevision] = useState(0)
|
||||
const [sceneSummary, setSceneSummary] = useState<string | null>(null)
|
||||
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 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)
|
||||
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), [])
|
||||
|
||||
useEffect(() => {
|
||||
if (notice === null) {
|
||||
return
|
||||
}
|
||||
const timer = window.setTimeout(() => setNotice(null), NOTICE_MILLIS)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [notice])
|
||||
|
||||
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])
|
||||
|
||||
useEffect(() => {
|
||||
if (toggles.follow && players.length > 0) {
|
||||
controller.current?.centerOn(players[0].worldX, players[0].worldZ)
|
||||
}
|
||||
}, [players, toggles.follow])
|
||||
|
||||
const packReloaded = useCallback(() => setPackRevision((revision) => revision + 1), [])
|
||||
useServerEvents(client, controller, setPlayers, tell, setConnected, packReloaded)
|
||||
useEntities(client, toggles.entities, setEntities)
|
||||
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(() => {
|
||||
if (pointer === null || controller.current === null) {
|
||||
return
|
||||
}
|
||||
const { subject } = controller.current.subjectsAt(pointer.x, pointer.y)
|
||||
setHighlight((current) => (subject === null || sameSubject(current, subject) ? null : subject))
|
||||
}, [pointer])
|
||||
|
||||
const runShortcut = useCallback(
|
||||
(action: ShortcutAction) => {
|
||||
const map = controller.current
|
||||
switch (action) {
|
||||
case 'nextView':
|
||||
selectView(views[(views.findIndex((candidate) => candidate.id === viewId) + 1) % views.length].id)
|
||||
return
|
||||
case 'refresh':
|
||||
map?.refresh()
|
||||
tell('Redrawing with the latest pack files')
|
||||
return
|
||||
case 'zoomIn':
|
||||
map?.zoomAt(KEYBOARD_ZOOM_FACTOR)
|
||||
return
|
||||
case 'zoomOut':
|
||||
map?.zoomAt(1 / KEYBOARD_ZOOM_FACTOR)
|
||||
return
|
||||
case 'resetZoom':
|
||||
map?.resetZoom()
|
||||
return
|
||||
case 'dismiss':
|
||||
setHighlight(null)
|
||||
return
|
||||
case 'follow':
|
||||
toggle('follow')
|
||||
return
|
||||
case 'grid':
|
||||
toggle('grid')
|
||||
return
|
||||
case 'entities':
|
||||
toggle('entities')
|
||||
return
|
||||
case 'highlight':
|
||||
highlightUnderCursor()
|
||||
return
|
||||
case 'shading':
|
||||
toggle('shading')
|
||||
return
|
||||
case 'borders':
|
||||
toggle('regionBorders')
|
||||
return
|
||||
case 'help':
|
||||
setHelpOpen((open) => !open)
|
||||
}
|
||||
},
|
||||
[views, viewId, selectView, toggle, highlightUnderCursor, tell]
|
||||
)
|
||||
|
||||
useKeyboard(runShortcut, selectView, setDetailed, world)
|
||||
|
||||
const teleport = useCallback(
|
||||
(point: CanvasPoint) => {
|
||||
const spot = controller.current?.worldAt(point.x, point.y)
|
||||
if (spot === undefined) {
|
||||
return
|
||||
}
|
||||
client
|
||||
.teleport(Math.floor(spot.x), Math.floor(spot.z))
|
||||
.then(() => tell(`Teleporting to ${Math.floor(spot.x)}, ${Math.floor(spot.z)}`))
|
||||
.catch((failure: Error) => tell(failure.message))
|
||||
},
|
||||
[client, tell]
|
||||
)
|
||||
|
||||
const openFile = useCallback(
|
||||
(point: CanvasPoint) => {
|
||||
const spot = controller.current?.worldAt(point.x, point.y)
|
||||
if (spot === undefined) {
|
||||
return
|
||||
}
|
||||
client
|
||||
.openInEditor(spot.x, spot.z, viewId)
|
||||
.then((message) => tell(message ?? 'Opened'))
|
||||
.catch((failure: Error) => tell(failure.message))
|
||||
},
|
||||
[client, viewId, tell]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col bg-background">
|
||||
<StudioToolbar
|
||||
title={view.label}
|
||||
world={world}
|
||||
toggles={toggles}
|
||||
hasPlayers={world.hasPlayers}
|
||||
mapTools={showsMap}
|
||||
theme={theme}
|
||||
onToggle={toggle}
|
||||
onRefresh={() => runShortcut('refresh')}
|
||||
onResetZoom={() => runShortcut('resetZoom')}
|
||||
onHelp={() => setHelpOpen(true)}
|
||||
onDisconnect={onDisconnect}
|
||||
/>
|
||||
<div className="flex min-h-0 flex-1">
|
||||
<ViewList views={views} current={viewId} onSelect={selectView}>
|
||||
{viewId === 'regions' && regions.length > 1 && <RegionPreviewList regions={regions} current={layer.preview} onSelect={selectPreview} />}
|
||||
</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 ? (
|
||||
<SavedWorldStudio client={client} world={world} onSummary={setSceneSummary} tell={tell} />
|
||||
) : viewId === NOISE.id ? (
|
||||
<NoiseStudio client={client} packRevision={packRevision} onSummary={setSceneSummary} tell={tell} />
|
||||
) : (
|
||||
<>
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<MapCanvas
|
||||
client={client}
|
||||
world={world}
|
||||
viewId={viewId}
|
||||
controllerRef={controller}
|
||||
listener={{ onStatus: setStatus, onShares: setShares, onArea: (next) => setArea((current) => (sameRect(current, next) ? current : next)), onError: tell }}
|
||||
onPointer={setPointer}
|
||||
onDragged={() => setToggles((current) => (current.follow ? { ...current, follow: false } : current))}
|
||||
onTeleport={teleport}
|
||||
onOpenFile={openFile}
|
||||
onHighlight={(subject) => setHighlight((current) => (sameSubject(current, subject) ? null : subject))}
|
||||
highlight={highlight}
|
||||
onCopy={(text) => {
|
||||
window.studio.copyText(text)
|
||||
tell(`Copied ${text}`)
|
||||
}}
|
||||
/>
|
||||
{pointer !== null && hover !== null && (
|
||||
<HoverCard hover={hover} point={pointer} viewId={viewId} previewing={layer.preview !== null} detailed={detailed} minY={world.minY} />
|
||||
)}
|
||||
{!connected && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-background/70">
|
||||
<div className="rounded-xl border border-overlay-border bg-card p-5 text-center shadow-lg">
|
||||
<p className="font-medium">Lost the connection to the server</p>
|
||||
<button className="mt-3 text-link hover:underline" onClick={onDisconnect}>
|
||||
Back to the world list
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<aside className="flex w-[250px] shrink-0 flex-col border-l bg-card">
|
||||
{inspectsPicks && (
|
||||
<PickInspector
|
||||
title={previewName ?? view.label}
|
||||
picksLabel={viewId === 'regions' && layer.preview === null ? 'Regions' : 'Biomes'}
|
||||
inspection={inspection}
|
||||
display={pickDisplay}
|
||||
onDisplay={setPickDisplay}
|
||||
/>
|
||||
)}
|
||||
<Legend
|
||||
className={inspectsPicks ? 'flex-[3]' : 'flex-1'}
|
||||
title={legendTitle(layer)}
|
||||
shares={shares}
|
||||
highlight={highlight}
|
||||
onSelect={(subject) => setHighlight((current) => (sameSubject(current, subject) ? null : subject))}
|
||||
/>
|
||||
</aside>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<StatusBar viewLabel={statusLabel(view.label, previewName, showsMap ? null : sceneSummary)} status={showsMap ? status : null} notice={notice} />
|
||||
<HelpDialog open={helpOpen} onOpenChange={setHelpOpen} views={views} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const SCENE_GROUP = { group: 'BLOCKS', groupLabel: 'Blocks' }
|
||||
/** The app draws the 3D world from the server's biome tiles, so the server does not list it among its views. */
|
||||
const WORLD_3D: ViewInfo = {
|
||||
id: 'world3d',
|
||||
label: '3D world',
|
||||
description: 'The terrain in 3D, coloured by biome, region or height',
|
||||
group: 'WORLD',
|
||||
groupLabel: 'World'
|
||||
}
|
||||
const SAVED_WORLD: ViewInfo = {
|
||||
id: 'savedWorld',
|
||||
label: 'Saved world',
|
||||
description: 'A world as the server saved it to disk, in 3D',
|
||||
group: 'WORLD',
|
||||
groupLabel: 'World'
|
||||
}
|
||||
const NOISE: ViewInfo = {
|
||||
id: 'noise',
|
||||
label: 'Noise',
|
||||
description: "The pack's generators and expressions and the built-in noise styles, from above or as terrain",
|
||||
group: 'PACK',
|
||||
groupLabel: 'Pack'
|
||||
}
|
||||
const APP_VIEW_IDS = new Set([WORLD_3D.id, SAVED_WORLD.id, NOISE.id])
|
||||
|
||||
function withAppViews(serverViews: ViewInfo[]): ViewInfo[] {
|
||||
const afterHeight = serverViews.findIndex((candidate) => candidate.id === 'height') + 1
|
||||
return [...serverViews.slice(0, afterHeight), WORLD_3D, SAVED_WORLD, ...serverViews.slice(afterHeight)]
|
||||
}
|
||||
|
||||
function asViewInfo(view: ModuleViewInfo): ViewInfo {
|
||||
return { ...view, ...SCENE_GROUP }
|
||||
}
|
||||
|
||||
function statusLabel(viewLabel: string, previewName: string | null, sceneSummary: string | null): string {
|
||||
const detail = sceneSummary ?? previewName
|
||||
return detail === null ? viewLabel : `${viewLabel} · ${detail}`
|
||||
}
|
||||
|
||||
/** Views the pack's modules show, read again after the pack reloads; keep {@code load} stable. */
|
||||
function useModuleViews<View extends ModuleViewInfo>(load: () => Promise<View[]>, packRevision: number): View[] {
|
||||
const [views, setViews] = useState<View[]>([])
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
load()
|
||||
.then((found) => active && setViews(found))
|
||||
.catch(() => undefined)
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [load, packRevision])
|
||||
return views
|
||||
}
|
||||
|
||||
function sameSubject(first: Highlight | null, second: Highlight | null): boolean {
|
||||
return first !== null && second !== null && first.kind === second.kind && first.key === second.key
|
||||
}
|
||||
|
||||
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 layer.view === 'height' ? 'Heights on screen' : 'Biomes on screen'
|
||||
}
|
||||
|
||||
/** The regions the region view can preview, read again after the pack reloads. */
|
||||
function usePreviewableRegions(client: BridgeClient, packRevision: number): MapLabel[] {
|
||||
const [regions, setRegions] = useState<MapLabel[]>([])
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
client
|
||||
.regions()
|
||||
.then((found) => active && setRegions(found))
|
||||
.catch(() => undefined)
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [client, packRevision])
|
||||
return regions
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures how the noise picks what the view shows, once the map has rested on an area for a moment; the last
|
||||
* measurement stays up until the next one arrives, so panning does not blank the panel.
|
||||
*/
|
||||
function usePickInspection(
|
||||
client: BridgeClient,
|
||||
layer: MapLayerQuery,
|
||||
area: WorldRect | null,
|
||||
enabled: boolean,
|
||||
packRevision: number
|
||||
): PickInspection | null {
|
||||
const [inspection, setInspection] = useState<PickInspection | null>(null)
|
||||
useEffect(() => setInspection(null), [layer, packRevision])
|
||||
useEffect(() => {
|
||||
if (!enabled || area === null) {
|
||||
return
|
||||
}
|
||||
const stop = new AbortController()
|
||||
const timer = window.setTimeout(() => {
|
||||
client
|
||||
.picks(layer, area, stop.signal)
|
||||
.then(setInspection)
|
||||
.catch(() => undefined)
|
||||
}, INSPECTION_REST_MILLIS)
|
||||
return () => {
|
||||
window.clearTimeout(timer)
|
||||
stop.abort()
|
||||
}
|
||||
}, [client, layer, area, enabled, packRevision])
|
||||
return inspection
|
||||
}
|
||||
|
||||
/** Players and hotloads from the server; the first world event only says the world runs, which is known. */
|
||||
function useServerEvents(
|
||||
client: BridgeClient,
|
||||
controller: React.RefObject<MapController | null>,
|
||||
setPlayers: (players: Marker[]) => void,
|
||||
tell: (message: string) => void,
|
||||
setConnected: (connected: boolean) => void,
|
||||
onPackReloaded: () => void
|
||||
): void {
|
||||
useEffect(() => {
|
||||
const stop = new AbortController()
|
||||
let firstWorldEvent = true
|
||||
void client.listen(
|
||||
{
|
||||
onWorld: (running) => {
|
||||
if (firstWorldEvent) {
|
||||
firstWorldEvent = false
|
||||
return
|
||||
}
|
||||
if (running) {
|
||||
controller.current?.refresh()
|
||||
onPackReloaded()
|
||||
tell('Pack reloaded, redrawing')
|
||||
} else {
|
||||
tell('The world stopped')
|
||||
}
|
||||
},
|
||||
onPlayers: setPlayers,
|
||||
onClosed: () => setConnected(false)
|
||||
},
|
||||
stop.signal
|
||||
)
|
||||
return () => stop.abort()
|
||||
}, [client, controller, setPlayers, tell, setConnected, onPackReloaded])
|
||||
}
|
||||
|
||||
function useEntities(client: BridgeClient, visible: boolean, setEntities: (entities: Marker[]) => void): void {
|
||||
useEffect(() => {
|
||||
if (!visible) {
|
||||
return
|
||||
}
|
||||
let active = true
|
||||
const refresh = (): void => {
|
||||
client
|
||||
.entities()
|
||||
.then((found) => active && setEntities(found))
|
||||
.catch(() => undefined)
|
||||
}
|
||||
refresh()
|
||||
const timer = window.setInterval(refresh, ENTITY_POLL_MILLIS)
|
||||
return () => {
|
||||
active = false
|
||||
window.clearInterval(timer)
|
||||
}
|
||||
}, [client, visible, setEntities])
|
||||
}
|
||||
|
||||
/** Asks the server about the spot under the cursor; a newer spot aborts the question about an older one. */
|
||||
function useHover(
|
||||
client: BridgeClient,
|
||||
controller: React.RefObject<MapController | null>,
|
||||
layer: MapLayerQuery,
|
||||
pointer: CanvasPoint | null,
|
||||
setHover: (hover: MapHover | null) => void
|
||||
): void {
|
||||
useEffect(() => {
|
||||
if (pointer === null || controller.current === null) {
|
||||
setHover(null)
|
||||
return
|
||||
}
|
||||
const spot = controller.current.worldAt(pointer.x, pointer.y)
|
||||
const stop = new AbortController()
|
||||
client
|
||||
.hover(layer, Math.floor(spot.x), Math.floor(spot.z), stop.signal)
|
||||
.then(setHover)
|
||||
.catch(() => undefined)
|
||||
return () => stop.abort()
|
||||
}, [client, controller, layer, pointer, setHover])
|
||||
}
|
||||
|
||||
function useKeyboard(
|
||||
runShortcut: (action: ShortcutAction) => void,
|
||||
selectView: (view: string) => void,
|
||||
setDetailed: (detailed: boolean) => void,
|
||||
world: WorldInfo
|
||||
): void {
|
||||
useEffect(() => {
|
||||
const down = (event: KeyboardEvent): void => {
|
||||
if (event.key === 'Shift') {
|
||||
setDetailed(true)
|
||||
}
|
||||
if (event.ctrlKey || event.metaKey || event.altKey || isTypingInto(event.target)) {
|
||||
return
|
||||
}
|
||||
const viewId = viewForKey(event.key)
|
||||
if (viewId !== null && world.views.some((view) => view.id === viewId)) {
|
||||
selectView(viewId)
|
||||
return
|
||||
}
|
||||
const action = actionForKey(event.key)
|
||||
if (action !== null) {
|
||||
event.preventDefault()
|
||||
runShortcut(action)
|
||||
}
|
||||
}
|
||||
const up = (event: KeyboardEvent): void => {
|
||||
if (event.key === 'Shift') {
|
||||
setDetailed(false)
|
||||
}
|
||||
}
|
||||
const blur = (): void => setDetailed(false)
|
||||
window.addEventListener('keydown', down)
|
||||
window.addEventListener('keyup', up)
|
||||
window.addEventListener('blur', blur)
|
||||
return () => {
|
||||
window.removeEventListener('keydown', down)
|
||||
window.removeEventListener('keyup', up)
|
||||
window.removeEventListener('blur', blur)
|
||||
}
|
||||
}, [runShortcut, selectView, setDetailed, world])
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
import { Box, Circle, Flower2, GitCommitVertical, GitFork, Group, Link2, Paintbrush, Sparkles, type LucideIcon } from 'lucide-react'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger } from '@/components/ui/context-menu'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { GraphEdit, GraphNode, JsonPath } from '../bridge/types'
|
||||
import { idOf, isWithin, layoutNodes, NODE_HEIGHT, NODE_WIDTH, type NodeLayout, type PlacedNode } from '../editor/nodeLayout'
|
||||
|
||||
const KIND_ICONS: Record<string, LucideIcon> = {
|
||||
Object: Box,
|
||||
Stem: GitCommitVertical,
|
||||
Blob: Circle,
|
||||
Branches: GitFork,
|
||||
Cluster: Sparkles,
|
||||
Group: Group,
|
||||
'Shared part': Link2,
|
||||
Material: Paintbrush,
|
||||
Decoration: Flower2
|
||||
}
|
||||
const FIT_MARGIN = 24
|
||||
const LARGEST_FIT_SCALE = 1
|
||||
// Below this the node text can't be read; a larger tree is panned instead of shrunk further.
|
||||
const SMALLEST_FIT_SCALE = 0.8
|
||||
const SMALLEST_SCALE = 0.25
|
||||
const LARGEST_SCALE = 2
|
||||
const WHEEL_ZOOM_PER_PIXEL = 0.0015
|
||||
const DRAG_START_PIXELS = 4
|
||||
const GRID_SPACING = 16
|
||||
|
||||
interface Camera {
|
||||
x: number
|
||||
y: number
|
||||
scale: number
|
||||
}
|
||||
|
||||
interface NodeDrag {
|
||||
placed: PlacedNode
|
||||
startX: number
|
||||
startY: number
|
||||
pointerX: number
|
||||
pointerY: number
|
||||
moved: boolean
|
||||
target: PlacedNode | null
|
||||
}
|
||||
|
||||
interface NodeCanvasProps {
|
||||
roots: GraphNode[]
|
||||
/** Tells files apart, so a new one is fitted into view. */
|
||||
fileKey: string
|
||||
selectedId: string | null
|
||||
locked: boolean
|
||||
onSelect(node: GraphNode | null): void
|
||||
onEdit(edit: GraphEdit): void
|
||||
}
|
||||
|
||||
/** The file as a tree of nodes: drag the background to look around, drag a node onto another to grow it from there. */
|
||||
export function NodeCanvas({ roots, fileKey, selectedId, locked, onSelect, onEdit }: NodeCanvasProps): React.JSX.Element {
|
||||
const layout = useMemo(() => layoutNodes(roots), [roots])
|
||||
const frame = useRef<HTMLDivElement>(null)
|
||||
const [camera, setCamera] = useCamera(frame, layout, fileKey)
|
||||
const [drag, setDrag] = useState<NodeDrag | null>(null)
|
||||
const [menuNode, setMenuNode] = useState<GraphNode | null>(null)
|
||||
const pan = useRef<{ x: number; y: number } | null>(null)
|
||||
|
||||
const canvasPoint = (clientX: number, clientY: number): { x: number; y: number } => {
|
||||
const bounds = frame.current!.getBoundingClientRect()
|
||||
return { x: (clientX - bounds.left - camera.x) / camera.scale, y: (clientY - bounds.top - camera.y) / camera.scale }
|
||||
}
|
||||
|
||||
const pointerDown = (event: React.PointerEvent): void => {
|
||||
if (event.button !== 0) {
|
||||
return
|
||||
}
|
||||
event.currentTarget.setPointerCapture(event.pointerId)
|
||||
const placed = nodeAt(layout, canvasPoint(event.clientX, event.clientY))
|
||||
if (placed === null) {
|
||||
pan.current = { x: event.clientX, y: event.clientY }
|
||||
return
|
||||
}
|
||||
setDrag({ placed, startX: event.clientX, startY: event.clientY, pointerX: event.clientX, pointerY: event.clientY, moved: false, target: null })
|
||||
}
|
||||
|
||||
const pointerMove = (event: React.PointerEvent): void => {
|
||||
if (pan.current !== null) {
|
||||
const [dx, dy] = [event.clientX - pan.current.x, event.clientY - pan.current.y]
|
||||
pan.current = { x: event.clientX, y: event.clientY }
|
||||
setCamera((current) => ({ ...current, x: current.x + dx, y: current.y + dy }))
|
||||
return
|
||||
}
|
||||
if (drag === null) {
|
||||
return
|
||||
}
|
||||
const moved = drag.moved || Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY) > DRAG_START_PIXELS
|
||||
const canMove = moved && !locked && drag.placed.node.movable
|
||||
const target = canMove ? moveTarget(layout, drag.placed, canvasPoint(event.clientX, event.clientY)) : null
|
||||
setDrag({ ...drag, pointerX: event.clientX, pointerY: event.clientY, moved, target })
|
||||
}
|
||||
|
||||
const pointerUp = (): void => {
|
||||
pan.current = null
|
||||
if (drag === null) {
|
||||
return
|
||||
}
|
||||
if (!drag.moved) {
|
||||
onSelect(drag.placed.node)
|
||||
} else if (drag.target !== null) {
|
||||
onEdit({ op: 'move', path: drag.placed.node.path, toList: drag.target.node.childList! })
|
||||
}
|
||||
setDrag(null)
|
||||
}
|
||||
|
||||
const dragging = drag !== null && drag.moved && drag.placed.node.movable && !locked
|
||||
const dragOffset = dragging ? { x: (drag.pointerX - drag.startX) / camera.scale, y: (drag.pointerY - drag.startY) / camera.scale } : null
|
||||
|
||||
return (
|
||||
<ContextMenu onOpenChange={(open) => !open && setMenuNode(null)}>
|
||||
<ContextMenuTrigger asChild>
|
||||
<div
|
||||
ref={frame}
|
||||
className="relative h-full w-full touch-none overflow-hidden bg-background select-none"
|
||||
style={{
|
||||
backgroundImage: 'radial-gradient(var(--overlay-border) 1px, transparent 1px)',
|
||||
backgroundSize: `${GRID_SPACING * camera.scale}px ${GRID_SPACING * camera.scale}px`,
|
||||
backgroundPosition: `${camera.x}px ${camera.y}px`
|
||||
}}
|
||||
onPointerDown={pointerDown}
|
||||
onPointerMove={pointerMove}
|
||||
onPointerUp={pointerUp}
|
||||
onPointerCancel={() => {
|
||||
pan.current = null
|
||||
setDrag(null)
|
||||
}}
|
||||
onContextMenu={(event) => {
|
||||
const placed = nodeAt(layout, canvasPoint(event.clientX, event.clientY))
|
||||
setMenuNode(placed?.node ?? null)
|
||||
if (placed === null) {
|
||||
event.preventDefault()
|
||||
} else {
|
||||
onSelect(placed.node)
|
||||
}
|
||||
}}
|
||||
onDoubleClick={(event) => nodeAt(layout, canvasPoint(event.clientX, event.clientY)) === null && setCamera(fitted(frame.current!, layout))}
|
||||
>
|
||||
<div className="absolute top-0 left-0 origin-top-left" style={{ transform: `translate(${camera.x}px, ${camera.y}px) scale(${camera.scale})` }}>
|
||||
<Wires layout={layout} />
|
||||
{layout.nodes.map((placed) => (
|
||||
<NodeBox
|
||||
key={placed.id}
|
||||
placed={placed}
|
||||
selected={placed.id === selectedId}
|
||||
target={drag?.target?.id === placed.id}
|
||||
offset={dragging && drag.placed.id === placed.id ? dragOffset : null}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</ContextMenuTrigger>
|
||||
{menuNode !== null && <NodeMenu node={menuNode} locked={locked} onEdit={onEdit} />}
|
||||
</ContextMenu>
|
||||
)
|
||||
}
|
||||
|
||||
function NodeBox({ placed, selected, target, offset }: { placed: PlacedNode; selected: boolean; target: boolean; offset: { x: number; y: number } | null }): React.JSX.Element {
|
||||
const { node } = placed
|
||||
const Icon = KIND_ICONS[node.kind] ?? Box
|
||||
const detail = node.roles.length > 0 ? node.roles.join(', ') : node.title === node.kind ? null : node.kind
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'absolute flex items-center gap-2 rounded-md border bg-card px-2.5 shadow-xs',
|
||||
selected ? 'border-primary ring-1 ring-primary' : 'border-overlay-border',
|
||||
target && 'border-primary bg-selection',
|
||||
offset !== null && 'z-10 opacity-80 shadow-md'
|
||||
)}
|
||||
style={{
|
||||
left: placed.x + (offset?.x ?? 0),
|
||||
top: placed.y + (offset?.y ?? 0),
|
||||
width: NODE_WIDTH,
|
||||
height: NODE_HEIGHT,
|
||||
cursor: node.movable ? 'grab' : 'default'
|
||||
}}
|
||||
>
|
||||
<Icon className="size-4 shrink-0 text-secondary-text" />
|
||||
<div className="min-w-0 leading-tight">
|
||||
<div className="truncate text-[12.5px] font-medium">{node.title}</div>
|
||||
{detail !== null && <div className="truncate text-[11px] text-secondary-text">{detail}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Wires({ layout }: { layout: NodeLayout }): React.JSX.Element {
|
||||
return (
|
||||
<svg className="pointer-events-none absolute top-0 left-0 overflow-visible" width={layout.width} height={layout.height}>
|
||||
{layout.wires.map(({ from, to, label }) => {
|
||||
const [startX, startY] = [from.x + NODE_WIDTH, from.y + NODE_HEIGHT / 2]
|
||||
const [endX, endY] = [to.x, to.y + NODE_HEIGHT / 2]
|
||||
const bend = (endX - startX) / 2
|
||||
return (
|
||||
<g key={`${from.id}>${to.id}`}>
|
||||
<path d={`M${startX},${startY} C${startX + bend},${startY} ${endX - bend},${endY} ${endX},${endY}`} className="fill-none stroke-input" strokeWidth={1.5} />
|
||||
{label !== '' && (
|
||||
<text x={endX - 6} y={endY - 6} textAnchor="end" className="fill-secondary-text text-[10.5px]">
|
||||
{label}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
)
|
||||
})}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function NodeMenu({ node, locked, onEdit }: { node: GraphNode; locked: boolean; onEdit(edit: GraphEdit): void }): React.JSX.Element {
|
||||
const removable = node.duplicable
|
||||
return (
|
||||
<ContextMenuContent className="min-w-[180px]">
|
||||
{node.additions.length > 0 && (
|
||||
<ContextMenuSub>
|
||||
<ContextMenuSubTrigger disabled={locked}>Add</ContextMenuSubTrigger>
|
||||
<ContextMenuSubContent>
|
||||
{node.additions.map((addition) => (
|
||||
<ContextMenuItem key={`${idOf(addition.list)}:${addition.label}`} onSelect={() => onEdit({ op: 'append', list: addition.list, literal: addition.literal })}>
|
||||
{addition.label}
|
||||
</ContextMenuItem>
|
||||
))}
|
||||
</ContextMenuSubContent>
|
||||
</ContextMenuSub>
|
||||
)}
|
||||
<ContextMenuItem disabled={locked || !node.duplicable} onSelect={() => onEdit({ op: 'duplicate', path: node.path })}>
|
||||
Duplicate
|
||||
</ContextMenuItem>
|
||||
<ContextMenuSeparator />
|
||||
<ContextMenuItem variant="destructive" disabled={locked || !removable} onSelect={() => onEdit({ op: 'delete', path: node.path })}>
|
||||
Delete
|
||||
</ContextMenuItem>
|
||||
</ContextMenuContent>
|
||||
)
|
||||
}
|
||||
|
||||
function nodeAt(layout: NodeLayout, point: { x: number; y: number }): PlacedNode | null {
|
||||
return layout.nodes.find((placed) => point.x >= placed.x && point.x <= placed.x + NODE_WIDTH && point.y >= placed.y && point.y <= placed.y + NODE_HEIGHT) ?? null
|
||||
}
|
||||
|
||||
// A node can grow from any other that takes children, except from inside itself or from where it already grows.
|
||||
function moveTarget(layout: NodeLayout, dragged: PlacedNode, point: { x: number; y: number }): PlacedNode | null {
|
||||
const over = nodeAt(layout, point)
|
||||
const toList = over?.node.childList
|
||||
if (over === null || toList === null || toList === undefined || isWithin(toList, dragged.node.path) || isParentList(dragged.node.path, toList)) {
|
||||
return null
|
||||
}
|
||||
return over
|
||||
}
|
||||
|
||||
function isParentList(path: JsonPath, list: JsonPath): boolean {
|
||||
return path.length === list.length + 1 && isWithin(path, list)
|
||||
}
|
||||
|
||||
function useCamera(frame: React.RefObject<HTMLDivElement | null>, layout: NodeLayout, fileKey: string): [Camera, React.Dispatch<React.SetStateAction<Camera>>] {
|
||||
const [camera, setCamera] = useState<Camera>({ x: FIT_MARGIN, y: FIT_MARGIN, scale: 1 })
|
||||
const fittedFile = useRef<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (frame.current === null || layout.nodes.length === 0 || fittedFile.current === fileKey) {
|
||||
return
|
||||
}
|
||||
fittedFile.current = fileKey
|
||||
setCamera(fitted(frame.current, layout))
|
||||
}, [frame, layout, fileKey])
|
||||
|
||||
useEffect(() => {
|
||||
const element = frame.current
|
||||
if (element === null) {
|
||||
return
|
||||
}
|
||||
const wheel = (event: WheelEvent): void => {
|
||||
event.preventDefault()
|
||||
const bounds = element.getBoundingClientRect()
|
||||
const [pointerX, pointerY] = [event.clientX - bounds.left, event.clientY - bounds.top]
|
||||
setCamera((current) => {
|
||||
const scale = clamp(current.scale * Math.exp(-event.deltaY * WHEEL_ZOOM_PER_PIXEL), SMALLEST_SCALE, LARGEST_SCALE)
|
||||
const ratio = scale / current.scale
|
||||
return { scale, x: pointerX - (pointerX - current.x) * ratio, y: pointerY - (pointerY - current.y) * ratio }
|
||||
})
|
||||
}
|
||||
element.addEventListener('wheel', wheel, { passive: false })
|
||||
return () => element.removeEventListener('wheel', wheel)
|
||||
}, [frame])
|
||||
|
||||
return [camera, setCamera]
|
||||
}
|
||||
|
||||
function fitted(frame: HTMLDivElement, layout: NodeLayout): Camera {
|
||||
const [width, height] = [frame.clientWidth - 2 * FIT_MARGIN, frame.clientHeight - 2 * FIT_MARGIN]
|
||||
const scale = clamp(Math.min(width / Math.max(layout.width, 1), height / Math.max(layout.height, 1)), SMALLEST_FIT_SCALE, LARGEST_FIT_SCALE)
|
||||
return { scale, x: FIT_MARGIN, y: FIT_MARGIN + Math.max(0, (height - layout.height * scale) / 2) }
|
||||
}
|
||||
|
||||
function clamp(value: number, lowest: number, highest: number): number {
|
||||
return Math.min(highest, Math.max(lowest, value))
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import { RotateCcw } from 'lucide-react'
|
||||
import { 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 { EditorState, GraphEdit, GraphNode, NodeSettings, SettingOption, ValueKind } from '../bridge/types'
|
||||
import { valueAt } from '../editor/jsonValues'
|
||||
|
||||
const NOT_SET = ''
|
||||
|
||||
interface NodeInspectorProps {
|
||||
node: GraphNode
|
||||
state: EditorState
|
||||
/** The file parsed, to read what each setting is set to. */
|
||||
values: unknown
|
||||
onEdit(edit: GraphEdit): void
|
||||
}
|
||||
|
||||
/** The settings of the chosen node, a field per option of its schema type; an empty field leaves the option unset. */
|
||||
export function NodeInspector({ node, state, values, onEdit }: NodeInspectorProps): React.JSX.Element {
|
||||
const locked = state.locked !== null
|
||||
return (
|
||||
<section className="flex min-h-0 flex-[7] flex-col">
|
||||
<header className="px-4 pt-2.5 pb-1.5">
|
||||
<h2 className="truncate text-[13px] font-semibold">{node.title}</h2>
|
||||
<p className="truncate text-[11.5px] text-secondary-text">{node.roles.length > 0 ? node.roles.join(', ') : node.kind}</p>
|
||||
</header>
|
||||
<ScrollArea className="min-h-0 flex-1 border-t">
|
||||
<div className="pb-3">
|
||||
{node.settings.map((section) => (
|
||||
<SettingsSection key={JSON.stringify(section.path) + section.type} section={section} state={state} values={values} locked={locked} onEdit={onEdit} />
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function SettingsSection({
|
||||
section,
|
||||
state,
|
||||
values,
|
||||
locked,
|
||||
onEdit
|
||||
}: {
|
||||
section: NodeSettings
|
||||
state: EditorState
|
||||
values: unknown
|
||||
locked: boolean
|
||||
onEdit(edit: GraphEdit): void
|
||||
}): React.JSX.Element {
|
||||
const type = state.types[section.type]
|
||||
const options = type?.options.filter((option) => !section.shownAsNodes.includes(option.name)) ?? []
|
||||
return (
|
||||
<section className="px-4 pt-3">
|
||||
<h3 className="pb-1 text-[11px] font-semibold text-muted-foreground" title={type?.description}>
|
||||
{section.title}
|
||||
</h3>
|
||||
{options.map((option) => {
|
||||
const value = valueAt(values, [...section.path, option.name])
|
||||
return (
|
||||
<SettingField
|
||||
key={`${option.name}=${JSON.stringify(value)}`}
|
||||
option={option}
|
||||
value={value}
|
||||
locked={locked}
|
||||
onSet={(literal) => onEdit({ op: 'set', object: section.path, key: option.name, literal })}
|
||||
onUnset={() => onEdit({ op: 'unset', object: section.path, key: option.name })}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
interface SettingFieldProps {
|
||||
option: SettingOption
|
||||
/** What the file sets it to; undefined when it is not set. */
|
||||
value: unknown
|
||||
locked: boolean
|
||||
onSet(literal: string): void
|
||||
onUnset(): void
|
||||
}
|
||||
|
||||
function SettingField(props: SettingFieldProps): React.JSX.Element {
|
||||
const kind = props.option.kind.kind
|
||||
return kind === 'boolean' || kind === 'enum' ? <ChoiceField {...props} /> : <TypedField {...props} />
|
||||
}
|
||||
|
||||
function FieldRow({ option, value, locked, onUnset, problem, children }: SettingFieldProps & { problem: string | null; children: React.ReactNode }): React.JSX.Element {
|
||||
return (
|
||||
<div className="py-0.5">
|
||||
<div className="flex h-7 items-center gap-2">
|
||||
<label className={cn('min-w-0 flex-[4] truncate text-[12px]', option.required && 'font-medium')} title={option.description}>
|
||||
{option.name}
|
||||
</label>
|
||||
<div className="flex min-w-0 flex-[6] items-center gap-1">
|
||||
{children}
|
||||
<Button variant="ghost" size="icon-sm" title="Unset" className={cn('size-6 shrink-0', value === undefined && 'invisible')} disabled={locked} onClick={onUnset}>
|
||||
<RotateCcw className="size-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{problem !== null && <p className="pt-0.5 text-right text-[11px] text-destructive">{problem}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ChoiceField(props: SettingFieldProps): React.JSX.Element {
|
||||
const { option, value, locked, onSet, onUnset } = props
|
||||
const choices = option.kind.kind === 'enum' ? option.kind.constants.map((constant) => constant.name) : ['true', 'false']
|
||||
const literalOf = (choice: string): string => (option.kind.kind === 'enum' ? JSON.stringify(choice) : choice)
|
||||
return (
|
||||
<FieldRow {...props} problem={null}>
|
||||
<select
|
||||
className="h-7 w-full min-w-0 rounded-md border border-input bg-transparent px-1.5 text-[12px] outline-none focus-visible:border-ring dark:bg-input/30"
|
||||
value={value === undefined ? NOT_SET : String(value)}
|
||||
disabled={locked}
|
||||
title={option.description}
|
||||
onChange={(event) => (event.target.value === NOT_SET ? onUnset() : onSet(literalOf(event.target.value)))}
|
||||
>
|
||||
<option value={NOT_SET}>{defaultLabel(option)}</option>
|
||||
{choices.map((choice) => (
|
||||
<option key={choice} value={choice}>
|
||||
{choice}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</FieldRow>
|
||||
)
|
||||
}
|
||||
|
||||
// Numbers, text and anything else are typed in; a draft that does not fit the option says why and is not written.
|
||||
function TypedField(props: SettingFieldProps): React.JSX.Element {
|
||||
const { option, value, locked, onSet, onUnset } = props
|
||||
const shown = textOf(option.kind, value)
|
||||
const [draft, setDraft] = useState(shown)
|
||||
const problem = draft.trim() === NOT_SET ? null : problemWith(option, draft)
|
||||
const commit = (): void => {
|
||||
if (draft === shown || problem !== null) {
|
||||
return
|
||||
}
|
||||
if (draft.trim() === NOT_SET) {
|
||||
onUnset()
|
||||
return
|
||||
}
|
||||
onSet(literalOf(option.kind, draft))
|
||||
}
|
||||
return (
|
||||
<FieldRow {...props} problem={problem}>
|
||||
<Input
|
||||
value={draft}
|
||||
disabled={locked}
|
||||
placeholder={defaultLabel(option)}
|
||||
aria-invalid={problem !== null}
|
||||
title={option.description}
|
||||
inputMode={isNumber(option.kind) ? 'decimal' : undefined}
|
||||
className={cn('h-7 px-2 text-[12px] md:text-[12px]', isNumber(option.kind) ? 'tabular-nums' : !isText(option.kind) && 'font-mono text-[11.5px] placeholder:font-sans md:text-[11.5px]')}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
onBlur={commit}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') {
|
||||
commit()
|
||||
} else if (event.key === 'Escape') {
|
||||
setDraft(shown)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</FieldRow>
|
||||
)
|
||||
}
|
||||
|
||||
function defaultLabel(option: SettingOption): string {
|
||||
if (option.defaultValue === null || option.defaultValue === undefined) {
|
||||
return option.required ? 'Required' : 'Not set'
|
||||
}
|
||||
const text = typeof option.defaultValue === 'string' ? option.defaultValue : JSON.stringify(option.defaultValue)
|
||||
return `Default ${text}`
|
||||
}
|
||||
|
||||
function isNumber(kind: ValueKind): boolean {
|
||||
return kind.kind === 'integer' || kind.kind === 'decimal'
|
||||
}
|
||||
|
||||
function isText(kind: ValueKind): boolean {
|
||||
return kind.kind === 'text' || kind.kind === 'reference' || kind.kind === 'resource'
|
||||
}
|
||||
|
||||
function textOf(kind: ValueKind, value: unknown): string {
|
||||
if (value === undefined) {
|
||||
return NOT_SET
|
||||
}
|
||||
return isText(kind) && typeof value === 'string' ? value : JSON.stringify(value)
|
||||
}
|
||||
|
||||
function literalOf(kind: ValueKind, draft: string): string {
|
||||
return isText(kind) ? JSON.stringify(draft) : draft.trim()
|
||||
}
|
||||
|
||||
function problemWith(option: SettingOption, draft: string): string | null {
|
||||
if (isText(option.kind)) {
|
||||
return null
|
||||
}
|
||||
if (!isNumber(option.kind)) {
|
||||
return isJson(draft) ? null : 'Not JSON'
|
||||
}
|
||||
const number = Number(draft)
|
||||
if (draft.trim() === '' || !Number.isFinite(number)) {
|
||||
return 'Not a number'
|
||||
}
|
||||
if (option.kind.kind === 'integer' && !Number.isInteger(number)) {
|
||||
return 'Not a whole number'
|
||||
}
|
||||
if (option.minimum !== null && number < option.minimum) {
|
||||
return `At least ${option.minimum}`
|
||||
}
|
||||
if (option.maximum !== null && number > option.maximum) {
|
||||
return `At most ${option.maximum}`
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function isJson(text: string): boolean {
|
||||
try {
|
||||
JSON.parse(text)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { Lock, Redo2, Undo2 } from 'lucide-react'
|
||||
import { useEffect } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { GraphNode } from '../bridge/types'
|
||||
import type { NodeEditor } from '../editor/useNodeEditor'
|
||||
import { NodeCanvas } from './NodeCanvas'
|
||||
import { isTypingInto } from './shortcuts'
|
||||
|
||||
interface NodePaneProps {
|
||||
editor: NodeEditor
|
||||
/** The entry the file belongs to. */
|
||||
entryKey: string
|
||||
selected: GraphNode | null
|
||||
onSelect(node: GraphNode | null): void
|
||||
}
|
||||
|
||||
/** The node editor under the scene: the entry's file as nodes, with undo and redo. */
|
||||
export function NodePane({ editor, entryKey, selected, onSelect }: NodePaneProps): React.JSX.Element {
|
||||
const { state } = editor
|
||||
const locked = state === null || state.locked !== null
|
||||
useEditorKeys(editor, selected, locked)
|
||||
|
||||
return (
|
||||
<section className="flex min-h-0 flex-[9] flex-col border-t">
|
||||
<header className="flex h-9 shrink-0 items-center gap-2 border-b bg-card px-3">
|
||||
<h2 className="text-[12px] font-semibold">Nodes</h2>
|
||||
<span className="min-w-0 truncate text-[11.5px] text-secondary-text">{state?.file ?? entryKey}</span>
|
||||
<span className="flex-1" />
|
||||
{state?.locked != null && (
|
||||
<span className="flex shrink-0 items-center gap-1 text-[11.5px] whitespace-nowrap text-secondary-text" title={state.locked}>
|
||||
<Lock className="size-3.5" />
|
||||
Read only
|
||||
</span>
|
||||
)}
|
||||
{editor.saving && <span className="text-[11.5px] text-secondary-text">Saving…</span>}
|
||||
<Button variant="ghost" size="icon-sm" title="Undo (Ctrl+Z)" disabled={locked || !editor.canUndo} onClick={editor.undo}>
|
||||
<Undo2 />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon-sm" title="Redo (Ctrl+Shift+Z)" disabled={locked || !editor.canRedo} onClick={editor.redo}>
|
||||
<Redo2 />
|
||||
</Button>
|
||||
</header>
|
||||
<div className="relative min-h-0 flex-1">
|
||||
{state === null && <p className="p-4 text-[12px] text-muted-foreground">Reading the file…</p>}
|
||||
{state !== null && state.roots === null && (
|
||||
<div className="p-4 text-[12px]">
|
||||
<p className="font-medium">This file can't be shown as nodes</p>
|
||||
<p className="pt-1 text-secondary-text">{state.problem}</p>
|
||||
</div>
|
||||
)}
|
||||
{state !== null && state.roots !== null && (
|
||||
<NodeCanvas
|
||||
roots={state.roots}
|
||||
fileKey={entryKey}
|
||||
selectedId={selected === null ? null : JSON.stringify(selected.path)}
|
||||
locked={locked}
|
||||
onSelect={onSelect}
|
||||
onEdit={editor.edit}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function useEditorKeys(editor: NodeEditor, selected: GraphNode | null, locked: boolean): void {
|
||||
const { undo, redo, edit } = editor
|
||||
useEffect(() => {
|
||||
if (locked) {
|
||||
return
|
||||
}
|
||||
const down = (event: KeyboardEvent): void => {
|
||||
if (isTypingInto(event.target)) {
|
||||
return
|
||||
}
|
||||
const command = event.ctrlKey || event.metaKey
|
||||
if (command && event.key.toLowerCase() === 'z') {
|
||||
event.preventDefault()
|
||||
if (event.shiftKey) {
|
||||
redo()
|
||||
} else {
|
||||
undo()
|
||||
}
|
||||
} else if (command && event.key.toLowerCase() === 'y') {
|
||||
event.preventDefault()
|
||||
redo()
|
||||
} else if (event.key === 'Delete' && selected !== null && selected.duplicable) {
|
||||
event.preventDefault()
|
||||
edit({ op: 'delete', path: selected.path })
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', down)
|
||||
return () => window.removeEventListener('keydown', down)
|
||||
}, [undo, redo, edit, selected, locked])
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
import { useState } from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { PickShare, PickSpread } from '../bridge/types'
|
||||
import { hexColor } from './colors'
|
||||
|
||||
// A long table keeps the options with the most ground in view until asked for all.
|
||||
const SHORT_TABLE_ROWS = 6
|
||||
// An option getting under half or over twice its share of the noise stands out.
|
||||
const FAR_FROM_WEIGHT_FACTOR = 2
|
||||
|
||||
interface NoiseChartProps {
|
||||
spread: PickSpread
|
||||
/** What the noise picks, as the table's heading: "Regions" or "Biomes". */
|
||||
optionNoun: string
|
||||
}
|
||||
|
||||
/**
|
||||
* One noise that picks regions or biomes: how its values in view spread over the bands that pick each option, and a
|
||||
* table of each option's share of the noise against its share of the ground in view (v3e NoisePickChart).
|
||||
*/
|
||||
export function NoiseChart({ spread, optionNoun }: NoiseChartProps): React.JSX.Element {
|
||||
if (spread.rows.length === 1) {
|
||||
return (
|
||||
<section className="py-2.5">
|
||||
<ChartTitle>{spread.title}</ChartTitle>
|
||||
<div className="mt-1.5 flex items-center gap-2 text-[12px]">
|
||||
<OptionName share={spread.rows[0]} rows={spread.rows} />
|
||||
<span className="shrink-0 text-secondary-text">Picked everywhere</span>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<section className="py-2.5">
|
||||
<ChartTitle>{spread.title}</ChartTitle>
|
||||
<Spread spread={spread} />
|
||||
<ShareTable rows={spread.rows} optionNoun={optionNoun} />
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function ChartTitle({ children }: { children: React.ReactNode }): React.JSX.Element {
|
||||
return <h4 className="truncate text-[11px] font-semibold text-muted-foreground">{children}</h4>
|
||||
}
|
||||
|
||||
function Spread({ spread }: { spread: PickSpread }): React.JSX.Element {
|
||||
const peak = Math.max(1, ...spread.histogram)
|
||||
return (
|
||||
<div className="mt-1.5">
|
||||
<div className="relative flex h-12 items-end gap-px">
|
||||
{spread.histogram.map((count, bin) => (
|
||||
<span key={bin} className="flex-1 rounded-t-[1px] bg-secondary-text/45" style={{ height: `${(count / peak) * 100}%` }} />
|
||||
))}
|
||||
{spread.bands.slice(0, -1).map((band, index) => (
|
||||
<span key={index} className="absolute inset-y-0 w-px bg-foreground/20" style={{ left: `${band.to * 100}%` }} />
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-0.5 flex h-2.5 overflow-hidden rounded-[2px]">
|
||||
{spread.bands.map((band, index) => (
|
||||
<span
|
||||
key={index}
|
||||
title={band.option.name}
|
||||
className="h-full"
|
||||
style={{ flexGrow: band.to - band.from, flexBasis: 0, backgroundColor: hexColor(band.option.color) }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-0.5 flex justify-between font-mono text-[10.5px] text-secondary-text">
|
||||
<span>0</span>
|
||||
<span>0.5</span>
|
||||
<span>1</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ShareTable({ rows, optionNoun }: { rows: PickShare[]; optionNoun: string }): React.JSX.Element {
|
||||
const [showsAll, setShowsAll] = useState(false)
|
||||
const long = rows.length > SHORT_TABLE_ROWS
|
||||
const shown = showsAll || !long ? rows : largestInView(rows)
|
||||
return (
|
||||
<div className="mt-2 grid grid-cols-[1fr_auto_auto] items-center gap-x-2.5 gap-y-0.5 text-[12px]">
|
||||
<span className="text-[11px] font-semibold text-muted-foreground">{optionNoun}</span>
|
||||
<span className="text-right text-[11px] font-semibold text-muted-foreground">Weight</span>
|
||||
<span className="text-right text-[11px] font-semibold text-muted-foreground">In view</span>
|
||||
{shown.map((share) => (
|
||||
<ShareRow key={share.option.key} share={share} rows={rows} />
|
||||
))}
|
||||
{long && (
|
||||
<button className="col-span-3 justify-self-start py-0.5 text-link hover:underline" onClick={() => setShowsAll(!showsAll)}>
|
||||
{showsAll ? 'Show fewer' : `Show all ${rows.length} ${optionNoun.toLowerCase()}`}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ShareRow({ share, rows }: { share: PickShare; rows: PickShare[] }): React.JSX.Element {
|
||||
const farFromWeight = share.inView * FAR_FROM_WEIGHT_FACTOR < share.weight || share.inView > share.weight * FAR_FROM_WEIGHT_FACTOR
|
||||
return (
|
||||
<>
|
||||
<OptionName share={share} rows={rows} />
|
||||
<span className="text-right text-secondary-text tabular-nums">{percent(share.weight)}</span>
|
||||
<span className={cn('text-right tabular-nums', farFromWeight && 'text-warning')}>{percent(share.inView)}</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// Two biomes in different folders can share a name, so their keys tell them apart.
|
||||
function OptionName({ share, rows }: { share: PickShare; rows: PickShare[] }): React.JSX.Element {
|
||||
const shared = rows.some((other) => other !== share && other.option.name === share.option.name)
|
||||
return (
|
||||
<span className="flex min-w-0 flex-1 items-center gap-1.5" title={share.option.key}>
|
||||
<span className="size-2.5 shrink-0 rounded-[3px]" style={{ backgroundColor: hexColor(share.option.color) }} />
|
||||
<span className="truncate">{shared ? `${share.option.name} (${share.option.key})` : share.option.name}</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** The rows with the most ground in view, still in the order the noise meets them. */
|
||||
export function largestInView(rows: PickShare[]): PickShare[] {
|
||||
const largest = new Set([...rows].sort((first, second) => second.inView - first.inView).slice(0, SHORT_TABLE_ROWS))
|
||||
return rows.filter((row) => largest.has(row))
|
||||
}
|
||||
|
||||
export function percent(fraction: number): string {
|
||||
if (fraction > 0 && fraction < 0.001) {
|
||||
return '<0.1%'
|
||||
}
|
||||
return `${(fraction * 100).toFixed(1)}%`
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
import { Dices, RotateCcw, Search } from 'lucide-react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
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 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 { SceneViewport } from './SceneViewport'
|
||||
import { TiledCanvas } from './TiledCanvas'
|
||||
|
||||
type NoiseDisplay = 'flat' | 'terrain'
|
||||
|
||||
const NUMBER = new Intl.NumberFormat('en-US', { maximumFractionDigits: 3 })
|
||||
const DEFAULT_SEED = '12345'
|
||||
const TERRAIN_TILES_PER_SIDE = 4
|
||||
const LOWEST_RELIEF_BLOCKS = 1
|
||||
const TALLEST_RELIEF_BLOCKS = 4064
|
||||
const DEFAULT_RELIEF_BLOCKS = 64
|
||||
const RELIEF_STEPS = 1000
|
||||
const SWATCH_STEPS = 24
|
||||
const TOGGLE_ITEM = 'h-7 px-3 text-[12px] data-[state=on]:bg-selection data-[state=on]:text-foreground'
|
||||
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 NoiseStudioProps {
|
||||
client: BridgeClient
|
||||
packRevision: number
|
||||
onSummary(summary: string | null): void
|
||||
tell(message: string): void
|
||||
}
|
||||
|
||||
/** The pack's noise and the built-in styles, from above or as terrain (v3e's noise explorer). */
|
||||
export function NoiseStudio({ client, packRevision, onSummary, tell }: NoiseStudioProps): React.JSX.Element {
|
||||
const sources = useNoiseSources(client, packRevision, tell)
|
||||
const [chosenId, setChosenId] = useState<string | null>(null)
|
||||
const source = sources.find((candidate) => candidate.id === chosenId) ?? sources[0] ?? null
|
||||
const [seed, setSeed] = useState(DEFAULT_SEED)
|
||||
const [paletteId, setPaletteId] = useState<NoisePaletteId>('terrain')
|
||||
const [display, setDisplay] = useState<NoiseDisplay>('flat')
|
||||
const [reliefBlocks, setReliefBlocks] = useState(DEFAULT_RELIEF_BLOCKS)
|
||||
const [status, setStatus] = useState<NoiseStatus | null>(null)
|
||||
const [terrainFraming, setTerrainFraming] = useState<TerrainFraming | null>(null)
|
||||
const controllerRef = useRef<NoiseView | null>(null)
|
||||
const scale = useMemo(() => noiseScale(paletteId, source), [paletteId, source])
|
||||
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 }
|
||||
controllerRef.current?.show(layer, { key: `${paletteId}/${source?.blockRange?.lowest}/${source?.blockRange?.highest}`, scale })
|
||||
}, [source, seed, packRevision, paletteId, scale])
|
||||
|
||||
const showAs = useCallback((next: NoiseDisplay) => {
|
||||
setDisplay(next)
|
||||
if (next === 'terrain') {
|
||||
setTerrainFraming(controllerRef.current?.framing() ?? null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (source === null) {
|
||||
onSummary(null)
|
||||
return
|
||||
}
|
||||
const seedText = source.usesSeed ? `seed ${seed}` : "the world's seed"
|
||||
onSummary(`${source.name} · ${seedText}`)
|
||||
}, [source, seed, onSummary])
|
||||
useEffect(() => () => onSummary(null), [onSummary])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<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 && (
|
||||
<NoiseTerrainView client={client} source={source} seed={seed} revision={packRevision} framing={terrainFraming} scale={scale} reliefBlocks={reliefBlocks} tell={tell} />
|
||||
)}
|
||||
<div className="absolute top-3 left-3 flex items-center gap-2">
|
||||
<ToggleGroup type="single" variant="outline" size="sm" className="bg-card/90" value={display} onValueChange={(value) => value !== '' && showAs(value as NoiseDisplay)}>
|
||||
<ToggleGroupItem value="flat" className={TOGGLE_ITEM} title="The noise from above, coloured by value">
|
||||
2D
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="terrain" className={TOGGLE_ITEM} title="The noise as terrain">
|
||||
3D
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
{display === 'flat' && (
|
||||
<Button variant="outline" size="icon-sm" className="bg-card/90" title="Back to 0, 0" onClick={() => controllerRef.current?.resetView()}>
|
||||
<RotateCcw />
|
||||
</Button>
|
||||
)}
|
||||
{display === 'terrain' && source?.blockRange === null && <ReliefControl blocks={reliefBlocks} onChange={setReliefBlocks} />}
|
||||
</div>
|
||||
{display === 'flat' && status !== null && source !== null && <div className={cn(PILL, 'right-3 bottom-3 tabular-nums')}>{readout(status, source)}</div>}
|
||||
</div>
|
||||
<aside className="flex w-[250px] shrink-0 flex-col border-l bg-card">
|
||||
<header className="px-4 pt-2.5 pb-2.5">
|
||||
<h2 className="text-[13px] font-semibold">Noise</h2>
|
||||
<p className="text-[11.5px] text-secondary-text">{NUMBER.format(sources.length)} sources</p>
|
||||
</header>
|
||||
<SeedField seed={seed} usesSeed={source?.usesSeed ?? true} onChange={setSeed} />
|
||||
<PaletteList current={paletteId} source={source} scale={scale} onSelect={setPaletteId} />
|
||||
<SourceList sources={sources} current={source?.id ?? null} onSelect={setChosenId} />
|
||||
</aside>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function readout(status: NoiseStatus, source: NoiseSource): string {
|
||||
const spot = `${Math.floor(status.cursorX)}, ${Math.floor(status.cursorZ)}`
|
||||
if (status.value === null) {
|
||||
return spot
|
||||
}
|
||||
const value = NUMBER.format(status.value)
|
||||
return `${spot} · ${source.blockRange === null ? value : `${value} blocks`}`
|
||||
}
|
||||
|
||||
function SeedField({ seed, usesSeed, onChange }: { seed: string; usesSeed: boolean; onChange(seed: string): void }): React.JSX.Element {
|
||||
const [draft, setDraft] = useState(seed)
|
||||
useEffect(() => setDraft(seed), [seed])
|
||||
const commit = (): void => {
|
||||
const trimmed = draft.trim()
|
||||
if (/^-?\d{1,19}$/.test(trimmed) && isLong(trimmed)) {
|
||||
onChange(trimmed)
|
||||
} else {
|
||||
setDraft(seed)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="border-t px-4 pt-2.5 pb-3">
|
||||
<h3 className="pb-1.5 text-[11px] font-semibold text-muted-foreground">Seed</h3>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Input
|
||||
value={draft}
|
||||
disabled={!usesSeed}
|
||||
inputMode="numeric"
|
||||
className="h-7 px-2 text-[12px] tabular-nums md:text-[12px]"
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
onBlur={commit}
|
||||
onKeyDown={(event) => event.key === 'Enter' && commit()}
|
||||
/>
|
||||
<Button variant="outline" size="icon-sm" title="Random seed" disabled={!usesSeed} onClick={() => onChange(randomSeed())}>
|
||||
<Dices />
|
||||
</Button>
|
||||
</div>
|
||||
{!usesSeed && <p className="pt-1.5 text-[11.5px] text-secondary-text">Keeps the world's seed</p>}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
const LONG_LIMIT = 2n ** 63n
|
||||
|
||||
function isLong(text: string): boolean {
|
||||
const value = BigInt(text)
|
||||
return value >= -LONG_LIMIT && value < LONG_LIMIT
|
||||
}
|
||||
|
||||
function randomSeed(): string {
|
||||
const [high, low] = crypto.getRandomValues(new Uint32Array(2))
|
||||
return BigInt.asIntN(64, (BigInt(high) << 32n) | BigInt(low)).toString()
|
||||
}
|
||||
|
||||
function PaletteList({
|
||||
current,
|
||||
source,
|
||||
scale,
|
||||
onSelect
|
||||
}: {
|
||||
current: NoisePaletteId
|
||||
source: NoiseSource | null
|
||||
scale: NoiseScale
|
||||
onSelect(palette: NoisePaletteId): void
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<section className="border-t px-2 pt-2.5 pb-2">
|
||||
<h3 className="px-2 pb-1 text-[11px] font-semibold text-muted-foreground">Palette</h3>
|
||||
{NOISE_PALETTES.map((palette) => (
|
||||
<button
|
||||
key={palette.id}
|
||||
onClick={() => onSelect(palette.id)}
|
||||
className={cn('flex h-[26px] w-full items-center gap-2 rounded-md px-2 text-left', palette.id === current ? 'bg-selection' : 'hover:bg-accent')}
|
||||
>
|
||||
<span className="w-[68px] shrink-0 truncate">{palette.label}</span>
|
||||
<span className="h-2.5 min-w-0 flex-1 rounded-[3px]" style={{ background: gradientOf(noiseScale(palette.id, source)) }} />
|
||||
</button>
|
||||
))}
|
||||
<p className="flex justify-between px-2 pt-1 text-[11px] text-secondary-text tabular-nums">
|
||||
<span>{NUMBER.format(scale.minimum)}</span>
|
||||
<span>{source?.blockRange === null ? '' : 'blocks above the fluid'}</span>
|
||||
<span>{NUMBER.format(scale.maximum)}</span>
|
||||
</p>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function gradientOf(scale: NoiseScale): string {
|
||||
const stops = Array.from({ length: SWATCH_STEPS + 1 }, (_, step) => hexColor(scale.colorAlong(step / SWATCH_STEPS)))
|
||||
return `linear-gradient(to right, ${stops.join(', ')})`
|
||||
}
|
||||
|
||||
function SourceList({ sources, current, onSelect }: { sources: NoiseSource[]; current: string | null; onSelect(id: string): void }): React.JSX.Element {
|
||||
const [filter, setFilter] = useState('')
|
||||
const shown = sources.filter((source) => source.name.toLowerCase().includes(filter.trim().toLowerCase()))
|
||||
const categories = [...new Set(shown.map((source) => source.category))]
|
||||
return (
|
||||
<section className="flex min-h-0 flex-1 flex-col border-t">
|
||||
<div className="relative px-3 pt-2.5 pb-1.5">
|
||||
<Search className="pointer-events-none absolute top-[15px] left-5 size-3.5 text-muted-foreground" />
|
||||
<Input value={filter} placeholder="Search" className="h-7 pl-7 text-[12px] md:text-[12px]" onChange={(event) => setFilter(event.target.value)} />
|
||||
</div>
|
||||
<ScrollArea className="min-h-0 flex-1">
|
||||
<div className="px-2 pb-1.5">
|
||||
{categories.map((category) => (
|
||||
<section key={category}>
|
||||
<h3 className="truncate px-2 pt-2 pb-1 text-[11px] font-semibold text-muted-foreground">{category}</h3>
|
||||
{shown
|
||||
.filter((source) => source.category === category)
|
||||
.map((source) => (
|
||||
<button
|
||||
key={source.id}
|
||||
title={source.id}
|
||||
onClick={() => onSelect(source.id)}
|
||||
className={cn('flex h-[26px] w-full items-center rounded-md px-2 text-left', source.id === current ? 'bg-selection' : 'hover:bg-accent')}
|
||||
>
|
||||
<span className="truncate">{source.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
{shown.length === 0 && <p className="px-2 py-1 text-[12px] text-muted-foreground">Nothing to show</p>}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** How many blocks the highest noise rises above the lowest, on a scale that gives low reliefs room. */
|
||||
function ReliefControl({ blocks, onChange }: { blocks: number; onChange(blocks: number): void }): React.JSX.Element {
|
||||
const span = Math.log(TALLEST_RELIEF_BLOCKS) - Math.log(LOWEST_RELIEF_BLOCKS)
|
||||
const step = Math.round(((Math.log(blocks) - Math.log(LOWEST_RELIEF_BLOCKS)) / span) * RELIEF_STEPS)
|
||||
return (
|
||||
<label className="flex h-8 items-center gap-2 rounded-md border bg-card/90 px-3 text-[12px] text-secondary-text" title="How many blocks the highest noise rises above the lowest">
|
||||
Relief
|
||||
<input
|
||||
type="range"
|
||||
min={0}
|
||||
max={RELIEF_STEPS}
|
||||
value={step}
|
||||
className="w-28 accent-primary"
|
||||
onChange={(event) => onChange(Math.round(Math.exp(Math.log(LOWEST_RELIEF_BLOCKS) + (Number(event.target.value) / RELIEF_STEPS) * span)))}
|
||||
/>
|
||||
<span className="w-[72px] text-foreground tabular-nums">{NUMBER.format(blocks)} blocks</span>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
|
||||
function NoiseTerrainView({
|
||||
client,
|
||||
source,
|
||||
seed,
|
||||
revision,
|
||||
framing,
|
||||
scale,
|
||||
reliefBlocks,
|
||||
tell
|
||||
}: {
|
||||
client: BridgeClient
|
||||
source: NoiseSource
|
||||
seed: string
|
||||
revision: number
|
||||
framing: TerrainFraming
|
||||
scale: NoiseScale
|
||||
reliefBlocks: number
|
||||
tell(message: string): void
|
||||
}): React.JSX.Element {
|
||||
const area = useNoiseArea(client, source.id, seed, revision, framing, tell)
|
||||
const mesh = useMemo(() => (area === null ? null : buildTerrainMesh(new NoiseTerrain(area, source, scale, reliefBlocks))), [area, source, scale, reliefBlocks])
|
||||
useEffect(() => () => mesh?.dispose(), [mesh])
|
||||
return (
|
||||
<div className="absolute inset-0">
|
||||
<SceneViewport content={mesh?.content ?? null} framing={area} />
|
||||
{area === null && <div className={cn(PILL, 'top-3 left-1/2 -translate-x-1/2')}>Sampling {source.name}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The square of tiles around where the 2D view looked, at the scale it drew; every tile arrives before it is shown. */
|
||||
function useNoiseArea(
|
||||
client: BridgeClient,
|
||||
sourceId: string,
|
||||
seed: string,
|
||||
revision: number,
|
||||
framing: TerrainFraming,
|
||||
tell: (message: string) => void
|
||||
): NoiseArea | null {
|
||||
const [area, setArea] = useState<NoiseArea | null>(null)
|
||||
useEffect(() => {
|
||||
const stop = new AbortController()
|
||||
const tileBlocks = NOISE_TILE_PIXELS * framing.renderScale
|
||||
const firstTileX = Math.floor(framing.centerX / tileBlocks - TERRAIN_TILES_PER_SIDE / 2)
|
||||
const firstTileZ = Math.floor(framing.centerZ / tileBlocks - TERRAIN_TILES_PER_SIDE / 2)
|
||||
const rows = Array.from({ length: TERRAIN_TILES_PER_SIDE }, (_, row) =>
|
||||
Promise.all(
|
||||
Array.from({ length: TERRAIN_TILES_PER_SIDE }, (_, column) =>
|
||||
client.noiseTile(sourceId, seed, firstTileX + column, firstTileZ + row, framing.renderScale, NOISE_TILE_PIXELS, stop.signal)
|
||||
)
|
||||
)
|
||||
)
|
||||
setArea(null)
|
||||
Promise.all(rows)
|
||||
.then((tiles: NoiseTile[][]) =>
|
||||
setArea({ tiles, originX: firstTileX * tileBlocks, originZ: firstTileZ * tileBlocks, blocksPerValue: framing.renderScale })
|
||||
)
|
||||
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
|
||||
return () => stop.abort()
|
||||
}, [client, sourceId, seed, revision, framing, tell])
|
||||
return area
|
||||
}
|
||||
|
||||
function useNoiseSources(client: BridgeClient, packRevision: number, tell: (message: string) => void): NoiseSource[] {
|
||||
const [sources, setSources] = useState<NoiseSource[]>([])
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
client
|
||||
.noiseSources()
|
||||
.then((found) => active && setSources(found))
|
||||
.catch((failure: Error) => active && tell(failure.message))
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [client, packRevision, tell])
|
||||
return sources
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
|
||||
import type { PickDisplay, PickInspection, PickSection } from '../bridge/types'
|
||||
import { hexColor } from './colors'
|
||||
import { NoiseChart, percent } from './NoiseChart'
|
||||
|
||||
// The chosen display reads like the toolbar's switched-on toggles.
|
||||
const DISPLAY_ITEM = 'h-7 text-[12px] data-[state=on]:bg-selection data-[state=on]:text-foreground'
|
||||
|
||||
interface PickInspectorProps {
|
||||
/** What is inspected: "Regions", "Biomes", or the previewed region's name. */
|
||||
title: string
|
||||
/** What the map shows when it draws the picks: "Regions" or "Biomes". */
|
||||
picksLabel: string
|
||||
/** The latest measurement of the view; null until the first one arrives. */
|
||||
inspection: PickInspection | null
|
||||
display: PickDisplay
|
||||
onDisplay(display: PickDisplay): void
|
||||
}
|
||||
|
||||
/**
|
||||
* How noise picks the regions or biomes in view, measured against what is in view, with a switch for how the map
|
||||
* draws the picks (v3e PickInspectorPanel).
|
||||
*/
|
||||
export function PickInspector({ title, picksLabel, inspection, display, onDisplay }: PickInspectorProps): React.JSX.Element {
|
||||
return (
|
||||
<section className="flex min-h-0 flex-[7] flex-col border-b">
|
||||
<header className="px-4 pt-2.5 pb-2.5">
|
||||
<h2 className="truncate text-[13px] font-semibold">{title}</h2>
|
||||
<p className="truncate text-[11.5px] text-secondary-text">{inspection?.detail ?? 'Measuring what is in view…'}</p>
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="mt-2 w-full"
|
||||
value={display}
|
||||
onValueChange={(value) => value !== '' && onDisplay(value as PickDisplay)}
|
||||
>
|
||||
<ToggleGroupItem value="picks" className={DISPLAY_ITEM}>
|
||||
{picksLabel}
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="noise" className={DISPLAY_ITEM}>
|
||||
Noise
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="both" className={DISPLAY_ITEM}>
|
||||
Both
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</header>
|
||||
<ScrollArea className="min-h-0 flex-1 border-t">
|
||||
<div className="px-4 pb-2">{inspection !== null && <Sections sections={inspection.sections} />}</div>
|
||||
</ScrollArea>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// A single section is the whole view, so its charts stand on their own; several are one region each, folded.
|
||||
function Sections({ sections }: { sections: PickSection[] }): React.JSX.Element {
|
||||
const [opened, setOpened] = useState<Set<string> | null>(null)
|
||||
if (sections.length === 1) {
|
||||
return <Charts section={sections[0]} />
|
||||
}
|
||||
const open = opened ?? new Set(sections.slice(0, 1).map(sectionKey))
|
||||
const toggle = (key: string): void => {
|
||||
const next = new Set(open)
|
||||
if (!next.delete(key)) {
|
||||
next.add(key)
|
||||
}
|
||||
setOpened(next)
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{sections.map((section) => (
|
||||
<RegionSection key={sectionKey(section)} section={section} open={open.has(sectionKey(section))} onToggle={() => toggle(sectionKey(section))} />
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function RegionSection({ section, open, onToggle }: { section: PickSection; open: boolean; onToggle(): void }): React.JSX.Element {
|
||||
const region = section.region
|
||||
return (
|
||||
<div className="border-b last:border-b-0">
|
||||
<button className="-mx-1.5 flex w-[calc(100%+12px)] items-center gap-2 rounded-md px-1.5 py-2 text-left hover:bg-accent" onClick={onToggle}>
|
||||
<ChevronRight className={`size-3.5 shrink-0 text-secondary-text transition-transform ${open ? 'rotate-90' : ''}`} />
|
||||
{region !== null && <span className="size-2.5 shrink-0 rounded-[3px]" style={{ backgroundColor: hexColor(region.color) }} />}
|
||||
<span className="min-w-0 flex-1 truncate font-medium">{region?.name ?? 'Regions'}</span>
|
||||
<span className="shrink-0 text-[11.5px] text-secondary-text tabular-nums">
|
||||
{percent(section.share)} · {section.biomeCount === 1 ? '1 biome' : `${section.biomeCount} biomes`}
|
||||
</span>
|
||||
</button>
|
||||
{open && <Charts section={section} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Charts({ section }: { section: PickSection }): React.JSX.Element {
|
||||
const optionNoun = section.region === null ? 'Regions' : 'Biomes'
|
||||
return (
|
||||
<div className="divide-y">
|
||||
{section.spreads.map((spread) => (
|
||||
<NoiseChart key={spread.title} spread={spread} optionNoun={optionNoun} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function sectionKey(section: PickSection): string {
|
||||
return section.region?.key ?? ''
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { PickBand, PickStep } from '../bridge/types'
|
||||
import { hexColor } from './colors'
|
||||
|
||||
// Gaps between bands shrink as there are more of them, so many thin bands still read as a bar.
|
||||
const WIDE_GAP_MOST_BANDS = 18
|
||||
const NARROW_GAP_MOST_BANDS = 50
|
||||
/** Why a step that nothing picked has its label. */
|
||||
const UNPICKED_NOTES: Partial<Record<PickStep['kind'], string>> = { FOCUS: 'Focus', IMAGE_MAP: 'Image map', PREVIEW: 'Preview' }
|
||||
|
||||
/** How the spot got its region and biome: one row per pick, the noise value marked on every option's share of it. */
|
||||
export function PickRows({ path }: { path: PickStep[] }): React.JSX.Element | null {
|
||||
if (path.length === 0) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<div className="mt-2 grid grid-cols-[auto_1fr_auto] items-center gap-x-2.5 gap-y-1.5 text-[11.5px]">
|
||||
{path.map((step, index) => (
|
||||
<PickRow key={index} step={step} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PickRow({ step }: { step: PickStep }): React.JSX.Element {
|
||||
return (
|
||||
<>
|
||||
<span className="text-muted-foreground">{rowLabel(step)}</span>
|
||||
{step.noise === null ? (
|
||||
<span className="truncate text-secondary-text">{UNPICKED_NOTES[step.kind] ?? ''}</span>
|
||||
) : (
|
||||
<NoiseBar bands={step.bands} noise={step.noise} />
|
||||
)}
|
||||
<span className="text-right font-mono text-[11px] text-secondary-text tabular-nums">{step.noise === null ? '' : step.noise.toFixed(3)}</span>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function NoiseBar({ bands, noise }: { bands: PickBand[]; noise: number }): React.JSX.Element {
|
||||
const picked = pickedBandIndex(bands, noise)
|
||||
const gap = bands.length <= WIDE_GAP_MOST_BANDS ? 2 : bands.length <= NARROW_GAP_MOST_BANDS ? 1 : 0
|
||||
return (
|
||||
<div className="relative flex h-1.5 min-w-0" style={{ gap }}>
|
||||
{bands.map((band, index) => (
|
||||
<span
|
||||
key={index}
|
||||
className="h-full min-w-px rounded-[2px]"
|
||||
style={{
|
||||
flexGrow: band.to - band.from,
|
||||
flexBasis: 0,
|
||||
backgroundColor: index === picked ? hexColor(band.option.color) : 'var(--overlay-border)'
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
<span
|
||||
className="absolute top-1/2 h-3 w-0.5 -translate-x-1/2 -translate-y-1/2 bg-foreground shadow-[0_0_0_1px_var(--popover)]"
|
||||
style={{ left: `${Math.min(1, Math.max(0, noise)) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** The first band the noise does not pass; values beyond 1 pick the last, as the generator does. */
|
||||
export function pickedBandIndex(bands: PickBand[], noise: number): number {
|
||||
const index = bands.findIndex((band) => noise <= band.to)
|
||||
return index === -1 ? bands.length - 1 : index
|
||||
}
|
||||
|
||||
function rowLabel(step: PickStep): string {
|
||||
switch (step.kind) {
|
||||
case 'REGION':
|
||||
return 'Region'
|
||||
case 'BIOME':
|
||||
return step.list === null ? 'Biome' : step.list.charAt(0).toUpperCase() + step.list.slice(1)
|
||||
case 'CHILD':
|
||||
return 'Child'
|
||||
case 'IMAGE_MAP':
|
||||
case 'FOCUS':
|
||||
case 'PREVIEW':
|
||||
return step.picked.kind === 'REGION' ? 'Region' : 'Biome'
|
||||
}
|
||||
}
|
||||
|
||||
/** The parent the spot's biome replaced, when a child step replaced one. */
|
||||
export function replacedParent(path: PickStep[]): string | null {
|
||||
return path.findLast((step) => step.kind === 'CHILD' && step.replaced !== null)?.replaced ?? null
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { useState } from 'react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { MapLabel } from '../bridge/types'
|
||||
import { hexColor } from './colors'
|
||||
|
||||
// Short lists are scanned at a glance; longer ones get a search field.
|
||||
const SEARCHABLE_FROM_REGIONS = 8
|
||||
|
||||
interface RegionPreviewListProps {
|
||||
regions: MapLabel[]
|
||||
/** The previewed region's key, or null for all regions. */
|
||||
current: string | null
|
||||
onSelect(regionKey: string | null): void
|
||||
}
|
||||
|
||||
/** The region view's regions, any of which can fill the map with its biomes, or all of them as they are (v3e RegionNavigator). */
|
||||
export function RegionPreviewList({ regions, current, onSelect }: RegionPreviewListProps): React.JSX.Element {
|
||||
const [search, setSearch] = useState('')
|
||||
const wanted = search.trim().toLowerCase()
|
||||
const shown = wanted === '' ? regions : regions.filter((region) => `${region.name} ${region.key}`.toLowerCase().includes(wanted))
|
||||
return (
|
||||
<section>
|
||||
<h2 className="px-2 pt-1 pb-1.5 text-[11px] font-semibold text-muted-foreground">Preview a region</h2>
|
||||
{regions.length >= SEARCHABLE_FROM_REGIONS && (
|
||||
<Input
|
||||
className="mb-1 h-7 text-[12px]"
|
||||
placeholder="Find a region"
|
||||
value={search}
|
||||
onChange={(event) => setSearch(event.target.value)}
|
||||
onKeyDown={(event) => event.key === 'Escape' && setSearch('')}
|
||||
/>
|
||||
)}
|
||||
<RegionRow name="All regions" color={null} selected={current === null} onSelect={() => onSelect(null)} />
|
||||
{shown.map((region) => (
|
||||
<RegionRow
|
||||
key={region.key}
|
||||
name={region.name}
|
||||
color={region.color}
|
||||
title={region.key}
|
||||
selected={region.key === current}
|
||||
onSelect={() => onSelect(region.key)}
|
||||
/>
|
||||
))}
|
||||
{shown.length === 0 && <p className="px-2 py-1 text-[12px] text-muted-foreground">No region matches</p>}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
interface RegionRowProps {
|
||||
name: string
|
||||
color: number | null
|
||||
title?: string
|
||||
selected: boolean
|
||||
onSelect(): void
|
||||
}
|
||||
|
||||
function RegionRow({ name, color, title, selected, onSelect }: RegionRowProps): React.JSX.Element {
|
||||
return (
|
||||
<button
|
||||
onClick={onSelect}
|
||||
title={title}
|
||||
className={cn('flex h-[26px] w-full items-center gap-2 rounded-md px-2 text-left', selected ? 'bg-selection' : 'hover:bg-accent')}
|
||||
>
|
||||
<span
|
||||
className={cn('size-3 shrink-0 rounded-[3px]', color === null && 'border border-secondary-text/60')}
|
||||
style={color === null ? undefined : { backgroundColor: hexColor(color) }}
|
||||
/>
|
||||
<span className="truncate">{name}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import { RotateCw } from 'lucide-react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { BridgeError, STATUS_NOT_FOUND, type BridgeClient } from '../bridge/BridgeClient'
|
||||
import type { SavedStart, SavedTile, SavedWorldInfo, WorldInfo } from '../bridge/types'
|
||||
import { BlockColors } from '../scene/blockColors'
|
||||
import { BlockModels } from '../scene/blockModels'
|
||||
import { BridgeAssets } from '../scene/BridgeAssets'
|
||||
import { SavedTerrain, type SavedTerrainArea, type SavedTerrainColoring } from '../scene/savedTerrain'
|
||||
import { buildTerrainMesh } from '../scene/terrainMesh'
|
||||
import { SceneViewport } from './SceneViewport'
|
||||
|
||||
const NUMBER = new Intl.NumberFormat('en-US')
|
||||
const TILES_PER_SIDE = 4
|
||||
const TILE_PIXELS = 128
|
||||
const BLOCKS_PER_PIXEL = 2
|
||||
const TILE_BLOCKS = TILE_PIXELS * BLOCKS_PER_PIXEL
|
||||
const NO_COLORS = new Map<string, number>()
|
||||
const COLORING_ITEM = 'h-7 px-3 text-[12px] data-[state=on]:bg-selection data-[state=on]:text-foreground'
|
||||
const PILL = 'pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 rounded-md border border-overlay-border bg-card/90 px-3 py-1.5 text-[12px] text-secondary-text'
|
||||
|
||||
interface SavedWorldStudioProps {
|
||||
client: BridgeClient
|
||||
/** The studio's own world, whose saved copy is chosen first. */
|
||||
world: WorldInfo
|
||||
onSummary(summary: string | null): void
|
||||
tell(message: string): void
|
||||
}
|
||||
|
||||
/** A world as its region files hold it, in 3D, around the region nearest its origin (v3e's saved world explorer). */
|
||||
export function SavedWorldStudio({ client, world, onSummary, tell }: SavedWorldStudioProps): React.JSX.Element {
|
||||
const worlds = useSavedWorlds(client, tell)
|
||||
const [chosenId, setChosenId] = useState<string | null>(null)
|
||||
const chosen = worlds.find((candidate) => candidate.id === chosenId) ?? ownWorldAmong(worlds, world) ?? worlds[0] ?? null
|
||||
const [coloring, setColoring] = useState<SavedTerrainColoring>('biomes')
|
||||
const [readings, setReadings] = useState(0)
|
||||
const { start, area, reading } = useSavedArea(client, chosen?.id ?? null, readings, tell)
|
||||
const blockColors = useBlockColors(client, coloring === 'blocks' ? area : null)
|
||||
const mesh = useMemo(() => {
|
||||
if (area === null || start === null || (coloring === 'blocks' && blockColors === null)) {
|
||||
return null
|
||||
}
|
||||
return buildTerrainMesh(new SavedTerrain(area, coloring, start.seaLevel, blockColors ?? NO_COLORS))
|
||||
}, [area, start, coloring, blockColors])
|
||||
|
||||
useEffect(() => () => mesh?.dispose(), [mesh])
|
||||
useEffect(() => {
|
||||
if (chosen === null || start === null) {
|
||||
onSummary(null)
|
||||
return
|
||||
}
|
||||
const side = NUMBER.format(TILES_PER_SIDE * TILE_BLOCKS)
|
||||
onSummary(`${chosen.name} · ${side} × ${side} blocks around ${NUMBER.format(start.centerX)}, ${NUMBER.format(start.centerZ)}`)
|
||||
}, [chosen, start, onSummary])
|
||||
useEffect(() => () => onSummary(null), [onSummary])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<SceneViewport content={mesh?.content ?? null} framing={area} />
|
||||
<div className="absolute top-3 left-3 flex items-center gap-2">
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="bg-card/90"
|
||||
value={coloring}
|
||||
onValueChange={(value) => value !== '' && setColoring(value as SavedTerrainColoring)}
|
||||
>
|
||||
<ToggleGroupItem value="biomes" className={COLORING_ITEM}>
|
||||
Biomes
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="blocks" className={COLORING_ITEM}>
|
||||
Blocks
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="height" className={COLORING_ITEM}>
|
||||
Height
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
<Button variant="outline" size="icon-sm" className="bg-card/90" title="Read again" disabled={reading} onClick={() => setReadings((count) => count + 1)}>
|
||||
<RotateCw />
|
||||
</Button>
|
||||
</div>
|
||||
{reading && chosen !== null && <div className={PILL}>Reading {chosen.name}</div>}
|
||||
{!reading && chosen !== null && start === null && <div className={PILL}>Nothing finished is saved in {chosen.name}</div>}
|
||||
</div>
|
||||
<aside className="flex w-[250px] shrink-0 flex-col border-l bg-card">
|
||||
<header className="px-4 pt-2.5 pb-2.5">
|
||||
<h2 className="text-[13px] font-semibold">Saved worlds</h2>
|
||||
<p className="text-[11.5px] text-secondary-text">{NUMBER.format(worlds.length)} on the server</p>
|
||||
</header>
|
||||
<ScrollArea className="min-h-0 flex-1 border-t">
|
||||
<WorldList worlds={worlds} current={chosen?.id ?? null} onSelect={setChosenId} />
|
||||
</ScrollArea>
|
||||
</aside>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function WorldList({ worlds, current, onSelect }: { worlds: SavedWorldInfo[]; current: string | null; onSelect(id: string): void }): React.JSX.Element {
|
||||
const namespaces = [...new Set(worlds.map((world) => world.namespace))]
|
||||
return (
|
||||
<div className="px-2 py-1.5">
|
||||
{namespaces.map((namespace) => (
|
||||
<section key={namespace}>
|
||||
<h3 className="truncate px-2 pt-2 pb-1 text-[11px] font-semibold text-muted-foreground">{namespace}</h3>
|
||||
{worlds
|
||||
.filter((world) => world.namespace === namespace)
|
||||
.map((world) => (
|
||||
<button
|
||||
key={world.id}
|
||||
title={world.id}
|
||||
onClick={() => onSelect(world.id)}
|
||||
className={cn('flex h-[26px] w-full items-center rounded-md px-2 text-left', world.id === current ? 'bg-selection' : 'hover:bg-accent')}
|
||||
>
|
||||
<span className="truncate">{world.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
{worlds.length === 0 && <p className="px-2 py-1 text-[12px] text-muted-foreground">Nothing to show</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// The studio's world folder is named after its dimension, so world_iris_procfix is saved as iris/procfix.
|
||||
function ownWorldAmong(worlds: SavedWorldInfo[], world: WorldInfo): SavedWorldInfo | undefined {
|
||||
return worlds.find((candidate) => world.world.endsWith(`_${candidate.name}`) || world.world === candidate.name)
|
||||
}
|
||||
|
||||
function useSavedWorlds(client: BridgeClient, tell: (message: string) => void): SavedWorldInfo[] {
|
||||
const [worlds, setWorlds] = useState<SavedWorldInfo[]>([])
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
client
|
||||
.savedWorlds()
|
||||
.then((found) => active && setWorlds(found))
|
||||
.catch((failure: Error) => active && tell(failure.message))
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [client, tell])
|
||||
return worlds
|
||||
}
|
||||
|
||||
/** Where the chosen world's view opens and the square of tiles around it; every tile arrives before it is shown. */
|
||||
function useSavedArea(
|
||||
client: BridgeClient,
|
||||
worldId: string | null,
|
||||
readings: number,
|
||||
tell: (message: string) => void
|
||||
): { start: SavedStart | null; area: SavedTerrainArea | null; reading: boolean } {
|
||||
const [start, setStart] = useState<SavedStart | null>(null)
|
||||
const [area, setArea] = useState<SavedTerrainArea | null>(null)
|
||||
const [reading, setReading] = useState(false)
|
||||
useEffect(() => {
|
||||
if (worldId === null) {
|
||||
return
|
||||
}
|
||||
const stop = new AbortController()
|
||||
setReading(true)
|
||||
setStart(null)
|
||||
setArea(null)
|
||||
readSavedArea(client, worldId, stop.signal)
|
||||
.then((found) => {
|
||||
setStart(found?.start ?? null)
|
||||
setArea(found?.area ?? null)
|
||||
})
|
||||
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
|
||||
.finally(() => !stop.signal.aborted && setReading(false))
|
||||
return () => stop.abort()
|
||||
}, [client, worldId, readings, tell])
|
||||
return { start, area, reading }
|
||||
}
|
||||
|
||||
async function readSavedArea(client: BridgeClient, worldId: string, signal: AbortSignal): Promise<{ start: SavedStart; area: SavedTerrainArea } | null> {
|
||||
let start: SavedStart
|
||||
try {
|
||||
start = await client.savedStart(worldId, signal)
|
||||
} catch (failure) {
|
||||
if (failure instanceof BridgeError && failure.status === STATUS_NOT_FOUND) {
|
||||
return null
|
||||
}
|
||||
throw failure
|
||||
}
|
||||
const firstTileX = Math.floor(start.centerX / TILE_BLOCKS - TILES_PER_SIDE / 2)
|
||||
const firstTileZ = Math.floor(start.centerZ / TILE_BLOCKS - TILES_PER_SIDE / 2)
|
||||
const tiles: SavedTile[][] = await Promise.all(
|
||||
Array.from({ length: TILES_PER_SIDE }, (_, row) =>
|
||||
Promise.all(
|
||||
Array.from({ length: TILES_PER_SIDE }, (_, column) =>
|
||||
client.savedTile(worldId, firstTileX + column, firstTileZ + row, BLOCKS_PER_PIXEL, TILE_PIXELS, signal)
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
return { start, area: { tiles, originX: firstTileX * TILE_BLOCKS, originZ: firstTileZ * TILE_BLOCKS } }
|
||||
}
|
||||
|
||||
/** The colour of every block in the area, read from the client's textures, or null until they are read. */
|
||||
function useBlockColors(client: BridgeClient, area: SavedTerrainArea | null): Map<string, number> | null {
|
||||
const colors = useMemo(() => {
|
||||
const images = new BridgeAssets(client, () => {})
|
||||
return new BlockColors(new BlockModels(images), images)
|
||||
}, [client])
|
||||
const [read, setRead] = useState<Map<string, number> | null>(null)
|
||||
useEffect(() => {
|
||||
setRead(null)
|
||||
if (area === null) {
|
||||
return
|
||||
}
|
||||
let active = true
|
||||
const blocks = area.tiles.flat().flatMap((tile) => tile.blockNames)
|
||||
colors.colorsOf(blocks).then((found) => active && setRead(found))
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [colors, area])
|
||||
return read
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import { ChevronLeft, ChevronRight } from 'lucide-react'
|
||||
import { useEffect, useMemo, 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 { JsonPath, SceneEntry, SceneViewInfo } from '../bridge/types'
|
||||
import { parsedText } from '../editor/jsonValues'
|
||||
import { nodeWithPath } from '../editor/nodeLayout'
|
||||
import { useNodeEditor } from '../editor/useNodeEditor'
|
||||
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 { NodeInspector } from './NodeInspector'
|
||||
import { NodePane } from './NodePane'
|
||||
import { SceneViewport } from './SceneViewport'
|
||||
|
||||
const NUMBER = new Intl.NumberFormat('en-US')
|
||||
const DEFAULT_NAMESPACE_PREFIX = 'minecraft:'
|
||||
|
||||
interface SceneStudioProps {
|
||||
client: BridgeClient
|
||||
view: SceneViewInfo
|
||||
/** 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. */
|
||||
onSummary(summary: string | null): void
|
||||
tell(message: string): void
|
||||
}
|
||||
|
||||
/**
|
||||
* A scene view: its entries on the right, the chosen one in 3D in the middle, with the blocks it is made of. An
|
||||
* editable view shows the entry's file as nodes under the scene, and the chosen node's settings on the right.
|
||||
*/
|
||||
export function SceneStudio({ client, view, packRevision, onSummary, tell }: SceneStudioProps): React.JSX.Element {
|
||||
const [waiting, setWaiting] = useState<string | null>(null)
|
||||
const images = useMemo(() => new BridgeAssets(client, setWaiting), [client])
|
||||
const models = useMemo(() => new BlockModels(images), [images])
|
||||
const entries = useSceneEntries(client, view.id, packRevision, tell)
|
||||
const [chosen, setChosen] = useState<{ key: string; variant: number } | null>(null)
|
||||
const entry = entries.find((candidate) => candidate.key === chosen?.key) ?? entries[0] ?? null
|
||||
const variant = entry !== null && chosen?.key === entry.key ? Math.min(chosen.variant, entry.variants - 1) : 0
|
||||
const { scene, mesh, building } = useSceneMesh(client, view.id, entry, variant, packRevision, models, images, tell)
|
||||
const chooseVariant = (next: number): void => {
|
||||
if (entry !== null) {
|
||||
setChosen({ key: entry.key, variant: (next + entry.variants) % entry.variants })
|
||||
}
|
||||
}
|
||||
|
||||
const editor = useNodeEditor(client, view.id, view.editable ? (entry?.key ?? null) : null, packRevision, tell)
|
||||
const [selectedPath, setSelectedPath] = useState<JsonPath | null>(null)
|
||||
const selected = editor.state?.roots != null && selectedPath !== null ? nodeWithPath(editor.state.roots, selectedPath) : null
|
||||
const values = useMemo(() => (editor.state === null ? undefined : parsedText(editor.state.text)), [editor.state])
|
||||
|
||||
useEffect(() => onSummary(entry === null || scene === null ? null : summaryOf(entry, scene)), [entry, scene, onSummary])
|
||||
useEffect(() => () => onSummary(null), [onSummary])
|
||||
useEffect(() => setSelectedPath(null), [entry?.key])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<SceneArea
|
||||
entry={entry}
|
||||
variant={variant}
|
||||
mesh={mesh}
|
||||
status={building && entry !== null ? (waiting ?? `Building ${entry.name}`) : null}
|
||||
onVariant={chooseVariant}
|
||||
/>
|
||||
{view.editable && entry !== null && (
|
||||
<NodePane editor={editor} entryKey={entry.key} selected={selected} onSelect={(node) => setSelectedPath(node?.path ?? null)} />
|
||||
)}
|
||||
</div>
|
||||
<aside className={cn('flex shrink-0 flex-col border-l bg-card', view.editable ? 'w-[300px]' : 'w-[250px]')}>
|
||||
<EntryBrowser className={selected === null ? 'flex-[7]' : 'flex-[3]'} title={view.label} entries={entries} current={entry?.key ?? null} onSelect={(key) => setChosen({ key, variant: 0 })} />
|
||||
{selected !== null && editor.state !== null ? (
|
||||
<NodeInspector key={JSON.stringify(selected.path)} node={selected} state={editor.state} values={values} onEdit={editor.edit} />
|
||||
) : (
|
||||
<BlockList scene={scene} />
|
||||
)}
|
||||
</aside>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
interface SceneAreaProps {
|
||||
entry: SceneEntry | null
|
||||
variant: number
|
||||
mesh: SceneMesh | null
|
||||
/** What is being built, or null when nothing is. */
|
||||
status: string | null
|
||||
onVariant(variant: number): void
|
||||
}
|
||||
|
||||
function SceneArea({ entry, variant, mesh, status, onVariant }: SceneAreaProps): React.JSX.Element {
|
||||
return (
|
||||
<div className="relative min-h-0 flex-[11]">
|
||||
<SceneViewport content={mesh?.content ?? null} framing={mesh} />
|
||||
{entry !== null && entry.variants > 1 && (
|
||||
<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">
|
||||
<Button variant="ghost" size="icon-sm" title="Previous variant" onClick={() => onVariant(variant - 1)}>
|
||||
<ChevronLeft />
|
||||
</Button>
|
||||
<span className="px-1">
|
||||
Variant {variant + 1} of {entry.variants}
|
||||
</span>
|
||||
<Button variant="ghost" size="icon-sm" title="Next variant" onClick={() => onVariant(variant + 1)}>
|
||||
<ChevronRight />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{status !== null && (
|
||||
<div className="pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 rounded-md border border-overlay-border bg-card/90 px-3 py-1.5 text-[12px] text-secondary-text">
|
||||
{status}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function summaryOf(entry: SceneEntry, scene: BlockScene): string {
|
||||
const [width, height, depth] = [0, 1, 2].map((axis) => scene.max[axis] - scene.min[axis])
|
||||
const blocks = scene.blocks.length / INTS_PER_BLOCK
|
||||
return `${entry.key} · ${NUMBER.format(blocks)} blocks · ${width} × ${height} × ${depth}`
|
||||
}
|
||||
|
||||
function useSceneEntries(client: BridgeClient, viewId: string, packRevision: number, tell: (message: string) => void): SceneEntry[] {
|
||||
const [entries, setEntries] = useState<SceneEntry[]>([])
|
||||
useEffect(() => {
|
||||
let active = true
|
||||
client
|
||||
.sceneEntries(viewId)
|
||||
.then((found) => active && setEntries(found))
|
||||
.catch((failure: Error) => active && tell(failure.message))
|
||||
return () => {
|
||||
active = false
|
||||
}
|
||||
}, [client, viewId, packRevision, tell])
|
||||
return entries
|
||||
}
|
||||
|
||||
/** The chosen entry's scene and its mesh; a newer choice abandons an older one, and a replaced mesh is freed. */
|
||||
function useSceneMesh(
|
||||
client: BridgeClient,
|
||||
viewId: string,
|
||||
entry: SceneEntry | null,
|
||||
variant: number,
|
||||
packRevision: number,
|
||||
models: BlockModels,
|
||||
images: BridgeAssets,
|
||||
tell: (message: string) => void
|
||||
): { scene: BlockScene | null; mesh: SceneMesh | null; building: boolean } {
|
||||
const [scene, setScene] = useState<BlockScene | null>(null)
|
||||
const [mesh, setMesh] = useState<SceneMesh | null>(null)
|
||||
const [building, setBuilding] = useState(false)
|
||||
const key = entry?.key ?? null
|
||||
|
||||
useEffect(() => {
|
||||
if (key === null) {
|
||||
return
|
||||
}
|
||||
const stop = new AbortController()
|
||||
setBuilding(true)
|
||||
client
|
||||
.scene(viewId, key, variant, stop.signal)
|
||||
.then(async (found) => {
|
||||
const built = await buildSceneMesh(found, models, images)
|
||||
if (stop.signal.aborted) {
|
||||
disposeMesh(built)
|
||||
return
|
||||
}
|
||||
setScene(found)
|
||||
setMesh(built)
|
||||
if (built.unknownStates.length > 0) {
|
||||
tell(`No model for ${built.unknownStates.length === 1 ? built.unknownStates[0] : `${built.unknownStates.length} block states`}`)
|
||||
}
|
||||
})
|
||||
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
|
||||
.finally(() => !stop.signal.aborted && setBuilding(false))
|
||||
return () => stop.abort()
|
||||
}, [client, viewId, key, variant, packRevision, models, images, tell])
|
||||
|
||||
useEffect(() => () => disposeMesh(mesh), [mesh])
|
||||
|
||||
return { scene, mesh, building }
|
||||
}
|
||||
|
||||
function disposeMesh(mesh: SceneMesh | null): void {
|
||||
mesh?.dispose()
|
||||
}
|
||||
|
||||
/** 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])
|
||||
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">
|
||||
{counts.map(([state, count]) => (
|
||||
<div key={state} title={state} className="flex h-[26px] items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate">{state.replace(DEFAULT_NAMESPACE_PREFIX, '')}</span>
|
||||
<span className="shrink-0 text-[11.5px] text-secondary-text tabular-nums">{NUMBER.format(count)}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
// Block states that differ only in how they face count as one block, as a builder reads the list.
|
||||
function blockCounts(scene: BlockScene): [string, number][] {
|
||||
const counts = new Map<string, number>()
|
||||
for (let offset = 3; offset < scene.blocks.length; offset += INTS_PER_BLOCK) {
|
||||
const state = scene.palette[scene.blocks[offset]]
|
||||
const material = state.includes('[') ? state.slice(0, state.indexOf('[')) : state
|
||||
counts.set(material, (counts.get(material) ?? 0) + 1)
|
||||
}
|
||||
return [...counts.entries()].sort((first, second) => second[1] - first[1])
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { Box3, PerspectiveCamera, Scene, Sphere, Vector3, WebGLRenderer, type Object3D } from 'three'
|
||||
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
|
||||
|
||||
const FIELD_OF_VIEW_DEGREES = 45
|
||||
// Looking down at the scene from the south east, as v3e's object view opens.
|
||||
const VIEW_DIRECTION = new Vector3(1, 0.8, 1.2).normalize()
|
||||
const FRAMING_MARGIN = 1.15
|
||||
const NEAREST_CLIP = 0.05
|
||||
// The near plane follows the orbit distance: a fixed tiny one leaves too little depth precision far away, so surfaces a block apart flicker.
|
||||
const NEAR_CLIP_PER_ORBIT_DISTANCE = 0.01
|
||||
|
||||
/** What a viewport shows: one object, and the box the camera frames when it is first shown. */
|
||||
export interface ViewportContent {
|
||||
object: Object3D
|
||||
bounds: Box3
|
||||
}
|
||||
|
||||
interface SceneViewportProps {
|
||||
content: ViewportContent | null
|
||||
/** Changes when the camera should frame the content again; the same content keeps the camera where it is. */
|
||||
framing?: unknown
|
||||
}
|
||||
|
||||
/** Something in 3D: drag to turn around it, right drag to move, scroll to come closer. Drawn only when it changes. */
|
||||
export function SceneViewport({ content, framing }: SceneViewportProps): React.JSX.Element {
|
||||
const host = useRef<HTMLDivElement>(null)
|
||||
const stage = useRef<Stage | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
const created = new Stage(host.current!)
|
||||
stage.current = created
|
||||
return () => {
|
||||
created.dispose()
|
||||
stage.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => stage.current?.show(content), [content])
|
||||
useEffect(() => stage.current?.frameShown(), [framing])
|
||||
|
||||
return <div ref={host} className="absolute inset-0 bg-map-background" />
|
||||
}
|
||||
|
||||
/** The renderer, camera and controls of one viewport. What it shows belongs to whoever built it, who frees it. */
|
||||
class Stage {
|
||||
private readonly renderer = new WebGLRenderer({ antialias: true, alpha: true })
|
||||
private readonly camera = new PerspectiveCamera(FIELD_OF_VIEW_DEGREES, 1, NEAREST_CLIP, 10_000)
|
||||
private readonly scene = new Scene()
|
||||
private readonly controls: OrbitControls
|
||||
private readonly resizes: ResizeObserver
|
||||
private shown: ViewportContent | null = null
|
||||
private framed = false
|
||||
private frameRequested = false
|
||||
|
||||
constructor(private readonly host: HTMLDivElement) {
|
||||
this.renderer.setPixelRatio(window.devicePixelRatio)
|
||||
this.renderer.setClearAlpha(0)
|
||||
host.appendChild(this.renderer.domElement)
|
||||
this.controls = new OrbitControls(this.camera, this.renderer.domElement)
|
||||
this.controls.enableDamping = true
|
||||
this.controls.addEventListener('change', () => {
|
||||
this.fitNearClipToOrbit()
|
||||
this.requestFrame()
|
||||
})
|
||||
this.resizes = new ResizeObserver(() => this.fitToHost())
|
||||
this.resizes.observe(host)
|
||||
this.fitToHost()
|
||||
}
|
||||
|
||||
show(content: ViewportContent | null): void {
|
||||
if (this.shown !== null) {
|
||||
this.scene.remove(this.shown.object)
|
||||
}
|
||||
this.shown = content
|
||||
if (content !== null) {
|
||||
this.scene.add(content.object)
|
||||
if (!this.framed) {
|
||||
this.frameShown()
|
||||
}
|
||||
}
|
||||
this.requestFrame()
|
||||
}
|
||||
|
||||
frameShown(): void {
|
||||
if (this.shown === null) {
|
||||
this.framed = false
|
||||
return
|
||||
}
|
||||
this.framed = true
|
||||
const bounds = this.shown.bounds
|
||||
const sphere = bounds.isEmpty() ? new Sphere(new Vector3(), 1) : bounds.getBoundingSphere(new Sphere())
|
||||
const halfVertical = (FIELD_OF_VIEW_DEGREES * Math.PI) / 360
|
||||
const halfHorizontal = Math.atan(Math.tan(halfVertical) * this.camera.aspect)
|
||||
const distance = (sphere.radius * FRAMING_MARGIN) / Math.sin(Math.min(halfVertical, halfHorizontal))
|
||||
this.controls.target.copy(sphere.center)
|
||||
this.camera.position.copy(sphere.center).addScaledVector(VIEW_DIRECTION, distance)
|
||||
this.camera.far = distance * 10 + sphere.radius * 4
|
||||
this.controls.update()
|
||||
this.fitNearClipToOrbit()
|
||||
this.requestFrame()
|
||||
}
|
||||
|
||||
private fitNearClipToOrbit(): void {
|
||||
this.camera.near = Math.max(NEAREST_CLIP, this.camera.position.distanceTo(this.controls.target) * NEAR_CLIP_PER_ORBIT_DISTANCE)
|
||||
this.camera.updateProjectionMatrix()
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.shown !== null) {
|
||||
this.scene.remove(this.shown.object)
|
||||
}
|
||||
this.resizes.disconnect()
|
||||
this.controls.dispose()
|
||||
this.renderer.dispose()
|
||||
this.renderer.domElement.remove()
|
||||
}
|
||||
|
||||
private fitToHost(): void {
|
||||
const width = Math.max(1, this.host.clientWidth)
|
||||
const height = Math.max(1, this.host.clientHeight)
|
||||
this.renderer.setSize(width, height)
|
||||
this.camera.aspect = width / height
|
||||
this.camera.updateProjectionMatrix()
|
||||
this.requestFrame()
|
||||
}
|
||||
|
||||
private requestFrame(): void {
|
||||
if (this.frameRequested) {
|
||||
return
|
||||
}
|
||||
this.frameRequested = true
|
||||
requestAnimationFrame(() => {
|
||||
this.frameRequested = false
|
||||
// Damping keeps turning the camera for a moment after a drag, and asks for frames until it stops.
|
||||
this.controls.update()
|
||||
this.renderer.render(this.scene, this.camera)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { MapStatus } from '../map/MapController'
|
||||
|
||||
interface StatusBarProps {
|
||||
viewLabel: string
|
||||
status: MapStatus | null
|
||||
notice: string | null
|
||||
}
|
||||
|
||||
const NUMBER = new Intl.NumberFormat('en-US')
|
||||
|
||||
/** What the map shows, what it is busy with, and where the cursor is (v3e StudioStatusBar). */
|
||||
export function StatusBar({ viewLabel, status, notice }: StatusBarProps): React.JSX.Element {
|
||||
const drawing = status !== null && status.tilesReady < status.tilesTotal
|
||||
return (
|
||||
<footer className="flex h-6 shrink-0 items-center gap-6 border-t bg-card px-3 text-[11.5px] text-secondary-text tabular-nums">
|
||||
<span className="truncate">
|
||||
{viewLabel}
|
||||
{status !== null && (
|
||||
<>
|
||||
<Gap />
|
||||
{formatScale(status.blocksPerPixel)} blocks/px
|
||||
<Gap />
|
||||
{NUMBER.format(status.widthBlocks)} × {NUMBER.format(status.heightBlocks)} blocks
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-1 items-center justify-center gap-2 truncate">
|
||||
{notice ?? (drawing ? `Drawing ${status.tilesReady} of ${status.tilesTotal} tiles` : '')}
|
||||
{notice === null && drawing && (
|
||||
<span className="h-1 w-24 overflow-hidden rounded-full bg-secondary">
|
||||
<span className="block h-full bg-primary" style={{ width: `${(status.tilesReady / status.tilesTotal) * 100}%` }} />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{status !== null && (
|
||||
<span>
|
||||
X {NUMBER.format(status.cursorX)}
|
||||
<Gap />Z {NUMBER.format(status.cursorZ)}
|
||||
</span>
|
||||
)}
|
||||
</footer>
|
||||
)
|
||||
}
|
||||
|
||||
function Gap(): React.JSX.Element {
|
||||
return <span className="inline-block w-3" />
|
||||
}
|
||||
|
||||
function formatScale(blocksPerPixel: number): string {
|
||||
if (blocksPerPixel >= 10) {
|
||||
return String(Math.round(blocksPerPixel))
|
||||
}
|
||||
return blocksPerPixel >= 1 ? blocksPerPixel.toFixed(1) : blocksPerPixel.toFixed(2)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import { CircleHelp, Grid3x3, LocateFixed, LogOut, Monitor, Moon, Mountain, PawPrint, RefreshCw, Spline, Sun, ZoomIn } from 'lucide-react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Kbd } from '@/components/ui/kbd'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Toggle } from '@/components/ui/toggle'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import type { ThemeChoice } from '../../../shared/bridge'
|
||||
import type { WorldInfo } from '../bridge/types'
|
||||
import type { StudioToggles } from './MapStudio'
|
||||
import { shortcutFor, type ShortcutAction } from './shortcuts'
|
||||
|
||||
interface StudioToolbarProps {
|
||||
title: string
|
||||
world: WorldInfo
|
||||
toggles: StudioToggles
|
||||
hasPlayers: boolean
|
||||
/** Whether the map's buttons apply: a scene view has no map to redraw, zoom or overlay. */
|
||||
mapTools: boolean
|
||||
theme: { choice: ThemeChoice; next: () => void }
|
||||
onToggle(name: keyof StudioToggles): void
|
||||
onRefresh(): void
|
||||
onResetZoom(): void
|
||||
onHelp(): void
|
||||
onDisconnect(): void
|
||||
}
|
||||
|
||||
const THEME_ICONS: Record<ThemeChoice, ReactNode> = { system: <Monitor />, light: <Sun />, dark: <Moon /> }
|
||||
const THEME_NAMES: Record<ThemeChoice, string> = { system: 'Theme: system', light: 'Theme: light', dark: 'Theme: dark' }
|
||||
|
||||
export function StudioToolbar(props: StudioToolbarProps): React.JSX.Element {
|
||||
return (
|
||||
<header className="flex h-10 shrink-0 items-center gap-1 border-b bg-card px-2">
|
||||
<span className="px-1.5 pr-3 text-[14px] font-semibold">{props.title}</span>
|
||||
{props.mapTools && <MapTools {...props} />}
|
||||
|
||||
<div className="flex-1" />
|
||||
<span className="truncate px-2 text-[12px] text-secondary-text" title={`${props.world.dimensionName} · seed ${props.world.seed}`}>
|
||||
{props.world.world}
|
||||
</span>
|
||||
<IconHint hint={THEME_NAMES[props.theme.choice]}>
|
||||
<Button variant="ghost" size="icon-sm" onClick={props.theme.next}>
|
||||
{THEME_ICONS[props.theme.choice]}
|
||||
</Button>
|
||||
</IconHint>
|
||||
<ToolButton action="help" hint="Show every mouse and key shortcut" onClick={props.onHelp}>
|
||||
<CircleHelp />
|
||||
</ToolButton>
|
||||
<IconHint hint="Back to the world list">
|
||||
<Button variant="ghost" size="icon-sm" onClick={props.onDisconnect}>
|
||||
<LogOut />
|
||||
</Button>
|
||||
</IconHint>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
function MapTools(props: StudioToolbarProps): React.JSX.Element {
|
||||
const { toggles, onToggle } = props
|
||||
return (
|
||||
<>
|
||||
<ToolButton action="refresh" hint="Redraw the map with the latest pack files" onClick={props.onRefresh}>
|
||||
<RefreshCw />
|
||||
</ToolButton>
|
||||
<ToolButton action="resetZoom" hint="Go back to the default zoom" onClick={props.onResetZoom}>
|
||||
<ZoomIn />
|
||||
</ToolButton>
|
||||
<ToolToggle action="grid" hint="Show chunk and region borders" pressed={toggles.grid} onPressed={() => onToggle('grid')}>
|
||||
<Grid3x3 /> Grid
|
||||
</ToolToggle>
|
||||
<ToolToggle action="entities" hint="Show mobs and other entities" pressed={toggles.entities} disabled={!props.hasPlayers} onPressed={() => onToggle('entities')}>
|
||||
<PawPrint /> Entities
|
||||
</ToolToggle>
|
||||
<ToolToggle action="follow" hint="Keep your player in the middle" pressed={toggles.follow} disabled={!props.hasPlayers} onPressed={() => onToggle('follow')}>
|
||||
<LocateFixed /> Follow
|
||||
</ToolToggle>
|
||||
<Separator orientation="vertical" className="mx-1 h-5! bg-input" />
|
||||
<ToolToggle action="shading" hint="Shade hills and valleys" pressed={toggles.shading} onPressed={() => onToggle('shading')}>
|
||||
<Mountain /> Shading
|
||||
</ToolToggle>
|
||||
<ToolToggle action="borders" hint="Outline the regions on every view" pressed={toggles.regionBorders} onPressed={() => onToggle('regionBorders')}>
|
||||
<Spline /> Borders
|
||||
</ToolToggle>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function IconHint({ hint, keyText, children }: { hint: string; keyText?: string; children: ReactNode }): React.JSX.Element {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{children}</TooltipTrigger>
|
||||
<TooltipContent className="flex items-center gap-2">
|
||||
{hint}
|
||||
{keyText !== undefined && <Kbd>{keyText}</Kbd>}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
function ToolButton({ action, hint, onClick, children }: { action: ShortcutAction; hint: string; onClick(): void; children: ReactNode }): React.JSX.Element {
|
||||
return (
|
||||
<IconHint hint={hint} keyText={shortcutFor(action).keyText}>
|
||||
<Button variant="ghost" size="icon-sm" onClick={onClick}>
|
||||
{children}
|
||||
</Button>
|
||||
</IconHint>
|
||||
)
|
||||
}
|
||||
|
||||
interface ToolToggleProps {
|
||||
action: ShortcutAction
|
||||
hint: string
|
||||
pressed: boolean
|
||||
disabled?: boolean
|
||||
onPressed(): void
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
function ToolToggle({ action, hint, pressed, disabled, onPressed, children }: ToolToggleProps): React.JSX.Element {
|
||||
return (
|
||||
<IconHint hint={disabled ? 'This server has no players to show' : hint} keyText={shortcutFor(action).keyText}>
|
||||
<span>
|
||||
<Toggle
|
||||
size="sm"
|
||||
pressed={pressed}
|
||||
disabled={disabled}
|
||||
onPressedChange={onPressed}
|
||||
className="h-7 gap-1.5 px-2 text-[12.5px] font-normal data-[state=on]:bg-selection data-[state=on]:text-foreground [&_svg:not([class*='size-'])]:size-3.5"
|
||||
>
|
||||
{children}
|
||||
</Toggle>
|
||||
</span>
|
||||
</IconHint>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import type { TiledView } from '../map/TiledView'
|
||||
|
||||
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
|
||||
|
||||
/** 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)
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current!
|
||||
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, view)
|
||||
return () => {
|
||||
stopMouse()
|
||||
resize.disconnect()
|
||||
view.close()
|
||||
viewRef.current = null
|
||||
}
|
||||
}, [create, viewRef])
|
||||
|
||||
return <canvas ref={canvasRef} className={className} />
|
||||
}
|
||||
|
||||
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()
|
||||
return { x: event.clientX - bounds.left, y: event.clientY - bounds.top }
|
||||
}
|
||||
const down = (event: PointerEvent): void => {
|
||||
if (event.button === 0) {
|
||||
canvas.setPointerCapture(event.pointerId)
|
||||
last = { x: event.clientX, y: event.clientY }
|
||||
}
|
||||
}
|
||||
const move = (event: PointerEvent): void => {
|
||||
view.setCursor(pointOf(event))
|
||||
if (last !== null) {
|
||||
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 => view.setCursor(null)
|
||||
const wheel = (event: WheelEvent): void => {
|
||||
event.preventDefault()
|
||||
const point = pointOf(event)
|
||||
view.zoomAt(2 ** (-event.deltaY * WHEEL_ZOOM_PER_DELTA), point.x, point.y)
|
||||
}
|
||||
canvas.addEventListener('pointerdown', down)
|
||||
canvas.addEventListener('pointermove', move)
|
||||
canvas.addEventListener('pointerup', up)
|
||||
canvas.addEventListener('pointerleave', leave)
|
||||
canvas.addEventListener('wheel', wheel, { passive: false })
|
||||
return () => {
|
||||
canvas.removeEventListener('pointerdown', down)
|
||||
canvas.removeEventListener('pointermove', move)
|
||||
canvas.removeEventListener('pointerup', up)
|
||||
canvas.removeEventListener('pointerleave', leave)
|
||||
canvas.removeEventListener('wheel', wheel)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
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'
|
||||
import type { ViewInfo } from '../bridge/types'
|
||||
import { VIEW_KEYS } from './shortcuts'
|
||||
|
||||
const VIEW_ICONS: Record<string, LucideIcon> = {
|
||||
biomes: Trees,
|
||||
regions: MapIcon,
|
||||
height: Mountain,
|
||||
world3d: Globe,
|
||||
savedWorld: HardDrive,
|
||||
noise: AudioWaveform,
|
||||
landBiomes: Sprout,
|
||||
seaBiomes: Waves,
|
||||
caveBiomes: Gem,
|
||||
'iris:objects': Box,
|
||||
'iris:objects/procedural': Shapes,
|
||||
'iris:terrain/palettes': Layers
|
||||
}
|
||||
|
||||
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, children }: ViewListProps): React.JSX.Element {
|
||||
const groups = [...new Set(views.map((view) => view.groupLabel))]
|
||||
return (
|
||||
<aside className="w-60 shrink-0 border-r bg-card">
|
||||
<ScrollArea className="h-full">
|
||||
<nav className="flex flex-col gap-3 p-2">
|
||||
{groups.map((group) => (
|
||||
<section key={group}>
|
||||
<h2 className="px-2 pt-1 pb-1.5 text-[11px] font-semibold text-muted-foreground">{group}</h2>
|
||||
{views
|
||||
.filter((view) => view.groupLabel === group)
|
||||
.map((view) => (
|
||||
<ViewRow key={view.id} view={view} selected={view.id === current} onSelect={() => onSelect(view.id)} />
|
||||
))}
|
||||
</section>
|
||||
))}
|
||||
{children}
|
||||
</nav>
|
||||
</ScrollArea>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
|
||||
function ViewRow({ view, selected, onSelect }: { view: ViewInfo; selected: boolean; onSelect(): void }): React.JSX.Element {
|
||||
const Icon = VIEW_ICONS[view.id] ?? MapIcon
|
||||
return (
|
||||
<button
|
||||
onClick={onSelect}
|
||||
className={cn('flex w-full items-start gap-2.5 rounded-md px-2 py-1.5 text-left', selected ? 'bg-selection' : 'hover:bg-accent')}
|
||||
>
|
||||
<Icon className="mt-0.5 size-4 shrink-0 text-secondary-text" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block font-medium">{view.label}</span>
|
||||
<span className="block text-[11.5px] leading-snug text-secondary-text">{view.description}</span>
|
||||
</span>
|
||||
{VIEW_KEYS[view.id] !== undefined && <Kbd className="mt-0.5">{VIEW_KEYS[view.id]}</Kbd>}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
|
||||
import type { BridgeClient, WorldRect } from '../bridge/BridgeClient'
|
||||
import type { MapTile, WorldInfo } from '../bridge/types'
|
||||
import { MapTerrain, type MapTerrainArea, type MapTerrainColoring } from '../scene/mapTerrain'
|
||||
import { buildTerrainMesh } from '../scene/terrainMesh'
|
||||
import { SceneViewport } from './SceneViewport'
|
||||
|
||||
const NUMBER = new Intl.NumberFormat('en-US')
|
||||
const TILES_PER_SIDE = 4
|
||||
const TILE_PIXELS = 128
|
||||
const BLOCKS_PER_PIXEL = 2
|
||||
const TILE_BLOCKS = TILE_PIXELS * BLOCKS_PER_PIXEL
|
||||
const COLORING_ITEM = 'h-7 px-3 text-[12px] data-[state=on]:bg-selection data-[state=on]:text-foreground'
|
||||
|
||||
interface WorldStudio3DProps {
|
||||
client: BridgeClient
|
||||
world: WorldInfo
|
||||
/** Where the map last looked; the terrain is the square around its middle, or around the world's centre. */
|
||||
mapArea: WorldRect | null
|
||||
packRevision: number
|
||||
onSummary(summary: string | null): void
|
||||
tell(message: string): void
|
||||
}
|
||||
|
||||
/** The terrain around where the map looked, in 3D, coloured by biome, region or height (v3e's 3D world view). */
|
||||
export function WorldStudio3D({ client, world, mapArea, packRevision, onSummary, tell }: WorldStudio3DProps): React.JSX.Element {
|
||||
const [coloring, setColoring] = useState<MapTerrainColoring>('biomes')
|
||||
const centre = useMemo(() => centreOf(mapArea), [mapArea])
|
||||
const area = useTerrainArea(client, centre, packRevision, tell)
|
||||
const mesh = useMemo(() => (area === null ? null : buildTerrainMesh(new MapTerrain(area, coloring, world.fluidHeight))), [area, coloring, world.fluidHeight])
|
||||
|
||||
useEffect(() => () => mesh?.dispose(), [mesh])
|
||||
useEffect(() => {
|
||||
const side = NUMBER.format(TILES_PER_SIDE * TILE_BLOCKS)
|
||||
onSummary(`${side} × ${side} blocks around ${NUMBER.format(centre.x)}, ${NUMBER.format(centre.z)}`)
|
||||
return () => onSummary(null)
|
||||
}, [centre, onSummary])
|
||||
|
||||
return (
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<SceneViewport content={mesh?.content ?? null} framing={area} />
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="absolute top-3 left-3 bg-card/90"
|
||||
value={coloring}
|
||||
onValueChange={(value) => value !== '' && setColoring(value as MapTerrainColoring)}
|
||||
>
|
||||
<ToggleGroupItem value="biomes" className={COLORING_ITEM}>
|
||||
Biomes
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="regions" className={COLORING_ITEM}>
|
||||
Regions
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="height" className={COLORING_ITEM}>
|
||||
Height
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
{area === null && (
|
||||
<div className="pointer-events-none absolute top-3 left-1/2 -translate-x-1/2 rounded-md border border-overlay-border bg-card/90 px-3 py-1.5 text-[12px] text-secondary-text">
|
||||
Sampling the terrain
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function centreOf(area: WorldRect | null): { x: number; z: number } {
|
||||
if (area === null) {
|
||||
return { x: 0, z: 0 }
|
||||
}
|
||||
return { x: Math.round((area.minX + area.maxX) / 2), z: Math.round((area.minZ + area.maxZ) / 2) }
|
||||
}
|
||||
|
||||
/** The tiles of the square around {@code centre}, with heights; every tile arrives before the square is shown. */
|
||||
function useTerrainArea(client: BridgeClient, centre: { x: number; z: number }, packRevision: number, tell: (message: string) => void): MapTerrainArea | null {
|
||||
const [area, setArea] = useState<MapTerrainArea | null>(null)
|
||||
useEffect(() => {
|
||||
const stop = new AbortController()
|
||||
const firstTileX = Math.floor(centre.x / TILE_BLOCKS - TILES_PER_SIDE / 2)
|
||||
const firstTileZ = Math.floor(centre.z / TILE_BLOCKS - TILES_PER_SIDE / 2)
|
||||
const rows = Array.from({ length: TILES_PER_SIDE }, (_, row) =>
|
||||
Promise.all(
|
||||
Array.from({ length: TILES_PER_SIDE }, (_, column) =>
|
||||
client.tile(
|
||||
{
|
||||
view: 'biomes',
|
||||
preview: null,
|
||||
tileX: firstTileX + column,
|
||||
tileZ: firstTileZ + row,
|
||||
blocksPerPixel: BLOCKS_PER_PIXEL,
|
||||
size: TILE_PIXELS,
|
||||
heights: true,
|
||||
pickNoise: false
|
||||
},
|
||||
stop.signal
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
setArea(null)
|
||||
Promise.all(rows)
|
||||
.then((tiles: MapTile[][]) => setArea({ tiles, originX: firstTileX * TILE_BLOCKS, originZ: firstTileZ * TILE_BLOCKS }))
|
||||
.catch((failure: Error) => !stop.signal.aborted && tell(failure.message))
|
||||
return () => stop.abort()
|
||||
}, [client, centre, packRevision, tell])
|
||||
return area
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/** A 0xRRGGBB colour as CSS. */
|
||||
export function hexColor(color: number): string {
|
||||
return `#${color.toString(16).padStart(6, '0')}`
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
/** The studio's keys, as v3e's studio had them (StudioShortcut). */
|
||||
export type ShortcutAction =
|
||||
| 'nextView'
|
||||
| 'refresh'
|
||||
| 'zoomIn'
|
||||
| 'zoomOut'
|
||||
| 'resetZoom'
|
||||
| 'dismiss'
|
||||
| 'follow'
|
||||
| 'grid'
|
||||
| 'entities'
|
||||
| 'highlight'
|
||||
| 'shading'
|
||||
| 'borders'
|
||||
| 'help'
|
||||
|
||||
export interface Shortcut {
|
||||
action: ShortcutAction
|
||||
label: string
|
||||
group: 'Views' | 'Everywhere' | 'Map'
|
||||
/** The key as shown, then every KeyboardEvent.key that triggers it. */
|
||||
keyText: string
|
||||
keys: string[]
|
||||
}
|
||||
|
||||
export const SHORTCUTS: Shortcut[] = [
|
||||
{ action: 'nextView', label: 'Next view', group: 'Views', keyText: 'M', keys: ['m'] },
|
||||
{ action: 'refresh', label: 'Redraw the map with the latest pack files', group: 'Everywhere', keyText: 'R', keys: ['r'] },
|
||||
{ action: 'zoomIn', label: 'Zoom in', group: 'Everywhere', keyText: '=', keys: ['=', '+'] },
|
||||
{ action: 'zoomOut', label: 'Zoom out', group: 'Everywhere', keyText: '-', keys: ['-'] },
|
||||
{ action: 'resetZoom', label: 'Reset zoom', group: 'Everywhere', keyText: '\\', keys: ['\\'] },
|
||||
{ action: 'dismiss', label: 'Clear the highlight', group: 'Everywhere', keyText: 'Esc', keys: ['Escape'] },
|
||||
{ action: 'follow', label: 'Follow your player', group: 'Map', keyText: 'F', keys: ['f'] },
|
||||
{ action: 'grid', label: 'Chunk and region grid', group: 'Map', keyText: 'G', keys: ['g'] },
|
||||
{ action: 'entities', label: 'Show entities', group: 'Map', keyText: 'E', keys: ['e'] },
|
||||
{ action: 'highlight', label: 'Highlight what is under the cursor', group: 'Map', keyText: 'H', keys: ['h'] },
|
||||
{ action: 'shading', label: 'Terrain shading', group: 'Map', keyText: 'S', keys: ['s'] },
|
||||
{ action: 'borders', label: 'Region borders', group: 'Map', keyText: 'B', keys: ['b'] },
|
||||
{ action: 'help', label: 'Show the shortcuts', group: 'Map', keyText: '/', keys: ['/', '?'] }
|
||||
]
|
||||
|
||||
/** The key of each view; 4 stays free for the 3D world, as in v3e. */
|
||||
export const VIEW_KEYS: Record<string, string> = {
|
||||
biomes: '1',
|
||||
regions: '2',
|
||||
height: '3',
|
||||
landBiomes: '5',
|
||||
seaBiomes: '6',
|
||||
caveBiomes: '7'
|
||||
}
|
||||
|
||||
export const MOUSE_HINTS: { gesture: string; label: string }[] = [
|
||||
{ gesture: 'Drag', label: 'Move the map' },
|
||||
{ gesture: 'Wheel', label: 'Zoom around the cursor' },
|
||||
{ gesture: 'Shift', label: 'More about the spot under the cursor' },
|
||||
{ gesture: 'Ctrl+Click', label: 'Teleport there' },
|
||||
{ gesture: 'Alt+Click', label: 'Open the biome or region file' },
|
||||
{ gesture: 'Right click', label: 'Highlight, teleport, open or copy' }
|
||||
]
|
||||
|
||||
export function shortcutFor(action: ShortcutAction): Shortcut {
|
||||
return SHORTCUTS.find((shortcut) => shortcut.action === action)!
|
||||
}
|
||||
|
||||
export function actionForKey(key: string): ShortcutAction | null {
|
||||
const pressed = key.length === 1 ? key.toLowerCase() : key
|
||||
return SHORTCUTS.find((shortcut) => shortcut.keys.includes(pressed))?.action ?? null
|
||||
}
|
||||
|
||||
export function viewForKey(key: string): string | null {
|
||||
return Object.entries(VIEW_KEYS).find(([, viewKey]) => viewKey === key)?.[0] ?? null
|
||||
}
|
||||
|
||||
/** Whether a key press goes to a field being typed into, so the studio's keys leave it alone. */
|
||||
export function isTypingInto(target: EventTarget | null): boolean {
|
||||
return target instanceof HTMLInputElement || target instanceof HTMLSelectElement || target instanceof HTMLTextAreaElement
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import type { ThemeChoice } from '../../../shared/bridge'
|
||||
|
||||
const STORAGE_KEY = 'iris-studio.theme'
|
||||
const DARK_QUERY = '(prefers-color-scheme: dark)'
|
||||
const ORDER: ThemeChoice[] = ['system', 'light', 'dark']
|
||||
|
||||
function storedChoice(): ThemeChoice {
|
||||
const stored = localStorage.getItem(STORAGE_KEY)
|
||||
return stored === 'light' || stored === 'dark' ? stored : 'system'
|
||||
}
|
||||
|
||||
function apply(choice: ThemeChoice): void {
|
||||
const dark = choice === 'dark' || (choice === 'system' && matchMedia(DARK_QUERY).matches)
|
||||
document.documentElement.classList.toggle('dark', dark)
|
||||
}
|
||||
|
||||
/** The light or dark look, following the system unless chosen; the choice outlives the window. */
|
||||
export function useTheme(): { choice: ThemeChoice; next: () => void } {
|
||||
const [choice, setChoice] = useState<ThemeChoice>(storedChoice)
|
||||
|
||||
useEffect(() => {
|
||||
apply(choice)
|
||||
window.studio.setTheme(choice)
|
||||
localStorage.setItem(STORAGE_KEY, choice)
|
||||
const media = matchMedia(DARK_QUERY)
|
||||
const follow = (): void => apply(choice)
|
||||
media.addEventListener('change', follow)
|
||||
return () => media.removeEventListener('change', follow)
|
||||
}, [choice])
|
||||
|
||||
return { choice, next: () => setChoice(ORDER[(ORDER.indexOf(choice) + 1) % ORDER.length]) }
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
/* The studio's colours, taken from the Swing studio (StudioTheme) so both look alike. */
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #000000;
|
||||
--card: #f7f8fa;
|
||||
--card-foreground: #000000;
|
||||
--popover: rgb(255 255 255 / 0.94);
|
||||
--popover-foreground: #000000;
|
||||
--primary: #3574f0;
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: #dfe1e5;
|
||||
--secondary-foreground: #000000;
|
||||
--muted: #f7f8fa;
|
||||
--muted-foreground: #818594;
|
||||
--secondary-text: #6c707e;
|
||||
--accent: #dfe1e5;
|
||||
--accent-foreground: #000000;
|
||||
--selection: #d4e2ff;
|
||||
--destructive: #db3b4b;
|
||||
--warning: #c27d04;
|
||||
--success: #208a3c;
|
||||
--link: #315fbd;
|
||||
--border: #ebecf0;
|
||||
--input: #c9ccd6;
|
||||
--ring: #3574f0;
|
||||
--overlay-border: #dfe1e5;
|
||||
--map-background: #e4e6eb;
|
||||
--radius: 10px;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: #1e1f22;
|
||||
--foreground: #dfe1e5;
|
||||
--card: #2b2d30;
|
||||
--card-foreground: #dfe1e5;
|
||||
--popover: rgb(43 45 48 / 0.93);
|
||||
--popover-foreground: #dfe1e5;
|
||||
--primary: #3574f0;
|
||||
--primary-foreground: #ffffff;
|
||||
--secondary: #393b40;
|
||||
--secondary-foreground: #dfe1e5;
|
||||
--muted: #2b2d30;
|
||||
--muted-foreground: #6f737a;
|
||||
--secondary-text: #9da0a8;
|
||||
--accent: #393b40;
|
||||
--accent-foreground: #dfe1e5;
|
||||
--selection: #2e436e;
|
||||
--destructive: #f75464;
|
||||
--warning: #f2c55c;
|
||||
--success: #5fb865;
|
||||
--link: #548af7;
|
||||
--border: #1e1f22;
|
||||
--input: #4e5157;
|
||||
--ring: #3574f0;
|
||||
--overlay-border: #43454a;
|
||||
--map-background: #16171a;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-secondary-text: var(--secondary-text);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-selection: var(--selection);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-warning: var(--warning);
|
||||
--color-success: var(--success);
|
||||
--color-link: var(--link);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-overlay-border: var(--overlay-border);
|
||||
--color-map-background: var(--map-background);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--font-sans: "Inter", "Segoe UI", system-ui, sans-serif;
|
||||
--font-mono: "JetBrains Mono", ui-monospace, monospace;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
@apply h-full overflow-hidden;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-background text-foreground text-[13px] antialiased select-none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/** A bridge a running Iris server opened, as its connection file or a studio link describes it. */
|
||||
export interface BridgeConnection {
|
||||
world: string
|
||||
port: number
|
||||
token: string
|
||||
startedMillis?: number
|
||||
}
|
||||
|
||||
export type ThemeChoice = 'system' | 'light' | 'dark'
|
||||
|
||||
/** What the preload script hands the renderer. */
|
||||
export interface StudioHost {
|
||||
listBridges(): Promise<BridgeConnection[]>
|
||||
/** The studio link the app was started with, if any. */
|
||||
initialLink(): Promise<string | null>
|
||||
onLink(listener: (link: string) => void): () => void
|
||||
setTheme(theme: ThemeChoice): void
|
||||
copyText(text: string): void
|
||||
}
|
||||
|
||||
const LINK_PROTOCOL = 'iris-studio:'
|
||||
|
||||
/** The bridge a link such as {@code iris-studio://127.0.0.1:44503/?token=...} names; null for anything else. */
|
||||
export function parseStudioLink(text: string): BridgeConnection | null {
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(text.trim())
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const port = Number(url.port)
|
||||
const token = url.searchParams.get('token')
|
||||
if (url.protocol !== LINK_PROTOCOL || !Number.isInteger(port) || port <= 0 || !token) {
|
||||
return null
|
||||
}
|
||||
return { world: url.searchParams.get('world') ?? '', port, token }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2023", "DOM", "DOM.Iterable"],
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"skipLibCheck": true,
|
||||
"isolatedModules": true,
|
||||
"resolveJsonModule": true,
|
||||
"types": ["node"],
|
||||
"paths": { "@/*": ["./src/renderer/src/*"] }
|
||||
},
|
||||
"include": ["src", "electron.vite.config.ts"]
|
||||
}
|
||||
Reference in new issue
Block a user