Match vanilla blockstate transforms and UV-locked baking

This commit is contained in:
Ludovic Marie
2026-10-06 21:49:27 +02:00
parent f286aa24e1
commit 90a76bc0aa
9 changed files with 538 additions and 25 deletions
@@ -0,0 +1,54 @@
{
"schema": 1,
"minecraft": "26.3",
"manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3",
"platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43",
"java": "openjdk 25.0.4.1 2026-08-18",
"rustc": "rustc 1.99.0 (b940084d7 2026-09-28)",
"resource_models": 2883,
"graph_fixtures": 440,
"rejected_roots": 1039,
"sources_sha256": {
"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaModelBakingOracle.java": "d05e04d25ed5e5aef260ce21cac627a79bdc5376326a5cb34ffb98462b79c79b",
"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCuboidModelOracle.java": "7526f20513c549483122ab0d5ad24b9e87f38dc2f6aae55addd701a91ac85e43",
"tools/test_model_baking_parity.py": "392ffec44918fb91740ca4a1316d684480d39f14bd34d46175f7f44946d15bd7",
"tools/test_cuboid_model_parity.py": "4a8b1cdcac335751c23413341ae939eea1c49c38d33d70d0708b8904ab8d0461",
"tools/test_model_resolution_parity.py": "d9595f2f1442f1f590b72d2a46600657e79ae103bec3d4c45db98242b964bde0",
"tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64",
"tools/test_rust_parity.py": "29d3db08005873528894b45ca10dcd6278753650473b3eb574e53e06ede40ec6",
"Cargo.toml": "3f93319c1eb70dbd7ba25cd74ef343fbf35c52c7c4752f955605c58699cbff9d",
"Cargo.lock": "cb1e87d449114a63edd904c0559d631e8fa9feeb27efd6539aacdcfeae178876",
"crates/horizon-assets/Cargo.toml": "2f2cffacec0b4e22dd7cb032d594289bc51c94ae6cc4e985fee3e310f441d751",
"crates/horizon-assets/examples/blockstate_binding_fixture.rs": "e58fdb432f6bfc1e400729baa9b48d4f00955b3143b98b52506b47dd8b065cf8",
"crates/horizon-assets/examples/blockstate_model_fixture.rs": "8f063322e57abdf9361a5a3a3badce2a7e727ee6d5e3947071cb448dfb38e8fd",
"crates/horizon-assets/examples/cuboid_model_fixture.rs": "97609d90e3f6ce340f3590296db2dc778113bb2b33c7d1b54080a1d6f3023f40",
"crates/horizon-assets/examples/model_baking_fixture.rs": "a762a8b48f09b5ac5e9c48d4a578b18b700810807fe5d3fc50798365cce1c314",
"crates/horizon-assets/examples/model_choice_fixture.rs": "a4c8a46501d2b5ae7051f10f2307ade048e96c2d330af51cd2431bb44977a99a",
"crates/horizon-assets/examples/model_resolution_fixture.rs": "c071067140299e49345a6ebd94e15b3b6d853cb9ae11d8de46e3cbdfb8b01f0e",
"crates/horizon-assets/examples/sprite_animation_fixture.rs": "254314d52deda129ab461221d3d8b95323a60730d374e566c1cd599fba85f072",
"crates/horizon-assets/examples/support/mod.rs": "bcf5a6d8a54845982191e037911c24139237771d6afa4b01b1e83c011489c3f5",
"crates/horizon-assets/src/animation.rs": "ebbf7952146a0e66b41396174492f5702627170b03a57e6cd5a45c97a08c975e",
"crates/horizon-assets/src/bake/transform.rs": "a95e658fef85b21bcb2f9f7512f98f98d57022d62c1199885b7133beae35a09d",
"crates/horizon-assets/src/bake.rs": "f55dda6b6cee5ac6e65a8ee4837fdd2c6674437d59e59b4c45718f6324d4a4d5",
"crates/horizon-assets/src/blockstate/bind.rs": "6278962e55c9786bba8184bdf2939af9c6e3b9002b08c3022129964b49a60009",
"crates/horizon-assets/src/blockstate/choice.rs": "5a66c8b9833e2f19dd8b0773f3593d97ff5941d3c5b773896b98049efa1395ba",
"crates/horizon-assets/src/blockstate.rs": "a4299dfd7adaeb4173982ffaa8e9c9eda2925739ae579a714193c99da2e7ce56",
"crates/horizon-assets/src/json.rs": "99fe8af4fbf5d4eed408a92e829ac1a39597a0d92471a6bff73771fad9c830a8",
"crates/horizon-assets/src/lib.rs": "e39f21c59a2c3e1c53d977b29bd5e0638e5fc41d86ff0fcc1882a6d90fd961e4",
"crates/horizon-assets/src/model.rs": "57ddb3d65e88e7a8aa22c62bc298a2dae7f4e994326a873a31f06c0f36ed051b",
"crates/horizon-assets/src/resolve.rs": "3927ac926cdcbd7d334901cc32d0ecc1e498b1bec98f76a46bca6d4964c13541"
},
"fixtures_sha256": {
".local/rust-model-baking-parity/inputs.jsonl": "aba24d38f4fc1af060502f983923c2f279c016d0fd412d40f6d50093fac1d811"
},
"rust_output_sha256": "9216be3bbae9e59bb89b6ed780ccedc5608cd4583c8e7527e50b165a0d8d30da",
"references": [
{
"side": "client",
"jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d",
"output_sha256": "9216be3bbae9e59bb89b6ed780ccedc5608cd4583c8e7527e50b165a0d8d30da",
"matched_output_lines": 7100
}
],
"scope": "Actual client FaceBakery geometry overload with a real unit-atlas sprite and default JOML math options. Identity blockstate transform, all bundled cuboid geometry and synthetic rotations, rescaling, default/explicit UVs, winding, degenerate and reversed bounds, inherited models and missing materials. Positions, UVs and element matrix coefficients compare by float bits. This does not cover blockstate transforms/UV lock, atlas packing, transparency classification, lighting, GPU rendering or gameplay."
}
@@ -0,0 +1,58 @@
{
"schema": 1,
"minecraft": "26.3",
"manifest_sha1": "4fe1aa1ef8da1cb95c5bad1fb98890ca56dd8ca3",
"platform": "Linux-7.0.0-31-generic-x86_64-with-glibc2.43",
"java": "openjdk 25.0.4.1 2026-08-18",
"rustc": "rustc 1.99.0 (b940084d7 2026-09-28)",
"resource_definitions": 1288,
"resource_model_transform_pairs": 7884,
"synthetic_models_per_all_128_transforms": 81,
"graph_fixtures": 189,
"rejected_roots": 0,
"baked_quads": 148439,
"sources_sha256": {
"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaModelBakingOracle.java": "d05e04d25ed5e5aef260ce21cac627a79bdc5376326a5cb34ffb98462b79c79b",
"mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCuboidModelOracle.java": "7526f20513c549483122ab0d5ad24b9e87f38dc2f6aae55addd701a91ac85e43",
"tools/test_blockstate_transform_parity.py": "5236987f561763571fd4d7b07c6ff72e5a34a065f8fc936d38189763de38a789",
"tools/test_model_baking_parity.py": "392ffec44918fb91740ca4a1316d684480d39f14bd34d46175f7f44946d15bd7",
"tools/test_cuboid_model_parity.py": "4a8b1cdcac335751c23413341ae939eea1c49c38d33d70d0708b8904ab8d0461",
"tools/test_model_resolution_parity.py": "d9595f2f1442f1f590b72d2a46600657e79ae103bec3d4c45db98242b964bde0",
"tools/lab.py": "d00bf107fa01b6c579734a082c3ca4ade3018f0d6851d46844acf17574f66e64",
"tools/test_rust_parity.py": "29d3db08005873528894b45ca10dcd6278753650473b3eb574e53e06ede40ec6",
"Cargo.toml": "3f93319c1eb70dbd7ba25cd74ef343fbf35c52c7c4752f955605c58699cbff9d",
"Cargo.lock": "cb1e87d449114a63edd904c0559d631e8fa9feeb27efd6539aacdcfeae178876",
"crates/horizon-assets/Cargo.toml": "2f2cffacec0b4e22dd7cb032d594289bc51c94ae6cc4e985fee3e310f441d751",
"crates/horizon-assets/examples/blockstate_binding_fixture.rs": "e58fdb432f6bfc1e400729baa9b48d4f00955b3143b98b52506b47dd8b065cf8",
"crates/horizon-assets/examples/blockstate_model_fixture.rs": "8f063322e57abdf9361a5a3a3badce2a7e727ee6d5e3947071cb448dfb38e8fd",
"crates/horizon-assets/examples/cuboid_model_fixture.rs": "97609d90e3f6ce340f3590296db2dc778113bb2b33c7d1b54080a1d6f3023f40",
"crates/horizon-assets/examples/model_baking_fixture.rs": "a762a8b48f09b5ac5e9c48d4a578b18b700810807fe5d3fc50798365cce1c314",
"crates/horizon-assets/examples/model_choice_fixture.rs": "a4c8a46501d2b5ae7051f10f2307ade048e96c2d330af51cd2431bb44977a99a",
"crates/horizon-assets/examples/model_resolution_fixture.rs": "c071067140299e49345a6ebd94e15b3b6d853cb9ae11d8de46e3cbdfb8b01f0e",
"crates/horizon-assets/examples/sprite_animation_fixture.rs": "254314d52deda129ab461221d3d8b95323a60730d374e566c1cd599fba85f072",
"crates/horizon-assets/examples/support/mod.rs": "bcf5a6d8a54845982191e037911c24139237771d6afa4b01b1e83c011489c3f5",
"crates/horizon-assets/src/animation.rs": "ebbf7952146a0e66b41396174492f5702627170b03a57e6cd5a45c97a08c975e",
"crates/horizon-assets/src/bake/transform.rs": "a95e658fef85b21bcb2f9f7512f98f98d57022d62c1199885b7133beae35a09d",
"crates/horizon-assets/src/bake.rs": "f55dda6b6cee5ac6e65a8ee4837fdd2c6674437d59e59b4c45718f6324d4a4d5",
"crates/horizon-assets/src/blockstate/bind.rs": "6278962e55c9786bba8184bdf2939af9c6e3b9002b08c3022129964b49a60009",
"crates/horizon-assets/src/blockstate/choice.rs": "5a66c8b9833e2f19dd8b0773f3593d97ff5941d3c5b773896b98049efa1395ba",
"crates/horizon-assets/src/blockstate.rs": "a4299dfd7adaeb4173982ffaa8e9c9eda2925739ae579a714193c99da2e7ce56",
"crates/horizon-assets/src/json.rs": "99fe8af4fbf5d4eed408a92e829ac1a39597a0d92471a6bff73771fad9c830a8",
"crates/horizon-assets/src/lib.rs": "e39f21c59a2c3e1c53d977b29bd5e0638e5fc41d86ff0fcc1882a6d90fd961e4",
"crates/horizon-assets/src/model.rs": "57ddb3d65e88e7a8aa22c62bc298a2dae7f4e994326a873a31f06c0f36ed051b",
"crates/horizon-assets/src/resolve.rs": "3927ac926cdcbd7d334901cc32d0ecc1e498b1bec98f76a46bca6d4964c13541"
},
"fixtures_sha256": {
".local/rust-blockstate-transform-parity/inputs.jsonl": "4a858b546c52f20ac82911e5f1bbe6f1ce4273a345f4fedb19dfbcfc50782c1d"
},
"rust_output_sha256": "a0d2017780ea594714a3e623333468d8485b2443f5e7547f8646470754edec4b",
"references": [
{
"side": "client",
"jar_sha256": "4508d006323f24fa02876310c192d739af56516eb259000ac50f0909a68c9a2d",
"output_sha256": "a0d2017780ea594714a3e623333468d8485b2443f5e7547f8646470754edec4b",
"matched_output_lines": 19704
}
],
"scope": "Actual FaceBakery with Variant.SimpleModelState and unit-atlas sprite, default JOML math. Every distinct model/XYZ-rotation/UV-lock tuple in bundled blockstates; all 64 quarter-turn combinations with and without UV lock on synthetic geometry. Exact float bits for positions, UVs, element matrices, orientation and all six inverse UV matrices; native Direction.rotate for culling. Includes identity UV lock, degenerate/reversed geometry, element rotations, signed zero and float overflow. Does not establish atlas packing, shader pixels, lighting, render classification, renderer integration or gameplay parity."
}
@@ -1,5 +1,5 @@
use horizon_assets::{
bake::{ElementMatrix, bake_model},
bake::{BlockModelTransform, ElementMatrix, bake_model_transformed},
model::*,
resolve::ModelLibrary,
};
@@ -28,17 +28,29 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.map(|(name, raw)| Ok((name.clone(), CuboidModel::from_json(raw.as_str().unwrap())?)))
.collect::<Result<_, horizon_assets::DecodeError>>()?;
let library = ModelLibrary::new(models)?;
let transform = row.get("transform").map(|t| {
BlockModelTransform::new(
std::array::from_fn(|i| t[i].as_u64().unwrap() as u8),
t[3].as_bool().unwrap(),
)
});
let state = transform.unwrap_or_else(|| BlockModelTransform::new([0; 3], false));
for root in row["roots"].as_array().unwrap() {
let name = root.as_str().unwrap();
let baked = library.resolve(name).and_then(|model| {
let quads = bake_model(&model)?.into_iter().map(|q| json!({
let quads = bake_model_transformed(&model, state)?.into_iter().map(|q| json!({
"positions":q.positions.map(|v| v.map(bits)),"uv":q.uv.map(|v| v.map(bits)),
"facing":q.facing.name(),"cull":q.cull.map(Direction::name),"tint":q.tint_index,
"shade":q.shade_direction_override.map(Direction::name),"light":q.light_emission,
"material":{"sprite":q.material.sprite,"translucent":q.material.force_translucent}
})).collect::<Vec<_>>();
let matrices: Vec<_> = model.elements().iter().map(|e| e.as_ref().unwrap().rotation.as_ref().map(|r| ElementMatrix::from_rotation(r).rows.map(|row| row.map(bits)))).collect();
Ok(json!({"quads":quads,"matrices":matrices}))
let mut value = json!({"quads":quads,"matrices":matrices});
if transform.is_some() {
value["transform"] = json!({"matrix":state.matrix_rows().map(|r| r.map(bits)),
"inverse_uv":Direction::ALL.map(|d| state.inverse_uv_rows(d).map(|r| r.map(bits)))});
}
Ok(value)
});
let value = match baked {
Ok(baked) => json!({"case":index,"name":name,"baked":baked}),
+26 -10
View File
@@ -1,5 +1,7 @@
//! Cuboid geometry in block units, before blockstate rotation and UV locking.
//! Cuboid geometry in block units, including blockstate rotation and UV locking.
use crate::{json::*, model::*, resolve::ResolvedCuboidModel};
mod transform;
pub use transform::BlockModelTransform;
#[derive(Clone, Debug, PartialEq)]
pub struct ModelQuad {
@@ -161,6 +163,12 @@ fn facing(vertices: &[[f32; 3]; 4]) -> Option<Direction> {
}
pub fn bake_model(model: &ResolvedCuboidModel) -> Result<Vec<ModelQuad>> {
bake_model_transformed(model, BlockModelTransform::new([0; 3], false))
}
pub fn bake_model_transformed(
model: &ResolvedCuboidModel,
transform: BlockModelTransform,
) -> Result<Vec<ModelQuad>> {
let mut output = Vec::new();
for element in model.elements() {
let element = element
@@ -173,7 +181,9 @@ pub fn bake_model(model: &ResolvedCuboidModel) -> Result<Vec<ModelQuad>> {
sprite: "minecraft:missingno".to_owned(),
force_translucent: false,
});
output.push(bake_face(element, face, *direction, matrix, material)?);
output.push(bake_face(
element, face, *direction, matrix, material, transform,
)?);
}
}
Ok(output)
@@ -184,6 +194,7 @@ fn bake_face(
direction: Direction,
matrix: Option<ElementMatrix>,
material: Material,
transform: BlockModelTransform,
) -> Result<ModelQuad> {
let mut positions = corners(element.from, element.to, direction).map(|v| v.map(|c| c / 16.0));
if let (Some(rotation), Some(matrix)) = (&element.rotation, matrix) {
@@ -193,18 +204,23 @@ fn bake_face(
*vertex = std::array::from_fn(|i| rotated[i] + rotation.origin[i]);
}
}
positions = positions.map(|v| transform.position(v));
let bounds = face
.uv
.unwrap_or_else(|| default_uv(element.from, element.to, direction));
let mut uv = std::array::from_fn(|i| {
let corner = (i + usize::from(face.rotation)) % 4;
[
bounds[if corner < 2 { 0 } else { 2 }] / 16.0,
bounds[if corner == 0 || corner == 3 { 1 } else { 3 }] / 16.0,
]
// Native TextureAtlasSprite applies origin + extent * coordinate;
// even the unit atlas changes negative zero to positive zero.
.map(|value| 0.0 + value)
transform
.uv(
direction,
[
bounds[if corner < 2 { 0 } else { 2 }] / 16.0,
bounds[if corner == 0 || corner == 3 { 1 } else { 3 }] / 16.0,
],
)
// Native TextureAtlasSprite applies origin + extent * coordinate;
// even the unit atlas changes negative zero to positive zero.
.map(|value| 0.0 + value)
});
let normal = facing(&positions);
if let (None, Some(facing)) = (&element.rotation, normal) {
@@ -232,7 +248,7 @@ fn bake_face(
positions,
uv,
facing: normal.unwrap_or(Direction::Up),
cull: face.cull,
cull: face.cull.map(|d| transform.direction(d)),
material,
tint_index: face.tint_index,
shade_direction_override: element.shade_direction_override,
+243
View File
@@ -0,0 +1,243 @@
//! Prepared blockstate transforms. The face basis and inverse arithmetic use
//! the pinned client's default, unfused f32 operations, including UV-lock
//! identity detection and quaternion basis normalization error.
use super::sin_cos;
use crate::model::Direction;
use std::sync::OnceLock;
#[derive(Clone, Copy, Debug)]
struct Affine {
rows: [[f32; 4]; 3],
identity: bool,
}
impl Affine {
const IDENTITY: Self = Self {
rows: [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
],
identity: true,
};
fn position(self, v: [f32; 3]) -> [f32; 3] {
self.rows
.map(|r| r[0] * v[0] + (r[1] * v[1] + (r[2] * v[2] + r[3])))
}
fn mul(self, b: Self) -> Self {
if self.identity {
return b;
}
if b.identity {
return self;
}
Self {
rows: std::array::from_fn(|r| {
std::array::from_fn(|c| {
self.rows[r][0] * b.rows[0][c]
+ (self.rows[r][1] * b.rows[1][c]
+ if c == 3 {
self.rows[r][2] * b.rows[2][c] + self.rows[r][3]
} else {
self.rows[r][2] * b.rows[2][c]
})
})
}),
identity: false,
}
}
fn inverse(self) -> Self {
let [[a, b, c, x], [d, e, f, y], [g, h, i, z]] = self.rows;
let ae = a * e;
let db = d * b;
let gb = g * b;
let ah = a * h;
let dh = d * h;
let ge = g * e;
let bi = b * i;
let bf = b * f;
let ei = e * i;
let ec = e * c;
let hf = h * f;
let hc = h * c;
let cg = c * g;
let cd = c * d;
let fg = f * g;
let fa = f * a;
let id = i * d;
let ia = i * a;
let inverse = 1.0 / ((ae - db) * i + (gb - ah) * f + (dh - ge) * c);
Self {
rows: [
[
(ei - hf) * inverse,
(hc - bi) * inverse,
(bf - ec) * inverse,
(bi * y - bf * z + ec * z - ei * x + hf * x - hc * y) * inverse,
],
[
(fg - id) * inverse,
(ia - cg) * inverse,
(cd - fa) * inverse,
(cg * y - cd * z + fa * z - fg * x + id * x - ia * y) * inverse,
],
[
(dh - ge) * inverse,
(gb - ah) * inverse,
(ae - db) * inverse,
(ge * x - dh * x + ah * y - gb * y + db * z - ae * z) * inverse,
],
],
identity: false,
}
}
fn face_basis(direction: Direction) -> Self {
use Direction::*;
use std::f32::consts::{FRAC_PI_2, PI};
let (axis, angle) = match direction {
South => return Self::IDENTITY,
Down => (0, FRAC_PI_2),
Up => (0, -FRAC_PI_2),
East => (1, FRAC_PI_2),
West => (1, -FRAC_PI_2),
North => (1, PI),
};
let (s, c) = sin_cos(angle * 0.5);
// Quaternion.rotateX/Y on an identity quaternion retains signed zeros.
let [x, y, z, w] = if axis == 0 {
[
s + 0.0 * c,
0.0 * c + 0.0 * s,
0.0 * c - 0.0 * s,
c - 0.0 * s,
]
} else {
[
0.0 * c - 0.0 * s,
s + 0.0 * c,
0.0 * s + 0.0 * c,
c - 0.0 * s,
]
};
let (xx, yy, zz, ww) = (x * x, y * y, z * z, w * w);
let (xy, xz, yz, xw, yw, zw) = (x * y, x * z, y * z, x * w, y * w, z * w);
let (xy, xz, yz, xw, yw, zw) = (xy + xy, xz + xz, yz + yz, xw + xw, yw + yw, zw + zw);
Self {
rows: [
[ww + xx - zz - yy, -zw + xy, yw + xz, 0.0],
[xy + zw, yy - zz + ww - xx, yz - xw, 0.0],
[xz - yw, yz + xw, zz - yy - xx + ww, 0.0],
],
identity: false,
}
}
}
/// A blockstate's negative XYZ quarter-turns and optional face UV locking.
/// All 64 rotation combinations are prepared once and reused across models.
#[derive(Clone, Copy, Debug)]
pub struct BlockModelTransform {
orientation: &'static Orientation,
uv_lock: bool,
}
#[derive(Debug)]
struct Orientation {
matrix: Affine,
inverse_uv: [Affine; 6],
}
impl BlockModelTransform {
pub fn new(quarter_turns: [u8; 3], uv_lock: bool) -> Self {
static ORIENTATIONS: OnceLock<[Orientation; 64]> = OnceLock::new();
let orientations = ORIENTATIONS.get_or_init(|| {
let bases = Direction::ALL.map(Affine::face_basis);
let inverses = bases.map(|b| if b.identity { b } else { b.inverse() });
std::array::from_fn(|index| {
let turns = [index / 16, index / 4 % 4, index % 4];
let mut rows = [[1i8, 0, 0], [0, 1, 0], [0, 0, 1]];
for (axis, turns) in turns.into_iter().enumerate() {
for _ in 0..turns {
let a = (axis + 1) % 3;
let b = (axis + 2) % 3;
let old = rows[a];
rows[a] = rows[b];
rows[b] = old.map(|v| -v);
}
}
let matrix = Affine {
identity: rows == [[1, 0, 0], [0, 1, 0], [0, 0, 1]],
rows: rows.map(|r| [f32::from(r[0]), f32::from(r[1]), f32::from(r[2]), 0.0]),
};
let inverse_uv = bases.map(|b| {
if matrix.identity {
return matrix.inverse();
}
let transformed = matrix.mul(b);
let normal = transformed.rows.map(|r| r[2]);
inverses[nearest(normal) as usize]
.mul(transformed)
.inverse()
});
Orientation { matrix, inverse_uv }
})
});
let [x, y, z] = quarter_turns.map(|n| usize::from(n % 4));
Self {
orientation: &orientations[x * 16 + y * 4 + z],
uv_lock,
}
}
pub fn matrix_rows(self) -> [[f32; 4]; 3] {
self.orientation.matrix.rows
}
pub fn inverse_uv_rows(self, direction: Direction) -> [[f32; 4]; 3] {
self.uv_matrix(direction).rows
}
fn uv_matrix(self, direction: Direction) -> Affine {
if self.uv_lock {
self.orientation.inverse_uv[direction as usize]
} else {
Affine::IDENTITY
}
}
pub(super) fn position(self, v: [f32; 3]) -> [f32; 3] {
if self.orientation.matrix.identity {
return v;
}
self.orientation
.matrix
.position(v.map(|c| c - 0.5))
.map(|c| c + 0.5)
}
pub(super) fn uv(self, direction: Direction, uv: [f32; 2]) -> [f32; 2] {
let matrix = self.uv_matrix(direction);
// MatrixUtil re-determines properties when the identity bit is absent.
// Its numeric comparison treats signed zeros as equal, without changing
// the matrix coefficients retained for later use.
if matrix.rows == Affine::IDENTITY.rows {
return uv;
}
let result = matrix.position([uv[0] - 0.5, uv[1] - 0.5, 0.0]);
[result[0] + 0.5, result[1] + 0.5]
}
pub fn direction(self, direction: Direction) -> Direction {
let v = match direction {
Direction::Down => [0.0, -1.0, 0.0],
Direction::Up => [0.0, 1.0, 0.0],
Direction::North => [0.0, 0.0, -1.0],
Direction::South => [0.0, 0.0, 1.0],
Direction::West => [-1.0, 0.0, 0.0],
Direction::East => [1.0, 0.0, 0.0],
};
nearest(self.orientation.matrix.position(v))
}
}
fn nearest([x, y, z]: [f32; 3]) -> Direction {
let mut best = f32::MIN_POSITIVE;
let mut direction = Direction::North;
for (candidate, dot) in Direction::ALL.into_iter().zip([-y, y, -z, z, -x, x]) {
if dot > best {
best = dot;
direction = candidate;
}
}
direction
}
+20 -3
View File
@@ -91,7 +91,8 @@ The [archived decoder result](../benchmarks/rust-resource-number-scanner-2026-10
records source, fixture and reference hashes. The oracle uses actual client
classes; those rendering APIs are absent from the server. The decoder, parent
resolver and baker now feed the development gallery. Blockstate selection, transformed
models, UV locking and rendered appearance still need their own checks.
models and UV locking have the separate geometry checks described below. Rendered
appearance still needs its own checks.
`ModelLibrary` resolves parent geometry, ambient occlusion, GUI lighting and
each display context. It shares inherited elements rather than cloning them.
@@ -124,11 +125,27 @@ Position, UV and matrix fields compare by exact float bits for these fixtures.
python3 tools/test_model_baking_parity.py
```
This comparison uses the identity blockstate transform. Atlas packing,
That comparison uses the identity blockstate transform. Atlas packing,
transparency classification, actual tint/light evaluation and GPU rendering
remain separate from the geometry result. Other operating systems still need
their native validation runs.
`BlockModelTransform` now prepares all 64 XYZ quarter-turn combinations once
and shares them across baked models. It rotates geometry around the block center,
rotates culling directions and applies UV locking in the original face basis.
The [transformed baking comparison](../benchmarks/rust-blockstate-transforms-2026-10-06/scoped-parity.json)
checks every distinct model/rotation/UV-lock tuple in bundled blockstates and
all 128 rotation/lock combinations on 81 synthetic models, plus further arbitrary
element rotations. Positions, UVs and every orientation/inverse-face matrix
compare by exact float bits: 19,704 roots and 148,439 quads match, including
7,884 bundled model/transform tuples. Quaternion basis rounding and numeric identity
rechecking are retained. This remains geometry validation; renderer integration,
atlas packing and pixel parity are separate work.
```sh
python3 tools/test_blockstate_transform_parity.py
```
Blockstate resources now decode into ordered variant selectors and multipart
conditions. The [native blockstate comparison](../benchmarks/rust-blockstate-model-decoding-2026-10-06/scoped-parity.json)
covers all 1,288 bundled definitions and 1,351 synthetic cases (2,639 total,
@@ -136,7 +153,7 @@ covers all 1,288 bundled definitions and 1,351 synthetic cases (2,639 total,
`BlockStateModelDispatcher.CODEC` as the pinned loader. The Rust representation
preserves single versus weighted variants, all three quarter-turn axes, UV-lock
flags, positive weights and total-weight limits, ordered selectors, nested
AND/OR conditions and per-term negation. Transformed baking remains separate work.
AND/OR conditions and per-term negation.
```sh
python3 tools/test_blockstate_model_parity.py
+4 -4
View File
@@ -18,13 +18,13 @@ The `horizon-assets` crate now decodes pinned cuboid models, with all 2,883 bund
block-model JSON files and 2,457 synthetic cases compared against the actual
client parser. [Decoder scope and validation](native-client.md#validation)
also include parent/texture resolution over 5,648 roots and cuboid baking over
7,100 roots with identity blockstate transforms. Blockstate selection, transformed
models and UV locking remain unfinished. Blockstate resource decoding now
7,100 roots with identity blockstate transforms. Blockstate resource decoding now
matches all 1,288 bundled definitions and 1,351 synthetic cases; registry
binding now also matches native selection across registered and special
item-frame states. Weighted selection and multipart random draw consumption
also match native traces. Transformed baking and renderer integration remain
unfinished. The native renderer now draws an
also match native traces. Transformed baking now checks every bundled
model/rotation/UV-lock tuple and all XYZ quarter-turn combinations against native
geometry by exact float bits. Renderer integration remains unfinished. The native renderer now draws an
inspection gallery from the decoded/resolved/baked models, including binary
cutouts and stepped lantern animation; these are not yet gameplay blocks.
Animation metadata, frame sequences and tick-state selection now have native
@@ -10,6 +10,8 @@ import net.minecraft.client.resources.model.cuboid.*;
import net.minecraft.client.resources.model.geometry.*;
import net.minecraft.client.resources.model.sprite.Material;
import net.minecraft.client.renderer.block.dispatch.ModelState;
import net.minecraft.client.renderer.block.dispatch.Variant;
import com.mojang.math.Quadrant;
import net.minecraft.client.renderer.texture.*;
import net.minecraft.client.resources.metadata.animation.FrameSize;
import net.minecraft.core.Direction;
@@ -34,7 +36,7 @@ public final class VanillaModelBakingOracle {
return new long[][]{{bits(m.m00()),bits(m.m10()),bits(m.m20())},
{bits(m.m01()),bits(m.m11()),bits(m.m21())},{bits(m.m02()),bits(m.m12()),bits(m.m22())}};
}
private static Object bake(ResolvedModel model, Sprite sprite) throws Exception {
private static Map<String,Object> bake(ResolvedModel model, Sprite sprite, ModelState state) throws Exception {
var geometry=model.getTopGeometry();
var quads=new ArrayList<Object>(); var matrices=new ArrayList<Object>();
if(geometry==UnbakedGeometry.EMPTY)return map("quads",quads,"matrices",matrices);
@@ -49,20 +51,25 @@ public final class VanillaModelBakingOracle {
var uv=face.uvs();
if(uv==null)uv=(CuboidFace.UVs)defaultUv.invoke(null,element.from(),element.to(),entry.getKey());
var info=new BakedQuad.MaterialInfo(sprite,null,null,null,null,face.tintIndex(),element.shadeDirectionOverride(),element.lightEmission());
var quad=FaceBakery.bakeQuad(INTERNER,element.from(),element.to(),uv,face.rotation(),info,entry.getKey(),new ModelState(){},element.rotation());
var quad=FaceBakery.bakeQuad(INTERNER,element.from(),element.to(),uv,face.rotation(),info,entry.getKey(),state,element.rotation());
var positions=new long[4][3];var uvs=new long[4][2];
for(int i=0;i<4;i++) {
var p=quad.position(i);positions[i]=new long[]{bits(p.x()),bits(p.y()),bits(p.z())};
long packed=quad.packedUV(i);uvs[i]=new long[]{packed >>> 32,packed & 0xffffffffL};
}
quads.add(map("positions",positions,"uv",uvs,"facing",quad.direction().getName(),
"cull",face.cullForDirection()==null?null:face.cullForDirection().getName(),"tint",face.tintIndex(),
"cull",face.cullForDirection()==null?null:Direction.rotate(state.transformation().getMatrix(),face.cullForDirection()).getName(),"tint",face.tintIndex(),
"shade",element.shadeDirectionOverride()==null?null:element.shadeDirectionOverride().getName(),
"light",element.lightEmission(),"material",map("sprite",material.sprite().toString(),"translucent",material.forceTranslucent())));
}
}
return map("quads",quads,"matrices",matrices);
}
private static Object affine(Matrix4fc matrix) {
var rows=new long[3][4];
for(int r=0;r<3;r++)for(int c=0;c<4;c++)rows[r][c]=bits(matrix.get(c,r));
return rows;
}
public static void main(String[] args) throws Exception {
net.minecraft.SharedConstants.tryDetectVersion();
if(org.joml.Options.FASTMATH || org.joml.Options.USE_MATH_FMA)throw new AssertionError("Expected default JOML math options");
@@ -77,9 +84,19 @@ public final class VanillaModelBakingOracle {
var discovery=new ModelDiscovery(models,MissingCuboidModel.missingModel());
discovery.addRoot(resolver->{for(var root:row.getAsJsonArray("roots"))resolver.markDependency(Identifier.parse(root.getAsString()));});
var resolved=discovery.resolve();
ModelState state=new ModelState(){};
if(row.has("transform")) {
var t=row.getAsJsonArray("transform");
state=new Variant.SimpleModelState(Quadrant.values()[t.get(0).getAsInt()],Quadrant.values()[t.get(1).getAsInt()],Quadrant.values()[t.get(2).getAsInt()],t.get(3).getAsBoolean()).asModelState();
}
for(var root:row.getAsJsonArray("roots")) {
String name=root.getAsString();Object value;
try {value=bake(Objects.requireNonNull(resolved.get(Identifier.parse(name))),sprite);}
String name=root.getAsString();Map<String,Object> value;
try {value=bake(Objects.requireNonNull(resolved.get(Identifier.parse(name))),sprite,state);
if(row.has("transform")) {
var inverse=new ArrayList<Object>();
for(var d:Direction.values())inverse.add(affine(state.inverseFaceTransformation(d)));
value.put("transform",map("matrix",affine(state.transformation().getMatrix()),"inverse_uv",inverse));
}}
catch(RuntimeException error) {output.write(JSON.toJson(map("case",index,"name",name,"error",true)));output.newLine();continue;}
output.write(JSON.toJson(map("case",index,"name",name,"baked",value)));output.newLine();
}
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""Compare blockstate-transformed cuboid baking against the pinned Java client."""
import itertools
import json
import os
from pathlib import Path
import platform
import subprocess
import zipfile
try:
from . import lab, test_rust_parity as base, test_model_baking_parity as baking, test_cuboid_model_parity as decoding
except ImportError:
import lab, test_rust_parity as base, test_model_baking_parity as baking, test_cuboid_model_parity as decoding
def corpus(archive):
models = {'minecraft:' + name.removeprefix('assets/minecraft/models/').removesuffix('.json'): archive.read(name).decode()
for name in sorted(archive.namelist()) if name.startswith('assets/minecraft/models/block/') and name.endswith('.json')}
groups = {}
definitions = 0
for name in sorted(archive.namelist()):
if not name.startswith('assets/minecraft/blockstates/') or not name.endswith('.json'):
continue
definitions += 1
root = json.loads(archive.read(name))
for choice in [*root.get('variants', {}).values(), *(s['apply'] for s in root.get('multipart', []))]:
for variant in choice if isinstance(choice, list) else [choice]:
state = tuple(variant.get(axis, 0) % 360 // 90 for axis in ['x', 'y', 'z']) + (variant.get('uvlock', False),)
model = variant['model']
if ':' not in model:
model = 'minecraft:' + model
groups.setdefault(state, set()).add(model)
rows = [{'models': models, 'roots': sorted(roots), 'transform': state} for state, roots in sorted(groups.items())]
resource_pairs = sum(len(roots) for roots in groups.values())
# All 128 transform/lock combinations on asymmetric, reversed and degenerate
# geometry, explicit/default UVs, signed zero and representative element rotations.
synthetic = list(baking.corpus())[-1]['models']
names = list(synthetic)
selected = names[:12] + names[12:248:9] + names[248:504:13] + names[504::53] + names[-4:]
focused = {name: synthetic[name] for name in dict.fromkeys(selected)}
for turns in itertools.product(range(4), repeat=3):
for lock in [False, True]:
rows.append({'models': focused, 'roots': list(focused), 'transform': [*turns, lock]})
# Cover every remaining arbitrary-angle element fixture under a deterministic
# transform; do not multiply the whole large corpus by 128 unnecessarily.
for state in itertools.product(range(4), range(4), [False, True]):
x, y, lock = state
subset = {name: raw for i, (name, raw) in enumerate(synthetic.items()) if i % 32 == x*8+y*2+lock}
rows.append({'models': subset, 'roots': list(subset), 'transform': [x, y, (x+y)%4, lock]})
return rows, definitions, resource_pairs, len(focused)
def main():
lock, jars, _ = base.verify_artifacts()
build = lab.LOCAL / 'rust-blockstate-transform-parity'; build.mkdir(parents=True, exist_ok=True)
report_path = build / 'report.json'; report_path.unlink(missing_ok=True)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaModelBakingOracle.java'
helper = oracle.with_name('VanillaCuboidModelOracle.java'); crate = lab.ROOT / 'crates/horizon-assets'
sources = [oracle, helper, Path(__file__), lab.ROOT/'tools/test_model_baking_parity.py',
lab.ROOT/'tools/test_cuboid_model_parity.py', lab.ROOT/'tools/test_model_resolution_parity.py',
lab.ROOT/'tools/lab.py', lab.ROOT/'tools/test_rust_parity.py', lab.ROOT/'Cargo.toml',
lab.ROOT/'Cargo.lock', crate/'Cargo.toml', *sorted(crate.rglob('*.rs'))]
tested = base.source_hashes(sources)
with zipfile.ZipFile(jars['client']) as archive:
rows, definitions, resource_pairs, focused = corpus(archive)
inputs = build/'inputs.jsonl'; inputs.write_text(''.join(json.dumps(row)+'\n' for row in rows))
fixtures = base.source_hashes([inputs]); classes = build/'classes'; classes.mkdir(exist_ok=True)
def run(command, name):
with (build/(name+'.log')).open('w') as log:
subprocess.run(list(map(str, command)), cwd=lab.ROOT, check=True, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
dependencies = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()]))
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle, helper], 'compile-java')
run(['cargo', 'build', '--locked', '-p', 'horizon-assets', '--example', 'model_baking_fixture'], 'compile-rust')
metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'], cwd=lab.ROOT))
binary = Path(metadata['target_directory'])/'debug/examples'/('model_baking_fixture.exe' if os.name == 'nt' else 'model_baking_fixture')
run([binary, inputs, build/'rust.jsonl'], 'rust')
run(['java', '-Xmx768M', '-cp', str(classes)+os.pathsep+dependencies, 'dev.horizonlab.parity.VanillaModelBakingOracle', inputs, build/'client.jsonl'], 'client')
rejected = decoding.canonicalize(build/'client.jsonl'); decoding.canonicalize(build/'rust.jsonl')
matched = base.compare(build/'client.jsonl', build/'rust.jsonl')
base.ensure_sources_unchanged(sources, tested); base.ensure_sources_unchanged([inputs], fixtures)
quads = sum(len(json.loads(line).get('baked', {}).get('quads', [])) for line in (build/'client.jsonl').open())
report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'manifest_sha1': lock['minecraft']['manifest_sha1'],
'platform': platform.platform(), 'java': subprocess.check_output(['java', '--version'], text=True).splitlines()[0],
'rustc': subprocess.check_output(['rustc', '--version'], text=True).strip(), 'resource_definitions': definitions,
'resource_model_transform_pairs': resource_pairs, 'synthetic_models_per_all_128_transforms': focused,
'graph_fixtures': len(rows), 'rejected_roots': rejected, 'baked_quads': quads,
'sources_sha256': tested, 'fixtures_sha256': fixtures, 'rust_output_sha256': lab.digest(build/'rust.jsonl', 'sha256'),
'references': [{'side': 'client', 'jar_sha256': lab.digest(jars['client'], 'sha256'),
'output_sha256': lab.digest(build/'client.jsonl', 'sha256'), 'matched_output_lines': matched}],
'scope': 'Actual FaceBakery with Variant.SimpleModelState and unit-atlas sprite, default JOML math. Every distinct model/XYZ-rotation/UV-lock tuple in bundled blockstates; all 64 quarter-turn combinations with and without UV lock on synthetic geometry. Exact float bits for positions, UVs, element matrices, orientation and all six inverse UV matrices; native Direction.rotate for culling. Includes identity UV lock, degenerate/reversed geometry, element rotations, signed zero and float overflow. Does not establish atlas packing, shader pixels, lighting, render classification, renderer integration or gameplay parity.'}
lab.write_json(report_path, report)
print(f'Native transformed baking: {matched:,} roots / {quads:,} quads match ({rejected:,} rejected); {report_path}', flush=True)
if __name__ == '__main__':
main()