Merge remote-tracking branch 'origin/wip/parity-render' into t3/minecraft-parity
# Conflicts: # crates/horizon-client/src/containers.rs # crates/horizon-client/src/entity.wgsl # crates/horizon-client/src/game.rs # crates/horizon-client/src/game/control.rs # crates/horizon-client/src/gfx.rs # crates/horizon-client/src/lib.rs
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(())
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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 {
|
||||
|
||||
@@ -50,9 +50,14 @@ pub enum BlockEntity {
|
||||
Chest(Vec<Option<ItemStack>>),
|
||||
Furnace(Furnace),
|
||||
Brewing(Box<crate::brewing::BrewingStand>),
|
||||
/// Signs and hanging signs (`SignBlockEntity`).
|
||||
Sign(crate::signs::SignData),
|
||||
}
|
||||
impl BlockEntity {
|
||||
pub fn for_block(name: &str) -> Option<Self> {
|
||||
if let Some(hanging) = crate::signs::sign_kind(name) {
|
||||
return Some(Self::Sign(crate::signs::SignData { hanging, ..Default::default() }));
|
||||
}
|
||||
if let Some(kind) = FurnaceKind::from_block(name) {
|
||||
return Some(Self::Furnace(Furnace {
|
||||
kind,
|
||||
@@ -112,6 +117,7 @@ impl BlockEntity {
|
||||
FurnaceKind::BlastFurnace => "minecraft:blast_furnace",
|
||||
FurnaceKind::Smoker => "minecraft:smoker",
|
||||
},
|
||||
Self::Sign(s) => s.id(),
|
||||
}
|
||||
}
|
||||
pub fn contents(&self) -> Vec<ItemStack> {
|
||||
@@ -125,6 +131,7 @@ impl BlockEntity {
|
||||
match self {
|
||||
Self::Chest(items) => items,
|
||||
Self::Furnace(f) => &f.items,
|
||||
Self::Sign(_) => Vec::new(),
|
||||
}
|
||||
}
|
||||
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
|
||||
@@ -132,6 +139,7 @@ impl BlockEntity {
|
||||
Self::Chest(items) => items,
|
||||
Self::Furnace(f) => &mut f.items,
|
||||
Self::Brewing(b) => &mut b.items,
|
||||
Self::Sign(_) => &mut [],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ struct Globals {
|
||||
inverse_view: mat4x4<f32>,
|
||||
sunrise: vec4<f32>,
|
||||
sun: vec4<f32>,
|
||||
// x: sky fog end, y: cloud fog end
|
||||
fog_ends: vec4<f32>,
|
||||
}
|
||||
@group(0) @binding(0) var<uniform> globals: Globals;
|
||||
@group(0) @binding(1) var atlas: texture_2d<f32>;
|
||||
@@ -22,6 +24,7 @@ struct Out {
|
||||
@location(2) spherical: f32,
|
||||
@location(3) cylindrical: f32,
|
||||
@location(4) flash: f32,
|
||||
@location(4) @interpolate(flat) overlay: u32,
|
||||
}
|
||||
@vertex fn vs_entity(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>) -> Out {
|
||||
@@ -31,8 +34,8 @@ struct Out {
|
||||
let l = vec2(f32(light.y), f32(light.x));
|
||||
let lm = textureSampleLevel(lightmap, lightmap_sampler,
|
||||
clamp(l / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0);
|
||||
// overlay 2: celestial bodies use their vertex colour unlit.
|
||||
var c = select(color * lm, color, overlay == 2u);
|
||||
// overlay 2: celestial bodies, 4: clouds; both use their vertex colour unlit.
|
||||
var c = select(color * lm, color, overlay == 2u || overlay == 4u);
|
||||
// Hurt overlay (OverlayTexture red tint).
|
||||
if overlay == 1u { c = vec4(mix(c.rgb, vec3(1.0, 0.0, 0.0), 0.3), c.a); }
|
||||
out.color = c;
|
||||
@@ -41,6 +44,8 @@ struct Out {
|
||||
// Sky geometry (clouds, celestial bodies) is exempt from render-distance fog.
|
||||
out.spherical = select(length(position), 0.0, overlay >= 2u);
|
||||
out.cylindrical = select(max(length(position.xz), abs(position.y)), 0.0, overlay >= 2u);
|
||||
out.overlay = overlay;
|
||||
if overlay == 4u { out.spherical = length(position); }
|
||||
return out;
|
||||
}
|
||||
fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
|
||||
@@ -50,6 +55,11 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
|
||||
}
|
||||
@fragment fn fs_entity(in: Out) -> @location(0) vec4<f32> {
|
||||
var color = textureSample(atlas, atlas_sampler, in.uv) * in.color;
|
||||
let color = textureSample(atlas, atlas_sampler, in.uv) * in.color;
|
||||
if in.overlay == 4u {
|
||||
// clouds.fsh: alpha fades out towards the cloud fog end.
|
||||
return vec4(color.rgb, color.a * (1.0 - linear_fog(in.spherical, 0.0, globals.fog_ends.y)));
|
||||
}
|
||||
if color.a < 0.1 { discard; }
|
||||
color = vec4(mix(color.rgb, vec3(1.0), in.flash), color.a);
|
||||
let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y),
|
||||
|
||||
@@ -0,0 +1,399 @@
|
||||
//! `FogRenderer` and its fog environments (atmospheric with rain fog, water
|
||||
//! with water vision, lava, powder snow, blindness), the camera fog type
|
||||
//! (`Camera.getFluidInCamera`) and the fog colour (`computeFogColor`: sunrise
|
||||
//! tint, sky-colour mix, void darkness, water-vision brightening).
|
||||
use crate::{
|
||||
biome::Biomes,
|
||||
blocks::{BlockFacts, Fluid},
|
||||
environment::Sky,
|
||||
world::World,
|
||||
};
|
||||
use std::path::Path;
|
||||
|
||||
/// `FogType` of the camera position.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum FogType {
|
||||
Atmospheric,
|
||||
Water,
|
||||
Lava,
|
||||
PowderSnow,
|
||||
}
|
||||
|
||||
/// The fog uniform (`FogData`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct FogData {
|
||||
pub color: [f32; 4],
|
||||
pub environmental_start: f32,
|
||||
pub environmental_end: f32,
|
||||
pub render_distance_start: f32,
|
||||
pub render_distance_end: f32,
|
||||
pub sky_end: f32,
|
||||
pub cloud_end: f32,
|
||||
}
|
||||
|
||||
/// Per-biome water fog end multipliers (`visual/water_fog_end_distance`).
|
||||
pub struct FogTables {
|
||||
water_fog_end: Vec<f32>,
|
||||
}
|
||||
impl FogTables {
|
||||
pub fn load(root: &Path, biomes: &Biomes) -> Self {
|
||||
let mut water_fog_end = vec![1.0; biomes.list.len()];
|
||||
for (name, &id) in &biomes.index {
|
||||
let path = root.join(format!(
|
||||
"data/minecraft/worldgen/biome/{}.json",
|
||||
name.trim_start_matches("minecraft:")
|
||||
));
|
||||
let Ok(bytes) = std::fs::read(path) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(json) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
|
||||
continue;
|
||||
};
|
||||
let v = &json["attributes"]["minecraft:visual/water_fog_end_distance"];
|
||||
if v["modifier"].as_str() == Some("multiply")
|
||||
&& let (Some(f), Some(slot)) =
|
||||
(v["argument"].as_f64(), water_fog_end.get_mut(id as usize))
|
||||
{
|
||||
*slot = f as f32;
|
||||
}
|
||||
}
|
||||
Self { water_fog_end }
|
||||
}
|
||||
}
|
||||
|
||||
/// Fog state that evolves over time.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct FogState {
|
||||
/// `LocalPlayer.waterVisionTime` (0..600).
|
||||
pub water_vision_time: i32,
|
||||
/// `AtmosphericFogEnvironment.rainFogMultiplier`.
|
||||
pub rain_fog_multiplier: f32,
|
||||
}
|
||||
impl FogState {
|
||||
/// `LocalPlayer.aiStep`: water vision ramps up while the eye is in water.
|
||||
pub fn tick(&mut self, eye_in_water: bool) {
|
||||
self.water_vision_time = if eye_in_water {
|
||||
(self.water_vision_time + 1).min(600)
|
||||
} else {
|
||||
(self.water_vision_time - 10).max(0)
|
||||
};
|
||||
}
|
||||
/// `LocalPlayer.getWaterVision`.
|
||||
pub fn water_vision(&self, eye_in_water: bool) -> f32 {
|
||||
if !eye_in_water {
|
||||
return 0.0;
|
||||
}
|
||||
let t = self.water_vision_time as f32;
|
||||
if t >= 600.0 {
|
||||
return 1.0;
|
||||
}
|
||||
let a = (t / 100.0).clamp(0.0, 1.0);
|
||||
let b = if t < 100.0 {
|
||||
0.0
|
||||
} else {
|
||||
((t - 100.0) / 500.0).clamp(0.0, 1.0)
|
||||
};
|
||||
a * 0.6 + b * 0.399_999_98
|
||||
}
|
||||
}
|
||||
|
||||
/// The fog tables and evolving state kept by the game.
|
||||
pub struct FogRenderer {
|
||||
pub tables: FogTables,
|
||||
pub state: FogState,
|
||||
}
|
||||
impl FogRenderer {
|
||||
pub fn load(root: &Path, biomes: &Biomes) -> Self {
|
||||
Self {
|
||||
tables: FogTables::load(root, biomes),
|
||||
state: FogState::default(),
|
||||
}
|
||||
}
|
||||
pub fn setup(&self, input: &FogInputs) -> FogData {
|
||||
setup_fog(&self.tables, &self.state, input)
|
||||
}
|
||||
}
|
||||
/// `FluidState.getHeightForCamera`.
|
||||
fn camera_fluid_height(world: &World, facts: &BlockFacts, b: [i32; 3]) -> Option<(Fluid, f64)> {
|
||||
let s = facts.get(world.block(b[0], b[1], b[2]));
|
||||
if s.fluid == Fluid::None {
|
||||
return None;
|
||||
}
|
||||
let above = facts.get(world.block(b[0], b[1] + 1, b[2]));
|
||||
let source = s.fluid_level >= 8 && !s.fluid_falling;
|
||||
let height = if source && above.full_collision {
|
||||
1.0
|
||||
} else if above.fluid == s.fluid {
|
||||
1.0
|
||||
} else {
|
||||
f64::from(s.fluid_level) / 9.0
|
||||
};
|
||||
Some((s.fluid, height))
|
||||
}
|
||||
/// `Camera.getFluidInCamera` (near-plane points reduced to the camera and
|
||||
/// the point just in front of it).
|
||||
pub fn fog_type(world: &World, facts: &BlockFacts, camera: [f64; 3], forward: [f64; 3]) -> FogType {
|
||||
let block = |p: [f64; 3]| {
|
||||
[
|
||||
p[0].floor() as i32,
|
||||
p[1].floor() as i32,
|
||||
p[2].floor() as i32,
|
||||
]
|
||||
};
|
||||
let b = block(camera);
|
||||
if let Some((Fluid::Water, h)) = camera_fluid_height(world, facts, b)
|
||||
&& camera[1] < f64::from(b[1]) + h
|
||||
{
|
||||
return FogType::Water;
|
||||
}
|
||||
for p in [
|
||||
[
|
||||
camera[0] + forward[0] * 0.05,
|
||||
camera[1] + forward[1] * 0.05,
|
||||
camera[2] + forward[2] * 0.05,
|
||||
],
|
||||
camera,
|
||||
] {
|
||||
let b = block(p);
|
||||
match camera_fluid_height(world, facts, b) {
|
||||
Some((Fluid::Lava, h)) if p[1] <= f64::from(b[1]) + h => return FogType::Lava,
|
||||
Some((Fluid::Lava, _)) => {}
|
||||
_ => {
|
||||
if &*facts.get(world.block(b[0], b[1], b[2])).name == "minecraft:powder_snow" {
|
||||
return FogType::PowderSnow;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
FogType::Atmospheric
|
||||
}
|
||||
|
||||
/// Everything `FogRenderer.setupFog` reads for one frame.
|
||||
pub struct FogInputs<'a> {
|
||||
pub fog_type: FogType,
|
||||
pub sky: &'a Sky,
|
||||
/// Biome water fog colour (`visual/water_fog_color`).
|
||||
pub water_fog_color: [f32; 3],
|
||||
pub biome: u16,
|
||||
pub render_distance_chunks: i32,
|
||||
pub camera_y: f64,
|
||||
pub min_y: i32,
|
||||
/// Flat worlds use a 1-block void darkness range.
|
||||
pub flat: bool,
|
||||
pub forward: [f32; 3],
|
||||
pub rain: f32,
|
||||
pub thunder: f32,
|
||||
/// Dimensions with a sky disc (overworld): sunrise tint and sky mix apply.
|
||||
pub skybox: bool,
|
||||
/// Blindness: (remaining duration ticks, infinite).
|
||||
pub blindness: Option<(i32, bool)>,
|
||||
}
|
||||
|
||||
/// `FogRenderer.setupFog` + `computeFogColor`.
|
||||
pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> FogData {
|
||||
let rd = input.render_distance_chunks as f32 * 16.0;
|
||||
let sky = input.sky;
|
||||
let eye_in_water = input.fog_type == FogType::Water;
|
||||
let water_vision = state.water_vision(eye_in_water);
|
||||
// Base colour of the applicable environment.
|
||||
let mut color = match input.fog_type {
|
||||
FogType::Lava => rgb(0x99_1A00),
|
||||
FogType::PowderSnow => rgb(0x9F_BACC),
|
||||
FogType::Water => input.water_fog_color,
|
||||
FogType::Atmospheric => {
|
||||
let mut fog = sky.fog_color;
|
||||
if input.skybox && input.render_distance_chunks >= 4 {
|
||||
let sun_x = if sky.sun_angle.to_radians().sin() > 0.0 {
|
||||
-1.0
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let looking = input.forward[0] * sun_x;
|
||||
let alpha = sky.sunrise_color[3];
|
||||
if looking > 0.0 && alpha > 0.0 {
|
||||
let t = looking * alpha;
|
||||
fog = std::array::from_fn(|i| fog[i] + (sky.sunrise_color[i] - fog[i]) * t);
|
||||
}
|
||||
}
|
||||
let mut sky_color = sky.sky_color;
|
||||
if input.rain > 0.0 {
|
||||
let m = 1.0 - input.rain * 0.5;
|
||||
let mb = 1.0 - input.rain * 0.4;
|
||||
sky_color = [sky_color[0] * m, sky_color[1] * m, sky_color[2] * mb];
|
||||
}
|
||||
if input.thunder > 0.0 {
|
||||
let m = 1.0 - input.thunder * 0.5;
|
||||
sky_color = sky_color.map(|c| c * m);
|
||||
}
|
||||
let sky_fog_end = (512.0f32 / 16.0).min(input.render_distance_chunks as f32);
|
||||
let mix = (sky_fog_end / 32.0).clamp(0.0, 1.0).mul_add(0.75, 0.25);
|
||||
let mix = 1.0 - mix.powf(0.25);
|
||||
std::array::from_fn(|i| fog[i] + (sky_color[i] - fog[i]) * mix)
|
||||
}
|
||||
};
|
||||
// Void darkness and blindness.
|
||||
let range = if input.flat { 1.0 } else { 32.0 };
|
||||
let mut darkness =
|
||||
((range + input.min_y as f32 - input.camera_y as f32) / range).clamp(0.0, 1.0);
|
||||
if let Some((duration, infinite)) = input.blindness {
|
||||
darkness = if !infinite && duration < 20 {
|
||||
darkness.max(duration as f32 / 20.0)
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
}
|
||||
if darkness > 0.0 && !matches!(input.fog_type, FogType::Lava | FogType::PowderSnow) {
|
||||
let brightness = (1.0 - darkness) * (1.0 - darkness);
|
||||
color = color.map(|c| c * brightness);
|
||||
}
|
||||
let brighten = if eye_in_water { water_vision } else { 0.0 };
|
||||
if color.iter().all(|&c| c != 0.0) {
|
||||
let scale = 1.0 / color[0].max(color[1]).max(color[2]);
|
||||
color = color.map(|c| c + (c * scale - c) * brighten);
|
||||
}
|
||||
let mut fog = FogData {
|
||||
color: [color[0], color[1], color[2], 1.0],
|
||||
environmental_start: 0.0,
|
||||
environmental_end: 1024.0,
|
||||
render_distance_start: 0.0,
|
||||
render_distance_end: rd,
|
||||
sky_end: rd.min(512.0),
|
||||
cloud_end: 2048.0,
|
||||
};
|
||||
match input.fog_type {
|
||||
FogType::Lava => {
|
||||
fog.environmental_start = 0.25;
|
||||
fog.environmental_end = 1.0;
|
||||
fog.sky_end = 1.0;
|
||||
fog.cloud_end = 1.0;
|
||||
}
|
||||
FogType::PowderSnow => {
|
||||
fog.environmental_start = 0.0;
|
||||
fog.environmental_end = 2.0;
|
||||
fog.sky_end = 2.0;
|
||||
fog.cloud_end = 2.0;
|
||||
}
|
||||
_ if input.blindness.is_some() => {
|
||||
let (duration, infinite) = input.blindness.unwrap_or((0, true));
|
||||
let distance = if infinite {
|
||||
5.0
|
||||
} else {
|
||||
rd + (5.0 - rd) * (duration as f32 / 20.0).min(1.0)
|
||||
};
|
||||
fog.environmental_start = distance * 0.25;
|
||||
fog.environmental_end = distance;
|
||||
fog.sky_end = distance * 0.8;
|
||||
fog.cloud_end = distance * 0.8;
|
||||
}
|
||||
FogType::Water => {
|
||||
fog.environmental_start = -8.0;
|
||||
let factor = tables
|
||||
.water_fog_end
|
||||
.get(input.biome as usize)
|
||||
.copied()
|
||||
.unwrap_or(1.0);
|
||||
fog.environmental_end = 96.0 * factor * water_vision.max(0.25);
|
||||
fog.sky_end = fog.environmental_end;
|
||||
fog.cloud_end = fog.environmental_end;
|
||||
}
|
||||
FogType::Atmospheric => {
|
||||
fog.environmental_start = sky.fog_start + -160.0 * state.rain_fog_multiplier;
|
||||
let min_end = sky.fog_end.min(96.0);
|
||||
fog.environmental_end = min_end.max(sky.fog_end + -256.0 * state.rain_fog_multiplier);
|
||||
fog.sky_end = rd.min(512.0);
|
||||
fog.cloud_end = 2048.0f32.min(128.0 * 16.0);
|
||||
}
|
||||
}
|
||||
let span = (rd / 10.0).clamp(4.0, 64.0);
|
||||
fog.render_distance_start = rd - span;
|
||||
fog.render_distance_end = rd;
|
||||
fog
|
||||
}
|
||||
/// `AtmosphericFogEnvironment.updateRainFogState`.
|
||||
pub fn update_rain_fog(
|
||||
state: &mut FogState,
|
||||
rain: f32,
|
||||
sky_light: u8,
|
||||
biome_rains: bool,
|
||||
delta_ticks: f32,
|
||||
) {
|
||||
let sky = ((f32::from(sky_light) - 8.0) / 7.0).clamp(0.0, 1.0);
|
||||
let target = rain * sky * if biome_rains { 1.0 } else { 0.5 };
|
||||
state.rain_fog_multiplier += (target - state.rain_fog_multiplier) * delta_ticks * 0.2;
|
||||
}
|
||||
fn rgb(c: u32) -> [f32; 3] {
|
||||
[
|
||||
(c >> 16 & 255) as f32 / 255.0,
|
||||
(c >> 8 & 255) as f32 / 255.0,
|
||||
(c & 255) as f32 / 255.0,
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn inputs(sky: &Sky) -> FogInputs<'_> {
|
||||
FogInputs {
|
||||
fog_type: FogType::Atmospheric,
|
||||
sky,
|
||||
water_fog_color: [0.0, 0.0, 0.2],
|
||||
biome: 0,
|
||||
render_distance_chunks: 12,
|
||||
camera_y: 70.0,
|
||||
min_y: -64,
|
||||
flat: false,
|
||||
forward: [0.0, 0.0, 1.0],
|
||||
rain: 0.0,
|
||||
thunder: 0.0,
|
||||
skybox: true,
|
||||
blindness: None,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn render_distance_fog_span() {
|
||||
let sky = Sky {
|
||||
fog_end: 1024.0,
|
||||
fog_color: [0.5; 3],
|
||||
sky_color: [0.5; 3],
|
||||
..Sky::default()
|
||||
};
|
||||
let tables = FogTables {
|
||||
water_fog_end: vec![1.0],
|
||||
};
|
||||
let fog = setup_fog(&tables, &FogState::default(), &inputs(&sky));
|
||||
// 12 chunks = 192 blocks, span clamp(19.2, 4, 64).
|
||||
assert!((fog.render_distance_start - (192.0 - 19.2)).abs() < 1e-4);
|
||||
assert_eq!(fog.render_distance_end, 192.0);
|
||||
assert_eq!(fog.sky_end, 192.0);
|
||||
}
|
||||
#[test]
|
||||
fn water_vision_ramps() {
|
||||
let mut s = FogState::default();
|
||||
for _ in 0..100 {
|
||||
s.tick(true);
|
||||
}
|
||||
assert!((s.water_vision(true) - 0.6).abs() < 1e-6);
|
||||
for _ in 0..500 {
|
||||
s.tick(true);
|
||||
}
|
||||
assert_eq!(s.water_vision(true), 1.0);
|
||||
assert_eq!(s.water_vision(false), 0.0);
|
||||
}
|
||||
#[test]
|
||||
fn rain_fog_pulls_fog_in() {
|
||||
let sky = Sky {
|
||||
fog_end: 1024.0,
|
||||
..Sky::default()
|
||||
};
|
||||
let tables = FogTables {
|
||||
water_fog_end: vec![1.0],
|
||||
};
|
||||
let state = FogState {
|
||||
rain_fog_multiplier: 1.0,
|
||||
..FogState::default()
|
||||
};
|
||||
let fog = setup_fog(&tables, &state, &inputs(&sky));
|
||||
assert_eq!(fog.environmental_start, -160.0);
|
||||
assert_eq!(fog.environmental_end, 768.0);
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,9 @@ mod options;
|
||||
mod packs;
|
||||
mod screens;
|
||||
mod creatures;
|
||||
mod render_control;
|
||||
mod render_tick;
|
||||
mod sign_edit;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
assets::Assets,
|
||||
@@ -337,7 +340,10 @@ pub struct Resources {
|
||||
mob_types: HashMap<String, Arc<MobType>>,
|
||||
mob_data: horizon_client::mobs::MobData,
|
||||
providers: Providers,
|
||||
chest_model: Option<horizon_client::mobs::Part>,
|
||||
block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer,
|
||||
animate: horizon_client::animate_tick::AnimateTables,
|
||||
fog: horizon_client::fog::FogRenderer,
|
||||
screen_fx: horizon_client::screen_effects::ScreenEffects,
|
||||
nether_environment: Environment,
|
||||
end_environment: Environment,
|
||||
behaviours: Behaviours,
|
||||
@@ -407,7 +413,9 @@ struct Game<'a> {
|
||||
audio: Audio,
|
||||
dropped: Vec<ItemEntity>,
|
||||
next_entity: u32,
|
||||
particles: Vec<Particle>,
|
||||
particles: horizon_client::particles::ParticleEngine,
|
||||
/// Sign text being edited (`SignEditScreen`).
|
||||
sign_edit: Option<sign_edit::SignEditor>,
|
||||
spawn_search: u32,
|
||||
mobs: Vec<Mob>,
|
||||
arrows: Vec<Arrow>,
|
||||
@@ -1132,7 +1140,11 @@ impl Game<'_> {
|
||||
};
|
||||
let target = [pos.x, pos.y, pos.z];
|
||||
if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) {
|
||||
let sign = matches!(entity, BlockEntity::Sign(_));
|
||||
self.world.block_entities.insert((target[0], target[1], target[2]), entity);
|
||||
if sign {
|
||||
self.open_sign_editor((target[0], target[1], target[2]), true);
|
||||
}
|
||||
}
|
||||
self.swing_arm();
|
||||
let sounds = self.res.facts.get(state).sounds.clone();
|
||||
@@ -1543,7 +1555,11 @@ impl Game<'_> {
|
||||
if self.particles.len() > 4000 {
|
||||
let excess = self.particles.len() - 4000;
|
||||
self.particles.drain(..excess);
|
||||
if let Some(r) = &self.renderer {
|
||||
let eye = self.player.as_ref().map(|p| [p.position.x, p.position.y + f64::from(self.eye), p.position.z]);
|
||||
self.res.block_entity_render.tick(r.block_entities(), eye);
|
||||
}
|
||||
self.tick_particles();
|
||||
if self.right && self.use_delay == 0 && self.screen == Screen::Playing {
|
||||
self.use_item()?;
|
||||
self.use_delay = 4;
|
||||
@@ -1847,6 +1863,7 @@ impl Game<'_> {
|
||||
Screen::Playing | Screen::Options => {}
|
||||
}
|
||||
self.remote_hud(&mut batch);
|
||||
self.draw_sign_editor(&mut batch);
|
||||
batch
|
||||
}
|
||||
fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) {
|
||||
@@ -1866,6 +1883,7 @@ impl Game<'_> {
|
||||
Some(BlockEntity::Chest(items)) => v.extend((0..items.len()).map(|i| 300 + i)),
|
||||
Some(BlockEntity::Furnace(_)) => v.extend(300..303),
|
||||
Some(BlockEntity::Brewing(_)) => v.extend(300..305),
|
||||
Some(BlockEntity::Sign(_)) => {}
|
||||
None => {
|
||||
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
|
||||
v.push(200);
|
||||
@@ -1989,6 +2007,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
Some(BlockEntity::Brewing(_)) => {}
|
||||
Some(BlockEntity::Sign(_)) => {}
|
||||
None => {
|
||||
let texture = if self.craft_size == 3 { "gui/container/crafting_table" } else { "gui/container/inventory" };
|
||||
part(batch, texture, 0.0, 0.0, 176.0, 166.0, ox, oy);
|
||||
@@ -2258,50 +2277,42 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Chests (ChestRenderer): rotate by facing around the block centre, lift the lid.
|
||||
if let Some(model) = &self.res.chest_model {
|
||||
for (pos, entity) in &self.world.block_entities {
|
||||
if !matches!(entity, BlockEntity::Chest(_)) {
|
||||
continue;
|
||||
}
|
||||
let state = self.world.block(pos.0, pos.1, pos.2);
|
||||
let name = &self.res.facts.get(state).name;
|
||||
let texture = match &**name {
|
||||
"minecraft:chest" => "entity/chest/normal",
|
||||
"minecraft:trapped_chest" => "entity/chest/trapped",
|
||||
_ => continue,
|
||||
};
|
||||
let origin = glam::DVec3::new(f64::from(pos.0), f64::from(pos.1), f64::from(pos.2)) - camera;
|
||||
if origin.length_squared() > 64.0 * 64.0 {
|
||||
continue;
|
||||
}
|
||||
let Some(r) = self.res.atlas.sprites.get(texture).copied() else { continue };
|
||||
let facing = self.res.assets.registry.state(state).and_then(|s| s.properties.get("facing").cloned()).unwrap_or_default();
|
||||
let yrot: f32 = match facing.as_str() {
|
||||
"west" => 90.0,
|
||||
"north" => 180.0,
|
||||
"east" => 270.0,
|
||||
_ => 0.0,
|
||||
};
|
||||
let (prev, cur) = self.chest_open.get(pos).copied().unwrap_or((0.0, 0.0));
|
||||
let o = prev + (cur - prev) * alpha as f32;
|
||||
let open = 1.0 - (1.0 - o).powi(3);
|
||||
let base = glam::Mat4::from_translation(origin.as_vec3())
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(0.5, 0.0, 0.5))
|
||||
* glam::Mat4::from_rotation_y((-yrot).to_radians())
|
||||
* glam::Mat4::from_translation(glam::Vec3::new(-0.5, 0.0, -0.5));
|
||||
let light = self.world.light(pos.0, pos.1, pos.2);
|
||||
let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8;
|
||||
let pose = |part: &horizon_client::mobs::Part| {
|
||||
let mut p = part.pose;
|
||||
if part.name == "lid" || part.name == "lock" {
|
||||
p[3] = -(open * std::f32::consts::FRAC_PI_2);
|
||||
}
|
||||
p
|
||||
};
|
||||
horizon_client::mobs::render_model(model, base, &pose, [r.u0, r.v0, r.u1, r.v1], packed, 0, &mut out);
|
||||
// Entity shadows (EntityRenderer.extractShadow).
|
||||
if let Some(sprite) = self.res.atlas.sprites.get("misc/shadow").copied() {
|
||||
let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 };
|
||||
let darken = self.sky_darken();
|
||||
let a = alpha;
|
||||
let lerp = |p: Vec3, q: Vec3| glam::DVec3::new(p.x + (q.x - p.x) * a, p.y + (q.y - p.y) * a, p.z + (q.z - p.z) * a);
|
||||
let mut casters: Vec<(glam::DVec3, &str)> = self.mobs.iter().map(|m| (lerp(m.previous, m.position), m.kind.id.as_str())).collect();
|
||||
casters.extend(self.dropped.iter().map(|i| (lerp(i.previous, i.position), "minecraft:item")));
|
||||
casters.extend(self.orbs.iter().map(|o| (lerp(o.previous, o.position), "minecraft:experience_orb")));
|
||||
for (pos, id) in casters {
|
||||
let (radius, strength) = horizon_client::shadows::shadow_params(id);
|
||||
horizon_client::shadows::shadow(&self.world, &self.res.facts, sprite, camera, pos, radius, strength, ambient, darken, &mut out);
|
||||
}
|
||||
}
|
||||
// Block entities (BlockEntityRenderers): chests, shulker boxes, banners, skulls...
|
||||
if let Some(r) = &self.renderer {
|
||||
let lid = |p: [i32; 3]| {
|
||||
let (prev, cur) = self.chest_open.get(&(p[0], p[1], p[2])).copied().unwrap_or((0.0, 0.0));
|
||||
prev + (cur - prev) * alpha as f32
|
||||
};
|
||||
let scene = horizon_client::block_entity_render::Scene {
|
||||
camera,
|
||||
partial: alpha as f32,
|
||||
game_time: self.world.game_time,
|
||||
world: &self.world,
|
||||
sprites: &self.res.atlas.sprites,
|
||||
nether: self.dim == Dim::Nether,
|
||||
lid: &lid,
|
||||
sign: &|p| match self.world.block_entities.get(&(p[0], p[1], p[2])) {
|
||||
Some(BlockEntity::Sign(sign)) => Some(sign),
|
||||
_ => None,
|
||||
},
|
||||
glyph: &|c| self.res.atlas.glyph(c),
|
||||
};
|
||||
self.res.block_entity_render.render(&scene, r.block_entities(), &mut out);
|
||||
}
|
||||
// Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet.
|
||||
if let Some(r) = self.res.atlas.sprites.get("entity/experience_orb").copied() {
|
||||
let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians());
|
||||
@@ -2366,29 +2377,10 @@ impl Game<'_> {
|
||||
let forward = glam::Vec3::new(-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos());
|
||||
let right = forward.cross(glam::Vec3::Y).normalize_or_zero();
|
||||
let up = right.cross(forward).normalize_or_zero();
|
||||
// Particles (ParticleEngine.extract): camera-facing quads.
|
||||
let world = &self.world;
|
||||
self.particles.render(camera, self.yaw, self.pitch, alpha as f32, &|b| world.light(b[0], b[1], b[2]), &mut out);
|
||||
let atlas = &self.res.atlas;
|
||||
for p in &self.particles {
|
||||
let Some(r) = atlas.sprites.get(&p.sprite).copied() else { continue };
|
||||
let a = alpha;
|
||||
let pos = glam::DVec3::new(
|
||||
p.previous[0] + (p.position[0] - p.previous[0]) * a,
|
||||
p.previous[1] + (p.position[1] - p.previous[1]) * a,
|
||||
p.previous[2] + (p.position[2] - p.previous[2]) * a,
|
||||
) - camera;
|
||||
let c = pos.as_vec3();
|
||||
let light = self.world.light(p.position[0].floor() as i32, p.position[1].floor() as i32, p.position[2].floor() as i32);
|
||||
let packed = u32::from(light >> 4) * 16 | (u32::from(light & 15) * 16) << 8;
|
||||
// TerrainParticle colour: 0.6 base brightness times the block tint.
|
||||
let ch = |sft: u32| (((p.tint >> sft) & 255) as f32 * 0.6) as u32;
|
||||
let color = 0xFF00_0000 | ch(0) << 16 | ch(8) << 8 | ch(16);
|
||||
let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0);
|
||||
let (u0, v0, u1, v1) = (r.u0 + du * p.uv[0], r.v0 + dv * p.uv[1], r.u0 + du * p.uv[2], r.v0 + dv * p.uv[3]);
|
||||
let s = p.size;
|
||||
for (k, uv) in [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].iter().zip([[u0, v1], [u1, v1], [u1, v0], [u0, v0]]) {
|
||||
let v = c + right * (k.0 * s) + up * (k.1 * s);
|
||||
out.push(Vertex { pos: v.to_array(), uv, layer: 0, color, light: packed });
|
||||
}
|
||||
}
|
||||
// Breaking progress overlay (destroy_stage_0..9).
|
||||
if let Some(m) = &self.mining
|
||||
&& m.progress > 0.0
|
||||
@@ -2502,6 +2494,15 @@ impl Game<'_> {
|
||||
let mob = &mut self.mobs[index];
|
||||
let center = [mob.position.x, mob.position.y + mob.kind.height / 2.0, mob.position.z];
|
||||
if mob.hurt(amount, from, &mut self.world.random) {
|
||||
// Player.attack: crit emitter and damage indicator hearts.
|
||||
let (feet, width, height) = ([mob.position.x, mob.position.y, mob.position.z], mob.kind.width, mob.kind.height);
|
||||
if crit {
|
||||
self.particles.tracking_emitter(horizon_client::particles::ParticleOptions::simple(horizon_client::particles::ParticleType::Crit), feet, width, height);
|
||||
}
|
||||
if amount > 2.0 {
|
||||
let indicator = horizon_client::particles::ParticleOptions::simple(horizon_client::particles::ParticleType::DamageIndicator);
|
||||
self.particles.send_particles(&indicator, [feet[0], feet[1] + height * 0.5, feet[2]], [0.1, 0.0, 0.1], 0.2, (amount * 0.5) as u32);
|
||||
}
|
||||
self.last_hurt_by_player.insert(mob.id);
|
||||
let kind = mob.kind.clone();
|
||||
let dead = !mob.alive();
|
||||
@@ -2559,6 +2560,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let destroyed_count = destroyed.len();
|
||||
for b in destroyed {
|
||||
let state = self.world.block(b[0], b[1], b[2]);
|
||||
if self.res.facts.is_air(state) {
|
||||
@@ -2573,6 +2575,8 @@ impl Game<'_> {
|
||||
}
|
||||
self.world.set(b[0], b[1], b[2], self.world.air)?;
|
||||
}
|
||||
let (world, facts) = (&self.world, &self.res.facts);
|
||||
self.particles.explosion(center, radius, destroyed_count, &|b| facts.is_air(world.block(b[0], b[1], b[2])));
|
||||
self.audio.play("minecraft:entity.generic.explode", Some(center), 4.0, (1.0 + (self.world.random.next_float() - self.world.random.next_float()) * 0.2) * 0.7);
|
||||
// Entity damage by distance (exposure approximated as unobstructed).
|
||||
let diameter = f64::from(radius) * 2.0;
|
||||
@@ -2901,7 +2905,8 @@ impl Game<'_> {
|
||||
let (x1, z1, y0, y1) = (x0 + 12.0, z0 + 12.0, bottom, bottom + 4.0);
|
||||
let mut quad = |p: [[f32; 3]; 4], shade: f32| {
|
||||
for v in p {
|
||||
out.push(Vertex { pos: v, uv, layer: 2, color: color(shade), light });
|
||||
// Overlay 4: clouds (unlit, faded by the cloud fog end).
|
||||
out.push(Vertex { pos: v, uv, layer: 4, color: color(shade), light });
|
||||
}
|
||||
};
|
||||
quad([[x0, y1, z0], [x0, y1, z1], [x1, y1, z1], [x1, y1, z0]], 1.0);
|
||||
@@ -4282,6 +4287,7 @@ impl Game<'_> {
|
||||
Vec::new()
|
||||
};
|
||||
let hand = if title || self.screen == Screen::Inventory { Vec::new() } else { self.hand_geometry(alpha) };
|
||||
let screen = if title { Vec::new() } else { self.screen_quads(alpha as f32, size) };
|
||||
let mut entities = entities;
|
||||
if !title {
|
||||
self.end_geometry(camera, &mut entities);
|
||||
@@ -4315,11 +4321,14 @@ impl Game<'_> {
|
||||
// The camera inside an opaque block sees nothing through it: disable.
|
||||
cave_culling: !self.res.facts.get(self.world.block(block[0], block[1], block[2])).solid_render,
|
||||
water_fog,
|
||||
fog: Some(self.frame_fog(camera, &sky, biome)),
|
||||
dark_disc: self.dark_disc(camera),
|
||||
outline,
|
||||
hud: &hud,
|
||||
entities: &entities,
|
||||
celestial: &celestial,
|
||||
hand: &hand,
|
||||
screen: &screen,
|
||||
game_time: self.world.game_time as f32,
|
||||
ticks: self.ticks,
|
||||
};
|
||||
@@ -4587,6 +4596,12 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { .. } if self.title.is_some() => {}
|
||||
WindowEvent::MouseInput { state, button, .. } if self.sign_edit.is_some() => {
|
||||
if state == ElementState::Pressed && button == MouseButton::Left {
|
||||
let size = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]).unwrap_or([1, 1]);
|
||||
self.sign_edit_click(size);
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { state, button, .. } => {
|
||||
let pressed = state == ElementState::Pressed;
|
||||
match self.screen {
|
||||
@@ -4658,6 +4673,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } if self.sign_edit.is_some() => self.sign_edit_key(&event),
|
||||
WindowEvent::KeyboardInput { event, .. }
|
||||
if self.screen == Screen::Creative && self.creative_screen.tab().search && event.state == ElementState::Pressed
|
||||
&& !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) =>
|
||||
@@ -4882,6 +4898,8 @@ pub fn run() -> Result<()> {
|
||||
let world = World::new(facts.air, 0);
|
||||
let creative = options.creative;
|
||||
let stations = horizon_client::stations::StationData::load(&root, &items);
|
||||
let animate = horizon_client::animate_tick::AnimateTables::load(&root, registry_owner.registry, &biomes)?;
|
||||
let fog = horizon_client::fog::FogRenderer::load(&root, &biomes);
|
||||
let mut resources = Resources {
|
||||
stations,
|
||||
assets,
|
||||
@@ -4894,7 +4912,10 @@ pub fn run() -> Result<()> {
|
||||
icons: HashMap::new(),
|
||||
layer_names,
|
||||
providers: Providers::load(&root),
|
||||
chest_model: horizon_client::mobs::load_model(&root, "minecraft:chest#main"),
|
||||
block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer::load(&root, ®istry_owner.registry)?,
|
||||
animate,
|
||||
fog,
|
||||
screen_fx: Default::default(),
|
||||
nether_environment: Environment::load_dimension(&root, "the_nether", false)?,
|
||||
end_environment: Environment::load_dimension(&root, "the_end", false)?,
|
||||
behaviours: Behaviours::load(registry_owner.registry, &root)?,
|
||||
@@ -4918,6 +4939,7 @@ pub fn run() -> Result<()> {
|
||||
settings.render_distance = d;
|
||||
}
|
||||
let look = options.look;
|
||||
let particles = horizon_client::particles::ParticleEngine::new(&root, &resources.atlas.sprites);
|
||||
let mut game = Game {
|
||||
res: &mut resources,
|
||||
collision: &collision,
|
||||
@@ -4970,7 +4992,8 @@ pub fn run() -> Result<()> {
|
||||
audio,
|
||||
dropped: Vec::new(),
|
||||
next_entity: 0,
|
||||
particles: Vec::new(),
|
||||
particles,
|
||||
sign_edit: None,
|
||||
spawn_search: 0,
|
||||
mobs: Vec::new(),
|
||||
arrows: Vec::new(),
|
||||
|
||||
@@ -81,6 +81,8 @@ impl Game<'_> {
|
||||
match words[0] {
|
||||
"help" => Ok(Some(json!({ "commands": HELP.iter().chain(super::station_control::HELP).collect::<Vec<_>>() }))),
|
||||
"help" => Ok(Some(json!({ "commands": HELP.iter().chain(super::blockctl::HELP).collect::<Vec<_>>() }))),
|
||||
"help" => Ok(Some(json!({ "commands": HELP.iter().chain(super::render_control::HELP).collect::<Vec<_>>() }))),
|
||||
"setblock" | "fill" | "particle" | "signedit" => self.render_command(&words),
|
||||
"status" => Ok(Some(self.control_status())),
|
||||
"key" => {
|
||||
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
//! Control-socket commands for inspecting rendering: place blocks without
|
||||
//! updates (`setblock`, `fill`) to build test scenes.
|
||||
use super::Game;
|
||||
use horizon_client::Result;
|
||||
use horizon_core::random::RandomSource;
|
||||
use horizon_world::registry::BlockStateId;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub const HELP: &[&str] = &[
|
||||
"setblock X Y Z STATE set a block state (name[prop=value,...]) without updates",
|
||||
"fill X1 Y1 Z1 X2 Y2 Z2 STATE fill a box with a block state without updates",
|
||||
"particle NAME X Y Z [DX DY DZ] [COUNT] spawn particles (vanilla /particle spread)",
|
||||
"signedit X Y Z [front|back] open the sign editor for the sign at X Y Z",
|
||||
];
|
||||
|
||||
impl Game<'_> {
|
||||
/// Parse `name[k=v,...]` into a registry state (defaults for missing properties).
|
||||
fn parse_state(&self, text: &str) -> Result<BlockStateId> {
|
||||
let (name, props) = match text.split_once('[') {
|
||||
Some((n, rest)) => (n, rest.trim_end_matches(']')),
|
||||
None => (text, ""),
|
||||
};
|
||||
let name = if name.contains(':') {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("minecraft:{name}")
|
||||
};
|
||||
let registry = &self.res.assets.registry;
|
||||
let default = registry
|
||||
.default_state(&name)
|
||||
.ok_or_else(|| format!("unknown block {name}"))?;
|
||||
let mut state = registry
|
||||
.state(default)
|
||||
.ok_or("missing default state")?
|
||||
.clone();
|
||||
for pair in props.split(',').filter(|p| !p.is_empty()) {
|
||||
let (k, v) = pair
|
||||
.split_once('=')
|
||||
.ok_or_else(|| format!("bad property {pair}"))?;
|
||||
if !state.properties.contains_key(k) {
|
||||
return Err(format!("{name} has no property {k}").into());
|
||||
}
|
||||
state.properties.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
Ok(registry.resolve(&state)?)
|
||||
}
|
||||
pub(super) fn render_command(&mut self, words: &[&str]) -> Result<Option<Value>> {
|
||||
let int = |i: usize| -> Result<i32> {
|
||||
Ok(words
|
||||
.get(i)
|
||||
.ok_or_else(|| format!("missing argument {i}"))?
|
||||
.parse::<i32>()?)
|
||||
};
|
||||
match words[0] {
|
||||
"setblock" => {
|
||||
let state = self.parse_state(words.get(4).ok_or("missing state")?)?;
|
||||
self.world.set(int(1)?, int(2)?, int(3)?, state)?;
|
||||
Ok(Some(json!({ "ok": true, "state": state.0 })))
|
||||
}
|
||||
"fill" => {
|
||||
let state = self.parse_state(words.get(7).ok_or("missing state")?)?;
|
||||
let (a, b) = ([int(1)?, int(2)?, int(3)?], [int(4)?, int(5)?, int(6)?]);
|
||||
let mut count = 0;
|
||||
for x in a[0].min(b[0])..=a[0].max(b[0]) {
|
||||
for y in a[1].min(b[1])..=a[1].max(b[1]) {
|
||||
for z in a[2].min(b[2])..=a[2].max(b[2]) {
|
||||
self.world.set(x, y, z, state)?;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(json!({ "ok": true, "blocks": count })))
|
||||
}
|
||||
"particle" => {
|
||||
use horizon_client::particles::{ParticleOptions, ParticleType};
|
||||
let ty = ParticleType::from_name(words.get(1).ok_or("missing particle")?)
|
||||
.ok_or("unknown particle type")?;
|
||||
let num = |i: usize, default: f64| -> Result<f64> {
|
||||
Ok(words.get(i).map_or(Ok(default), |w| w.parse::<f64>())?)
|
||||
};
|
||||
let at = [num(2, 0.0)?, num(3, 0.0)?, num(4, 0.0)?];
|
||||
let delta = [num(5, 0.0)?, num(6, 0.0)?, num(7, 0.0)?];
|
||||
let count = num(8, 1.0)? as u32;
|
||||
let options = match ty {
|
||||
ParticleType::Dust => ParticleOptions::dust([1.0, 0.0, 0.0], 1.0),
|
||||
ParticleType::Block | ParticleType::FallingDust | ParticleType::DustPillar => {
|
||||
ParticleOptions::block(ty, "block/stone".into(), 0x808080)
|
||||
}
|
||||
_ => ParticleOptions::simple(ty),
|
||||
};
|
||||
// ServerLevel.sendParticles: count 0 uses the delta as velocity.
|
||||
if count == 0 {
|
||||
self.particles.create(&options, at, delta);
|
||||
}
|
||||
for _ in 0..count {
|
||||
let r = self.particles.random();
|
||||
let p = [
|
||||
at[0] + r.next_gaussian() * delta[0],
|
||||
at[1] + r.next_gaussian() * delta[1],
|
||||
at[2] + r.next_gaussian() * delta[2],
|
||||
];
|
||||
self.particles.create(&options, p, [0.0; 3]);
|
||||
}
|
||||
Ok(Some(json!({ "ok": true, "live": self.particles.len() })))
|
||||
}
|
||||
"signedit" => {
|
||||
let key = (int(1)?, int(2)?, int(3)?);
|
||||
let name = self.res.facts.get(self.world.block(key.0, key.1, key.2)).name.clone();
|
||||
let entity = horizon_client::containers::BlockEntity::for_block(&name)
|
||||
.filter(|e| matches!(e, horizon_client::containers::BlockEntity::Sign(_)))
|
||||
.ok_or("no sign there")?;
|
||||
self.world.block_entities.entry(key).or_insert(entity);
|
||||
self.open_sign_editor(key, words.get(4) != Some(&"back"));
|
||||
Ok(Some(json!({ "ok": true })))
|
||||
}
|
||||
other => Err(format!("unknown render command {other}").into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
//! Per-tick client visuals: the particle engine, `ClientLevel.animateTick`,
|
||||
//! campfire smoke and rain splashes (`ClientLevel.tickWeatherEffects`).
|
||||
use super::{Dim, Game};
|
||||
use horizon_client::fog::{FogData, FogInputs, FogType, fog_type, update_rain_fog};
|
||||
use horizon_client::screen_effects::{ScreenInputs, ScreenQuad, lightmap_brightness};
|
||||
use horizon_client::{
|
||||
animate_tick::{AnimateContext, animate_tick, campfire_particles},
|
||||
biome::Biomes,
|
||||
blocks::{BlockFacts, Fluid},
|
||||
chunk::{HEIGHT, MIN_Y},
|
||||
particles::{ParticleLevel, ParticleOptions, ParticleType},
|
||||
world::World,
|
||||
};
|
||||
use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
|
||||
/// The first motion-blocking block at or below `from` (Heightmap MOTION_BLOCKING), plus one.
|
||||
fn motion_blocking(world: &World, facts: &BlockFacts, x: i32, z: i32, from: i32) -> i32 {
|
||||
let mut y = from.min(MIN_Y + HEIGHT - 1);
|
||||
while y > MIN_Y {
|
||||
let f = facts.get(world.block(x, y, z));
|
||||
if f.full_collision || f.fluid != Fluid::None || f.name.contains("leaves") {
|
||||
return y + 1;
|
||||
}
|
||||
y -= 1;
|
||||
}
|
||||
MIN_Y
|
||||
}
|
||||
/// `Biome.getPrecipitationAt` is rain (not snow) at this position.
|
||||
fn rains_at(world: &World, biomes: &Biomes, x: i32, y: i32, z: i32) -> bool {
|
||||
let Some(chunk) = world.chunks.get(&(x >> 4, z >> 4)) else {
|
||||
return false;
|
||||
};
|
||||
let b = biomes.get(chunk.biome(x, y, z));
|
||||
if !b.precipitation {
|
||||
return false;
|
||||
}
|
||||
let t = if y > 80 {
|
||||
b.temperature - (y - 80) as f32 * 0.05 / 40.0
|
||||
} else {
|
||||
b.temperature
|
||||
};
|
||||
t >= 0.15
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn forward(&self) -> [f64; 3] {
|
||||
let (yaw, pitch) = (
|
||||
f64::from(self.yaw).to_radians(),
|
||||
f64::from(self.pitch).to_radians(),
|
||||
);
|
||||
[
|
||||
-yaw.sin() * pitch.cos(),
|
||||
-pitch.sin(),
|
||||
yaw.cos() * pitch.cos(),
|
||||
]
|
||||
}
|
||||
/// `FogRenderer.setupFog` for the frame's camera.
|
||||
pub(super) fn frame_fog(
|
||||
&self,
|
||||
camera: glam::DVec3,
|
||||
sky: &horizon_client::environment::Sky,
|
||||
biome: u16,
|
||||
) -> FogData {
|
||||
let forward = self.forward();
|
||||
let at = [camera.x, camera.y, camera.z];
|
||||
let fog_type = fog_type(&self.world, &self.res.facts, at, forward);
|
||||
let water = self.res.biomes.get(biome).water_fog;
|
||||
let (rain, thunder) = if self.dim == Dim::Overworld {
|
||||
self.world.weather.levels(self.clock.fraction() as f32)
|
||||
} else {
|
||||
(0.0, 0.0)
|
||||
};
|
||||
self.res.fog.setup(&FogInputs {
|
||||
fog_type,
|
||||
sky,
|
||||
water_fog_color: [
|
||||
(water >> 16 & 255) as f32 / 255.0,
|
||||
(water >> 8 & 255) as f32 / 255.0,
|
||||
(water & 255) as f32 / 255.0,
|
||||
],
|
||||
biome,
|
||||
render_distance_chunks: self.streaming.radius,
|
||||
camera_y: camera.y,
|
||||
min_y: MIN_Y,
|
||||
flat: false,
|
||||
forward: forward.map(|c| c as f32),
|
||||
rain,
|
||||
thunder,
|
||||
skybox: self.dim == Dim::Overworld,
|
||||
blindness: None,
|
||||
})
|
||||
}
|
||||
/// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water.
|
||||
pub(super) fn dark_disc(&self, camera: glam::DVec3) -> bool {
|
||||
camera.y < 63.0
|
||||
&& fog_type(
|
||||
&self.world,
|
||||
&self.res.facts,
|
||||
[camera.x, camera.y, camera.z],
|
||||
self.forward(),
|
||||
) != FogType::Water
|
||||
}
|
||||
/// `ScreenEffectRenderer` + `Hud` camera overlays for this frame.
|
||||
pub(super) fn screen_quads(&self, partial: f32, size: [u32; 2]) -> Vec<ScreenQuad> {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let eye = [
|
||||
p.position.x,
|
||||
p.position.y + f64::from(p.dimensions.eye_height),
|
||||
p.position.z,
|
||||
];
|
||||
// LevelExtractor.getViewBlockingState: 8 points around the eye.
|
||||
let mut block_overlay = None;
|
||||
let w = f64::from(p.dimensions.width) * 0.8;
|
||||
for i in 0..8 {
|
||||
let t = [
|
||||
p.position.x + (f64::from(i & 1) - 0.5) * w,
|
||||
eye[1] + (f64::from((i >> 1) & 1) - 0.5) * 0.1,
|
||||
p.position.z + (f64::from((i >> 2) & 1) - 0.5) * w,
|
||||
];
|
||||
let state = self.world.block(
|
||||
t[0].floor() as i32,
|
||||
t[1].floor() as i32,
|
||||
t[2].floor() as i32,
|
||||
);
|
||||
let f = self.res.facts.get(state);
|
||||
if f.render_shape != horizon_client::blocks::RenderShape::Invisible
|
||||
&& f.solid_render
|
||||
&& f.full_collision
|
||||
{
|
||||
block_overlay = self.particle_sprite(state).map(|(name, _)| name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let in_water =
|
||||
fog_type(&self.world, &self.res.facts, eye, self.forward()) == FogType::Water;
|
||||
let water = in_water.then(|| (self.eye_brightness(eye), self.yaw, self.pitch));
|
||||
let camera_overlays = match &self.armor[0] {
|
||||
Some(stack) if &*stack.item == "minecraft:carved_pumpkin" => {
|
||||
vec!["misc/pumpkinblur".to_owned()]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
self.res.screen_fx.build(&ScreenInputs {
|
||||
sprites: &self.res.atlas.sprites,
|
||||
aspect: size[0] as f32 / size[1].max(1) as f32,
|
||||
partial,
|
||||
block_overlay,
|
||||
water,
|
||||
on_fire: false,
|
||||
camera_overlays,
|
||||
frozen: 0.0,
|
||||
vignette: true,
|
||||
border_warning: None,
|
||||
})
|
||||
}
|
||||
/// `Lightmap.getBrightness(getMaxLocalRawBrightness(eye))`.
|
||||
fn eye_brightness(&self, eye: [f64; 3]) -> f32 {
|
||||
let b = [
|
||||
eye[0].floor() as i32,
|
||||
eye[1].floor() as i32,
|
||||
eye[2].floor() as i32,
|
||||
];
|
||||
let packed = self.world.light(b[0], b[1], b[2]);
|
||||
let sky = i32::from(packed >> 4) - self.sky_darken();
|
||||
let raw = sky.max(i32::from(packed & 15)).clamp(0, 15) as u8;
|
||||
lightmap_brightness(if self.dim == Dim::Nether { 0.1 } else { 0.0 }, raw)
|
||||
}
|
||||
pub(super) fn tick_particles(&mut self) {
|
||||
let eye = self.eye_position();
|
||||
if let Some(e) = eye {
|
||||
let brightness = self.eye_brightness(e);
|
||||
let inside_portal = self.portal_ticks > 0;
|
||||
self.res.screen_fx.tick(brightness, inside_portal);
|
||||
// LocalPlayer water vision and AtmosphericFogEnvironment rain fog.
|
||||
let in_water =
|
||||
fog_type(&self.world, &self.res.facts, e, self.forward()) == FogType::Water;
|
||||
self.res.fog.state.tick(in_water);
|
||||
let b = [
|
||||
e[0].floor() as i32,
|
||||
e[1].floor() as i32,
|
||||
e[2].floor() as i32,
|
||||
];
|
||||
let rain = if self.dim == Dim::Overworld {
|
||||
self.world.weather.levels(1.0).0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let biome = self
|
||||
.world
|
||||
.chunks
|
||||
.get(&(b[0] >> 4, b[2] >> 4))
|
||||
.map_or(0, |c| c.biome(b[0], b[1], b[2]));
|
||||
let rains = self.res.biomes.get(biome).precipitation;
|
||||
update_rain_fog(
|
||||
&mut self.res.fog.state,
|
||||
rain,
|
||||
self.world.light(b[0], b[1], b[2]) >> 4,
|
||||
rains,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
if let Some(e) = eye {
|
||||
self.particles.camera = e;
|
||||
}
|
||||
let (rain, _) = if self.dim == Dim::Overworld {
|
||||
self.world.weather.levels(1.0)
|
||||
} else {
|
||||
(0.0, 0.0)
|
||||
};
|
||||
let world = &self.world;
|
||||
let facts = &self.res.facts;
|
||||
let biomes = &self.res.biomes;
|
||||
let raining = rain > 0.2;
|
||||
let raining_at = |p: [i32; 3]| {
|
||||
raining
|
||||
&& motion_blocking(world, facts, p[0], p[2], p[1] + 64) <= p[1]
|
||||
&& rains_at(world, biomes, p[0], p[1], p[2])
|
||||
};
|
||||
let ctx = AnimateContext {
|
||||
world,
|
||||
facts,
|
||||
collision: self.collision,
|
||||
biomes,
|
||||
registry: self.res.assets.registry,
|
||||
raining_at: &raining_at,
|
||||
};
|
||||
if let Some(e) = eye {
|
||||
let block = [
|
||||
e[0].floor() as i32,
|
||||
e[1].floor() as i32,
|
||||
e[2].floor() as i32,
|
||||
];
|
||||
animate_tick(&self.res.animate, &mut self.particles, &ctx, block);
|
||||
if rain > 0.0 {
|
||||
// ClientLevel.tickWeatherEffects: rain splashes (weather radius 10).
|
||||
let mut random = LegacyRandom::new(self.world.game_time.wrapping_mul(312_987_231));
|
||||
let radius = 10;
|
||||
let diameter = 2 * radius + 1;
|
||||
let count = (0.225 * (diameter * diameter) as f32 * rain * rain) as i32;
|
||||
for _ in 0..count {
|
||||
let x = block[0] + random.next_int_bound(diameter).unwrap_or(0) - radius;
|
||||
let z = block[2] + random.next_int_bound(diameter).unwrap_or(0) - radius;
|
||||
let top = motion_blocking(world, facts, x, z, block[1] + 64);
|
||||
if top <= MIN_Y
|
||||
|| top > block[1] + 10
|
||||
|| top < block[1] - 10
|
||||
|| !rains_at(world, biomes, x, top, z)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let below = top - 1;
|
||||
let (bx, bz) = (random.next_double(), random.next_double());
|
||||
let state = world.block(x, below, z);
|
||||
let f = facts.get(state);
|
||||
let block_top = match self.collision.cached_shapes().cached_shape(state) {
|
||||
Ok(Some(shape)) if !shape.is_empty() => {
|
||||
shape.max_at(horizon_core::geometry::Axis::Y, bx, bz)
|
||||
}
|
||||
_ => 0.0,
|
||||
};
|
||||
let fluid_top = if f.fluid == Fluid::None {
|
||||
0.0
|
||||
} else {
|
||||
f64::from(f.fluid_level) / 9.0
|
||||
};
|
||||
let smoke = f.fluid == Fluid::Lava
|
||||
|| &*f.name == "minecraft:magma_block"
|
||||
|| (f.name.ends_with("campfire")
|
||||
&& self.res.animate.is_lit_campfire(state.0));
|
||||
let ty = if smoke {
|
||||
ParticleType::Smoke
|
||||
} else {
|
||||
ParticleType::Rain
|
||||
};
|
||||
let p = [
|
||||
f64::from(x) + bx,
|
||||
f64::from(below) + block_top.max(fluid_top),
|
||||
f64::from(z) + bz,
|
||||
];
|
||||
self.particles
|
||||
.add(&ParticleOptions::simple(ty), p, [0.0; 3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(r) = &self.renderer {
|
||||
campfire_particles(
|
||||
&self.res.animate,
|
||||
&mut self.particles,
|
||||
&ctx,
|
||||
r.block_entities(),
|
||||
);
|
||||
}
|
||||
let level = ParticleLevel {
|
||||
world,
|
||||
facts,
|
||||
collision: self.collision,
|
||||
player: self
|
||||
.player
|
||||
.as_ref()
|
||||
.map(|p| ([p.position.x, p.position.y, p.position.z], p.velocity.y)),
|
||||
};
|
||||
self.particles.tick(&level);
|
||||
for (name, at, volume, pitch) in std::mem::take(&mut self.particles.sounds) {
|
||||
self.audio.play(name, Some(at), volume, pitch);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
//! The sign editing screen (`SignEditScreen` / `HangingSignEditScreen`):
|
||||
//! opened when a sign is placed, four lines limited to the sign's line
|
||||
//! width, Up/Down/Enter move between lines, Escape or Done closes.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
containers::BlockEntity,
|
||||
hud::{HudBatch, rgba},
|
||||
signs::{SignData, wood_type},
|
||||
};
|
||||
use std::time::Instant;
|
||||
use winit::{
|
||||
event::{ElementState, KeyEvent},
|
||||
keyboard::{KeyCode, PhysicalKey},
|
||||
};
|
||||
|
||||
pub(super) struct SignEditor {
|
||||
pub pos: (i32, i32, i32),
|
||||
pub front: bool,
|
||||
pub line: usize,
|
||||
pub opened: Instant,
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn edited_sign(&mut self) -> Option<&mut SignData> {
|
||||
let key = self.sign_edit.as_ref()?.pos;
|
||||
match self.world.block_entities.get_mut(&key) {
|
||||
Some(BlockEntity::Sign(sign)) => Some(sign),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `SignBlock.openTextEdit` for the front side after placement.
|
||||
pub(super) fn open_sign_editor(&mut self, pos: (i32, i32, i32), front: bool) {
|
||||
self.sign_edit = Some(SignEditor { pos, front, line: 0, opened: Instant::now() });
|
||||
self.keys.clear();
|
||||
self.right = false;
|
||||
self.capture(false);
|
||||
}
|
||||
fn close_sign_editor(&mut self) {
|
||||
if let Some(edit) = self.sign_edit.take() {
|
||||
self.world.modified.insert((edit.pos.0 >> 4, edit.pos.2 >> 4));
|
||||
}
|
||||
self.capture(true);
|
||||
}
|
||||
pub(super) fn sign_edit_key(&mut self, event: &KeyEvent) {
|
||||
if event.state != ElementState::Pressed {
|
||||
return;
|
||||
}
|
||||
let Some(edit) = self.sign_edit.as_mut() else { return };
|
||||
let front = edit.front;
|
||||
match event.physical_key {
|
||||
PhysicalKey::Code(KeyCode::Escape) => self.close_sign_editor(),
|
||||
PhysicalKey::Code(KeyCode::ArrowUp) => edit.line = (edit.line + 3) & 3,
|
||||
PhysicalKey::Code(KeyCode::ArrowDown | KeyCode::Enter | KeyCode::NumpadEnter) => edit.line = (edit.line + 1) & 3,
|
||||
PhysicalKey::Code(KeyCode::Backspace) => {
|
||||
let line = edit.line;
|
||||
if let Some(sign) = self.edited_sign() {
|
||||
let text = if front { &mut sign.front } else { &mut sign.back };
|
||||
text.lines[line].pop();
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let Some(typed) = event.text.as_ref().map(|t| t.to_string()) else { return };
|
||||
let line = edit.line;
|
||||
let atlas = &self.res.atlas;
|
||||
let width = |s: &str| HudBatch::text_width(atlas, s);
|
||||
let Some(key) = self.sign_edit.as_ref().map(|e| e.pos) else { return };
|
||||
if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) {
|
||||
let max = sign.max_line_width();
|
||||
let text = if front { &mut sign.front } else { &mut sign.back };
|
||||
for ch in typed.chars().filter(|c| !c.is_control()) {
|
||||
let mut next = text.lines[line].clone();
|
||||
next.push(ch);
|
||||
// TextFieldHelper filter: font.width(s) <= maxTextLineWidth.
|
||||
if width(&next) <= max {
|
||||
text.lines[line] = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Done button (`this.width / 2 - 100, this.height / 4 + 144`, 200x20).
|
||||
pub(super) fn sign_edit_click(&mut self, size: [u32; 2]) {
|
||||
let b = HudBatch::new(size);
|
||||
let (x, y) = (b.width / 2.0 - 100.0, b.height / 4.0 + 144.0);
|
||||
let (mx, my) = self.cursor;
|
||||
if mx >= x && mx < x + 200.0 && my >= y && my < y + 20.0 {
|
||||
self.close_sign_editor();
|
||||
}
|
||||
}
|
||||
pub(super) fn draw_sign_editor(&self, batch: &mut HudBatch) {
|
||||
let Some(edit) = &self.sign_edit else { return };
|
||||
let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) else { return };
|
||||
let atlas = &self.res.atlas;
|
||||
let (w, h) = (batch.width, batch.height);
|
||||
batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 16, 160));
|
||||
let title = if sign.hanging { "Edit Hanging Sign Message" } else { "Edit Sign Message" };
|
||||
let tw = HudBatch::text_width(atlas, title);
|
||||
batch.text(atlas, title, (w - tw) / 2.0, 40.0, u32::MAX, true);
|
||||
let name = self.res.facts.get(self.world.block(edit.pos.0, edit.pos.1, edit.pos.2)).name.clone();
|
||||
let wood = wood_type(&name);
|
||||
let cx = w / 2.0;
|
||||
let y = if sign.hanging {
|
||||
// HangingSignEditScreen: 16x16 texture scaled 4.5 at (0, -13).
|
||||
let s = 4.5;
|
||||
batch.sprite_scaled(atlas, &format!("gui/hanging_signs/{wood}"), cx - 8.0 * s, 125.0 - 13.0 - 8.0 * s, 16.0 * s, 16.0 * s, u32::MAX);
|
||||
125.0
|
||||
} else {
|
||||
// SignEditScreen: 24x26 texture scaled 3.9 at (0, 27); wall signs show 12 rows.
|
||||
let s = 3.9;
|
||||
let wall = name.contains("_wall_");
|
||||
let rows = if wall { 12.0 } else { 26.0 };
|
||||
if let Some(mut r) = atlas.sprites.get(&format!("gui/signs/{wood}")).copied() {
|
||||
r.v1 = r.v0 + (r.v1 - r.v0) * rows / 26.0;
|
||||
batch.rect_uv(cx - 12.0 * s, 90.0 + 27.0 - 13.0 * s, 24.0 * s, rows * s, r, u32::MAX);
|
||||
}
|
||||
90.0
|
||||
};
|
||||
let text = if edit.front { &sign.front } else { &sign.back };
|
||||
let color = if text.glowing { text.text_color() } else { text.dark_color() };
|
||||
let color = rgba((color >> 16) as u8, (color >> 8) as u8, color as u8, 255);
|
||||
let line_height = sign.line_height();
|
||||
let midpoint = (4.0 * line_height / 2.0).floor();
|
||||
let blink = (edit.opened.elapsed().as_millis() / 300) % 2 == 0;
|
||||
for (i, line) in text.lines.iter().enumerate() {
|
||||
let lw = HudBatch::text_width(atlas, line);
|
||||
let x = cx - (lw as i32 / 2) as f32;
|
||||
let ly = y + i as f32 * line_height - midpoint;
|
||||
batch.text(atlas, line, x, ly, color, false);
|
||||
if i == edit.line && blink {
|
||||
// TextCursorUtils.extractAppendCursor: an underscore after the text.
|
||||
batch.text(atlas, "_", x + lw, ly, color, false);
|
||||
}
|
||||
}
|
||||
let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 144.0);
|
||||
batch.sprite_scaled(atlas, "gui/sprites/widget/button", bx, by, 200.0, 20.0, u32::MAX);
|
||||
let tw = HudBatch::text_width(atlas, "Done");
|
||||
batch.text(atlas, "Done", bx + (200.0 - tw) / 2.0, by + 6.0, u32::MAX, true);
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,8 @@ struct Globals {
|
||||
inverse_view: [[f32; 4]; 4],
|
||||
sunrise: [f32; 4],
|
||||
sun: [f32; 4],
|
||||
/// x: sky fog end, y: cloud fog end, z: dark disc (camera below the horizon), w: unused.
|
||||
fog_ends: [f32; 4],
|
||||
}
|
||||
pub type SectionKey = (i32, i32, i32);
|
||||
struct SectionGpu {
|
||||
@@ -54,6 +56,10 @@ pub struct Frame<'a> {
|
||||
/// Environmental fog start/end (Nether 10..96), if any.
|
||||
pub environment_fog: Option<(f32, f32)>,
|
||||
pub water_fog: [f32; 3],
|
||||
/// `FogRenderer.setupFog` result; replaces the underwater/environment fields when set.
|
||||
pub fog: Option<crate::fog::FogData>,
|
||||
/// Camera eye below the horizon height and not under water (`shouldRenderDarkDisc`).
|
||||
pub dark_disc: bool,
|
||||
pub outline: Option<[f64; 6]>,
|
||||
pub hud: &'a HudBatch,
|
||||
/// Camera-relative entity geometry textured from the shared atlas.
|
||||
@@ -62,6 +68,8 @@ pub struct Frame<'a> {
|
||||
pub celestial: &'a [Vertex],
|
||||
/// First-person hand and held item, drawn after clearing depth.
|
||||
pub hand: &'a [Vertex],
|
||||
/// Full-screen camera effects drawn over the world and hand, under the HUD.
|
||||
pub screen: &'a [crate::screen_effects::ScreenQuad],
|
||||
pub game_time: f32,
|
||||
pub ticks: u64,
|
||||
}
|
||||
@@ -75,10 +83,15 @@ pub struct Renderer {
|
||||
solid: wgpu::RenderPipeline,
|
||||
translucent: wgpu::RenderPipeline,
|
||||
sky: wgpu::RenderPipeline,
|
||||
dark_disc: wgpu::RenderPipeline,
|
||||
lines: wgpu::RenderPipeline,
|
||||
entity_pipeline: wgpu::RenderPipeline,
|
||||
celestial_pipeline: wgpu::RenderPipeline,
|
||||
celestial_buffer: wgpu::Buffer,
|
||||
/// Screen effects: alpha-blended and vignette (`dst * (1 - src)`) pipelines.
|
||||
screen_pipelines: [wgpu::RenderPipeline; 2],
|
||||
screen_buffer: wgpu::Buffer,
|
||||
screen_capacity: u64,
|
||||
entity_group: wgpu::BindGroup,
|
||||
entity_buffer: wgpu::Buffer,
|
||||
entity_capacity: u64,
|
||||
@@ -95,6 +108,8 @@ pub struct Renderer {
|
||||
outline: wgpu::Buffer,
|
||||
depth: wgpu::TextureView,
|
||||
sections: HashMap<SectionKey, SectionGpu>,
|
||||
/// Block-entity blocks per meshed section (world position, state id).
|
||||
block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>,
|
||||
/// VisGraph face connectivity per meshed section (cave culling).
|
||||
visibility: HashMap<SectionKey, u64>,
|
||||
reachable: std::collections::HashSet<SectionKey>,
|
||||
@@ -360,6 +375,7 @@ impl Renderer {
|
||||
Some(alpha_blend),
|
||||
);
|
||||
let sky = pipeline("Sky", "vs_sky", "fs_sky", &[], tri, None, false, false, None);
|
||||
let dark_disc = pipeline("Dark disc", "vs_sky", "fs_dark_disc", &[], tri, None, false, false, Some(alpha_blend));
|
||||
let lines = pipeline(
|
||||
"Block outline",
|
||||
"vs_line",
|
||||
@@ -650,6 +666,62 @@ impl Renderer {
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
let screen_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Horizon screen effects"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("screen.wgsl").into()),
|
||||
});
|
||||
let screen_attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4];
|
||||
let screen_vertex = [Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<crate::screen_effects::ScreenVertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &screen_attributes,
|
||||
})];
|
||||
let vignette_blend = wgpu::BlendState {
|
||||
color: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::Zero,
|
||||
dst_factor: wgpu::BlendFactor::OneMinusSrc,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
alpha: wgpu::BlendComponent {
|
||||
src_factor: wgpu::BlendFactor::Zero,
|
||||
dst_factor: wgpu::BlendFactor::One,
|
||||
operation: wgpu::BlendOperation::Add,
|
||||
},
|
||||
};
|
||||
let screen_pipelines = [("fs_screen", alpha_blend), ("fs_vignette", vignette_blend)].map(|(entry, blend)| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Screen effects"),
|
||||
layout: Some(&entity_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &screen_shader,
|
||||
entry_point: Some("vs_screen"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &screen_vertex,
|
||||
},
|
||||
primitive: wgpu::PrimitiveState { cull_mode: None, ..Default::default() },
|
||||
depth_stencil: None,
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &screen_shader,
|
||||
entry_point: Some(entry),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: config.format.remove_srgb_suffix(),
|
||||
blend: Some(blend),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
});
|
||||
let screen_capacity = 64;
|
||||
let screen_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Screen effect vertices"),
|
||||
size: screen_capacity * std::mem::size_of::<crate::screen_effects::ScreenVertex>() as u64,
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let celestial_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Celestial vertices"),
|
||||
size: 2048 * 4 * std::mem::size_of::<Vertex>() as u64,
|
||||
@@ -673,10 +745,14 @@ impl Renderer {
|
||||
solid,
|
||||
translucent,
|
||||
sky,
|
||||
dark_disc,
|
||||
lines,
|
||||
entity_pipeline,
|
||||
celestial_pipeline,
|
||||
celestial_buffer,
|
||||
screen_pipelines,
|
||||
screen_buffer,
|
||||
screen_capacity,
|
||||
entity_group,
|
||||
entity_buffer,
|
||||
entity_capacity,
|
||||
@@ -693,6 +769,7 @@ impl Renderer {
|
||||
outline,
|
||||
depth,
|
||||
sections: HashMap::new(),
|
||||
block_entities: HashMap::new(),
|
||||
visibility: HashMap::new(),
|
||||
reachable: std::collections::HashSet::new(),
|
||||
reachable_from: None,
|
||||
@@ -772,6 +849,11 @@ impl Renderer {
|
||||
if self.visibility.insert(key, mesh.visibility) != Some(mesh.visibility) {
|
||||
self.visibility_dirty = true;
|
||||
}
|
||||
if mesh.block_entities.is_empty() {
|
||||
self.block_entities.remove(&key);
|
||||
} else {
|
||||
self.block_entities.insert(key, mesh.block_entities.clone());
|
||||
}
|
||||
let solid = (mesh.solid.len() / 4) as u32;
|
||||
let translucent = (mesh.translucent.len() / 4) as u32;
|
||||
if solid + translucent == 0 {
|
||||
@@ -804,7 +886,12 @@ impl Renderer {
|
||||
},
|
||||
);
|
||||
}
|
||||
/// Block-entity blocks of every meshed section (see `SectionMesh::block_entities`).
|
||||
pub fn block_entities(&self) -> impl Iterator<Item = &([i32; 3], u32)> {
|
||||
self.block_entities.values().flatten()
|
||||
}
|
||||
pub fn clear_sections(&mut self) {
|
||||
self.block_entities.clear();
|
||||
self.sections.clear();
|
||||
self.visibility.clear();
|
||||
self.visibility_dirty = true;
|
||||
@@ -844,6 +931,7 @@ impl Renderer {
|
||||
self.visibility_dirty = false;
|
||||
}
|
||||
pub fn remove(&mut self, key: SectionKey) {
|
||||
self.block_entities.remove(&key);
|
||||
self.visibility.remove(&key);
|
||||
self.visibility_dirty = true;
|
||||
self.sections.remove(&key);
|
||||
@@ -985,7 +1073,9 @@ impl Renderer {
|
||||
let sun_angle = frame.sky.sun_angle.to_radians();
|
||||
// Celestial bodies rotate around the X axis; angle 0 = noon.
|
||||
let sun = Vec3::new(0.0, sun_angle.cos(), -sun_angle.sin());
|
||||
let (fog_color, fog) = if frame.underwater {
|
||||
let (fog_color, fog) = if let Some(f) = frame.fog {
|
||||
(f.color, [f.environmental_start, f.environmental_end, f.render_distance_start, f.render_distance_end])
|
||||
} else if frame.underwater {
|
||||
(
|
||||
[frame.water_fog[0], frame.water_fog[1], frame.water_fog[2], 1.0],
|
||||
[-8.0, 96.0, -8.0, 96.0],
|
||||
@@ -1015,6 +1105,12 @@ impl Renderer {
|
||||
inverse_view: view.inverse().to_cols_array_2d(),
|
||||
sunrise: frame.sky.sunrise_color,
|
||||
sun: [sun.x, sun.y, sun.z, frame.sky.star_brightness],
|
||||
fog_ends: [
|
||||
frame.fog.map_or(frame.distance.min(512.0), |f| f.sky_end),
|
||||
frame.fog.map_or(2048.0, |f| f.cloud_end),
|
||||
if frame.dark_disc { 1.0 } else { 0.0 },
|
||||
0.0,
|
||||
],
|
||||
};
|
||||
self.queue
|
||||
.write_buffer(&self.globals, 0, bytemuck::bytes_of(&globals));
|
||||
@@ -1187,6 +1283,13 @@ impl Renderer {
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
if !frame.underwater && (frame.skybox || frame.end_sky) {
|
||||
if !frame.title && frame.skybox {
|
||||
// LevelRenderer: no sky inside lava or powder snow (sky fog ends within 2 blocks).
|
||||
let sky_visible = match frame.fog {
|
||||
Some(f) => f.sky_end > 2.0,
|
||||
None => !frame.underwater,
|
||||
};
|
||||
if sky_visible && frame.skybox {
|
||||
if !frame.title {
|
||||
pass.set_pipeline(&self.sky);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
@@ -1198,6 +1301,10 @@ impl Renderer {
|
||||
pass.draw_indexed(0..(celestial_vertices as u32 / 4) * 6, 0, 0..1);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
}
|
||||
if !frame.title && frame.dark_disc {
|
||||
pass.set_pipeline(&self.dark_disc);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
if frame.title {
|
||||
visible.clear();
|
||||
@@ -1269,6 +1376,41 @@ impl Renderer {
|
||||
pass.set_vertex_buffer(0, self.entity_buffer.slice(..));
|
||||
pass.draw_indexed(0..hand_quads * 6, (entity_quads * 4) as i32, 0..1);
|
||||
}
|
||||
if !frame.screen.is_empty() {
|
||||
let vertices: Vec<crate::screen_effects::ScreenVertex> = frame.screen.iter().flat_map(|q| q.vertices).collect();
|
||||
if vertices.len() as u64 > self.screen_capacity {
|
||||
self.screen_capacity = (vertices.len() as u64).next_power_of_two();
|
||||
self.screen_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Screen effect vertices"),
|
||||
size: self.screen_capacity * std::mem::size_of::<crate::screen_effects::ScreenVertex>() as u64,
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
}
|
||||
self.queue.write_buffer(&self.screen_buffer, 0, bytemuck::cast_slice(&vertices));
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: &view_target,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store },
|
||||
})];
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Screen effects"),
|
||||
color_attachments: &attachments,
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_bind_group(0, &self.entity_group, &[]);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(0, self.screen_buffer.slice(..));
|
||||
for (i, quad) in frame.screen.iter().enumerate() {
|
||||
let pipeline = match quad.blend {
|
||||
crate::screen_effects::Blend::Alpha => &self.screen_pipelines[0],
|
||||
crate::screen_effects::Blend::Vignette => &self.screen_pipelines[1],
|
||||
};
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.draw_indexed(0..6, (i * 4) as i32, 0..1);
|
||||
}
|
||||
}
|
||||
self.hud.draw(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
|
||||
@@ -59,6 +59,10 @@ fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
}
|
||||
}
|
||||
impl HudAtlas {
|
||||
/// A font glyph's atlas cell (8x8 GUI pixels) and advance.
|
||||
pub fn glyph(&self, ch: char) -> Option<(Rect, f32)> {
|
||||
self.glyphs.get(&ch).map(|g| (g.rect, g.advance))
|
||||
}
|
||||
pub fn build(root: &Path) -> Result<Self> {
|
||||
let textures = root.join("assets/minecraft/textures");
|
||||
let mut files = Vec::new();
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
//! Horizon native client: resources, world streaming, rendering and the
|
||||
//! bindings between the validated simulation pieces and the game loop.
|
||||
#![forbid(unsafe_code)]
|
||||
pub mod animate_tick;
|
||||
pub mod assets;
|
||||
pub mod attribute_updates;
|
||||
pub mod audio;
|
||||
pub mod biome;
|
||||
pub mod block_entity_render;
|
||||
pub mod blocks;
|
||||
pub mod brewing;
|
||||
pub mod chunk;
|
||||
@@ -23,6 +25,7 @@ pub mod entity_nbt;
|
||||
pub mod environment;
|
||||
pub mod font;
|
||||
pub mod gamerules;
|
||||
pub mod fog;
|
||||
pub mod gfx;
|
||||
pub mod health;
|
||||
pub mod hud;
|
||||
@@ -47,7 +50,10 @@ pub mod particles;
|
||||
pub mod pose;
|
||||
pub mod projectiles;
|
||||
pub mod save;
|
||||
pub mod screen_effects;
|
||||
pub mod settings;
|
||||
pub mod shadows;
|
||||
pub mod signs;
|
||||
pub mod sprint;
|
||||
pub mod sprites;
|
||||
pub mod stations;
|
||||
|
||||
+269
-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)]
|
||||
@@ -32,10 +38,14 @@ pub struct SectionMesh {
|
||||
/// VisGraph: bit `a * 6 + b` is set when faces `a` and `b` (Direction
|
||||
/// order) are connected through non-opaque blocks.
|
||||
pub visibility: u64,
|
||||
/// Blocks with a block-entity renderer (world position, state id), drawn
|
||||
/// each frame by `block_entity_render` like vanilla's per-section
|
||||
/// `SectionCompiler.Results.blockEntities`.
|
||||
pub block_entities: Vec<([i32; 3], u32)>,
|
||||
}
|
||||
impl Default for SectionMesh {
|
||||
fn default() -> Self {
|
||||
Self { solid: Vec::new(), translucent: Vec::new(), visibility: ALL_VISIBLE }
|
||||
Self { solid: Vec::new(), translucent: Vec::new(), visibility: ALL_VISIBLE, block_entities: Vec::new() }
|
||||
}
|
||||
}
|
||||
pub const ALL_VISIBLE: u64 = (1 << 36) - 1;
|
||||
@@ -100,22 +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,
|
||||
}
|
||||
@@ -140,75 +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,
|
||||
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>,
|
||||
@@ -218,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 {
|
||||
@@ -269,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 {
|
||||
@@ -288,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.
|
||||
@@ -335,7 +458,10 @@ 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)));
|
||||
}
|
||||
if state.solid
|
||||
&& Direction::ALL.iter().all(|d| {
|
||||
let [dx, dy, dz] = d.normal();
|
||||
@@ -344,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;
|
||||
@@ -355,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();
|
||||
@@ -369,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -390,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],
|
||||
@@ -406,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(
|
||||
@@ -416,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)?;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -350,6 +350,7 @@ fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity, b
|
||||
entries.push(("total_fuel", Tag::Int(b.total_fuel)));
|
||||
entries.push(("speed_multiplier", Tag::Float(b.speed.to_bits())));
|
||||
}
|
||||
BlockEntity::Sign(sign) => entries.extend(sign.encode()),
|
||||
}
|
||||
Tag::compound(entries)
|
||||
}
|
||||
@@ -387,6 +388,7 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers:
|
||||
_ => 1.0,
|
||||
};
|
||||
}
|
||||
BlockEntity::Sign(sign) => sign.decode(tag),
|
||||
}
|
||||
Some((pos, entity))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// Full-screen camera effects (screen_effects.rs): clip-space quads sampling
|
||||
// the shared 2D atlas with repeat inside each sprite rectangle.
|
||||
@group(0) @binding(1) var atlas: texture_2d<f32>;
|
||||
@group(0) @binding(2) var atlas_sampler: sampler;
|
||||
struct Out {
|
||||
@builtin(position) clip: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
@location(1) @interpolate(flat) rect: vec4<f32>,
|
||||
@location(2) color: vec4<f32>,
|
||||
}
|
||||
@vertex fn vs_screen(@location(0) pos: vec2<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) rect: vec4<f32>, @location(3) color: vec4<f32>) -> Out {
|
||||
var out: Out;
|
||||
out.clip = vec4(pos, 0.0, 1.0);
|
||||
out.uv = uv;
|
||||
out.rect = rect;
|
||||
out.color = color;
|
||||
return out;
|
||||
}
|
||||
fn sample(in: Out) -> vec4<f32> {
|
||||
let f = fract(in.uv);
|
||||
let uv = in.rect.xy + f * (in.rect.zw - in.rect.xy);
|
||||
return textureSampleLevel(atlas, atlas_sampler, uv, 0.0) * in.color;
|
||||
}
|
||||
@fragment fn fs_screen(in: Out) -> @location(0) vec4<f32> {
|
||||
let c = sample(in);
|
||||
if c.a <= 0.0 { discard; }
|
||||
return c;
|
||||
}
|
||||
// RenderPipelines.VIGNETTE blends ZERO, ONE_MINUS_SRC_COLOR: output the
|
||||
// texture colour; the blend state darkens the frame by it.
|
||||
@fragment fn fs_vignette(in: Out) -> @location(0) vec4<f32> {
|
||||
return vec4(sample(in).rgb, 1.0);
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
//! Full-screen camera effects drawn between the world and the HUD:
|
||||
//! `ScreenEffectRenderer` (in-wall block texture, underwater overlay, fire)
|
||||
//! and the `Hud` camera overlays (vignette, pumpkin blur, powder-snow
|
||||
//! outline, nether portal swirl). Positions are clip-space quads; textures
|
||||
//! come from the shared 2D atlas and may repeat.
|
||||
use crate::hud::Rect;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Blend {
|
||||
/// `GUI_TEXTURED` / screen effects: alpha blending.
|
||||
Alpha,
|
||||
/// `RenderPipelines.VIGNETTE`: `dst * (1 - src)`.
|
||||
Vignette,
|
||||
}
|
||||
/// One clip-space vertex of a screen quad.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct ScreenVertex {
|
||||
pub pos: [f32; 2],
|
||||
/// Texture coordinates in sprite units (repeat outside 0..1).
|
||||
pub uv: [f32; 2],
|
||||
/// Atlas rectangle (u0, v0, u1, v1) of the sprite.
|
||||
pub rect: [f32; 4],
|
||||
pub color: [f32; 4],
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ScreenQuad {
|
||||
pub vertices: [ScreenVertex; 4],
|
||||
pub blend: Blend,
|
||||
}
|
||||
|
||||
/// What the camera sees this frame.
|
||||
pub struct ScreenInputs<'a> {
|
||||
pub sprites: &'a HashMap<String, Rect>,
|
||||
pub aspect: f32,
|
||||
pub partial: f32,
|
||||
/// Particle sprite of the view-blocking block around the eye.
|
||||
pub block_overlay: Option<String>,
|
||||
/// Eye in water: (lightmap brightness at the eye, yaw, pitch).
|
||||
pub water: Option<(f32, f32, f32)>,
|
||||
pub on_fire: bool,
|
||||
/// Equipment camera overlays (`Equippable.cameraOverlay`, e.g. `misc/pumpkinblur`).
|
||||
pub camera_overlays: Vec<String>,
|
||||
/// `Player.getPercentFrozen`.
|
||||
pub frozen: f32,
|
||||
/// `Options.vignette`.
|
||||
pub vignette: bool,
|
||||
/// Distance to the world border and its warning distance, when close.
|
||||
pub border_warning: Option<f32>,
|
||||
}
|
||||
|
||||
/// Effect state advanced every tick.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct ScreenEffects {
|
||||
/// `Hud.vignetteBrightness`.
|
||||
pub vignette_brightness: f32,
|
||||
pub portal: f32,
|
||||
pub o_portal: f32,
|
||||
}
|
||||
impl Default for ScreenEffects {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
vignette_brightness: 1.0,
|
||||
portal: 0.0,
|
||||
o_portal: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Lightmap.getBrightness`.
|
||||
pub fn lightmap_brightness(ambient_light: f32, level: u8) -> f32 {
|
||||
let v = f32::from(level) / 15.0;
|
||||
let curved = v / (4.0 - 3.0 * v);
|
||||
curved + (1.0 - curved) * ambient_light
|
||||
}
|
||||
/// Clip-space scale of the hand projection (fov 70) at view depth 0.5.
|
||||
fn hand_scale(aspect: f32) -> [f32; 2] {
|
||||
let half = 0.5 * (35.0f32).to_radians().tan();
|
||||
[1.0 / (half * aspect), 1.0 / half]
|
||||
}
|
||||
impl ScreenEffects {
|
||||
/// `Hud.updateVignetteBrightness` and `LocalPlayer.handlePortalTransitionEffect`.
|
||||
pub fn tick(&mut self, eye_brightness: f32, inside_portal: bool) {
|
||||
let target = (1.0 - eye_brightness).clamp(0.0, 1.0);
|
||||
self.vignette_brightness += (target - self.vignette_brightness) * 0.01;
|
||||
self.o_portal = self.portal;
|
||||
let step = if inside_portal {
|
||||
0.0125
|
||||
} else if self.portal > 0.0 {
|
||||
-0.05
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
self.portal = (self.portal + step).clamp(0.0, 1.0);
|
||||
}
|
||||
pub fn build(&self, input: &ScreenInputs) -> Vec<ScreenQuad> {
|
||||
let mut out = Vec::new();
|
||||
let sprite = |name: &str| input.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
|
||||
let scale = hand_scale(input.aspect);
|
||||
// Screen-effect quads live at view depth 0.5 in the hand projection.
|
||||
let hand_quad = |corners: [[f32; 2]; 4],
|
||||
uv: [[f32; 2]; 4],
|
||||
rect: [f32; 4],
|
||||
color: [f32; 4]| ScreenQuad {
|
||||
vertices: std::array::from_fn(|i| ScreenVertex {
|
||||
pos: [corners[i][0] * scale[0], corners[i][1] * scale[1]],
|
||||
uv: uv[i],
|
||||
rect,
|
||||
color,
|
||||
}),
|
||||
blend: Blend::Alpha,
|
||||
};
|
||||
let full = [[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]];
|
||||
// ScreenEffectRenderer.submitBlockSprite: u1/v1 at (-1, -1), colour 0xFF191919.
|
||||
if let Some(name) = &input.block_overlay
|
||||
&& let Some(rect) = sprite(name)
|
||||
{
|
||||
let c = 0x19 as f32 / 255.0;
|
||||
out.push(hand_quad(
|
||||
full,
|
||||
[[1.0, 1.0], [0.0, 1.0], [0.0, 0.0], [1.0, 0.0]],
|
||||
rect,
|
||||
[c, c, c, 1.0],
|
||||
));
|
||||
}
|
||||
if let Some((brightness, yaw, pitch)) = input.water
|
||||
&& let Some(rect) = sprite("misc/underwater")
|
||||
{
|
||||
let (u, v) = (-yaw / 64.0, pitch / 64.0);
|
||||
let uv = [[u + 4.0, v + 4.0], [u, v + 4.0], [u, v], [u + 4.0, v]];
|
||||
out.push(hand_quad(
|
||||
full,
|
||||
uv,
|
||||
rect,
|
||||
[brightness, brightness, brightness, 0.1],
|
||||
));
|
||||
}
|
||||
if input.on_fire
|
||||
&& let Some(rect) = sprite("block/fire_1")
|
||||
{
|
||||
for (dx, angle) in [(0.24f32, -10.0f32), (-0.24, 10.0)] {
|
||||
let (s, c) = angle.to_radians().sin_cos();
|
||||
// rotateY about the quad then translate; z = -0.5 feeds into x.
|
||||
let corner = |x: f32, y: f32| [x * c + -0.5 * s + dx, y - 0.3];
|
||||
let corners = [
|
||||
corner(-0.5, -0.5),
|
||||
corner(0.5, -0.5),
|
||||
corner(0.5, 0.5),
|
||||
corner(-0.5, 0.5),
|
||||
];
|
||||
let alpha = 0xE5 as f32 / 255.0;
|
||||
out.push(hand_quad(
|
||||
corners,
|
||||
[[1.0, 1.0], [0.0, 1.0], [0.0, 0.0], [1.0, 0.0]],
|
||||
rect,
|
||||
[1.0, 1.0, 1.0, alpha],
|
||||
));
|
||||
}
|
||||
}
|
||||
// Hud camera overlays: GUI-space full-screen blits (v grows downwards).
|
||||
let gui = |rect: [f32; 4], color: [f32; 4], blend: Blend| ScreenQuad {
|
||||
vertices: std::array::from_fn(|i| {
|
||||
let p = [[-1.0f32, 1.0], [1.0, 1.0], [1.0, -1.0], [-1.0, -1.0]][i];
|
||||
ScreenVertex {
|
||||
pos: p,
|
||||
uv: [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]][i],
|
||||
rect,
|
||||
color,
|
||||
}
|
||||
}),
|
||||
blend,
|
||||
};
|
||||
if input.vignette
|
||||
&& let Some(rect) = sprite("misc/vignette")
|
||||
{
|
||||
let b = self.vignette_brightness.clamp(0.0, 1.0);
|
||||
let color = match input.border_warning {
|
||||
Some(w) if w > 0.0 => {
|
||||
let w = w.clamp(0.0, 1.0);
|
||||
let red = b * (1.0 - w);
|
||||
let gb = b + (1.0 - b) * w;
|
||||
[red, gb, gb, 1.0]
|
||||
}
|
||||
_ => [b, b, b, 1.0],
|
||||
};
|
||||
out.push(gui(rect, color, Blend::Vignette));
|
||||
}
|
||||
for overlay in &input.camera_overlays {
|
||||
if let Some(rect) = sprite(overlay) {
|
||||
out.push(gui(rect, [1.0; 4], Blend::Alpha));
|
||||
}
|
||||
}
|
||||
if input.frozen > 0.0
|
||||
&& let Some(rect) = sprite("misc/powder_snow_outline")
|
||||
{
|
||||
out.push(gui(rect, [1.0, 1.0, 1.0, input.frozen], Blend::Alpha));
|
||||
}
|
||||
let portal = self.o_portal + (self.portal - self.o_portal) * input.partial;
|
||||
if portal > 0.0
|
||||
&& let Some(rect) = sprite("block/nether_portal")
|
||||
{
|
||||
let mut a = portal;
|
||||
if a < 1.0 {
|
||||
a *= a;
|
||||
a *= a;
|
||||
a = a * 0.8 + 0.2;
|
||||
}
|
||||
out.push(gui(rect, [1.0, 1.0, 1.0, a], Blend::Alpha));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn lightmap_brightness_curve() {
|
||||
assert_eq!(lightmap_brightness(0.0, 15), 1.0);
|
||||
assert_eq!(lightmap_brightness(0.0, 0), 0.0);
|
||||
assert!((lightmap_brightness(0.1, 0) - 0.1).abs() < 1e-6);
|
||||
}
|
||||
#[test]
|
||||
fn portal_intensity_ramps() {
|
||||
let mut e = ScreenEffects::default();
|
||||
for _ in 0..80 {
|
||||
e.tick(1.0, true);
|
||||
}
|
||||
assert!((e.portal - 1.0).abs() < 1e-5);
|
||||
e.tick(1.0, false);
|
||||
assert!((e.portal - 0.95).abs() < 1e-5);
|
||||
// Vignette fades towards 1 - brightness at 1% per tick.
|
||||
assert!(e.vignette_brightness < 1.0);
|
||||
}
|
||||
#[test]
|
||||
fn overlays_need_their_sprites() {
|
||||
let mut sprites = HashMap::new();
|
||||
sprites.insert(
|
||||
"misc/vignette".to_owned(),
|
||||
Rect {
|
||||
u0: 0.0,
|
||||
v0: 0.0,
|
||||
u1: 1.0,
|
||||
v1: 1.0,
|
||||
w: 256,
|
||||
h: 256,
|
||||
},
|
||||
);
|
||||
let e = ScreenEffects::default();
|
||||
let input = ScreenInputs {
|
||||
sprites: &sprites,
|
||||
aspect: 1.6,
|
||||
partial: 0.0,
|
||||
block_overlay: None,
|
||||
water: Some((1.0, 0.0, 0.0)),
|
||||
on_fire: false,
|
||||
camera_overlays: vec![],
|
||||
frozen: 0.0,
|
||||
vignette: true,
|
||||
border_warning: None,
|
||||
};
|
||||
let quads = e.build(&input);
|
||||
assert_eq!(quads.len(), 1);
|
||||
assert_eq!(quads[0].blend, Blend::Vignette);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Entity shadows (`EntityRenderer.extractShadow` + `ShadowFeatureRenderer`):
|
||||
//! `misc/shadow.png` projected onto the tops of full-collision blocks under
|
||||
//! an entity, faded by camera distance, depth below the entity and the light
|
||||
//! at each block.
|
||||
use crate::{blocks::BlockFacts, hud::Rect, mesher::Vertex, world::World};
|
||||
use glam::DVec3;
|
||||
|
||||
/// Vanilla renderer shadow radius and strength for an entity type id.
|
||||
pub fn shadow_params(entity: &str) -> (f32, f32) {
|
||||
let id = entity.strip_prefix("minecraft:").unwrap_or(entity);
|
||||
let radius = match id {
|
||||
"item" | "experience_orb" | "tropical_fish" => 0.15,
|
||||
"tadpole" => 0.14,
|
||||
"pufferfish" => 0.2,
|
||||
"slime" | "magma_cube" | "bat" => 0.25,
|
||||
"chicken" | "cod" | "parrot" | "rabbit" | "frog" | "silverfish" | "endermite" | "vex" => 0.3,
|
||||
"cat" | "ocelot" | "fox" | "bee" | "allay" | "salmon" => 0.4,
|
||||
"zombie" | "husk" | "drowned" | "zombie_villager" | "zombified_piglin" | "skeleton" | "stray" | "wither_skeleton" | "bogged"
|
||||
| "creeper" | "enderman" | "villager" | "wandering_trader" | "witch" | "pillager" | "vindicator" | "evoker" | "illusioner"
|
||||
| "blaze" | "breeze" | "snow_golem" | "copper_golem" | "strider" | "wolf" | "axolotl" | "tnt" | "falling_block" | "end_crystal" => {
|
||||
0.5
|
||||
}
|
||||
"cave_spider" => 0.56,
|
||||
"creaking" => 0.6,
|
||||
"pig" | "cow" | "mooshroom" | "sheep" | "goat" | "llama" | "trader_llama" | "iron_golem" | "camel" | "camel_husk" | "squid"
|
||||
| "glow_squid" | "dolphin" | "turtle" | "hoglin" | "zoglin" | "nautilus" | "zombie_nautilus" | "minecart" => 0.7,
|
||||
"horse" | "donkey" | "mule" | "skeleton_horse" | "zombie_horse" | "phantom" => 0.75,
|
||||
"spider" | "boat" => 0.8,
|
||||
"polar_bear" | "panda" | "warden" => 0.9,
|
||||
"wither" => 1.0,
|
||||
"sniffer" | "ravager" => 1.1,
|
||||
"ghast" => 1.5,
|
||||
_ => 0.5,
|
||||
};
|
||||
let strength = if matches!(id, "item" | "experience_orb") { 0.75 } else { 1.0 };
|
||||
(radius, strength)
|
||||
}
|
||||
|
||||
/// Shadow quads for an entity at `pos` (interpolated feet position).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn shadow(
|
||||
world: &World,
|
||||
facts: &BlockFacts,
|
||||
sprite: Rect,
|
||||
camera: DVec3,
|
||||
pos: DVec3,
|
||||
radius: f32,
|
||||
strength: f32,
|
||||
ambient_light: f32,
|
||||
sky_darken: i32,
|
||||
out: &mut Vec<Vertex>,
|
||||
) {
|
||||
let radius = radius.min(32.0);
|
||||
if radius <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let dist_sq = pos.distance_squared(camera);
|
||||
let pow = ((1.0 - dist_sq / 256.0) * f64::from(strength)) as f32;
|
||||
if pow <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let r = f64::from(radius);
|
||||
let (x0, x1) = ((pos.x - r).floor() as i32, (pos.x + r).floor() as i32);
|
||||
let (z0, z1) = ((pos.z - r).floor() as i32, (pos.z + r).floor() as i32);
|
||||
let depth = (pow / 0.5 - 1.0).min(radius);
|
||||
let (y0, y1) = ((pos.y - f64::from(depth)).floor() as i32, pos.y.floor() as i32);
|
||||
for z in z0..=z1 {
|
||||
for x in x0..=x1 {
|
||||
for y in y0..=y1 {
|
||||
let below = facts.get(world.block(x, y - 1, z));
|
||||
if below.render_shape == crate::blocks::RenderShape::Invisible || !below.full_collision {
|
||||
continue;
|
||||
}
|
||||
let packed = world.light(x, y, z);
|
||||
let raw = (i32::from(packed >> 4) - sky_darken).max(i32::from(packed & 15));
|
||||
if raw <= 3 {
|
||||
continue;
|
||||
}
|
||||
let power_at_depth = pow - (pos.y - f64::from(y)) as f32 * 0.5;
|
||||
let alpha = (power_at_depth * 0.5 * crate::screen_effects::lightmap_brightness(ambient_light, raw as u8)).clamp(0.0, 1.0);
|
||||
// The block top, clipped to the shadow square so the UVs stay inside the sprite.
|
||||
let (bx0, bx1) = (f64::from(x).max(pos.x - r), f64::from(x + 1).min(pos.x + r));
|
||||
let (bz0, bz1) = (f64::from(z).max(pos.z - r), f64::from(z + 1).min(pos.z + r));
|
||||
if bx1 <= bx0 || bz1 <= bz0 {
|
||||
continue;
|
||||
}
|
||||
let u = |wx: f64| (-((wx - pos.x) as f32) / 2.0 / radius + 0.5).clamp(0.0, 1.0);
|
||||
let v = |wz: f64| (-((wz - pos.z) as f32) / 2.0 / radius + 0.5).clamp(0.0, 1.0);
|
||||
let a = (alpha * 255.0) as u32;
|
||||
let color = a << 24 | 0x00FF_FFFF;
|
||||
let top = f64::from(y) + 0.001;
|
||||
for (wx, wz) in [(bx0, bz0), (bx0, bz1), (bx1, bz1), (bx1, bz0)] {
|
||||
let p = DVec3::new(wx, top, wz) - camera;
|
||||
out.push(Vertex {
|
||||
pos: p.as_vec3().to_array(),
|
||||
uv: [sprite.u0 + (sprite.u1 - sprite.u0) * u(wx), sprite.v0 + (sprite.v1 - sprite.v0) * v(wz)],
|
||||
layer: 0,
|
||||
color,
|
||||
light: 240 | 240 << 8,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn vanilla_radii() {
|
||||
assert_eq!(shadow_params("minecraft:zombie"), (0.5, 1.0));
|
||||
assert_eq!(shadow_params("minecraft:item"), (0.15, 0.75));
|
||||
assert_eq!(shadow_params("minecraft:spider"), (0.8, 1.0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
//! Sign block entities (`SignBlockEntity`, `SignText`): two four-line text
|
||||
//! sides with a dye colour and glow, saved in vanilla's `front_text` /
|
||||
//! `back_text` NBT layout.
|
||||
use horizon_world::nbt::Tag;
|
||||
|
||||
/// `DyeColor` names and `getTextColor` values by id.
|
||||
pub const DYE_TEXT: [(&str, u32); 16] = [
|
||||
("white", 0xFFFFFF),
|
||||
("orange", 0xFF681F),
|
||||
("magenta", 0xFF00FF),
|
||||
("light_blue", 0x9AC0CD),
|
||||
("yellow", 0xFFFF00),
|
||||
("lime", 0xBFFF00),
|
||||
("pink", 0xFF69B4),
|
||||
("gray", 0x808080),
|
||||
("light_gray", 0xD3D3D3),
|
||||
("cyan", 0x00FFFF),
|
||||
("purple", 0xA020F0),
|
||||
("blue", 0x0000FF),
|
||||
("brown", 0x8B4513),
|
||||
("green", 0x00FF00),
|
||||
("red", 0xFF0000),
|
||||
("black", 0x000000),
|
||||
];
|
||||
const BLACK: u8 = 15;
|
||||
|
||||
/// One sign side (`SignText`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct SignText {
|
||||
pub lines: [String; 4],
|
||||
/// `DyeColor` id.
|
||||
pub color: u8,
|
||||
pub glowing: bool,
|
||||
}
|
||||
impl Default for SignText {
|
||||
fn default() -> Self {
|
||||
Self { lines: Default::default(), color: BLACK, glowing: false }
|
||||
}
|
||||
}
|
||||
impl SignText {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.lines.iter().all(String::is_empty)
|
||||
}
|
||||
/// `DyeColor.getTextColor` of this side.
|
||||
pub fn text_color(&self) -> u32 {
|
||||
DYE_TEXT[usize::from(self.color.min(15))].1
|
||||
}
|
||||
/// `AbstractSignRenderer.getDarkColor`.
|
||||
pub fn dark_color(&self) -> u32 {
|
||||
let c = self.text_color();
|
||||
if c == 0 && self.glowing {
|
||||
0xF0EBCC
|
||||
} else {
|
||||
let s = |shift: u32| ((((c >> shift) & 255) as f32 * 0.4) as u32) << shift;
|
||||
s(16) | s(8) | s(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `SignBlockEntity` / `HangingSignBlockEntity` data.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SignData {
|
||||
pub hanging: bool,
|
||||
pub front: SignText,
|
||||
pub back: SignText,
|
||||
pub waxed: bool,
|
||||
}
|
||||
impl SignData {
|
||||
pub fn id(&self) -> &'static str {
|
||||
if self.hanging { "minecraft:hanging_sign" } else { "minecraft:sign" }
|
||||
}
|
||||
/// `SignBlockEntity.getMaxTextLineWidth`.
|
||||
pub fn max_line_width(&self) -> f32 {
|
||||
if self.hanging { 60.0 } else { 90.0 }
|
||||
}
|
||||
/// `SignBlockEntity.getTextLineHeight`.
|
||||
pub fn line_height(&self) -> f32 {
|
||||
if self.hanging { 9.0 } else { 10.0 }
|
||||
}
|
||||
/// NBT entries after the common block-entity header.
|
||||
pub fn encode(&self) -> Vec<(&'static str, Tag)> {
|
||||
let side = |t: &SignText| {
|
||||
Tag::compound([
|
||||
("messages", Tag::List(t.lines.iter().map(|l| Tag::String(l.as_str().into())).collect())),
|
||||
("color", Tag::String(DYE_TEXT[usize::from(t.color.min(15))].0.into())),
|
||||
("has_glowing_text", Tag::Byte(i8::from(t.glowing))),
|
||||
])
|
||||
};
|
||||
vec![("front_text", side(&self.front)), ("back_text", side(&self.back)), ("is_waxed", Tag::Byte(i8::from(self.waxed)))]
|
||||
}
|
||||
pub fn decode(&mut self, tag: &Tag) {
|
||||
let side = |t: Option<&Tag>| -> SignText {
|
||||
let mut out = SignText::default();
|
||||
let Some(t) = t else { return out };
|
||||
if let Some(Tag::List(messages)) = t.get("messages") {
|
||||
for (line, m) in out.lines.iter_mut().zip(messages) {
|
||||
*line = component_text(m);
|
||||
}
|
||||
}
|
||||
if let Some(Tag::String(c)) = t.get("color") {
|
||||
let name = c.to_string_lossy();
|
||||
if let Some(i) = DYE_TEXT.iter().position(|(n, _)| *n == name) {
|
||||
out.color = i as u8;
|
||||
}
|
||||
}
|
||||
out.glowing = matches!(t.get("has_glowing_text"), Some(Tag::Byte(b)) if *b != 0);
|
||||
out
|
||||
};
|
||||
self.front = side(tag.get("front_text"));
|
||||
self.back = side(tag.get("back_text"));
|
||||
self.waxed = matches!(tag.get("is_waxed"), Some(Tag::Byte(b)) if *b != 0);
|
||||
}
|
||||
}
|
||||
/// Plain text of a stored text component (string, `{text: ...}` or JSON string).
|
||||
fn component_text(tag: &Tag) -> String {
|
||||
match tag {
|
||||
Tag::String(s) => {
|
||||
let s = s.to_string_lossy();
|
||||
match serde_json::from_str::<serde_json::Value>(&s) {
|
||||
Ok(serde_json::Value::String(text)) => text,
|
||||
Ok(v) if v.get("text").is_some() => v["text"].as_str().unwrap_or_default().to_owned(),
|
||||
_ => s,
|
||||
}
|
||||
}
|
||||
Tag::Compound(_) => match tag.get("text") {
|
||||
Some(Tag::String(t)) => t.to_string_lossy(),
|
||||
_ => String::new(),
|
||||
},
|
||||
_ => String::new(),
|
||||
}
|
||||
}
|
||||
/// Whether a block name is a sign (standing, wall, hanging or wall hanging).
|
||||
pub fn sign_kind(name: &str) -> Option<bool> {
|
||||
let name = name.strip_prefix("minecraft:").unwrap_or(name);
|
||||
if name == "hanging_sign" || name.ends_with("_hanging_sign") {
|
||||
Some(true)
|
||||
} else if name == "sign" || name.ends_with("_sign") {
|
||||
Some(false)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
/// Wood type of a sign block (`SignBlock.getWoodType`), for the editor texture.
|
||||
pub fn wood_type(name: &str) -> &str {
|
||||
let name = name.strip_prefix("minecraft:").unwrap_or(name);
|
||||
for suffix in ["_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign"] {
|
||||
if let Some(wood) = name.strip_suffix(suffix) {
|
||||
return wood;
|
||||
}
|
||||
}
|
||||
"oak"
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn round_trips_nbt() {
|
||||
let mut data = SignData { hanging: false, ..SignData::default() };
|
||||
data.front.lines[0] = "Hello".into();
|
||||
data.front.color = 14;
|
||||
data.back.glowing = true;
|
||||
let tag = Tag::compound(data.encode());
|
||||
let mut decoded = SignData::default();
|
||||
decoded.decode(&tag);
|
||||
assert_eq!(decoded, data);
|
||||
}
|
||||
#[test]
|
||||
fn names_and_colors() {
|
||||
assert_eq!(sign_kind("minecraft:oak_wall_hanging_sign"), Some(true));
|
||||
assert_eq!(sign_kind("minecraft:sign"), Some(false));
|
||||
assert_eq!(sign_kind("minecraft:spruce_wall_sign"), Some(false));
|
||||
assert_eq!(sign_kind("minecraft:stone"), None);
|
||||
assert_eq!(wood_type("minecraft:dark_oak_wall_sign"), "dark_oak");
|
||||
assert_eq!(SignText::default().dark_color(), 0);
|
||||
let red = SignText { color: 14, ..SignText::default() };
|
||||
assert_eq!(red.dark_color(), 0x660000);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ struct Globals {
|
||||
sunrise: vec4<f32>,
|
||||
// xyz: sun direction, w: star brightness
|
||||
sun: vec4<f32>,
|
||||
// x: sky fog end, y: cloud fog end, z: dark disc flag
|
||||
fog_ends: vec4<f32>,
|
||||
}
|
||||
@group(0) @binding(0) var<uniform> globals: Globals;
|
||||
@group(0) @binding(1) var sprites: texture_2d_array<f32>;
|
||||
@@ -67,8 +69,12 @@ fn apply_fog(color: vec4<f32>, spherical: f32, cylindrical: f32) -> vec4<f32> {
|
||||
return apply_fog(color, in.spherical, in.cylindrical);
|
||||
}
|
||||
|
||||
// Sky: vanilla draws a sky disc in the sky colour and blends towards the fog
|
||||
// colour at the horizon; sunrise/sunset tints the horizon facing the sun.
|
||||
// Sky (SkyRenderer): the 10-vertex sky disc fan at y = 16 (radius 512) in
|
||||
// the sky colour with sky fog (sky.fsh: fog 0..FogSkyEnd on the spherical
|
||||
// distance, a step at FogSkyEnd on the cylindrical one), evaluated per pixel
|
||||
// along the view ray with the fan's interpolated vertex distances; the
|
||||
// clear colour (fog colour) elsewhere; the sunrise/sunset fan blended over
|
||||
// it; the dark disc (y = -4) below the horizon when the camera is low.
|
||||
struct SkyOut {
|
||||
@builtin(position) clip: vec4<f32>,
|
||||
@location(0) ndc: vec2<f32>,
|
||||
@@ -80,22 +86,87 @@ struct SkyOut {
|
||||
out.ndc = p;
|
||||
return out;
|
||||
}
|
||||
fn view_ray(ndc: vec2<f32>) -> vec3<f32> {
|
||||
return normalize((globals.inverse_view * vec4(ndc.x * globals.misc.z * globals.misc.w,
|
||||
ndc.y * globals.misc.w, -1.0, 0.0)).xyz);
|
||||
}
|
||||
const PI: f32 = 3.14159265;
|
||||
// Interpolated (spherical, cylindrical) distance where the ray meets a disc
|
||||
// fan at height y, or negative when it misses.
|
||||
fn disc_distance(d: vec3<f32>, y: f32) -> vec2<f32> {
|
||||
if d.y * y <= 0.0 { return vec2(-1.0); }
|
||||
let p = d * (y / d.y);
|
||||
let h = length(p.xz);
|
||||
let phi = atan2(p.z, p.x);
|
||||
let sector = PI / 4.0;
|
||||
let delta = phi - (floor(phi / sector) * sector + sector * 0.5);
|
||||
let edge = 512.0 * cos(sector * 0.5) / cos(delta);
|
||||
if h > edge { return vec2(-1.0); }
|
||||
let s = h / edge;
|
||||
let ay = abs(y);
|
||||
let rim = sqrt(512.0 * 512.0 + y * y);
|
||||
return vec2(ay + s * (rim - ay), ay + s * (512.0 - ay));
|
||||
}
|
||||
fn sky_fog(color: vec3<f32>, dist: vec2<f32>) -> vec3<f32> {
|
||||
let end = globals.fog_ends.x;
|
||||
let f = max(linear_fog(dist.x, 0.0, end), linear_fog(dist.y, end, end));
|
||||
return mix(color, globals.fog_color.rgb, f * globals.fog_color.a);
|
||||
}
|
||||
fn rotate_x90(v: vec3<f32>) -> vec3<f32> { return vec3(v.x, -v.z, v.y); }
|
||||
// Weight of the fan centre where the ray crosses the sunrise fan (0 when missed).
|
||||
fn sunrise_weight(d: vec3<f32>) -> f32 {
|
||||
let alpha = globals.sunrise.a;
|
||||
if alpha <= 0.001 { return 0.0; }
|
||||
// sin(sunAngle) < 0 flips the fan to the other horizon; sun.z = -sin(sunAngle).
|
||||
let flip = select(0.0, 180.0, -globals.sun.z < 0.0);
|
||||
let theta = radians(flip + 90.0);
|
||||
let c = cos(theta);
|
||||
let s = sin(theta);
|
||||
var best = 0.0;
|
||||
let apex = rotate_x90(vec3(-100.0 * s, 100.0 * c, 0.0));
|
||||
for (var i = 0; i < 16; i++) {
|
||||
let a0 = f32(i) * 2.0 * PI / 16.0;
|
||||
let a1 = f32(i + 1) * 2.0 * PI / 16.0;
|
||||
let l0 = vec3(sin(a0) * 120.0, cos(a0) * 120.0, -cos(a0) * 40.0 * alpha);
|
||||
let l1 = vec3(sin(a1) * 120.0, cos(a1) * 120.0, -cos(a1) * 40.0 * alpha);
|
||||
let r0 = rotate_x90(vec3(l0.x * c - l0.y * s, l0.x * s + l0.y * c, l0.z));
|
||||
let r1 = rotate_x90(vec3(l1.x * c - l1.y * s, l1.x * s + l1.y * c, l1.z));
|
||||
// Moller-Trumbore from the origin along d.
|
||||
let e1 = r0 - apex;
|
||||
let e2 = r1 - apex;
|
||||
let pv = cross(d, e2);
|
||||
let det = dot(e1, pv);
|
||||
if abs(det) < 1e-6 { continue; }
|
||||
let tv = -apex;
|
||||
let u = dot(tv, pv) / det;
|
||||
let qv = cross(tv, e1);
|
||||
let v = dot(d, qv) / det;
|
||||
let t = dot(e2, qv) / det;
|
||||
if u >= 0.0 && v >= 0.0 && u + v <= 1.0 && t > 0.0 {
|
||||
best = max(best, 1.0 - u - v);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
@fragment fn fs_sky(in: SkyOut) -> @location(0) vec4<f32> {
|
||||
let view = normalize((globals.inverse_view * vec4(in.ndc.x * globals.misc.z * globals.misc.w,
|
||||
in.ndc.y * globals.misc.w, -1.0, 0.0)).xyz);
|
||||
let up = clamp(view.y, -1.0, 1.0);
|
||||
// Fog band towards the horizon (vanilla sky end distance blending).
|
||||
let horizon = 1.0 - smoothstep(0.0, 0.35, up);
|
||||
var color = mix(globals.sky_color.rgb, globals.fog_color.rgb, horizon);
|
||||
let toward_sun = max(dot(normalize(vec3(view.x, 0.0, view.z) + vec3(0.0001)), normalize(vec3(globals.sun.x, 0.0, globals.sun.z) + vec3(0.0001))), 0.0);
|
||||
let band = (1.0 - smoothstep(-0.1, 0.4, abs(up))) * pow(toward_sun, 3.0);
|
||||
color = mix(color, globals.sunrise.rgb, band * globals.sunrise.a);
|
||||
if up < 0.0 {
|
||||
// Void below the horizon.
|
||||
color = mix(color, globals.sky_color.rgb * 0.2, smoothstep(0.0, -0.3, up) * (1.0 - globals.misc.x));
|
||||
let d = view_ray(in.ndc);
|
||||
var color = globals.fog_color.rgb;
|
||||
let dist = disc_distance(d, 16.0);
|
||||
if dist.x >= 0.0 {
|
||||
color = sky_fog(globals.sky_color.rgb, dist);
|
||||
}
|
||||
let w = sunrise_weight(d);
|
||||
if w > 0.0 {
|
||||
color = mix(color, globals.sunrise.rgb, w * globals.sunrise.a);
|
||||
}
|
||||
return vec4(color, 1.0);
|
||||
}
|
||||
@fragment fn fs_dark_disc(in: SkyOut) -> @location(0) vec4<f32> {
|
||||
let d = view_ray(in.ndc);
|
||||
let dist = disc_distance(d, -4.0);
|
||||
if dist.x < 0.0 { discard; }
|
||||
return vec4(sky_fog(vec3(0.0), dist), 1.0);
|
||||
}
|
||||
|
||||
struct LineOut { @builtin(position) clip: vec4<f32> }
|
||||
@vertex fn vs_line(@location(0) position: vec3<f32>) -> LineOut {
|
||||
|
||||
@@ -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