Merge section mesh parity work (agent/render-mesh)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -168,6 +168,22 @@ pub fn bake_model(model: &ResolvedCuboidModel) -> Result<Vec<ModelQuad>> {
|
||||
pub fn bake_model_transformed(
|
||||
model: &ResolvedCuboidModel,
|
||||
transform: BlockModelTransform,
|
||||
) -> Result<Vec<ModelQuad>> {
|
||||
bake_elements(model, transform, false)
|
||||
}
|
||||
/// Block-model baking as `UnbakedCuboidGeometry.bake` does it: an element with
|
||||
/// zero extent along an axis draws no faces across that extent (a flat X
|
||||
/// element keeps only its X faces, and so on).
|
||||
pub fn bake_block_model(
|
||||
model: &ResolvedCuboidModel,
|
||||
transform: BlockModelTransform,
|
||||
) -> Result<Vec<ModelQuad>> {
|
||||
bake_elements(model, transform, true)
|
||||
}
|
||||
fn bake_elements(
|
||||
model: &ResolvedCuboidModel,
|
||||
transform: BlockModelTransform,
|
||||
skip_flat: bool,
|
||||
) -> Result<Vec<ModelQuad>> {
|
||||
let mut output = Vec::new();
|
||||
for element in model.elements() {
|
||||
@@ -175,7 +191,16 @@ pub fn bake_model_transformed(
|
||||
.as_ref()
|
||||
.ok_or_else(|| error("null model element"))?;
|
||||
let matrix = element.rotation.as_ref().map(ElementMatrix::from_rotation);
|
||||
let flat = |axis: usize| skip_flat && element.from[axis] == element.to[axis];
|
||||
for (direction, face) in &element.faces {
|
||||
let drawn = match direction {
|
||||
Direction::West | Direction::East => !flat(1) && !flat(2),
|
||||
Direction::Down | Direction::Up => !flat(0) && !flat(2),
|
||||
Direction::North | Direction::South => !flat(0) && !flat(1),
|
||||
};
|
||||
if !drawn {
|
||||
continue;
|
||||
}
|
||||
let face = face.as_ref().ok_or_else(|| error("null model face"))?;
|
||||
let material = model.material(&face.texture)?.cloned().unwrap_or(Material {
|
||||
sprite: "minecraft:missingno".to_owned(),
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Headless transport for the section-mesh parity gate: builds the requested
|
||||
//! scenes in real client chunks and writes the vertices `Mesher::mesh` emits in
|
||||
//! the oracle's canonical form (vanilla ARGB colours and packed light coords).
|
||||
#![forbid(unsafe_code)]
|
||||
use horizon_client::{
|
||||
assets::Assets,
|
||||
biome::{Biomes, GrassModifier},
|
||||
blocks::BlockFacts,
|
||||
chunk::{Chunk, Light, MIN_Y, index},
|
||||
mesher::{MeshTables, Mesher, Vertex},
|
||||
models,
|
||||
};
|
||||
use horizon_world::registry::BlockStateId;
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
fs,
|
||||
io::{BufRead, BufReader, BufWriter, Write},
|
||||
path::PathBuf,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
|
||||
fn int(value: &Value) -> Result<i32> {
|
||||
Ok(i32::try_from(value.as_i64().ok_or("expected integer")?)?)
|
||||
}
|
||||
/// Horizon packs RGBA little endian (red in the low byte); vanilla uses ARGB.
|
||||
fn argb(color: u32) -> i32 {
|
||||
let [r, g, b, a] = color.to_le_bytes();
|
||||
i32::from_be_bytes([a, r, g, b])
|
||||
}
|
||||
/// Horizon keeps sky*16 in the low byte and block*16 above it; vanilla's light
|
||||
/// coords keep block in the low half-word and sky in the high one.
|
||||
fn light_coords(light: u32) -> i32 {
|
||||
((light & 0xFF) << 16 | (light >> 8 & 0xFF)) as i32
|
||||
}
|
||||
/// Scenes cover the 3x3 chunk region around chunk (0, 0).
|
||||
fn chunk_index(x: i32, z: i32) -> Result<usize> {
|
||||
let (cx, cz) = (x.div_euclid(16), z.div_euclid(16));
|
||||
if !(-1..=1).contains(&cx) || !(-1..=1).contains(&cz) {
|
||||
return Err("scene block outside the 3x3 chunk region".into());
|
||||
}
|
||||
Ok(((cz + 1) * 3 + cx + 1) as usize)
|
||||
}
|
||||
fn scene(
|
||||
row: &Value,
|
||||
assets: &Assets,
|
||||
tables: &MeshTables,
|
||||
biomes: &mut Biomes,
|
||||
names: &BTreeMap<u32, &str>,
|
||||
elapsed: &mut Duration,
|
||||
) -> Result<Value> {
|
||||
let colors = &row["colors"];
|
||||
let color = |k: &str| -> Result<u32> { Ok(int(&colors[k])? as u32 & 0xFF_FFFF) };
|
||||
for biome in &mut biomes.list {
|
||||
biome.grass = color("grass")?;
|
||||
biome.modifier = GrassModifier::None;
|
||||
biome.foliage = color("foliage")?;
|
||||
biome.dry_foliage = color("dry_foliage")?;
|
||||
biome.water = color("water")?;
|
||||
}
|
||||
let default = row["light"].as_array().ok_or("missing default light")?;
|
||||
let packed = |sky: i32, block: i32| (sky << 4 | block) as u8;
|
||||
let default = packed(int(&default[0])?, int(&default[1])?);
|
||||
let mut chunks: Vec<Chunk> = (0..9)
|
||||
.map(|i| {
|
||||
let mut chunk = Chunk::empty(i % 3 - 1, i / 3 - 1);
|
||||
for section in &mut chunk.sections {
|
||||
Arc::make_mut(section).light = Light::Uniform(default);
|
||||
}
|
||||
chunk
|
||||
})
|
||||
.collect();
|
||||
for block in row["blocks"].as_array().ok_or("missing blocks")? {
|
||||
let (x, y, z) = (int(&block[0])?, int(&block[1])?, int(&block[2])?);
|
||||
let i = chunk_index(x, z)?;
|
||||
chunks[i].set(x & 15, y, z & 15, u16::try_from(int(&block[3])?)?);
|
||||
}
|
||||
for cell in row["lights"].as_array().ok_or("missing lights")? {
|
||||
let (x, y, z) = (int(&cell[0])?, int(&cell[1])?, int(&cell[2])?);
|
||||
let i = chunk_index(x, z)?;
|
||||
let s = ((y - MIN_Y) >> 4) as usize;
|
||||
let section = Arc::make_mut(&mut chunks[i].sections[s]);
|
||||
if let Light::Uniform(v) = section.light {
|
||||
section.light = Light::Full(Box::new([v; 4096]));
|
||||
}
|
||||
if let Light::Full(values) = &mut section.light {
|
||||
values[index(x, y, z)] = packed(int(&cell[3])?, int(&cell[4])?);
|
||||
}
|
||||
}
|
||||
let region: [[Option<&Chunk>; 3]; 3] =
|
||||
std::array::from_fn(|z| std::array::from_fn(|x| Some(&chunks[z * 3 + x])));
|
||||
let mut mesher = Mesher {
|
||||
nether_shading: row["nether"].as_bool().unwrap_or(false),
|
||||
assets,
|
||||
tables,
|
||||
biomes: &*biomes,
|
||||
visibility: tables.visibility.clone(),
|
||||
};
|
||||
let section_y = int(&row["section_y"])?;
|
||||
let started = Instant::now();
|
||||
let mesh = mesher.mesh(®ion, (section_y * 16 - MIN_Y) / 16);
|
||||
*elapsed += started.elapsed();
|
||||
let mut quads = Vec::new();
|
||||
for (layer, vertices) in [("opaque", &mesh.solid), ("translucent", &mesh.translucent)] {
|
||||
let (vertices, rest) = vertices.as_chunks::<4>();
|
||||
if !rest.is_empty() {
|
||||
return Err("partial quad".into());
|
||||
}
|
||||
for quad in vertices {
|
||||
let sprite = names.get(&quad[0].layer).ok_or("unknown sprite layer")?;
|
||||
if quad.iter().any(|v: &Vertex| v.layer != quad[0].layer) {
|
||||
return Err("quad mixes sprite layers".into());
|
||||
}
|
||||
let vertices: Vec<Value> = quad
|
||||
.iter()
|
||||
.map(|v| {
|
||||
json!([
|
||||
v.pos[0],
|
||||
v.pos[1],
|
||||
v.pos[2],
|
||||
v.uv[0],
|
||||
v.uv[1],
|
||||
argb(v.color),
|
||||
light_coords(v.light)
|
||||
])
|
||||
})
|
||||
.collect();
|
||||
quads.push(json!({"layer": layer, "sprite": sprite, "vertices": vertices}));
|
||||
}
|
||||
}
|
||||
Ok(json!({"name": row["name"], "quads": quads}))
|
||||
}
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<_> = std::env::args().skip(1).collect();
|
||||
if args.len() != 3 {
|
||||
return Err(
|
||||
"usage: section_mesh_fixture RESOURCES (INPUT.jsonl | facts) OUTPUT.jsonl".into(),
|
||||
);
|
||||
}
|
||||
let root = PathBuf::from(&args[0]);
|
||||
let assets = Assets::load(&root)?;
|
||||
let facts = BlockFacts::load(&root, assets.registry)?;
|
||||
let mut biomes = Biomes::load(&root)?;
|
||||
let visibility = models::load_visibility(&root, assets.registry)?;
|
||||
let tables = MeshTables::new(&assets, &facts, visibility)?;
|
||||
let names: BTreeMap<u32, &str> = assets
|
||||
.sprite_layers
|
||||
.iter()
|
||||
.map(|(name, layer)| (*layer, name.as_str()))
|
||||
.collect();
|
||||
let mut output = BufWriter::new(fs::File::create(&args[2])?);
|
||||
if args[1] == "facts" {
|
||||
// The per-state facts the mesher derives, in the oracle's order and positions.
|
||||
let positions = [(0, 0), (5, -3), (-17, 31), (123, -456), (9, 2)];
|
||||
for id in 0..assets.registry.len() as u32 {
|
||||
let state = BlockStateId(id);
|
||||
let f = tables.facts(state).ok_or("missing mesh facts")?;
|
||||
let offsets: Vec<_> = positions
|
||||
.iter()
|
||||
.filter_map(|&(x, z)| tables.offset(state, x, z))
|
||||
.collect();
|
||||
let row = json!({"id": id, "shade": f.shade, "emissive": f.emissive,
|
||||
"legacy_solid": f.legacy_solid, "light_permeable": f.light_permeable,
|
||||
"solid_render": f.solid_render, "full_collision": f.full_collision,
|
||||
"emission": f.emission, "overlay": f.overlay, "tint_sources": f.tint_sources,
|
||||
"offsets": offsets});
|
||||
serde_json::to_writer(&mut output, &row)?;
|
||||
output.write_all(b"\n")?;
|
||||
}
|
||||
output.flush()?;
|
||||
return Ok(());
|
||||
}
|
||||
let (mut elapsed, mut sections) = (Duration::ZERO, 0u32);
|
||||
for line in BufReader::new(fs::File::open(&args[1])?).lines() {
|
||||
let row: Value = serde_json::from_str(&line?)?;
|
||||
let result = scene(&row, &assets, &tables, &mut biomes, &names, &mut elapsed)?;
|
||||
serde_json::to_writer(&mut output, &result)?;
|
||||
output.write_all(b"\n")?;
|
||||
sections += 1;
|
||||
}
|
||||
output.flush()?;
|
||||
eprintln!(
|
||||
"meshed {sections} sections in {:.1} ms ({:.0} us per section)",
|
||||
elapsed.as_secs_f64() * 1e3,
|
||||
elapsed.as_secs_f64() * 1e6 / f64::from(sections.max(1))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
@@ -63,6 +63,8 @@ pub struct Assets {
|
||||
pub animations: Vec<crate::sprites::SpriteAnimation>,
|
||||
pub sprite_layers: std::collections::BTreeMap<String, u32>,
|
||||
pub translucent_layers: Vec<bool>,
|
||||
/// Block names in `#minecraft:blocks_fluid_flow` (fluid flow vectors).
|
||||
pub blocks_fluid_flow: BTreeSet<String>,
|
||||
}
|
||||
fn invalid(message: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, message)
|
||||
@@ -144,6 +146,13 @@ impl Assets {
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
let blocks_fluid_flow = built
|
||||
.tags
|
||||
.get("minecraft:blocks_fluid_flow")
|
||||
.ok_or_else(|| invalid("missing fluid flow tag"))?
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect();
|
||||
let properties = Properties(Arc::new(
|
||||
states
|
||||
.iter()
|
||||
@@ -202,6 +211,7 @@ impl Assets {
|
||||
animations: sprites.animations,
|
||||
sprite_layers: sprites.layers,
|
||||
translucent_layers: sprites.translucent,
|
||||
blocks_fluid_flow,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +52,19 @@ pub struct StateFacts {
|
||||
pub fluid_level: u8,
|
||||
pub fluid_falling: bool,
|
||||
pub waterlogged: bool,
|
||||
/// `hasOffsetFunction`: the model is jittered per column.
|
||||
pub random_offset: bool,
|
||||
/// `BlockState.isSolid()` (legacy solidity; fluid surfaces read it).
|
||||
pub legacy_solid: bool,
|
||||
/// `isFaceSturdy(.., SupportType.FULL)` by Direction ordinal.
|
||||
pub sturdy_full: u8,
|
||||
/// The block's class chain (`TransparentBlock`, `LeavesBlock`, ...), most specific first.
|
||||
pub classes: Arc<[Arc<str>]>,
|
||||
}
|
||||
impl StateFacts {
|
||||
pub fn has_class(&self, name: &str) -> bool {
|
||||
self.classes.iter().any(|c| &**c == name)
|
||||
}
|
||||
}
|
||||
pub struct BlockFacts {
|
||||
pub states: Vec<StateFacts>,
|
||||
@@ -67,6 +80,33 @@ impl BlockFacts {
|
||||
if entries.len() != registry.len() {
|
||||
return Err("gameplay facts do not match the block registry".into());
|
||||
}
|
||||
// Class chains and per-state behaviour flags exported from the actual block objects.
|
||||
let behaviours: Value = serde_json::from_reader(BufReader::new(File::open(
|
||||
root.join("block-behaviours.json"),
|
||||
)?))?;
|
||||
let behaviour_states = behaviours["states"]
|
||||
.as_array()
|
||||
.filter(|s| s.len() == registry.len())
|
||||
.ok_or("block behaviour facts do not match the block registry")?;
|
||||
let mut class_names: HashMap<String, Arc<str>> = HashMap::new();
|
||||
let classes: HashMap<&str, Arc<[Arc<str>]>> = behaviours["blocks"]
|
||||
.as_array()
|
||||
.ok_or("missing block behaviour classes")?
|
||||
.iter()
|
||||
.filter_map(|b| {
|
||||
let chain = b["class"]
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(|c| {
|
||||
class_names
|
||||
.entry(c.to_owned())
|
||||
.or_insert_with(|| Arc::from(c))
|
||||
.clone()
|
||||
});
|
||||
Some((b["name"].as_str()?, chain.collect()))
|
||||
})
|
||||
.collect();
|
||||
let mut names: HashMap<String, Arc<str>> = HashMap::new();
|
||||
let mut intern = |s: &str| -> Arc<str> {
|
||||
names
|
||||
@@ -143,6 +183,13 @@ impl BlockFacts {
|
||||
fluid_level,
|
||||
fluid_falling,
|
||||
waterlogged: prop("waterlogged") == Some("true"),
|
||||
random_offset: flag("offset"),
|
||||
legacy_solid: behaviour_states[index][1].as_u64().unwrap_or(0) & 1 != 0,
|
||||
sturdy_full: (behaviour_states[index][0].as_u64().unwrap_or(0) & 63) as u8,
|
||||
classes: classes
|
||||
.get(state.name.as_str())
|
||||
.cloned()
|
||||
.ok_or("missing block behaviour class chain")?,
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
|
||||
+259
-396
@@ -1,17 +1,23 @@
|
||||
//! Section meshing on worker threads. Faces follow the baked blockstate models
|
||||
//! with vanilla's neighbour culling; vertex lighting follows
|
||||
//! `ModelBlockRenderer`'s smooth-lighting blend (four samples per corner, zero
|
||||
//! samples replaced by the centre) and ambient-occlusion shade brightness.
|
||||
//! Fluids follow `FluidRenderer` (corner heights, still/flowing sprites).
|
||||
//! with vanilla's neighbour culling; vertex light and colour follow
|
||||
//! `ModelBlockRenderer`/`BlockModelLighter` (smooth light, ambient occlusion,
|
||||
//! cardinal shading, tint sources, block offsets; see `lighting`). Fluids
|
||||
//! follow `FluidRenderer` (see `fluid`).
|
||||
mod fluid;
|
||||
mod lighting;
|
||||
use crate::{
|
||||
assets::Assets,
|
||||
biome::Biomes,
|
||||
blocks::{BlockFacts, Fluid, RenderShape},
|
||||
blocks::{BlockFacts, RenderShape},
|
||||
chunk::{Chunk, MIN_Y},
|
||||
models::catalog::BakedFace,
|
||||
};
|
||||
use horizon_core::{geometry::Direction, position::BlockPos};
|
||||
use horizon_world::{block_render::FaceVisibility, registry::BlockStateId};
|
||||
use horizon_core::{geometry::Direction, position::BlockPos, random::position_seed};
|
||||
use horizon_world::{
|
||||
block_render::FaceVisibility,
|
||||
fluid::{FluidKind, FluidState},
|
||||
registry::BlockStateId,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[repr(C)]
|
||||
@@ -104,24 +110,57 @@ enum Tint {
|
||||
/// Per-state data the mesher needs on every block, flattened for speed.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Info {
|
||||
/// `isSolidRender`.
|
||||
solid: bool,
|
||||
/// `isCollisionShapeFullBlock` drives the 0.2 AO shade brightness.
|
||||
/// `isCollisionShapeFullBlock`: AO faces flush with a full block sample outside it.
|
||||
full: bool,
|
||||
/// Side blocks that are transparent let the AO corner sample through.
|
||||
translucent: bool,
|
||||
/// `isLightPermeable`: diagonal AO samples are taken through such side blocks.
|
||||
permeable: bool,
|
||||
/// `getShadeBrightness` (ambient occlusion contribution).
|
||||
shade: f32,
|
||||
emission: u8,
|
||||
fluid: Fluid,
|
||||
level: u8,
|
||||
/// `emissiveRendering`: drawn and sampled at full brightness.
|
||||
emissive: bool,
|
||||
fluid: FluidState,
|
||||
model: bool,
|
||||
/// The state has a block entity (candidates for block-entity renderers).
|
||||
block_entity: bool,
|
||||
tints: [Tint; 2],
|
||||
tint_count: u8,
|
||||
/// `OffsetType` as (max horizontal, max vertical): vertical 0 for XZ.
|
||||
offset: Option<(f32, f32)>,
|
||||
/// `isSolid()` (legacy), for fluid corner heights.
|
||||
legacy_solid: bool,
|
||||
/// `HalfTransparentBlock`/`LeavesBlock`: water sides show the overlay sprite.
|
||||
overlay: bool,
|
||||
blocks_flow: bool,
|
||||
ice: bool,
|
||||
sturdy: u8,
|
||||
/// Occlusion face per direction: 0 empty, 1 the full-block singleton, 2 partial.
|
||||
face: [u8; 6],
|
||||
/// Height from the bottom over which face `d`, flush with the `d` side, covers
|
||||
/// the full width (vertical faces: 1 when the whole square is covered).
|
||||
cover: [f32; 6],
|
||||
}
|
||||
/// Derived per-state facts, exposed for the section-mesh parity gate.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct MeshFacts {
|
||||
pub shade: f32,
|
||||
pub emissive: bool,
|
||||
pub legacy_solid: bool,
|
||||
pub light_permeable: bool,
|
||||
pub solid_render: bool,
|
||||
pub full_collision: bool,
|
||||
pub emission: u8,
|
||||
pub overlay: bool,
|
||||
pub tint_sources: u8,
|
||||
}
|
||||
pub struct MeshTables {
|
||||
info: Vec<Info>,
|
||||
pub visibility: FaceVisibility,
|
||||
water_still: u32,
|
||||
water_flow: u32,
|
||||
water_overlay: u32,
|
||||
lava_still: u32,
|
||||
lava_flow: u32,
|
||||
}
|
||||
@@ -146,76 +185,162 @@ impl MeshTables {
|
||||
.copied()
|
||||
.ok_or_else(|| format!("missing fluid sprite {name}").into())
|
||||
};
|
||||
let info = facts
|
||||
.states
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(id, s)| {
|
||||
let props = assets
|
||||
.registry
|
||||
.state(BlockStateId(id as u32))
|
||||
.map(|s| &s.properties);
|
||||
let prop = |k: &str| -> u8 {
|
||||
props
|
||||
.and_then(|p| p.get(k))
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(0)
|
||||
};
|
||||
let name = s.name.strip_prefix("minecraft:").unwrap_or(&s.name);
|
||||
let tints = match name {
|
||||
"large_fern" | "tall_grass" => {
|
||||
if props.and_then(|p| p.get("half")).map(String::as_str) == Some("upper") {
|
||||
[Tint::TallGrassUpper; 2]
|
||||
} else {
|
||||
[Tint::Grass; 2]
|
||||
}
|
||||
let mut covers = std::collections::HashMap::new();
|
||||
let mut info = Vec::with_capacity(facts.states.len());
|
||||
for (id, s) in facts.states.iter().enumerate() {
|
||||
let state = assets
|
||||
.registry
|
||||
.state(BlockStateId(id as u32))
|
||||
.ok_or("missing registry state")?;
|
||||
let props = &state.properties;
|
||||
let prop = |k: &str| -> u8 { props.get(k).and_then(|v| v.parse().ok()).unwrap_or(0) };
|
||||
let name = s.name.strip_prefix("minecraft:").unwrap_or(&s.name);
|
||||
// BlockColors.createDefault: tint sources by block.
|
||||
let (tints, tint_count) = match name {
|
||||
"large_fern" | "tall_grass" => {
|
||||
if props.get("half").map(String::as_str) == Some("upper") {
|
||||
([Tint::TallGrassUpper; 2], 1)
|
||||
} else {
|
||||
([Tint::Grass; 2], 1)
|
||||
}
|
||||
"fern" | "short_grass" | "potted_fern" | "bush" | "grass_block"
|
||||
| "sugar_cane" => [Tint::Grass; 2],
|
||||
"pink_petals" | "wildflowers" => [Tint::None, Tint::Grass],
|
||||
"spruce_leaves" => [Tint::Constant(0x61_9961); 2],
|
||||
"birch_leaves" => [Tint::Constant(0x80_A755); 2],
|
||||
"oak_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves"
|
||||
| "vine" | "mangrove_leaves" => [Tint::Foliage; 2],
|
||||
"leaf_litter" => [Tint::DryFoliage; 2],
|
||||
"water_cauldron" | "water" | "bubble_column" => [Tint::Water; 2],
|
||||
"redstone_wire" => [Tint::Redstone(prop("power")); 2],
|
||||
"attached_melon_stem" | "attached_pumpkin_stem" => {
|
||||
[Tint::Constant(0xE0_C71C); 2]
|
||||
}
|
||||
"melon_stem" | "pumpkin_stem" => [Tint::Stem(prop("age")); 2],
|
||||
"lily_pad" => [Tint::Constant(0x20_8030); 2],
|
||||
_ => [Tint::None; 2],
|
||||
};
|
||||
Info {
|
||||
solid: s.solid_render,
|
||||
full: s.full_collision,
|
||||
translucent: !s.solid_render || s.dampening == 0,
|
||||
emission: s.emission,
|
||||
fluid: s.fluid,
|
||||
level: s.fluid_level,
|
||||
model: s.render_shape == RenderShape::Model,
|
||||
block_entity: s.block_entity,
|
||||
tints,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
"fern" | "short_grass" | "potted_fern" | "bush" | "grass_block" | "sugar_cane" => {
|
||||
([Tint::Grass; 2], 1)
|
||||
}
|
||||
"pink_petals" | "wildflowers" => ([Tint::None, Tint::Grass], 2),
|
||||
"spruce_leaves" => ([Tint::Constant(0x61_9961); 2], 1),
|
||||
"birch_leaves" => ([Tint::Constant(0x80_A755); 2], 1),
|
||||
"oak_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves" | "vine"
|
||||
| "mangrove_leaves" => ([Tint::Foliage; 2], 1),
|
||||
"leaf_litter" => ([Tint::DryFoliage; 2], 1),
|
||||
"water_cauldron" => ([Tint::Water; 2], 1),
|
||||
// Their in-world colour is the particle-only source's -1.
|
||||
"water" | "bubble_column" => ([Tint::None; 2], 1),
|
||||
"redstone_wire" => ([Tint::Redstone(prop("power")); 2], 1),
|
||||
"attached_melon_stem" | "attached_pumpkin_stem" => {
|
||||
([Tint::Constant(0xE0_C71C); 2], 1)
|
||||
}
|
||||
"melon_stem" | "pumpkin_stem" => ([Tint::Stem(prop("age")); 2], 1),
|
||||
"lily_pad" => ([Tint::Constant(0x20_8030); 2], 1),
|
||||
_ => ([Tint::None; 2], 0),
|
||||
};
|
||||
// getShadeBrightness overrides; the default is 0.2 for full collision shapes.
|
||||
let overrides = [
|
||||
"TransparentBlock",
|
||||
"BarrierBlock",
|
||||
"LightBlock",
|
||||
"StructureVoidBlock",
|
||||
];
|
||||
let shade = if overrides.iter().any(|c| s.has_class(c)) {
|
||||
1.0
|
||||
} else if s.has_class("SoulSandBlock") || s.has_class("MudBlock") {
|
||||
0.2
|
||||
} else if s.has_class("SnowLayerBlock") {
|
||||
if prop("layers") == 8 { 0.2 } else { 1.0 }
|
||||
} else if s.full_collision {
|
||||
0.2
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let emissive = name == "magma_block"
|
||||
|| (matches!(name, "sculk_sensor" | "calibrated_sculk_sensor")
|
||||
&& props.get("sculk_sensor_phase").map(String::as_str) == Some("active"));
|
||||
// OffsetType.XZ/XYZ with getMaxHorizontalOffset/getMaxVerticalOffset.
|
||||
let offset = s.random_offset.then(|| {
|
||||
let horizontal = if s.has_class("SpeleothemBlock") {
|
||||
0.125
|
||||
} else {
|
||||
0.25
|
||||
};
|
||||
let vertical = match name {
|
||||
"small_dripleaf" => 0.1,
|
||||
"short_grass" | "fern" | "short_dry_grass" | "tall_dry_grass" => 0.2,
|
||||
_ => 0.0,
|
||||
};
|
||||
(horizontal, vertical)
|
||||
});
|
||||
let mut face = [0u8; 6];
|
||||
let mut cover = [0f32; 6];
|
||||
for d in Direction::ALL {
|
||||
let (face_id, shape) = visibility
|
||||
.occlusion_face(BlockStateId(id as u32), d)
|
||||
.ok_or("missing occlusion face")?;
|
||||
face[d as usize] = face_id.min(2) as u8;
|
||||
cover[d as usize] = *covers
|
||||
.entry((face_id, d as u8))
|
||||
.or_insert_with(|| fluid::coverage(shape, d));
|
||||
}
|
||||
info.push(Info {
|
||||
solid: s.solid_render,
|
||||
full: s.full_collision,
|
||||
permeable: !s.solid_render || s.dampening == 0,
|
||||
shade,
|
||||
emission: s.emission,
|
||||
emissive,
|
||||
fluid: FluidState::from_block(state)?,
|
||||
model: s.render_shape == RenderShape::Model,
|
||||
block_entity: s.block_entity,
|
||||
tints,
|
||||
tint_count,
|
||||
offset,
|
||||
legacy_solid: s.legacy_solid,
|
||||
overlay: s.has_class("HalfTransparentBlock") || s.has_class("LeavesBlock"),
|
||||
blocks_flow: assets.blocks_fluid_flow.contains(&*s.name),
|
||||
ice: s.has_class("IceBlock"),
|
||||
sturdy: s.sturdy_full,
|
||||
face,
|
||||
cover,
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
info,
|
||||
visibility,
|
||||
water_still: layer("minecraft:block/water_still")?,
|
||||
water_flow: layer("minecraft:block/water_flow")?,
|
||||
water_overlay: layer("minecraft:block/water_overlay")?,
|
||||
lava_still: layer("minecraft:block/lava_still")?,
|
||||
lava_flow: layer("minecraft:block/lava_flow")?,
|
||||
})
|
||||
}
|
||||
pub fn facts(&self, state: BlockStateId) -> Option<MeshFacts> {
|
||||
let i = self.info.get(state.0 as usize)?;
|
||||
Some(MeshFacts {
|
||||
shade: i.shade,
|
||||
emissive: i.emissive,
|
||||
legacy_solid: i.legacy_solid,
|
||||
light_permeable: i.permeable,
|
||||
solid_render: i.solid,
|
||||
full_collision: i.full,
|
||||
emission: i.emission,
|
||||
overlay: i.overlay,
|
||||
tint_sources: i.tint_count,
|
||||
})
|
||||
}
|
||||
/// `BlockState.getOffset` for blocks with a random model offset.
|
||||
pub fn offset(&self, state: BlockStateId, x: i32, z: i32) -> Option<[f64; 3]> {
|
||||
offset(self.info.get(state.0 as usize)?, x, z)
|
||||
}
|
||||
}
|
||||
const P: usize = 18;
|
||||
/// `OffsetType.XZ`/`XYZ`: a per-column jitter from `Mth.getSeed(x, 0, z)`.
|
||||
fn offset(info: &Info, x: i32, z: i32) -> Option<[f64; 3]> {
|
||||
let (horizontal, vertical) = info.offset?;
|
||||
let seed = position_seed(BlockPos::new(x, 0, z));
|
||||
let nibble = |shift: u32| ((seed >> shift) & 15) as f32 / 15.0;
|
||||
let h = f64::from(horizontal);
|
||||
Some([
|
||||
((f64::from(nibble(0)) - 0.5) * 0.5).clamp(-h, h),
|
||||
(f64::from(nibble(4)) - 1.0) * f64::from(vertical),
|
||||
((f64::from(nibble(8)) - 0.5) * 0.5).clamp(-h, h),
|
||||
])
|
||||
}
|
||||
/// Border width: smooth lighting samples up to two blocks out along a face normal.
|
||||
const B: i32 = 2;
|
||||
const P: usize = 16 + 2 * B as usize;
|
||||
#[inline]
|
||||
fn pi(x: i32, y: i32, z: i32) -> usize {
|
||||
((y + 1) as usize * P + (z + 1) as usize) * P + (x + 1) as usize
|
||||
((y + B) as usize * P + (z + B) as usize) * P + (x + B) as usize
|
||||
}
|
||||
/// Blocks and light of one section plus a one-block border.
|
||||
/// Blocks and light of one section plus a `B`-block border.
|
||||
struct Padded {
|
||||
blocks: Vec<u16>,
|
||||
light: Vec<u8>,
|
||||
@@ -225,10 +350,10 @@ impl Padded {
|
||||
let mut blocks = vec![0u16; P * P * P];
|
||||
let mut light = vec![0u8; P * P * P];
|
||||
let base_y = MIN_Y + sy * 16;
|
||||
for y in -1..17 {
|
||||
for y in -B..16 + B {
|
||||
let wy = base_y + y;
|
||||
for z in -1..17i32 {
|
||||
for x in -1..17i32 {
|
||||
for z in -B..16 + B {
|
||||
for x in -B..16 + B {
|
||||
let chunk = region[((z + 16) >> 4) as usize][((x + 16) >> 4) as usize];
|
||||
let i = pi(x, y, z);
|
||||
if let Some(c) = chunk {
|
||||
@@ -276,7 +401,7 @@ fn blend(region: &[[Option<&Chunk>; 3]; 3], biomes: &Biomes, cx: i32, cz: i32, y
|
||||
}
|
||||
}
|
||||
let n = ((2 * R + 1) * (2 * R + 1)) as u32;
|
||||
(r / n) << 16 | (g / n) << 8 | b / n
|
||||
(r / n) << 16 | (g / n) << 8 | (b / n)
|
||||
};
|
||||
for z in 0..16 {
|
||||
for x in 0..16 {
|
||||
@@ -295,23 +420,14 @@ fn blend(region: &[[Option<&Chunk>; 3]; 3], biomes: &Biomes, cx: i32, cz: i32, y
|
||||
}
|
||||
colors
|
||||
}
|
||||
fn shade(direction: horizon_assets::model::Direction) -> f32 {
|
||||
use horizon_assets::model::Direction as D;
|
||||
match direction {
|
||||
D::Down => 0.5,
|
||||
D::Up => 1.0,
|
||||
D::North | D::South => 0.8,
|
||||
D::West | D::East => 0.6,
|
||||
}
|
||||
}
|
||||
fn pack_color(rgb: u32, brightness: f32) -> u32 {
|
||||
let r = ((rgb >> 16 & 255) as f32 * brightness) as u32;
|
||||
let g = ((rgb >> 8 & 255) as f32 * brightness) as u32;
|
||||
let b = ((rgb & 255) as f32 * brightness) as u32;
|
||||
/// Packs 8-bit RGB into the vertex's RGBA8 (red in the low byte), opaque.
|
||||
fn pack_rgb([r, g, b]: [u32; 3]) -> u32 {
|
||||
0xFF00_0000 | b << 16 | g << 8 | r
|
||||
}
|
||||
fn pack_light(sky: f32, block: f32) -> u32 {
|
||||
(sky * 16.0).clamp(0.0, 255.0) as u32 | ((block * 16.0).clamp(0.0, 255.0) as u32) << 8
|
||||
/// Vanilla light coords (block*16 in the low half, sky*16 in the high half) to
|
||||
/// the vertex layout (sky*16 in bits 0..8, block*16 in bits 8..16).
|
||||
fn pack_coords(coords: u32) -> u32 {
|
||||
(coords >> 16 & 0xFF) | (coords & 0xFF) << 8
|
||||
}
|
||||
pub struct Mesher<'a> {
|
||||
/// CardinalLighting.NETHER: brighter up/down faces.
|
||||
@@ -342,7 +458,7 @@ impl Mesher<'_> {
|
||||
if id == 0 {
|
||||
continue;
|
||||
}
|
||||
let state = info[id as usize];
|
||||
let state = &info[id as usize];
|
||||
if state.block_entity {
|
||||
out.block_entities.push(([center.x * 16 + x, base_y + y, center.z * 16 + z], u32::from(id)));
|
||||
}
|
||||
@@ -354,8 +470,10 @@ impl Mesher<'_> {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if state.fluid != Fluid::None {
|
||||
self.fluid(&pad, &colors, &mut out, x, y, z, id);
|
||||
if state.fluid.kind() != FluidKind::Empty {
|
||||
let water = colors.water[(z * 16 + x) as usize];
|
||||
let nether = self.nether_shading;
|
||||
fluid::tesselate(self.tables, nether, &pad, water, &mut out, [x, y, z]);
|
||||
}
|
||||
if !state.model {
|
||||
continue;
|
||||
@@ -365,6 +483,20 @@ impl Mesher<'_> {
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// ModelBlockRenderer: the first part decides smooth lighting
|
||||
// for all; light-emitting blocks are always lit flat.
|
||||
let Some((_, first)) = models.first() else {
|
||||
continue;
|
||||
};
|
||||
let ao = state.emission == 0 && first.ambient_occlusion;
|
||||
let origin = match offset(state, world.x, world.z) {
|
||||
Some(o) => [
|
||||
x as f32 + o[0] as f32,
|
||||
y as f32 + o[1] as f32,
|
||||
z as f32 + o[2] as f32,
|
||||
],
|
||||
None => [x as f32, y as f32, z as f32],
|
||||
};
|
||||
let mut visible = [false; 6];
|
||||
for d in Direction::ALL {
|
||||
let [dx, dy, dz] = d.normal();
|
||||
@@ -379,20 +511,12 @@ impl Mesher<'_> {
|
||||
)
|
||||
.unwrap_or(true);
|
||||
}
|
||||
for (_, model) in models {
|
||||
for (_, model) in &models {
|
||||
for face in &model.faces {
|
||||
if face.quad.cull.is_some_and(|d| !visible[d as usize]) {
|
||||
continue;
|
||||
}
|
||||
self.face(
|
||||
&pad,
|
||||
&colors,
|
||||
&mut out,
|
||||
[x, y, z],
|
||||
face,
|
||||
model.ambient_occlusion,
|
||||
state,
|
||||
);
|
||||
self.face(&pad, &colors, &mut out, [x, y, z], origin, face, ao, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -400,13 +524,14 @@ impl Mesher<'_> {
|
||||
}
|
||||
out
|
||||
}
|
||||
fn tint(state: Info, index: i32, colors: &Colors, x: i32, z: i32) -> u32 {
|
||||
if index < 0 {
|
||||
return 0xFF_FFFF;
|
||||
/// `BlockColors` tint source `index`, or `None` for an untinted (-1) layer.
|
||||
fn tint(state: &Info, index: i32, colors: &Colors, x: i32, z: i32) -> Option<u32> {
|
||||
if index < 0 || index >= i32::from(state.tint_count) {
|
||||
return None;
|
||||
}
|
||||
let column = (z * 16 + x) as usize;
|
||||
match state.tints[(index as usize).min(1)] {
|
||||
Tint::None => 0xFF_FFFF,
|
||||
Some(match state.tints[(index as usize).min(1)] {
|
||||
Tint::None => return None,
|
||||
Tint::Grass => colors.grass[column],
|
||||
Tint::TallGrassUpper => colors.tall_upper[column],
|
||||
Tint::Foliage => colors.foliage[column],
|
||||
@@ -416,9 +541,9 @@ impl Mesher<'_> {
|
||||
Tint::Redstone(p) => redstone_color(p),
|
||||
Tint::Stem(age) => {
|
||||
let a = u32::from(age);
|
||||
(a * 32) << 16 | (255 - a * 8) << 8 | a * 4
|
||||
(a * 32) << 16 | (255 - a * 8) << 8 | (a * 4)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn face(
|
||||
@@ -426,313 +551,51 @@ impl Mesher<'_> {
|
||||
pad: &Padded,
|
||||
colors: &Colors,
|
||||
out: &mut SectionMesh,
|
||||
[x, y, z]: [i32; 3],
|
||||
pos: [i32; 3],
|
||||
origin: [f32; 3],
|
||||
face: &BakedFace,
|
||||
ao: bool,
|
||||
state: Info,
|
||||
state: &Info,
|
||||
) {
|
||||
let q = &face.quad;
|
||||
let facing = q.facing;
|
||||
let normal = Direction::ALL[facing as usize].normal();
|
||||
let axis = normal.iter().position(|&n| n != 0).unwrap_or(1);
|
||||
let positive = normal[axis] > 0;
|
||||
let on_boundary = q.positions.iter().all(|p| {
|
||||
if positive {
|
||||
p[axis] >= 1.0 - 1e-4
|
||||
} else {
|
||||
p[axis] <= 1e-4
|
||||
}
|
||||
});
|
||||
let base = if on_boundary {
|
||||
[x + normal[0], y + normal[1], z + normal[2]]
|
||||
let shade_face = q.shade_direction_override.unwrap_or(q.facing);
|
||||
let directional = lighting::cardinal(self.nether_shading, shade_face);
|
||||
// Grey level per vertex before tinting, and vanilla light coords.
|
||||
let (gray, coords) = if ao {
|
||||
let info = &self.tables.info;
|
||||
let (brightness, coords) =
|
||||
lighting::ambient_occlusion(pad, info, state, pos, &q.positions, q.facing);
|
||||
let gray = brightness.map(|b| lighting::scale(lighting::gray(b), directional));
|
||||
(gray, coords)
|
||||
} else {
|
||||
[x, y, z]
|
||||
};
|
||||
let tint = Self::tint(state, q.tint_index, colors, x, z);
|
||||
let mut directional = match q.shade_direction_override {
|
||||
Some(d) => shade(d),
|
||||
None => shade(facing),
|
||||
};
|
||||
if self.nether_shading && matches!(q.shade_direction_override.unwrap_or(facing), horizon_assets::model::Direction::Up | horizon_assets::model::Direction::Down) {
|
||||
directional = 0.9;
|
||||
}
|
||||
let info = &self.tables.info;
|
||||
let light_at = |p: [i32; 3]| -> u32 {
|
||||
let i = pi(p[0], p[1], p[2]);
|
||||
let packed = pad.light[i];
|
||||
let s = info[pad.blocks[i] as usize];
|
||||
let block = (packed & 15).max(s.emission);
|
||||
u32::from(packed >> 4) << 16 | u32::from(block)
|
||||
};
|
||||
let shade_at = |p: [i32; 3]| -> f32 {
|
||||
if info[pad.blocks[pi(p[0], p[1], p[2])] as usize].full {
|
||||
0.2
|
||||
} else {
|
||||
1.0
|
||||
}
|
||||
};
|
||||
let open_at = |p: [i32; 3]| -> bool { info[pad.blocks[pi(p[0], p[1], p[2])] as usize].translucent };
|
||||
// Tangent axes of the face plane.
|
||||
let (ua, va) = match axis {
|
||||
0 => (2, 1),
|
||||
1 => (0, 2),
|
||||
_ => (0, 1),
|
||||
};
|
||||
let center_light = light_at(base);
|
||||
let center_shade = shade_at(base);
|
||||
// Corner values for (su, sv) in {0,1}^2 -> (sky, block, ao).
|
||||
let mut corners = [[0f32; 3]; 4];
|
||||
for (ci, corner) in corners.iter_mut().enumerate() {
|
||||
let su = if ci & 1 == 0 { -1 } else { 1 };
|
||||
let sv = if ci & 2 == 0 { -1 } else { 1 };
|
||||
let mut p1 = base;
|
||||
p1[ua] += su;
|
||||
let mut p2 = base;
|
||||
p2[va] += sv;
|
||||
let mut pc = base;
|
||||
pc[ua] += su;
|
||||
pc[va] += sv;
|
||||
let (l1, l2) = (light_at(p1), light_at(p2));
|
||||
let (lc, ac) = if open_at(p1) || open_at(p2) {
|
||||
(light_at(pc), shade_at(pc))
|
||||
} else {
|
||||
(l1, shade_at(p1))
|
||||
let coords = match q.cull {
|
||||
Some(d) => lighting::coords(pad, state, lighting::step(pos, d)),
|
||||
None => lighting::flat(pad, state, pos, &q.positions, q.facing),
|
||||
};
|
||||
// ModelBlockRenderer.blend: zero samples take the centre value.
|
||||
let fix = |v: u32| if v == 0 { center_light } else { v };
|
||||
let sum = fix(l1) + fix(l2) + fix(lc) + center_light;
|
||||
corner[0] = (sum >> 16) as f32 / 4.0;
|
||||
corner[1] = (sum & 0xFFFF) as f32 / 4.0;
|
||||
corner[2] = (shade_at(p1) + shade_at(p2) + ac + center_shade) / 4.0;
|
||||
}
|
||||
let flat_sky = (center_light >> 16) as f32;
|
||||
let flat_block = (center_light & 0xFFFF) as f32;
|
||||
([lighting::gray(directional); 4], [coords; 4])
|
||||
};
|
||||
let tint = Self::tint(state, q.tint_index, colors, pos[0], pos[2]);
|
||||
let target = if face.translucent {
|
||||
&mut out.translucent
|
||||
} else {
|
||||
&mut out.solid
|
||||
};
|
||||
for (p, uv) in q.positions.iter().zip(q.uv) {
|
||||
let (sky, block, occlusion) = if ao {
|
||||
let u = p[ua].clamp(0.0, 1.0);
|
||||
let v = p[va].clamp(0.0, 1.0);
|
||||
let lerp = |k: usize| {
|
||||
let a = corners[0][k] * (1.0 - u) + corners[1][k] * u;
|
||||
let b = corners[2][k] * (1.0 - u) + corners[3][k] * u;
|
||||
a * (1.0 - v) + b * v
|
||||
};
|
||||
(lerp(0), lerp(1), lerp(2))
|
||||
} else {
|
||||
(flat_sky, flat_block, 1.0)
|
||||
for i in 0..4 {
|
||||
let g = gray[i] as u32;
|
||||
let rgb = match tint {
|
||||
Some(t) => [16, 8, 0].map(|shift| g * (t >> shift & 255) / 255),
|
||||
None => [g; 3],
|
||||
};
|
||||
let p = q.positions[i];
|
||||
target.push(Vertex {
|
||||
pos: [p[0] + x as f32, p[1] + y as f32, p[2] + z as f32],
|
||||
uv,
|
||||
pos: [p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]],
|
||||
uv: q.uv[i],
|
||||
layer: face.layer,
|
||||
color: pack_color(tint, directional * occlusion),
|
||||
light: pack_light(sky, block),
|
||||
color: pack_rgb(rgb),
|
||||
light: pack_coords(lighting::with_emission(coords[i], q.light_emission)),
|
||||
});
|
||||
}
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn fluid(&self, pad: &Padded, colors: &Colors, out: &mut SectionMesh, x: i32, y: i32, z: i32, id: u16) {
|
||||
let info = &self.tables.info;
|
||||
let me = info[id as usize];
|
||||
let water = me.fluid == Fluid::Water;
|
||||
let same = |p: [i32; 3]| info[pad.blocks[pi(p[0], p[1], p[2])] as usize].fluid == me.fluid;
|
||||
let solid = |p: [i32; 3]| {
|
||||
let s = info[pad.blocks[pi(p[0], p[1], p[2])] as usize];
|
||||
s.solid || s.full
|
||||
};
|
||||
let height = |p: [i32; 3]| -> f32 {
|
||||
let s = info[pad.blocks[pi(p[0], p[1], p[2])] as usize];
|
||||
if s.fluid == me.fluid {
|
||||
if same([p[0], p[1] + 1, p[2]]) {
|
||||
1.0
|
||||
} else {
|
||||
f32::from(s.level) / 9.0
|
||||
}
|
||||
} else if !(s.solid || s.full) {
|
||||
0.0
|
||||
} else {
|
||||
-1.0
|
||||
}
|
||||
};
|
||||
let own = height([x, y, z]);
|
||||
let corner = |a: f32, b: f32, c: [i32; 3]| -> f32 {
|
||||
if a >= 1.0 || b >= 1.0 {
|
||||
return 1.0;
|
||||
}
|
||||
let mut sum = [0.0f32; 2];
|
||||
let mut add = |h: f32| {
|
||||
if h >= 0.8 {
|
||||
sum[0] += h * 10.0;
|
||||
sum[1] += 10.0;
|
||||
} else if h >= 0.0 {
|
||||
sum[0] += h;
|
||||
sum[1] += 1.0;
|
||||
}
|
||||
};
|
||||
if a > 0.0 || b > 0.0 {
|
||||
let hc = height(c);
|
||||
if hc >= 1.0 {
|
||||
return 1.0;
|
||||
}
|
||||
add(hc);
|
||||
}
|
||||
add(own);
|
||||
add(a);
|
||||
add(b);
|
||||
sum[0] / sum[1]
|
||||
};
|
||||
let (nw, sw, se, ne) = if own >= 1.0 {
|
||||
(1.0, 1.0, 1.0, 1.0)
|
||||
} else {
|
||||
let n = height([x, y, z - 1]);
|
||||
let s = height([x, y, z + 1]);
|
||||
let e = height([x + 1, y, z]);
|
||||
let w = height([x - 1, y, z]);
|
||||
(
|
||||
corner(n, w, [x - 1, y, z - 1]),
|
||||
corner(s, w, [x - 1, y, z + 1]),
|
||||
corner(s, e, [x + 1, y, z + 1]),
|
||||
corner(n, e, [x + 1, y, z - 1]),
|
||||
)
|
||||
};
|
||||
let tint = if water {
|
||||
colors.water[(z * 16 + x) as usize]
|
||||
} else {
|
||||
0xFF_FFFF
|
||||
};
|
||||
let (still, flow) = if water {
|
||||
(self.tables.water_still, self.tables.water_flow)
|
||||
} else {
|
||||
(self.tables.lava_still, self.tables.lava_flow)
|
||||
};
|
||||
let light = |p: [i32; 3]| {
|
||||
let packed = pad.light[pi(p[0], p[1], p[2])];
|
||||
let emission = if water { 0 } else { 15 };
|
||||
pack_light(f32::from(packed >> 4), f32::from((packed & 15).max(emission)))
|
||||
};
|
||||
let target = if water {
|
||||
&mut out.translucent
|
||||
} else {
|
||||
&mut out.solid
|
||||
};
|
||||
let (fx, fy, fz) = (x as f32, y as f32, z as f32);
|
||||
let quad = |target: &mut Vec<Vertex>, v: [([f32; 3], [f32; 2]); 4], layer: u32, b: f32, l: u32, back: bool| {
|
||||
for (p, uv) in v {
|
||||
target.push(Vertex {
|
||||
pos: p,
|
||||
uv,
|
||||
layer,
|
||||
color: pack_color(tint, b),
|
||||
light: l,
|
||||
});
|
||||
}
|
||||
if back {
|
||||
for i in [0, 3, 2, 1] {
|
||||
let (p, uv) = v[i];
|
||||
target.push(Vertex {
|
||||
pos: p,
|
||||
uv,
|
||||
layer,
|
||||
color: pack_color(tint, b),
|
||||
light: l,
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
let above_same = same([x, y + 1, z]);
|
||||
if !above_same && !solid([x, y + 1, z]) || !above_same && own < 1.0 {
|
||||
let o = 0.001;
|
||||
let (h0, h1, h2, h3) = (nw - o, sw - o, se - o, ne - o);
|
||||
// Flow direction from neighbour height differences.
|
||||
let mut fxv = 0.0f32;
|
||||
let mut fzv = 0.0f32;
|
||||
if own < 1.0 && me.level < 8 || own < 0.88 {
|
||||
for (dx, dz) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
|
||||
let h = height([x + dx, y, z + dz]);
|
||||
if h >= 0.0 {
|
||||
let d = own - h.max(0.0);
|
||||
fxv += dx as f32 * d;
|
||||
fzv += dz as f32 * d;
|
||||
}
|
||||
}
|
||||
}
|
||||
let (layer, uvs) = if fxv.abs() < 1e-4 && fzv.abs() < 1e-4 {
|
||||
(still, [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]])
|
||||
} else {
|
||||
let angle = fzv.atan2(fxv) - std::f32::consts::FRAC_PI_2;
|
||||
let (s, c) = (angle.sin() * 0.25, angle.cos() * 0.25);
|
||||
// Flowing sprites are sampled over their top-left quarter-scaled region (getU(0.5+..) of 16 units).
|
||||
(
|
||||
flow,
|
||||
[
|
||||
[0.5 + (-c - s), 0.5 + (-c + s)],
|
||||
[0.5 + (-c + s), 0.5 + (c + s)],
|
||||
[0.5 + (c + s), 0.5 + (c - s)],
|
||||
[0.5 + (c - s), 0.5 + (-c - s)],
|
||||
],
|
||||
)
|
||||
};
|
||||
quad(
|
||||
target,
|
||||
[
|
||||
([fx, fy + h0, fz], uvs[0]),
|
||||
([fx, fy + h1, fz + 1.0], uvs[1]),
|
||||
([fx + 1.0, fy + h2, fz + 1.0], uvs[2]),
|
||||
([fx + 1.0, fy + h3, fz], uvs[3]),
|
||||
],
|
||||
layer,
|
||||
1.0,
|
||||
light([x, y, z]),
|
||||
water && !solid([x, y + 1, z]),
|
||||
);
|
||||
}
|
||||
if !same([x, y - 1, z]) && !solid([x, y - 1, z]) {
|
||||
quad(
|
||||
target,
|
||||
[
|
||||
([fx, fy + 0.001, fz], [0.0, 0.0]),
|
||||
([fx + 1.0, fy + 0.001, fz], [1.0, 0.0]),
|
||||
([fx + 1.0, fy + 0.001, fz + 1.0], [1.0, 1.0]),
|
||||
([fx, fy + 0.001, fz + 1.0], [0.0, 1.0]),
|
||||
],
|
||||
still,
|
||||
0.5,
|
||||
light([x, y - 1, z]),
|
||||
false,
|
||||
);
|
||||
}
|
||||
let o = 0.001;
|
||||
for (dx, dz, h0, h1, p0, p1, sh) in [
|
||||
(0, -1, nw, ne, [fx, fz + o], [fx + 1.0, fz + o], 0.8),
|
||||
(0, 1, se, sw, [fx + 1.0, fz + 1.0 - o], [fx, fz + 1.0 - o], 0.8),
|
||||
(-1, 0, sw, nw, [fx + o, fz + 1.0], [fx + o, fz], 0.6),
|
||||
(1, 0, ne, se, [fx + 1.0 - o, fz], [fx + 1.0 - o, fz + 1.0], 0.6),
|
||||
] {
|
||||
let n = [x + dx, y, z + dz];
|
||||
if same(n) || solid(n) {
|
||||
continue;
|
||||
}
|
||||
let v0 = (1.0 - h0) * 0.5;
|
||||
let v1 = (1.0 - h1) * 0.5;
|
||||
quad(
|
||||
target,
|
||||
[
|
||||
([p0[0], fy + h0, p0[1]], [0.0, v0]),
|
||||
([p1[0], fy + h1, p1[1]], [0.5, v1]),
|
||||
([p1[0], fy, p1[1]], [0.5, 0.5]),
|
||||
([p0[0], fy, p0[1]], [0.0, 0.5]),
|
||||
],
|
||||
flow,
|
||||
sh,
|
||||
light([x, y, z]),
|
||||
water,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Snapshot of the 3x3 chunk neighbourhood used by a worker job.
|
||||
pub type Region = [[Option<Arc<Chunk>>; 3]; 3];
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
//! Fluid surfaces following `FluidRenderer.tesselate`: corner heights, face
|
||||
//! occlusion against neighbour shapes, flow-rotated top UVs, the water overlay
|
||||
//! beside glass and leaves, back faces, cardinal shading and max(self, above)
|
||||
//! light.
|
||||
use super::{Info, MeshTables, Padded, SectionMesh, Vertex, lighting, pack_coords, pack_rgb, pi};
|
||||
use horizon_core::{
|
||||
geometry::{Axis, Direction, VoxelShape, trig},
|
||||
position::BlockPos,
|
||||
};
|
||||
use horizon_world::{
|
||||
fluid::{FluidKind, FluidState},
|
||||
fluid_flow::{FluidFlowWorld, flow_at},
|
||||
};
|
||||
use std::{convert::Infallible, sync::OnceLock};
|
||||
|
||||
/// `FluidRenderer.MAX_FLUID_HEIGHT`.
|
||||
const MAX_HEIGHT: f32 = 0.888_888_9;
|
||||
const EPSILON: f32 = 0.001;
|
||||
|
||||
/// For the occlusion face toward `direction`: the height from the bottom over
|
||||
/// which its slice flush with the `direction` side covers the whole width
|
||||
/// (vertical faces: 1 when the whole square is covered, else 0). This is what
|
||||
/// `Shapes.blockOccludes` decides for a fluid box of a given height.
|
||||
pub(super) fn coverage(shape: &VoxelShape, direction: Direction) -> f32 {
|
||||
let (axis, u, v) = match direction {
|
||||
Direction::Down | Direction::Up => (Axis::Y, Axis::X, Axis::Z),
|
||||
Direction::North | Direction::South => (Axis::Z, Axis::X, Axis::Y),
|
||||
Direction::West | Direction::East => (Axis::X, Axis::Z, Axis::Y),
|
||||
};
|
||||
let positive = matches!(
|
||||
direction,
|
||||
Direction::Up | Direction::South | Direction::East
|
||||
);
|
||||
let rects: Vec<[f64; 4]> = shape
|
||||
.boxes()
|
||||
.iter()
|
||||
.filter(|b| {
|
||||
if positive {
|
||||
b.max(axis) >= 1.0 - 1e-7
|
||||
} else {
|
||||
b.min(axis) <= 1e-7
|
||||
}
|
||||
})
|
||||
.map(|b| [b.min(u), b.max(u), b.min(v), b.max(v)])
|
||||
.collect();
|
||||
let mut cuts: Vec<f64> = rects
|
||||
.iter()
|
||||
.flat_map(|r| [r[2], r[3]])
|
||||
.filter(|c| (0.0..=1.0).contains(c))
|
||||
.chain([0.0, 1.0])
|
||||
.collect();
|
||||
cuts.sort_by(f64::total_cmp);
|
||||
cuts.dedup();
|
||||
let mut covered = 0.0;
|
||||
for w in cuts.windows(2) {
|
||||
let middle = (w[0] + w[1]) / 2.0;
|
||||
let mut spans: Vec<(f64, f64)> = rects
|
||||
.iter()
|
||||
.filter(|r| r[2] <= middle && middle <= r[3])
|
||||
.map(|r| (r[0], r[1]))
|
||||
.collect();
|
||||
spans.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
let mut reach = 0.0f64;
|
||||
for (lo, hi) in spans {
|
||||
if lo > reach + 1e-7 {
|
||||
break;
|
||||
}
|
||||
reach = reach.max(hi);
|
||||
}
|
||||
if reach < 1.0 - 1e-7 {
|
||||
break;
|
||||
}
|
||||
covered = w[1];
|
||||
}
|
||||
if matches!(direction, Direction::Down | Direction::Up) && covered < 1.0 {
|
||||
return 0.0;
|
||||
}
|
||||
covered as f32
|
||||
}
|
||||
/// `isFaceOccludedByState` for a fluid box `height` tall against `state`'s
|
||||
/// face opposite `direction`.
|
||||
fn occluded_by(direction: Direction, height: f32, state: &Info) -> bool {
|
||||
let opposite = direction.opposite() as usize;
|
||||
match state.face[opposite] {
|
||||
0 => false,
|
||||
1 => direction != Direction::Up || height == 1.0,
|
||||
_ => match direction {
|
||||
Direction::Up => {
|
||||
f64::from(height) >= 1.0 - 1e-7 && state.cover[Direction::Down as usize] >= 1.0
|
||||
}
|
||||
Direction::Down => state.cover[Direction::Up as usize] >= 1.0,
|
||||
_ => f64::from(height) <= f64::from(state.cover[opposite]) + 1e-7,
|
||||
},
|
||||
}
|
||||
}
|
||||
/// `isFaceOccludedBySelf`: the cell's own occlusion face toward `direction`.
|
||||
fn occluded_by_self(state: &Info, direction: Direction) -> bool {
|
||||
match state.face[direction as usize] {
|
||||
0 => false,
|
||||
1 => true,
|
||||
_ => state.cover[direction as usize] >= 1.0,
|
||||
}
|
||||
}
|
||||
/// `Mth.atan2`: the client's table-driven arctangent.
|
||||
fn atan2(mut y: f64, mut x: f64) -> f64 {
|
||||
static TABLES: OnceLock<(Vec<f64>, Vec<f64>)> = OnceLock::new();
|
||||
let (asin, cos) = TABLES.get_or_init(|| {
|
||||
(0..257)
|
||||
.map(|i| {
|
||||
let a = (f64::from(i) / 256.0).asin();
|
||||
(a, a.cos())
|
||||
})
|
||||
.unzip()
|
||||
});
|
||||
let frac_bias = f64::from_bits(4_805_340_802_404_319_232);
|
||||
let d2 = x * x + y * y;
|
||||
if d2.is_nan() {
|
||||
return f64::NAN;
|
||||
}
|
||||
let negative_y = y < 0.0;
|
||||
if negative_y {
|
||||
y = -y;
|
||||
}
|
||||
let negative_x = x < 0.0;
|
||||
if negative_x {
|
||||
x = -x;
|
||||
}
|
||||
let steep = y > x;
|
||||
if steep {
|
||||
std::mem::swap(&mut x, &mut y);
|
||||
}
|
||||
// Mth.fastInvSqrt
|
||||
let half = 0.5 * d2;
|
||||
let mut r = f64::from_bits((6_910_469_410_427_058_090i64 - (d2.to_bits() as i64 >> 1)) as u64);
|
||||
r *= 1.5 - half * r * r;
|
||||
x *= r;
|
||||
y *= r;
|
||||
let yp = frac_bias + y;
|
||||
let index = yp.to_bits() as i32 as usize;
|
||||
let s_phi = yp - frac_bias;
|
||||
let sd = y * cos[index] - x * s_phi;
|
||||
let mut theta = asin[index] + (6.0 + sd * sd) * sd * 0.166_666_666_666_666_66;
|
||||
if steep {
|
||||
theta = std::f64::consts::FRAC_PI_2 - theta;
|
||||
}
|
||||
if negative_x {
|
||||
theta = std::f64::consts::PI - theta;
|
||||
}
|
||||
if negative_y {
|
||||
theta = -theta;
|
||||
}
|
||||
theta
|
||||
}
|
||||
/// The padded section as `FlowingFluid.getFlow` sees it (section-relative positions).
|
||||
struct FlowView<'a> {
|
||||
pad: &'a Padded,
|
||||
info: &'a [Info],
|
||||
}
|
||||
impl FlowView<'_> {
|
||||
fn id(&self, p: BlockPos) -> u16 {
|
||||
self.pad.blocks[pi(p.x, p.y, p.z)]
|
||||
}
|
||||
}
|
||||
impl FluidFlowWorld for FlowView<'_> {
|
||||
type Error = Infallible;
|
||||
type Block = u16;
|
||||
fn fluid(&mut self, p: BlockPos) -> Result<FluidState, Infallible> {
|
||||
Ok(self.info[self.id(p) as usize].fluid)
|
||||
}
|
||||
fn block(&mut self, p: BlockPos) -> Result<u16, Infallible> {
|
||||
Ok(self.id(p))
|
||||
}
|
||||
fn blocks_fluid_flow(&self, state: u16) -> bool {
|
||||
self.info[state as usize].blocks_flow
|
||||
}
|
||||
fn is_ice_class(&self, state: u16) -> bool {
|
||||
self.info[state as usize].ice
|
||||
}
|
||||
fn is_face_sturdy(
|
||||
&mut self,
|
||||
state: u16,
|
||||
_: BlockPos,
|
||||
d: Direction,
|
||||
) -> Result<bool, Infallible> {
|
||||
Ok(self.info[state as usize].sturdy & 1 << d as u8 != 0)
|
||||
}
|
||||
}
|
||||
/// Emits one fluid cell at section-relative `[x, y, z]`.
|
||||
pub(super) fn tesselate(
|
||||
tables: &MeshTables,
|
||||
nether: bool,
|
||||
pad: &Padded,
|
||||
water_color: u32,
|
||||
out: &mut SectionMesh,
|
||||
[x, y, z]: [i32; 3],
|
||||
) {
|
||||
use horizon_assets::model::Direction as D;
|
||||
let info = &tables.info;
|
||||
let at = |p: [i32; 3]| &info[pad.blocks[pi(p[0], p[1], p[2])] as usize];
|
||||
let me = at([x, y, z]);
|
||||
let kind = me.fluid.kind();
|
||||
let same = |s: &Info| s.fluid.kind().same_family(kind);
|
||||
let neighbor = |d: Direction| {
|
||||
let [dx, dy, dz] = d.normal();
|
||||
at([x + dx, y + dy, z + dz])
|
||||
};
|
||||
let (down, up) = (neighbor(Direction::Down), neighbor(Direction::Up));
|
||||
let should_render = |d: Direction| !same(neighbor(d)) && !occluded_by_self(me, d);
|
||||
let render_up = !same(up);
|
||||
let render_down =
|
||||
should_render(Direction::Down) && !occluded_by(Direction::Down, MAX_HEIGHT, down);
|
||||
let sides = [
|
||||
Direction::North,
|
||||
Direction::South,
|
||||
Direction::West,
|
||||
Direction::East,
|
||||
]
|
||||
.map(should_render);
|
||||
if !render_up && !render_down && !sides.iter().any(|&s| s) {
|
||||
return;
|
||||
}
|
||||
let water = matches!(kind, FluidKind::Water | FluidKind::FlowingWater);
|
||||
let tint = if water {
|
||||
water_color & 0xFF_FFFF
|
||||
} else {
|
||||
0xFF_FFFF
|
||||
};
|
||||
let color = |by: f32| {
|
||||
pack_rgb([16, 8, 0].map(|shift| lighting::scale((tint >> shift & 255) as i32, by) as u32))
|
||||
};
|
||||
let height = |p: [i32; 3]| -> f32 {
|
||||
let s = at(p);
|
||||
if same(s) {
|
||||
if same(at([p[0], p[1] + 1, p[2]])) {
|
||||
1.0
|
||||
} else {
|
||||
s.fluid.own_height()
|
||||
}
|
||||
} else if !s.legacy_solid {
|
||||
0.0
|
||||
} else {
|
||||
-1.0
|
||||
}
|
||||
};
|
||||
let own = height([x, y, z]);
|
||||
let (mut ne, mut nw, mut se, mut sw) = (1.0f32, 1.0f32, 1.0f32, 1.0f32);
|
||||
if own < 1.0 {
|
||||
let n = height([x, y, z - 1]);
|
||||
let s = height([x, y, z + 1]);
|
||||
let e = height([x + 1, y, z]);
|
||||
let w = height([x - 1, y, z]);
|
||||
// calculateAverageHeight(self, height2, height1, corner)
|
||||
let average = |h2: f32, h1: f32, corner: [i32; 3]| -> f32 {
|
||||
if h1 >= 1.0 || h2 >= 1.0 {
|
||||
return 1.0;
|
||||
}
|
||||
let mut sum = [0f32; 2];
|
||||
let mut add = |h: f32| {
|
||||
if h >= 0.8 {
|
||||
sum[0] += h * 10.0;
|
||||
sum[1] += 10.0;
|
||||
} else if h >= 0.0 {
|
||||
sum[0] += h;
|
||||
sum[1] += 1.0;
|
||||
}
|
||||
};
|
||||
if h1 > 0.0 || h2 > 0.0 {
|
||||
let hc = height(corner);
|
||||
if hc >= 1.0 {
|
||||
return 1.0;
|
||||
}
|
||||
add(hc);
|
||||
}
|
||||
add(own);
|
||||
add(h1);
|
||||
add(h2);
|
||||
sum[0] / sum[1]
|
||||
};
|
||||
ne = average(n, e, [x + 1, y, z - 1]);
|
||||
nw = average(n, w, [x - 1, y, z - 1]);
|
||||
se = average(s, e, [x + 1, y, z + 1]);
|
||||
sw = average(s, w, [x - 1, y, z + 1]);
|
||||
}
|
||||
let light = |p: [i32; 3]| {
|
||||
let above = [p[0], p[1] + 1, p[2]];
|
||||
pack_coords(lighting::max_coords(
|
||||
lighting::coords(pad, at(p), p),
|
||||
lighting::coords(pad, at(above), above),
|
||||
))
|
||||
};
|
||||
let (still, flow, overlay) = if water {
|
||||
(
|
||||
tables.water_still,
|
||||
tables.water_flow,
|
||||
Some(tables.water_overlay),
|
||||
)
|
||||
} else {
|
||||
(tables.lava_still, tables.lava_flow, None)
|
||||
};
|
||||
let target = if water {
|
||||
&mut out.translucent
|
||||
} else {
|
||||
&mut out.solid
|
||||
};
|
||||
let mut quad =
|
||||
|v: [([f32; 3], [f32; 2]); 4], layer: u32, color: u32, light: u32, back: bool| {
|
||||
let vertex = |(pos, uv): ([f32; 3], [f32; 2])| Vertex {
|
||||
pos,
|
||||
uv,
|
||||
layer,
|
||||
color,
|
||||
light,
|
||||
};
|
||||
target.extend(v.map(vertex));
|
||||
if back {
|
||||
target.extend([v[0], v[3], v[2], v[1]].map(vertex));
|
||||
}
|
||||
};
|
||||
let (fx, fy, fz) = (x as f32, y as f32, z as f32);
|
||||
let bottom = if render_down { EPSILON } else { 0.0 };
|
||||
if render_up && !occluded_by(Direction::Up, nw.min(sw).min(se.min(ne)), up) {
|
||||
nw -= EPSILON;
|
||||
sw -= EPSILON;
|
||||
se -= EPSILON;
|
||||
ne -= EPSILON;
|
||||
let flow_vector = flow_at(
|
||||
&mut FlowView { pad, info },
|
||||
me.fluid,
|
||||
BlockPos::new(x, y, z),
|
||||
)
|
||||
.unwrap_or_else(|e| match e {});
|
||||
let (layer, uv) = if flow_vector.x == 0.0 && flow_vector.z == 0.0 {
|
||||
(still, [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]])
|
||||
} else {
|
||||
let angle =
|
||||
atan2(flow_vector.z, flow_vector.x) as f32 - std::f64::consts::FRAC_PI_2 as f32;
|
||||
let s = trig::sin(f64::from(angle)) * 0.25;
|
||||
let c = trig::cos(f64::from(angle)) * 0.25;
|
||||
(
|
||||
flow,
|
||||
[
|
||||
[0.5 + (-c - s), 0.5 + (-c + s)],
|
||||
[0.5 + (-c + s), 0.5 + (c + s)],
|
||||
[0.5 + (c + s), 0.5 + (c - s)],
|
||||
[0.5 + (c - s), 0.5 + (-c - s)],
|
||||
],
|
||||
)
|
||||
};
|
||||
// FluidState.shouldRenderBackwardUpFace over the 3x3 cells above.
|
||||
let backward = (-1..=1).any(|ox| {
|
||||
(-1..=1).any(|oz| {
|
||||
let s = at([x + ox, y + 1, z + oz]);
|
||||
!same(s) && !s.solid
|
||||
})
|
||||
});
|
||||
quad(
|
||||
[
|
||||
([fx, fy + nw, fz], uv[0]),
|
||||
([fx, fy + sw, fz + 1.0], uv[1]),
|
||||
([fx + 1.0, fy + se, fz + 1.0], uv[2]),
|
||||
([fx + 1.0, fy + ne, fz], uv[3]),
|
||||
],
|
||||
layer,
|
||||
color(lighting::cardinal(nether, D::Up)),
|
||||
light([x, y, z]),
|
||||
backward,
|
||||
);
|
||||
}
|
||||
if render_down {
|
||||
let y0 = fy + bottom;
|
||||
quad(
|
||||
[
|
||||
([fx, y0, fz], [0.0, 0.0]),
|
||||
([fx + 1.0, y0, fz], [1.0, 0.0]),
|
||||
([fx + 1.0, y0, fz + 1.0], [1.0, 1.0]),
|
||||
([fx, y0, fz + 1.0], [0.0, 1.0]),
|
||||
],
|
||||
still,
|
||||
color(lighting::cardinal(nether, D::Down)),
|
||||
light([x, y - 1, z]),
|
||||
false,
|
||||
);
|
||||
}
|
||||
let side_light = light([x, y, z]);
|
||||
let up_shade = lighting::cardinal(nether, D::Up);
|
||||
for (i, d) in [
|
||||
Direction::North,
|
||||
Direction::South,
|
||||
Direction::West,
|
||||
Direction::East,
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let (h0, h1, [x0, z0], [x1, z1]) = match d {
|
||||
Direction::North => (nw, ne, [fx, fz + EPSILON], [fx + 1.0, fz + EPSILON]),
|
||||
Direction::South => (
|
||||
se,
|
||||
sw,
|
||||
[fx + 1.0, fz + 1.0 - EPSILON],
|
||||
[fx, fz + 1.0 - EPSILON],
|
||||
),
|
||||
Direction::West => (sw, nw, [fx + EPSILON, fz + 1.0], [fx + EPSILON, fz]),
|
||||
_ => (
|
||||
ne,
|
||||
se,
|
||||
[fx + 1.0 - EPSILON, fz],
|
||||
[fx + 1.0 - EPSILON, fz + 1.0],
|
||||
),
|
||||
};
|
||||
let face_state = neighbor(d);
|
||||
if !sides[i] || occluded_by(d, h0.max(h1), face_state) {
|
||||
continue;
|
||||
}
|
||||
let (layer, is_overlay) = match overlay {
|
||||
Some(layer) if face_state.overlay => (layer, true),
|
||||
_ => (flow, false),
|
||||
};
|
||||
let side = if matches!(d, Direction::North | Direction::South) {
|
||||
lighting::cardinal(nether, D::North)
|
||||
} else {
|
||||
lighting::cardinal(nether, D::West)
|
||||
};
|
||||
let (v0, v1) = ((1.0 - h0) * 0.5, (1.0 - h1) * 0.5);
|
||||
quad(
|
||||
[
|
||||
([x0, fy + h0, z0], [0.0, v0]),
|
||||
([x1, fy + h1, z1], [0.5, v1]),
|
||||
([x1, fy + bottom, z1], [0.5, 0.5]),
|
||||
([x0, fy + bottom, z0], [0.0, 0.5]),
|
||||
],
|
||||
layer,
|
||||
color(up_shade * side),
|
||||
side_light,
|
||||
!is_overlay,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn atan2_follows_the_table_approximation() {
|
||||
for (y, x) in [
|
||||
(1.0, 0.0),
|
||||
(0.0, 1.0),
|
||||
(-0.5, 0.25),
|
||||
(0.3, -0.9),
|
||||
(-1.0, -1.0),
|
||||
(0.1, 0.7),
|
||||
] {
|
||||
let exact = f64::atan2(y, x);
|
||||
assert!((atan2(y, x) - exact).abs() < 1e-6, "{y} {x}");
|
||||
}
|
||||
assert!(atan2(f64::NAN, 1.0).is_nan());
|
||||
}
|
||||
#[test]
|
||||
fn coverage_of_full_and_partial_faces() {
|
||||
assert_eq!(coverage(&VoxelShape::block(), Direction::North), 1.0);
|
||||
assert_eq!(coverage(&VoxelShape::block(), Direction::Up), 1.0);
|
||||
assert_eq!(coverage(&VoxelShape::empty(), Direction::East), 0.0);
|
||||
// A bottom slab covers the lower half of each side and the whole floor.
|
||||
let slab = VoxelShape::from_cube([1, 2, 1], &[true, false]).unwrap();
|
||||
assert_eq!(coverage(&slab, Direction::South), 0.5);
|
||||
assert_eq!(coverage(&slab, Direction::Down), 1.0);
|
||||
assert_eq!(coverage(&slab, Direction::Up), 0.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
//! Vertex light and colour of model quads, following `BlockModelLighter`
|
||||
//! (smooth light and ambient occlusion, including the partial-face weights)
|
||||
//! and `ModelBlockRenderer`'s integer colour arithmetic (`ARGB.gray`,
|
||||
//! `scaleRGB`, `multiply`).
|
||||
use super::{Info, Padded, pi};
|
||||
use horizon_assets::model::Direction as D;
|
||||
|
||||
/// `LightCoordsUtil.FULL_BRIGHT`.
|
||||
pub(super) const FULL_BRIGHT: u32 = 0x00F0_00F0;
|
||||
|
||||
/// `CardinalLighting.DEFAULT`/`NETHER` by face.
|
||||
pub(super) fn cardinal(nether: bool, face: D) -> f32 {
|
||||
match face {
|
||||
D::Down if nether => 0.9,
|
||||
D::Up if nether => 0.9,
|
||||
D::Down => 0.5,
|
||||
D::Up => 1.0,
|
||||
D::North | D::South => 0.8,
|
||||
D::West | D::East => 0.6,
|
||||
}
|
||||
}
|
||||
fn normal(face: D) -> [i32; 3] {
|
||||
match face {
|
||||
D::Down => [0, -1, 0],
|
||||
D::Up => [0, 1, 0],
|
||||
D::North => [0, 0, -1],
|
||||
D::South => [0, 0, 1],
|
||||
D::West => [-1, 0, 0],
|
||||
D::East => [1, 0, 0],
|
||||
}
|
||||
}
|
||||
pub(super) fn step(p: [i32; 3], face: D) -> [i32; 3] {
|
||||
let n = normal(face);
|
||||
[p[0] + n[0], p[1] + n[1], p[2] + n[2]]
|
||||
}
|
||||
fn state<'a>(pad: &Padded, info: &'a [Info], p: [i32; 3]) -> &'a Info {
|
||||
&info[pad.blocks[pi(p[0], p[1], p[2])] as usize]
|
||||
}
|
||||
/// `LightCoordsUtil.getLightCoords`: light at `p` as seen through `state`
|
||||
/// (block level << 4 | sky level << 20).
|
||||
pub(super) fn coords(pad: &Padded, state: &Info, p: [i32; 3]) -> u32 {
|
||||
if state.emissive {
|
||||
return FULL_BRIGHT;
|
||||
}
|
||||
let packed = pad.light[pi(p[0], p[1], p[2])];
|
||||
let block = u32::from((packed & 15).max(state.emission));
|
||||
block << 4 | u32::from(packed >> 4) << 20
|
||||
}
|
||||
/// `LightCoordsUtil.max`.
|
||||
pub(super) fn max_coords(a: u32, b: u32) -> u32 {
|
||||
(a >> 4 & 15).max(b >> 4 & 15) << 4 | (a >> 20 & 15).max(b >> 20 & 15) << 20
|
||||
}
|
||||
/// `LightCoordsUtil.lightCoordsWithEmission` (a quad's element light emission).
|
||||
pub(super) fn with_emission(coords: u32, emission: u8) -> u32 {
|
||||
if emission == 0 {
|
||||
return coords;
|
||||
}
|
||||
let e = u32::from(emission);
|
||||
(coords >> 4 & 15).max(e) << 4 | (coords >> 20 & 15).max(e) << 20
|
||||
}
|
||||
/// `LightCoordsUtil.smoothBlend`: zero samples take the centre; samples without
|
||||
/// sky light borrow the centre's sky.
|
||||
pub(super) fn smooth_blend(mut a: u32, mut b: u32, mut c: u32, center: u32) -> u32 {
|
||||
if center >> 20 & 15 > 2 || center >> 4 & 15 > 2 {
|
||||
for n in [&mut a, &mut b, &mut c] {
|
||||
if *n == 0 {
|
||||
*n = center;
|
||||
} else if *n >> 20 & 15 == 0 {
|
||||
*n |= center & 0x00FF_0000;
|
||||
}
|
||||
}
|
||||
}
|
||||
(a + b + c + center) >> 2 & 0x00FF_00FF
|
||||
}
|
||||
/// `LightCoordsUtil.smoothWeightedBlend` (Java float sums and int narrowing).
|
||||
fn weighted_blend(c: [u32; 4], w: [f32; 4]) -> u32 {
|
||||
let channel = |shift: u32| {
|
||||
let v = |i: usize| (c[i] >> shift & 0xFF) as f32 * w[i];
|
||||
(v(0) + v(1) + v(2) + v(3)) as i32 as u32 & 0xFF
|
||||
};
|
||||
channel(0) | channel(16) << 16
|
||||
}
|
||||
/// `ARGB.gray` channel: `Mth.floor(brightness * 255)`.
|
||||
pub(super) fn gray(brightness: f32) -> i32 {
|
||||
(brightness * 255.0).floor() as i32
|
||||
}
|
||||
/// One channel of `ARGB.scaleRGB(color, float)`.
|
||||
pub(super) fn scale(channel: i32, by: f32) -> i32 {
|
||||
((channel as f32 * by) as i32).clamp(0, 255)
|
||||
}
|
||||
// SizeInfo indices into the face shape.
|
||||
const DOWN: u8 = 0;
|
||||
const UP: u8 = 1;
|
||||
const NORTH: u8 = 2;
|
||||
const SOUTH: u8 = 3;
|
||||
const WEST: u8 = 4;
|
||||
const EAST: u8 = 5;
|
||||
const FLIP_DOWN: u8 = 6;
|
||||
const FLIP_UP: u8 = 7;
|
||||
const FLIP_NORTH: u8 = 8;
|
||||
const FLIP_SOUTH: u8 = 9;
|
||||
const FLIP_WEST: u8 = 10;
|
||||
const FLIP_EAST: u8 = 11;
|
||||
struct Adjacency {
|
||||
corners: [D; 4],
|
||||
/// Face-shape factor pairs for each vertex's four corner weights.
|
||||
weights: [[u8; 8]; 4],
|
||||
/// Output vertex for each of the four computed corners.
|
||||
remap: [usize; 4],
|
||||
}
|
||||
const fn adjacency(face: D) -> Adjacency {
|
||||
use D::*;
|
||||
match face {
|
||||
Down => Adjacency {
|
||||
corners: [West, East, North, South],
|
||||
weights: [
|
||||
[
|
||||
FLIP_WEST, SOUTH, FLIP_WEST, FLIP_SOUTH, WEST, FLIP_SOUTH, WEST, SOUTH,
|
||||
],
|
||||
[
|
||||
FLIP_WEST, NORTH, FLIP_WEST, FLIP_NORTH, WEST, FLIP_NORTH, WEST, NORTH,
|
||||
],
|
||||
[
|
||||
FLIP_EAST, NORTH, FLIP_EAST, FLIP_NORTH, EAST, FLIP_NORTH, EAST, NORTH,
|
||||
],
|
||||
[
|
||||
FLIP_EAST, SOUTH, FLIP_EAST, FLIP_SOUTH, EAST, FLIP_SOUTH, EAST, SOUTH,
|
||||
],
|
||||
],
|
||||
remap: [0, 1, 2, 3],
|
||||
},
|
||||
Up => Adjacency {
|
||||
corners: [East, West, North, South],
|
||||
weights: [
|
||||
[
|
||||
EAST, SOUTH, EAST, FLIP_SOUTH, FLIP_EAST, FLIP_SOUTH, FLIP_EAST, SOUTH,
|
||||
],
|
||||
[
|
||||
EAST, NORTH, EAST, FLIP_NORTH, FLIP_EAST, FLIP_NORTH, FLIP_EAST, NORTH,
|
||||
],
|
||||
[
|
||||
WEST, NORTH, WEST, FLIP_NORTH, FLIP_WEST, FLIP_NORTH, FLIP_WEST, NORTH,
|
||||
],
|
||||
[
|
||||
WEST, SOUTH, WEST, FLIP_SOUTH, FLIP_WEST, FLIP_SOUTH, FLIP_WEST, SOUTH,
|
||||
],
|
||||
],
|
||||
remap: [2, 3, 0, 1],
|
||||
},
|
||||
North => Adjacency {
|
||||
corners: [Up, Down, East, West],
|
||||
weights: [
|
||||
[UP, FLIP_WEST, UP, WEST, FLIP_UP, WEST, FLIP_UP, FLIP_WEST],
|
||||
[UP, FLIP_EAST, UP, EAST, FLIP_UP, EAST, FLIP_UP, FLIP_EAST],
|
||||
[
|
||||
DOWN, FLIP_EAST, DOWN, EAST, FLIP_DOWN, EAST, FLIP_DOWN, FLIP_EAST,
|
||||
],
|
||||
[
|
||||
DOWN, FLIP_WEST, DOWN, WEST, FLIP_DOWN, WEST, FLIP_DOWN, FLIP_WEST,
|
||||
],
|
||||
],
|
||||
remap: [3, 0, 1, 2],
|
||||
},
|
||||
South => Adjacency {
|
||||
corners: [West, East, Down, Up],
|
||||
weights: [
|
||||
[UP, FLIP_WEST, FLIP_UP, FLIP_WEST, FLIP_UP, WEST, UP, WEST],
|
||||
[
|
||||
DOWN, FLIP_WEST, FLIP_DOWN, FLIP_WEST, FLIP_DOWN, WEST, DOWN, WEST,
|
||||
],
|
||||
[
|
||||
DOWN, FLIP_EAST, FLIP_DOWN, FLIP_EAST, FLIP_DOWN, EAST, DOWN, EAST,
|
||||
],
|
||||
[UP, FLIP_EAST, FLIP_UP, FLIP_EAST, FLIP_UP, EAST, UP, EAST],
|
||||
],
|
||||
remap: [0, 1, 2, 3],
|
||||
},
|
||||
West => Adjacency {
|
||||
corners: [Up, Down, North, South],
|
||||
weights: [
|
||||
[
|
||||
UP, SOUTH, UP, FLIP_SOUTH, FLIP_UP, FLIP_SOUTH, FLIP_UP, SOUTH,
|
||||
],
|
||||
[
|
||||
UP, NORTH, UP, FLIP_NORTH, FLIP_UP, FLIP_NORTH, FLIP_UP, NORTH,
|
||||
],
|
||||
[
|
||||
DOWN, NORTH, DOWN, FLIP_NORTH, FLIP_DOWN, FLIP_NORTH, FLIP_DOWN, NORTH,
|
||||
],
|
||||
[
|
||||
DOWN, SOUTH, DOWN, FLIP_SOUTH, FLIP_DOWN, FLIP_SOUTH, FLIP_DOWN, SOUTH,
|
||||
],
|
||||
],
|
||||
remap: [3, 0, 1, 2],
|
||||
},
|
||||
East => Adjacency {
|
||||
corners: [Down, Up, North, South],
|
||||
weights: [
|
||||
[
|
||||
FLIP_DOWN, SOUTH, FLIP_DOWN, FLIP_SOUTH, DOWN, FLIP_SOUTH, DOWN, SOUTH,
|
||||
],
|
||||
[
|
||||
FLIP_DOWN, NORTH, FLIP_DOWN, FLIP_NORTH, DOWN, FLIP_NORTH, DOWN, NORTH,
|
||||
],
|
||||
[
|
||||
FLIP_UP, NORTH, FLIP_UP, FLIP_NORTH, UP, FLIP_NORTH, UP, NORTH,
|
||||
],
|
||||
[
|
||||
FLIP_UP, SOUTH, FLIP_UP, FLIP_SOUTH, UP, FLIP_SOUTH, UP, SOUTH,
|
||||
],
|
||||
],
|
||||
remap: [1, 2, 3, 0],
|
||||
},
|
||||
}
|
||||
}
|
||||
const ADJACENCY: [Adjacency; 6] = [
|
||||
adjacency(D::Down),
|
||||
adjacency(D::Up),
|
||||
adjacency(D::North),
|
||||
adjacency(D::South),
|
||||
adjacency(D::West),
|
||||
adjacency(D::East),
|
||||
];
|
||||
/// `prepareQuadShape`: the quad's bounds, whether it is partial (smaller than
|
||||
/// the block face) and whether it is cubic (flush with the block boundary, or
|
||||
/// flat on a full collision shape).
|
||||
struct Shape {
|
||||
bounds: [f32; 12],
|
||||
partial: bool,
|
||||
cubic: bool,
|
||||
}
|
||||
fn shape(positions: &[[f32; 3]; 4], face: D, full: bool) -> Shape {
|
||||
let (mut min, mut max) = ([32f32; 3], [-32f32; 3]);
|
||||
for p in positions {
|
||||
for i in 0..3 {
|
||||
min[i] = min[i].min(p[i]);
|
||||
max[i] = max[i].max(p[i]);
|
||||
}
|
||||
}
|
||||
let mut bounds = [0f32; 12];
|
||||
for (index, value) in [
|
||||
(WEST, min[0]),
|
||||
(EAST, max[0]),
|
||||
(DOWN, min[1]),
|
||||
(UP, max[1]),
|
||||
(NORTH, min[2]),
|
||||
(SOUTH, max[2]),
|
||||
] {
|
||||
bounds[index as usize] = value;
|
||||
bounds[index as usize + 6] = 1.0 - value;
|
||||
}
|
||||
let (lo, hi) = (1.0e-4f32, 0.9999f32);
|
||||
let partial = |a: usize, b: usize| min[a] >= lo || min[b] >= lo || max[a] <= hi || max[b] <= hi;
|
||||
let (partial, cubic) = match face {
|
||||
D::Down => (partial(0, 2), min[1] == max[1] && (min[1] < lo || full)),
|
||||
D::Up => (partial(0, 2), min[1] == max[1] && (max[1] > hi || full)),
|
||||
D::North => (partial(0, 1), min[2] == max[2] && (min[2] < lo || full)),
|
||||
D::South => (partial(0, 1), min[2] == max[2] && (max[2] > hi || full)),
|
||||
D::West => (partial(1, 2), min[0] == max[0] && (min[0] < lo || full)),
|
||||
D::East => (partial(1, 2), min[0] == max[0] && (max[0] > hi || full)),
|
||||
};
|
||||
Shape {
|
||||
bounds,
|
||||
partial,
|
||||
cubic,
|
||||
}
|
||||
}
|
||||
/// `prepareQuadFlat` for a quad without a cull face: light from the
|
||||
/// neighbour when the quad is flush with the face, else from the block itself.
|
||||
pub(super) fn flat(
|
||||
pad: &Padded,
|
||||
own: &Info,
|
||||
pos: [i32; 3],
|
||||
positions: &[[f32; 3]; 4],
|
||||
face: D,
|
||||
) -> u32 {
|
||||
let cubic = shape(positions, face, own.full).cubic;
|
||||
coords(pad, own, if cubic { step(pos, face) } else { pos })
|
||||
}
|
||||
/// `prepareQuadAmbientOcclusion`: per-vertex AO brightness (before `ARGB.gray`)
|
||||
/// and smooth light coords, by vertex index.
|
||||
pub(super) fn ambient_occlusion(
|
||||
pad: &Padded,
|
||||
info: &[Info],
|
||||
own: &Info,
|
||||
pos: [i32; 3],
|
||||
positions: &[[f32; 3]; 4],
|
||||
face: D,
|
||||
) -> ([f32; 4], [u32; 4]) {
|
||||
let shape = shape(positions, face, own.full);
|
||||
let base = if shape.cubic { step(pos, face) } else { pos };
|
||||
let adjacency = &ADJACENCY[face as usize];
|
||||
let corner = |i: usize| step(base, adjacency.corners[i]);
|
||||
let sample = |p: [i32; 3]| {
|
||||
let s = state(pad, info, p);
|
||||
(coords(pad, s, p), s.shade)
|
||||
};
|
||||
let (light0, shade0) = sample(corner(0));
|
||||
let (light1, shade1) = sample(corner(1));
|
||||
let (light2, shade2) = sample(corner(2));
|
||||
let (light3, shade3) = sample(corner(3));
|
||||
let permeable = |i: usize| state(pad, info, step(corner(i), face)).permeable;
|
||||
let (p0, p1, p2, p3) = (permeable(0), permeable(1), permeable(2), permeable(3));
|
||||
let diagonal = |a: usize, b: usize, open: bool| {
|
||||
if open {
|
||||
sample(step(corner(a), adjacency.corners[b]))
|
||||
} else {
|
||||
(light0, shade0)
|
||||
}
|
||||
};
|
||||
let (light02, shade02) = diagonal(0, 2, p2 || p0);
|
||||
let (light03, shade03) = diagonal(0, 3, p3 || p0);
|
||||
let (light12, shade12) = diagonal(1, 2, p2 || p1);
|
||||
let (light13, shade13) = diagonal(1, 3, p3 || p1);
|
||||
let next = step(pos, face);
|
||||
let next_state = state(pad, info, next);
|
||||
let light_center = if shape.cubic || !next_state.solid {
|
||||
coords(pad, next_state, next)
|
||||
} else {
|
||||
coords(pad, own, pos)
|
||||
};
|
||||
let shade_center = if shape.cubic {
|
||||
state(pad, info, base).shade
|
||||
} else {
|
||||
own.shade
|
||||
};
|
||||
let ao = [
|
||||
(shade3 + shade0 + shade03 + shade_center) * 0.25,
|
||||
(shade2 + shade0 + shade02 + shade_center) * 0.25,
|
||||
(shade2 + shade1 + shade12 + shade_center) * 0.25,
|
||||
(shade3 + shade1 + shade13 + shade_center) * 0.25,
|
||||
];
|
||||
let blended = [
|
||||
smooth_blend(light3, light0, light03, light_center),
|
||||
smooth_blend(light2, light0, light02, light_center),
|
||||
smooth_blend(light2, light1, light12, light_center),
|
||||
smooth_blend(light3, light1, light13, light_center),
|
||||
];
|
||||
let mut brightness = [0f32; 4];
|
||||
let mut light = [0u32; 4];
|
||||
for (k, &vertex) in adjacency.remap.iter().enumerate() {
|
||||
if shape.partial {
|
||||
let f = |i: usize| shape.bounds[adjacency.weights[k][i] as usize];
|
||||
let w = [f(0) * f(1), f(2) * f(3), f(4) * f(5), f(6) * f(7)];
|
||||
brightness[vertex] =
|
||||
(ao[0] * w[0] + ao[1] * w[1] + ao[2] * w[2] + ao[3] * w[3]).clamp(0.0, 1.0);
|
||||
light[vertex] = weighted_blend(blended, w);
|
||||
} else {
|
||||
brightness[vertex] = ao[k];
|
||||
light[vertex] = blended[k];
|
||||
}
|
||||
}
|
||||
(brightness, light)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
const fn packed(block: u32, sky: u32) -> u32 {
|
||||
block << 4 | sky << 20
|
||||
}
|
||||
#[test]
|
||||
fn smooth_blend_replaces_dark_samples_with_the_centre() {
|
||||
let center = packed(2, 15);
|
||||
// A zero sample takes the centre; a sky-less sample borrows its sky.
|
||||
let blended = smooth_blend(0, packed(8, 0), packed(4, 15), center);
|
||||
assert_eq!(blended & 0xFF, (32 + 128 + 64 + 32) / 4);
|
||||
assert_eq!(blended >> 16 & 0xFF, 240);
|
||||
// A dark centre leaves samples untouched.
|
||||
assert_eq!(
|
||||
smooth_blend(0, 0, packed(15, 15), packed(1, 1)) & 0xFF,
|
||||
(240 + 16) / 4
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn weighted_blend_narrows_like_java_int_casts() {
|
||||
let c = [packed(15, 15); 4];
|
||||
assert_eq!(weighted_blend(c, [0.25; 4]), packed(15, 15));
|
||||
// Negative weights (geometry past the block) wrap through the 0xFF mask.
|
||||
assert_eq!(
|
||||
weighted_blend([packed(1, 0); 4], [-0.25; 4]) & 0xFF,
|
||||
(-16i32 as u32) & 0xFF
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn colour_arithmetic_matches_argb_helpers() {
|
||||
assert_eq!(gray(1.0), 255);
|
||||
assert_eq!(gray(0.8), 204);
|
||||
assert_eq!(scale(255, 0.5), 127);
|
||||
assert_eq!(scale(gray(0.6), 0.8), 122);
|
||||
assert_eq!(cardinal(true, D::Down), 0.9);
|
||||
assert_eq!(cardinal(false, D::Down), 0.5);
|
||||
}
|
||||
#[test]
|
||||
fn emission_raises_both_channels_and_drops_fractions() {
|
||||
assert_eq!(with_emission(0x0087_0013, 0), 0x0087_0013);
|
||||
assert_eq!(with_emission(0x0087_0013, 3), packed(3, 8));
|
||||
assert_eq!(max_coords(packed(3, 9), packed(7, 2)), packed(7, 9));
|
||||
}
|
||||
#[test]
|
||||
fn quad_shape_classifies_partial_and_cubic_faces() {
|
||||
let full_top = [
|
||||
[0.0, 1.0, 0.0],
|
||||
[0.0, 1.0, 1.0],
|
||||
[1.0, 1.0, 1.0],
|
||||
[1.0, 1.0, 0.0],
|
||||
];
|
||||
let s = shape(&full_top, D::Up, false);
|
||||
assert!(s.cubic && !s.partial);
|
||||
let slab_top = full_top.map(|[x, _, z]| [x, 0.5, z]);
|
||||
let s = shape(&slab_top, D::Up, false);
|
||||
assert!(!s.cubic && !s.partial);
|
||||
assert!(shape(&slab_top, D::Up, true).cubic);
|
||||
let small = slab_top.map(|[x, y, z]| [x * 0.5, y, z]);
|
||||
let s = shape(&small, D::Up, false);
|
||||
assert!(s.partial);
|
||||
assert_eq!(s.bounds[EAST as usize], 0.5);
|
||||
assert_eq!(s.bounds[FLIP_EAST as usize], 0.5);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
//! resource-pack reloads remain separate work.
|
||||
use crate::{Result, sprites::Sprites};
|
||||
use horizon_assets::{
|
||||
bake::{BlockModelTransform, ModelQuad, bake_model_transformed},
|
||||
bake::{BlockModelTransform, ModelQuad, bake_block_model},
|
||||
blockstate::{
|
||||
BlockStateDefinition, Variant, VariantSet,
|
||||
bind::{Properties, PropertySchema, PropertyValues, SelectedModels},
|
||||
@@ -176,7 +176,7 @@ impl StateModels {
|
||||
for (name, turns, lock) in variants {
|
||||
let model = library.resolve(&name)?;
|
||||
let faces: Vec<BakedFace> =
|
||||
bake_model_transformed(&model, BlockModelTransform::new(turns, lock))?
|
||||
bake_block_model(&model, BlockModelTransform::new(turns, lock))?
|
||||
.into_iter()
|
||||
.map(|quad| {
|
||||
let layer = sprites.insert(root, &quad.material.sprite)?;
|
||||
|
||||
@@ -163,6 +163,16 @@ impl FaceVisibility {
|
||||
.get(state.0 as usize)
|
||||
.is_some_and(|s| s.faces[direction as usize] == 1)
|
||||
}
|
||||
/// The state's occlusion face toward `direction` (`getFaceOcclusionShape`) and
|
||||
/// its shared ID: 0 is the empty singleton, 1 the full-block singleton.
|
||||
pub fn occlusion_face(
|
||||
&self,
|
||||
state: BlockStateId,
|
||||
direction: Direction,
|
||||
) -> Option<(u32, &VoxelShape)> {
|
||||
let id = self.states.get(state.0 as usize)?.faces[direction as usize];
|
||||
Some((id, &self.faces[id as usize]))
|
||||
}
|
||||
/// Whether the state's occlusion face toward `direction` is empty.
|
||||
pub fn empty_face(&self, state: BlockStateId, direction: Direction) -> bool {
|
||||
self.states
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
# Section meshing parity
|
||||
|
||||
`tools/test_section_mesh_parity.py` compares the vertices Horizon's section
|
||||
mesher (`crates/horizon-client/src/mesher.rs`, with `mesher/lighting.rs` and
|
||||
`mesher/fluid.rs`) emits with the vertices the pinned client's own renderers
|
||||
emit for the same scenes.
|
||||
|
||||
## What is compared
|
||||
|
||||
- **Vanilla side**: `VanillaSectionMeshOracle` bootstraps the game, binds the
|
||||
prepared block tags, parses the jar's blockstate definitions and block
|
||||
models, and bakes `BlockStateModel`s through the real `ModelDiscovery`,
|
||||
`UnbakedRoot.bake` and `FaceBakery` path. Every texture becomes a real sprite
|
||||
(its PNG from the jar) alone in a unit atlas, so UVs stay in sprite-local
|
||||
[0,1] space; the five fluid sprites share one strip with gaps so the fluid
|
||||
vertex stream still identifies them. A fixed `BlockAndTintGetter` serves the
|
||||
scene's block states, per-cell sky/block light, constant biome colours per
|
||||
`ColorResolver` and the overworld or Nether `CardinalLighting`. Blocks of one
|
||||
section are visited like `SectionCompiler.compile`: fluids through
|
||||
`FluidRenderer.tesselate`, then `RenderShape.MODEL` blocks through
|
||||
`ModelBlockRenderer.tesselateBlock` with smooth lighting on, culling on,
|
||||
cutout leaves, `BlockColors.createDefault()` and `state.getSeed(pos)`.
|
||||
- **Horizon side**: `crates/horizon-client/examples/section_mesh_fixture.rs`
|
||||
loads the prepared resources (`Assets`, `BlockFacts`, `Biomes`,
|
||||
`load_visibility`, `MeshTables`), builds the same blocks and light in real
|
||||
client `Chunk`s (a 3x3 chunk region), sets every biome's colours to the
|
||||
scene constants and runs `Mesher::mesh`.
|
||||
- **Comparison**: quads are matched as multisets per scene, keyed by sprite,
|
||||
render-layer class (translucent vs. solid/cutout) and geometry rounded to
|
||||
1/1000 after binary32 normalisation, with a winding-preserving rotation.
|
||||
Matched quads compare per vertex: positions and UVs within 1e-4, ARGB colour
|
||||
and light coordinates (sky and block, 1/16 steps) exactly.
|
||||
- **Per-state facts**: a second gate compares, for all 35,723 states, the facts
|
||||
the Rust tables derive from prepared resources with the client's accessors:
|
||||
`getShadeBrightness`, `emissiveRendering`, `isSolid`, `isLightPermeable`,
|
||||
`isSolidRender`, `isCollisionShapeFullBlock`, light emission, the water
|
||||
overlay classes (`HalfTransparentBlock`/`LeavesBlock`), tint source counts
|
||||
and `getOffset` at five columns.
|
||||
|
||||
The corpus (94 sections, ~842k quads, ~206k of them fluid quads) has full
|
||||
cubes in open air, corners, cavities and overhangs; slabs, stairs, walls,
|
||||
fences, panes, bars, torches, flowers and grasses with XZ/XYZ offsets, tall
|
||||
plants, tinted blocks (grass, leaves, stems, redstone, lily pad, petals, leaf
|
||||
litter, cauldrons), snow layers, carpets, farmland, paths, hoppers, anvils,
|
||||
chains, lanterns, dripleaf, dripstone; water and lava sources, flowing levels,
|
||||
falling columns, waterlogged blocks, water against glass/leaves/slabs/ice;
|
||||
section edges with neighbours in other chunks and sections; a cave with
|
||||
emissive and light-emitting blocks (magma, glowstone, sea lantern, active
|
||||
sculk sensor, glow lichen); Nether shading; every block's default state; every
|
||||
`RenderShape.MODEL` state of the registry on a sparse grid; and dense random
|
||||
scenes mixing all model states with fluids under propagated or random light.
|
||||
|
||||
## Running
|
||||
|
||||
```sh
|
||||
python3 tools/test_section_mesh_parity.py # full corpus
|
||||
python3 tools/test_section_mesh_parity.py --quick # skip the all-states catalogue
|
||||
python3 tools/test_section_mesh_parity.py --strict # exit 1 on any difference
|
||||
python3 tools/test_section_mesh_parity.py --only fluids
|
||||
```
|
||||
|
||||
It needs the pinned jars (`tools/lab.py prepare`) and prepared client resources
|
||||
(`tools/prepare_native_client.py --prepare`). Outputs, logs and
|
||||
`report.json` go to `target/section-mesh-parity/`; nothing is written under
|
||||
`.local/`. The fixture is built with `--profile fast` and reports its
|
||||
meshing time.
|
||||
|
||||
## Results
|
||||
|
||||
Before the port (commit `2940b5a`, first 18 scenes): 25,391 of 55,017 vanilla
|
||||
quads identical (46%); 7,685 fluid quads missing, 9,231 extra quads, and
|
||||
light/colour differences on most of the rest.
|
||||
|
||||
After: all 841,775 quads of the 94 scenes match and are identical, and all
|
||||
per-state facts match. Meshing cost is unchanged within noise: the fixture
|
||||
meshes the 94 (dense) corpus sections in about 3 ms each with both the old and
|
||||
the ported mesher (`--profile fast`, loaded 24-thread desktop).
|
||||
|
||||
What was ported to get there:
|
||||
|
||||
- `BlockModelLighter`: quad shape (`faceCubic`/`facePartial`), the corner,
|
||||
diagonal and centre samples (diagonals only through light-permeable blocks,
|
||||
the centre from the neighbour unless it is solid-render), shade brightness
|
||||
overrides, emissive full-bright samples, `smoothBlend` (zero samples take the
|
||||
centre, sky-less samples borrow its sky, only when the centre is above 2),
|
||||
the partial-face weights with `smoothWeightedBlend`'s int narrowing, and the
|
||||
vertex remap. The padded section border grew to two blocks because cubic
|
||||
faces sample two blocks out along their normal.
|
||||
- `ModelBlockRenderer`: flat lighting for light-emitting blocks or when the
|
||||
first model part disables AO (culled quads read light from the cull
|
||||
neighbour, others from the neighbour only when flush), `ARGB.gray`/
|
||||
`scaleRGB`/`multiply` integer arithmetic, cardinal shading including
|
||||
`NETHER`, shade-direction overrides, per-element light emission, tint source
|
||||
counts (layer indices past the list are untinted; water and bubble columns
|
||||
are untinted in the world) and `getOffset` for XZ/XYZ blocks.
|
||||
- `FluidRenderer`: face culling against the neighbour's occlusion face shape
|
||||
for the fluid box height, self occlusion, `isSolid` corner heights, the
|
||||
weighted corner averages in vanilla order, the 0.001 insets (also feeding the
|
||||
side faces), `FlowingFluid.getFlow` with `Mth.atan2` and the sine table, the
|
||||
water overlay beside half-transparent and leaf blocks, back faces,
|
||||
`max(self, above)` light, bottom light from below, and cardinal shading.
|
||||
- `UnbakedCuboidGeometry.bake`: elements flat along an axis draw no faces
|
||||
across it (`bake_block_model` in horizon-assets; the raw
|
||||
`bake_model_transformed` used by the model-baking gate is unchanged).
|
||||
|
||||
Exported facts used: `block-behaviours.json` (class chains, `isSolid`, full
|
||||
face sturdiness), `gameplay-facts.json` (`offset` flag, emission, shapes),
|
||||
the `#minecraft:blocks_fluid_flow` tag and the occlusion faces already loaded
|
||||
for face visibility. Offset types and maximum offsets, shade-brightness and
|
||||
emissive overrides are keyed by class or block name and checked by the facts
|
||||
gate.
|
||||
|
||||
## What remains different or untested
|
||||
|
||||
- Biome tint blending: vanilla blends `BiomeManager`'s zoomed biome at each
|
||||
block's own height; Horizon blends its quart biome cells at the section's
|
||||
mid-height. The gate uses one constant colour per resolver, so this is not
|
||||
compared.
|
||||
- Model variant seeds: `DoublePlantBlock`, `DoorBlock` and `AbstractBedBlock`
|
||||
override `getSeed`; Horizon seeds every block from its own position. No
|
||||
vanilla block among those has weighted variants, so output is unaffected.
|
||||
- Settings: only smooth lighting on and cutout ("fancy") leaves are covered;
|
||||
Horizon has no flat-lighting or opaque-leaves modes.
|
||||
- Layers: vanilla's solid and cutout layers are compared as one class because
|
||||
Horizon draws both in its opaque pass.
|
||||
- Not compared: block entities and their renderers, animated sprite frames,
|
||||
translucent sorting, chunk-border light outside loaded chunks and GPU
|
||||
pixels.
|
||||
@@ -0,0 +1,297 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import com.mojang.blaze3d.vertex.QuadInstance;
|
||||
import com.mojang.blaze3d.vertex.VertexConsumer;
|
||||
import com.mojang.serialization.JsonOps;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.client.color.block.BlockColors;
|
||||
import net.minecraft.client.renderer.BiomeColors;
|
||||
import net.minecraft.client.renderer.block.*;
|
||||
import net.minecraft.client.renderer.block.dispatch.*;
|
||||
import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
|
||||
import net.minecraft.client.renderer.texture.*;
|
||||
import net.minecraft.client.resources.metadata.animation.FrameSize;
|
||||
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.*;
|
||||
import net.minecraft.core.*;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.util.StrictJsonParser;
|
||||
import net.minecraft.world.level.CardinalLighting;
|
||||
import net.minecraft.world.level.ColorResolver;
|
||||
import net.minecraft.world.level.EmptyBlockGetter;
|
||||
import net.minecraft.world.level.LightLayer;
|
||||
import net.minecraft.world.level.block.*;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.lighting.LevelLightEngine;
|
||||
import net.minecraft.world.level.material.FluidState;
|
||||
import org.joml.Vector3fc;
|
||||
import static dev.horizonlab.parity.VanillaCuboidModelOracle.map;
|
||||
|
||||
/** Runs the client's own ModelBlockRenderer (smooth lighting on) and FluidRenderer
|
||||
* over small fixed scenes, the way SectionCompiler visits one section, and
|
||||
* records every emitted vertex. Block models are baked from the jar's own
|
||||
* blockstate and model resources; every texture becomes a real sprite alone in
|
||||
* a unit atlas so UVs stay in sprite-local [0,1] space. Fluid sprites share one
|
||||
* strip with gaps so their vertex stream still identifies the sprite. */
|
||||
public final class VanillaSectionMeshOracle {
|
||||
private static final Gson JSON = new GsonBuilder().serializeNulls().create();
|
||||
private static final String[] FLUID_SPRITES = {"minecraft:block/water_still", "minecraft:block/water_flow",
|
||||
"minecraft:block/water_overlay", "minecraft:block/lava_still", "minecraft:block/lava_flow"};
|
||||
private static final int STRIP = 2 * FLUID_SPRITES.length;
|
||||
|
||||
private static final class Sprite extends TextureAtlasSprite {
|
||||
Sprite(SpriteContents contents, int slots, int slot) {
|
||||
super(TextureAtlas.LOCATION_BLOCKS, contents, contents.width() * slots, contents.height(), contents.width() * slot, 0, 0);
|
||||
}
|
||||
}
|
||||
private static final Map<Identifier, TextureAtlasSprite> SPRITES = new HashMap<>();
|
||||
private static SpriteContents contents(Identifier id) throws IOException {
|
||||
var path = "/assets/" + id.getNamespace() + "/textures/" + id.getPath() + ".png";
|
||||
try (var input = VanillaSectionMeshOracle.class.getResourceAsStream(path)) {
|
||||
NativeImage image = input == null ? new NativeImage(16, 16, true) : NativeImage.read(input);
|
||||
int size = Math.min(image.getWidth(), image.getHeight());
|
||||
return new SpriteContents(id, new FrameSize(image.getWidth(), size), image);
|
||||
}
|
||||
}
|
||||
private static TextureAtlasSprite sprite(Identifier id) {
|
||||
return SPRITES.computeIfAbsent(id, key -> {
|
||||
try {
|
||||
int slot = Arrays.asList(FLUID_SPRITES).indexOf(key.toString());
|
||||
return slot < 0 ? new Sprite(contents(key), 1, 0) : new Sprite(contents(key), STRIP, 2 * slot);
|
||||
} catch (IOException error) { throw new UncheckedIOException(error); }
|
||||
});
|
||||
}
|
||||
/** Hands out the unit-atlas sprite named by each material. */
|
||||
private static final class Materials extends MaterialBaker {
|
||||
Materials(SpriteLoader.Preparations atlas) { super(atlas, atlas); }
|
||||
@Override public Material.Baked get(Material material, ModelDebugName name) {
|
||||
return new Material.Baked(sprite(material.sprite()), material.forceTranslucent());
|
||||
}
|
||||
}
|
||||
private static final class Baker implements ModelBaker {
|
||||
final Map<Identifier, ResolvedModel> resolved; final ResolvedModel missing; final MaterialBaker materials;
|
||||
final Map<SharedOperationKey<?>, Object> cache = new HashMap<>();
|
||||
Baker(Map<Identifier, ResolvedModel> resolved, ResolvedModel missing, MaterialBaker materials) {
|
||||
this.resolved = resolved; this.missing = missing; this.materials = materials;
|
||||
}
|
||||
public ResolvedModel getModel(Identifier id) { return resolved.getOrDefault(id, missing); }
|
||||
public BlockStateModelPart missingBlockModelPart() { throw new AssertionError("missing block model part"); }
|
||||
public MaterialBaker materials() { return materials; }
|
||||
public ModelBaker.Interner interner() {
|
||||
return new ModelBaker.Interner() {
|
||||
public Vector3fc vector(Vector3fc vector) { return vector; }
|
||||
public BakedQuad.MaterialInfo materialInfo(BakedQuad.MaterialInfo value) { return value; }
|
||||
};
|
||||
}
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T compute(SharedOperationKey<T> key) {
|
||||
var value = cache.get(key);
|
||||
if (value == null) { value = key.compute(this); cache.put(key, value); }
|
||||
return (T) value;
|
||||
}
|
||||
}
|
||||
private static String resource(String path) throws IOException {
|
||||
try (var input = VanillaSectionMeshOracle.class.getResourceAsStream(path)) {
|
||||
return input == null ? null : new String(input.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
/** Real blockstate definitions and models for the requested blocks. */
|
||||
private static final class Models {
|
||||
final Map<BlockState, BlockStateModel.UnbakedRoot> roots = new HashMap<>();
|
||||
final Map<BlockState, BlockStateModel> baked = new HashMap<>();
|
||||
final Baker baker;
|
||||
Models(Set<Block> blocks, MaterialBaker materials) throws IOException {
|
||||
var unbaked = new HashMap<Identifier, UnbakedModel>();
|
||||
for (var block : blocks) {
|
||||
var id = BuiltInRegistries.BLOCK.getKey(block);
|
||||
var raw = resource("/assets/" + id.getNamespace() + "/blockstates/" + id.getPath() + ".json");
|
||||
if (raw == null) continue;
|
||||
var definition = BlockStateModelDispatcher.CODEC.parse(JsonOps.INSTANCE, StrictJsonParser.parse(raw)).getOrThrow();
|
||||
roots.putAll(definition.instantiate(block.getStateDefinition(), id::toString));
|
||||
}
|
||||
var pending = new ArrayList<Identifier>();
|
||||
for (var root : new HashSet<>(roots.values())) root.resolveDependencies(pending::add);
|
||||
for (int i = 0; i < pending.size(); i++) {
|
||||
var id = pending.get(i);
|
||||
if (unbaked.containsKey(id)) continue;
|
||||
var raw = resource("/assets/" + id.getNamespace() + "/models/" + id.getPath() + ".json");
|
||||
if (raw == null) continue;
|
||||
var model = CuboidModel.fromStream(new StringReader(raw));
|
||||
unbaked.put(id, model);
|
||||
if (model.parent() != null) pending.add(model.parent());
|
||||
}
|
||||
var discovery = new ModelDiscovery(unbaked, MissingCuboidModel.missingModel());
|
||||
discovery.addRoot(resolver -> { for (var id : unbaked.keySet()) resolver.markDependency(id); });
|
||||
var resolved = discovery.resolve();
|
||||
baker = new Baker(resolved, discovery.missingModel(), materials);
|
||||
}
|
||||
BlockStateModel get(BlockState state) {
|
||||
return baked.computeIfAbsent(state, s -> Objects.requireNonNull(roots.get(s), () -> "no model for " + s).bake(s, baker));
|
||||
}
|
||||
}
|
||||
private static long key(int x, int y, int z) { return BlockPos.asLong(x, y, z); }
|
||||
/** A fixed region: listed blocks over air, listed light over a default. */
|
||||
private static final class Scene implements BlockAndTintGetter {
|
||||
final Map<Long, BlockState> blocks = new HashMap<>();
|
||||
final Map<Long, int[]> light = new HashMap<>();
|
||||
int[] defaultLight; boolean nether; int grass, foliage, dry, water;
|
||||
public CardinalLighting cardinalLighting() { return nether ? CardinalLighting.NETHER : CardinalLighting.DEFAULT; }
|
||||
public LevelLightEngine getLightEngine() { return LevelLightEngine.EMPTY; }
|
||||
public int getBrightness(LightLayer layer, BlockPos pos) {
|
||||
var value = light.getOrDefault(pos.asLong(), defaultLight);
|
||||
return layer == LightLayer.SKY ? value[0] : value[1];
|
||||
}
|
||||
public int getBlockTint(BlockPos pos, ColorResolver resolver) {
|
||||
int rgb = resolver == BiomeColors.GRASS_COLOR_RESOLVER ? grass : resolver == BiomeColors.FOLIAGE_COLOR_RESOLVER ? foliage
|
||||
: resolver == BiomeColors.DRY_FOLIAGE_COLOR_RESOLVER ? dry : resolver == BiomeColors.WATER_COLOR_RESOLVER ? water : -1;
|
||||
if (rgb == -1) throw new AssertionError("unexpected colour resolver");
|
||||
return 0xFF000000 | rgb;
|
||||
}
|
||||
public BlockEntity getBlockEntity(BlockPos pos) { return null; }
|
||||
public BlockState getBlockState(BlockPos pos) { return blocks.getOrDefault(pos.asLong(), Blocks.AIR.defaultBlockState()); }
|
||||
public FluidState getFluidState(BlockPos pos) { return getBlockState(pos).getFluidState(); }
|
||||
public int getHeight() { return 384; }
|
||||
public int getMinY() { return -64; }
|
||||
}
|
||||
private static final class Recorder {
|
||||
final List<Object> quads = new ArrayList<>();
|
||||
List<Object> pending; BlockPos block; String kind, layer, sprite;
|
||||
void vertex(float x, float y, float z, int color, float u, float v, int light) {
|
||||
if (pending == null) pending = new ArrayList<>();
|
||||
pending.add(new Object[]{x, y, z, u, v, color, light});
|
||||
if (pending.size() == 4) {
|
||||
quads.add(map("block", new int[]{block.getX(), block.getY(), block.getZ()}, "kind", kind, "layer", layer, "sprite", sprite, "vertices", pending));
|
||||
pending = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
private static String layer(ChunkSectionLayer layer) { return layer.name().toLowerCase(Locale.ROOT); }
|
||||
private static Object scene(JsonObject row, Models models, FluidStateModelSet fluids) {
|
||||
var scene = new Scene();
|
||||
var light = row.getAsJsonArray("light");
|
||||
scene.defaultLight = new int[]{light.get(0).getAsInt(), light.get(1).getAsInt()};
|
||||
scene.nether = row.get("nether").getAsBoolean();
|
||||
var colors = row.getAsJsonObject("colors");
|
||||
scene.grass = colors.get("grass").getAsInt(); scene.foliage = colors.get("foliage").getAsInt();
|
||||
scene.dry = colors.get("dry_foliage").getAsInt(); scene.water = colors.get("water").getAsInt();
|
||||
for (var item : row.getAsJsonArray("blocks")) {
|
||||
var b = item.getAsJsonArray();
|
||||
scene.blocks.put(key(b.get(0).getAsInt(), b.get(1).getAsInt(), b.get(2).getAsInt()), Block.stateById(b.get(3).getAsInt()));
|
||||
}
|
||||
for (var item : row.getAsJsonArray("lights")) {
|
||||
var l = item.getAsJsonArray();
|
||||
scene.light.put(key(l.get(0).getAsInt(), l.get(1).getAsInt(), l.get(2).getAsInt()), new int[]{l.get(3).getAsInt(), l.get(4).getAsInt()});
|
||||
}
|
||||
var recorder = new Recorder();
|
||||
BlockModelLighter.enableCaching();
|
||||
var renderer = new ModelBlockRenderer(true, true, BlockColors.createDefault());
|
||||
var fluidRenderer = new FluidRenderer(fluids);
|
||||
BlockQuadOutput output = (x, y, z, quad, instance) -> {
|
||||
recorder.kind = "model"; recorder.layer = layer(quad.materialInfo().layer());
|
||||
recorder.sprite = quad.materialInfo().sprite().contents().name().toString();
|
||||
int emission = quad.materialInfo().lightEmission();
|
||||
int slot = Arrays.asList(FLUID_SPRITES).indexOf(recorder.sprite);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
var p = quad.position(i); long uv = quad.packedUV(i);
|
||||
float u = Float.intBitsToFloat((int) (uv >>> 32));
|
||||
recorder.vertex(p.x() + x, p.y() + y, p.z() + z, instance.getColor(i),
|
||||
slot < 0 ? u : u * STRIP - 2 * slot, Float.intBitsToFloat((int) uv), instance.getLightCoordsWithEmission(i, emission));
|
||||
}
|
||||
};
|
||||
int baseY = row.get("section_y").getAsInt() * 16;
|
||||
for (var pos : BlockPos.betweenClosed(0, baseY, 0, 15, baseY + 15, 15)) {
|
||||
var state = scene.getBlockState(pos);
|
||||
if (state.isAir()) continue;
|
||||
recorder.block = pos.immutable();
|
||||
var fluid = state.getFluidState();
|
||||
if (!fluid.isEmpty()) {
|
||||
fluidRenderer.tesselate(scene, pos, sectionLayer -> new VertexConsumer() {
|
||||
public void addVertex(float x, float y, float z, int color, float u, float v, int overlay, int light, float nx, float ny, float nz) {
|
||||
int slot = (int) Math.floor(u * STRIP / 2.0f);
|
||||
recorder.kind = "fluid"; recorder.layer = layer(sectionLayer); recorder.sprite = FLUID_SPRITES[slot];
|
||||
recorder.vertex(x, y, z, color, u * STRIP - 2 * slot, v, light);
|
||||
}
|
||||
public VertexConsumer addVertex(float x, float y, float z) { throw new AssertionError(); }
|
||||
public VertexConsumer setColor(int r, int g, int b, int a) { throw new AssertionError(); }
|
||||
public VertexConsumer setColor(int color) { throw new AssertionError(); }
|
||||
public VertexConsumer setUv(float u, float v) { throw new AssertionError(); }
|
||||
public VertexConsumer setUv1(int u, int v) { throw new AssertionError(); }
|
||||
public VertexConsumer setUv2(int u, int v) { throw new AssertionError(); }
|
||||
public VertexConsumer setUv3(float u, float v) { throw new AssertionError(); }
|
||||
public VertexConsumer setNormal(float x, float y, float z) { throw new AssertionError(); }
|
||||
public VertexConsumer setLineWidth(float width) { throw new AssertionError(); }
|
||||
}, state, fluid);
|
||||
}
|
||||
if (state.getRenderShape() == RenderShape.MODEL) {
|
||||
renderer.tesselateBlock(ModelBlockRenderer.forceOpaque(true, state) ? (x, y, z, quad, instance) -> {
|
||||
throw new AssertionError("cutout leaves are enabled");
|
||||
} : output, SectionPos.sectionRelative(pos.getX()), SectionPos.sectionRelative(pos.getY()), SectionPos.sectionRelative(pos.getZ()),
|
||||
scene, pos, state, models.get(state), state.getSeed(pos));
|
||||
}
|
||||
}
|
||||
BlockModelLighter.clearCache();
|
||||
if (recorder.pending != null) throw new AssertionError("partial quad");
|
||||
return map("name", row.get("name").getAsString(), "quads", recorder.quads);
|
||||
}
|
||||
private static BlockColors COLORS;
|
||||
/** Per-state facts the Rust mesher derives from prepared resources. */
|
||||
private static Object facts(BlockState state, int id) {
|
||||
var level = EmptyBlockGetter.INSTANCE;
|
||||
var offsets = new ArrayList<Object>();
|
||||
if (state.hasOffsetFunction()) {
|
||||
for (var p : new BlockPos[]{new BlockPos(0, 0, 0), new BlockPos(5, 7, -3), new BlockPos(-17, 70, 31), new BlockPos(123, -40, -456), new BlockPos(9, 1, 2)}) {
|
||||
var o = state.getOffset(p);
|
||||
offsets.add(new double[]{o.x, o.y, o.z});
|
||||
}
|
||||
}
|
||||
var block = state.getBlock();
|
||||
return map("id", id, "shade", state.getShadeBrightness(level, BlockPos.ZERO), "emissive", state.emissiveRendering(),
|
||||
"legacy_solid", state.isSolid(), "light_permeable", state.isLightPermeable(), "solid_render", state.isSolidRender(),
|
||||
"full_collision", state.isCollisionShapeFullBlock(level, BlockPos.ZERO), "emission", state.getLightEmission(),
|
||||
"overlay", block instanceof HalfTransparentBlock || block instanceof LeavesBlock,
|
||||
"tint_sources", COLORS.getTintSources(state).size(), "offsets", offsets);
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(Path.of(args[2]).resolve("block-tags.json"))).getAsJsonObject());
|
||||
LeavesBlock.setCutoutLeaves(true);
|
||||
COLORS = BlockColors.createDefault();
|
||||
if (args[0].equals("facts")) {
|
||||
try (var output = Files.newBufferedWriter(Path.of(args[1]))) {
|
||||
int id = 0;
|
||||
for (var state : Block.BLOCK_STATE_REGISTRY) {
|
||||
if (Block.getId(state) != id) throw new AssertionError("state registry order");
|
||||
output.write(JSON.toJson(facts(state, id++))); output.newLine();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
var rows = new ArrayList<JsonObject>();
|
||||
try (var input = Files.newBufferedReader(Path.of(args[0]))) {
|
||||
for (String line; (line = input.readLine()) != null; ) rows.add(JsonParser.parseString(line).getAsJsonObject());
|
||||
}
|
||||
var blocks = new HashSet<Block>();
|
||||
for (var row : rows) for (var item : row.getAsJsonArray("blocks")) blocks.add(Block.stateById(item.getAsJsonArray().get(3).getAsInt()).getBlock());
|
||||
var missingContents = new SpriteContents(Identifier.parse("minecraft:missingno"), new FrameSize(16, 16), new NativeImage(16, 16, true));
|
||||
var missing = new Sprite(missingContents, 1, 0);
|
||||
var atlas = new SpriteLoader.Preparations(16, 16, 0, missing, Map.of(), CompletableFuture.completedFuture(null));
|
||||
var materials = new Materials(atlas);
|
||||
var models = new Models(blocks, materials);
|
||||
var fluidModels = FluidStateModelSet.bake(materials);
|
||||
var fluids = new FluidStateModelSet(fluidModels, fluidModels.values().iterator().next());
|
||||
try (var output = Files.newBufferedWriter(Path.of(args[1]))) {
|
||||
for (var row : rows) { output.write(JSON.toJson(scene(row, models, fluids))); output.newLine(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare Horizon's section mesher with the client's own ModelBlockRenderer and FluidRenderer.
|
||||
|
||||
Both sides mesh the same scenes (block states by registry ID, per-cell sky/block
|
||||
light, constant biome colours, overworld or Nether cardinal lighting). The Java
|
||||
oracle runs vanilla smooth lighting (AO on, cutout leaves) block by block the way
|
||||
SectionCompiler visits a section; the Rust fixture runs ``Mesher::mesh`` on real
|
||||
client chunks. Quads are compared as multisets keyed by sprite, render layer class
|
||||
and rounded geometry; matched quads then compare UVs, ARGB colours and light
|
||||
coordinates per vertex. A second gate compares the per-state facts the Rust mesher
|
||||
derives (shade brightness, emissive rendering, legacy solidity, offsets, ...)
|
||||
with the client's own state accessors for every registry state.
|
||||
"""
|
||||
import argparse
|
||||
from collections import Counter, defaultdict
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import random
|
||||
import struct
|
||||
import subprocess
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
import test_model_baking_parity as baking
|
||||
|
||||
BUILD = lab.ROOT / 'target/section-mesh-parity'
|
||||
SECTION_Y = 0
|
||||
COLORS = {'grass': 0x91BD59, 'foliage': 0x77AB2F, 'dry_foliage': 0xA88B5E, 'water': 0x3F76E4}
|
||||
POSITION_TOLERANCE = 1e-4
|
||||
UV_TOLERANCE = 1e-4
|
||||
|
||||
|
||||
class States:
|
||||
"""Registry state IDs by name and properties, from the prepared registry facts."""
|
||||
def __init__(self, resources):
|
||||
facts = json.loads((resources / 'facts.json').read_text())
|
||||
self.defaults = facts['defaults']
|
||||
self.properties = [entry[4].get('properties', {}) for entry in facts['states']]
|
||||
self.names = [entry[0] for entry in facts['states']]
|
||||
self.by_name = defaultdict(list)
|
||||
for index, name in enumerate(self.names):
|
||||
self.by_name[name].append(index)
|
||||
gameplay = json.loads((resources / 'gameplay-facts.json').read_text())['states']
|
||||
self.dampening = [s['dampening'] for s in gameplay]
|
||||
self.emission = [s['emission'] for s in gameplay]
|
||||
self.opaque = [s['solid_render'] for s in gameplay]
|
||||
self.render_shape = [s['render_shape'] for s in gameplay]
|
||||
|
||||
def __call__(self, name, **properties):
|
||||
name = name if ':' in name else 'minecraft:' + name
|
||||
wanted = dict(self.properties[self.defaults[name]])
|
||||
for key, value in properties.items():
|
||||
key = key.rstrip('_')
|
||||
if key not in wanted:
|
||||
raise KeyError(f'{name} has no property {key}')
|
||||
wanted[key] = str(value).lower()
|
||||
for index in self.by_name[name]:
|
||||
if self.properties[index] == wanted:
|
||||
return index
|
||||
raise KeyError(f'no state {name} {wanted}')
|
||||
|
||||
|
||||
class Scene:
|
||||
def __init__(self, states, name, nether=False):
|
||||
self.states, self.name, self.nether = states, name, nether
|
||||
self.blocks = {}
|
||||
self.light_override = {}
|
||||
self.noise = None
|
||||
|
||||
def put(self, x, y, z, name, **properties):
|
||||
self.blocks[(x, y, z)] = name if isinstance(name, int) else self.states(name, **properties)
|
||||
|
||||
def fill(self, x0, y0, z0, x1, y1, z1, name, **properties):
|
||||
state = self.states(name, **properties)
|
||||
for x in range(x0, x1 + 1):
|
||||
for y in range(y0, y1 + 1):
|
||||
for z in range(z0, z1 + 1):
|
||||
self.blocks[(x, y, z)] = state
|
||||
|
||||
def floor(self, y=3, name='stone'):
|
||||
self.fill(-1, y, -1, 16, y, 16, name)
|
||||
|
||||
def lights(self):
|
||||
"""Simple deterministic propagation: straight-down skylight, -1 per step
|
||||
sideways, dampening per cell; emitters spread block light the same way."""
|
||||
lo, hi = -2, 17
|
||||
base = SECTION_Y * 16
|
||||
cells = [(x, y, z) for x in range(lo, hi + 1) for y in range(base + lo, base + hi + 1) for z in range(lo, hi + 1)]
|
||||
damp = {c: self.states.dampening[self.blocks.get(c, 0)] for c in cells}
|
||||
opaque = {c: self.states.opaque[self.blocks.get(c, 0)] and damp[c] > 0 for c in cells}
|
||||
def spread(seeds, straight_down):
|
||||
level = {c: 0 for c in cells}
|
||||
queue = []
|
||||
for c, v in seeds:
|
||||
if v > level[c]:
|
||||
level[c] = v
|
||||
queue.append(c)
|
||||
while queue:
|
||||
nxt = []
|
||||
for c in queue:
|
||||
v = level[c]
|
||||
for d in [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]:
|
||||
n = (c[0] + d[0], c[1] + d[1], c[2] + d[2])
|
||||
if n not in level or opaque[n]:
|
||||
continue
|
||||
loss = 0 if straight_down and d == (0, -1, 0) and v == 15 and damp[n] == 0 else 1
|
||||
w = v - loss - damp[n]
|
||||
if w > level[n]:
|
||||
level[n] = w
|
||||
nxt.append(n)
|
||||
queue = nxt
|
||||
return level
|
||||
top = base + hi
|
||||
sky = spread([((x, top, z), 15) for x in range(lo, hi + 1) for z in range(lo, hi + 1) if not opaque[(x, top, z)]], True)
|
||||
block = spread([(c, self.states.emission[self.blocks.get(c, 0)]) for c in cells], False)
|
||||
rng = random.Random(self.noise) if self.noise is not None else None
|
||||
result = []
|
||||
for c in cells:
|
||||
s, b = sky[c], block[c]
|
||||
if rng is not None:
|
||||
s, b = rng.randrange(16), rng.randrange(16)
|
||||
s, b = self.light_override.get(c, (s, b))
|
||||
if (s, b) != (15, 0):
|
||||
result.append([*c, s, b])
|
||||
return result
|
||||
|
||||
def row(self):
|
||||
return {'name': self.name, 'nether': self.nether, 'section_y': SECTION_Y, 'colors': COLORS, 'light': [15, 0],
|
||||
'blocks': [[*p, s] for p, s in sorted(self.blocks.items())], 'lights': self.lights()}
|
||||
|
||||
|
||||
def corpus(states, full=True):
|
||||
scenes = []
|
||||
def scene(name, **kwargs):
|
||||
s = Scene(states, name, **kwargs)
|
||||
scenes.append(s)
|
||||
return s
|
||||
# Full cubes: open air, corners, cavities, overhangs and steps for AO.
|
||||
s = scene('cubes_open')
|
||||
s.put(8, 8, 8, 'stone')
|
||||
s.put(3, 3, 3, 'grass_block')
|
||||
s = scene('cubes_corners')
|
||||
s.floor(3)
|
||||
s.fill(0, 4, 0, 15, 7, 0, 'stone')
|
||||
s.fill(0, 4, 0, 0, 7, 15, 'cobblestone')
|
||||
s.fill(4, 4, 4, 6, 4, 6, 'oak_planks')
|
||||
s.put(5, 5, 5, 'stone')
|
||||
s.fill(9, 4, 9, 12, 6, 12, 'stone')
|
||||
s.put(10, 6, 10, 'air')
|
||||
s.put(11, 5, 10, 'air')
|
||||
s.put(10, 5, 10, 'air')
|
||||
s.fill(2, 8, 2, 6, 8, 6, 'stone')
|
||||
s.put(13, 4, 2, 'glass')
|
||||
s.put(13, 4, 3, 'stone')
|
||||
s.put(14, 4, 2, 'oak_leaves')
|
||||
s.put(14, 5, 2, 'grass_block')
|
||||
s.put(12, 4, 14, 'soul_sand')
|
||||
s.put(13, 4, 14, 'mud')
|
||||
s.put(14, 4, 14, 'barrier')
|
||||
s.put(12, 5, 14, 'grass_block')
|
||||
s.put(13, 5, 14, 'grass_block')
|
||||
s.put(14, 5, 14, 'snow', layers=8)
|
||||
s.put(15, 5, 14, 'snow', layers=4)
|
||||
s = scene('cave')
|
||||
s.fill(-1, 0, -1, 16, 15, 16, 'stone')
|
||||
s.fill(2, 3, 2, 13, 9, 13, 'air')
|
||||
s.fill(5, 3, 5, 9, 3, 9, 'water')
|
||||
s.put(4, 4, 4, 'torch')
|
||||
s.put(12, 3, 12, 'glowstone')
|
||||
s.put(3, 3, 12, 'magma_block')
|
||||
s.put(12, 3, 3, 'sea_lantern')
|
||||
s.put(7, 9, 7, 'shroomlight')
|
||||
s.put(10, 4, 4, 'lantern')
|
||||
s.put(2, 5, 7, 'wall_torch', facing='east')
|
||||
s.put(6, 4, 11, 'redstone_wire', power=15)
|
||||
s.put(7, 4, 11, 'redstone_wire', power=7)
|
||||
s.put(8, 4, 11, 'redstone_wire', power=0)
|
||||
s.put(6, 3, 11, 'stone')
|
||||
s.put(9, 4, 12, 'sculk_sensor', sculk_sensor_phase='active')
|
||||
s.put(10, 4, 12, 'sculk_sensor')
|
||||
s.put(11, 4, 12, 'glow_lichen', down=True)
|
||||
# Shapes on a floor, against walls and in the open.
|
||||
s = scene('shapes')
|
||||
s.floor(3)
|
||||
s.fill(-1, 4, 15, 16, 7, 16, 'stone')
|
||||
x = 0
|
||||
for name, props in [('stone_slab', {'type': 'bottom'}), ('stone_slab', {'type': 'top'}), ('stone_slab', {'type': 'double'}),
|
||||
('oak_stairs', {}), ('oak_stairs', {'facing': 'east', 'half': 'top'}), ('oak_stairs', {'shape': 'inner_left'}),
|
||||
('oak_stairs', {'facing': 'south', 'shape': 'outer_right'}), ('cobblestone_wall', {'north': 'low', 'up': True}),
|
||||
('oak_fence', {'north': True, 'east': True}), ('glass_pane', {'north': True, 'south': True}),
|
||||
('iron_bars', {'east': True, 'west': True}), ('torch', {}), ('poppy', {}), ('dandelion', {}),
|
||||
('short_grass', {}), ('fern', {})]:
|
||||
s.put(x, 4, 7, name, **props)
|
||||
s.put(x, 4, 14, name, **props)
|
||||
x += 1
|
||||
x = 0
|
||||
for name, props in [('tall_grass', {'half': 'lower'}), ('large_fern', {'half': 'lower'}), ('sunflower', {'half': 'lower'}),
|
||||
('grass_block', {}), ('oak_leaves', {}), ('spruce_leaves', {}), ('birch_leaves', {}), ('snow', {'layers': 1}),
|
||||
('snow', {'layers': 7}), ('white_carpet', {}), ('farmland', {}), ('dirt_path', {}), ('cauldron', {}),
|
||||
('water_cauldron', {'level': 3}), ('hopper', {}), ('anvil', {})]:
|
||||
s.put(x, 4, 4, name, **props)
|
||||
if name in ('tall_grass', 'large_fern', 'sunflower'):
|
||||
s.put(x, 5, 4, name, half='upper')
|
||||
x += 1
|
||||
x = 0
|
||||
for name, props in [('iron_chain', {}), ('iron_chain', {'axis': 'x'}), ('lantern', {}), ('lantern', {'hanging': True}),
|
||||
('soul_lantern', {}), ('lily_pad', {}), ('vine', {'north': True}), ('sugar_cane', {}), ('pink_petals', {'flower_amount': 4}),
|
||||
('melon_stem', {'age': 5}), ('attached_pumpkin_stem', {}), ('leaf_litter', {'segment_amount': 3}),
|
||||
('small_dripleaf', {}), ('pointed_dripstone', {}), ('bamboo', {}), ('brewing_stand', {})]:
|
||||
s.put(x, 4, 10, name, **props)
|
||||
x += 1
|
||||
s.put(15, 8, 10, 'stone')
|
||||
s.put(3, 7, 10, 'stone')
|
||||
s.put(2, 5, 10, 'stone')
|
||||
s.put(15, 4, 1, 'scaffolding')
|
||||
# Fluids: sources, flowing levels, falling columns, mixed neighbours, waterlogging.
|
||||
s = scene('fluids')
|
||||
s.floor(2)
|
||||
s.fill(0, 3, 0, 4, 3, 4, 'water')
|
||||
for i, level in enumerate([1, 2, 3, 4, 5, 6, 7]):
|
||||
s.put(5 + i, 3, 2, 'water', level=level)
|
||||
s.put(5 + i, 3, 3, 'water', level=8 - level)
|
||||
s.put(5 + i, 3, 6, 'lava', level=level)
|
||||
s.put(2, 4, 2, 'water', level=8)
|
||||
s.put(2, 5, 2, 'water', level=8)
|
||||
s.put(13, 3, 3, 'glass')
|
||||
s.put(12, 4, 3, 'oak_leaves')
|
||||
s.put(4, 4, 4, 'stone_slab', type='bottom', waterlogged=True)
|
||||
s.put(4, 4, 3, 'oak_stairs', waterlogged=True)
|
||||
s.put(3, 4, 4, 'oak_fence', waterlogged=True)
|
||||
s.put(1, 4, 1, 'ice')
|
||||
s.fill(0, 3, 8, 3, 3, 11, 'lava')
|
||||
s.put(1, 4, 9, 'lava', level=8)
|
||||
s.put(2, 4, 10, 'stone')
|
||||
s.fill(8, 3, 9, 12, 5, 13, 'water')
|
||||
s.put(10, 6, 11, 'water', level=3)
|
||||
s.put(9, 6, 11, 'oak_slab', type='top')
|
||||
s.put(11, 6, 11, 'glass')
|
||||
s.put(10, 6, 12, 'stone')
|
||||
s.put(13, 4, 11, 'kelp')
|
||||
s.put(14, 3, 11, 'seagrass')
|
||||
s.put(15, 3, 13, 'water', level=2)
|
||||
s.put(15, 4, 14, 'water', level=9)
|
||||
s.put(15, 3, 15, 'stone_slab', type='top')
|
||||
# Section edges with neighbours in other chunks and sections.
|
||||
s = scene('edges')
|
||||
for x in [0, 15]:
|
||||
for y in [0, 15]:
|
||||
for z in [0, 15]:
|
||||
s.put(x, y, z, 'stone')
|
||||
s.put(x + (-1 if x == 0 else 1), y, z, 'stone')
|
||||
s.put(x, y + (-1 if y == 0 else 1), z, 'dirt')
|
||||
s.put(7, 15, 7, 'water')
|
||||
s.put(7, 16, 7, 'water')
|
||||
s.put(8, 0, 8, 'water', level=3)
|
||||
s.put(8, -1, 8, 'stone')
|
||||
s.put(-1, 7, 7, 'water')
|
||||
s.put(0, 7, 7, 'water', level=2)
|
||||
s.put(16, 7, 7, 'oak_leaves')
|
||||
s.put(15, 7, 7, 'oak_leaves')
|
||||
# Every block with a model, default state, on a sparse grid.
|
||||
model_blocks = sorted(name for name, default in states.defaults.items() if states.render_shape[default] == 'MODEL'
|
||||
and name not in ('minecraft:air', 'minecraft:cave_air', 'minecraft:void_air'))
|
||||
per_scene = 8 * 8 * 8
|
||||
for chunk in range(0, len(model_blocks), per_scene):
|
||||
s = scene(f'catalog_{chunk // per_scene}')
|
||||
for i, name in enumerate(model_blocks[chunk:chunk + per_scene]):
|
||||
s.put(i % 8 * 2, i // 64 * 2, i // 8 % 8 * 2, states.defaults[name])
|
||||
# Every model state (rotations, multipart, UV lock, waterlogging) on a sparse grid.
|
||||
air = {'minecraft:air', 'minecraft:cave_air', 'minecraft:void_air'}
|
||||
model_states = [i for i, name in enumerate(states.names) if states.render_shape[i] == 'MODEL' and name not in air]
|
||||
if full:
|
||||
for chunk in range(0, len(model_states), per_scene):
|
||||
s = scene(f'states_{chunk // per_scene}')
|
||||
for i, state in enumerate(model_states[chunk:chunk + per_scene]):
|
||||
s.put(i % 8 * 2, i // 64 * 2, i // 8 % 8 * 2, state)
|
||||
# Dense random states from the whole registry packed against each other and fluids.
|
||||
fluids = [states('water'), states('lava'), states('water', level=3), states('water', level=9), states('lava', level=4)]
|
||||
for seed in range(6 if full else 2):
|
||||
rng = random.Random(0x44454E53 + seed)
|
||||
s = scene(f'dense_{seed}', nether=seed == 5)
|
||||
for x in range(-1, 17):
|
||||
for y in range(-1, 17):
|
||||
for z in range(-1, 17):
|
||||
roll = rng.random()
|
||||
if roll < 0.45:
|
||||
s.put(x, y, z, rng.choice(model_states))
|
||||
elif roll < 0.6:
|
||||
s.put(x, y, z, rng.choice(fluids))
|
||||
if seed % 2:
|
||||
s.noise = seed
|
||||
# Random dense scenes over a palette, with structured and noisy light.
|
||||
palette = ['stone', 'glass', 'oak_leaves', 'grass_block', 'water', 'lava', 'oak_slab', 'oak_stairs', 'torch', 'poppy',
|
||||
'short_grass', 'glowstone', 'oak_fence', 'snow', 'white_carpet', 'magma_block', 'soul_sand', 'ice', 'farmland', 'dirt_path']
|
||||
for seed in range(8):
|
||||
rng = random.Random(0x4D455348 + seed)
|
||||
s = scene(f'random_{seed}', nether=seed % 4 == 3)
|
||||
for _ in range(900):
|
||||
name = rng.choice(palette)
|
||||
ids = states.by_name['minecraft:' + name]
|
||||
s.put(rng.randrange(-1, 17), rng.randrange(-1, 17), rng.randrange(-1, 17), rng.choice(ids))
|
||||
if seed % 2:
|
||||
s.noise = seed
|
||||
s = scene('cubes_nether', nether=True)
|
||||
s.floor(3, 'netherrack')
|
||||
s.fill(4, 4, 4, 6, 6, 6, 'nether_bricks')
|
||||
s.fill(8, 4, 8, 10, 4, 10, 'lava')
|
||||
s.put(12, 4, 12, 'glowstone')
|
||||
return scenes
|
||||
|
||||
|
||||
def f32(value):
|
||||
"""Both sides emit binary32 values; Java prints them shortest-form, so parse back to the same float."""
|
||||
return struct.unpack('<f', struct.pack('<f', value))[0]
|
||||
|
||||
|
||||
def quad_key(quad):
|
||||
vertices = quad['vertices']
|
||||
rounded = [tuple(round(f32(v[i]) * 1000) for i in range(3)) for v in vertices]
|
||||
rotation = min(range(4), key=lambda r: rounded[r:] + rounded[:r])
|
||||
layer = 'translucent' if quad['layer'] == 'translucent' else 'opaque'
|
||||
return (quad['sprite'], layer, tuple(rounded[rotation:] + rounded[:rotation])), rotation
|
||||
|
||||
|
||||
def channels(color):
|
||||
color &= 0xFFFFFFFF
|
||||
return [color >> 16 & 255, color >> 8 & 255, color & 255, color >> 24]
|
||||
|
||||
|
||||
def light(coords):
|
||||
return [coords >> 16 & 0xFFFF, coords & 0xFFFF]
|
||||
|
||||
|
||||
def compare(scene, client, rust, states, report, limit):
|
||||
blocks = {tuple(b[:3]): b[3] for b in scene['blocks']}
|
||||
def describe(quad, rotation):
|
||||
v = quad['vertices']
|
||||
centre = [sum(p[i] for p in v) / 4 for i in range(3)]
|
||||
block = quad.get('block') or [math.floor(c + 1e-4 if i != 1 else c - 1e-3) for i, c in enumerate(centre)]
|
||||
state = blocks.get(tuple(block), 0)
|
||||
return {'block': block, 'state': f"{states.names[state]}{states.properties[state] or ''}",
|
||||
'sprite': quad['sprite'], 'kind': quad.get('kind', 'rust'),
|
||||
'vertices': [list(x) for x in (v[rotation:] + v[:rotation])]}
|
||||
groups = defaultdict(lambda: ([], []))
|
||||
for side, quads in [(0, client), (1, rust)]:
|
||||
for quad in quads:
|
||||
key, rotation = quad_key(quad)
|
||||
groups[key][side].append((quad, rotation))
|
||||
counts = Counter()
|
||||
def add(category, *examples):
|
||||
counts[category] += 1
|
||||
report['categories'][category] = report['categories'].get(category, 0) + 1
|
||||
bucket = report['examples'].setdefault(category, [])
|
||||
if len(bucket) < limit:
|
||||
bucket.append({'scene': scene['name'], 'quads': list(examples)})
|
||||
def attributes(entry):
|
||||
quad, rotation = entry
|
||||
v = quad['vertices']
|
||||
return str([(round(x[3], 3), round(x[4], 3), channels(x[5]), light(x[6])) for x in v[rotation:] + v[:rotation]])
|
||||
for key, (left, right) in groups.items():
|
||||
# Coincident quads (back faces, overlapping elements) pair up by their attributes.
|
||||
left.sort(key=attributes)
|
||||
right.sort(key=attributes)
|
||||
for a, b in zip(left, right):
|
||||
report['matched_quads'] += 1
|
||||
ca = a[0]['vertices'][a[1]:] + a[0]['vertices'][:a[1]]
|
||||
cb = b[0]['vertices'][b[1]:] + b[0]['vertices'][:b[1]]
|
||||
problems = set()
|
||||
for p, q in zip(ca, cb):
|
||||
if any(abs(p[i] - q[i]) > POSITION_TOLERANCE for i in range(3)):
|
||||
problems.add('position')
|
||||
if any(abs(p[i] - q[i]) > UV_TOLERANCE for i in (3, 4)):
|
||||
problems.add('uv')
|
||||
cp, cq = channels(p[5]), channels(q[5])
|
||||
if cp != cq:
|
||||
problems.add('color' if max(abs(x - y) for x, y in zip(cp, cq)) > 1 else 'color_rounding')
|
||||
if light(p[6]) != light(q[6]):
|
||||
lp, lq = light(p[6]), light(q[6])
|
||||
problems.add('light_sky' if lp[0] != lq[0] else 'light_block')
|
||||
if not problems:
|
||||
report['identical_quads'] += 1
|
||||
for problem in sorted(problems):
|
||||
add(f"{problem}:{a[0].get('kind', 'model')}", describe(*a), describe(*b))
|
||||
for entry in left[len(right):]:
|
||||
add(f"missing:{entry[0]['kind']}", describe(*entry))
|
||||
for entry in right[len(left):]:
|
||||
add('extra', describe(*entry))
|
||||
report['client_quads'] += len(client)
|
||||
report['rust_quads'] += len(rust)
|
||||
return counts
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument('--strict', action='store_true', help='fail when any quad or fact differs')
|
||||
parser.add_argument('--examples', type=int, default=12, help='examples kept per mismatch category')
|
||||
parser.add_argument('--only', help='only scenes whose name contains this text')
|
||||
parser.add_argument('--quick', action='store_true', help='skip the all-states catalogue and most dense scenes')
|
||||
args = parser.parse_args()
|
||||
lock, jars, _ = base.verify_artifacts()
|
||||
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
|
||||
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/VanillaSectionMeshOracle.java'
|
||||
helpers = [oracle.with_name(n + '.java') for n in ['VanillaCuboidModelOracle', 'VanillaHeightmapOracle']]
|
||||
sources = [Path(__file__), lab.ROOT / 'tools/lab.py', lab.ROOT / 'tools/test_rust_parity.py', oracle, *helpers,
|
||||
lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', lab.ROOT / 'crates/horizon-client/examples/section_mesh_fixture.rs']
|
||||
for crate in ['horizon-core', 'horizon-world', 'horizon-assets', 'horizon-client']:
|
||||
sources += [lab.ROOT / 'crates' / crate / 'Cargo.toml', *sorted((lab.ROOT / 'crates' / crate / 'src').rglob('*.rs'))]
|
||||
tested = base.source_hashes(sources)
|
||||
states = States(resources)
|
||||
scenes = [s for s in corpus(states, not args.quick) if not args.only or args.only in s.name]
|
||||
rows = [s.row() for s in scenes]
|
||||
inputs = BUILD / 'inputs.jsonl'
|
||||
inputs.write_text(''.join(json.dumps(row) + '\n' for row in rows))
|
||||
def run(command, name):
|
||||
path = BUILD / (name + '.log')
|
||||
with path.open('w') as log:
|
||||
code = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT).returncode
|
||||
if code:
|
||||
tail = [line for line in path.read_text(errors='replace').splitlines() if not line.startswith('WARNING')][-15:]
|
||||
raise SystemExit(f'{name} failed ({code}); see {path}\n' + '\n'.join(tail))
|
||||
classes = BUILD / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
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, *helpers], 'compile-java')
|
||||
env_jobs = os.environ.get('CARGO_BUILD_JOBS', '3')
|
||||
run(['cargo', 'build', '--locked', '--profile', 'fast', '-j', env_jobs, '-p', 'horizon-client', '--example', 'section_mesh_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']) / 'fast/examples' / ('section_mesh_fixture.exe' if os.name == 'nt' else 'section_mesh_fixture')
|
||||
java = ['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaSectionMeshOracle']
|
||||
run([binary, resources, inputs, BUILD / 'rust.jsonl'], 'rust')
|
||||
run([*java, inputs, BUILD / 'client.jsonl', resources], 'client')
|
||||
run([*java, 'facts', BUILD / 'client-facts.jsonl', resources], 'client-facts')
|
||||
run([binary, resources, 'facts', BUILD / 'rust-facts.jsonl'], 'rust-facts')
|
||||
report = {'schema': 1, 'minecraft': lock['minecraft']['version'], 'platform': platform.platform(),
|
||||
'scenes': len(rows), 'client_quads': 0, 'rust_quads': 0, 'matched_quads': 0, 'identical_quads': 0,
|
||||
'categories': {}, 'examples': {}, 'per_scene': {}, 'facts': {}}
|
||||
client = [json.loads(line) for line in (BUILD / 'client.jsonl').read_text().splitlines()]
|
||||
rust = [json.loads(line) for line in (BUILD / 'rust.jsonl').read_text().splitlines()]
|
||||
for row, a, b in zip(rows, client, rust):
|
||||
assert row['name'] == a['name'] == b['name']
|
||||
counts = compare(row, a['quads'], b['quads'], states, report, args.examples)
|
||||
report['per_scene'][row['name']] = {'client': len(a['quads']), 'rust': len(b['quads']), **counts}
|
||||
client_facts = [json.loads(line) for line in (BUILD / 'client-facts.jsonl').read_text().splitlines()]
|
||||
rust_facts = [json.loads(line) for line in (BUILD / 'rust-facts.jsonl').read_text().splitlines()]
|
||||
fact_mismatches = Counter()
|
||||
for a, b in zip(client_facts, rust_facts):
|
||||
for key in a:
|
||||
if key == 'offsets':
|
||||
same = len(a[key]) == len(b.get(key, [])) and all(abs(x - y) < 1e-6 for p, q in zip(a[key], b[key]) for x, y in zip(p, q))
|
||||
elif isinstance(a[key], float):
|
||||
same = isinstance(b.get(key), (int, float)) and abs(f32(a[key]) - f32(b[key])) == 0
|
||||
else:
|
||||
same = a[key] == b.get(key)
|
||||
if not same:
|
||||
fact_mismatches[key] += 1
|
||||
examples = report['facts'].setdefault(key, [])
|
||||
if len(examples) < args.examples:
|
||||
examples.append({'state': f"{states.names[a['id']]}{states.properties[a['id']]}", 'client': a[key], 'rust': b.get(key)})
|
||||
timing = [line for line in (BUILD / 'rust.log').read_text().splitlines() if line.startswith('meshed ')]
|
||||
report['rust_mesh_timing'] = timing[-1] if timing else None
|
||||
report['fact_mismatches'] = dict(fact_mismatches)
|
||||
report['fact_states'] = len(client_facts)
|
||||
base.ensure_sources_unchanged(sources, tested)
|
||||
report['sources_sha256'] = tested
|
||||
lab.write_json(report_path, report)
|
||||
total = report['client_quads']
|
||||
print(f"Section mesh parity: {len(rows)} scenes, client {total:,} quads, Rust {report['rust_quads']:,} quads, "
|
||||
f"{report['matched_quads']:,} geometry matches, {report['identical_quads']:,} identical "
|
||||
f"({100.0 * report['identical_quads'] / max(total, 1):.2f}% of client quads)")
|
||||
for category, count in sorted(report['categories'].items(), key=lambda kv: -kv[1]):
|
||||
print(f' {category:<28} {count:,}')
|
||||
print(f"Mesh facts: {len(client_facts):,} states, mismatches: {dict(fact_mismatches) or 'none'}")
|
||||
print(f"Rust fixture (fast profile): {report['rust_mesh_timing']}")
|
||||
print(f'Report: {report_path}')
|
||||
if args.strict and (report['categories'] or fact_mismatches):
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user