Mesh resident block models with native culling and UV-aware merging

This commit is contained in:
Ludovic Marie
2026-10-06 22:30:16 +02:00
parent f5ba959cdc
commit a6966ab450
17 changed files with 1330 additions and 185 deletions
+7 -13
View File
@@ -53,11 +53,11 @@ pub struct Assets {
pub registry: BlockRegistry,
pub properties: Properties,
pub material_states: [BlockStateId; 6],
pub layers: Vec<i32>,
pub sprite_size: u32,
pub pixels: Vec<u8>,
pub texture_layers: u32,
pub model_quads: Vec<crate::models::ModelInstance>,
pub model_catalog: crate::models::StateModels,
pub model_placements: Vec<(horizon_core::position::BlockPos, BlockStateId)>,
pub model_gallery: Vec<Value>,
pub animations: Vec<crate::sprites::SpriteAnimation>,
}
@@ -167,11 +167,6 @@ impl Assets {
})
.collect::<Result<_>>()?,
));
let mut layers: Vec<_> = properties
.0
.iter()
.map(|state| if state.air { -1 } else { -2 })
.collect();
let mut material_states = [BlockStateId(0); 6];
let mut sprites = crate::sprites::Sprites::default();
for (layer, name) in MATERIALS.iter().enumerate() {
@@ -179,20 +174,19 @@ impl Assets {
.default_state(&format!("minecraft:{name}"))
.ok_or_else(|| invalid("missing test-scene material"))?;
material_states[layer] = state;
let sprite = sprites.insert(root, &format!("minecraft:block/{name}"))?;
layers[state.0 as usize] = sprite as i32;
sprites.insert(root, &format!("minecraft:block/{name}"))?;
}
let gallery = crate::models::gallery(root, &registry, &mut sprites)?;
let models = crate::models::prepare(root, &registry, &mut sprites)?;
Ok(Self {
registry,
properties,
material_states,
layers,
sprite_size: sprites.size,
texture_layers: u32::try_from(sprites.layers.len())?,
pixels: sprites.pixels,
model_quads: gallery.quads,
model_gallery: gallery.states,
model_catalog: models.catalog,
model_placements: models.placements,
model_gallery: models.states,
animations: sprites.animations,
})
}
+14 -9
View File
@@ -10,7 +10,7 @@ mod sprites;
mod world;
use assets::Assets;
use camera::Camera;
use mesh::Quad;
use mesh::Mesh;
use render::Renderer;
use std::{
collections::HashSet,
@@ -101,7 +101,7 @@ impl Options {
struct App<'a> {
assets: &'a Assets,
world: TestWorld<'a>,
mesh: Vec<Quad>,
mesh: Mesh,
options: Options,
window: Option<Arc<Window>>,
renderer: Option<Renderer>,
@@ -167,8 +167,11 @@ impl App<'_> {
"presented_frames": self.frames,
"elapsed_seconds": self.started.elapsed().as_secs_f64(),
"resident_chunks": self.world.chunks.len(),
"merged_quads": self.mesh.len(),
"model_quads": self.assets.model_quads.len(),
"merged_quads": self.mesh.cubes.len(),
"model_quads": self.mesh.models.len(),
"visible_model_faces": self.mesh.visible_faces,
"culled_model_faces": self.mesh.culled_faces,
"model_blocks": self.mesh.model_blocks,
"model_gallery": self.assets.model_gallery,
"sprite_layers": self.assets.texture_layers,
"animated_sprites": self.assets.animations.len(),
@@ -204,7 +207,8 @@ impl ApplicationHandler for App<'_> {
match pollster::block_on(Renderer::new(
window.clone(),
self.assets,
&self.mesh,
&self.mesh.cubes,
&self.mesh.models,
((self.options.radius + 1) * 16) as f32,
)) {
Ok(renderer) => self.renderer = Some(renderer),
@@ -305,7 +309,7 @@ impl ApplicationHandler for App<'_> {
self.window.as_ref().unwrap().set_title(&format!(
"Horizon — Development | {fps:.0} FPS | {} chunks | {} quads",
self.world.chunks.len(),
self.mesh.len()
self.mesh.cubes.len()
));
self.title_at = Instant::now();
self.title_frames = self.frames;
@@ -353,12 +357,13 @@ fn run() -> Result<()> {
format!("{error}\nPrepare pinned resources with: python3 tools/prepare_native_client.py")
})?;
let world = TestWorld::new(&assets, options.radius)?;
let mesh = mesh::build(&world)?;
let mut visibility = models::load_visibility(&options.resources, &assets.registry)?;
let mesh = mesh::build(&world, &assets, &mut visibility)?;
eprintln!(
"Horizon development scene: {} resident chunks, {} merged cube faces, {} baked model faces.\nClick to capture mouse; WASD/Space/Shift move; arrows rotate; Esc releases; Ctrl+Q quits.",
world.chunks.len(),
mesh.len(),
assets.model_quads.len()
mesh.cubes.len(),
mesh.models.len()
);
let now = Instant::now();
let mut app = App {
+202 -57
View File
@@ -1,6 +1,14 @@
//! Greedy opaque-cube meshing for the controlled renderer scene. Model geometry,
//! weighted variants, tinting, transparency and lighting are separate work.
use crate::{Result, world::TestWorld};
//! Resident blockstate model meshing. Greedy rectangles preserve the texture
//! and signed UV basis of eligible unit-cube faces; other geometry stays baked.
use crate::{
Result,
assets::Assets,
models::{self, CubeStyle, ModelInstance},
world::TestWorld,
};
use horizon_core::{geometry::Direction, position::BlockPos};
use horizon_world::block_render::FaceVisibility;
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Quad {
@@ -8,6 +16,17 @@ pub struct Quad {
pub extent: [f32; 2],
pub face: u32,
pub layer: u32,
pub uv_origin: [f32; 2],
pub uv_u: [f32; 2],
pub uv_v: [f32; 2],
pub shade: f32,
}
pub struct Mesh {
pub cubes: Vec<Quad>,
pub models: Vec<ModelInstance>,
pub visible_faces: usize,
pub culled_faces: usize,
pub model_blocks: usize,
}
fn position(face: usize, plane: usize, u: usize, v: usize) -> [usize; 3] {
match face {
@@ -16,36 +35,137 @@ fn position(face: usize, plane: usize, u: usize, v: usize) -> [usize; 3] {
_ => [plane, v, u],
}
}
pub fn build(world: &TestWorld<'_>) -> Result<Vec<Quad>> {
let mut quads = Vec::new();
pub fn build(
world: &TestWorld<'_>,
assets: &Assets,
visibility: &mut FaceVisibility,
) -> Result<Mesh> {
let mut mesh = Mesh {
cubes: Vec::new(),
models: Vec::new(),
visible_faces: 0,
culled_faces: 0,
model_blocks: 0,
};
for &(cx, cz) in world.chunks.keys() {
let mut cells = [-1_i32; 18 * 18 * 18];
for y in 0..18 {
for z in 0..18 {
for x in 0..18 {
cells[index(x, y, z)] = world.layer(
cx * 16 + x as i32 - 1,
y as i32 - 1,
cz * 16 + z as i32 - 1,
)?;
let mut masks = vec![[None; 256]; 6 * 16];
for y in 0..16 {
for z in 0..16 {
for x in 0..16 {
let pos = BlockPos::new(cx * 16 + x, y, cz * 16 + z);
let state = world.block(pos.x, pos.y, pos.z);
if world.is_air(state) {
continue;
}
mesh.model_blocks += 1;
let selected = assets.model_catalog.collect(state, pos)?;
let mut visible = [false; 6];
for direction in Direction::ALL {
let [dx, dy, dz] = direction.normal();
let neighbor = world.block(pos.x + dx, pos.y + dy, pos.z + dz);
visible[direction as usize] =
visibility.should_render_face(state, neighbor, direction, true)?;
}
if selected.len() == 1
&& let Some(styles) = selected[0].1.cube
{
for (face, style) in styles.into_iter().enumerate() {
if !visible[face] {
mesh.culled_faces += 1;
continue;
}
mesh.visible_faces += 1;
let (plane, u, v) = match face {
0 | 1 => (y, x, z),
2 | 3 => (z, x, y),
_ => (x, z, y),
};
masks[face * 16 + plane as usize][(u + 16 * v) as usize] = Some(style);
}
} else {
for (_, model) in selected {
for face in &model.faces {
if face.quad.cull.is_some_and(|d| !visible[d as usize]) {
mesh.culled_faces += 1;
continue;
}
mesh.visible_faces += 1;
mesh.models.push(models::instance(face, pos));
}
}
}
}
}
}
mesh_chunk(&cells, cx, cz, &mut quads);
for (index, mask) in masks.iter_mut().enumerate() {
merge(mask, index / 16, index % 16, cx, cz, &mut mesh.cubes);
}
}
Ok(quads)
Ok(mesh)
}
fn merge(
mask: &mut [Option<CubeStyle>; 256],
face: usize,
plane: usize,
cx: i32,
cz: i32,
quads: &mut Vec<Quad>,
) {
for v in 0..16 {
let mut u = 0;
while u < 16 {
let Some(style) = mask[u + v * 16] else {
u += 1;
continue;
};
let mut width = 1;
while u + width < 16 && mask[u + width + v * 16] == Some(style) {
width += 1;
}
let mut height = 1;
while v + height < 16
&& (u..u + width).all(|x| mask[x + (v + height) * 16] == Some(style))
{
height += 1;
}
for y in v..v + height {
for x in u..u + width {
mask[x + y * 16] = None;
}
}
let p = position(face, plane + usize::from(face % 2 == 1), u, v);
let [a, b, c, d, e, f] = style.uv.map(f32::from);
quads.push(Quad {
origin: [
(cx * 16 + p[0] as i32) as f32,
p[1] as f32,
(cz * 16 + p[2] as i32) as f32,
],
extent: [width as f32, height as f32],
face: face as u32,
layer: style.layer,
uv_origin: [a, b],
uv_u: [c, d],
uv_v: [e, f],
shade: f32::from_bits(style.shade_bits),
});
u += width;
}
}
}
#[cfg(test)]
fn index(x: usize, y: usize, z: usize) -> usize {
x + 18 * (z + 18 * y)
}
#[cfg(test)]
fn mesh_chunk(cells: &[i32; 18 * 18 * 18], cx: i32, cz: i32, quads: &mut Vec<Quad>) {
for face in 0..6 {
for plane in 0..16 {
let mut mask = [-1_i32; 256];
let mut mask = [None; 256];
for v in 0..16 {
for u in 0..16 {
let p = position(face, plane + 1, u + 1, v + 1);
let layer = cells[index(p[0], p[1], p[2])];
let mut adjacent = p;
let axis = match face {
0 | 1 => 1,
@@ -57,52 +177,20 @@ fn mesh_chunk(cells: &[i32; 18 * 18 * 18], cx: i32, cz: i32, quads: &mut Vec<Qua
} else {
adjacent[axis] += 1;
}
let layer = cells[index(p[0], p[1], p[2])];
if layer >= 0 && cells[index(adjacent[0], adjacent[1], adjacent[2])] < 0 {
mask[u + v * 16] = layer;
mask[u + 16 * v] = Some(CubeStyle {
layer: layer as u32,
uv: [0, 1, 1, 0, 0, -1],
shade_bits: 1f32.to_bits(),
});
}
}
}
for v in 0..16 {
let mut u = 0;
while u < 16 {
let layer = mask[u + v * 16];
if layer < 0 {
u += 1;
continue;
}
let mut width = 1;
while u + width < 16 && mask[u + width + v * 16] == layer {
width += 1;
}
let mut height = 1;
while v + height < 16
&& (u..u + width).all(|x| mask[x + (v + height) * 16] == layer)
{
height += 1;
}
for y in v..v + height {
for x in u..u + width {
mask[x + y * 16] = -1;
}
}
let p = position(face, plane + usize::from(face % 2 == 1), u, v);
quads.push(Quad {
origin: [
(cx * 16 + p[0] as i32) as f32,
p[1] as f32,
(cz * 16 + p[2] as i32) as f32,
],
extent: [width as f32, height as f32],
face: face as u32,
layer: layer as u32,
});
u += width;
}
}
merge(&mut mask, face, plane, cx, cz, quads);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -178,6 +266,63 @@ mod tests {
quads
}
#[test]
fn merging_preserves_rotation_mirroring_shade_and_texture() {
let bases = [
[0, 0, 1, 0, 0, 1],
[1, 0, 0, 1, -1, 0],
[1, 1, -1, 0, 0, -1],
[0, 1, 0, -1, 1, 0],
[1, 0, -1, 0, 0, 1],
[0, 1, 1, 0, 0, -1],
[0, 0, 0, 1, 1, 0],
[1, 1, 0, -1, -1, 0],
];
let original: [Option<CubeStyle>; 256] = std::array::from_fn(|i| {
(i % 17 != 0).then_some(CubeStyle {
layer: (i / 64) as u32,
uv: bases[(i / 4) % 8],
shade_bits: if i % 5 == 0 { 0.5f32 } else { 1f32 }.to_bits(),
})
});
for face in 0..6 {
let mut mask = original;
let mut quads = Vec::new();
merge(&mut mask, face, 4, -2, 3, &mut quads);
let mut covered = [false; 256];
for q in quads {
let p = [q.origin[0] + 32.0, q.origin[1], q.origin[2] - 48.0];
let (u0, v0) = match face {
0 | 1 => (p[0] as usize, p[2] as usize),
2 | 3 => (p[0] as usize, p[1] as usize),
_ => (p[2] as usize, p[1] as usize),
};
for dv in 0..q.extent[1] as usize {
for du in 0..q.extent[0] as usize {
let index = u0 + du + 16 * (v0 + dv);
assert!(!covered[index]);
covered[index] = true;
let style = original[index].unwrap();
assert_eq!(q.layer, style.layer);
assert_eq!(q.shade.to_bits(), style.shade_bits);
let [a, b, c, d, e, f] = style.uv.map(f32::from);
let local = [a + c * 0.25 + e * 0.75, b + d * 0.25 + f * 0.75];
let merged: [f32; 2] = std::array::from_fn(|axis| {
q.uv_origin[axis]
+ q.uv_u[axis] * (du as f32 + 0.25)
+ q.uv_v[axis] * (dv as f32 + 0.75)
});
assert_eq!(
local.map(|v| v.rem_euclid(1.0)),
merged.map(|v| v.rem_euclid(1.0))
);
}
}
}
assert_eq!(covered, original.map(|v| v.is_some()));
}
}
#[test]
fn empty_solid_and_neighbor_seams() {
let mut cells = [-1; 18 * 18 * 18];
+75 -31
View File
@@ -1,10 +1,12 @@
//! A blockstate-driven inspection gallery, separate from gameplay simulation.
mod catalog;
mod cube;
use crate::{Result, sprites::Sprites};
use catalog::{StateModels, descriptor};
use horizon_assets::model::Direction;
pub use catalog::StateModels;
use catalog::descriptor;
pub use cube::CubeStyle;
use horizon_core::position::BlockPos;
use horizon_world::registry::BlockRegistry;
use horizon_world::registry::{BlockRegistry, BlockStateId};
use serde_json::{Value, json};
use std::path::Path;
@@ -43,13 +45,20 @@ pub struct ModelInstance {
pub layer: u32,
pub shade: f32,
}
pub struct Gallery {
pub quads: Vec<ModelInstance>,
pub struct PreparedModels {
pub catalog: StateModels,
pub placements: Vec<(BlockPos, BlockStateId)>,
pub states: Vec<Value>,
}
pub fn gallery(root: &Path, registry: &BlockRegistry, sprites: &mut Sprites) -> Result<Gallery> {
let models = StateModels::load(root, registry, &GALLERY.map(|(name, _)| name), sprites)?;
let mut instances = Vec::new();
pub fn prepare(
root: &Path,
registry: &BlockRegistry,
sprites: &mut Sprites,
) -> Result<PreparedModels> {
let mut blocks = GALLERY.map(|(name, _)| name).to_vec();
blocks.extend(crate::assets::MATERIALS);
let catalog = StateModels::load(root, registry, &blocks, sprites)?;
let mut placements = Vec::new();
let mut states = Vec::new();
for (index, (name, properties)) in GALLERY.iter().enumerate() {
let state = registry.resolve(&descriptor(name, properties))?;
@@ -57,33 +66,68 @@ pub fn gallery(root: &Path, registry: &BlockRegistry, sprites: &mut Sprites) ->
.state(state)
.ok_or("missing gallery registry state")?;
let position = BlockPos::new((index % 4) as i32 * 4 - 7, 4, (index / 4) as i32 * 4 + 14);
let origin = [position.x as f32, position.y as f32, position.z as f32];
let selected = models.collect(state, position)?;
let selected = catalog.collect(state, position)?;
states.push(json!({"block":actual.name,"properties":actual.properties,"state_id":state.0,
"position":[position.x,position.y,position.z],
"models":selected.iter().map(|(v,_)| json!({"model":v.model,"rotations":v.rotations,"uv_lock":v.uv_lock})).collect::<Vec<_>>()}));
for (_, faces) in selected {
for face in faces {
let quad = &face.quad;
let shade = match quad.shade_direction_override.unwrap_or(quad.facing) {
Direction::Down => 0.5,
Direction::Up => 1.0,
Direction::North | Direction::South => 0.8,
Direction::West | Direction::East => 0.6,
};
instances.push(ModelInstance {
positions: quad
.positions
.map(|v| std::array::from_fn(|i| v[i] + origin[i])),
uv: quad.uv,
layer: face.layer,
shade,
});
}
}
placements.push((position, state));
}
Ok(Gallery {
quads: instances,
Ok(PreparedModels {
catalog,
placements,
states,
})
}
pub fn instance(face: &catalog::BakedFace, position: BlockPos) -> ModelInstance {
let origin = [position.x as f32, position.y as f32, position.z as f32];
ModelInstance {
positions: face
.quad
.positions
.map(|v| std::array::from_fn(|i| v[i] + origin[i])),
uv: face.quad.uv,
layer: face.layer,
shade: cube::shade(face),
}
}
pub fn load_visibility(
root: &Path,
registry: &BlockRegistry,
) -> Result<horizon_world::block_render::FaceVisibility> {
use horizon_world::{
block_render::{FaceVisibility, RenderDefinition, SkipRendering},
collision::CachedCollisionRegistry,
nbt::{self, Limits},
};
use std::{collections::BTreeMap, fs};
let data = nbt::read_named(&fs::read(root.join("occlusion.nbt"))?, Limits::default())?
.0
.tag;
let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?;
let raw: BTreeMap<String, Value> =
serde_json::from_reader(fs::File::open(root.join("render-definitions.json"))?)?;
let definitions = raw
.into_iter()
.map(|(name, v)| {
let skip = match v["rule"].as_str().ok_or("missing render rule")? {
"never" => SkipRendering::Never,
"same_block" => SkipRendering::SameBlock,
"bars" => SkipRendering::Bars,
"leaves" => SkipRendering::Leaves,
"liquid" => SkipRendering::Liquid,
"mangrove_roots" => SkipRendering::MangroveRoots,
_ => return Err("unrecognized render rule"),
};
Ok((
name,
RenderDefinition {
skip,
can_occlude: v["can_occlude"].as_bool().ok_or("missing occlusion flag")?,
bars_tag: v["bars_tag"].as_bool().ok_or("missing bars tag")?,
},
))
})
.collect::<std::result::Result<_, &str>>()?;
Ok(FaceVisibility::new(&occlusion, &definitions)?)
}
+28 -19
View File
@@ -30,12 +30,17 @@ use std::{
pub struct BakedFace {
pub quad: ModelQuad,
pub layer: u32,
pub opaque: bool,
}
pub struct BakedModel {
pub faces: Vec<BakedFace>,
pub cube: Option<[super::cube::CubeStyle; 6]>,
}
type VariantKey = (String, [u8; 3], bool);
pub struct StateModels {
choices: Vec<CompiledChoices>,
states: BTreeMap<BlockStateId, (usize, SelectedModels)>,
baked: BTreeMap<VariantKey, Vec<BakedFace>>,
baked: BTreeMap<VariantKey, BakedModel>,
}
fn key(variant: &Variant) -> VariantKey {
(variant.model.clone(), variant.rotations, variant.uv_lock)
@@ -159,14 +164,26 @@ impl StateModels {
let mut baked = BTreeMap::new();
for (name, turns, lock) in variants {
let model = library.resolve(&name)?;
let faces = bake_model_transformed(&model, BlockModelTransform::new(turns, lock))?.into_iter().map(|quad| {
if quad.material.force_translucent || quad.tint_index != -1 {
return Err("inspection gallery requires untinted opaque or binary-cutout materials".into());
}
let layer = sprites.insert(root, &quad.material.sprite)?;
Ok(BakedFace { quad, layer })
}).collect::<Result<_>>()?;
baked.insert((name, turns, lock), faces);
let faces: Vec<BakedFace> =
bake_model_transformed(&model, BlockModelTransform::new(turns, lock))?
.into_iter()
.map(|quad| {
if quad.material.force_translucent || quad.tint_index != -1 {
return Err(
"inspection gallery requires untinted opaque or binary-cutout materials"
.into(),
);
}
let layer = sprites.insert(root, &quad.material.sprite)?;
Ok(BakedFace {
quad,
layer,
opaque: sprites.opaque[layer as usize],
})
})
.collect::<Result<_>>()?;
let cube = super::cube::cube_styles(&faces);
baked.insert((name, turns, lock), BakedModel { faces, cube });
}
Ok(Self {
choices,
@@ -178,7 +195,7 @@ impl StateModels {
&self,
state: BlockStateId,
position: BlockPos,
) -> Result<Vec<(&Variant, &[BakedFace])>> {
) -> Result<Vec<(&Variant, &BakedModel)>> {
let (choice, selected) = self
.states
.get(&state)
@@ -190,15 +207,7 @@ impl StateModels {
self.choices[*choice].collect(selected, &mut random, &mut variants)?;
variants
.into_iter()
.map(|v| {
Ok((
v,
self.baked
.get(&key(v))
.ok_or("unbaked block model")?
.as_slice(),
))
})
.map(|v| Ok((v, self.baked.get(&key(v)).ok_or("unbaked block model")?)))
.collect()
}
}
+158
View File
@@ -0,0 +1,158 @@
//! Exact unit-cube faces eligible for repeated-texture greedy rectangles.
use super::catalog::BakedFace;
use horizon_assets::model::Direction;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CubeStyle {
pub layer: u32,
/// UV at spatial (u,v)=(0,0), then the two signed unit-axis derivatives.
pub uv: [i8; 6],
pub shade_bits: u32,
}
pub fn shade(face: &BakedFace) -> f32 {
match face
.quad
.shade_direction_override
.unwrap_or(face.quad.facing)
{
Direction::Down => 0.5,
Direction::Up => 1.0,
Direction::North | Direction::South => 0.8,
Direction::West | Direction::East => 0.6,
}
}
pub fn cube_styles(faces: &[BakedFace]) -> Option<[CubeStyle; 6]> {
if faces.len() != 6 {
return None;
}
let mut styles = [None; 6];
for face in faces {
if !face.opaque || face.quad.light_emission != 0 {
return None;
}
let q = &face.quad;
let direction = q.cull?;
if q.facing != direction || styles[direction as usize].is_some() {
return None;
}
let (axis, u, v) = match direction {
Direction::Down | Direction::Up => (1, 0, 2),
Direction::North | Direction::South => (2, 0, 1),
Direction::West | Direction::East => (0, 2, 1),
};
let plane = if (direction as usize).is_multiple_of(2) {
0.0
} else {
1.0
};
let mut uv = [None; 4];
for (p, texture) in q.positions.iter().zip(q.uv) {
if p[axis] != plane
|| ![p[u], p[v], texture[0], texture[1]]
.iter()
.all(|&x| x == 0.0 || x == 1.0)
{
return None;
}
let index = p[u] as usize + 2 * p[v] as usize;
if uv[index].replace(texture.map(|x| x as i8)).is_some() {
return None;
}
}
let [a, b, c, d] = uv.map(|v| v.unwrap());
let du = [b[0] - a[0], b[1] - a[1]];
let dv = [c[0] - a[0], c[1] - a[1]];
if d != [a[0] + du[0] + dv[0], a[1] + du[1] + dv[1]]
|| (du[0] * dv[1] - du[1] * dv[0]).abs() != 1
{
return None;
}
styles[direction as usize] = Some(CubeStyle {
layer: face.layer,
uv: [a[0], a[1], du[0], du[1], dv[0], dv[1]],
shade_bits: shade(face).to_bits(),
});
}
Some(styles.map(|v| v.unwrap()))
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_assets::{
bake::{BlockModelTransform, bake_model_transformed},
model::CuboidModel,
resolve::ModelLibrary,
};
use serde_json::json;
#[test]
fn projected_cube_uvs_match_baked_quarter_turns() {
let faces: serde_json::Map<String, serde_json::Value> = Direction::ALL
.into_iter()
.map(|d| {
(
d.name().to_owned(),
json!({"texture":"#all","cullface":d.name()}),
)
})
.collect();
let model = CuboidModel::from_json(&json!({"textures":{"all":"horizon:probe"},"elements":[{"from":[0,0,0],"to":[16,16,16],"faces":faces}]}).to_string()).unwrap();
let library = ModelLibrary::new([("horizon:cube".to_owned(), model)].into()).unwrap();
let model = library.resolve("horizon:cube").unwrap();
let mut eligible = 0;
for x in 0..4 {
for y in 0..4 {
for z in 0..4 {
for lock in [false, true] {
let faces: Vec<_> = bake_model_transformed(
&model,
BlockModelTransform::new([x, y, z], lock),
)
.unwrap()
.into_iter()
.map(|quad| BakedFace {
quad,
layer: 7,
opaque: true,
})
.collect();
let Some(styles) = cube_styles(&faces) else {
assert!(lock);
continue;
};
eligible += 1;
for face in &faces {
let direction = face.quad.cull.unwrap();
let (u, v) = match direction {
Direction::Down | Direction::Up => (0, 2),
Direction::North | Direction::South => (0, 1),
_ => (2, 1),
};
let style = styles[direction as usize];
let [a, b, c, d, e, f] = style.uv.map(f32::from);
for (p, uv) in face.quad.positions.iter().zip(face.quad.uv) {
assert_eq!([a + c * p[u] + e * p[v], b + d * p[u] + f * p[v]], uv);
}
}
}
}
}
}
assert!(eligible >= 64);
let mut faces: Vec<_> =
bake_model_transformed(&model, BlockModelTransform::new([0; 3], false))
.unwrap()
.into_iter()
.map(|quad| BakedFace {
quad,
layer: 0,
opaque: true,
})
.collect();
faces[0].opaque = false;
assert!(cube_styles(&faces).is_none());
faces[0].opaque = true;
faces[0].quad.positions[0][0] = 0.25;
assert!(cube_styles(&faces).is_none());
}
}
+4 -3
View File
@@ -39,6 +39,7 @@ impl Renderer {
window: Arc<Window>,
assets: &Assets,
quads: &[Quad],
model_faces: &[ModelInstance],
fog_distance: f32,
) -> Result<Self> {
let instance =
@@ -153,7 +154,7 @@ impl Renderer {
cache: None,
})
};
let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Uint32];
let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Uint32,4=>Float32x2,5=>Float32x2,6=>Float32x2,7=>Float32];
let pipeline = create_pipeline(
"Horizon opaque cubes",
"vs_main",
@@ -236,10 +237,10 @@ impl Renderer {
contents: bytemuck::cast_slice(quads),
usage: wgpu::BufferUsages::VERTEX,
});
let model_quad_count = u32::try_from(assets.model_quads.len())?;
let model_quad_count = u32::try_from(model_faces.len())?;
let model_quads = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Baked vanilla model faces"),
contents: bytemuck::cast_slice(&assets.model_quads),
contents: bytemuck::cast_slice(model_faces),
usage: wgpu::BufferUsages::VERTEX,
});
let depth = Self::depth(&device, &config);
+3
View File
@@ -30,6 +30,7 @@ pub struct Sprites {
pub pixels: Vec<u8>,
pub layers: BTreeMap<String, u32>,
pub animations: Vec<SpriteAnimation>,
pub opaque: Vec<bool>,
}
impl Sprites {
pub fn insert(&mut self, root: &Path, name: &str) -> Result<u32> {
@@ -130,6 +131,8 @@ impl Sprites {
clip: Arc::new(clip),
});
}
self.opaque
.push(pixels.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
self.layers.insert(name.to_owned(), layer);
self.size = width;
self.pixels.extend_from_slice(&frames[initial]);
+10 -12
View File
@@ -1,4 +1,4 @@
//! A controlled opaque-cube scene for exercising the native renderer. This is
//! A controlled blockstate scene for exercising the native renderer. This is
//! not the vanilla world generator or an authoritative gameplay simulation.
use crate::{
Result,
@@ -10,7 +10,6 @@ use std::collections::BTreeMap;
pub struct TestWorld<'a> {
pub chunks: BTreeMap<(i32, i32), TerrainChunk<'a, Properties>>,
assets: &'a Assets,
air: BlockStateId,
}
impl<'a> TestWorld<'a> {
@@ -21,7 +20,6 @@ impl<'a> TestWorld<'a> {
.ok_or("missing air state")?;
let mut world = Self {
chunks: BTreeMap::new(),
assets,
air,
};
for cz in -radius..=radius {
@@ -73,6 +71,9 @@ impl<'a> TestWorld<'a> {
}
}
}
for (position, state) in &assets.model_placements {
world.set(position.x, position.y, position.z, *state)?;
}
Ok(world)
}
fn set(&mut self, x: i32, y: i32, z: i32, state: BlockStateId) -> Result<()> {
@@ -82,15 +83,12 @@ impl<'a> TestWorld<'a> {
.set_block_worldgen(x, y, z, state)?;
Ok(())
}
pub fn layer(&self, x: i32, y: i32, z: i32) -> Result<i32> {
let state = self
.chunks
pub fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId {
self.chunks
.get(&(x >> 4, z >> 4))
.map_or(self.air, |chunk| chunk.block(x, y, z));
let layer = self.assets.layers[state.0 as usize];
if layer == -2 {
return Err("test scene contains an unsupported non-cube material".into());
}
Ok(layer)
.map_or(self.air, |chunk| chunk.block(x, y, z))
}
pub fn is_air(&self, state: BlockStateId) -> bool {
state == self.air
}
}
+5 -3
View File
@@ -15,7 +15,9 @@ struct VertexOut {
}
@vertex fn vs_main(@builtin(vertex_index) vertex: u32,
@location(0) origin: vec3<f32>, @location(1) extent: vec2<f32>,
@location(2) face: u32, @location(3) layer: u32) -> VertexOut {
@location(2) face: u32, @location(3) layer: u32,
@location(4) uv_origin: vec2<f32>, @location(5) uv_u: vec2<f32>,
@location(6) uv_v: vec2<f32>, @location(7) shade: f32) -> VertexOut {
let corners = array<vec2<f32>,4>(vec2(0.0,0.0),vec2(1.0,0.0),vec2(1.0,1.0),vec2(0.0,1.0));
let normal_order = array<u32,6>(0u,1u,2u,0u,2u,3u);
let reversed_order = array<u32,6>(0u,2u,1u,0u,3u,2u);
@@ -28,9 +30,9 @@ struct VertexOut {
else { position+=vec3(0.0,offset.y,offset.x); }
var output: VertexOut;
output.clip=camera.view_projection*vec4(position,1.0);
output.uv=vec2(offset.x,extent.y-offset.y);
output.uv=uv_origin+uv_u*offset.x+uv_v*offset.y;
output.layer=layer;
output.shade=select(select(0.8,0.6,face>=4u),select(0.5,1.0,face==1u),face<2u);
output.shade=shade;
output.world_position=position;
return output;
}