From e0812cca660d5943e4c7496a9d344c081722140a Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 01:26:06 +0100 Subject: [PATCH] Objects view: the pack's block scenes in 3D Scene views the pack's modules show join the view list under Blocks. Choosing one lists its entries under their folders, with a search, and draws the chosen one with three.js: block states resolve to the client's models (variants, multipart, parents, element and variant turns), their textures go into one atlas, faces against solid blocks are left out, and each side gets Minecraft's flat light and its block's tint. The blocks it is made of are listed with their counts. Models the client draws without elements stand in as cubes of their break texture. --- package-lock.json | 67 +++- package.json | 4 +- src/renderer/src/bridge/BridgeClient.ts | 32 +- src/renderer/src/bridge/types.ts | 15 + src/renderer/src/scene/BridgeAssets.ts | 44 +++ src/renderer/src/scene/blockModels.test.ts | 68 ++++ src/renderer/src/scene/blockModels.ts | 389 +++++++++++++++++++++ src/renderer/src/scene/blockTints.ts | 51 +++ src/renderer/src/scene/sceneDecoding.ts | 32 ++ src/renderer/src/scene/sceneMesh.ts | 137 ++++++++ src/renderer/src/scene/textureAtlas.ts | 105 ++++++ src/renderer/src/studio/MapStudio.tsx | 53 ++- src/renderer/src/studio/SceneStudio.tsx | 219 ++++++++++++ src/renderer/src/studio/SceneViewport.tsx | 122 +++++++ src/renderer/src/studio/StudioToolbar.tsx | 50 +-- src/renderer/src/studio/ViewList.tsx | 5 +- 16 files changed, 1361 insertions(+), 32 deletions(-) create mode 100644 src/renderer/src/scene/BridgeAssets.ts create mode 100644 src/renderer/src/scene/blockModels.test.ts create mode 100644 src/renderer/src/scene/blockModels.ts create mode 100644 src/renderer/src/scene/blockTints.ts create mode 100644 src/renderer/src/scene/sceneDecoding.ts create mode 100644 src/renderer/src/scene/sceneMesh.ts create mode 100644 src/renderer/src/scene/textureAtlas.ts create mode 100644 src/renderer/src/studio/SceneStudio.tsx create mode 100644 src/renderer/src/studio/SceneViewport.tsx diff --git a/package-lock.json b/package-lock.json index c62737202..2ed25bf5e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,13 +15,15 @@ "radix-ui": "^1.8.1", "react": "^19.3.1", "react-dom": "^19.3.1", - "tailwind-merge": "^3.7.0" + "tailwind-merge": "^3.7.0", + "three": "^0.187.0" }, "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", @@ -317,6 +319,13 @@ "node": ">=6.9.0" } }, + "node_modules/@dimforge/rapier3d-compat": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz", + "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/@electron-internal/extract-zip": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.8.tgz", @@ -2579,6 +2588,13 @@ "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, + "node_modules/@tweenjs/tween.js": { + "version": "23.1.3", + "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz", + "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/chai": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", @@ -2634,6 +2650,35 @@ "@types/react": "^19.3.0" } }, + "node_modules/@types/stats.js": { + "version": "0.17.4", + "resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz", + "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/three": { + "version": "0.187.0", + "resolved": "https://registry.npmjs.org/@types/three/-/three-0.187.0.tgz", + "integrity": "sha512-v+vKNarUtk4n2QRZ4+CN5ygMM0ARUjXjIQl0R/unMUfmStFeVqGbgqarbrpoGTXRZoulSH16ePrVJVxPJEbMUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@dimforge/rapier3d-compat": "~0.12.0", + "@tweenjs/tween.js": "~23.1.3", + "@types/stats.js": "*", + "@types/webxr": ">=0.5.17", + "fflate": "~0.8.3", + "meshoptimizer": "~1.1.1" + } + }, + "node_modules/@types/webxr": { + "version": "0.5.24", + "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz", + "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==", + "dev": true, + "license": "MIT" + }, "node_modules/@typescript/typescript-aix-ppc64": { "version": "7.0.2", "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", @@ -3388,6 +3433,13 @@ } } }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "dev": true, + "license": "MIT" + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -3780,6 +3832,13 @@ "@jridgewell/sourcemap-codec": "^1.6.0" } }, + "node_modules/meshoptimizer": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.1.1.tgz", + "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g==", + "dev": true, + "license": "MIT" + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -4170,6 +4229,12 @@ "url": "https://opencollective.com/webpack" } }, + "node_modules/three": { + "version": "0.187.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.187.0.tgz", + "integrity": "sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA==", + "license": "MIT" + }, "node_modules/tinybench": { "version": "6.2.3", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.3.tgz", diff --git a/package.json b/package.json index 47598774d..38e4424d5 100644 --- a/package.json +++ b/package.json @@ -18,6 +18,7 @@ "@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", @@ -34,6 +35,7 @@ "radix-ui": "^1.8.1", "react": "^19.3.1", "react-dom": "^19.3.1", - "tailwind-merge": "^3.7.0" + "tailwind-merge": "^3.7.0", + "three": "^0.187.0" } } diff --git a/src/renderer/src/bridge/BridgeClient.ts b/src/renderer/src/bridge/BridgeClient.ts index 9a3c0255c..15a27ab73 100644 --- a/src/renderer/src/bridge/BridgeClient.ts +++ b/src/renderer/src/bridge/BridgeClient.ts @@ -1,6 +1,10 @@ import type { BridgeConnection } from '../../../shared/bridge' +import { decodeScene, type BlockScene } from '../scene/sceneDecoding' import { decodeTile } from './tileDecoding' -import type { MapHover, MapLabel, MapTile, Marker, PickInspection, WorldInfo } from './types' +import type { MapHover, MapLabel, MapTile, Marker, PickInspection, SceneEntry, SceneViewInfo, WorldInfo } from './types' + +export const STATUS_NOT_FOUND = 404 +export const STATUS_UNAVAILABLE = 503 export class BridgeError extends Error { constructor( @@ -100,6 +104,32 @@ export class BridgeClient { return decodeTile(await response.arrayBuffer()) } + /** The scene views the pack's modules show, such as its objects. */ + sceneViews(): Promise { + return this.json('scenes') + } + + sceneEntries(viewId: string): Promise { + return this.json(`scene-entries?${new URLSearchParams({ view: viewId })}`) + } + + async scene(viewId: string, key: string, variant: number, signal?: AbortSignal): Promise { + const response = await this.fetch(`scene?${new URLSearchParams({ view: viewId, key, variant: String(variant) })}`, { signal }) + return decodeScene(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 { + 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 { try { diff --git a/src/renderer/src/bridge/types.ts b/src/renderer/src/bridge/types.ts index 97fecd342..ec4592f5c 100644 --- a/src/renderer/src/bridge/types.ts +++ b/src/renderer/src/bridge/types.ts @@ -18,6 +18,21 @@ export interface ViewInfo { groupLabel: string } +/** A view of block scenes a module of the pack shows, such as its objects (IrisApi SceneView). */ +export interface SceneViewInfo { + 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 +} + export interface WorldInfo { world: string dimension: string diff --git a/src/renderer/src/scene/BridgeAssets.ts b/src/renderer/src/scene/BridgeAssets.ts new file mode 100644 index 000000000..e6fc40d6d --- /dev/null +++ b/src/renderer/src/scene/BridgeAssets.ts @@ -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 { + const response = await this.fetch(path) + return response === null ? null : response.json() + } + + async image(path: string): Promise { + const response = await this.fetch(path) + return response === null ? null : createImageBitmap(await response.blob()) + } + + private async fetch(path: string): Promise { + 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)) + } + } + } +} diff --git a/src/renderer/src/scene/blockModels.test.ts b/src/renderer/src/scene/blockModels.test.ts new file mode 100644 index 000000000..7cf4570bd --- /dev/null +++ b/src/renderer/src/scene/blockModels.test.ts @@ -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 = { + '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() + }) +}) diff --git a/src/renderer/src/scene/blockModels.ts b/src/renderer/src/scene/blockModels.ts new file mode 100644 index 000000000..abecc1a4c --- /dev/null +++ b/src/renderer/src/scene/blockModels.ts @@ -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 +} + +/** 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 +} + +type Json = Record + +interface Variant { + model: string + x: number + y: number +} + +interface ModelFile { + parent?: string + textures?: Record + elements?: ElementJson[] +} + +interface ElementJson { + from: Vec3 + to: Vec3 + rotation?: { origin: Vec3; axis: 'x' | 'y' | 'z'; angle: number; rescale?: boolean } + shade?: boolean + faces: Partial> +} + +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 = { + 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 = {} + 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>() + private readonly files = new Map>() + + 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 { + 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 { + 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 { + const chain = await this.parentChain(variant.model) + const textures: Record = {} + 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 { + 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 { + let file = this.files.get(modelId) + if (file === undefined) { + const { namespace, path } = splitId(modelId) + file = this.assets.json(`${namespace}/models/${path}.json`) as Promise + 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): Variant[] { + const variants = blockstate.variants as Record | 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): 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): 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): 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 | 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' +} diff --git a/src/renderer/src/scene/blockTints.ts b/src/renderer/src/scene/blockTints.ts new file mode 100644 index 000000000..e1d7a4f09 --- /dev/null +++ b/src/renderer/src/scene/blockTints.ts @@ -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 = { + 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, 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 +} diff --git a/src/renderer/src/scene/sceneDecoding.ts b/src/renderer/src/scene/sceneDecoding.ts new file mode 100644 index 000000000..6a06858ea --- /dev/null +++ b/src/renderer/src/scene/sceneDecoding.ts @@ -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 + } +} diff --git a/src/renderer/src/scene/sceneMesh.ts b/src/renderer/src/scene/sceneMesh.ts new file mode 100644 index 000000000..17a95dfc9 --- /dev/null +++ b/src/renderer/src/scene/sceneMesh.ts @@ -0,0 +1,137 @@ +import { BufferAttribute, BufferGeometry } from 'three' +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 { + geometry: BufferGeometry + atlas: TextureAtlas + /** Block states the client has no blockstate file for, drawn as magenta and black cubes. */ + unknownStates: string[] +} + +/** The light Minecraft gives each side of a block without shadows: the top brightest, the bottom darkest. */ +const FACE_LIGHT: Record = { 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 = { + 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 + /** 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 { + 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 } + }) + return { geometry: geometryOf(scene, palette, atlas), atlas, unknownStates } +} + +// 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 + } +} diff --git a/src/renderer/src/scene/textureAtlas.ts b/src/renderer/src/scene/textureAtlas.ts new file mode 100644 index 000000000..ffc8d6665 --- /dev/null +++ b/src/renderer/src/scene/textureAtlas.ts @@ -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 +} + +/** 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, + 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 { + 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() + 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}. */ +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 +} diff --git a/src/renderer/src/studio/MapStudio.tsx b/src/renderer/src/studio/MapStudio.tsx index 4ac806c69..a979b380e 100644 --- a/src/renderer/src/studio/MapStudio.tsx +++ b/src/renderer/src/studio/MapStudio.tsx @@ -1,7 +1,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { ThemeChoice } from '../../../shared/bridge' import type { BridgeClient, MapLayerQuery, WorldRect } from '../bridge/BridgeClient' -import type { MapHover, MapLabel, Marker, PickDisplay, PickInspection, WorldInfo } from '../bridge/types' +import type { MapHover, MapLabel, Marker, PickDisplay, PickInspection, SceneViewInfo, 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' @@ -11,6 +11,7 @@ import { Legend } from './Legend' import { MapCanvas, type CanvasPoint } from './MapCanvas' import { PickInspector } from './PickInspector' import { RegionPreviewList } from './RegionPreviewList' +import { SceneStudio } from './SceneStudio' import { actionForKey, viewForKey, type ShortcutAction } from './shortcuts' import { StatusBar } from './StatusBar' import { StudioToolbar } from './StudioToolbar' @@ -56,7 +57,11 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps const [pickDisplay, setPickDisplay] = useState('picks') const [area, setArea] = useState(null) const [packRevision, setPackRevision] = useState(0) - const view = world.views.find((candidate) => candidate.id === viewId) ?? world.views[0] + const [sceneSummary, setSceneSummary] = useState(null) + const sceneViews = useSceneViews(client, packRevision) + const views = useMemo(() => [...world.views, ...sceneViews.map(asViewInfo)], [world.views, sceneViews]) + const sceneView = sceneViews.find((candidate) => candidate.id === viewId) ?? null + const view = views.find((candidate) => candidate.id === viewId) ?? views[0] const layer = useMemo(() => ({ view: viewId, preview: viewId === 'regions' ? preview : null }), [viewId, preview]) const regions = usePreviewableRegions(client, packRevision) const inspectsPicks = PICK_VIEWS.has(viewId) @@ -115,7 +120,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps const map = controller.current switch (action) { case 'nextView': - selectView(world.views[(world.views.findIndex((candidate) => candidate.id === viewId) + 1) % world.views.length].id) + selectView(views[(views.findIndex((candidate) => candidate.id === viewId) + 1) % views.length].id) return case 'refresh': map?.refresh() @@ -155,7 +160,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps setHelpOpen((open) => !open) } }, - [world.views, viewId, selectView, toggle, highlightUnderCursor, tell] + [views, viewId, selectView, toggle, highlightUnderCursor, tell] ) useKeyboard(runShortcut, selectView, setDetailed, world) @@ -195,6 +200,7 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps world={world} toggles={toggles} hasPlayers={world.hasPlayers} + mapTools={sceneView === null} theme={theme} onToggle={toggle} onRefresh={() => runShortcut('refresh')} @@ -203,9 +209,13 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps onDisconnect={onDisconnect} />
- + {viewId === 'regions' && regions.length > 1 && } + {sceneView !== null ? ( + + ) : ( + <>
setHighlight((current) => (sameSubject(current, subject) ? null : subject))} /> + + )}
- - + +
) } +const SCENE_GROUP = { group: 'BLOCKS', groupLabel: 'Blocks' } + +function asViewInfo(view: SceneViewInfo): 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}` +} + +/** The scene views the pack's modules show, read again after the pack reloads. */ +function useSceneViews(client: BridgeClient, packRevision: number): SceneViewInfo[] { + const [views, setViews] = useState([]) + useEffect(() => { + let active = true + client + .sceneViews() + .then((found) => active && setViews(found)) + .catch(() => undefined) + return () => { + active = false + } + }, [client, 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 } diff --git a/src/renderer/src/studio/SceneStudio.tsx b/src/renderer/src/studio/SceneStudio.tsx new file mode 100644 index 000000000..5d44dbcda --- /dev/null +++ b/src/renderer/src/studio/SceneStudio.tsx @@ -0,0 +1,219 @@ +import { useEffect, useMemo, useState } from 'react' +import { Input } from '@/components/ui/input' +import { ScrollArea } from '@/components/ui/scroll-area' +import { cn } from '@/lib/utils' +import type { BridgeClient } from '../bridge/BridgeClient' +import type { SceneEntry, SceneViewInfo } from '../bridge/types' +import { 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 { 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. */ +export function SceneStudio({ client, view, packRevision, onSummary, tell }: SceneStudioProps): React.JSX.Element { + const [waiting, setWaiting] = useState(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(null) + const entry = entries.find((candidate) => candidate.key === chosen) ?? entries[0] ?? null + const { scene, mesh, building } = useSceneMesh(client, view.id, entry, packRevision, models, images, tell) + + useEffect(() => onSummary(entry === null || scene === null ? null : summaryOf(entry, scene)), [entry, scene, onSummary]) + useEffect(() => () => onSummary(null), [onSummary]) + + return ( + <> +
+ + {building && entry !== null && ( +
+ {waiting ?? `Building ${entry.name}`} +
+ )} +
+ + + ) +} + +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([]) + 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, + packRevision: number, + models: BlockModels, + images: BridgeAssets, + tell: (message: string) => void +): { scene: BlockScene | null; mesh: SceneMesh | null; building: boolean } { + const [scene, setScene] = useState(null) + const [mesh, setMesh] = useState(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, 0, 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, packRevision, models, images, tell]) + + useEffect(() => () => disposeMesh(mesh), [mesh]) + + return { scene, mesh, building } +} + +function disposeMesh(mesh: SceneMesh | null): void { + mesh?.geometry.dispose() + mesh?.atlas.dispose() +} + +interface EntryBrowserProps { + title: string + entries: SceneEntry[] + current: string | null + onSelect(key: string): void +} + +/** The view's entries under their folders, with a search over names and folders (v3e ObjectBrowser). */ +function EntryBrowser({ title, entries, current, onSelect }: EntryBrowserProps): React.JSX.Element { + const [search, setSearch] = useState('') + const wanted = search.trim().toLowerCase() + const groups = useMemo(() => groupedEntries(entries, wanted), [entries, wanted]) + return ( +
+
+

{title}

+

{NUMBER.format(entries.length)} in the pack

+ setSearch(event.target.value)} + onKeyDown={(event) => event.key === 'Escape' && setSearch('')} + /> +
+ +
+ {groups.map(([group, members]) => ( +
+ {group !== '' &&

{group}

} + {members.map((entry) => ( + + ))} +
+ ))} + {groups.length === 0 &&

{entries.length === 0 ? 'Nothing to show' : 'Nothing matches'}

} +
+
+
+ ) +} + +function groupedEntries(entries: SceneEntry[], wanted: string): [string, SceneEntry[]][] { + const groups = new Map() + for (const entry of entries) { + if (wanted !== '' && !entry.key.toLowerCase().includes(wanted)) { + continue + } + const members = groups.get(entry.group) ?? [] + members.push(entry) + groups.set(entry.group, members) + } + return [...groups.entries()] +} + +/** The blocks of the scene, most used first, each with its count (v3e ObjectOverviewPanel). */ +function BlockList({ scene }: { scene: BlockScene | null }): React.JSX.Element { + const counts = useMemo(() => (scene === null ? [] : blockCounts(scene)), [scene]) + return ( +
+

Blocks

+ +
+ {counts.map(([state, count]) => ( +
+ {state.replace(DEFAULT_NAMESPACE_PREFIX, '')} + {NUMBER.format(count)} +
+ ))} +
+
+
+ ) +} + +// 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() + 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]) +} diff --git a/src/renderer/src/studio/SceneViewport.tsx b/src/renderer/src/studio/SceneViewport.tsx new file mode 100644 index 000000000..7f8ef3764 --- /dev/null +++ b/src/renderer/src/studio/SceneViewport.tsx @@ -0,0 +1,122 @@ +import { useEffect, useRef } from 'react' +import { Box3, Mesh, MeshBasicMaterial, PerspectiveCamera, Scene, Sphere, Vector3, WebGLRenderer } from 'three' +import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js' +import type { SceneMesh } from '../scene/sceneMesh' + +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 +const CUTOUT_ALPHA = 0.1 + +interface SceneViewportProps { + mesh: SceneMesh | null +} + +/** A block scene in 3D: drag to turn around it, right drag to move, scroll to come closer. Drawn only when it changes. */ +export function SceneViewport({ mesh }: SceneViewportProps): React.JSX.Element { + const host = useRef(null) + const stage = useRef(null) + + useEffect(() => { + const created = new Stage(host.current!) + stage.current = created + return () => { + created.dispose() + stage.current = null + } + }, []) + + useEffect(() => stage.current?.show(mesh), [mesh]) + + return
+} + +/** The renderer, camera and controls of one viewport. */ +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: Mesh | null = null + 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.requestFrame()) + this.resizes = new ResizeObserver(() => this.fitToHost()) + this.resizes.observe(host) + this.fitToHost() + } + + show(mesh: SceneMesh | null): void { + this.removeShown() + if (mesh === null) { + this.requestFrame() + return + } + const material = new MeshBasicMaterial({ map: mesh.atlas.texture, vertexColors: true, alphaTest: CUTOUT_ALPHA }) + this.shown = new Mesh(mesh.geometry, material) + this.scene.add(this.shown) + this.frame(new Box3().setFromBufferAttribute(mesh.geometry.getAttribute('position') as never)) + this.requestFrame() + } + + dispose(): void { + this.removeShown() + this.resizes.disconnect() + this.controls.dispose() + this.renderer.dispose() + this.renderer.domElement.remove() + } + + private frame(bounds: Box3): void { + 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.camera.updateProjectionMatrix() + this.controls.update() + } + + // The mesh and its atlas belong to whoever built them; only the material is the viewport's. + private removeShown(): void { + if (this.shown === null) { + return + } + this.scene.remove(this.shown) + ;(this.shown.material as MeshBasicMaterial).dispose() + this.shown = null + } + + 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) + }) + } +} diff --git a/src/renderer/src/studio/StudioToolbar.tsx b/src/renderer/src/studio/StudioToolbar.tsx index 386013f42..a14590184 100644 --- a/src/renderer/src/studio/StudioToolbar.tsx +++ b/src/renderer/src/studio/StudioToolbar.tsx @@ -15,6 +15,8 @@ interface StudioToolbarProps { 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 @@ -27,10 +29,36 @@ const THEME_ICONS: Record = { system: , light const THEME_NAMES: Record = { system: 'Theme: system', light: 'Theme: light', dark: 'Theme: dark' } export function StudioToolbar(props: StudioToolbarProps): React.JSX.Element { - const { toggles, onToggle } = props return (
{props.title} + {props.mapTools && } + +
+ + {props.world.world} + + + + + + + + + + +
+ ) +} + +function MapTools(props: StudioToolbarProps): React.JSX.Element { + const { toggles, onToggle } = props + return ( + <> @@ -53,25 +81,7 @@ export function StudioToolbar(props: StudioToolbarProps): React.JSX.Element { onToggle('regionBorders')}> Borders - -
- - {props.world.world} - - - - - - - - - - - + ) } diff --git a/src/renderer/src/studio/ViewList.tsx b/src/renderer/src/studio/ViewList.tsx index 362e0e074..001416f8d 100644 --- a/src/renderer/src/studio/ViewList.tsx +++ b/src/renderer/src/studio/ViewList.tsx @@ -1,4 +1,4 @@ -import { Gem, Map as MapIcon, Mountain, Sprout, Trees, Waves, type LucideIcon } from 'lucide-react' +import { Box, Gem, Map as MapIcon, Mountain, 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' @@ -11,7 +11,8 @@ const VIEW_ICONS: Record = { height: Mountain, landBiomes: Sprout, seaBiomes: Waves, - caveBiomes: Gem + caveBiomes: Gem, + 'iris:objects': Box } interface ViewListProps {