actually useful
This commit is contained in:
@@ -22,9 +22,17 @@ export function resolveBlock(state, properties) {
|
||||
// Handle standard variants
|
||||
const propStr = Object.keys(properties).sort().map(k => `${k}=${properties[k]}`).join(',');
|
||||
let variantDef = state.variants[propStr] || state.variants[""] || state.variants["normal"];
|
||||
if (Array.isArray(variantDef)) variantDef = variantDef[0]; // Take first random model
|
||||
|
||||
if (variantDef) parts.push(variantDef);
|
||||
// --- NEW ERROR REPORTING ---
|
||||
if (!variantDef) {
|
||||
console.warn("Available states:", Object.keys(state.variants));
|
||||
throw new Error(
|
||||
`Failed to resolve block variant.\nRequested: "${propStr}"\nCheck the console for available states.`
|
||||
);
|
||||
}
|
||||
|
||||
if (Array.isArray(variantDef)) variantDef = variantDef[0]; // Take first random model
|
||||
parts.push(variantDef);
|
||||
} else if (state.multipart) {
|
||||
// Handle multipart
|
||||
for (const part of state.multipart) {
|
||||
@@ -34,9 +42,12 @@ export function resolveBlock(state, properties) {
|
||||
parts.push(applyDef);
|
||||
}
|
||||
}
|
||||
|
||||
if (parts.length === 0) {
|
||||
console.warn("Possibly malformed multipart block with no parts.")
|
||||
}
|
||||
}
|
||||
|
||||
// Returns an array of definitions: [{ model: "block/wall_post", y: 90, uvlock: true }, ...]
|
||||
return parts;
|
||||
}
|
||||
|
||||
|
||||
155
index.html
155
index.html
@@ -37,138 +37,73 @@
|
||||
</div>
|
||||
|
||||
<script type="module">
|
||||
import {loadBlockstate, loadModel, TextureAtlas} from './assets.js';
|
||||
import {resolveTexture, buildGeometry} from './geometry.js';
|
||||
import {Renderer} from './renderer.js';
|
||||
import {mat4Identity, mat4Ortho, mat4LookAt, mat4Multiply, mat4Translate} from './math.js';
|
||||
import {World} from './world.js';
|
||||
import {resolveBlock} from './blockstate.js';
|
||||
|
||||
// Helper to uniquely identify a baked model
|
||||
function getVariantHash(part) {
|
||||
return `${part.model}#y=${part.y || 0},x=${part.x || 0},uvlock=${!!part.uvlock}`;
|
||||
}
|
||||
import {Renderer} from './renderer.js';
|
||||
|
||||
async function testPipeline() {
|
||||
try {
|
||||
const atlas = new TextureAtlas(512);
|
||||
document.getElementById('atlas-container').appendChild(atlas.canvas);
|
||||
|
||||
// 1. Manually Populate World
|
||||
const world = new World();
|
||||
|
||||
// Draw a redstone line into a repeater, next to a cobblestone wall
|
||||
world.setBlock('minecraft:redstone_wire', 0, 0, 0, {
|
||||
east: 'side',
|
||||
west: 'up',
|
||||
north: 'none',
|
||||
south: 'none',
|
||||
power: '15'
|
||||
});
|
||||
world.setBlock('minecraft:redstone_wire', 1, 0, 0, {
|
||||
east: 'side',
|
||||
west: 'side',
|
||||
north: 'none',
|
||||
south: 'none',
|
||||
power: '3'
|
||||
});
|
||||
world.setBlock('minecraft:repeater', 2, 0, 0, {
|
||||
facing: 'east',
|
||||
delay: '1',
|
||||
locked: 'false',
|
||||
powered: 'true'
|
||||
});
|
||||
world.setBlock('minecraft:cobblestone_wall', 2, 0, -1, {
|
||||
up: 'true',
|
||||
north: 'tall',
|
||||
south: 'low'
|
||||
});
|
||||
|
||||
// 2. Build Scene Pools
|
||||
const instancePool = new Map();
|
||||
|
||||
for (const block of world.blocks.values()) {
|
||||
const stateJSON = await loadBlockstate(block.id);
|
||||
const parts = resolveBlock(stateJSON, block.props);
|
||||
|
||||
for (const part of parts) {
|
||||
const hash = getVariantHash(part);
|
||||
if (!instancePool.has(hash)) {
|
||||
instancePool.set(hash, {partDef: part, matrices: [], colors: []});
|
||||
}
|
||||
|
||||
const matrix = mat4Identity(new Float32Array(16));
|
||||
mat4Translate(matrix, matrix, [block.x, block.y, block.z]);
|
||||
|
||||
const pool = instancePool.get(hash);
|
||||
pool.matrices.push(...matrix);
|
||||
|
||||
// Simple redstone tint calculation (if power exists)
|
||||
if (block.props.power) {
|
||||
const p = parseInt(block.props.power, 10);
|
||||
const red = (0x4B + (p * 12)) / 255;
|
||||
pool.colors.push(red, 0.0, 0.0);
|
||||
} else {
|
||||
pool.colors.push(1.0, 1.0, 1.0); // Default white
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Bake Geometries & Create WebGL Buffers
|
||||
const webglCanvas = document.getElementById('webgl-canvas');
|
||||
const renderer = new Renderer(webglCanvas);
|
||||
const renderableMeshes = [];
|
||||
// Adjusted camera slightly to see the block underneath
|
||||
renderer.setCamera(-3, 3, -3, 3, 5, 4, 5, 0, 0, 0);
|
||||
|
||||
for (const [hash, pool] of instancePool.entries()) {
|
||||
const modelJSON = await loadModel(pool.partDef.model);
|
||||
document.getElementById('atlas-container').appendChild(renderer.atlas.canvas);
|
||||
|
||||
// Load textures
|
||||
for (const el of modelJSON.elements || []) {
|
||||
for (const face of Object.values(el.faces || {})) {
|
||||
const texPath = resolveTexture(modelJSON, face.texture);
|
||||
if (texPath) await atlas.load(texPath);
|
||||
}
|
||||
}
|
||||
const world = new World();
|
||||
|
||||
// Bake geometry with local rotations
|
||||
const geometry = buildGeometry(modelJSON, atlas, pool.partDef);
|
||||
// Initial State: Closed trapdoor, no redstone block
|
||||
world.setBlock('minecraft:oak_trapdoor', 0, 0, 0, {
|
||||
facing: 'east',
|
||||
open: 'false',
|
||||
half: 'bottom'
|
||||
});
|
||||
world.setBlock('minecraft:glass', -1, 0, 0);
|
||||
world.setBlock('minecraft:glass', 0, 0, -1);
|
||||
world.setBlock('minecraft:coal_block', 0, -1, 0);
|
||||
world.setBlock('minecraft:repeater', 1, -1, 0, {facing: 'west', delay: 1, locked: false, powered: false});
|
||||
world.setBlock('minecraft:comparator', 0, -1, 1, {facing: 'north', mode: 'compare', powered: false});
|
||||
|
||||
// Pack instances
|
||||
const matrixArray = new Float32Array(pool.matrices);
|
||||
const colorArray = new Float32Array(pool.colors);
|
||||
const instanceCount = pool.matrices.length / 16;
|
||||
await renderer.updateWorld(world);
|
||||
|
||||
const mesh = renderer.createInstancedMesh(geometry, instanceCount, matrixArray, colorArray);
|
||||
renderableMeshes.push(mesh);
|
||||
// Render Loop (Static, just drawing the current buffers)
|
||||
function animate() {
|
||||
renderer.render();
|
||||
requestAnimationFrame(animate);
|
||||
}
|
||||
|
||||
renderer.updateAtlas(atlas.canvas);
|
||||
animate();
|
||||
|
||||
// 4. Render Setup
|
||||
const proj = new Float32Array(16);
|
||||
const view = new Float32Array(16);
|
||||
const viewProj = new Float32Array(16);
|
||||
// --- THE STATE MACHINE LOOP ---
|
||||
let isOpen = false;
|
||||
|
||||
mat4Ortho(proj, -3, 3, -3, 3, -20, 20);
|
||||
mat4LookAt(view, 6, 5, 6, 1, 0, 0, 0, 1, 0);
|
||||
mat4Multiply(viewProj, proj, view);
|
||||
setInterval(async () => {
|
||||
isOpen = !isOpen;
|
||||
|
||||
function render() {
|
||||
const gl = renderer.gl;
|
||||
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
|
||||
gl.clearColor(0.1, 0.1, 0.12, 1.0);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
|
||||
// 1. Mutate the world data
|
||||
world.updateBlock(0, 0, 0, {open: isOpen.toString()});
|
||||
|
||||
for (const mesh of renderableMeshes) {
|
||||
renderer.drawInstanced(mesh, viewProj);
|
||||
if (isOpen) {
|
||||
world.setBlock('minecraft:redstone_block', 0, -1, 0);
|
||||
world.updateBlock(1, -1, 0, {powered: true})
|
||||
world.updateBlock(0, -1, 1, {powered: true})
|
||||
} else {
|
||||
world.removeBlock(0, -1, 0);
|
||||
world.updateBlock(1, -1, 0, {powered: false})
|
||||
world.updateBlock(0, -1, 1, {mode: 'subtract', powered: false})
|
||||
}
|
||||
requestAnimationFrame(render);
|
||||
}
|
||||
|
||||
render();
|
||||
// 2. Tell the renderer to sync with the new world state
|
||||
await renderer.updateWorld(world);
|
||||
|
||||
document.getElementById('output').innerHTML = `<strong>State Demo:</strong> Trapdoor is ${isOpen ? 'OPEN' : 'CLOSED'}`;
|
||||
|
||||
// await return new Promise((resolve) => setTimeout(resolve, time));
|
||||
|
||||
}, 1000);
|
||||
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
document.getElementById('output').textContent = 'Error: ' + err.message;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
99
renderer.js
99
renderer.js
@@ -1,4 +1,7 @@
|
||||
import {mat4Identity, mat4Multiply, mat4Ortho, mat4LookAt} from './math.js';
|
||||
import {mat4Identity, mat4Multiply, mat4Ortho, mat4LookAt, mat4Translate} from './math.js';
|
||||
import {loadBlockstate, loadModel, TextureAtlas} from './assets.js';
|
||||
import {resolveTexture, buildGeometry} from './geometry.js';
|
||||
import {resolveBlock, getVariantHash} from './blockstate.js';
|
||||
|
||||
const VS_SRC = `#version 300 es
|
||||
layout(location=0) in vec3 a_position;
|
||||
@@ -65,18 +68,14 @@ export class Renderer {
|
||||
|
||||
const gl = this.gl;
|
||||
gl.enable(gl.DEPTH_TEST);
|
||||
gl.enable(gl.CULL_FACE); // Minecraft culls inside faces
|
||||
gl.enable(gl.CULL_FACE);
|
||||
|
||||
// Compile Program
|
||||
const vs = compileShader(gl, gl.VERTEX_SHADER, VS_SRC);
|
||||
const fs = compileShader(gl, gl.FRAGMENT_SHADER, FS_SRC);
|
||||
this.program = gl.createProgram();
|
||||
gl.attachShader(this.program, vs);
|
||||
gl.attachShader(this.program, fs);
|
||||
gl.linkProgram(this.program);
|
||||
if (!gl.getProgramParameter(this.program, gl.LINK_STATUS)) {
|
||||
throw new Error(gl.getProgramInfoLog(this.program));
|
||||
}
|
||||
|
||||
this.uniforms = {
|
||||
viewProj: gl.getUniformLocation(this.program, "u_viewProj"),
|
||||
@@ -85,12 +84,81 @@ export class Renderer {
|
||||
};
|
||||
|
||||
this.atlasTexture = gl.createTexture();
|
||||
this.atlas = new TextureAtlas(512);
|
||||
this.meshes = []; // Array of renderable VAO objects
|
||||
|
||||
// Default Camera Setup
|
||||
this.projMatrix = new Float32Array(16);
|
||||
this.viewMatrix = new Float32Array(16);
|
||||
this.viewProjMatrix = new Float32Array(16);
|
||||
this.setCamera(-4, 4, -4, 4, 8, 6, 8, 1, 0, 1);
|
||||
}
|
||||
|
||||
updateAtlas(canvasAtlas) {
|
||||
setCamera(left, right, bottom, top, eyeX, eyeY, eyeZ, targetX, targetY, targetZ) {
|
||||
mat4Ortho(this.projMatrix, left, right, bottom, top, -20, 20);
|
||||
mat4LookAt(this.viewMatrix, eyeX, eyeY, eyeZ, targetX, targetY, targetZ, 0, 1, 0);
|
||||
mat4Multiply(this.viewProjMatrix, this.projMatrix, this.viewMatrix);
|
||||
}
|
||||
|
||||
// This method takes a World object and rebuilds the WebGL buffers
|
||||
async updateWorld(world) {
|
||||
const instancePool = new Map();
|
||||
|
||||
// 1. Resolve all blocks in the world into part definitions
|
||||
for (const block of world.blocks.values()) {
|
||||
const stateJSON = await loadBlockstate(block.id);
|
||||
const parts = resolveBlock(stateJSON, block.props);
|
||||
|
||||
for (const part of parts) {
|
||||
const hash = getVariantHash(part);
|
||||
if (!instancePool.has(hash)) {
|
||||
instancePool.set(hash, {partDef: part, matrices: [], colors: []});
|
||||
}
|
||||
|
||||
const matrix = mat4Identity(new Float32Array(16));
|
||||
mat4Translate(matrix, matrix, [block.x, block.y, block.z]);
|
||||
|
||||
const pool = instancePool.get(hash);
|
||||
pool.matrices.push(...matrix);
|
||||
|
||||
if (block.props.power) {
|
||||
const p = parseInt(block.props.power, 10);
|
||||
pool.colors.push((0x4B + (p * 12)) / 255, 0.0, 0.0);
|
||||
} else {
|
||||
pool.colors.push(1.0, 1.0, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Build geometries, load textures, and create WebGL buffers
|
||||
const newMeshes = [];
|
||||
for (const [hash, pool] of instancePool.entries()) {
|
||||
const modelJSON = await loadModel(pool.partDef.model);
|
||||
|
||||
for (const el of modelJSON.elements || []) {
|
||||
for (const face of Object.values(el.faces || {})) {
|
||||
const texPath = resolveTexture(modelJSON, face.texture);
|
||||
if (texPath) await this.atlas.load(texPath);
|
||||
}
|
||||
}
|
||||
|
||||
const geometry = buildGeometry(modelJSON, this.atlas, pool.partDef);
|
||||
const matrixArray = new Float32Array(pool.matrices);
|
||||
const colorArray = new Float32Array(pool.colors);
|
||||
const instanceCount = pool.matrices.length / 16;
|
||||
|
||||
newMeshes.push(this.createInstancedMesh(geometry, instanceCount, matrixArray, colorArray));
|
||||
}
|
||||
|
||||
// 3. Upload updated atlas and swap the active meshes
|
||||
this.updateAtlasTexture();
|
||||
this.meshes = newMeshes;
|
||||
}
|
||||
|
||||
updateAtlasTexture() {
|
||||
const gl = this.gl;
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.atlasTexture);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, canvasAtlas);
|
||||
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.atlas.canvas);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
|
||||
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
|
||||
}
|
||||
@@ -145,18 +213,23 @@ export class Renderer {
|
||||
return {vao, indexCount: geometry.indices.length, instanceCount};
|
||||
}
|
||||
|
||||
drawInstanced(mesh, viewProjMatrix) {
|
||||
render() {
|
||||
const gl = this.gl;
|
||||
gl.useProgram(this.program);
|
||||
gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
|
||||
gl.clearColor(0.1, 0.1, 0.12, 1.0);
|
||||
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
|
||||
|
||||
gl.uniformMatrix4fv(this.uniforms.viewProj, false, viewProjMatrix);
|
||||
gl.useProgram(this.program);
|
||||
gl.uniformMatrix4fv(this.uniforms.viewProj, false, this.viewProjMatrix);
|
||||
gl.uniform3f(this.uniforms.lightDir, 1.0, 2.0, 0.5);
|
||||
|
||||
gl.activeTexture(gl.TEXTURE0);
|
||||
gl.bindTexture(gl.TEXTURE_2D, this.atlasTexture);
|
||||
gl.uniform1i(this.uniforms.texture, 0);
|
||||
|
||||
gl.bindVertexArray(mesh.vao);
|
||||
gl.drawElementsInstanced(gl.TRIANGLES, mesh.indexCount, gl.UNSIGNED_SHORT, 0, mesh.instanceCount);
|
||||
for (const mesh of this.meshes) {
|
||||
gl.bindVertexArray(mesh.vao);
|
||||
gl.drawElementsInstanced(gl.TRIANGLES, mesh.indexCount, gl.UNSIGNED_SHORT, 0, mesh.instanceCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user