Add native Horizon development client with textured chunk rendering
This commit is contained in:
Generated
+2412
-2
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -1,5 +1,5 @@
|
||||
[workspace]
|
||||
members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels"]
|
||||
members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Horizon
|
||||
|
||||
Horizon is a Rust rewrite effort targeting one-to-one vanilla gameplay parity with Minecraft Java **26.3**, alongside client performance research. The Rust implementation has core primitives and world-data storage verified against pinned vanilla classes. It does not yet run a playable game. Existing playable downloads use Java performance packs. Not affiliated with Mojang or Microsoft.
|
||||
Horizon is a Rust rewrite effort targeting one-to-one vanilla gameplay parity with Minecraft Java **26.3**, alongside client performance research. The Rust implementation has core primitives and world-data storage verified against pinned vanilla classes, plus a [native development client](docs/native-client.md) for inspecting a controlled block scene. It does not yet run a playable game. Existing playable downloads use Java performance packs. Not affiliated with Mojang or Microsoft.
|
||||
|
||||
**First playable release:** pinned Java performance packs, distant terrain, an original frame/tick recorder, and Mac/client/server starter downloads. The M2 Pro/16 GB Mac is the first testing target. A Rust rewrite or custom renderer has not been completed; no M2 FPS improvement has been measured yet.
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
{
|
||||
"adapter": {
|
||||
"backend": "Vulkan",
|
||||
"device": 0,
|
||||
"device_type": "Cpu",
|
||||
"name": "llvmpipe (LLVM 21.1.8, 256 bits)",
|
||||
"vendor": 65541
|
||||
},
|
||||
"arch": "x86_64",
|
||||
"camera_pitch": -0.3839724354387525,
|
||||
"camera_position": [
|
||||
25.0,
|
||||
18.0,
|
||||
25.0
|
||||
],
|
||||
"camera_yaw": -2.356194490192345,
|
||||
"elapsed_seconds": 0.541997659,
|
||||
"error": null,
|
||||
"merged_quads": 166,
|
||||
"os": "linux",
|
||||
"presented_frames": 30,
|
||||
"project": "Horizon",
|
||||
"resident_chunks": 9,
|
||||
"schema": 1,
|
||||
"scope": "Native opaque-cube renderer and free inspection camera; no gameplay simulation",
|
||||
"window_size": [
|
||||
1280,
|
||||
720
|
||||
],
|
||||
"executable_sha256": "4907a5678c323ab250934f3dfa32ba10e1554635f81d226ed2a88e7625737c5f",
|
||||
"resource_manifest_sha256": "eda44ebee6904eab880c15458dbd1212dc2799d320a4419fc810e2ceb0e5d9d6",
|
||||
"sources": {
|
||||
"crates/horizon-client/src/assets.rs": "f35107193fc6d08be41891181da1803abf15bd373b62dd63758213809e2c5cbf",
|
||||
"crates/horizon-client/src/camera.rs": "f9821c8a51a004dd4ad9c0952e746eb07926f6040cf8660bc26da5a0728ae572",
|
||||
"crates/horizon-client/src/main.rs": "0cc250b695ba0d1e49107f581695edea1d24cdc2fb8ffa3a46368ef2c40430a7",
|
||||
"crates/horizon-client/src/mesh.rs": "e2fa00435ec8239ba8a3c6539022bb50a10ff9c3850c6faab72f86aabea896ef",
|
||||
"crates/horizon-client/src/render.rs": "4d58443465ea25769d73701d138db6a99c4f939a288e89e1f2b1ee3d017a2737",
|
||||
"crates/horizon-client/src/world.rs": "901aa59c23ea084e926eec014589f4d511c41691a8dc1520534e039c28cfc76c",
|
||||
"crates/horizon-client/src/world.wgsl": "dd7d579d0afb8a61da849171e444fa05a3e9d15bbfe6d019ff6653e8e0774c66",
|
||||
"Cargo.toml": "4f803d21656a1420555bee6369617ddc825219a2cf05f842a209b3f8eaa583ec",
|
||||
"Cargo.lock": "b1674833e1d5e66032589eea75643bf1c1eb2f2d6503e79ff7da8efa1b6d21dc",
|
||||
"crates/horizon-client/Cargo.toml": "3047995858c9cd103ce358dfd991cb81e7d0688a149f4874cc73c36b859bbff7",
|
||||
"tools/prepare_native_client.py": "b16f62acfc6242552af14ff405e2169ebba3adab12b991fc011e78edb4ffa982",
|
||||
"tools/test_native_client.py": "adb9aa87cc28b0980d811ce47c1b09878d2d72cef2e083b278ec41183d231f1b"
|
||||
},
|
||||
"validation": {
|
||||
"rust_workspace_tests": "passed",
|
||||
"clippy_all_targets": "passed",
|
||||
"python_tooling_tests": 149,
|
||||
"mesh_tests": 2,
|
||||
"manual_visual_checks": [
|
||||
"textured scene with 81 chunks and 382 merged quads",
|
||||
"window resize from 1600x1000 to 1280x720"
|
||||
],
|
||||
"input_checks": [
|
||||
"physical W movement",
|
||||
"physical Right rotation",
|
||||
"captured relative mouse delta (150,-50) changed yaw by -0.3 and pitch by +0.1 radians",
|
||||
"Escape and Ctrl+Q"
|
||||
]
|
||||
},
|
||||
"environment": {
|
||||
"os": "Ubuntu 26.04.1 LTS",
|
||||
"kernel": "7.0.0-31-generic",
|
||||
"cpu": "Intel Core i7-7500U",
|
||||
"display": "headless Sway Wayland",
|
||||
"renderer": "Vulkan llvmpipe software rasterizer"
|
||||
},
|
||||
"limits": [
|
||||
"Controlled development scene only; no gameplay simulation or vanilla pixel-parity claim",
|
||||
"No hardware FPS or render-distance improvement demonstrated",
|
||||
"macOS and Windows runtime checks and final playable packages remain pending",
|
||||
"Private game resources and screenshots excluded from this report"
|
||||
],
|
||||
"mouse_check": {
|
||||
"adapter": {
|
||||
"backend": "Vulkan",
|
||||
"device": 0,
|
||||
"device_type": "Cpu",
|
||||
"name": "llvmpipe (LLVM 21.1.8, 256 bits)",
|
||||
"vendor": 65541
|
||||
},
|
||||
"arch": "x86_64",
|
||||
"camera_pitch": -0.2839724354387525,
|
||||
"camera_position": [
|
||||
25.0,
|
||||
18.0,
|
||||
25.0
|
||||
],
|
||||
"camera_yaw": -2.6561944901923447,
|
||||
"elapsed_seconds": 8.654220098,
|
||||
"error": null,
|
||||
"merged_quads": 166,
|
||||
"os": "linux",
|
||||
"presented_frames": 532,
|
||||
"project": "Horizon",
|
||||
"resident_chunks": 9,
|
||||
"schema": 1,
|
||||
"scope": "Native opaque-cube renderer and free inspection camera; no gameplay simulation",
|
||||
"window_size": [
|
||||
1280,
|
||||
720
|
||||
]
|
||||
},
|
||||
"physical_keyboard_check": {
|
||||
"adapter": {
|
||||
"backend": "Vulkan",
|
||||
"device": 0,
|
||||
"device_type": "Cpu",
|
||||
"name": "llvmpipe (LLVM 21.1.8, 256 bits)",
|
||||
"vendor": 65541
|
||||
},
|
||||
"arch": "x86_64",
|
||||
"camera_pitch": -0.3839724354387525,
|
||||
"camera_position": [
|
||||
18.943610750255,
|
||||
18.0,
|
||||
18.943610750255
|
||||
],
|
||||
"camera_yaw": -2.6478875051923443,
|
||||
"elapsed_seconds": 17.488515374,
|
||||
"error": null,
|
||||
"merged_quads": 166,
|
||||
"os": "linux",
|
||||
"presented_frames": 1080,
|
||||
"project": "Horizon",
|
||||
"resident_chunks": 9,
|
||||
"schema": 1,
|
||||
"scope": "Native opaque-cube renderer and free inspection camera; no gameplay simulation",
|
||||
"window_size": [
|
||||
1280,
|
||||
720
|
||||
],
|
||||
"source_note": "Same camera/input behavior; before subsequent diagnostic formatting and equivalent let-chain cleanup"
|
||||
},
|
||||
"private_capture_sha256": {
|
||||
"first-launch.png": "7e53fa26d3d55f943db41828e1c8dd5b65279f9a130854fff288c75a394ee5aa",
|
||||
"moved-resized.png": "be5a0473ab505740d18ba8eecf1512c15ba93d53d046f49b8dfa96357b25bf22",
|
||||
"mouse-look.png": "7103678309f06938de40ac294f2f9ca1f56b253bc463e792b121ba607cd7b0a3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "horizon-client"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version = "1.90"
|
||||
description = "Horizon native development client"
|
||||
|
||||
[dependencies]
|
||||
horizon-core = { path = "../horizon-core" }
|
||||
horizon-world = { path = "../horizon-world" }
|
||||
wgpu = { version = "30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "dx12", "wgsl"] }
|
||||
winit = "0.30.13"
|
||||
pollster = "0.4"
|
||||
bytemuck = { version = "1.24", features = ["derive"] }
|
||||
glam = "0.30"
|
||||
png = "0.18"
|
||||
serde_json = "1.0.151"
|
||||
@@ -0,0 +1,223 @@
|
||||
use crate::Result;
|
||||
use horizon_world::{
|
||||
DATA_VERSION,
|
||||
heightmap::HeightmapState,
|
||||
nbt::Tag,
|
||||
registry::{BlockRegistry, BlockStateId},
|
||||
worldgen::{tags::TagDefinitions, terrain::TerrainBlockStates},
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
fs::File,
|
||||
io::{self, BufReader},
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
pub const MATERIALS: [&str; 6] = ["bedrock", "dirt", "stone", "sand", "oak_planks", "bricks"];
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct StateFacts {
|
||||
air: bool,
|
||||
fluid: bool,
|
||||
air_block: bool,
|
||||
motion: bool,
|
||||
no_leaves: bool,
|
||||
}
|
||||
impl HeightmapState for StateFacts {
|
||||
fn is_air(self) -> bool {
|
||||
self.air
|
||||
}
|
||||
fn is_air_block(self) -> bool {
|
||||
self.air_block
|
||||
}
|
||||
fn has_fluid(self) -> bool {
|
||||
self.fluid
|
||||
}
|
||||
fn blocks_motion_in_heightmap(self) -> bool {
|
||||
self.motion
|
||||
}
|
||||
fn blocks_motion_in_heightmap_no_leaves(self) -> bool {
|
||||
self.no_leaves
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct Properties(Arc<Vec<StateFacts>>);
|
||||
impl TerrainBlockStates for Properties {
|
||||
type State = StateFacts;
|
||||
fn heightmap_state(&self, id: BlockStateId) -> StateFacts {
|
||||
self.0[id.0 as usize]
|
||||
}
|
||||
}
|
||||
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>,
|
||||
}
|
||||
fn invalid(message: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, message)
|
||||
}
|
||||
fn tag(value: &Value) -> Result<Tag> {
|
||||
Ok(match value {
|
||||
Value::String(value) => Tag::String(value.as_str().into()),
|
||||
Value::Number(value) => Tag::Int(i32::try_from(
|
||||
value
|
||||
.as_i64()
|
||||
.ok_or_else(|| invalid("invalid registry number"))?,
|
||||
)?),
|
||||
Value::Array(values) => Tag::List(values.iter().map(tag).collect::<Result<_>>()?),
|
||||
Value::Object(values) => Tag::Compound(
|
||||
values
|
||||
.iter()
|
||||
.map(|(name, value)| Ok((name.as_str().into(), tag(value)?)))
|
||||
.collect::<Result<_>>()?,
|
||||
),
|
||||
_ => return Err(invalid("unsupported registry value").into()),
|
||||
})
|
||||
}
|
||||
impl Assets {
|
||||
pub fn load(root: &Path) -> Result<Self> {
|
||||
let manifest: Value = serde_json::from_reader(BufReader::new(File::open(
|
||||
root.join("horizon-resources.json"),
|
||||
)?))?;
|
||||
if manifest["data_version"].as_i64() != Some(i64::from(DATA_VERSION)) {
|
||||
return Err(invalid("resources do not match Horizon's pinned data version").into());
|
||||
}
|
||||
let facts: Value =
|
||||
serde_json::from_reader(BufReader::new(File::open(root.join("facts.json"))?))?;
|
||||
let states = facts["states"]
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid("missing registry state facts"))?;
|
||||
let registry = BlockRegistry::from_nbt(&Tag::compound([
|
||||
("DataVersion", Tag::Int(DATA_VERSION)),
|
||||
(
|
||||
"states",
|
||||
Tag::List(
|
||||
states
|
||||
.iter()
|
||||
.map(|state| tag(&state[4]))
|
||||
.collect::<Result<_>>()?,
|
||||
),
|
||||
),
|
||||
("defaults", tag(&facts["defaults"])?),
|
||||
]))?;
|
||||
let bundle: Value =
|
||||
serde_json::from_reader(BufReader::new(File::open(root.join("block-tags.json"))?))?;
|
||||
let mut definitions = TagDefinitions::default();
|
||||
for (name, text) in bundle
|
||||
.as_object()
|
||||
.ok_or_else(|| invalid("invalid block tag bundle"))?
|
||||
{
|
||||
definitions.apply_json(
|
||||
name,
|
||||
"vanilla",
|
||||
text.as_str()
|
||||
.ok_or_else(|| invalid("invalid block tag text"))?,
|
||||
)?;
|
||||
}
|
||||
let built =
|
||||
definitions.build(|name, _| facts["defaults"].get(name).map(|_| name.to_owned()))?;
|
||||
if !built.missing.is_empty() {
|
||||
return Err(invalid("unresolved block tags").into());
|
||||
}
|
||||
let motion: BTreeSet<_> = built
|
||||
.tags
|
||||
.get("minecraft:blocks_motion_in_heightmap")
|
||||
.ok_or_else(|| invalid("missing motion tag"))?
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
let no_leaves: BTreeSet<_> = built
|
||||
.tags
|
||||
.get("minecraft:blocks_motion_in_heightmap_no_leaves")
|
||||
.ok_or_else(|| invalid("missing no-leaves motion tag"))?
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect();
|
||||
let properties = Properties(Arc::new(
|
||||
states
|
||||
.iter()
|
||||
.map(|state| {
|
||||
Ok(StateFacts {
|
||||
air: state[1]
|
||||
.as_bool()
|
||||
.ok_or_else(|| invalid("missing air fact"))?,
|
||||
fluid: state[2]
|
||||
.as_bool()
|
||||
.ok_or_else(|| invalid("missing fluid fact"))?,
|
||||
air_block: state[0].as_str() == Some("minecraft:air"),
|
||||
motion: motion.contains(
|
||||
state[0]
|
||||
.as_str()
|
||||
.ok_or_else(|| invalid("missing state name"))?,
|
||||
),
|
||||
no_leaves: no_leaves.contains(
|
||||
state[0]
|
||||
.as_str()
|
||||
.ok_or_else(|| invalid("missing state name"))?,
|
||||
),
|
||||
})
|
||||
})
|
||||
.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 pixels = Vec::new();
|
||||
let mut sprite_size = 0;
|
||||
for (layer, name) in MATERIALS.iter().enumerate() {
|
||||
let state = registry
|
||||
.default_state(&format!("minecraft:{name}"))
|
||||
.ok_or_else(|| invalid("missing test-scene material"))?;
|
||||
material_states[layer] = state;
|
||||
layers[state.0 as usize] = layer as i32;
|
||||
let path = root.join(format!("assets/minecraft/textures/block/{name}.png"));
|
||||
let mut decoder = png::Decoder::new(BufReader::new(File::open(path)?));
|
||||
decoder
|
||||
.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
|
||||
let mut reader = decoder.read_info()?;
|
||||
let mut bytes = vec![
|
||||
0;
|
||||
reader
|
||||
.output_buffer_size()
|
||||
.ok_or_else(|| invalid("sprite exceeds decoder limits"))?
|
||||
];
|
||||
let info = reader.next_frame(&mut bytes)?;
|
||||
if info.width != info.height
|
||||
|| info.width == 0
|
||||
|| (sprite_size != 0 && sprite_size != info.width)
|
||||
{
|
||||
return Err(invalid(
|
||||
"test-client sprites must be square and use matching dimensions",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
sprite_size = info.width;
|
||||
let channels = info.color_type.samples();
|
||||
for pixel in bytes[..info.buffer_size()].chunks_exact(channels) {
|
||||
let rgba = match info.color_type {
|
||||
png::ColorType::Rgba => [pixel[0], pixel[1], pixel[2], pixel[3]],
|
||||
png::ColorType::Rgb => [pixel[0], pixel[1], pixel[2], 255],
|
||||
png::ColorType::Grayscale => [pixel[0], pixel[0], pixel[0], 255],
|
||||
png::ColorType::GrayscaleAlpha => [pixel[0], pixel[0], pixel[0], pixel[1]],
|
||||
_ => return Err(invalid("unsupported expanded sprite format").into()),
|
||||
};
|
||||
pixels.extend(rgba);
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
registry,
|
||||
properties,
|
||||
material_states,
|
||||
layers,
|
||||
sprite_size,
|
||||
pixels,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Free inspection camera, deliberately separate from future player simulation.
|
||||
use glam::{DVec3, Mat4, Vec3};
|
||||
use std::collections::HashSet;
|
||||
use winit::keyboard::KeyCode;
|
||||
pub struct Camera {
|
||||
pub position: DVec3,
|
||||
pub yaw: f64,
|
||||
pub pitch: f64,
|
||||
}
|
||||
impl Default for Camera {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
position: DVec3::new(25.0, 18.0, 25.0),
|
||||
yaw: -135_f64.to_radians(),
|
||||
pitch: -22_f64.to_radians(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Camera {
|
||||
pub fn look(&mut self, x: f64, y: f64) {
|
||||
self.yaw -= x * 0.002;
|
||||
self.pitch = (self.pitch - y * 0.002).clamp(-1.55, 1.55);
|
||||
}
|
||||
pub fn update(&mut self, keys: &HashSet<KeyCode>, seconds: f64) {
|
||||
let held = |key| f64::from(u8::from(keys.contains(&key)));
|
||||
self.yaw += (held(KeyCode::ArrowLeft) - held(KeyCode::ArrowRight)) * seconds * 1.5;
|
||||
self.pitch = (self.pitch
|
||||
+ (held(KeyCode::ArrowUp) - held(KeyCode::ArrowDown)) * seconds * 1.5)
|
||||
.clamp(-1.55, 1.55);
|
||||
let forward = DVec3::new(self.yaw.sin(), 0.0, self.yaw.cos());
|
||||
let right = DVec3::new(-self.yaw.cos(), 0.0, self.yaw.sin());
|
||||
let movement = forward * (held(KeyCode::KeyW) - held(KeyCode::KeyS))
|
||||
+ right * (held(KeyCode::KeyD) - held(KeyCode::KeyA))
|
||||
+ DVec3::Y
|
||||
* (held(KeyCode::Space) - held(KeyCode::ShiftLeft) - held(KeyCode::ShiftRight));
|
||||
if movement.length_squared() > 0.0 {
|
||||
self.position += movement.normalize()
|
||||
* seconds
|
||||
* if keys.contains(&KeyCode::ControlLeft) || keys.contains(&KeyCode::ControlRight) {
|
||||
40.0
|
||||
} else {
|
||||
12.0
|
||||
};
|
||||
}
|
||||
}
|
||||
pub fn matrix(&self, aspect: f32) -> Mat4 {
|
||||
let forward = Vec3::new(
|
||||
(self.yaw.sin() * self.pitch.cos()) as f32,
|
||||
self.pitch.sin() as f32,
|
||||
(self.yaw.cos() * self.pitch.cos()) as f32,
|
||||
);
|
||||
Mat4::perspective_rh(70_f32.to_radians(), aspect, 0.05, 1024.0)
|
||||
* Mat4::look_to_rh(self.position.as_vec3(), forward, Vec3::Y)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
//! Native Horizon development client. The scene and free camera are rendering
|
||||
//! tools; they do not replace the authoritative gameplay implementation.
|
||||
#![forbid(unsafe_code)]
|
||||
mod assets;
|
||||
mod camera;
|
||||
mod mesh;
|
||||
mod render;
|
||||
mod world;
|
||||
use assets::Assets;
|
||||
use camera::Camera;
|
||||
use mesh::Quad;
|
||||
use render::Renderer;
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
fs,
|
||||
path::PathBuf,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
event::{DeviceEvent, DeviceId, ElementState, MouseButton, WindowEvent},
|
||||
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
|
||||
keyboard::{KeyCode, PhysicalKey},
|
||||
window::{CursorGrabMode, Window, WindowId},
|
||||
};
|
||||
use world::TestWorld;
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
|
||||
struct Options {
|
||||
resources: PathBuf,
|
||||
radius: i32,
|
||||
frames: Option<u64>,
|
||||
report: Option<PathBuf>,
|
||||
timeout: Duration,
|
||||
trace_input: bool,
|
||||
}
|
||||
impl Options {
|
||||
fn read() -> Result<Option<Self>> {
|
||||
let sibling = std::env::current_exe()?
|
||||
.parent()
|
||||
.ok_or("missing executable directory")?
|
||||
.join("resources");
|
||||
let mut options = Self {
|
||||
resources: if sibling.join("horizon-resources.json").exists() {
|
||||
sibling
|
||||
} else {
|
||||
PathBuf::from(".local/horizon-client/26.3")
|
||||
},
|
||||
radius: 4,
|
||||
frames: None,
|
||||
report: None,
|
||||
timeout: Duration::from_secs(90),
|
||||
trace_input: false,
|
||||
};
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(argument) = args.next() {
|
||||
if argument == "--trace-input" {
|
||||
options.trace_input = true;
|
||||
continue;
|
||||
}
|
||||
if argument == "--help" || argument == "-h" {
|
||||
println!(
|
||||
"Horizon native development client\n\n --resources PATH Prepared pinned resources\n --radius CHUNKS Controlled scene radius, 1..16 (default 4)\n --frames COUNT Exit after this many presented frames\n --smoke-report PATH Write a runtime report on exit\n --timeout-seconds N Deadline for a frame-limited run (default 90)\n --trace-input Log received keyboard, mouse-button and focus events\n\nControls: click to capture mouse; WASD move; Space/Shift rise/descend;\nCtrl boosts speed; arrow keys rotate; Esc releases mouse; Ctrl+Q quits; F3 shows diagnostics.\n\nThis is a controlled cube scene with a free inspection camera, not complete gameplay."
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
let value = args
|
||||
.next()
|
||||
.ok_or_else(|| format!("missing value after {argument}"))?;
|
||||
match argument.as_str() {
|
||||
"--resources" => options.resources = value.into(),
|
||||
"--radius" => {
|
||||
options.radius = value.parse()?;
|
||||
if !(1..=16).contains(&options.radius) {
|
||||
return Err("radius must be 1..16 chunks".into());
|
||||
}
|
||||
}
|
||||
"--frames" => {
|
||||
let frames = value.parse()?;
|
||||
if frames == 0 {
|
||||
return Err("frame count must be positive".into());
|
||||
}
|
||||
options.frames = Some(frames);
|
||||
}
|
||||
"--smoke-report" => options.report = Some(value.into()),
|
||||
"--timeout-seconds" => {
|
||||
let seconds: u64 = value.parse()?;
|
||||
if seconds == 0 {
|
||||
return Err("timeout must be positive".into());
|
||||
}
|
||||
options.timeout = Duration::from_secs(seconds);
|
||||
}
|
||||
_ => return Err(format!("unknown option {argument}").into()),
|
||||
}
|
||||
}
|
||||
Ok(Some(options))
|
||||
}
|
||||
}
|
||||
struct App<'a> {
|
||||
assets: &'a Assets,
|
||||
world: TestWorld<'a>,
|
||||
mesh: Vec<Quad>,
|
||||
options: Options,
|
||||
window: Option<Arc<Window>>,
|
||||
renderer: Option<Renderer>,
|
||||
camera: Camera,
|
||||
keys: HashSet<KeyCode>,
|
||||
captured: bool,
|
||||
focused: bool,
|
||||
diagnostics: bool,
|
||||
started: Instant,
|
||||
previous: Instant,
|
||||
next_redraw: Instant,
|
||||
title_at: Instant,
|
||||
title_frames: u64,
|
||||
frames: u64,
|
||||
error: Option<String>,
|
||||
}
|
||||
impl App<'_> {
|
||||
fn fail(&mut self, event_loop: &ActiveEventLoop, error: impl ToString) {
|
||||
self.error = Some(error.to_string());
|
||||
event_loop.exit();
|
||||
}
|
||||
fn capture(&mut self, capture: bool) {
|
||||
let Some(window) = &self.window else {
|
||||
return;
|
||||
};
|
||||
if capture {
|
||||
self.captured = window
|
||||
.set_cursor_grab(CursorGrabMode::Locked)
|
||||
.or_else(|_| window.set_cursor_grab(CursorGrabMode::Confined))
|
||||
.is_ok();
|
||||
} else {
|
||||
let _ = window.set_cursor_grab(CursorGrabMode::None);
|
||||
self.captured = false;
|
||||
}
|
||||
window.set_cursor_visible(!self.captured);
|
||||
}
|
||||
fn write_report(&self) -> Result<()> {
|
||||
let Some(path) = &self.options.report else {
|
||||
return Ok(());
|
||||
};
|
||||
let renderer = self.renderer.as_ref();
|
||||
let adapter = renderer.map(|r| {
|
||||
serde_json::json!({
|
||||
"name": r.info.name,
|
||||
"backend": format!("{:?}", r.info.backend),
|
||||
"device_type": format!("{:?}", r.info.device_type),
|
||||
"vendor": r.info.vendor,
|
||||
"device": r.info.device,
|
||||
})
|
||||
});
|
||||
let size = self.window.as_ref().map(|window| {
|
||||
let size = window.inner_size();
|
||||
[size.width, size.height]
|
||||
});
|
||||
let report = serde_json::json!({
|
||||
"schema": 1,
|
||||
"project": "Horizon",
|
||||
"scope": "Native opaque-cube renderer and free inspection camera; no gameplay simulation",
|
||||
"os": std::env::consts::OS,
|
||||
"arch": std::env::consts::ARCH,
|
||||
"adapter": adapter,
|
||||
"window_size": size,
|
||||
"presented_frames": self.frames,
|
||||
"elapsed_seconds": self.started.elapsed().as_secs_f64(),
|
||||
"resident_chunks": self.world.chunks.len(),
|
||||
"merged_quads": self.mesh.len(),
|
||||
"camera_position": self.camera.position.to_array(),
|
||||
"camera_yaw": self.camera.yaw,
|
||||
"camera_pitch": self.camera.pitch,
|
||||
"error": self.error,
|
||||
});
|
||||
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
fs::write(path, serde_json::to_vec_pretty(&report)?)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl ApplicationHandler for App<'_> {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.window.is_some() {
|
||||
return;
|
||||
}
|
||||
let window = match event_loop.create_window(
|
||||
Window::default_attributes()
|
||||
.with_title("Horizon — Development Client")
|
||||
.with_inner_size(winit::dpi::LogicalSize::new(1280.0, 800.0)),
|
||||
) {
|
||||
Ok(window) => Arc::new(window),
|
||||
Err(error) => {
|
||||
self.fail(event_loop, error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
match pollster::block_on(Renderer::new(
|
||||
window.clone(),
|
||||
self.assets,
|
||||
&self.mesh,
|
||||
((self.options.radius + 1) * 16) as f32,
|
||||
)) {
|
||||
Ok(renderer) => self.renderer = Some(renderer),
|
||||
Err(error) => {
|
||||
self.fail(event_loop, error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.window = Some(window);
|
||||
self.previous = Instant::now();
|
||||
self.next_redraw = self.previous;
|
||||
self.title_at = self.previous;
|
||||
}
|
||||
fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
|
||||
if self.options.trace_input
|
||||
&& matches!(
|
||||
event,
|
||||
WindowEvent::Focused(_)
|
||||
| WindowEvent::KeyboardInput { .. }
|
||||
| WindowEvent::MouseInput { .. }
|
||||
)
|
||||
{
|
||||
eprintln!("Horizon input: {event:?}");
|
||||
}
|
||||
if self.window.as_ref().is_none_or(|window| window.id() != id) {
|
||||
return;
|
||||
}
|
||||
match event {
|
||||
WindowEvent::CloseRequested => event_loop.exit(),
|
||||
WindowEvent::Resized(size) => {
|
||||
if let Some(renderer) = &mut self.renderer {
|
||||
renderer.resize(size.width, size.height);
|
||||
}
|
||||
self.next_redraw = Instant::now();
|
||||
}
|
||||
WindowEvent::Focused(focused) => {
|
||||
self.focused = focused;
|
||||
if !focused {
|
||||
self.keys.clear();
|
||||
self.capture(false);
|
||||
}
|
||||
self.previous = Instant::now();
|
||||
}
|
||||
WindowEvent::MouseInput {
|
||||
state: ElementState::Pressed,
|
||||
button: MouseButton::Left,
|
||||
..
|
||||
} => self.capture(true),
|
||||
WindowEvent::KeyboardInput { event, .. } => {
|
||||
if let PhysicalKey::Code(key) = event.physical_key {
|
||||
if event.state == ElementState::Pressed {
|
||||
self.keys.insert(key);
|
||||
if key == KeyCode::Escape {
|
||||
self.capture(false);
|
||||
}
|
||||
if key == KeyCode::F3 && !event.repeat {
|
||||
self.diagnostics = !self.diagnostics;
|
||||
if !self.diagnostics {
|
||||
self.window
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.set_title("Horizon — Development Client");
|
||||
}
|
||||
}
|
||||
if key == KeyCode::KeyQ
|
||||
&& (self.keys.contains(&KeyCode::ControlLeft)
|
||||
|| self.keys.contains(&KeyCode::ControlRight))
|
||||
{
|
||||
event_loop.exit();
|
||||
}
|
||||
} else {
|
||||
self.keys.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
let now = Instant::now();
|
||||
let seconds = now.duration_since(self.previous).as_secs_f64().min(0.1);
|
||||
self.previous = now;
|
||||
if self.focused {
|
||||
self.camera.update(&self.keys, seconds);
|
||||
}
|
||||
let result = self.renderer.as_mut().unwrap().render(&self.camera);
|
||||
match result {
|
||||
Ok(true) => {
|
||||
self.frames += 1;
|
||||
self.next_redraw = Instant::now();
|
||||
if self
|
||||
.options
|
||||
.frames
|
||||
.is_some_and(|target| self.frames >= target)
|
||||
{
|
||||
event_loop.exit();
|
||||
}
|
||||
if self.diagnostics && self.title_at.elapsed() >= Duration::from_secs(1) {
|
||||
let fps = (self.frames - self.title_frames) as f64
|
||||
/ self.title_at.elapsed().as_secs_f64();
|
||||
self.window.as_ref().unwrap().set_title(&format!(
|
||||
"Horizon — Development | {fps:.0} FPS | {} chunks | {} quads",
|
||||
self.world.chunks.len(),
|
||||
self.mesh.len()
|
||||
));
|
||||
self.title_at = Instant::now();
|
||||
self.title_frames = self.frames;
|
||||
}
|
||||
}
|
||||
Ok(false) => self.next_redraw = Instant::now() + Duration::from_millis(100),
|
||||
Err(error) => self.fail(event_loop, error),
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
fn device_event(&mut self, _: &ActiveEventLoop, _: DeviceId, event: DeviceEvent) {
|
||||
if self.captured
|
||||
&& self.focused
|
||||
&& let DeviceEvent::MouseMotion { delta: (x, y) } = event
|
||||
{
|
||||
self.camera.look(x, y);
|
||||
}
|
||||
}
|
||||
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.options.frames.is_some() && self.started.elapsed() > self.options.timeout {
|
||||
self.fail(event_loop, "frame-limited client run timed out");
|
||||
return;
|
||||
}
|
||||
if Instant::now() >= self.next_redraw {
|
||||
if let Some(window) = &self.window {
|
||||
window.request_redraw();
|
||||
}
|
||||
event_loop.set_control_flow(if self.options.frames.is_some() {
|
||||
ControlFlow::WaitUntil(self.started + self.options.timeout)
|
||||
} else {
|
||||
ControlFlow::Wait
|
||||
});
|
||||
} else {
|
||||
event_loop.set_control_flow(ControlFlow::WaitUntil(self.next_redraw));
|
||||
}
|
||||
}
|
||||
}
|
||||
fn run() -> Result<()> {
|
||||
let Some(options) = Options::read()? else {
|
||||
return Ok(());
|
||||
};
|
||||
let assets = Assets::load(&options.resources).map_err(|error| {
|
||||
format!("{error}\nPrepare pinned resources with: python3 tools/prepare_native_client.py")
|
||||
})?;
|
||||
let world = TestWorld::new(&assets, options.radius)?;
|
||||
let mesh = mesh::build(&world)?;
|
||||
eprintln!(
|
||||
"Horizon development scene: {} resident chunks, {} merged cube faces.\nClick to capture mouse; WASD/Space/Shift move; arrows rotate; Esc releases; Ctrl+Q quits.",
|
||||
world.chunks.len(),
|
||||
mesh.len()
|
||||
);
|
||||
let now = Instant::now();
|
||||
let mut app = App {
|
||||
assets: &assets,
|
||||
world,
|
||||
mesh,
|
||||
options,
|
||||
window: None,
|
||||
renderer: None,
|
||||
camera: Camera::default(),
|
||||
keys: HashSet::new(),
|
||||
captured: false,
|
||||
focused: true,
|
||||
diagnostics: false,
|
||||
started: now,
|
||||
previous: now,
|
||||
next_redraw: now,
|
||||
title_at: now,
|
||||
title_frames: 0,
|
||||
frames: 0,
|
||||
error: None,
|
||||
};
|
||||
EventLoop::new()?.run_app(&mut app)?;
|
||||
app.write_report()?;
|
||||
if let Some(error) = app.error {
|
||||
return Err(error.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn main() {
|
||||
if let Err(error) = run() {
|
||||
eprintln!("Horizon: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! 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};
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct Quad {
|
||||
pub origin: [f32; 3],
|
||||
pub extent: [f32; 2],
|
||||
pub face: u32,
|
||||
pub layer: u32,
|
||||
}
|
||||
fn position(face: usize, plane: usize, u: usize, v: usize) -> [usize; 3] {
|
||||
match face {
|
||||
0 | 1 => [u, plane, v],
|
||||
2 | 3 => [u, v, plane],
|
||||
_ => [plane, v, u],
|
||||
}
|
||||
}
|
||||
pub fn build(world: &TestWorld<'_>) -> Result<Vec<Quad>> {
|
||||
let mut quads = Vec::new();
|
||||
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,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
mesh_chunk(&cells, cx, cz, &mut quads);
|
||||
}
|
||||
Ok(quads)
|
||||
}
|
||||
fn index(x: usize, y: usize, z: usize) -> usize {
|
||||
x + 18 * (z + 18 * y)
|
||||
}
|
||||
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];
|
||||
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,
|
||||
2 | 3 => 2,
|
||||
_ => 0,
|
||||
};
|
||||
if face % 2 == 0 {
|
||||
adjacent[axis] -= 1;
|
||||
} else {
|
||||
adjacent[axis] += 1;
|
||||
}
|
||||
if layer >= 0 && cells[index(adjacent[0], adjacent[1], adjacent[2])] < 0 {
|
||||
mask[u + v * 16] = layer;
|
||||
}
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
// Compare rectangles expanded to unit faces against direct voxel adjacency.
|
||||
// The reference does not use the mesher's plane masks or coordinate helper.
|
||||
fn verify(cells: &[i32; 18 * 18 * 18], cx: i32, cz: i32) -> Vec<Quad> {
|
||||
let mut expected = BTreeSet::new();
|
||||
let directions = [
|
||||
[0, -1, 0],
|
||||
[0, 1, 0],
|
||||
[0, 0, -1],
|
||||
[0, 0, 1],
|
||||
[-1, 0, 0],
|
||||
[1, 0, 0],
|
||||
];
|
||||
for y in 1..=16 {
|
||||
for z in 1..=16 {
|
||||
for x in 1..=16 {
|
||||
let layer = cells[index(x, y, z)];
|
||||
if layer < 0 {
|
||||
continue;
|
||||
}
|
||||
for (face, [dx, dy, dz]) in directions.iter().enumerate() {
|
||||
let neighbor = [
|
||||
(x as i32 + dx) as usize,
|
||||
(y as i32 + dy) as usize,
|
||||
(z as i32 + dz) as usize,
|
||||
];
|
||||
if cells[index(neighbor[0], neighbor[1], neighbor[2])] < 0 {
|
||||
expected.insert((
|
||||
x as i32 - 1 + cx * 16,
|
||||
y as i32 - 1,
|
||||
z as i32 - 1 + cz * 16,
|
||||
face as u32,
|
||||
layer as u32,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut quads = Vec::new();
|
||||
mesh_chunk(cells, cx, cz, &mut quads);
|
||||
let mut actual = BTreeSet::new();
|
||||
for quad in &quads {
|
||||
assert!(
|
||||
quad.extent
|
||||
.iter()
|
||||
.all(|&e| (1.0..=16.0).contains(&e) && e.fract() == 0.0)
|
||||
);
|
||||
for v in 0..quad.extent[1] as i32 {
|
||||
for u in 0..quad.extent[0] as i32 {
|
||||
let [x, y, z] = quad.origin.map(|n| n as i32);
|
||||
let (x, y, z) = match quad.face {
|
||||
0 => (x + u, y, z + v),
|
||||
1 => (x + u, y - 1, z + v),
|
||||
2 => (x + u, y + v, z),
|
||||
3 => (x + u, y + v, z - 1),
|
||||
4 => (x, y + v, z + u),
|
||||
5 => (x - 1, y + v, z + u),
|
||||
_ => panic!("invalid face"),
|
||||
};
|
||||
assert!(
|
||||
actual.insert((x, y, z, quad.face, quad.layer)),
|
||||
"overlapping faces"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(actual, expected);
|
||||
quads
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_solid_and_neighbor_seams() {
|
||||
let mut cells = [-1; 18 * 18 * 18];
|
||||
assert!(verify(&cells, 0, 0).is_empty());
|
||||
for y in 1..=16 {
|
||||
for z in 1..=16 {
|
||||
for x in 1..=16 {
|
||||
cells[index(x, y, z)] = 3;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(verify(&cells, -3, 2).len(), 6);
|
||||
// A solid neighbor removes only the shared boundary, including corners.
|
||||
for y in 1..=16 {
|
||||
for z in 1..=16 {
|
||||
cells[index(17, y, z)] = 4;
|
||||
}
|
||||
}
|
||||
assert_eq!(verify(&cells, -3, 2).len(), 5);
|
||||
cells.fill(3);
|
||||
assert!(verify(&cells, 1, -2).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cavities_material_boundaries_and_random_neighbors() {
|
||||
let mut state = 0x183d_994e_058b_9432_u64;
|
||||
for pattern in 0..12 {
|
||||
let mut cells = [-1; 18 * 18 * 18];
|
||||
for y in 0..18 {
|
||||
for z in 0..18 {
|
||||
for x in 0..18 {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
cells[index(x, y, z)] = match pattern {
|
||||
0 => {
|
||||
if x == 8 && y == 8 && z == 8 {
|
||||
-1
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
1 => ((x + y + z) % 3) as i32,
|
||||
_ => (state % 7) as i32 - 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
verify(&cells, pattern - 6, 3 - pattern);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
use crate::{Result, assets::Assets, camera::Camera, mesh::Quad};
|
||||
use std::sync::Arc;
|
||||
use wgpu::util::DeviceExt;
|
||||
use winit::window::Window;
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct Uniforms {
|
||||
matrix: [[f32; 4]; 4],
|
||||
position: [f32; 4],
|
||||
fog: [f32; 4],
|
||||
}
|
||||
pub struct Renderer {
|
||||
instance: wgpu::Instance,
|
||||
surface: wgpu::Surface<'static>,
|
||||
window: Arc<Window>,
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
config: wgpu::SurfaceConfiguration,
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
group: wgpu::BindGroup,
|
||||
uniform: wgpu::Buffer,
|
||||
quads: wgpu::Buffer,
|
||||
depth: wgpu::TextureView,
|
||||
pub quad_count: u32,
|
||||
pub info: wgpu::AdapterInfo,
|
||||
pub suspended: bool,
|
||||
fog_distance: f32,
|
||||
}
|
||||
impl Renderer {
|
||||
pub async fn new(
|
||||
window: Arc<Window>,
|
||||
assets: &Assets,
|
||||
quads: &[Quad],
|
||||
fog_distance: f32,
|
||||
) -> Result<Self> {
|
||||
let instance =
|
||||
wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env());
|
||||
let surface = instance.create_surface(window.clone())?;
|
||||
let adapter = instance
|
||||
.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::HighPerformance,
|
||||
compatible_surface: Some(&surface),
|
||||
force_fallback_adapter: false,
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
let info = adapter.get_info();
|
||||
eprintln!(
|
||||
"Horizon renderer: {} ({:?}, {:?})",
|
||||
info.name, info.backend, info.device_type
|
||||
);
|
||||
let (device, queue) = adapter
|
||||
.request_device(&wgpu::DeviceDescriptor {
|
||||
label: Some("Horizon device"),
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
let size = window.inner_size();
|
||||
let mut config = surface
|
||||
.get_default_config(&adapter, size.width.max(1), size.height.max(1))
|
||||
.ok_or("surface has no supported configuration")?;
|
||||
let caps = surface.get_capabilities(&adapter);
|
||||
config.format = caps
|
||||
.formats
|
||||
.iter()
|
||||
.copied()
|
||||
.find(wgpu::TextureFormat::is_srgb)
|
||||
.unwrap_or(config.format);
|
||||
config.present_mode = wgpu::PresentMode::Fifo;
|
||||
surface.configure(&device, &config);
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("Horizon cube renderer"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("world.wgsl").into()),
|
||||
});
|
||||
let attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint32,3=>Uint32];
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Horizon opaque cubes"),
|
||||
layout: None,
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs_main"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[Some(wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<Quad>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Instance,
|
||||
attributes: &attributes,
|
||||
})],
|
||||
},
|
||||
primitive: wgpu::PrimitiveState {
|
||||
cull_mode: Some(wgpu::Face::Back),
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(true),
|
||||
depth_compare: Some(wgpu::CompareFunction::Less),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some("fs_main"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: config.format,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Horizon camera"),
|
||||
size: std::mem::size_of::<Uniforms>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let texture = device.create_texture_with_data(
|
||||
&queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: Some("Pinned cube sprites"),
|
||||
size: wgpu::Extent3d {
|
||||
width: assets.sprite_size,
|
||||
height: assets.sprite_size,
|
||||
depth_or_array_layers: assets.material_states.len() as u32,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8UnormSrgb,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
},
|
||||
wgpu::util::TextureDataOrder::LayerMajor,
|
||||
&assets.pixels,
|
||||
);
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
dimension: Some(wgpu::TextureViewDimension::D2Array),
|
||||
..Default::default()
|
||||
});
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("Repeating nearest cube sprites"),
|
||||
address_mode_u: wgpu::AddressMode::Repeat,
|
||||
address_mode_v: wgpu::AddressMode::Repeat,
|
||||
mag_filter: wgpu::FilterMode::Nearest,
|
||||
min_filter: wgpu::FilterMode::Nearest,
|
||||
..Default::default()
|
||||
});
|
||||
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("Horizon world resources"),
|
||||
layout: &pipeline.get_bind_group_layout(0),
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: uniform.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::TextureView(&view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource: wgpu::BindingResource::Sampler(&sampler),
|
||||
},
|
||||
],
|
||||
});
|
||||
let quad_count = u32::try_from(quads.len())?;
|
||||
let quads = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Greedy cube faces"),
|
||||
contents: bytemuck::cast_slice(quads),
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
});
|
||||
let depth = Self::depth(&device, &config);
|
||||
Ok(Self {
|
||||
instance,
|
||||
surface,
|
||||
window,
|
||||
device,
|
||||
queue,
|
||||
config,
|
||||
pipeline,
|
||||
group,
|
||||
uniform,
|
||||
quads,
|
||||
depth,
|
||||
quad_count,
|
||||
info,
|
||||
suspended: size.width == 0 || size.height == 0,
|
||||
fog_distance,
|
||||
})
|
||||
}
|
||||
fn depth(device: &wgpu::Device, config: &wgpu::SurfaceConfiguration) -> wgpu::TextureView {
|
||||
device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("Horizon depth"),
|
||||
size: wgpu::Extent3d {
|
||||
width: config.width,
|
||||
height: config.height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
view_formats: &[],
|
||||
})
|
||||
.create_view(&Default::default())
|
||||
}
|
||||
pub fn resize(&mut self, width: u32, height: u32) {
|
||||
self.suspended = width == 0 || height == 0;
|
||||
if self.suspended {
|
||||
return;
|
||||
}
|
||||
self.config.width = width;
|
||||
self.config.height = height;
|
||||
self.surface.configure(&self.device, &self.config);
|
||||
self.depth = Self::depth(&self.device, &self.config);
|
||||
}
|
||||
pub fn render(&mut self, camera: &Camera) -> Result<bool> {
|
||||
if self.suspended {
|
||||
return Ok(false);
|
||||
}
|
||||
let (frame, reconfigure) = match self.surface.get_current_texture() {
|
||||
wgpu::CurrentSurfaceTexture::Success(frame) => (frame, false),
|
||||
wgpu::CurrentSurfaceTexture::Suboptimal(frame) => (frame, true),
|
||||
wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
|
||||
return Ok(false);
|
||||
}
|
||||
wgpu::CurrentSurfaceTexture::Outdated => {
|
||||
self.surface.configure(&self.device, &self.config);
|
||||
return Ok(false);
|
||||
}
|
||||
wgpu::CurrentSurfaceTexture::Lost => {
|
||||
self.surface = self.instance.create_surface(self.window.clone())?;
|
||||
self.surface.configure(&self.device, &self.config);
|
||||
return Ok(false);
|
||||
}
|
||||
wgpu::CurrentSurfaceTexture::Validation => {
|
||||
return Err("surface acquisition failed validation".into());
|
||||
}
|
||||
};
|
||||
let fog = [0.35, 0.55, 0.80, 1.0];
|
||||
let p = camera.position.as_vec3();
|
||||
let uniforms = Uniforms {
|
||||
matrix: camera
|
||||
.matrix(self.config.width as f32 / self.config.height as f32)
|
||||
.to_cols_array_2d(),
|
||||
position: [p.x, p.y, p.z, self.fog_distance],
|
||||
fog,
|
||||
};
|
||||
self.queue
|
||||
.write_buffer(&self.uniform, 0, bytemuck::bytes_of(&uniforms));
|
||||
let view = frame.texture.create_view(&Default::default());
|
||||
let mut encoder = self
|
||||
.device
|
||||
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("Horizon frame"),
|
||||
});
|
||||
{
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: &view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color {
|
||||
r: f64::from(fog[0]),
|
||||
g: f64::from(fog[1]),
|
||||
b: f64::from(fog[2]),
|
||||
a: 1.0,
|
||||
}),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})];
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Horizon world"),
|
||||
color_attachments: &attachments,
|
||||
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
|
||||
view: &self.depth,
|
||||
depth_ops: Some(wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(1.0),
|
||||
store: wgpu::StoreOp::Discard,
|
||||
}),
|
||||
stencil_ops: None,
|
||||
}),
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
pass.set_vertex_buffer(0, self.quads.slice(..));
|
||||
pass.draw(0..6, 0..self.quad_count);
|
||||
}
|
||||
self.queue.submit([encoder.finish()]);
|
||||
self.window.pre_present_notify();
|
||||
self.queue.present(frame);
|
||||
if reconfigure {
|
||||
self.surface.configure(&self.device, &self.config);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
//! A controlled opaque-cube scene for exercising the native renderer. This is
|
||||
//! not the vanilla world generator or an authoritative gameplay simulation.
|
||||
use crate::{
|
||||
Result,
|
||||
assets::{Assets, Properties},
|
||||
};
|
||||
use horizon_core::position::ChunkPos;
|
||||
use horizon_world::{registry::BlockStateId, worldgen::terrain::TerrainChunk};
|
||||
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> {
|
||||
pub fn new(assets: &'a Assets, radius: i32) -> Result<Self> {
|
||||
let air = assets
|
||||
.registry
|
||||
.default_state("minecraft:air")
|
||||
.ok_or("missing air state")?;
|
||||
let mut world = Self {
|
||||
chunks: BTreeMap::new(),
|
||||
assets,
|
||||
air,
|
||||
};
|
||||
for cz in -radius..=radius {
|
||||
for cx in -radius..=radius {
|
||||
let mut chunk = TerrainChunk::new(
|
||||
ChunkPos::new(cx, cz),
|
||||
0,
|
||||
16,
|
||||
&assets.registry,
|
||||
assets.properties.clone(),
|
||||
)?;
|
||||
for z in 0..16 {
|
||||
for x in 0..16 {
|
||||
for y in 0..4 {
|
||||
let layer = match y {
|
||||
0 => 0,
|
||||
1 | 2 => 1,
|
||||
_ => {
|
||||
if (cx + cz) & 1 == 0 {
|
||||
2
|
||||
} else {
|
||||
3
|
||||
}
|
||||
}
|
||||
};
|
||||
chunk.set_block_worldgen(
|
||||
cx * 16 + x,
|
||||
y,
|
||||
cz * 16 + z,
|
||||
assets.material_states[layer],
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
world.chunks.insert((cx, cz), chunk);
|
||||
}
|
||||
}
|
||||
for y in 4..11 {
|
||||
for z in -10_i32..=10 {
|
||||
for x in -10_i32..=10 {
|
||||
if x.abs().max(z.abs()) <= 10 - (y - 4) {
|
||||
world.set(
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
assets.material_states[if y & 1 == 0 { 4 } else { 5 }],
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(world)
|
||||
}
|
||||
fn set(&mut self, x: i32, y: i32, z: i32, state: BlockStateId) -> Result<()> {
|
||||
self.chunks
|
||||
.get_mut(&(x >> 4, z >> 4))
|
||||
.ok_or("test scene exceeds resident chunks")?
|
||||
.set_block_worldgen(x, y, z, state)?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn layer(&self, x: i32, y: i32, z: i32) -> Result<i32> {
|
||||
let state = 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
struct Camera {
|
||||
view_projection: mat4x4<f32>,
|
||||
position: vec4<f32>,
|
||||
fog: vec4<f32>,
|
||||
}
|
||||
@group(0) @binding(0) var<uniform> camera: Camera;
|
||||
@group(0) @binding(1) var sprites: texture_2d_array<f32>;
|
||||
@group(0) @binding(2) var sprite_sampler: sampler;
|
||||
struct VertexOut {
|
||||
@builtin(position) clip: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
@location(1) @interpolate(flat) layer: u32,
|
||||
@location(2) shade: f32,
|
||||
@location(3) world_position: vec3<f32>,
|
||||
}
|
||||
@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 {
|
||||
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);
|
||||
let flipped = face==1u || face==2u || face==5u;
|
||||
let corner = corners[select(normal_order[vertex],reversed_order[vertex],flipped)];
|
||||
let offset = corner*extent;
|
||||
var position = origin;
|
||||
if face<2u { position+=vec3(offset.x,0.0,offset.y); }
|
||||
else if face<4u { position+=vec3(offset.x,offset.y,0.0); }
|
||||
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.layer=layer;
|
||||
output.shade=select(select(0.8,0.6,face>=4u),select(0.5,1.0,face==1u),face<2u);
|
||||
output.world_position=position;
|
||||
return output;
|
||||
}
|
||||
@fragment fn fs_main(input:VertexOut)->@location(0) vec4<f32> {
|
||||
let color=textureSample(sprites,sprite_sampler,input.uv,i32(input.layer));
|
||||
let distance=length(input.world_position-camera.position.xyz);
|
||||
let fog_amount=smoothstep(camera.position.w*0.65,camera.position.w,distance);
|
||||
return vec4(mix(color.rgb*input.shade,camera.fog.rgb,fog_amount),1.0);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
# Horizon native development client
|
||||
|
||||
`horizon-client` opens a native Rust window and renders a controlled block scene
|
||||
stored in Horizon's resident chunks. It loads six opaque cube textures and the
|
||||
block registry from the pinned Java Edition 26.3 resources. A padded chunk mesh
|
||||
culls hidden faces across chunk boundaries and merges adjacent matching faces;
|
||||
the GPU draws the rectangles as instances. The camera is a free inspection tool.
|
||||
|
||||
This checkpoint has no player simulation, vanilla world generation, block
|
||||
interaction, inventory, sound, networking or world save/load. It does not meet
|
||||
the [playable-build acceptance criteria](rust-parity.md#completion-criteria-and-playable-builds).
|
||||
Full block models, weighted variants, texture orientation, transparency, tinting,
|
||||
light, resource packs, chunk streaming and visual parity remain unfinished.
|
||||
|
||||
## Run from a checkout
|
||||
|
||||
Use current stable Rust (the locked client dependencies require Rust 1.90 or
|
||||
newer), Python 3.10+ and JDK 25. A native desktop display and compatible graphics
|
||||
driver are required. Resource preparation verifies the pinned game artifacts,
|
||||
exports the registry using the reference server, and extracts selected client
|
||||
resources into ignored `.local/horizon-client/26.3/`.
|
||||
|
||||
```sh
|
||||
python3 tools/prepare_native_client.py --prepare
|
||||
cargo +stable run --locked -p horizon-client
|
||||
```
|
||||
|
||||
Java is used during preparation. The native executable itself runs without a
|
||||
JVM. Prepared resources stay private; do not commit or publish the extracted game
|
||||
files. Final distributable builds still need resource provisioning and packaging.
|
||||
|
||||
Use `--resources PATH` for a prepared resource directory. The executable also
|
||||
looks for a sibling `resources/` directory before the checkout default. Use
|
||||
`--radius N` to select 1–16 chunks around the origin; this is a finite test scene,
|
||||
not a render-distance or world-streaming implementation.
|
||||
|
||||
| Control | Action |
|
||||
| --- | --- |
|
||||
| WASD | Move horizontally |
|
||||
| Space / either Shift | Rise / descend |
|
||||
| Either Ctrl | Boost inspection speed |
|
||||
| Arrow keys | Rotate camera |
|
||||
| Left click | Capture mouse for camera rotation |
|
||||
| Escape | Release mouse |
|
||||
| F3 | Toggle FPS/chunk/mesh diagnostics in the window title |
|
||||
| Ctrl+Q or window close | Exit |
|
||||
|
||||
Controls bind physical keyboard positions. Losing focus clears held keys and
|
||||
releases the mouse. `--trace-input` logs keyboard, mouse-button and focus events
|
||||
for diagnosis. On headless Linux use `vscreen run ./target/debug/horizon-client`,
|
||||
then `vscreen shot`. The `wtype` tool's default generated keymap does not preserve
|
||||
physical key positions; typing the character W can report physical Escape.
|
||||
|
||||
## Validation
|
||||
|
||||
```sh
|
||||
cargo +stable test -p horizon-client
|
||||
cargo +stable clippy --workspace --all-targets -- -D warnings
|
||||
python3 tools/test_native_client.py
|
||||
# Headless Linux alternative:
|
||||
python3 tools/test_native_client.py --vscreen
|
||||
```
|
||||
|
||||
The mesh tests compare expanded rectangles against independently enumerated
|
||||
exposed voxel faces, including solid neighbors, cavities, material boundaries,
|
||||
negative chunk origins and random surroundings. The startup runner launches a
|
||||
nine-chunk scene, requires 30 presented frames and a clean exit, and writes GPU,
|
||||
platform, binary and source information to ignored
|
||||
`.local/horizon-client/startup-smoke.json`. It has an external timeout as well as
|
||||
the application's frame deadline. These checks do not establish gameplay or
|
||||
pixel parity with Java.
|
||||
|
||||
Initial local validation uses Linux x86_64, a headless Wayland compositor and
|
||||
Vulkan llvmpipe software rendering. Textured geometry and resizing were visually
|
||||
inspected; movement, arrow rotation and Ctrl+Q were exercised using virtual
|
||||
physical key codes. Captured relative mouse movement and Escape release were
|
||||
exercised through a virtual pointer. Native macOS/Metal and
|
||||
Windows/Direct3D 12 runtime tests remain pending. Software-renderer frame rates
|
||||
are not evidence of a hardware speedup.
|
||||
+6
-2
@@ -2,7 +2,9 @@
|
||||
|
||||
The behavior target is the repository's pinned **Minecraft Java Edition 26.3**.
|
||||
One-to-one vanilla gameplay parity is the acceptance criterion. It has **not**
|
||||
been reached: Horizon's Rust code does not yet run a client, server, or simulation.
|
||||
been reached. Horizon now has a [native development client](native-client.md)
|
||||
that renders a controlled block scene with a free camera. It does not run a
|
||||
complete game server or gameplay simulation.
|
||||
The Rust workspace implements core arithmetic/random streams, world data and
|
||||
resident sections, scheduled tick ordering, geometry, contained fluid states,
|
||||
noise/density evaluation, biome and terrain generation kernels, material rules,
|
||||
@@ -78,7 +80,9 @@ Negative lengths and the complete Java object/API surface are not supported.
|
||||
|
||||
## Reproduce validation
|
||||
|
||||
Requires Rust 1.85 or newer, Python 3.10 or newer, and JDK 25. From the checkout:
|
||||
The core/world libraries require Rust 1.85 or newer; the native client's locked
|
||||
dependencies require Rust 1.90 or newer. Use current stable Rust, Python 3.10 or
|
||||
newer, and JDK 25 for the complete workspace. From the checkout:
|
||||
|
||||
```sh
|
||||
cargo test --workspace
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prepare private pinned resources for Horizon's native development client."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import zipfile
|
||||
try:
|
||||
from . import lab, test_rust_parity as base, test_worldgen_parity as worldgen
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
import test_worldgen_parity as worldgen
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--prepare', action='store_true', help='Fetch pinned reference artifacts first')
|
||||
args = parser.parse_args()
|
||||
if args.prepare:
|
||||
lab.prepare()
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
root = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
facts = root / 'facts.json'
|
||||
manifest = root / 'horizon-resources.json'
|
||||
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeightmapOracle.java'
|
||||
origin = {'minecraft': lock['minecraft']['version'],
|
||||
'client_sha256': lab.digest(jars['client'], 'sha256'),
|
||||
'server_sha256': lab.digest(jars['server'], 'sha256'),
|
||||
'exporter_sha256': lab.digest(oracle, 'sha256')}
|
||||
previous = json.loads(manifest.read_text()) if manifest.exists() else {}
|
||||
if not (all(previous.get(k) == v for k, v in origin.items()) and facts.exists()
|
||||
and previous.get('facts_sha256') == lab.digest(facts, 'sha256')):
|
||||
classes = root / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
with (root / 'export.log').open('w') as log:
|
||||
subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none',
|
||||
'-cp', dependencies, '-d', str(classes), str(oracle)], check=True,
|
||||
stdout=log, stderr=subprocess.STDOUT, timeout=3600)
|
||||
subprocess.run(['java', '-Xmx512M', '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.VanillaHeightmapOracle', 'export', str(facts)],
|
||||
check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600)
|
||||
tags = worldgen.tag_resources(jars['server'])
|
||||
if tags != worldgen.tag_resources(jars['client']):
|
||||
raise ValueError('Reference block tags disagree')
|
||||
lab.write_json(root / 'block-tags.json', tags)
|
||||
count = 0
|
||||
prefixes = ('assets/minecraft/blockstates/', 'assets/minecraft/models/block/',
|
||||
'assets/minecraft/textures/block/')
|
||||
with zipfile.ZipFile(jars['client']) as archive:
|
||||
version = json.loads(archive.read('version.json'))
|
||||
for name in archive.namelist():
|
||||
if not name.startswith(prefixes) or name.endswith('/'):
|
||||
continue
|
||||
relative = Path(name)
|
||||
if relative.is_absolute() or '..' in relative.parts:
|
||||
raise ValueError('Invalid resource path')
|
||||
target = root / relative
|
||||
data = archive.read(name)
|
||||
if not target.exists() or target.read_bytes() != data:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(data)
|
||||
count += 1
|
||||
lab.write_json(manifest, {'schema': 1, **origin, 'data_version': version['world_version'],
|
||||
'facts_sha256': lab.digest(facts, 'sha256'),
|
||||
'block_tags_sha256': lab.digest(root / 'block-tags.json', 'sha256'), 'resource_files': count})
|
||||
print(f'Prepared Horizon native-client resources: {root}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Launch the Rust development scene and check bounded GPU presentation.
|
||||
|
||||
Requires prepared private resources and a desktop display (or --vscreen on
|
||||
headless Linux). This is a renderer startup check, not a gameplay parity gate.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
try:
|
||||
from . import lab
|
||||
except ImportError:
|
||||
import lab
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--vscreen', action='store_true')
|
||||
parser.add_argument('--prepare', action='store_true')
|
||||
args = parser.parse_args()
|
||||
if args.prepare:
|
||||
subprocess.run([sys.executable, str(lab.ROOT / 'tools/prepare_native_client.py'),
|
||||
'--prepare'], cwd=lab.ROOT, check=True)
|
||||
root = lab.LOCAL / 'horizon-client'
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
report = root / 'startup-smoke.json'
|
||||
report.unlink(missing_ok=True)
|
||||
environment = dict(os.environ, RUSTUP_TOOLCHAIN='stable')
|
||||
subprocess.run(['cargo', 'build', '--locked', '-p', 'horizon-client'],
|
||||
cwd=lab.ROOT, env=environment, check=True, timeout=3600)
|
||||
metadata = json.loads(subprocess.check_output(
|
||||
['cargo', 'metadata', '--locked', '--no-deps', '--format-version', '1'],
|
||||
cwd=lab.ROOT, env=environment))
|
||||
executable = Path(metadata['target_directory']) / 'debug' / (
|
||||
'horizon-client.exe' if os.name == 'nt' else 'horizon-client')
|
||||
command = (['vscreen', 'run'] if args.vscreen else []) + [
|
||||
str(executable), '--radius', '1', '--frames', '30',
|
||||
'--smoke-report', str(report), '--timeout-seconds', '60']
|
||||
with (root / 'startup-smoke.log').open('w') as log:
|
||||
subprocess.run(command, cwd=lab.ROOT, env=environment, check=True,
|
||||
stdout=log, stderr=subprocess.STDOUT, timeout=120)
|
||||
result = json.loads(report.read_text())
|
||||
if (result.get('error') is not None or result.get('presented_frames') != 30
|
||||
or result.get('resident_chunks') != 9 or result.get('merged_quads', 0) <= 0
|
||||
or not result.get('adapter') or min(result.get('window_size', [0])) <= 0):
|
||||
raise RuntimeError('Incomplete native client presentation: ' + str(report))
|
||||
result['executable_sha256'] = lab.digest(executable, 'sha256')
|
||||
result['resource_manifest_sha256'] = lab.digest(
|
||||
root / '26.3/horizon-resources.json', 'sha256')
|
||||
result['sources'] = {
|
||||
str(path.relative_to(lab.ROOT)): lab.digest(path, 'sha256')
|
||||
for path in sorted((lab.ROOT / 'crates/horizon-client/src').glob('*'))
|
||||
if path.is_file()
|
||||
}
|
||||
lab.write_json(report, result)
|
||||
print(f'Native renderer startup passed: {report}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user