Add item model definitions, baking and parity harness (WIP)
Work in progress on vanilla's item model pipeline in horizon-assets: definition parsing, resolution, generated model baking, special renderers and a differential harness against a Java oracle. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Generated
+1
@@ -672,6 +672,7 @@ name = "horizon-assets"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"horizon-core",
|
||||
"png",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
@@ -13,3 +13,6 @@ serde_json = { version = "1.0.151", features = ["raw_value"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
png = "0.18"
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
//! Resolve item stacks into render layers for the differential harness
|
||||
//! `tools/test_item_model_parity.py`.
|
||||
use horizon_assets::{
|
||||
animation::AnimationMetadata,
|
||||
item_bake::{BakedItemModel, SpriteLookup, SpriteMask, bake_item_model},
|
||||
item_model::*,
|
||||
math::Mat4,
|
||||
model::{CuboidModel, Direction},
|
||||
resolve::{MISSING_MODEL, ModelLibrary},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::BTreeMap,
|
||||
fs::{self, File},
|
||||
io::{BufRead, BufReader, BufWriter, Write},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
fn bits(v: f32) -> u32 {
|
||||
if v.is_nan() { 0x7fc0_0000 } else { v.to_bits() }
|
||||
}
|
||||
|
||||
struct Sprites {
|
||||
root: PathBuf,
|
||||
cache: RefCell<BTreeMap<String, Option<SpriteMask>>>,
|
||||
}
|
||||
impl SpriteLookup for Sprites {
|
||||
fn mask(&self, sprite: &str) -> Option<SpriteMask> {
|
||||
if let Some(hit) = self.cache.borrow().get(sprite) {
|
||||
return hit.clone();
|
||||
}
|
||||
let mask = self.load(sprite);
|
||||
self.cache.borrow_mut().insert(sprite.to_owned(), mask.clone());
|
||||
mask
|
||||
}
|
||||
}
|
||||
impl Sprites {
|
||||
fn load(&self, sprite: &str) -> Option<SpriteMask> {
|
||||
let (namespace, path) = sprite.split_once(':')?;
|
||||
let png = self
|
||||
.root
|
||||
.join(format!("assets/{namespace}/textures/{path}.png"));
|
||||
let mut decoder = png::Decoder::new(BufReader::new(File::open(&png).ok()?));
|
||||
decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
|
||||
let mut reader = decoder.read_info().ok()?;
|
||||
let mut bytes = vec![0; reader.output_buffer_size()?];
|
||||
let info = reader.next_frame(&mut bytes).ok()?;
|
||||
let channels = info.color_type.samples();
|
||||
let alpha = |pixel: &[u8]| match info.color_type {
|
||||
png::ColorType::Rgba => pixel[3],
|
||||
png::ColorType::GrayscaleAlpha => pixel[1],
|
||||
_ => 255,
|
||||
};
|
||||
let (iw, ih) = (info.width as usize, info.height as usize);
|
||||
let pixels: Vec<u8> = bytes[..info.buffer_size()]
|
||||
.chunks_exact(channels)
|
||||
.map(alpha)
|
||||
.collect();
|
||||
let meta = fs::read_to_string(png.with_extension("png.mcmeta")).ok();
|
||||
let animation = meta
|
||||
.and_then(|m| serde_json::from_str::<Value>(&m).ok())
|
||||
.and_then(|m| m.get("animation").map(|a| a.to_string()))
|
||||
.and_then(|a| AnimationMetadata::from_json(&a).ok());
|
||||
let (w, h) = match &animation {
|
||||
Some(a) => {
|
||||
let [w, h] = a.frame_size(iw as i32, ih as i32);
|
||||
(w as usize, h as usize)
|
||||
}
|
||||
None => (iw, ih),
|
||||
};
|
||||
let columns = iw / w;
|
||||
let total = columns * (ih / h);
|
||||
let clip = animation.and_then(|a| a.clip(total as u32).ok().flatten());
|
||||
let frame_indices: Vec<usize> = match clip {
|
||||
Some(clip) => {
|
||||
let mut unique = Vec::new();
|
||||
for (index, _) in clip.sequence() {
|
||||
if !unique.contains(&(*index as usize)) {
|
||||
unique.push(*index as usize);
|
||||
}
|
||||
}
|
||||
unique
|
||||
}
|
||||
None => vec![0],
|
||||
};
|
||||
let frames = frame_indices
|
||||
.into_iter()
|
||||
.map(|f| {
|
||||
let (fx, fy) = (f % columns * w, f / columns * h);
|
||||
(0..h)
|
||||
.flat_map(|y| (0..w).map(move |x| (x, y)))
|
||||
.map(|(x, y)| pixels[(fy + y) * iw + fx + x] == 0)
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
Some(SpriteMask {
|
||||
width: w,
|
||||
height: h,
|
||||
frames,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct Env {
|
||||
grass: Vec<i32>,
|
||||
local_time: String,
|
||||
bundle_weight: bool,
|
||||
prototypes: BTreeMap<String, Components>,
|
||||
}
|
||||
impl ItemEnv for Env {
|
||||
fn grass_color(&self, temperature: f64, downfall: f64) -> i32 {
|
||||
let rain = downfall * temperature;
|
||||
let x = ((1.0 - temperature) * 255.0) as i64;
|
||||
let y = ((1.0 - rain) * 255.0) as i64;
|
||||
let index = (y << 8 | x) as usize;
|
||||
self.grass.get(index).copied().unwrap_or(-65281)
|
||||
}
|
||||
fn local_time(&self, _: &str, _: &str, _: Option<&str>) -> String {
|
||||
self.local_time.clone()
|
||||
}
|
||||
fn bundle_fullness(&self, stack: &StackView, components: &Components) -> f32 {
|
||||
// Sum of count / max stack size over the contents, as a double fraction.
|
||||
let Some(items) = components
|
||||
.get("minecraft:bundle_contents")
|
||||
.and_then(Value::as_array)
|
||||
else {
|
||||
return 0.0;
|
||||
};
|
||||
let _ = (stack, self.bundle_weight);
|
||||
let mut total = 0.0f64;
|
||||
for item in items {
|
||||
let id = item["id"].as_str().unwrap_or("");
|
||||
let count = item["count"].as_i64().unwrap_or(1) as f64;
|
||||
let max = self
|
||||
.prototypes
|
||||
.get(id)
|
||||
.and_then(|c| c.get("minecraft:max_stack_size"))
|
||||
.and_then(Value::as_i64)
|
||||
.unwrap_or(1) as f64;
|
||||
total += count / max;
|
||||
}
|
||||
total as f32
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args: Vec<_> = std::env::args().collect();
|
||||
let root = PathBuf::from(&args[1]);
|
||||
let prototypes_path = &args[2];
|
||||
let mut output = BufWriter::new(File::create(&args[4])?);
|
||||
|
||||
let raw: BTreeMap<String, Components> =
|
||||
serde_json::from_slice(&fs::read(prototypes_path)?)?;
|
||||
let mut models = ItemModels {
|
||||
prototypes: raw,
|
||||
..Default::default()
|
||||
};
|
||||
writeln!(output, "{}", json!({"row":"components","names":DATA_COMPONENT_TYPES.to_vec()}))?;
|
||||
let items_dir = root.join("assets/minecraft/items");
|
||||
let mut files: Vec<_> = fs::read_dir(&items_dir)?.collect::<Result<_, _>>()?;
|
||||
files.sort_by_key(|f| f.file_name());
|
||||
for file in files {
|
||||
let name = file.file_name().to_string_lossy().into_owned();
|
||||
let id = format!("minecraft:{}", name.trim_end_matches(".json"));
|
||||
let ok = match ClientItem::from_json(&fs::read_to_string(file.path())?) {
|
||||
Ok(item) => {
|
||||
models.definitions.insert(id, item);
|
||||
true
|
||||
}
|
||||
Err(_) => false,
|
||||
};
|
||||
writeln!(output, "{}", json!({"row":"decode","name":name,"ok":ok}))?;
|
||||
}
|
||||
for line in BufReader::new(File::open(format!("{}.definitions", args[3]))?).lines() {
|
||||
let row: Value = serde_json::from_str(&line?)?;
|
||||
let name = row["name"].as_str().unwrap();
|
||||
let ok = match ClientItem::from_json(row["json"].as_str().unwrap()) {
|
||||
Ok(item) => {
|
||||
models
|
||||
.definitions
|
||||
.insert(horizon_assets::item_model::identifier(name)?, item);
|
||||
true
|
||||
}
|
||||
Err(_) => false,
|
||||
};
|
||||
writeln!(output, "{}", json!({"row":"decode","name":name,"ok":ok}))?;
|
||||
}
|
||||
|
||||
let mut cuboids = BTreeMap::new();
|
||||
let models_dir = root.join("assets/minecraft/models");
|
||||
let mut stack = vec![models_dir.clone()];
|
||||
while let Some(dir) = stack.pop() {
|
||||
for entry in fs::read_dir(&dir)? {
|
||||
let path = entry?.path();
|
||||
if path.is_dir() {
|
||||
stack.push(path);
|
||||
} else if path.extension().is_some_and(|e| e == "json") {
|
||||
let relative = path.strip_prefix(&models_dir)?.with_extension("");
|
||||
let id = format!(
|
||||
"minecraft:{}",
|
||||
relative.to_string_lossy().replace('\\', "/")
|
||||
);
|
||||
if let Ok(model) = CuboidModel::from_json(&fs::read_to_string(&path)?) {
|
||||
cuboids.insert(id, model);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let library = ModelLibrary::with_item_generator(cuboids)?;
|
||||
let sprites = Sprites {
|
||||
root: root.clone(),
|
||||
cache: RefCell::default(),
|
||||
};
|
||||
let grass = {
|
||||
let mut decoder = png::Decoder::new(BufReader::new(File::open(
|
||||
root.join("assets/minecraft/textures/colormap/grass.png"),
|
||||
)?));
|
||||
decoder.set_transformations(png::Transformations::EXPAND);
|
||||
let mut reader = decoder.read_info()?;
|
||||
let mut bytes = vec![0; reader.output_buffer_size().unwrap()];
|
||||
let info = reader.next_frame(&mut bytes)?;
|
||||
let channels = info.color_type.samples();
|
||||
bytes[..info.buffer_size()]
|
||||
.chunks_exact(channels)
|
||||
.map(|p| {
|
||||
let a = if channels == 4 { p[3] } else { 255 };
|
||||
i32::from_be_bytes([a, p[0], p[1], p[2]])
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut env = Env {
|
||||
grass,
|
||||
local_time: String::new(),
|
||||
bundle_weight: true,
|
||||
prototypes: models.prototypes.clone(),
|
||||
};
|
||||
let mut baked_cache: BTreeMap<String, BakedItemModel> = BTreeMap::new();
|
||||
let mut bake = |name: &str| -> BakedItemModel {
|
||||
baked_cache
|
||||
.entry(name.to_owned())
|
||||
.or_insert_with(|| {
|
||||
bake_item_model(&library, &sprites, name)
|
||||
.or_else(|_| bake_item_model(&library, &sprites, MISSING_MODEL))
|
||||
.expect("missing model bakes")
|
||||
})
|
||||
.clone()
|
||||
};
|
||||
|
||||
for line in BufReader::new(File::open(&args[3])?).lines() {
|
||||
let row: Value = serde_json::from_str(&line?)?;
|
||||
let id = row["id"].as_str().unwrap();
|
||||
let mut stack = StackView::new(
|
||||
row["item"].as_str().unwrap(),
|
||||
row["count"].as_i64().unwrap() as i32,
|
||||
);
|
||||
if let Some(components) = row["components"].as_object() {
|
||||
for (key, value) in components {
|
||||
match key.strip_prefix('!') {
|
||||
Some(removed) => stack.patch.insert(removed.to_owned(), None),
|
||||
None => stack.patch.insert(key.clone(), Some(value.clone())),
|
||||
};
|
||||
}
|
||||
}
|
||||
stack.bundle_selected = row["bundle_selected"].as_i64().unwrap_or(-1) as i32;
|
||||
env.local_time = row["local_time"].as_str().unwrap_or("").to_owned();
|
||||
let context = DisplayContext::by_name(row["context"].as_str().unwrap()).unwrap();
|
||||
let owner = row["owner"].as_object().map(|o| {
|
||||
let derived = &row["derived"];
|
||||
OwnerState {
|
||||
entity_type: o["entity_type"].as_str().unwrap().to_owned(),
|
||||
main_arm_left: o["main_arm"] == "left",
|
||||
using_this_item: o["using"].as_bool().unwrap(),
|
||||
use_item_remaining_ticks: o["remaining"].as_i64().unwrap() as i32,
|
||||
use_duration: derived["use_duration"].as_i64().unwrap_or(0) as i32,
|
||||
crossbow_charge_duration: derived["charge_duration"].as_i64().unwrap_or(0) as i32,
|
||||
..Default::default()
|
||||
}
|
||||
});
|
||||
let level = row["dimension"].as_str().map(|d| LevelState {
|
||||
dimension: d.to_owned(),
|
||||
..Default::default()
|
||||
});
|
||||
let ctx = Context {
|
||||
display: context,
|
||||
owner: owner.as_ref(),
|
||||
level: level.as_ref(),
|
||||
seed: row["seed"].as_i64().unwrap_or(0) as i32,
|
||||
};
|
||||
let resolved = models.resolve(&stack, &ctx, &env);
|
||||
let mut layers = Vec::new();
|
||||
for layer in &resolved.layers {
|
||||
let (kind, baked, extra) = match &layer.content {
|
||||
LayerContent::Model { model } => ("model", bake(model), json!({})),
|
||||
LayerContent::Missing => ("model", bake(MISSING_MODEL), json!({})),
|
||||
LayerContent::Special {
|
||||
base,
|
||||
model,
|
||||
argument,
|
||||
} => (
|
||||
"special",
|
||||
bake(base),
|
||||
json!({"special":model.to_json(),"argument":argument}),
|
||||
),
|
||||
};
|
||||
let matrix: Mat4 = baked.layer_matrix(context, &layer.transform);
|
||||
let mut value = json!({
|
||||
"kind":kind,
|
||||
"tints":layer.tints,
|
||||
"foil":match layer.foil { FoilType::None=>"none", FoilType::Standard=>"standard", FoilType::Special=>"special" },
|
||||
"matrix":matrix.rows().iter().flatten().map(|v| bits(*v)).collect::<Vec<_>>(),
|
||||
"uses_block_light":baked.uses_block_light,
|
||||
"particle":baked.particle.sprite,
|
||||
"has_transform":baked.transform(context).is_some(),
|
||||
});
|
||||
if kind == "model" {
|
||||
value["quads"] = Value::Array(
|
||||
baked
|
||||
.quads
|
||||
.iter()
|
||||
.map(|q| {
|
||||
json!({
|
||||
"positions":q.positions.map(|v| v.map(bits)),
|
||||
"uv":q.uv.map(|v| v.map(bits)),
|
||||
"facing":q.facing.name(),
|
||||
"tint":q.tint_index,
|
||||
"sprite":q.material.sprite,
|
||||
"shade":q.shade_direction_override.map(Direction::name),
|
||||
"light":q.light_emission,
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
if let (Some(target), Some(source)) = (value.as_object_mut(), extra.as_object()) {
|
||||
for (k, v) in source {
|
||||
target.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
layers.push(value);
|
||||
}
|
||||
writeln!(
|
||||
output,
|
||||
"{}",
|
||||
json!({"row":"case","id":id,"layers":layers,"oversized":resolved.oversized_in_gui,
|
||||
"swap":{"play":models.hand_animation_on_swap(&stack),"scale":bits(models.swap_animation_scale(&stack))}})
|
||||
)?;
|
||||
}
|
||||
let _ = Path::new("");
|
||||
Ok(())
|
||||
}
|
||||
@@ -213,6 +213,40 @@ fn bake_elements(
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
/// `FaceBakery.bakeQuad` for a quad with explicit corners and unit-atlas UVs
|
||||
/// (`uv` in 0..16 texels), as `ItemModelGenerator` builds its layers.
|
||||
pub fn bake_flat_face(
|
||||
from: [f32; 3],
|
||||
to: [f32; 3],
|
||||
uv: [f32; 4],
|
||||
direction: Direction,
|
||||
material: Material,
|
||||
tint_index: i32,
|
||||
) -> Result<ModelQuad> {
|
||||
let element = Element {
|
||||
from,
|
||||
to,
|
||||
faces: Default::default(),
|
||||
rotation: None,
|
||||
shade_direction_override: None,
|
||||
light_emission: 0,
|
||||
};
|
||||
let face = Face {
|
||||
cull: None,
|
||||
tint_index,
|
||||
texture: String::new(),
|
||||
uv: Some(uv),
|
||||
rotation: 0,
|
||||
};
|
||||
bake_face(
|
||||
&element,
|
||||
&face,
|
||||
direction,
|
||||
None,
|
||||
material,
|
||||
BlockModelTransform::new([0; 3], false),
|
||||
)
|
||||
}
|
||||
fn bake_face(
|
||||
element: &Element,
|
||||
face: &Face,
|
||||
|
||||
@@ -0,0 +1,299 @@
|
||||
//! Baking of item models: a cuboid model's quads, or the layer extrusion of
|
||||
//! `builtin/generated` (`ItemModelGenerator`), with the display transforms
|
||||
//! and render properties a `CuboidItemModelWrapper` keeps.
|
||||
use crate::{
|
||||
bake::{ModelQuad, bake_block_model, bake_flat_face},
|
||||
item_model::DisplayContext,
|
||||
json::Result,
|
||||
math::{Mat4, quaternion_xyz},
|
||||
model::{Direction, DisplayTransform, GuiLight, ItemTransform, Material},
|
||||
resolve::ModelLibrary,
|
||||
};
|
||||
use std::{collections::BTreeSet, f32::consts::PI};
|
||||
|
||||
pub const MISSING_SPRITE: &str = "minecraft:missingno";
|
||||
|
||||
/// The alpha of every unique animation frame of a sprite.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SpriteMask {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
/// `frames[f][y * width + x]` is true for alpha 0.
|
||||
pub frames: Vec<Vec<bool>>,
|
||||
}
|
||||
impl SpriteMask {
|
||||
pub fn opaque(width: usize, height: usize) -> Self {
|
||||
Self {
|
||||
width,
|
||||
height,
|
||||
frames: vec![vec![false; width * height]],
|
||||
}
|
||||
}
|
||||
fn transparent(&self, frame: usize, x: i64, y: i64) -> bool {
|
||||
if x < 0 || y < 0 || x >= self.width as i64 || y >= self.height as i64 {
|
||||
return true;
|
||||
}
|
||||
self.frames[frame][y as usize * self.width + x as usize]
|
||||
}
|
||||
}
|
||||
/// The sprites of the item and block atlases.
|
||||
pub trait SpriteLookup {
|
||||
/// `None` when the sprite is in neither atlas (the missing sprite stands in).
|
||||
fn mask(&self, sprite: &str) -> Option<SpriteMask>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BakedItemModel {
|
||||
/// `QuadCollection.getAll`: unculled quads, then north, south, east,
|
||||
/// west, up and down.
|
||||
pub quads: Vec<ModelQuad>,
|
||||
/// `gui_light: side`.
|
||||
pub uses_block_light: bool,
|
||||
pub particle: Material,
|
||||
/// By [`crate::model::DISPLAY_CONTEXTS`]; `None` is `NO_TRANSFORM`.
|
||||
pub transforms: [Option<ItemTransform>; 9],
|
||||
}
|
||||
|
||||
fn context_index(context: DisplayContext) -> Option<usize> {
|
||||
Some(match context {
|
||||
DisplayContext::None => return None,
|
||||
DisplayContext::ThirdPersonLeftHand => 0,
|
||||
DisplayContext::ThirdPersonRightHand => 1,
|
||||
DisplayContext::FirstPersonLeftHand => 2,
|
||||
DisplayContext::FirstPersonRightHand => 3,
|
||||
DisplayContext::Head => 4,
|
||||
DisplayContext::Gui => 5,
|
||||
DisplayContext::Ground => 6,
|
||||
DisplayContext::Fixed => 7,
|
||||
DisplayContext::OnShelf => 8,
|
||||
})
|
||||
}
|
||||
impl BakedItemModel {
|
||||
/// `ItemTransforms.getTransform`.
|
||||
pub fn transform(&self, context: DisplayContext) -> Option<&ItemTransform> {
|
||||
context_index(context).and_then(|i| self.transforms[i].as_ref())
|
||||
}
|
||||
/// `LayerRenderState.applyTransform`: the display transform followed by
|
||||
/// the item model's own local transformation.
|
||||
pub fn layer_matrix(&self, context: DisplayContext, local: &Mat4) -> Mat4 {
|
||||
item_transform_matrix(self.transform(context), context.left_hand()).mul(local)
|
||||
}
|
||||
}
|
||||
/// `ItemTransform.apply` on an identity pose.
|
||||
pub fn item_transform_matrix(transform: Option<&ItemTransform>, left_hand: bool) -> Mat4 {
|
||||
let Some(t) = transform else {
|
||||
return Mat4::IDENTITY.translate([-0.5, -0.5, -0.5]);
|
||||
};
|
||||
let (tx, ry, rz) = if left_hand {
|
||||
(-t.translation[0], -t.rotation[1], -t.rotation[2])
|
||||
} else {
|
||||
(t.translation[0], t.rotation[1], t.rotation[2])
|
||||
};
|
||||
let radians = PI / 180.0;
|
||||
Mat4::IDENTITY
|
||||
.translate([tx, t.translation[1], t.translation[2]])
|
||||
.rotate(quaternion_xyz(
|
||||
t.rotation[0] * radians,
|
||||
ry * radians,
|
||||
rz * radians,
|
||||
))
|
||||
.scale(t.scale)
|
||||
.translate([-0.5, -0.5, -0.5])
|
||||
}
|
||||
|
||||
/// Bake the top geometry of `name` the way `CuboidItemModelWrapper` does.
|
||||
pub fn bake_item_model(
|
||||
library: &ModelLibrary,
|
||||
sprites: &dyn SpriteLookup,
|
||||
name: &str,
|
||||
) -> Result<BakedItemModel> {
|
||||
let model = library
|
||||
.resolve(name)
|
||||
.or_else(|_| library.resolve(crate::resolve::MISSING_MODEL))?;
|
||||
let known = |sprite: &str| sprite == MISSING_SPRITE || sprites.mask(sprite).is_some();
|
||||
let material = |m: &Material| {
|
||||
if known(&m.sprite) {
|
||||
m.clone()
|
||||
} else {
|
||||
Material {
|
||||
sprite: MISSING_SPRITE.to_owned(),
|
||||
force_translucent: m.force_translucent,
|
||||
}
|
||||
}
|
||||
};
|
||||
let quads = if model.uses_item_generator() {
|
||||
let mut quads = Vec::new();
|
||||
for (layer, slot) in ["layer0", "layer1", "layer2", "layer3", "layer4"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let Some(m) = model.material(slot)? else {
|
||||
break;
|
||||
};
|
||||
let m = material(m);
|
||||
let mask = if m.sprite == MISSING_SPRITE {
|
||||
SpriteMask::opaque(16, 16)
|
||||
} else {
|
||||
sprites.mask(&m.sprite).unwrap_or_else(|| SpriteMask::opaque(16, 16))
|
||||
};
|
||||
quads.extend(extrude_layer(&mask, &m, layer as i32)?);
|
||||
}
|
||||
quads
|
||||
} else {
|
||||
let mut quads = bake_block_model(
|
||||
&model,
|
||||
crate::bake::BlockModelTransform::new([0; 3], false),
|
||||
)?;
|
||||
for q in &mut quads {
|
||||
q.material = material(&q.material);
|
||||
}
|
||||
// `QuadCollection.Builder.build`: unculled, then each culled direction.
|
||||
let mut ordered: Vec<ModelQuad> = quads.iter().filter(|q| q.cull.is_none()).cloned().collect();
|
||||
for side in [
|
||||
Direction::North,
|
||||
Direction::South,
|
||||
Direction::East,
|
||||
Direction::West,
|
||||
Direction::Up,
|
||||
Direction::Down,
|
||||
] {
|
||||
ordered.extend(quads.iter().filter(|q| q.cull == Some(side)).cloned());
|
||||
}
|
||||
ordered
|
||||
};
|
||||
// `resolveParticleMaterial`: a missing `particle` slot is the missing sprite.
|
||||
let particle = model.material("particle")?.map_or_else(
|
||||
|| Material {
|
||||
sprite: MISSING_SPRITE.to_owned(),
|
||||
force_translucent: false,
|
||||
},
|
||||
material,
|
||||
);
|
||||
let transforms = std::array::from_fn(|i| match &model.display.contexts[i] {
|
||||
DisplayTransform::Explicit(Some(t)) => Some(t.clone()),
|
||||
_ => None,
|
||||
});
|
||||
Ok(BakedItemModel {
|
||||
quads,
|
||||
uses_block_light: model.gui_light == GuiLight::Side,
|
||||
particle,
|
||||
transforms,
|
||||
})
|
||||
}
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum Side {
|
||||
Up,
|
||||
Down,
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
impl Side {
|
||||
fn step(self) -> (i64, i64) {
|
||||
match self {
|
||||
Self::Up => (0, 1),
|
||||
Self::Down => (0, -1),
|
||||
Self::Left => (1, 0),
|
||||
Self::Right => (-1, 0),
|
||||
}
|
||||
}
|
||||
fn direction(self) -> Direction {
|
||||
match self {
|
||||
Self::Up => Direction::Up,
|
||||
Self::Down => Direction::Down,
|
||||
Self::Left => Direction::East,
|
||||
Self::Right => Direction::West,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ItemModelGenerator.bakeExtrudedSprite` for one layer: the front and back
|
||||
/// faces and one thin face per opaque/transparent pixel edge. The native
|
||||
/// client collects the sides in a hash set, so their order is unspecified;
|
||||
/// they are emitted sorted by pixel here.
|
||||
fn extrude_layer(mask: &SpriteMask, material: &Material, layer: i32) -> Result<Vec<ModelQuad>> {
|
||||
let from = [0.0, 0.0, 7.5];
|
||||
let to = [16.0, 16.0, 8.5];
|
||||
let mut quads = vec![
|
||||
bake_flat_face(
|
||||
from,
|
||||
to,
|
||||
[0.0, 0.0, 16.0, 16.0],
|
||||
Direction::South,
|
||||
material.clone(),
|
||||
layer,
|
||||
)?,
|
||||
bake_flat_face(
|
||||
from,
|
||||
to,
|
||||
[16.0, 0.0, 0.0, 16.0],
|
||||
Direction::North,
|
||||
material.clone(),
|
||||
layer,
|
||||
)?,
|
||||
];
|
||||
let (width, height) = (mask.width as i64, mask.height as i64);
|
||||
let mut faces = BTreeSet::new();
|
||||
for frame in 0..mask.frames.len() {
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
if mask.transparent(frame, x, y) {
|
||||
continue;
|
||||
}
|
||||
for side in [Side::Up, Side::Down, Side::Left, Side::Right] {
|
||||
let (sx, sy) = side.step();
|
||||
if mask.transparent(frame, x - sx, y - sy) {
|
||||
faces.insert((y, x, side));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let x_scale = 16.0 / mask.width as f32;
|
||||
let y_scale = 16.0 / mask.height as f32;
|
||||
for (y, x, side) in faces {
|
||||
let (x, y) = (x as f32, y as f32);
|
||||
let u0 = x + 0.1;
|
||||
let u1 = x + 1.0 - 0.1;
|
||||
let (v0, v1) = if matches!(side, Side::Up | Side::Down) {
|
||||
(y + 0.1, y + 1.0 - 0.1)
|
||||
} else {
|
||||
(y + 1.0 - 0.1, y + 0.1)
|
||||
};
|
||||
let (mut start_x, mut start_y, mut end_x, mut end_y) = (x, y, x, y);
|
||||
match side {
|
||||
Side::Up => end_x += 1.0,
|
||||
Side::Down => {
|
||||
end_x += 1.0;
|
||||
start_y += 1.0;
|
||||
end_y += 1.0;
|
||||
}
|
||||
Side::Left => end_y += 1.0,
|
||||
Side::Right => {
|
||||
start_x += 1.0;
|
||||
end_x += 1.0;
|
||||
end_y += 1.0;
|
||||
}
|
||||
}
|
||||
start_x *= x_scale;
|
||||
end_x *= x_scale;
|
||||
start_y *= y_scale;
|
||||
end_y *= y_scale;
|
||||
start_y = 16.0 - start_y;
|
||||
end_y = 16.0 - end_y;
|
||||
let (from, to) = match side {
|
||||
Side::Up => ([start_x, start_y, 7.5], [end_x, start_y, 8.5]),
|
||||
Side::Down => ([start_x, end_y, 7.5], [end_x, end_y, 8.5]),
|
||||
Side::Left => ([start_x, start_y, 7.5], [start_x, end_y, 8.5]),
|
||||
Side::Right => ([end_x, start_y, 7.5], [end_x, end_y, 8.5]),
|
||||
};
|
||||
quads.push(bake_flat_face(
|
||||
from,
|
||||
to,
|
||||
[u0 * x_scale, v0 * y_scale, u1 * x_scale, v1 * y_scale],
|
||||
side.direction(),
|
||||
material.clone(),
|
||||
layer,
|
||||
)?);
|
||||
}
|
||||
Ok(quads)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,254 @@
|
||||
//! `special` item models: the block-entity style renderers an item can ask
|
||||
//! for (`SpecialModelRenderers`), their codec fields and what each reads from
|
||||
//! the stack (`extractArgument`).
|
||||
use super::{Result, float, get, ident, object, required, string};
|
||||
use crate::json::error as err;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum SpecialKind {
|
||||
Bell,
|
||||
Banner {
|
||||
color: String,
|
||||
wall: bool,
|
||||
},
|
||||
Book {
|
||||
open_angle: f32,
|
||||
page1: f32,
|
||||
page2: f32,
|
||||
},
|
||||
Conduit,
|
||||
Chest {
|
||||
texture: String,
|
||||
openness: f32,
|
||||
chest_type: String,
|
||||
},
|
||||
CopperGolemStatue {
|
||||
texture: String,
|
||||
pose: String,
|
||||
},
|
||||
DecoratedPot,
|
||||
EndCube {
|
||||
effect: String,
|
||||
},
|
||||
Head {
|
||||
kind: String,
|
||||
texture: Option<String>,
|
||||
animation: f32,
|
||||
},
|
||||
PlayerHead,
|
||||
ShulkerBox {
|
||||
texture: String,
|
||||
openness: f32,
|
||||
},
|
||||
Shield,
|
||||
Trident,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct SpecialModel {
|
||||
pub kind: SpecialKind,
|
||||
}
|
||||
|
||||
const DYES: [&str; 16] = [
|
||||
"white",
|
||||
"orange",
|
||||
"magenta",
|
||||
"light_blue",
|
||||
"yellow",
|
||||
"lime",
|
||||
"pink",
|
||||
"gray",
|
||||
"light_gray",
|
||||
"cyan",
|
||||
"purple",
|
||||
"blue",
|
||||
"brown",
|
||||
"green",
|
||||
"red",
|
||||
"black",
|
||||
];
|
||||
fn one_of(v: &Value, names: &[&str]) -> Result<String> {
|
||||
let s = string(v)?;
|
||||
if names.contains(&s.as_str()) {
|
||||
Ok(s)
|
||||
} else {
|
||||
Err(err("invalid enum name"))
|
||||
}
|
||||
}
|
||||
|
||||
impl SpecialModel {
|
||||
pub fn decode(v: &Value) -> Result<Self> {
|
||||
let m = object(v)?;
|
||||
let float_or = |key: &str, default: f32| get(m, key).map_or(Ok(default), float);
|
||||
let kind = match ident(required(m, "type")?)?.as_str() {
|
||||
"minecraft:bell" => SpecialKind::Bell,
|
||||
"minecraft:banner" => SpecialKind::Banner {
|
||||
color: one_of(required(m, "color")?, &DYES)?,
|
||||
wall: match get(m, "attachment") {
|
||||
None => false,
|
||||
Some(a) => one_of(a, &["wall", "ground"])? == "wall",
|
||||
},
|
||||
},
|
||||
"minecraft:book" => SpecialKind::Book {
|
||||
open_angle: float(required(m, "open_angle")?)?,
|
||||
page1: float(required(m, "page1")?)?,
|
||||
page2: float(required(m, "page2")?)?,
|
||||
},
|
||||
"minecraft:conduit" => SpecialKind::Conduit,
|
||||
"minecraft:chest" => SpecialKind::Chest {
|
||||
texture: ident(required(m, "texture")?)?,
|
||||
openness: float_or("openness", 0.0)?,
|
||||
chest_type: match get(m, "chest_type") {
|
||||
None => "single".to_owned(),
|
||||
Some(t) => one_of(t, &["single", "left", "right"])?,
|
||||
},
|
||||
},
|
||||
"minecraft:copper_golem_statue" => SpecialKind::CopperGolemStatue {
|
||||
texture: ident(required(m, "texture")?)?,
|
||||
pose: one_of(
|
||||
required(m, "pose")?,
|
||||
&["standing", "sitting", "running", "star"],
|
||||
)?,
|
||||
},
|
||||
"minecraft:decorated_pot" => SpecialKind::DecoratedPot,
|
||||
"minecraft:end_cube" => SpecialKind::EndCube {
|
||||
effect: one_of(required(m, "effect")?, &["portal", "gateway"])?,
|
||||
},
|
||||
"minecraft:head" => SpecialKind::Head {
|
||||
kind: one_of(
|
||||
required(m, "kind")?,
|
||||
&[
|
||||
"skeleton",
|
||||
"wither_skeleton",
|
||||
"player",
|
||||
"zombie",
|
||||
"creeper",
|
||||
"piglin",
|
||||
"dragon",
|
||||
],
|
||||
)?,
|
||||
texture: get(m, "texture").map(ident).transpose()?,
|
||||
animation: float_or("animation", 0.0)?,
|
||||
},
|
||||
"minecraft:player_head" => SpecialKind::PlayerHead,
|
||||
"minecraft:shulker_box" => SpecialKind::ShulkerBox {
|
||||
texture: ident(required(m, "texture")?)?,
|
||||
openness: float_or("openness", 0.0)?,
|
||||
},
|
||||
"minecraft:shield" => SpecialKind::Shield,
|
||||
"minecraft:trident" => SpecialKind::Trident,
|
||||
_ => return Err(err("unknown special model type")),
|
||||
};
|
||||
Ok(Self { kind })
|
||||
}
|
||||
/// The codec's encoding: optional fields equal to their default are omitted.
|
||||
pub fn to_json(&self) -> Value {
|
||||
let mut m = Map::new();
|
||||
let mut put = |k: &str, v: Value| {
|
||||
m.insert(k.to_owned(), v);
|
||||
};
|
||||
let ty = match &self.kind {
|
||||
SpecialKind::Bell => "bell",
|
||||
SpecialKind::Banner { color, wall } => {
|
||||
put("color", json!(color));
|
||||
if *wall {
|
||||
put("attachment", json!("wall"));
|
||||
}
|
||||
"banner"
|
||||
}
|
||||
SpecialKind::Book {
|
||||
open_angle,
|
||||
page1,
|
||||
page2,
|
||||
} => {
|
||||
put("open_angle", json!(open_angle));
|
||||
put("page1", json!(page1));
|
||||
put("page2", json!(page2));
|
||||
"book"
|
||||
}
|
||||
SpecialKind::Conduit => "conduit",
|
||||
SpecialKind::Chest {
|
||||
texture,
|
||||
openness,
|
||||
chest_type,
|
||||
} => {
|
||||
put("texture", json!(texture));
|
||||
if *openness != 0.0 {
|
||||
put("openness", json!(openness));
|
||||
}
|
||||
if chest_type != "single" {
|
||||
put("chest_type", json!(chest_type));
|
||||
}
|
||||
"chest"
|
||||
}
|
||||
SpecialKind::CopperGolemStatue { texture, pose } => {
|
||||
put("texture", json!(texture));
|
||||
put("pose", json!(pose));
|
||||
"copper_golem_statue"
|
||||
}
|
||||
SpecialKind::DecoratedPot => "decorated_pot",
|
||||
SpecialKind::EndCube { effect } => {
|
||||
put("effect", json!(effect));
|
||||
"end_cube"
|
||||
}
|
||||
SpecialKind::Head {
|
||||
kind,
|
||||
texture,
|
||||
animation,
|
||||
} => {
|
||||
put("kind", json!(kind));
|
||||
if let Some(t) = texture {
|
||||
put("texture", json!(t));
|
||||
}
|
||||
if *animation != 0.0 {
|
||||
put("animation", json!(animation));
|
||||
}
|
||||
"head"
|
||||
}
|
||||
SpecialKind::PlayerHead => "player_head",
|
||||
SpecialKind::ShulkerBox { texture, openness } => {
|
||||
if texture != "minecraft:shulker" {
|
||||
put("texture", json!(texture));
|
||||
}
|
||||
if *openness != 0.0 {
|
||||
put("openness", json!(openness));
|
||||
}
|
||||
"shulker_box"
|
||||
}
|
||||
SpecialKind::Shield => "shield",
|
||||
SpecialKind::Trident => "trident",
|
||||
};
|
||||
m.insert("type".to_owned(), json!(format!("minecraft:{ty}")));
|
||||
Value::Object(m)
|
||||
}
|
||||
pub fn type_name(&self) -> String {
|
||||
self.to_json()["type"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_owned()
|
||||
}
|
||||
/// What `extractArgument` reads: banners their pattern layers, shields
|
||||
/// their base colour and layers, decorated pots their sherds and player
|
||||
/// heads their profile. Absent components give `null`.
|
||||
pub fn argument(&self, component: &dyn Fn(&str) -> Option<Value>) -> Value {
|
||||
match &self.kind {
|
||||
SpecialKind::Banner { .. } => {
|
||||
component("minecraft:banner_patterns").unwrap_or(Value::Null)
|
||||
}
|
||||
SpecialKind::DecoratedPot => {
|
||||
component("minecraft:pot_decorations").unwrap_or(Value::Null)
|
||||
}
|
||||
SpecialKind::PlayerHead => component("minecraft:profile").unwrap_or(Value::Null),
|
||||
SpecialKind::Shield => {
|
||||
let mut m = Map::new();
|
||||
for key in ["minecraft:banner_patterns", "minecraft:base_color"] {
|
||||
if let Some(v) = component(key) {
|
||||
m.insert(key.to_owned(), v);
|
||||
}
|
||||
}
|
||||
Value::Object(m)
|
||||
}
|
||||
_ => Value::Null,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
use super::*;
|
||||
@@ -4,7 +4,10 @@
|
||||
pub mod animation;
|
||||
pub mod bake;
|
||||
pub mod blockstate;
|
||||
pub mod item_bake;
|
||||
pub mod item_model;
|
||||
mod json;
|
||||
pub mod math;
|
||||
pub mod model;
|
||||
pub mod resolve;
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//! Column-major `Matrix4f` arithmetic with the operand order of JOML's
|
||||
//! default (non-FMA) code paths, for composing item-model transformations.
|
||||
|
||||
/// A JOML `Matrix4f`: `m[column][row]`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Mat4(pub [[f32; 4]; 4]);
|
||||
|
||||
impl Mat4 {
|
||||
pub const IDENTITY: Self = Self([
|
||||
[1.0, 0.0, 0.0, 0.0],
|
||||
[0.0, 1.0, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
]);
|
||||
/// `Matrix4f.translation(x, y, z)`.
|
||||
pub fn translation(t: [f32; 3]) -> Self {
|
||||
let mut m = Self::IDENTITY;
|
||||
m.0[3][..3].copy_from_slice(&t);
|
||||
m
|
||||
}
|
||||
/// `ExtraCodecs.MATRIX4F`: sixteen values in row-major order.
|
||||
pub fn from_row_major(values: [f32; 16]) -> Self {
|
||||
let mut m = Self([[0.0; 4]; 4]);
|
||||
for (i, v) in values.into_iter().enumerate() {
|
||||
m.0[i & 3][i >> 2] = v;
|
||||
}
|
||||
m
|
||||
}
|
||||
/// The matrix as `[row][column]` entries, the order `getRowColumn` reads.
|
||||
pub fn rows(&self) -> [[f32; 4]; 4] {
|
||||
std::array::from_fn(|r| std::array::from_fn(|c| self.0[c][r]))
|
||||
}
|
||||
/// `this * right` (`Matrix4f.mul`).
|
||||
pub fn mul(&self, right: &Self) -> Self {
|
||||
let (m, r) = (&self.0, &right.0);
|
||||
let mut out = [[0.0; 4]; 4];
|
||||
for c in 0..4 {
|
||||
for row in 0..4 {
|
||||
out[c][row] = m[0][row] * r[c][0]
|
||||
+ m[1][row] * r[c][1]
|
||||
+ m[2][row] * r[c][2]
|
||||
+ m[3][row] * r[c][3];
|
||||
}
|
||||
}
|
||||
Self(out)
|
||||
}
|
||||
/// `Matrix4f.translate(x, y, z)` (`translateGeneric`).
|
||||
pub fn translate(&self, t: [f32; 3]) -> Self {
|
||||
let mut out = *self;
|
||||
for row in 0..4 {
|
||||
out.0[3][row] =
|
||||
self.0[0][row] * t[0] + (self.0[1][row] * t[1] + (self.0[2][row] * t[2] + self.0[3][row]));
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `Matrix4f.scale(x, y, z)`: the first three columns are scaled.
|
||||
pub fn scale(&self, s: [f32; 3]) -> Self {
|
||||
let mut out = *self;
|
||||
for c in 0..3 {
|
||||
for row in 0..4 {
|
||||
out.0[c][row] = self.0[c][row] * s[c];
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `Matrix4f.rotate(Quaternionfc)` (`rotateGeneric`).
|
||||
pub fn rotate(&self, q: [f32; 4]) -> Self {
|
||||
let [x, y, z, w] = q;
|
||||
let (w2, x2, y2, z2) = (w * w, x * x, y * y, z * z);
|
||||
let (zw, xy, xz, yw, yz, xw) = (z * w, x * y, x * z, y * w, y * z, x * w);
|
||||
let (dzw, dxy, dxz, dyw, dyz, dxw) = (zw + zw, xy + xy, xz + xz, yw + yw, yz + yz, xw + xw);
|
||||
let r = [
|
||||
[w2 + x2 - z2 - y2, dxy + dzw, dxz - dyw],
|
||||
[dxy - dzw, y2 - z2 + w2 - x2, dyz + dxw],
|
||||
[dyw + dxz, dyz - dxw, z2 - y2 - x2 + w2],
|
||||
];
|
||||
let m = &self.0;
|
||||
let mut out = *self;
|
||||
for c in 0..3 {
|
||||
for row in 0..4 {
|
||||
out.0[c][row] = m[0][row] * r[c][0] + m[1][row] * r[c][1] + m[2][row] * r[c][2];
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
pub fn is_finite(&self) -> bool {
|
||||
self.0.iter().flatten().all(|v| v.is_finite())
|
||||
}
|
||||
}
|
||||
|
||||
/// `Quaternionf.normalize` as the codec applies it to four components.
|
||||
pub fn normalize_quaternion(q: [f32; 4]) -> [f32; 4] {
|
||||
let [x, y, z, w] = q;
|
||||
let inv = 1.0 / (x * x + (y * y + (z * z + w * w))).sqrt();
|
||||
[x * inv, y * inv, z * inv, w * inv]
|
||||
}
|
||||
/// `Quaternionf.rotationXYZ` from angles in radians.
|
||||
pub fn quaternion_xyz(x: f32, y: f32, z: f32) -> [f32; 4] {
|
||||
let half = |a: f32| -> (f32, f32) {
|
||||
let h = a * 0.5;
|
||||
((f64::from(h).sin()) as f32, (f64::from(h).cos()) as f32)
|
||||
};
|
||||
let ((sx, cx), (sy, cy), (sz, cz)) = (half(x), half(y), half(z));
|
||||
let (cx_cy, sx_cy, cx_sy, sx_sy) = (cx * cy, sx * cy, cx * sy, sx * sy);
|
||||
[
|
||||
sx_cy * cz + cx_sy * sz,
|
||||
cx_sy * cz - sx_cy * sz,
|
||||
cx_cy * sz + sx_sy * cz,
|
||||
cx_cy * cz - sx_sy * sz,
|
||||
]
|
||||
}
|
||||
/// `new Quaternionf(new AxisAngle4f(angle, axis))`.
|
||||
pub fn quaternion_from_axis_angle(angle: f32, axis: [f32; 3]) -> [f32; 4] {
|
||||
let half = angle * 0.5;
|
||||
let (sin, cos) = (half.sin(), half.cos());
|
||||
let norm = 1.0 / (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
|
||||
let s = sin * norm;
|
||||
[axis[0] * s, axis[1] * s, axis[2] * s, cos]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn composes_in_joml_order() {
|
||||
let t = Mat4::translation([1.0, 2.0, 3.0]);
|
||||
let s = Mat4::IDENTITY.scale([2.0, -1.0, 1.0]);
|
||||
let m = t.mul(&s);
|
||||
assert_eq!(m.0[0][0], 2.0);
|
||||
assert_eq!(m.0[1][1], -1.0);
|
||||
assert_eq!(m.0[3][..3], [1.0, 2.0, 3.0]);
|
||||
assert_eq!(s.mul(&t).0[3][..3], [2.0, -2.0, 3.0]);
|
||||
}
|
||||
#[test]
|
||||
fn quarter_turn_about_z_rotates_x_into_y() {
|
||||
let q = quaternion_from_axis_angle(std::f32::consts::FRAC_PI_2, [0.0, 0.0, 1.0]);
|
||||
let m = Mat4::IDENTITY.rotate(q);
|
||||
assert!((m.0[0][1] - 1.0).abs() < 1e-6 && m.0[0][0].abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ use std::{
|
||||
};
|
||||
|
||||
pub const MISSING_MODEL: &str = "minecraft:builtin/missing";
|
||||
/// `ItemModelGenerator.GENERATED_ITEM_MODEL_ID`.
|
||||
pub const GENERATED_MODEL: &str = "minecraft:builtin/generated";
|
||||
|
||||
/// Decoded models are immutable and their inherited geometry is shared.
|
||||
pub struct ModelLibrary {
|
||||
@@ -21,8 +23,14 @@ pub struct ResolvedCuboidModel {
|
||||
/// Cyclic and dangling aliases are absent from `textures`.
|
||||
pub unresolved_textures: BTreeSet<String>,
|
||||
geometry: Option<Arc<CuboidModel>>,
|
||||
generated: bool,
|
||||
}
|
||||
impl ResolvedCuboidModel {
|
||||
/// Whether the top geometry is `builtin/generated`'s layer extrusion
|
||||
/// (no model closer to the leaf has elements of its own).
|
||||
pub fn uses_item_generator(&self) -> bool {
|
||||
self.generated
|
||||
}
|
||||
pub fn elements(&self) -> &[Option<Element>] {
|
||||
self.geometry
|
||||
.as_ref()
|
||||
@@ -39,6 +47,25 @@ impl ResolvedCuboidModel {
|
||||
}
|
||||
}
|
||||
impl ModelLibrary {
|
||||
/// A library that also knows `builtin/generated`, the parent of every
|
||||
/// flat item model; the native client registers it as a special model.
|
||||
pub fn with_item_generator(mut models: BTreeMap<String, CuboidModel>) -> Result<Self> {
|
||||
models.insert(
|
||||
GENERATED_MODEL.to_owned(),
|
||||
CuboidModel {
|
||||
parent: None,
|
||||
ambient_occlusion: None,
|
||||
gui_light: Some(GuiLight::Front),
|
||||
textures: BTreeMap::from([(
|
||||
"particle".to_owned(),
|
||||
TextureSlot::Reference("layer0".to_owned()),
|
||||
)]),
|
||||
elements: None,
|
||||
display: None,
|
||||
},
|
||||
);
|
||||
Self::new(models)
|
||||
}
|
||||
pub fn new(models: BTreeMap<String, CuboidModel>) -> Result<Self> {
|
||||
let mut decoded = BTreeMap::new();
|
||||
for (name, model) in models {
|
||||
@@ -64,12 +91,14 @@ impl ModelLibrary {
|
||||
let mut name = identifier(name)?;
|
||||
let mut visited = BTreeSet::new();
|
||||
let mut chain = Vec::new();
|
||||
let mut names = Vec::new();
|
||||
loop {
|
||||
if !visited.insert(name.clone()) {
|
||||
return Err(error("cyclic model parent"));
|
||||
}
|
||||
let model = self.models.get(&name).unwrap_or(&self.missing);
|
||||
chain.push(model);
|
||||
names.push(name.clone());
|
||||
match &model.parent {
|
||||
Some(parent) => name = parent.clone(),
|
||||
None => break,
|
||||
@@ -87,6 +116,11 @@ impl ModelLibrary {
|
||||
.iter()
|
||||
.find(|m| m.elements.is_some())
|
||||
.map(|m| Arc::clone(m));
|
||||
let generated = chain
|
||||
.iter()
|
||||
.zip(&names)
|
||||
.find(|(m, name)| m.elements.is_some() || *name == GENERATED_MODEL)
|
||||
.is_some_and(|(_, name)| name == GENERATED_MODEL);
|
||||
let display = ItemTransforms {
|
||||
contexts: std::array::from_fn(|index| {
|
||||
chain
|
||||
@@ -146,6 +180,7 @@ impl ModelLibrary {
|
||||
textures,
|
||||
unresolved_textures,
|
||||
geometry,
|
||||
generated,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import java.io.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.*;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.model.geom.EntityModelSet;
|
||||
import net.minecraft.client.renderer.item.*;
|
||||
import net.minecraft.client.renderer.item.properties.select.SelectItemModelProperty;
|
||||
import net.minecraft.client.renderer.special.SpecialModelRenderer;
|
||||
import net.minecraft.client.renderer.special.SpecialModelRenderers;
|
||||
import net.minecraft.client.renderer.texture.*;
|
||||
import net.minecraft.client.resources.metadata.animation.AnimationMetadataSection;
|
||||
import net.minecraft.client.resources.model.*;
|
||||
import net.minecraft.client.resources.model.cuboid.*;
|
||||
import net.minecraft.client.resources.model.geometry.BakedQuad;
|
||||
import net.minecraft.client.resources.model.sprite.SpriteGetter;
|
||||
import net.minecraft.client.resources.model.sprite.SpriteId;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.component.DataComponentType;
|
||||
import net.minecraft.core.component.DataComponents;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.data.registries.VanillaRegistries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.util.StrictJsonParser;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.EntityTypes;
|
||||
import net.minecraft.world.entity.ItemOwner;
|
||||
import net.minecraft.world.entity.HumanoidArm;
|
||||
import net.minecraft.world.entity.decoration.ArmorStand;
|
||||
import net.minecraft.world.item.*;
|
||||
import net.minecraft.world.item.component.BundleContents;
|
||||
import net.minecraft.world.level.GrassColor;
|
||||
import net.minecraft.world.level.Level;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Vector3fc;
|
||||
|
||||
/**
|
||||
* Drives the pinned client's own item pipeline headlessly: the ClientItem codec,
|
||||
* ModelDiscovery, ModelBakery with real baked item models, ItemModelResolver
|
||||
* semantics and ItemStackRenderState layers. Sprites are real PNGs in a unit
|
||||
* atlas; the player skin cache and GPU are never touched.
|
||||
*/
|
||||
public final class VanillaItemModelOracle {
|
||||
private static final Gson JSON = new GsonBuilder().serializeNulls().create();
|
||||
private static long bits(float value) { return Integer.toUnsignedLong(Float.floatToIntBits(value)); }
|
||||
static Map<String, Object> map(Object... values) {
|
||||
var result = new TreeMap<String, Object>();
|
||||
for (int i = 0; i < values.length; i += 2) result.put((String) values[i], values[i + 1]);
|
||||
return result;
|
||||
}
|
||||
|
||||
static Path root;
|
||||
static HolderLookup.Provider registries;
|
||||
static RegistryOps<JsonElement> ops;
|
||||
static String frozenTime = "";
|
||||
static final Identifier BLOCKS = TextureAtlas.LOCATION_BLOCKS, ITEMS = TextureAtlas.LOCATION_ITEMS;
|
||||
|
||||
static final class Sprite extends TextureAtlasSprite {
|
||||
Sprite(Identifier atlas, SpriteContents contents) { super(atlas, contents, contents.width(), contents.height(), 0, 0, 0); }
|
||||
}
|
||||
|
||||
/** Sprites loaded on demand from the extracted jar. */
|
||||
static final class Regions extends HashMap<Identifier, TextureAtlasSprite> {
|
||||
final boolean items;
|
||||
Regions(boolean items) { this.items = items; }
|
||||
@Override public TextureAtlasSprite get(Object key) {
|
||||
var id = (Identifier) key;
|
||||
boolean itemAtlas = id.getPath().startsWith("item/") || id.getPath().startsWith("trims/");
|
||||
if (itemAtlas != items) return null;
|
||||
return computeIfAbsent(id, k -> load(k, items ? ITEMS : BLOCKS));
|
||||
}
|
||||
}
|
||||
static TextureAtlasSprite load(Identifier id, Identifier atlas) {
|
||||
try {
|
||||
var png = root.resolve("assets").resolve(id.getNamespace()).resolve("textures").resolve(id.getPath() + ".png");
|
||||
if (!Files.isRegularFile(png)) return null;
|
||||
NativeImage image;
|
||||
try (var in = Files.newInputStream(png)) { image = NativeImage.read(in); }
|
||||
var mcmeta = png.resolveSibling(png.getFileName() + ".mcmeta");
|
||||
Optional<AnimationMetadataSection> animation = Optional.empty();
|
||||
if (Files.isRegularFile(mcmeta)) {
|
||||
var json = JsonParser.parseString(Files.readString(mcmeta)).getAsJsonObject();
|
||||
if (json.has("animation"))
|
||||
animation = Optional.of(AnimationMetadataSection.CODEC.parse(JsonOps.INSTANCE, json.get("animation")).getOrThrow());
|
||||
}
|
||||
var size = animation.map(a -> a.calculateFrameSize(image.getWidth(), image.getHeight()))
|
||||
.orElse(new net.minecraft.client.resources.metadata.animation.FrameSize(image.getWidth(), image.getHeight()));
|
||||
return new Sprite(atlas, new SpriteContents(id, size, image, animation, List.of(), Optional.empty()));
|
||||
} catch (IOException e) { throw new UncheckedIOException(e); }
|
||||
}
|
||||
|
||||
// --- Tagging of special renderers so the layer carries its codec form. ---
|
||||
static final class Tagged implements SpecialModelRenderer.Unbaked<Object> {
|
||||
final SpecialModelRenderer.Unbaked<?> delegate;
|
||||
Tagged(SpecialModelRenderer.Unbaked<?> delegate) { this.delegate = delegate; }
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
public MapCodec<? extends SpecialModelRenderer.Unbaked<Object>> type() { return (MapCodec) delegate.type(); }
|
||||
public SpecialModelRenderer<Object> bake(SpecialModelRenderer.BakingContext context) {
|
||||
var baked = delegate.bake(context);
|
||||
if (baked == null) return null;
|
||||
@SuppressWarnings({"unchecked", "rawtypes"}) JsonElement config = SpecialModelRenderers.CODEC.encodeStart(JsonOps.INSTANCE, (SpecialModelRenderer.Unbaked) delegate).getOrThrow();
|
||||
return new TaggedRenderer(baked, config);
|
||||
}
|
||||
}
|
||||
static final class TaggedRenderer implements SpecialModelRenderer<Object> {
|
||||
final SpecialModelRenderer<?> delegate; final JsonElement config;
|
||||
TaggedRenderer(SpecialModelRenderer<?> delegate, JsonElement config) { this.delegate = delegate; this.config = config; }
|
||||
public void submit(Object argument, com.mojang.blaze3d.vertex.PoseStack poseStack, net.minecraft.client.renderer.SubmitNodeCollector collector, int light, int overlay, boolean foil, int outline) {}
|
||||
public void getExtents(java.util.function.Consumer<Vector3fc> output) { delegate.getExtents(output); }
|
||||
public Object extractArgument(ItemStack stack) { return new Argument(argument(config.getAsJsonObject().get("type").getAsString(), stack)); }
|
||||
}
|
||||
record Argument(JsonElement json) {}
|
||||
static JsonElement encode(DataComponentType<?> type, ItemStack stack) {
|
||||
var value = stack.get((DataComponentType) type);
|
||||
if (value == null) return JsonNull.INSTANCE;
|
||||
@SuppressWarnings({"unchecked", "rawtypes"}) var result = ((Codec) type.codecOrThrow()).encodeStart(ops, value).getOrThrow();
|
||||
return (JsonElement) result;
|
||||
}
|
||||
static JsonElement argument(String type, ItemStack stack) {
|
||||
return switch (type) {
|
||||
case "minecraft:banner" -> encode(DataComponents.BANNER_PATTERNS, stack);
|
||||
case "minecraft:decorated_pot" -> encode(DataComponents.POT_DECORATIONS, stack);
|
||||
case "minecraft:player_head" -> encode(DataComponents.PROFILE, stack);
|
||||
case "minecraft:shield" -> {
|
||||
var o = new JsonObject();
|
||||
var patterns = encode(DataComponents.BANNER_PATTERNS, stack);
|
||||
if (!patterns.isJsonNull()) o.add("minecraft:banner_patterns", patterns);
|
||||
var color = encode(DataComponents.BASE_COLOR, stack);
|
||||
if (!color.isJsonNull()) o.add("minecraft:base_color", color);
|
||||
yield o;
|
||||
}
|
||||
default -> JsonNull.INSTANCE;
|
||||
};
|
||||
}
|
||||
/** Stands in for LocalTime so a case can script the formatted time. */
|
||||
record FrozenTime(Codec<String> valueCodec) implements SelectItemModelProperty<String> {
|
||||
public String get(ItemStack s, ClientLevel l, net.minecraft.world.entity.LivingEntity o, int seed, ItemDisplayContext d) { return frozenTime; }
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
public SelectItemModelProperty.Type type() { return net.minecraft.client.renderer.item.properties.select.LocalTime.TYPE; }
|
||||
}
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
static ItemModel.Unbaked tag(ItemModel.Unbaked u) {
|
||||
if (u instanceof SpecialModelWrapper.Unbaked s)
|
||||
return new SpecialModelWrapper.Unbaked(s.base(), s.transformation(), new Tagged(s.specialModel()));
|
||||
if (u instanceof CompositeModel.Unbaked c)
|
||||
return new CompositeModel.Unbaked(c.models().stream().map(VanillaItemModelOracle::tag).collect(Collectors.toList()), c.transformation());
|
||||
if (u instanceof ConditionalItemModel.Unbaked c)
|
||||
return new ConditionalItemModel.Unbaked(c.transformation(), c.property(), tag(c.onTrue()), tag(c.onFalse()));
|
||||
if (u instanceof SelectItemModel.Unbaked s) {
|
||||
var sw = (SelectItemModel.UnbakedSwitch) s.unbakedSwitch();
|
||||
var cases = new ArrayList<SelectItemModel.SwitchCase>();
|
||||
for (var c : (List<SelectItemModel.SwitchCase>) sw.cases()) cases.add(new SelectItemModel.SwitchCase(c.values(), tag(c.model())));
|
||||
Object property = sw.property();
|
||||
if (property instanceof net.minecraft.client.renderer.item.properties.select.LocalTime) property = new FrozenTime(Codec.STRING);
|
||||
return new SelectItemModel.Unbaked(s.transformation(), new SelectItemModel.UnbakedSwitch((SelectItemModelProperty) property, cases), s.fallback().map(VanillaItemModelOracle::tag));
|
||||
}
|
||||
if (u instanceof RangeSelectItemModel.Unbaked r) {
|
||||
var entries = new ArrayList<RangeSelectItemModel.Entry>();
|
||||
for (var e : r.entries()) entries.add(new RangeSelectItemModel.Entry(e.threshold(), tag(e.model())));
|
||||
return new RangeSelectItemModel.Unbaked(r.transformation(), r.property(), r.scale(), entries, r.fallback().map(VanillaItemModelOracle::tag));
|
||||
}
|
||||
return u;
|
||||
}
|
||||
|
||||
// --- Scripted owner ---
|
||||
static final class Actor extends ArmorStand {
|
||||
boolean using; int remaining; ItemStack stack = ItemStack.EMPTY; HumanoidArm arm = HumanoidArm.RIGHT; EntityType<?> kind = EntityTypes.PLAYER;
|
||||
Actor() { super(null, null); }
|
||||
@Override public boolean isUsingItem() { return using; }
|
||||
@Override public ItemStack getUseItem() { return using ? stack : ItemStack.EMPTY; }
|
||||
@Override public int getUseItemRemainingTicks() { return remaining; }
|
||||
@Override public HumanoidArm getMainArm() { return arm; }
|
||||
@Override public net.minecraft.core.Holder.Reference<EntityType<?>> typeHolder() { return kind.builtInRegistryHolder(); }
|
||||
}
|
||||
static Object unsafe; static Method allocate;
|
||||
@SuppressWarnings("unchecked") static <T> T make(Class<T> type) throws Exception { return (T) allocate.invoke(unsafe, type); }
|
||||
|
||||
static final class Resolver extends ItemModelResolver {
|
||||
Map<Identifier, ItemModel> models; Map<Identifier, ClientItem.Properties> properties; ItemModel missing;
|
||||
Resolver() { super(null); }
|
||||
@Override public void appendItemLayers(ItemStackRenderState output, ItemStack item, ItemDisplayContext context, Level level, ItemOwner owner, int seed) {
|
||||
Identifier id = item.get(DataComponents.ITEM_MODEL);
|
||||
if (id != null) {
|
||||
output.setOversizedInGui(properties.getOrDefault(id, ClientItem.Properties.DEFAULT).oversizedInGui());
|
||||
models.getOrDefault(id, missing).update(output, item, this, context, level instanceof ClientLevel c ? c : null, owner, seed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static Object field(Object target, Class<?> type, String name) throws Exception {
|
||||
var f = type.getDeclaredField(name); f.setAccessible(true); return f.get(target);
|
||||
}
|
||||
static Object quad(BakedQuad q) {
|
||||
var positions = new long[4][3]; var uvs = new long[4][2];
|
||||
for (int i = 0; i < 4; i++) {
|
||||
var p = q.position(i); positions[i] = new long[]{bits(p.x()), bits(p.y()), bits(p.z())};
|
||||
long packed = q.packedUV(i); uvs[i] = new long[]{packed >>> 32, packed & 0xffffffffL};
|
||||
}
|
||||
var info = q.materialInfo();
|
||||
return map("positions", positions, "uv", uvs, "facing", q.direction().getName(), "tint", info.tintIndex(),
|
||||
"sprite", info.sprite().contents().name().toString(),
|
||||
"shade", info.shadeDirectionOverride() == null ? null : info.shadeDirectionOverride().getName(), "light", info.lightEmission());
|
||||
}
|
||||
static Object matrix(Matrix4f m) {
|
||||
var rows = new long[16];
|
||||
for (int r = 0; r < 4; r++) for (int c = 0; c < 4; c++) rows[r * 4 + c] = bits(m.getRowColumn(r, c));
|
||||
return rows;
|
||||
}
|
||||
static Object layer(ItemStackRenderState state, Object layer, ItemDisplayContext context) throws Exception {
|
||||
var type = layer.getClass();
|
||||
var out = new TreeMap<String, Object>();
|
||||
var special = (SpecialModelRenderer<?>) field(layer, type, "specialRenderer");
|
||||
var tints = (it.unimi.dsi.fastutil.ints.IntList) field(layer, type, "tintLayers");
|
||||
out.put("tints", tints == null ? new int[0] : tints.toIntArray());
|
||||
out.put("foil", ((ItemStackRenderState.FoilType) field(layer, type, "foilType")).name().toLowerCase(Locale.ROOT));
|
||||
var pose = new com.mojang.blaze3d.vertex.PoseStack.Pose();
|
||||
var apply = type.getDeclaredMethod("applyTransform", com.mojang.blaze3d.vertex.PoseStack.Pose.class);
|
||||
apply.setAccessible(true); apply.invoke(layer, pose);
|
||||
out.put("matrix", matrix(pose.pose()));
|
||||
out.put("uses_block_light", field(layer, type, "usesBlockLight"));
|
||||
var particle = (net.minecraft.client.resources.model.sprite.Material.Baked) field(layer, type, "particleMaterial");
|
||||
out.put("particle", particle == null ? null : particle.sprite().contents().name().toString());
|
||||
var transform = (net.minecraft.client.resources.model.cuboid.ItemTransform) field(layer, type, "itemTransform");
|
||||
out.put("has_transform", transform != net.minecraft.client.resources.model.cuboid.ItemTransform.NO_TRANSFORM);
|
||||
if (special instanceof TaggedRenderer tagged) {
|
||||
out.put("kind", "special");
|
||||
out.put("special", tagged.config);
|
||||
var argument = field(layer, type, "argumentForSpecialRendering");
|
||||
out.put("argument", argument instanceof Argument a ? a.json() : JsonNull.INSTANCE);
|
||||
} else {
|
||||
var quads = (net.minecraft.client.resources.model.geometry.ItemQuads) field(layer, type, "quads");
|
||||
out.put("quads", quads.all().stream().map(VanillaItemModelOracle::quad).toList());
|
||||
out.put("kind", "model");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static Map<String, JsonObject> prototypes = new HashMap<>();
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
ItemModels.bootstrap();
|
||||
SpecialModelRenderers.bootstrap();
|
||||
net.minecraft.client.color.item.ItemTintSources.bootstrap();
|
||||
net.minecraft.client.renderer.item.properties.select.SelectItemModelProperties.bootstrap();
|
||||
net.minecraft.client.renderer.item.properties.conditional.ConditionalItemModelProperties.bootstrap();
|
||||
net.minecraft.client.renderer.item.properties.numeric.RangeSelectItemModelProperties.bootstrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
var uf = u.getDeclaredField("theUnsafe"); uf.setAccessible(true); unsafe = uf.get(null);
|
||||
allocate = u.getMethod("allocateInstance", Class.class);
|
||||
root = Path.of(args[0]);
|
||||
registries = VanillaRegistries.createWorldLookup();
|
||||
ops = RegistryOps.create(JsonOps.INSTANCE, registries);
|
||||
// Default components come from the prepared export of the vanilla reports.
|
||||
var defaults = JsonParser.parseString(Files.readString(Path.of(args[3]))).getAsJsonObject();
|
||||
for (var item : BuiltInRegistries.ITEM) {
|
||||
var json = defaults.get(BuiltInRegistries.ITEM.getKey(item).toString());
|
||||
var map = json == null ? net.minecraft.core.component.DataComponentMap.EMPTY
|
||||
: net.minecraft.core.component.DataComponentMap.CODEC.parse(ops, json).getOrThrow();
|
||||
item.builtInRegistryHolder().bindComponents(map);
|
||||
}
|
||||
|
||||
// Grass colour map for the grass tint.
|
||||
try (var in = Files.newInputStream(root.resolve("assets/minecraft/textures/colormap/grass.png")); var image = NativeImage.read(in)) {
|
||||
GrassColor.init(image.getPixels());
|
||||
}
|
||||
|
||||
// Every model file.
|
||||
var models = new HashMap<Identifier, UnbakedModel>();
|
||||
try (Stream<Path> files = Files.walk(root.resolve("assets/minecraft/models"))) {
|
||||
for (var file : (Iterable<Path>) files.filter(p -> p.toString().endsWith(".json"))::iterator) {
|
||||
var relative = root.resolve("assets/minecraft/models").relativize(file).toString().replace('\\', '/');
|
||||
try (var reader = Files.newBufferedReader(file)) {
|
||||
models.put(Identifier.withDefaultNamespace(relative.substring(0, relative.length() - 5)), CuboidModel.fromStream(reader));
|
||||
} catch (RuntimeException ignored) {}
|
||||
}
|
||||
}
|
||||
// Every item definition.
|
||||
var output = Files.newBufferedWriter(Path.of(args[2]));
|
||||
output.write(JSON.toJson(map("row", "components", "names",
|
||||
BuiltInRegistries.DATA_COMPONENT_TYPE.keySet().stream().map(Identifier::toString).sorted().toList()))); output.newLine();
|
||||
var items = new TreeMap<Identifier, ClientItem>();
|
||||
try (Stream<Path> files = Files.list(root.resolve("assets/minecraft/items"))) {
|
||||
for (var file : (Iterable<Path>) files.sorted()::iterator) {
|
||||
var name = file.getFileName().toString();
|
||||
var id = Identifier.withDefaultNamespace(name.substring(0, name.length() - 5));
|
||||
String text = Files.readString(file);
|
||||
boolean ok = decode(id, text, items);
|
||||
output.write(JSON.toJson(map("row", "decode", "name", name, "ok", ok))); output.newLine();
|
||||
}
|
||||
}
|
||||
// Synthetic definitions from the harness.
|
||||
try (var lines = Files.lines(Path.of(args[1] + ".definitions"))) {
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var row = JsonParser.parseString(line).getAsJsonObject();
|
||||
var id = Identifier.parse(row.get("name").getAsString());
|
||||
boolean ok = decode(id, row.get("json").getAsString(), items);
|
||||
output.write(JSON.toJson(map("row", "decode", "name", row.get("name").getAsString(), "ok", ok))); output.newLine();
|
||||
}
|
||||
}
|
||||
|
||||
var missingModel = MissingCuboidModel.missingModel();
|
||||
var discovery = new ModelDiscovery(models, missingModel);
|
||||
discovery.addSpecialModel(ItemModelGenerator.GENERATED_ITEM_MODEL_ID, new ItemModelGenerator());
|
||||
items.values().forEach(info -> discovery.addRoot(info.model()));
|
||||
var resolved = discovery.resolve();
|
||||
var missingSprite = new Sprite(BLOCKS, MissingTextureAtlasSprite.create());
|
||||
var blockAtlas = new SpriteLoader.Preparations(16, 16, 0, missingSprite, new Regions(false), CompletableFuture.completedFuture(null));
|
||||
var itemAtlas = new SpriteLoader.Preparations(16, 16, 0, missingSprite, new Regions(true), CompletableFuture.completedFuture(null));
|
||||
var materials = new net.minecraft.client.resources.model.sprite.MaterialBaker(blockAtlas, itemAtlas);
|
||||
var dummy = new Sprite(ITEMS, new SpriteContents(Identifier.parse("minecraft:dummy"), new net.minecraft.client.resources.metadata.animation.FrameSize(16, 16), new NativeImage(16, 16, true)));
|
||||
SpriteGetter sprites = id -> dummy;
|
||||
var bakery = new ModelBakery(EntityModelSet.vanilla(), sprites, null, Map.of(), tagged(items), resolved, discovery.missingModel());
|
||||
var baked = bakery.bakeModels(materials, Runnable::run).join();
|
||||
var resolver = new Resolver();
|
||||
resolver.models = baked.itemStackModels(); resolver.properties = baked.itemProperties(); resolver.missing = baked.missingModels().item();
|
||||
for (var id : items.keySet()) if (!resolver.models.containsKey(id)) {
|
||||
output.write(JSON.toJson(map("row", "unbaked", "name", id.toString()))); output.newLine();
|
||||
}
|
||||
var state = new ItemStackRenderState();
|
||||
|
||||
try (var lines = Files.lines(Path.of(args[1]))) {
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var row = JsonParser.parseString(line).getAsJsonObject();
|
||||
var result = new TreeMap<String, Object>();
|
||||
result.put("row", "case"); result.put("id", row.get("id").getAsString());
|
||||
try {
|
||||
var stackJson = new JsonObject();
|
||||
stackJson.addProperty("id", row.get("item").getAsString());
|
||||
stackJson.addProperty("count", row.get("count").getAsInt());
|
||||
if (row.has("components")) stackJson.add("components", row.get("components"));
|
||||
var stack = ItemStack.CODEC.parse(ops, stackJson).getOrThrow();
|
||||
if (row.has("bundle_selected") && row.get("bundle_selected").getAsInt() >= 0) {
|
||||
var contents = stack.get(DataComponents.BUNDLE_CONTENTS);
|
||||
var mutable = contents.asMutable();
|
||||
mutable.toggleSelectedItem(row.get("bundle_selected").getAsInt());
|
||||
stack.set(DataComponents.BUNDLE_CONTENTS, mutable.toImmutable());
|
||||
}
|
||||
var context = ItemDisplayContext.CODEC.parse(JsonOps.INSTANCE, row.get("context")).getOrThrow();
|
||||
frozenTime = row.has("local_time") ? row.get("local_time").getAsString() : "";
|
||||
Actor actor = null;
|
||||
if (row.has("owner") && !row.get("owner").isJsonNull()) {
|
||||
var o = row.getAsJsonObject("owner");
|
||||
actor = make(Actor.class);
|
||||
actor.using = o.get("using").getAsBoolean();
|
||||
actor.remaining = o.get("remaining").getAsInt();
|
||||
actor.stack = stack;
|
||||
actor.arm = o.get("main_arm").getAsString().equals("left") ? HumanoidArm.LEFT : HumanoidArm.RIGHT;
|
||||
actor.kind = BuiltInRegistries.ENTITY_TYPE.getValue(Identifier.parse(o.get("entity_type").getAsString()));
|
||||
var derived = new TreeMap<String, Object>();
|
||||
derived.put("use_duration", stack.getUseDuration(actor));
|
||||
try { derived.put("charge_duration", CrossbowItem.getChargeDuration(stack, actor)); } catch (RuntimeException e) { derived.put("charge_duration", 0); }
|
||||
result.put("derived", derived);
|
||||
}
|
||||
Level level = null;
|
||||
if (row.has("dimension") && !row.get("dimension").isJsonNull()) {
|
||||
var dim = net.minecraft.resources.ResourceKey.create(net.minecraft.core.registries.Registries.DIMENSION, Identifier.parse(row.get("dimension").getAsString()));
|
||||
var clientLevel = make(ClientLevel.class);
|
||||
var f = Level.class.getDeclaredField("dimension"); f.setAccessible(true);
|
||||
var offset = (long) u.getMethod("objectFieldOffset", Field.class).invoke(unsafe, f);
|
||||
u.getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, clientLevel, offset, dim);
|
||||
level = clientLevel;
|
||||
}
|
||||
resolver.updateForTopItem(state, stack, context, level, actor, row.has("seed") ? row.get("seed").getAsInt() : 0);
|
||||
var layersField = ItemStackRenderState.class.getDeclaredField("layers"); layersField.setAccessible(true);
|
||||
var countField = ItemStackRenderState.class.getDeclaredField("activeLayerCount"); countField.setAccessible(true);
|
||||
var layers = (Object[]) layersField.get(state); int count = countField.getInt(state);
|
||||
var list = new ArrayList<Object>();
|
||||
for (int i = 0; i < count; i++) list.add(layer(state, layers[i], context));
|
||||
result.put("layers", list);
|
||||
result.put("oversized", state.isOversizedInGui());
|
||||
result.put("swap", map("play", resolver.shouldPlaySwapAnimation(stack), "scale", bits(resolver.swapAnimationScale(stack))));
|
||||
} catch (Throwable e) {
|
||||
Throwable cause = e; while (cause.getCause() != null) cause = cause.getCause();
|
||||
result.put("error", cause.toString());
|
||||
}
|
||||
output.write(JSON.toJson(result)); output.newLine();
|
||||
}
|
||||
}
|
||||
output.close();
|
||||
}
|
||||
|
||||
static Map<Identifier, ClientItem> tagged(Map<Identifier, ClientItem> items) {
|
||||
var out = new TreeMap<Identifier, ClientItem>();
|
||||
items.forEach((id, item) -> out.put(id, new ClientItem(tag(item.model()), item.properties(), item.registrySwapper())));
|
||||
return out;
|
||||
}
|
||||
static boolean decode(Identifier id, String text, Map<Identifier, ClientItem> items) {
|
||||
try {
|
||||
var parsed = ClientItem.CODEC.parse(ops, StrictJsonParser.parse(new StringReader(text))).result();
|
||||
parsed.ifPresent(item -> items.put(id, item));
|
||||
return parsed.isPresent();
|
||||
} catch (Exception e) { return false; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare item model resolution with the pinned client's own item pipeline.
|
||||
|
||||
The vanilla side (VanillaItemModelOracle) decodes every `items/*.json` with the
|
||||
client codec, discovers and bakes all models with `ModelBakery` against real
|
||||
PNG sprites, and resolves stacks through `ItemStackRenderState` layers. The
|
||||
Rust side (`item_model_fixture`) must pick the same layers, tints, foil,
|
||||
transformations, special-renderer configurations and baked quads."""
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import random
|
||||
import subprocess
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
except ImportError:
|
||||
import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
|
||||
CONTEXTS = ['gui', 'ground', 'fixed', 'head', 'thirdperson_righthand', 'thirdperson_lefthand',
|
||||
'firstperson_righthand', 'firstperson_lefthand', 'on_shelf', 'none']
|
||||
DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan',
|
||||
'purple', 'blue', 'brown', 'green', 'red', 'black']
|
||||
TRIM_MATERIALS = ['quartz', 'iron', 'netherite', 'redstone', 'copper', 'gold', 'emerald', 'diamond', 'lapis',
|
||||
'amethyst', 'resin']
|
||||
NEEDED = ('assets/minecraft/items/', 'assets/minecraft/models/', 'assets/minecraft/textures/item/',
|
||||
'assets/minecraft/textures/block/', 'assets/minecraft/textures/trims/',
|
||||
'assets/minecraft/textures/colormap/')
|
||||
|
||||
|
||||
def extract(jar, destination):
|
||||
marker = destination / '.jar-sha256'
|
||||
digest = lab.digest(jar, 'sha256')
|
||||
if marker.exists() and marker.read_text() == digest:
|
||||
return
|
||||
destination.mkdir(parents=True, exist_ok=True)
|
||||
with zipfile.ZipFile(jar) as archive:
|
||||
for name in archive.namelist():
|
||||
if name.startswith(NEEDED) and not name.endswith('/'):
|
||||
target = destination / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(archive.read(name))
|
||||
marker.write_text(digest)
|
||||
|
||||
|
||||
def owner(using, remaining, arm='right', entity='minecraft:player'):
|
||||
return {'using': using, 'remaining': remaining, 'main_arm': arm, 'entity_type': entity}
|
||||
|
||||
|
||||
def corpus(prototypes):
|
||||
"""Representative stacks for every registered item."""
|
||||
rng = random.Random(0x4954454d)
|
||||
cases = []
|
||||
def add(item, context='gui', count=1, components=None, **extra):
|
||||
case = {'id': str(len(cases)), 'item': item, 'count': count, 'context': context}
|
||||
if components: case['components'] = components
|
||||
case.update(extra)
|
||||
cases.append(case)
|
||||
for item, components in prototypes.items():
|
||||
stack = components.get('minecraft:max_stack_size', 64)
|
||||
for context in CONTEXTS: add(item, context)
|
||||
max_damage = components.get('minecraft:max_damage', 0)
|
||||
if max_damage:
|
||||
for damage in sorted({0, 1, max_damage // 2, max_damage - 2, max_damage - 1, max_damage}):
|
||||
add(item, 'gui', components={'minecraft:damage': damage})
|
||||
add(item, 'gui', components={'minecraft:damage': max_damage - 1, 'minecraft:unbreakable': {}})
|
||||
add(item, 'gui', components={'!minecraft:max_damage': {}})
|
||||
for count in sorted({2, stack // 2, stack}):
|
||||
if 1 <= count <= stack: add(item, 'gui', count=count)
|
||||
for color in (0xFF0000, 0x123456, 0xFFFFFF, 0):
|
||||
add(item, 'gui', components={'minecraft:dyed_color': color})
|
||||
for material in TRIM_MATERIALS:
|
||||
add(item, 'gui', components={'minecraft:trim': {'material': 'minecraft:' + material, 'pattern': 'minecraft:coast'}})
|
||||
add(item, 'gui', components={'minecraft:custom_model_data': {'floats': [0.0, 0.5, 1.0, 2.5, 7.0],
|
||||
'flags': [True, False, True], 'strings': ['a', 'b', 'c'], 'colors': [0xFF0000, 0x00FF00]}})
|
||||
add(item, 'gui', components={'minecraft:custom_model_data': {'floats': [3.0]}})
|
||||
for context in ('gui', 'ground', 'head'):
|
||||
add(item, context, components={'minecraft:enchantments': {'minecraft:sharpness': 1}})
|
||||
add(item, 'gui', components={'minecraft:enchantment_glint_override': True})
|
||||
add(item, 'gui', components={'minecraft:enchantment_glint_override': False,
|
||||
'minecraft:enchantments': {'minecraft:sharpness': 1}})
|
||||
add(item, 'gui', components={'minecraft:potion_contents': {'custom_color': 0x00FF7F}})
|
||||
add(item, 'gui', components={'minecraft:potion_contents': {'potion': 'minecraft:water'}})
|
||||
add(item, 'gui', components={'minecraft:potion_contents': {}})
|
||||
for colors in ([], [0xFF0000], [0xFF0000, 0x0000FF], [0x112233, 0x445566, 0x778899]):
|
||||
add(item, 'gui', components={'minecraft:firework_explosion': {'shape': 'small_ball', 'colors': colors}})
|
||||
add(item, 'gui', components={'minecraft:item_model': 'minecraft:diamond'})
|
||||
add(item, 'gui', components={'minecraft:item_model': 'minecraft:horizon_unknown'})
|
||||
add(item, 'gui', components={'!minecraft:item_model': {}})
|
||||
add(item, 'gui', components={'minecraft:item_model': 'minecraft:bundle'}, bundle_selected=0)
|
||||
for state in ({'honey_level': '0'}, {'honey_level': '5'}, {'light_level': '7'}, {'level': '1'},
|
||||
{'age': '3'}, {'powered': 'true'}, {'unknown': 'x'}):
|
||||
add(item, 'gui', components={'minecraft:block_state': state})
|
||||
for projectile in ('minecraft:arrow', 'minecraft:firework_rocket'):
|
||||
add(item, 'gui', components={'minecraft:charged_projectiles': [{'id': projectile, 'count': 1}]})
|
||||
add(item, 'gui', components={'minecraft:charged_projectiles': []})
|
||||
add(item, 'gui', components={'minecraft:lodestone_tracker': {}})
|
||||
add(item, 'gui', components={'minecraft:lodestone_tracker': {'tracked': True,
|
||||
'target': {'dimension': 'minecraft:overworld', 'pos': [1, 2, 3]}}})
|
||||
add(item, 'gui', components={'minecraft:banner_patterns': [{'pattern': 'minecraft:circle', 'color': 'red'},
|
||||
{'pattern': 'minecraft:border', 'color': 'blue'}]})
|
||||
add(item, 'gui', components={'minecraft:base_color': 'green',
|
||||
'minecraft:banner_patterns': [{'pattern': 'minecraft:globe', 'color': 'yellow'}]})
|
||||
add(item, 'gui', components={'minecraft:pot_decorations': {'back': {'id': 'minecraft:brick'},
|
||||
'left': {'id': 'minecraft:angler_pottery_sherd'}, 'front': {'id': 'minecraft:blade_pottery_sherd'}}})
|
||||
add(item, 'gui', components={'minecraft:profile': {'name': 'Notch'}})
|
||||
add(item, 'gui', components={'minecraft:bundle_contents': [{'id': 'minecraft:stone', 'count': 3},
|
||||
{'id': 'minecraft:diamond_sword', 'count': 1},
|
||||
{'id': 'minecraft:dirt', 'count': 20}]}, bundle_selected=1)
|
||||
add(item, 'gui', components={'minecraft:bundle_contents': [{'id': 'minecraft:stone', 'count': 3}]}, bundle_selected=-1)
|
||||
for time in ('12-24', '12-25', '12-26', '10-09', ''):
|
||||
add(item, 'gui', local_time=time)
|
||||
for dimension in ('minecraft:overworld', 'minecraft:the_nether', 'minecraft:the_end', 'horizon:other'):
|
||||
add(item, 'gui', dimension=dimension)
|
||||
for arm in ('left', 'right'):
|
||||
for entity in ('minecraft:player', 'minecraft:zombie'):
|
||||
add(item, 'firstperson_righthand', owner=owner(False, 0, arm, entity))
|
||||
for remaining in (0, 1, 3, 7, 13, 20, 71000, 71990, 72000):
|
||||
for context in ('firstperson_righthand', 'thirdperson_righthand'):
|
||||
add(item, context, owner=owner(True, remaining))
|
||||
add(item, 'firstperson_righthand', owner=owner(False, 5))
|
||||
# Item definitions with every shape the codec accepts and rejects.
|
||||
return cases
|
||||
|
||||
|
||||
def definitions():
|
||||
"""Synthetic client item definitions: valid and invalid shapes."""
|
||||
model = {'type': 'minecraft:model', 'model': 'minecraft:item/stick'}
|
||||
other = {'type': 'minecraft:model', 'model': 'minecraft:item/diamond'}
|
||||
rows = {}
|
||||
def put(name, definition):
|
||||
rows['horizon:' + name] = definition if isinstance(definition, str) else json.dumps(definition)
|
||||
put('plain', {'model': model})
|
||||
put('props', {'model': model, 'hand_animation_on_swap': False, 'oversized_in_gui': True, 'swap_animation_scale': 2.5})
|
||||
put('no_model', {})
|
||||
put('unknown_type', {'model': {'type': 'minecraft:horizon'}})
|
||||
put('empty', {'model': {'type': 'minecraft:empty'}})
|
||||
put('composite', {'model': {'type': 'minecraft:composite', 'models': [model, other, {'type': 'minecraft:empty'}]}})
|
||||
put('composite_empty', {'model': {'type': 'minecraft:composite', 'models': []}})
|
||||
put('composite_one', {'model': {'type': 'minecraft:composite', 'models': [model],
|
||||
'transformation': [1, 0, 0, 0.5, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]}})
|
||||
put('matrix', {'model': dict(model, transformation=[0.5, 0, 0, 1, 0, 0.5, 0, 2, 0, 0, 0.5, 3, 0, 0, 0, 1])})
|
||||
put('matrix_short', {'model': dict(model, transformation=[1, 0, 0])})
|
||||
quarter = [0.0, 0.0, 0.70710677, 0.70710677]
|
||||
put('decomposed', {'model': dict(model, transformation={'translation': [1, 2, 3], 'left_rotation': quarter,
|
||||
'scale': [1, 2, 3], 'right_rotation': [0, 0.38268343, 0, 0.9238795]})})
|
||||
put('axis_angle', {'model': dict(model, transformation={'translation': [0, 0, 0],
|
||||
'left_rotation': {'angle': 1.5707964, 'axis': [0, 0, 1]}, 'scale': [1, 1, 1], 'right_rotation': [0, 0, 0, 1]})})
|
||||
put('decomposed_partial', {'model': dict(model, transformation={'translation': [0, 0, 0], 'scale': [1, 1, 1]})})
|
||||
put('nested_transform', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:damaged',
|
||||
'transformation': [2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1], 'on_true': dict(model, transformation=[1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), 'on_false': other}})
|
||||
put('tints', {'model': dict(model, tints=[{'type': 'minecraft:constant', 'value': 0x123456},
|
||||
{'type': 'minecraft:constant', 'value': [0.5, 0.25, 1.0]},
|
||||
{'type': 'minecraft:dye', 'default': -6265536}, {'type': 'minecraft:grass', 'temperature': 0.5, 'downfall': 1.0},
|
||||
{'type': 'minecraft:grass', 'temperature': 0.0, 'downfall': 0.0}, {'type': 'minecraft:grass', 'temperature': 1.0, 'downfall': 0.3},
|
||||
{'type': 'minecraft:firework', 'default': 7}, {'type': 'minecraft:potion', 'default': 9},
|
||||
{'type': 'minecraft:team', 'default': 11},
|
||||
{'type': 'minecraft:custom_model_data', 'index': 1, 'default': 0x0000FF}])})
|
||||
put('bad_tint', {'model': dict(model, tints=[{'type': 'minecraft:horizon'}])})
|
||||
put('bad_grass', {'model': dict(model, tints=[{'type': 'minecraft:grass', 'temperature': 2.0, 'downfall': 0.0}])})
|
||||
put('condition_missing_branch', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:damaged', 'on_true': model}})
|
||||
for prop in ('broken', 'damaged', 'using_item', 'selected', 'carried', 'view_entity', 'extended_view',
|
||||
'fishing_rod/cast', 'bundle/has_selected_item'):
|
||||
put('cond_' + prop.replace('/', '_'), {'model': {'type': 'minecraft:condition', 'property': 'minecraft:' + prop, 'on_true': model, 'on_false': other}})
|
||||
for index in (0, 1, 3, -1):
|
||||
put(f'cond_cmd_{index}', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:custom_model_data', 'index': index, 'on_true': model, 'on_false': other}})
|
||||
for ignore in (True, False):
|
||||
for component in ('minecraft:damage', 'minecraft:enchantments', 'minecraft:max_damage', 'minecraft:custom_name', 'minecraft:horizon'):
|
||||
put(f'cond_has_{ignore}_{component}'.lower().replace(':', '_'), {'model': {'type': 'minecraft:condition', 'property': 'minecraft:has_component',
|
||||
'component': component, 'ignore_default': ignore, 'on_true': model, 'on_false': other}})
|
||||
select = lambda prop, cases, **extra: {'model': dict({'type': 'minecraft:select', 'property': 'minecraft:' + prop,
|
||||
'cases': [{'when': w, 'model': m} for w, m in cases]}, **extra)}
|
||||
put('select_ctx', select('display_context', [(['gui', 'ground'], model), ('head', other)], fallback={'type': 'minecraft:empty'}))
|
||||
put('select_ctx_nofallback', select('display_context', [('gui', model)]))
|
||||
put('select_ctx_bad', select('display_context', [('guii', model)]))
|
||||
put('select_dup', select('display_context', [('gui', model), (['gui', 'head'], other)]))
|
||||
put('select_empty_cases', select('display_context', []))
|
||||
put('select_empty_when', select('display_context', [([], model)]))
|
||||
put('select_arm', select('main_hand', [('left', model), ('right', other)]))
|
||||
put('select_arm_fallback', select('main_hand', [('left', model)], fallback=other))
|
||||
put('select_charge', select('charge_type', [('none', model), ('arrow', other), ('rocket', {'type': 'minecraft:empty'})]))
|
||||
put('select_trim', select('trim_material', [(['minecraft:quartz', 'iron'], model), ('minecraft:gold', other)], fallback={'type': 'minecraft:empty'}))
|
||||
put('select_state', select('block_state', [('3', model), ('5', other)], block_state_property='honey_level', fallback=model))
|
||||
put('select_state_missing_prop', select('block_state', [('3', model)]))
|
||||
put('select_entity', select('context_entity_type', [('minecraft:player', model), ('zombie', other)], fallback={'type': 'minecraft:empty'}))
|
||||
put('select_dimension', select('context_dimension', [('minecraft:overworld', model), ('the_nether', other)], fallback={'type': 'minecraft:empty'}))
|
||||
put('select_cmd', select('custom_model_data', [('a', model), ('c', other)], index=2, fallback={'type': 'minecraft:empty'}))
|
||||
put('select_time', select('local_time', [('12-25', model)], pattern='MM-dd', fallback=other))
|
||||
put('select_time_bad', select('local_time', [('12-25', model)], pattern='Q{', fallback=other))
|
||||
put('select_component', select('component', [('minecraft:diamond_sword', model)], component='minecraft:item_model', fallback=other))
|
||||
put('select_unknown_prop', select('horizon', [('a', model)]))
|
||||
ranges = lambda prop, entries, **extra: {'model': dict({'type': 'minecraft:range_dispatch', 'property': 'minecraft:' + prop,
|
||||
'entries': [{'threshold': t, 'model': m} for t, m in entries]}, **extra)}
|
||||
put('range_damage', ranges('damage', [(0.0, model), (0.5, other), (0.99, {'type': 'minecraft:empty'})], fallback={'type': 'minecraft:empty'}))
|
||||
put('range_damage_raw', ranges('damage', [(0, model), (10, other)], normalize=False))
|
||||
put('range_count', ranges('count', [(0.0, model), (0.5, other), (1.0, {'type': 'minecraft:empty'})]))
|
||||
put('range_count_raw', ranges('count', [(1, model), (32, other)], normalize=False))
|
||||
put('range_scale', ranges('damage', [(0, model), (50, other)], scale=100))
|
||||
put('range_nofallback', ranges('damage', [(0.4, model)]))
|
||||
put('range_unsorted', ranges('count', [(0.9, other), (0.1, model), (0.5, {'type': 'minecraft:empty'}), (0.1, other)]))
|
||||
put('range_many', ranges('count', [(i / 20, model if i % 2 else other) for i in range(20)]))
|
||||
put('range_cmd', ranges('custom_model_data', [(0, model), (1, other), (2.5, {'type': 'minecraft:empty'})], index=0))
|
||||
put('range_cooldown', ranges('cooldown', [(0, model), (0.5, other)]))
|
||||
put('range_use_duration', ranges('use_duration', [(0, model), (10, other)]))
|
||||
put('range_use_remaining', ranges('use_duration', [(0, model), (10, other)], remaining=True))
|
||||
put('range_cycle', ranges('use_cycle', [(0, model), (2, other)], period=4))
|
||||
put('range_cycle_bad', ranges('use_cycle', [(0, model)], period=0))
|
||||
put('range_crossbow', ranges('crossbow/pull', [(0, model), (0.5, other)]))
|
||||
put('range_fullness', ranges('bundle/fullness', [(0, model), (0.5, other)]))
|
||||
put('range_time', ranges('time', [(0, model)], source='daytime'))
|
||||
put('range_compass', ranges('compass', [(0, model)], target='spawn'))
|
||||
put('range_compass_bad', ranges('compass', [(0, model)], target='moon'))
|
||||
put('range_nan_threshold', ranges('damage', [(float('nan'), model)]))
|
||||
put('range_no_entries', {'model': {'type': 'minecraft:range_dispatch', 'property': 'minecraft:damage'}})
|
||||
for kind, config in [('banner', {'color': 'red'}), ('banner', {'color': 'blue', 'attachment': 'wall'}),
|
||||
('banner', {'color': 'pink', 'attachment': 'ground'}), ('banner', {'color': 'nope'}), ('banner', {}),
|
||||
('bell', {}), ('book', {'open_angle': 1.0, 'page1': 0.25, 'page2': 0.75}), ('book', {'open_angle': 1.0}),
|
||||
('chest', {'texture': 'minecraft:normal'}), ('chest', {'texture': 'christmas', 'openness': 0.5, 'chest_type': 'left'}),
|
||||
('chest', {'texture': 'minecraft:normal', 'chest_type': 'triple'}), ('chest', {}),
|
||||
('conduit', {}), ('copper_golem_statue', {'texture': 'minecraft:copper', 'pose': 'star'}),
|
||||
('copper_golem_statue', {'texture': 'minecraft:copper', 'pose': 'dancing'}),
|
||||
('decorated_pot', {}), ('end_cube', {'effect': 'portal'}), ('end_cube', {'effect': 'void'}),
|
||||
('head', {'kind': 'dragon'}), ('head', {'kind': 'player', 'texture': 'horizon:custom', 'animation': 1.5}),
|
||||
('head', {'kind': 'ghast'}), ('player_head', {}),
|
||||
('shulker_box', {}), ('shulker_box', {'texture': 'minecraft:shulker_red', 'openness': 0.25}),
|
||||
('shield', {}), ('trident', {}), ('horizon', {})]:
|
||||
put(f'special_{kind}_{len(rows)}', {'model': {'type': 'minecraft:special', 'base': 'minecraft:item/shield' if kind == 'shield' else 'minecraft:item/template_banner',
|
||||
'model': dict(config, type='minecraft:' + kind)}})
|
||||
put('special_transformed', {'model': {'type': 'minecraft:special', 'base': 'minecraft:item/trident_in_hand', 'model': {'type': 'minecraft:trident'},
|
||||
'transformation': {'left_rotation': [0, 0, 0, 1], 'right_rotation': [0, 0, 0, 1], 'scale': [1, -1, -1], 'translation': [0, 0, 0]}}})
|
||||
put('bundle_selected', {'model': {'type': 'minecraft:composite', 'models': [model, {'type': 'minecraft:bundle/selected_item'}, other]}})
|
||||
for pack in ('', '_x'):
|
||||
put('trailing' + pack, json.dumps({'model': model}) + pack)
|
||||
put('not_object', '[]')
|
||||
put('null_model', {'model': None})
|
||||
put('number_scale', {'model': model, 'swap_animation_scale': 'x'})
|
||||
put('bool_flag_number', {'model': model, 'oversized_in_gui': 1})
|
||||
put('bool_flag_string', {'model': model, 'oversized_in_gui': 'true'})
|
||||
put('bool_flag_float', {'model': model, 'oversized_in_gui': 0.5})
|
||||
put('swap_bool', {'model': model, 'swap_animation_scale': True})
|
||||
put('int_float_index', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:custom_model_data', 'index': 1.5, 'on_true': model, 'on_false': other}})
|
||||
put('int_bool_index', {'model': {'type': 'minecraft:condition', 'property': 'minecraft:custom_model_data', 'index': True, 'on_true': model, 'on_false': other}})
|
||||
put('bool_as_number', {'model': dict({'type': 'minecraft:range_dispatch', 'property': 'minecraft:damage', 'entries': [{'threshold': True, 'model': model}]})})
|
||||
return rows
|
||||
|
||||
|
||||
def definition_cases(rows):
|
||||
cases = []
|
||||
stacks = [('minecraft:diamond_sword', {'minecraft:damage': 100}, 1), ('minecraft:diamond_sword', {'minecraft:damage': 1560}, 1),
|
||||
('minecraft:diamond_sword', {}, 1), ('minecraft:stone', {}, 64), ('minecraft:stone', {}, 17), ('minecraft:stone', {}, 1),
|
||||
('minecraft:bow', {}, 1), ('minecraft:leather_helmet', {'minecraft:trim': {'material': 'minecraft:gold', 'pattern': 'minecraft:coast'}}, 1),
|
||||
('minecraft:beehive', {'minecraft:block_state': {'honey_level': '3'}}, 1),
|
||||
('minecraft:beehive', {'minecraft:block_state': {'honey_level': '5'}}, 1), ('minecraft:crossbow', {}, 1),
|
||||
('minecraft:crossbow', {'minecraft:charged_projectiles': [{'id': 'minecraft:arrow', 'count': 1}]}, 1),
|
||||
('minecraft:diamond_sword', {'minecraft:custom_model_data': {'floats': [0.0, 1.0, 3.0], 'flags': [True], 'strings': ['a', 'b', 'c']}}, 1),
|
||||
('minecraft:diamond_sword', {'minecraft:custom_model_data': {'floats': [2.5], 'flags': [False, True], 'strings': ['x']}}, 1),
|
||||
('minecraft:bundle', {'minecraft:bundle_contents': [{'id': 'minecraft:diamond_sword', 'count': 1}, {'id': 'minecraft:stone', 'count': 3}]}, 1),
|
||||
('minecraft:bundle', {'minecraft:bundle_contents': []}, 1),
|
||||
('minecraft:stone', {'minecraft:enchantments': {'minecraft:sharpness': 1}}, 1),
|
||||
('minecraft:stone', {'minecraft:custom_name': '"x"'}, 1)]
|
||||
for name in rows:
|
||||
for stack_index, (item, components, count) in enumerate(stacks):
|
||||
for context in ('gui', 'head', 'firstperson_lefthand', 'ground'):
|
||||
for owner_state in (None, owner(True, 9), owner(False, 0, 'left', 'minecraft:zombie')):
|
||||
for dimension in (None, 'minecraft:overworld', 'minecraft:the_nether'):
|
||||
if dimension and context != 'gui': continue
|
||||
case = {'id': f'd{len(cases)}', 'item': item, 'count': count, 'context': context,
|
||||
'components': dict(components, **{'minecraft:item_model': name})}
|
||||
if owner_state: case['owner'] = owner_state
|
||||
if dimension: case['dimension'] = dimension
|
||||
if 'bundle_contents' in str(components) and count == 1 and 'diamond_sword' in str(components):
|
||||
case['bundle_selected'] = stack_index % 2
|
||||
case['local_time'] = '12-25' if stack_index % 2 else '01-01'
|
||||
cases.append(case)
|
||||
return cases
|
||||
|
||||
|
||||
import struct
|
||||
def float_bits(value):
|
||||
return struct.unpack('<I', struct.pack('<f', value))[0]
|
||||
THIN = (float_bits(7.5 / 16), float_bits(8.5 / 16))
|
||||
|
||||
|
||||
def canonical_quads(quads):
|
||||
"""The extruded sides of generated layers come out of a hash set in vanilla: no order to keep."""
|
||||
if quads and all(THIN[0] <= p[2] <= THIN[1] for q in quads for p in q['positions']):
|
||||
return sorted(quads, key=lambda q: json.dumps(q, sort_keys=True))
|
||||
return quads
|
||||
|
||||
|
||||
def matrix(bits):
|
||||
return [0 if b == 0x80000000 else b for b in bits]
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / 'item-model-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/VanillaItemModelOracle.java'
|
||||
crate = lab.ROOT / 'crates/horizon-assets'
|
||||
sources = [oracle, Path(__file__), 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)
|
||||
resources = build / 'resources'
|
||||
extract(jars['client'], resources)
|
||||
_, directory = lab.config()
|
||||
prototypes_path = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] / 'items.json'
|
||||
prototypes = json.loads(prototypes_path.read_text())
|
||||
cases = corpus(prototypes)
|
||||
rows = definitions()
|
||||
cases += definition_cases(rows)
|
||||
inputs = build / 'cases.jsonl'; inputs.write_text(''.join(json.dumps(c) + '\n' for c in cases))
|
||||
(build / 'cases.jsonl.definitions').write_text(''.join(json.dumps({'name': n, 'json': j}) + '\n' for n, j in rows.items()))
|
||||
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], 'compile-java')
|
||||
run(['cargo', 'build', '--locked', '-p', 'horizon-assets', '--example', 'item_model_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' / ('item_model_fixture.exe' if os.name == 'nt' else 'item_model_fixture')
|
||||
run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaItemModelOracle',
|
||||
resources, inputs, build / 'client.jsonl', prototypes_path], 'client')
|
||||
# The host inputs vanilla derives from the stack (use duration, charge time).
|
||||
client = [json.loads(line) for line in (build / 'client.jsonl').read_text().splitlines()]
|
||||
derived = {r['id']: r['derived'] for r in client if r.get('row') == 'case' and 'derived' in r}
|
||||
rust_cases = []
|
||||
for case in cases:
|
||||
case = dict(case)
|
||||
if case['id'] in derived: case['derived'] = derived[case['id']]
|
||||
rust_cases.append(case)
|
||||
rust_inputs = build / 'rust-cases.jsonl'
|
||||
rust_inputs.write_text(''.join(json.dumps(c) + '\n' for c in rust_cases))
|
||||
(build / 'rust-cases.jsonl.definitions').write_text((build / 'cases.jsonl.definitions').read_text())
|
||||
run([binary, resources, prototypes_path, rust_inputs, build / 'rust.jsonl'], 'rust')
|
||||
rust = [json.loads(line) for line in (build / 'rust.jsonl').read_text().splitlines()]
|
||||
mismatches, compared, skipped, decoded = [], 0, 0, 0
|
||||
vanilla_by_key = {(r['row'], r.get('id') or r.get('name')): r for r in client if r['row'] in ('case', 'decode', 'components')}
|
||||
rust_by_key = {(r['row'], r.get('id') or r.get('name')): r for r in rust}
|
||||
assert vanilla_by_key.keys() == rust_by_key.keys(), 'The two sides produced different rows'
|
||||
assert vanilla_by_key[('components', None)]['names'] == rust_by_key[('components', None)]['names'], 'Data component registry differs'
|
||||
unbaked = [r['name'] for r in client if r['row'] == 'unbaked']
|
||||
for key, left in vanilla_by_key.items():
|
||||
right = rust_by_key[key]
|
||||
if key[0] == 'components': continue
|
||||
if key[0] == 'decode':
|
||||
decoded += 1
|
||||
if left['ok'] != right['ok']: mismatches.append(('decode', key[1], left, right))
|
||||
continue
|
||||
if 'error' in left:
|
||||
skipped += 1
|
||||
continue
|
||||
compared += 1
|
||||
for side in (left, right):
|
||||
for layer in side['layers']:
|
||||
layer['matrix'] = matrix(layer['matrix'])
|
||||
layer.pop('has_transform', None)
|
||||
if layer.get('quads') is not None: layer['quads'] = canonical_quads(layer['quads'])
|
||||
if left != right:
|
||||
mismatches.append(('case', key[1], left, right))
|
||||
if mismatches:
|
||||
for kind, name, left, right in mismatches[:5]:
|
||||
print(kind, name, '\nvanilla:', json.dumps(left)[:1500], '\nrust: ', json.dumps(right)[:1500])
|
||||
raise AssertionError(f'{len(mismatches)} item model mismatches')
|
||||
base.ensure_sources_unchanged(sources, tested)
|
||||
assert compared > 1000, 'Too few cases compared'
|
||||
assert skipped * 20 < len(cases), f'Too many cases rejected by vanilla: {skipped}'
|
||||
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(),
|
||||
'cases': len(cases), 'compared': compared, 'rejected_by_vanilla': skipped, 'definitions_decoded': decoded,
|
||||
'definitions_unbaked': unbaked, 'sources_sha256': tested,
|
||||
'scope': 'Actual ClientItem codec, ModelDiscovery, ModelBakery item baking and ItemModelResolver semantics against real sprites in a unit atlas. Every bundled items/*.json and synthetic definitions; every item prototype in every display context with representative components. Layer content, tints, foil, composed transformation matrices (numeric equality), special-renderer codec forms and arguments, baked quads by float bits, render properties. Not covered: GPU rendering, atlas packing, level-dependent needles (see the needle tests), player/keybind/team-based properties that need a live client.'}
|
||||
lab.write_json(report_path, report)
|
||||
print(f'Item models: {compared:,} resolved stacks match ({skipped:,} rejected by vanilla, {decoded:,} definitions); {report_path}', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__': main()
|
||||
Reference in New Issue
Block a user