From 7042538b8907ddc1c3c518e73506a6f4c6bce3ff Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 10 Nov 2026 12:12:19 +0100 Subject: [PATCH] Draw block textures on saved-world columns in the studio 3D view The Blocks colouring of the saved-world view showed one flat average colour per block. Columns a block wide now show their top block's real textures: the top, the side of the top block, and the side of the blocks under it (dirt under grass), tinted as the client tints them. Coarser tiles keep the flat colours. Textures go in one growing atlas; textured faces are one quad per block, and sides deeper than 16 blocks under a column's top stay a single flat quad. v3: 950aca969 --- studio/src/renderer/src/scene/blockColors.ts | 3 +- .../src/renderer/src/scene/blockLooks.test.ts | 153 ++++++++++++++++++ studio/src/renderer/src/scene/blockLooks.ts | 130 +++++++++++++++ studio/src/renderer/src/scene/columnFaces.ts | 51 ++++-- studio/src/renderer/src/scene/columnField.ts | 13 ++ studio/src/renderer/src/scene/quadBatch.ts | 48 +++++- .../renderer/src/scene/savedTerrain.test.ts | 63 ++++++++ studio/src/renderer/src/scene/savedTerrain.ts | 22 ++- .../src/renderer/src/scene/savedTileSource.ts | 11 +- .../renderer/src/scene/terrainAtlas.test.ts | 23 +++ studio/src/renderer/src/scene/terrainAtlas.ts | 102 ++++++++++++ studio/src/renderer/src/scene/terrainMesh.ts | 11 +- .../src/scene/texturedTerrain.test.ts | 151 +++++++++++++++++ .../renderer/src/studio/SavedWorldStudio.tsx | 13 +- 14 files changed, 767 insertions(+), 27 deletions(-) create mode 100644 studio/src/renderer/src/scene/blockLooks.test.ts create mode 100644 studio/src/renderer/src/scene/blockLooks.ts create mode 100644 studio/src/renderer/src/scene/savedTerrain.test.ts create mode 100644 studio/src/renderer/src/scene/terrainAtlas.test.ts create mode 100644 studio/src/renderer/src/scene/terrainAtlas.ts create mode 100644 studio/src/renderer/src/scene/texturedTerrain.test.ts diff --git a/studio/src/renderer/src/scene/blockColors.ts b/studio/src/renderer/src/scene/blockColors.ts index fb26184fc..e8c3fbae1 100644 --- a/studio/src/renderer/src/scene/blockColors.ts +++ b/studio/src/renderer/src/scene/blockColors.ts @@ -81,7 +81,8 @@ function tinted(texture: ImageData, tint: number): ImageData { return texture } -function averageColor(texture: ImageData): number { +/** The mean colour of the pixels that are opaque enough, as 0xRRGGBB. */ +export 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) { diff --git a/studio/src/renderer/src/scene/blockLooks.test.ts b/studio/src/renderer/src/scene/blockLooks.test.ts new file mode 100644 index 000000000..19869b86b --- /dev/null +++ b/studio/src/renderer/src/scene/blockLooks.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, it } from 'vitest' +import { BlockLooks, faceTexturesOf } from './blockLooks' +import { BlockModels, type AssetSource } from './blockModels' +import { cellAt, type PictureSource, type UvCell } from './terrainAtlas' + +const SIDES = ['down', 'up', 'north', 'south', 'west', 'east'] +const GRASS_TINT = 0x91bd59 + +// Grass as the client has it: a dirt side with a tinted overlay element over it, a tinted top, and the dirt's bottom. +const FILES: Record = { + 'minecraft/blockstates/dirt.json': { variants: { '': { model: 'minecraft:block/dirt' } } }, + 'minecraft/models/block/dirt.json': { + textures: { particle: 'minecraft:block/dirt' }, + elements: [{ from: [0, 0, 0], to: [16, 16, 16], faces: Object.fromEntries(SIDES.map((side) => [side, { texture: 'minecraft:block/dirt', cullface: side }])) }] + }, + 'minecraft/blockstates/grass_block.json': { variants: { '': { model: 'minecraft:block/grass_block' } } }, + 'minecraft/models/block/grass_block.json': { + textures: { particle: 'minecraft:block/dirt' }, + elements: [ + { + from: [0, 0, 0], + to: [16, 16, 16], + faces: { + down: { texture: 'minecraft:block/dirt', cullface: 'down' }, + up: { texture: 'minecraft:block/grass_block_top', cullface: 'up', tintindex: 0 }, + north: { texture: 'minecraft:block/grass_block_side', cullface: 'north' }, + south: { texture: 'minecraft:block/grass_block_side', cullface: 'south' }, + west: { texture: 'minecraft:block/grass_block_side', cullface: 'west' }, + east: { texture: 'minecraft:block/grass_block_side', cullface: 'east' } + } + }, + { + from: [0, 0, 0], + to: [16, 16, 16], + faces: { north: { texture: 'minecraft:block/grass_block_side_overlay', tintindex: 0 } } + } + ] + }, + 'minecraft/blockstates/log.json': { variants: { '': { model: 'minecraft:block/log' } } }, + 'minecraft/models/block/log.json': { + textures: { particle: 'minecraft:block/log' }, + elements: [ + { + from: [0, 0, 0], + to: [16, 16, 16], + faces: { + down: { texture: 'minecraft:block/log_top', cullface: 'down' }, + up: { texture: 'minecraft:block/log_top', cullface: 'up' }, + north: { texture: 'minecraft:block/log', cullface: 'north' } + } + } + ] + }, + 'minecraft/blockstates/chest.json': { variants: { '': { model: 'minecraft:block/chest' } } }, + 'minecraft/models/block/chest.json': { textures: { particle: 'minecraft:block/oak_planks' } }, + 'minecraft/blockstates/glass.json': { variants: { '': { model: 'minecraft:block/glass' } } }, + 'minecraft/models/block/glass.json': {} +} + +const assets: AssetSource = { json: async (path) => FILES[path] ?? null } + +// Every texture is placed in the next cell, with a grey as light as its number, except the ones named missing. +function pictures(missing: string[] = []): PictureSource { + const cells = new Map() + return { + cellOf: async (textureId) => { + if (missing.includes(textureId)) { + return null + } + if (!cells.has(textureId)) { + cells.set(textureId, cellAt(cells.size + 1, (cells.size + 1) * 0x101010)) + } + return cells.get(textureId)! + } + } +} + +async function modelOf(block: string): ReturnType { + return new BlockModels(assets).model(block) +} + +describe('block faces', () => { + it('takes the top, the untinted side layer and the dirt under a block that caps dirt', async () => { + const faces = faceTexturesOf((await modelOf('minecraft:grass_block'))!, 'minecraft:block/dirt') + + expect(faces).toEqual({ + top: { texture: 'minecraft:block/grass_block_top', tintIndex: 0 }, + side: { texture: 'minecraft:block/grass_block_side', tintIndex: -1 }, + below: { texture: 'minecraft:block/dirt', tintIndex: -1 } + }) + }) + + it('shows the side below the top block when the block does not cap dirt', async () => { + const faces = faceTexturesOf((await modelOf('minecraft:log'))!, 'minecraft:block/dirt') + + expect(faces!.below).toEqual(faces!.side) + expect(faces!.side.texture).toBe('minecraft:block/log') + }) + + it('stands the particle texture in for a block the client draws without a model', async () => { + const faces = faceTexturesOf((await modelOf('minecraft:chest'))!, null) + + expect(faces).toEqual({ + top: { texture: 'minecraft:block/oak_planks', tintIndex: -1 }, + side: { texture: 'minecraft:block/oak_planks', tintIndex: -1 }, + below: { texture: 'minecraft:block/oak_planks', tintIndex: -1 } + }) + }) + + it('has none for a model without any texture', async () => { + expect(faceTexturesOf((await modelOf('minecraft:glass'))!, null)).toBeNull() + }) +}) + +describe('block looks', () => { + it('gives each face the cell of its texture and tints the faces that take a tint', async () => { + const looks = new BlockLooks(new BlockModels(assets), pictures()) + + const grass = (await looks.lookOf('minecraft:grass_block[snowy=false]'))! + + const dirt = (await looks.lookOf('minecraft:dirt'))! + + expect(grass.top.tint).toBe(GRASS_TINT) + expect(grass.side.tint).toBe(0xffffff) + expect(grass.below.cell).toBe(dirt.top.cell) + expect(grass.side.cell).not.toBe(grass.top.cell) + }) + + it("colours a face with its picture's average under the tint", async () => { + const looks = new BlockLooks(new BlockModels(assets), pictures()) + + const grass = (await looks.lookOf('minecraft:grass_block'))! + + expect(grass.top.color).toBe(multiplied(grass.top.cell.average, GRASS_TINT)) + expect(grass.side.color).toBe(grass.side.cell.average) + }) + + it('has no look for a block without a model, or one whose picture cannot be placed', async () => { + const looks = new BlockLooks(new BlockModels(assets), pictures(['minecraft:block/log_top'])) + + const found = await looks.looksOf(['minecraft:unknown_block', 'minecraft:log', 'minecraft:dirt', 'minecraft:dirt']) + + expect([...found.keys()]).toEqual(['minecraft:unknown_block', 'minecraft:log', 'minecraft:dirt']) + expect(found.get('minecraft:unknown_block')).toBeNull() + expect(found.get('minecraft:log')).toBeNull() + expect(found.get('minecraft:dirt')).not.toBeNull() + }) +}) + +function multiplied(color: number, tint: number): number { + const channel = (shift: number): number => Math.round((((color >> shift) & 0xff) * ((tint >> shift) & 0xff)) / 255) + return (channel(16) << 16) | (channel(8) << 8) | channel(0) +} diff --git a/studio/src/renderer/src/scene/blockLooks.ts b/studio/src/renderer/src/scene/blockLooks.ts new file mode 100644 index 000000000..867d20c9f --- /dev/null +++ b/studio/src/renderer/src/scene/blockLooks.ts @@ -0,0 +1,130 @@ +import { parseState, type BlockModel, type Direction, type ParsedState } from './blockModels' +import { blockTint } from './blockTints' +import type { PictureSource, UvCell } from './terrainAtlas' + +const NO_TINT_INDEX = -1 +const DIRT = 'minecraft:dirt' +const WHITE = 0xffffff + +/** One face of a block as the terrain draws it: its picture, the colour that tints the picture, and the picture's tinted average. */ +export interface FaceLook { + cell: UvCell + tint: number + color: number +} + +/** A block seen on a column: from above, on the side of its top block, and on the sides of the blocks under it. */ +export interface BlockLook { + top: FaceLook + side: FaceLook + below: FaceLook +} + +/** The texture a face takes from a block's model, and which of the block's tints colours it. */ +export interface FaceTexture { + texture: string + tintIndex: number +} + +export interface BlockFaceTextures { + top: FaceTexture + side: FaceTexture + below: FaceTexture +} + +/** Where block models come from. */ +export interface ModelSource { + model(stateKey: string): Promise +} + +/** + * The textures a column of the block shows. A side can be drawn in layers, like grass over dirt, and the untinted layer is + * the one that reads on its own. A column is one block drawn as tall as its side shows, so a grassy edge would repeat all + * the way down a cliff: blocks capping dirt show dirt under their top block instead. Null where the model has no texture. + */ +export function faceTexturesOf(model: BlockModel, dirtBottom: string | null): BlockFaceTextures | null { + const stood = model.particle === null ? null : { texture: model.particle, tintIndex: NO_TINT_INDEX } + const top = lastFacing(model, 'up') ?? stood + if (top === null) { + return null + } + const side = untintedFacing(model, 'north') ?? top + const bottom = lastFacing(model, 'down') + const below = bottom !== null && bottom.texture === dirtBottom ? bottom : side + return { top, side, below } +} + +function lastFacing(model: BlockModel, facing: Direction): FaceTexture | null { + const quad = model.quads.filter((candidate) => candidate.facing === facing).at(-1) + return quad === undefined ? null : { texture: quad.texture, tintIndex: quad.tintIndex } +} + +function untintedFacing(model: BlockModel, facing: Direction): FaceTexture | null { + const quads = model.quads.filter((candidate) => candidate.facing === facing) + const quad = quads.find((candidate) => candidate.tintIndex === NO_TINT_INDEX) ?? quads[0] + return quad === undefined ? null : { texture: quad.texture, tintIndex: quad.tintIndex } +} + +/** The look of each block state the terrain draws, read once. */ +export class BlockLooks { + private readonly looks = new Map>() + private dirtBottom: Promise | null = null + + constructor( + private readonly models: ModelSource, + private readonly pictures: PictureSource + ) {} + + /** The block's look; null when it has no model or texture, or one of its pictures cannot be placed. */ + lookOf(block: string): Promise { + let look = this.looks.get(block) + if (look === undefined) { + look = this.read(block).catch(() => null) + this.looks.set(block, look) + } + return look + } + + /** Every block's look, by name. */ + async looksOf(blocks: Iterable): Promise> { + const names = [...new Set(blocks)] + const looks = await Promise.all(names.map((name) => this.lookOf(name))) + return new Map(names.map((name, index) => [name, looks[index]])) + } + + private async read(block: string): Promise { + const model = await this.models.model(block) + if (model === null) { + return null + } + const textures = faceTexturesOf(model, await this.dirtBottomTexture()) + if (textures === null) { + return null + } + const state = parseState(block) + const [top, side, below] = await Promise.all([textures.top, textures.side, textures.below].map((face) => this.faceLook(face, state))) + return top === null || side === null || below === null ? null : { top, side, below } + } + + private async faceLook(face: FaceTexture, state: ParsedState): Promise { + const cell = await this.pictures.cellOf(face.texture) + if (cell === null) { + return null + } + const tint = blockTint(state.name, state.properties, face.tintIndex) + return { cell, tint, color: multiplied(cell.average, tint) } + } + + private dirtBottomTexture(): Promise { + this.dirtBottom ??= this.models.model(DIRT).then((model) => (model === null ? null : lastFacing(model, 'down')?.texture ?? null)) + return this.dirtBottom + } +} + +function multiplied(color: number, tint: number): number { + if (tint === WHITE) { + return color + } + const channel = (shift: number): number => Math.round((((color >> shift) & 0xff) * ((tint >> shift) & 0xff)) / 255) + return (channel(16) << 16) | (channel(8) << 8) | channel(0) +} diff --git a/studio/src/renderer/src/scene/columnFaces.ts b/studio/src/renderer/src/scene/columnFaces.ts index 4056a8acb..a1540fd37 100644 --- a/studio/src/renderer/src/scene/columnFaces.ts +++ b/studio/src/renderer/src/scene/columnFaces.ts @@ -1,5 +1,6 @@ +import type { BlockLook } from './blockLooks' import type { ColumnField } from './columnField' -import { QuadBatch, type Vec3 } from './quadBatch' +import { QuadBatch, type Picture, type Vec3 } from './quadBatch' import { submergedTint, sunk, tintAt } from './waterTint' // Light on each face, as Minecraft shades blocks: tops full, north and south sides lighter than east and west. @@ -7,6 +8,8 @@ const TOP_LIGHT = 1 const NORTH_SOUTH_LIGHT = 0.8 const EAST_WEST_LIGHT = 0.6 const WATER_COLOR = 0 +// Textured sides stop this many blocks under the top of their column; what lies deeper is one quad in the average colour of its picture. +const MOST_TEXTURED_SIDE_BLOCKS = 16 interface Span { bottom: number @@ -14,6 +17,8 @@ interface Span { color: number /** The top face of the water the span lies under, or null where it lies in the open. */ water: number | null + /** What the column's block looks like, or null where it shows its colour. */ + look: BlockLook | null } interface Side { @@ -37,10 +42,11 @@ const SIDES: readonly Side[] = [ * it lies. */ export function groundFaces(field: ColumnField, base: number): QuadBatch { - const batch = new QuadBatch(true) + const batch = new QuadBatch(true, field.pictures?.plain ?? null) addTops(field, batch, (column, row) => { const top = field.hasGround(column, row) ? field.groundTop[field.indexOf(column, row)] : null - return top === null ? null : { bottom: top, top, color: field.color[field.indexOf(column, row)], water: field.waterTopAt(column, row) } + const index = field.indexOf(column, row) + return top === null ? null : { bottom: top, top, color: field.color[index], water: field.waterTopAt(column, row), look: field.looks[index] } }) addSides(field, batch, (column, row, side) => { if (!field.hasGround(column, row)) { @@ -53,7 +59,8 @@ export function groundFaces(field: ColumnField, base: number): QuadBatch { return null } const water = field.waterTopAt(column, row) ?? field.waterTopAt(nextColumn, nextRow) - return { bottom, top, color: field.color[field.indexOf(column, row)], water } + const index = field.indexOf(column, row) + return { bottom, top, color: field.color[index], water, look: field.looks[index] } }) return batch } @@ -67,7 +74,7 @@ export function waterFaces(field: ColumnField): QuadBatch { const batch = new QuadBatch(false) addTops(field, batch, (column, row) => { const top = field.waterTopAt(column, row) - return top === null ? null : { bottom: top, top, color: WATER_COLOR, water: null } + return top === null ? null : { bottom: top, top, color: WATER_COLOR, water: null, look: null } }) addSides(field, batch, (column, row, side) => { const top = field.waterTopAt(column, row) @@ -79,7 +86,7 @@ export function waterFaces(field: ColumnField): QuadBatch { return null } const bottom = Math.max(next, field.groundTop[field.indexOf(column, row)]) - return bottom < top ? { bottom, top, color: WATER_COLOR, water: null } : null + return bottom < top ? { bottom, top, color: WATER_COLOR, water: null, look: null } : null }) return batch } @@ -88,7 +95,9 @@ function addTops(field: ColumnField, batch: QuadBatch, spanAt: (column: number, for (let row = 0; row < field.rows; row++) { mergeRuns(field.columns, (column) => spanAt(column, row), (first, count, span) => { const step = field.blocksPerColumn - batch.add([field.originX + first * step, span.top, field.originZ + row * step], [count * step, 0, 0], [0, 0, step], topColor(span)) + const color = topColor(span) + const picture: Picture | null = span.look === null ? null : { cell: span.look.top.cell, standing: false } + batch.add([field.originX + first * step, span.top, field.originZ + row * step], [count * step, 0, 0], [0, 0, step], color, color, picture) }) } } @@ -102,8 +111,12 @@ function addSides(field: ColumnField, batch: QuadBatch, spanAt: (column: number, const columnOf = (step: number): number => (runsAlongRow ? step : lane) const rowOf = (step: number): number => (runsAlongRow ? lane : step) mergeRuns(length, (step) => spanAt(columnOf(step), rowOf(step), side), (first, count, span) => { - const light = shaded(span.color, side.light) for (const part of sideParts(span)) { + if (span.look !== null) { + addTexturedSide(batch, field, side, columnOf(first), rowOf(first), part, span.look, span.top) + continue + } + const light = shaded(span.color, side.light) batch.add(...sideQuad(field, side, columnOf(first), rowOf(first), count, part), sunk(light, part.bottomTint), sunk(light, part.topTint)) } }) @@ -112,7 +125,7 @@ function addSides(field: ColumnField, batch: QuadBatch, spanAt: (column: number, } function topColor(span: Span): Vec3 { - const light = shaded(span.color, TOP_LIGHT) + const light = shaded(span.look === null ? span.color : span.look.top.tint, TOP_LIGHT) return span.water === null ? light : sunk(light, tintAt(span.water - span.top)) } @@ -137,6 +150,24 @@ function sideParts(span: Span): SidePart[] { ] } +// One picture to a block: the column's top block in its side's, the blocks under it in theirs. Under the textured depth +// the rest is a single quad in the colour of the picture. +function addTexturedSide(batch: QuadBatch, field: ColumnField, side: Side, column: number, row: number, part: SidePart, look: BlockLook, columnTop: number): void { + const tintAt = (y: number): number => part.bottomTint + ((part.topTint - part.bottomTint) * (y - part.bottom)) / (part.top - part.bottom) + const texturedFloor = Math.max(part.bottom, columnTop - MOST_TEXTURED_SIDE_BLOCKS) + for (let top = part.top; top > texturedFloor; top--) { + const face = top === columnTop ? look.side : look.below + const light = shaded(face.tint, side.light) + const picture: Picture = { cell: face.cell, standing: true } + batch.add(...sideQuad(field, side, column, row, 1, { ...part, bottom: top - 1, top }), sunk(light, tintAt(top - 1)), sunk(light, tintAt(top)), picture) + } + const deepTop = Math.min(part.top, texturedFloor) + if (deepTop > part.bottom) { + const light = shaded(look.below.color, side.light) + batch.add(...sideQuad(field, side, column, row, 1, { ...part, top: deepTop }), sunk(light, part.bottomTint), sunk(light, tintAt(deepTop))) + } +} + // The corner a side starts from is the one on its left as seen from outside, so it runs and rises into view. function sideQuad(field: ColumnField, side: Side, column: number, row: number, count: number, span: Span): [Vec3, Vec3, Vec3] { const step = field.blocksPerColumn @@ -174,7 +205,7 @@ function mergeRuns(length: number, spanAt: (index: number) => Span | null, emit: } function sameSpan(span: Span, other: Span | null): boolean { - return other !== null && other.top === span.top && other.bottom === span.bottom && other.color === span.color && other.water === span.water + return span.look === null && other !== null && other.look === null && other.top === span.top && other.bottom === span.bottom && other.color === span.color && other.water === span.water } function shaded(color: number, light: number): Vec3 { diff --git a/studio/src/renderer/src/scene/columnField.ts b/studio/src/renderer/src/scene/columnField.ts index b15b0a350..89fe576da 100644 --- a/studio/src/renderer/src/scene/columnField.ts +++ b/studio/src/renderer/src/scene/columnField.ts @@ -1,3 +1,5 @@ +import type { BlockLook } from './blockLooks' +import type { TerrainPictures } from './terrainAtlas' import type { TerrainSurface } from './terrainMesh' import type { ColumnArea } from './terrainTiles' @@ -17,6 +19,10 @@ export class ColumnField { readonly groundTop: Float32Array readonly waterTop: Float32Array readonly color: Int32Array + /** What each column's block looks like, or null to show its colour. */ + readonly looks: (BlockLook | null)[] + /** The atlas of the looks, or null where no column has one. */ + readonly pictures: TerrainPictures | null constructor(surface: TerrainSurface, holes: readonly ColumnArea[] = []) { this.columns = surface.columns @@ -28,6 +34,9 @@ export class ColumnField { this.groundTop = new Float32Array(count).fill(NO_VALUE) this.waterTop = new Float32Array(count).fill(NO_VALUE) this.color = new Int32Array(count) + this.looks = new Array(count).fill(null) + const hasPictures = surface.pictures !== undefined + let anyLook = false const inHole = this.holeMask(holes) for (let row = 0; row < this.rows; row++) { for (let column = 0; column < this.columns; column++) { @@ -40,8 +49,12 @@ export class ColumnField { this.groundTop[index] = ground + 1 this.waterTop[index] = water === null ? NO_VALUE : water + 1 this.color[index] = surface.colorAt(column, row) + const look = hasPictures ? (surface.lookAt?.(column, row) ?? null) : null + this.looks[index] = look + anyLook ||= look !== null } } + this.pictures = anyLook ? (surface.pictures ?? null) : null } indexOf(column: number, row: number): number { diff --git a/studio/src/renderer/src/scene/quadBatch.ts b/studio/src/renderer/src/scene/quadBatch.ts index ed71e8ca8..bb6ffa64b 100644 --- a/studio/src/renderer/src/scene/quadBatch.ts +++ b/studio/src/renderer/src/scene/quadBatch.ts @@ -1,18 +1,38 @@ import { BufferAttribute, BufferGeometry } from 'three' +import type { UvCell } from './terrainAtlas' const VERTICES_PER_QUAD = 4 const INDICES_PER_QUAD = 6 const COMPONENTS = 3 +const UV_COMPONENTS = 2 const FIRST_CAPACITY_QUADS = 1024 -/** Flat quads gathered for one geometry; vertices are not shared, so every quad keeps its own colour and shade. */ +/** + * A picture on a quad. A standing picture is upright seen from outside, as on a side: it runs from the far end of + * {@code along} on its left to the near end on its right, with its top edge at the far end of {@code up}. A lying one is + * as seen from above, as on a top: left to right along {@code along}, its top edge at the near end of {@code up}. + */ +export interface Picture { + cell: UvCell + standing: boolean +} + +/** + * Flat quads gathered for one geometry; vertices are not shared, so every quad keeps its own colour and shade. A batch + * given a {@code plain} cell is textured: quads without a picture show that cell, so their colour alone is seen. + */ export class QuadBatch { private positions = new Float32Array(FIRST_CAPACITY_QUADS * VERTICES_PER_QUAD * COMPONENTS) private colors: Float32Array | null + private uvs: Float32Array | null private quads = 0 - constructor(coloured: boolean) { + constructor( + coloured: boolean, + private readonly plain: UvCell | null = null + ) { this.colors = coloured ? new Float32Array(this.positions.length) : null + this.uvs = plain === null ? null : new Float32Array(FIRST_CAPACITY_QUADS * VERTICES_PER_QUAD * UV_COMPONENTS) } get count(): number { @@ -23,7 +43,7 @@ export class QuadBatch { * A quad from {@code origin} along {@code along} and {@code up}; it faces the way {@code up} crosses {@code along}. * Colours are red, green and blue from 0 to 1; the corners at the far end of {@code up} take {@code topColor}. */ - add(origin: Vec3, along: Vec3, up: Vec3, color: Vec3 | null, topColor: Vec3 | null = color): void { + add(origin: Vec3, along: Vec3, up: Vec3, color: Vec3 | null, topColor: Vec3 | null = color, picture: Picture | null = null): void { this.reserveOne() const first = this.quads * VERTICES_PER_QUAD * COMPONENTS for (let corner = 0; corner < VERTICES_PER_QUAD; corner++) { @@ -36,6 +56,7 @@ export class QuadBatch { this.colors[at] = cornerColor[axis] } } + this.setUv(this.quads * VERTICES_PER_QUAD + corner, alongSteps, upSteps, picture) } this.quads++ } @@ -47,6 +68,9 @@ export class QuadBatch { if (this.colors !== null) { geometry.setAttribute('color', new BufferAttribute(this.colors.slice(0, used), COMPONENTS)) } + if (this.uvs !== null) { + geometry.setAttribute('uv', new BufferAttribute(this.uvs.slice(0, this.quads * VERTICES_PER_QUAD * UV_COMPONENTS), UV_COMPONENTS)) + } const indices = new Uint32Array(this.quads * INDICES_PER_QUAD) for (let quad = 0; quad < this.quads; quad++) { const first = quad * VERTICES_PER_QUAD @@ -56,6 +80,21 @@ export class QuadBatch { return geometry } + private setUv(vertex: number, alongSteps: number, upSteps: number, picture: Picture | null): void { + if (this.uvs === null || this.plain === null) { + return + } + const at = vertex * UV_COMPONENTS + if (picture === null) { + this.uvs[at] = this.plain.u + this.plain.width / 2 + this.uvs[at + 1] = this.plain.v + this.plain.height / 2 + return + } + const [rightSteps, downSteps] = picture.standing ? [1 - alongSteps, 1 - upSteps] : [alongSteps, upSteps] + this.uvs[at] = picture.cell.u + rightSteps * picture.cell.width + this.uvs[at + 1] = picture.cell.v + downSteps * picture.cell.height + } + private reserveOne(): void { if ((this.quads + 1) * VERTICES_PER_QUAD * COMPONENTS <= this.positions.length) { return @@ -64,6 +103,9 @@ export class QuadBatch { if (this.colors !== null) { this.colors = grown(this.colors) } + if (this.uvs !== null) { + this.uvs = grown(this.uvs) + } } } diff --git a/studio/src/renderer/src/scene/savedTerrain.test.ts b/studio/src/renderer/src/scene/savedTerrain.test.ts new file mode 100644 index 000000000..1c6289a23 --- /dev/null +++ b/studio/src/renderer/src/scene/savedTerrain.test.ts @@ -0,0 +1,63 @@ +import { Texture } from 'three' +import { describe, expect, it } from 'vitest' +import type { SavedTile } from '../bridge/types' +import type { BlockLook } from './blockLooks' +import { SavedTerrain, type ReadSavedTile, type SavedTerrainColoring } from './savedTerrain' +import { cellAt, type TerrainPictures } from './terrainAtlas' + +const GRASS = 'minecraft:grass_block' +const STONE = 'minecraft:stone' +const FACE = { cell: cellAt(1, 0x808080), tint: 0xffffff, color: 0x808080 } +const LOOK: BlockLook = { top: FACE, side: FACE, below: FACE } +const pictures: TerrainPictures = { texture: new Texture(), plain: cellAt(0, 0xffffff) } + +// Two by two columns: grass, stone, then two of stone. +const tile = { + size: 2, + blocksPerPixel: 1, + groundY: Int16Array.of(64, 64, 64, 64), + waterSurfaceY: Int16Array.of(-1, -1, -1, -1), + blocks: Int16Array.of(0, 1, 1, 1), + biomes: Int16Array.of(0, 0, 0, 0), + blockNames: [GRASS, STONE], + biomeLabels: [{ color: 0x00ff00 }], + noGround: -32768, + noWater: -1 +} as unknown as SavedTile + +const read: ReadSavedTile = { + tile, + blockColors: new Map([ + [GRASS, 0x4a7a2a], + [STONE, 0x7f7f7f] + ]), + blockLooks: new Map([[GRASS, LOOK]]) +} + +function terrain(coloring: SavedTerrainColoring, level = 0): SavedTerrain { + return new SavedTerrain(read, { level, tileX: 0, tileZ: 0 }, coloring, null, pictures) +} + +describe('saved terrain looks', () => { + it('shows the look of the block of a column when coloured by blocks and a column is a block', () => { + expect(terrain('blocks').lookAt(0, 0)).toBe(LOOK) + }) + + it('has no look for a block without one', () => { + expect(terrain('blocks').lookAt(1, 0)).toBeNull() + }) + + it('has none in the other colourings', () => { + expect(terrain('biomes').lookAt(0, 0)).toBeNull() + expect(terrain('height').lookAt(0, 0)).toBeNull() + }) + + it('has none where a column is wider than a block', () => { + expect(terrain('blocks', 1).lookAt(0, 0)).toBeNull() + }) + + it('still colours by block where there is no look', () => { + expect(terrain('blocks').colorAt(0, 0)).toBe(0x4a7a2a) + expect(terrain('blocks').colorAt(1, 0)).toBe(0x7f7f7f) + }) +}) diff --git a/studio/src/renderer/src/scene/savedTerrain.ts b/studio/src/renderer/src/scene/savedTerrain.ts index 474f819f4..ec1660366 100644 --- a/studio/src/renderer/src/scene/savedTerrain.ts +++ b/studio/src/renderer/src/scene/savedTerrain.ts @@ -1,21 +1,28 @@ import type { SavedTile } from '../bridge/types' import { heightColor } from '../map/heightColors' +import type { BlockLook } from './blockLooks' +import type { TerrainPictures } from './terrainAtlas' import type { TerrainSurface } from './terrainMesh' import { blocksPerColumn, originXOf, originZOf, type TerrainTile } from './terrainTiles' export type SavedTerrainColoring = 'biomes' | 'blocks' | 'height' -/** A saved tile and the colour of every block it holds. */ +/** A saved tile, the colour of every block it holds, and the look of each where the tile is fine enough to show textures. */ export interface ReadSavedTile { tile: SavedTile blockColors: Map + blockLooks: Map } // A world without water is measured from where vanilla's sea would be. const VANILLA_SEA_LEVEL = 63 const UNKNOWN_BLOCK_COLOR = 0x7f7f7f +export const FINEST_BLOCKS_PER_COLUMN = 1 -/** One saved tile as a surface, a column to a pixel, so each is the block it was read from. */ +/** + * One saved tile as a surface, a column to a pixel, so each is the block it was read from. Coloured by blocks, columns a + * block wide show their blocks' textures. + */ export class SavedTerrain implements TerrainSurface { readonly columns: number readonly rows: number @@ -27,7 +34,8 @@ export class SavedTerrain implements TerrainSurface { private readonly read: ReadSavedTile, place: TerrainTile, private readonly coloring: SavedTerrainColoring, - private readonly seaLevel: number | null + private readonly seaLevel: number | null, + readonly pictures: TerrainPictures ) { this.columns = read.tile.size this.rows = read.tile.size @@ -46,6 +54,14 @@ export class SavedTerrain implements TerrainSurface { return water === this.read.tile.noWater ? null : water } + lookAt(column: number, row: number): BlockLook | null { + if (this.coloring !== 'blocks' || this.blocksPerColumn !== FINEST_BLOCKS_PER_COLUMN) { + return null + } + const { tile, blockLooks } = this.read + return blockLooks.get(tile.blockNames[tile.blocks[this.pixelAt(column, row)]]) ?? null + } + colorAt(column: number, row: number): number { const { tile, blockColors } = this.read const pixel = this.pixelAt(column, row) diff --git a/studio/src/renderer/src/scene/savedTileSource.ts b/studio/src/renderer/src/scene/savedTileSource.ts index 1d20e309a..77706be74 100644 --- a/studio/src/renderer/src/scene/savedTileSource.ts +++ b/studio/src/renderer/src/scene/savedTileSource.ts @@ -1,7 +1,8 @@ import type { BridgeClient } from '../bridge/BridgeClient' import type { TileSource } from '../map/TileStore' import type { BlockColors } from './blockColors' -import type { ReadSavedTile } from './savedTerrain' +import type { BlockLook, BlockLooks } from './blockLooks' +import { FINEST_BLOCKS_PER_COLUMN, type ReadSavedTile } from './savedTerrain' import { TILE_COLUMNS } from './terrainTiles' /** Which saved world the tiles are read from. */ @@ -14,13 +15,15 @@ export interface SavedLayer { // The block and biome names and colours a tile carries, as far as they add up. const ESTIMATED_EXTRA_BYTES_PER_COLUMN = 4 -/** A saved world's tiles, each with the colour of every block in it. */ -export function savedTileSource(client: BridgeClient, blockColors: BlockColors): TileSource { +/** A saved world's tiles, each with the colour of every block in it, and their looks where a column is one block. */ +export function savedTileSource(client: BridgeClient, blockColors: BlockColors, blockLooks: BlockLooks): TileSource { return { layerKey: (layer) => `${layer.worldId}/${layer.readings}`, fetch: async (address, layer, signal) => { const tile = await client.savedTile(layer.worldId, address.tileX, address.tileZ, address.blocksPerPixel, TILE_COLUMNS, signal) - return { tile, blockColors: await blockColors.colorsOf(tile.blockNames) } + const textured = address.blocksPerPixel === FINEST_BLOCKS_PER_COLUMN + const [colors, looks] = await Promise.all([blockColors.colorsOf(tile.blockNames), textured ? blockLooks.looksOf(tile.blockNames) : new Map()]) + return { tile, blockColors: colors, blockLooks: looks } }, bytesOf: ({ tile }) => tile.groundY.byteLength + tile.waterSurfaceY.byteLength + tile.blocks.byteLength + tile.biomes.byteLength + tile.size * tile.size * ESTIMATED_EXTRA_BYTES_PER_COLUMN diff --git a/studio/src/renderer/src/scene/terrainAtlas.test.ts b/studio/src/renderer/src/scene/terrainAtlas.test.ts new file mode 100644 index 000000000..d1b0993cd --- /dev/null +++ b/studio/src/renderer/src/scene/terrainAtlas.test.ts @@ -0,0 +1,23 @@ +import { describe, expect, it } from 'vitest' +import { cellAt, MOST_CELLS } from './terrainAtlas' + +const CELLS_PER_SIDE = Math.sqrt(MOST_CELLS) + +describe('terrain atlas cells', () => { + it('counts cells row by row from the top left', () => { + expect(cellAt(0, 0)).toMatchObject({ u: 0, v: 0 }) + expect(cellAt(1, 0).u).toBe(1 / CELLS_PER_SIDE) + expect(cellAt(CELLS_PER_SIDE, 0)).toMatchObject({ u: 0, v: 1 / CELLS_PER_SIDE }) + }) + + it('keeps every cell inside the atlas and apart from the others', () => { + const last = cellAt(MOST_CELLS - 1, 0) + expect(last.u + last.width).toBeCloseTo(1) + expect(last.v + last.height).toBeCloseTo(1) + expect(cellAt(5, 0).width).toBe(1 / CELLS_PER_SIDE) + }) + + it('carries the average colour of its picture', () => { + expect(cellAt(3, 0x336699).average).toBe(0x336699) + }) +}) diff --git a/studio/src/renderer/src/scene/terrainAtlas.ts b/studio/src/renderer/src/scene/terrainAtlas.ts new file mode 100644 index 000000000..13bb4d5cf --- /dev/null +++ b/studio/src/renderer/src/scene/terrainAtlas.ts @@ -0,0 +1,102 @@ +import { CanvasTexture, NearestFilter, SRGBColorSpace, type Texture } from 'three' +import { averageColor } from './blockColors' +import { texturePath, type ImageSource } from './textureAtlas' + +/** Where one picture lies in the atlas, as a rectangle of it from 0 to 1, and the picture's average colour as 0xRRGGBB. */ +export interface UvCell { + u: number + v: number + width: number + height: number + average: number +} + +/** The atlas as the terrain draws it. */ +export interface TerrainPictures { + readonly texture: Texture + /** A cell of plain white, for faces that show only their colour. */ + readonly plain: UvCell +} + +/** Where block pictures are placed. */ +export interface PictureSource { + /** The cell of the texture such as {@code minecraft:block/stone}, or null when it is missing or the atlas is full. */ + cellOf(textureId: string): Promise +} + +const CELL_PIXELS = 16 +const CELLS_PER_SIDE = 64 +const ATLAS_PIXELS = CELLS_PER_SIDE * CELL_PIXELS +const PLAIN_CELL = 0 +const WHITE = '#ffffff' +const WHITE_COLOR = 0xffffff + +/** The cell with this number, counted row by row from the top left. */ +export function cellAt(index: number, average: number): UvCell { + return { + u: (index % CELLS_PER_SIDE) / CELLS_PER_SIDE, + v: Math.floor(index / CELLS_PER_SIDE) / CELLS_PER_SIDE, + width: 1 / CELLS_PER_SIDE, + height: 1 / CELLS_PER_SIDE, + average + } +} + +/** The most pictures one atlas holds, the plain cell among them. */ +export const MOST_CELLS = CELLS_PER_SIDE * CELLS_PER_SIDE + +/** + * Block textures of the terrain in one image, each scaled to 16 pixels and placed the first time it is asked for, so + * the atlas grows as tiles arrive; an animated texture shows its first frame. + */ +export class TerrainAtlas implements TerrainPictures, PictureSource { + readonly texture: CanvasTexture + readonly plain = cellAt(PLAIN_CELL, WHITE_COLOR) + + private readonly drawing: CanvasRenderingContext2D + private readonly cells = new Map>() + private used = PLAIN_CELL + 1 + + constructor(private readonly images: ImageSource) { + const canvas = document.createElement('canvas') + canvas.width = ATLAS_PIXELS + canvas.height = ATLAS_PIXELS + this.drawing = canvas.getContext('2d', { willReadFrequently: true })! + this.drawing.imageSmoothingEnabled = false + this.drawing.fillStyle = WHITE + this.drawing.fillRect(0, 0, CELL_PIXELS, CELL_PIXELS) + 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 + } + + cellOf(textureId: string): Promise { + let cell = this.cells.get(textureId) + if (cell === undefined) { + cell = this.place(textureId) + this.cells.set(textureId, cell) + } + return cell + } + + dispose(): void { + this.texture.dispose() + } + + private async place(textureId: string): Promise { + const bitmap = await this.images.image(texturePath(textureId)).catch(() => null) + if (bitmap === null || this.used >= MOST_CELLS) { + return null + } + const index = this.used++ + const placed = cellAt(index, WHITE_COLOR) + const left = placed.u * ATLAS_PIXELS + const top = placed.v * ATLAS_PIXELS + this.drawing.drawImage(bitmap, 0, 0, bitmap.width, Math.min(bitmap.width, bitmap.height), left, top, CELL_PIXELS, CELL_PIXELS) + this.texture.needsUpdate = true + return { ...placed, average: averageColor(this.drawing.getImageData(left, top, CELL_PIXELS, CELL_PIXELS)) } + } +} diff --git a/studio/src/renderer/src/scene/terrainMesh.ts b/studio/src/renderer/src/scene/terrainMesh.ts index 2794ecb05..2cff31522 100644 --- a/studio/src/renderer/src/scene/terrainMesh.ts +++ b/studio/src/renderer/src/scene/terrainMesh.ts @@ -1,6 +1,8 @@ import { DoubleSide, FrontSide, Group, Mesh, MeshBasicMaterial } from 'three' +import type { BlockLook } from './blockLooks' import { groundFaces, waterFaces } from './columnFaces' import { ColumnField } from './columnField' +import type { TerrainPictures } from './terrainAtlas' import type { ColumnArea } from './terrainTiles' import { WATER_SURFACE_COLOR, WATER_SURFACE_OPACITY } from './waterTint' @@ -21,6 +23,10 @@ export interface TerrainSurface { /** The Y of the water's top block over the column, or null where it is dry. */ waterAt(column: number, row: number): number | null colorAt(column: number, row: number): number + /** The atlas that {@link lookAt}'s pictures lie in; a surface without one is drawn in colour alone. */ + readonly pictures?: TerrainPictures + /** What the block of the column looks like, or null to show the column in its colour. */ + lookAt?(column: number, row: number): BlockLook | null } export interface TerrainMesh { @@ -32,7 +38,8 @@ export interface TerrainMesh { /** * The surface as columns with their faces merged where neighbours show the same one, flat-shaded as Minecraft shades * blocks, with the ground under water sunk toward a deep colour and a light sheet of water over it. Sides on the edge reach down to {@code base}, so tiles of ground next to - * each other leave no cracks. The columns in {@code holes} are left out, for finer ground to fill. + * each other leave no cracks. The columns in {@code holes} are left out, for finer ground to fill. Columns with a look + * show their block's textures, one picture to a block face. */ export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: readonly ColumnArea[] = []): TerrainMesh { const field = new ColumnField(surface, holes) @@ -42,7 +49,7 @@ export function buildTerrainMesh(surface: TerrainSurface, base: number, holes: r } const ground = groundFaces(field, base).geometry() const water = waterFaces(field).geometry() - const groundMaterial = new MeshBasicMaterial({ vertexColors: true, side: FrontSide }) + const groundMaterial = new MeshBasicMaterial({ vertexColors: true, side: FrontSide, map: field.pictures?.texture ?? null }) const waterMaterial = new MeshBasicMaterial({ color: WATER_SURFACE_COLOR, transparent: true, opacity: WATER_SURFACE_OPACITY, depthWrite: false, side: DoubleSide }) group.add(new Mesh(ground, groundMaterial), new Mesh(water, waterMaterial)) return { diff --git a/studio/src/renderer/src/scene/texturedTerrain.test.ts b/studio/src/renderer/src/scene/texturedTerrain.test.ts new file mode 100644 index 000000000..4e37b708f --- /dev/null +++ b/studio/src/renderer/src/scene/texturedTerrain.test.ts @@ -0,0 +1,151 @@ +import { Texture, Vector3, type BufferGeometry, type Mesh, type MeshBasicMaterial } from 'three' +import { describe, expect, it } from 'vitest' +import type { BlockLook, FaceLook } from './blockLooks' +import { cellAt, type TerrainPictures } from './terrainAtlas' +import { buildTerrainMesh, type TerrainSurface } from './terrainMesh' + +const ORIGIN_X = 100 +const ORIGIN_Z = 200 +const PEAK_COLUMN = 1 +const PEAK_GROUND = 12 +const LOW_GROUND = 10 +const HIGH_GROUND = 70 +const FLOOR = 0 +const MOST_TEXTURED_SIDE_BLOCKS = 16 +const GRASS_TINT = 0x91bd59 +const WHITE = 0xffffff + +const plain = cellAt(0, WHITE) +const pictures: TerrainPictures = { texture: new Texture(), plain } +const cellWidth = plain.width + +function face(index: number, tint = WHITE): FaceLook { + return { cell: cellAt(index, 0x808080), tint, color: 0x606060 } +} + +const grass: BlockLook = { top: face(1, GRASS_TINT), side: face(2), below: face(3) } + +// Three by three columns of one-block ground, the middle one two blocks above the rest. +function surfaceOf(lookAt: TerrainSurface['lookAt'], ground = LOW_GROUND, withPictures = true): TerrainSurface { + return { + columns: 3, + rows: 3, + originX: ORIGIN_X, + originZ: ORIGIN_Z, + blocksPerColumn: 1, + groundAt: (column, row) => (column === PEAK_COLUMN && row === PEAK_COLUMN ? ground + (PEAK_GROUND - LOW_GROUND) : ground), + waterAt: () => null, + colorAt: () => 0x808080, + ...(withPictures ? { pictures, lookAt } : {}) + } +} + +function groundOf(terrain: TerrainSurface): Mesh { + return buildTerrainMesh(terrain, FLOOR).object.children[0] as Mesh +} + +interface Placed { + quad: number + middle: Vector3 + normal: Vector3 +} + +function placed(geometry: BufferGeometry): Placed[] { + const positions = geometry.getAttribute('position') + const found: Placed[] = [] + for (let quad = 0; quad < positions.count / 4; quad++) { + const corner = (index: number): Vector3 => new Vector3().fromBufferAttribute(positions, quad * 4 + index) + const [origin, up, along, far] = [corner(0), corner(1), corner(2), corner(3)] + found.push({ + quad, + middle: origin.clone().add(far).multiplyScalar(0.5), + normal: up.clone().sub(origin).cross(along.clone().sub(origin)).normalize() + }) + } + return found +} + +function uvOf(geometry: BufferGeometry, quad: number, corner: number): [number, number] { + const uvs = geometry.getAttribute('uv') + return [uvs.getX(quad * 4 + corner), uvs.getY(quad * 4 + corner)] +} + +function peakSides(ground: Mesh): Placed[] { + return placed(ground.geometry) + .filter((face) => face.normal.z === -1 && face.middle.x === ORIGIN_X + PEAK_COLUMN + 0.5 && face.middle.z === ORIGIN_Z + PEAK_COLUMN) + .sort((first, second) => second.middle.y - first.middle.y) +} + +describe('textured terrain', () => { + it('draws a top for every column, as tall as it is wide, with the texture of its block', () => { + const ground = groundOf(surfaceOf(() => grass)) + const tops = placed(ground.geometry).filter((face) => face.normal.y === 1) + + expect(tops).toHaveLength(9) + expect((ground.material as MeshBasicMaterial).map).toBe(pictures.texture) + const top = tops.find((candidate) => candidate.middle.x === ORIGIN_X + 0.5 && candidate.middle.z === ORIGIN_Z + 0.5)! + expect(uvOf(ground.geometry, top.quad, 0)).toEqual([grass.top.cell.u, grass.top.cell.v]) + expect(uvOf(ground.geometry, top.quad, 2)).toEqual([grass.top.cell.u + cellWidth, grass.top.cell.v]) + expect(uvOf(ground.geometry, top.quad, 1)).toEqual([grass.top.cell.u, grass.top.cell.v + cellWidth]) + }) + + it('multiplies the picture with the tint of its face, and with nothing on an untinted one', () => { + const ground = groundOf(surfaceOf(() => grass)) + const colors = ground.geometry.getAttribute('color') + const top = placed(ground.geometry).find((face) => face.normal.y === 1)! + const side = peakSides(ground)[0] + + expect(colors.getX(top.quad * 4)).toBeCloseTo(0x91 / 255) + expect(colors.getX(side.quad * 4)).toBeCloseTo(0.8) + }) + + it('shows the side of the top block over the blocks of the side below it, upright seen from outside', () => { + const ground = groundOf(surfaceOf(() => grass)) + const [topBlock, blockBelow] = peakSides(ground) + + expect(topBlock.middle.y).toBe(PEAK_GROUND + 1 - 0.5) + expect(blockBelow.middle.y).toBe(PEAK_GROUND + 1 - 1.5) + expect(uvOf(ground.geometry, topBlock.quad, 3)).toEqual([grass.side.cell.u, grass.side.cell.v]) + expect(uvOf(ground.geometry, topBlock.quad, 0)).toEqual([grass.side.cell.u + cellWidth, grass.side.cell.v + cellWidth]) + expect(uvOf(ground.geometry, blockBelow.quad, 3)).toEqual([grass.below.cell.u, grass.below.cell.v]) + }) + + it('draws deep sides as one flat quad in the average colour below the textured blocks', () => { + const ground = groundOf(surfaceOf(() => grass, HIGH_GROUND)) + const northEdge = placed(ground.geometry) + .filter((face) => face.normal.z === -1 && face.middle.x === ORIGIN_X + 1.5 && face.middle.z === ORIGIN_Z) + .sort((first, second) => second.middle.y - first.middle.y) + const deep = northEdge[northEdge.length - 1] + const texturedFloor = HIGH_GROUND + 1 - MOST_TEXTURED_SIDE_BLOCKS + + expect(northEdge).toHaveLength(MOST_TEXTURED_SIDE_BLOCKS + 1) + expect(deep.middle.y).toBe((FLOOR + texturedFloor) / 2) + expect(uvOf(ground.geometry, deep.quad, 0)).toEqual([plain.u + cellWidth / 2, plain.v + cellWidth / 2]) + expect(ground.geometry.getAttribute('color').getX(deep.quad * 4)).toBeCloseTo((0x60 / 255) * 0.8) + }) + + it('shows columns without a look in their colour on the plain cell, among textured ones', () => { + const ground = groundOf(surfaceOf((column, row) => (column === 0 && row === 0 ? null : grass))) + const tops = placed(ground.geometry).filter((face) => face.normal.y === 1) + const bare = tops.find((face) => face.middle.x === ORIGIN_X + 0.5 && face.middle.z === ORIGIN_Z + 0.5)! + + expect(tops).toHaveLength(9) + expect(uvOf(ground.geometry, bare.quad, 0)).toEqual([plain.u + cellWidth / 2, plain.v + cellWidth / 2]) + expect(ground.geometry.getAttribute('color').getX(bare.quad * 4)).toBeCloseTo(0x80 / 255) + }) + + it('keeps merging columns that show no texture, and draws no uvs for them', () => { + const ground = groundOf(surfaceOf(() => null)) + const tops = placed(ground.geometry).filter((face) => face.normal.y === 1) + + expect(tops).toHaveLength(5) + expect(ground.geometry.getAttribute('uv')).toBeUndefined() + expect((ground.material as MeshBasicMaterial).map).toBeNull() + }) + + it('draws a surface without an atlas in its colour alone', () => { + const ground = groundOf(surfaceOf(() => grass, LOW_GROUND, false)) + + expect(ground.geometry.getAttribute('uv')).toBeUndefined() + }) +}) diff --git a/studio/src/renderer/src/studio/SavedWorldStudio.tsx b/studio/src/renderer/src/studio/SavedWorldStudio.tsx index 95a855b2a..137f8ba7c 100644 --- a/studio/src/renderer/src/studio/SavedWorldStudio.tsx +++ b/studio/src/renderer/src/studio/SavedWorldStudio.tsx @@ -7,10 +7,12 @@ import { cn } from '@/lib/utils' import { BridgeError, STATUS_NOT_FOUND, type BridgeClient } from '../bridge/BridgeClient' import type { SavedStart, SavedWorldInfo, WorldInfo } from '../bridge/types' import { BlockColors } from '../scene/blockColors' +import { BlockLooks } from '../scene/blockLooks' import { BlockModels } from '../scene/blockModels' import { BridgeAssets } from '../scene/BridgeAssets' import { SavedTerrain, type ReadSavedTile, type SavedTerrainColoring } from '../scene/savedTerrain' import { savedTileSource, type SavedLayer } from '../scene/savedTileSource' +import { TerrainAtlas } from '../scene/terrainAtlas' import { focusAround, type TerrainStyle } from '../scene/terrainStream' import { SceneViewport } from './SceneViewport' import { useTerrainStream } from './useTerrainStream' @@ -37,10 +39,13 @@ export function SavedWorldStudio({ client, world, onSummary, tell }: SavedWorldS const [coloring, setColoring] = useState('biomes') const [readings, setReadings] = useState(0) const { start, looking } = useSavedStart(client, chosen?.id ?? null, readings, tell) - const tileSource = useMemo(() => { + const { tileSource, atlas } = useMemo(() => { const images = new BridgeAssets(client, () => {}) - return savedTileSource(client, new BlockColors(new BlockModels(images), images)) + const models = new BlockModels(images) + const pictures = new TerrainAtlas(images) + return { tileSource: savedTileSource(client, new BlockColors(models, images), new BlockLooks(models, pictures)), atlas: pictures } }, [client]) + useEffect(() => () => atlas.dispose(), [atlas]) const centerX = start?.centerX ?? 0 const centerZ = start?.centerZ ?? 0 const lowestGround = start?.lowestGround ?? 0 @@ -53,8 +58,8 @@ export function SavedWorldStudio({ client, world, onSummary, tell }: SavedWorldS () => minY === null ? null - : { surfaceOf: (read, place) => new SavedTerrain(read, place, coloring, seaLevel), floorY: minY, topY: minY + world.height }, - [minY, seaLevel, coloring, world.height] + : { surfaceOf: (read, place) => new SavedTerrain(read, place, coloring, seaLevel, atlas), floorY: minY, topY: minY + world.height }, + [minY, seaLevel, coloring, world.height, atlas] ) const { content, pending } = useTerrainStream(tileSource, COARSEST_SAVED_LEVEL, focus, layer, style, tell) const reading = looking || pending > 0