Merge main into fix/banner-item-components

Resolve game.rs and titles.rs against the resources split (#537): layer
names and item names now come from self.pack, the atlas from self.atlas.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-17 00:47:22 +02:00
170 changed files with 7428 additions and 1197 deletions
Generated
+14
View File
@@ -1483,6 +1483,7 @@ dependencies = [
"horizon-mods",
"log",
"serde",
"serde_json",
"toml",
"wasmtime",
"wit-component 0.239.0",
@@ -1497,6 +1498,19 @@ dependencies = [
"horizon-mod-sdk",
]
[[package]]
name = "horizon-port-pack"
version = "0.1.0"
dependencies = [
"horizon-mods",
"serde",
"serde_json",
"sha1",
"toml",
"ureq",
"zip",
]
[[package]]
name = "horizon-prepare"
version = "0.1.0"
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
exclude = ["launcher", "crates/horizon-telemetry-server"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"]
resolver = "2"
[workspace.package]
+7 -3
View File
@@ -120,8 +120,9 @@ impl Input<'_> {
bottom: bottom + 4.0 >= 0.0,
};
let colors = [1.0, 0.7, 0.8, 0.9].map(|shade| {
self.color
.map(|v| ((v * shade).clamp(0.0, 1.0) * 255.0) as u8 as f32 / 255.0)
let [r, g, b, a] = self.color;
[r * shade, g * shade, b * shade, a]
.map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8 as f32 / 255.0)
});
(
key,
@@ -249,8 +250,11 @@ mod tests {
assert_eq!(uniform.offset[1], (192.33 - input.camera.y) as f32);
assert_eq!(
uniform.colors[1],
[0.8, 0.7, 0.6, 0.5].map(|v| ((v * 0.7f32) * 255.0) as u8 as f32 / 255.0)
[0.8 * 0.7, 0.7 * 0.7, 0.6 * 0.7, 0.5].map(|v| (v * 255.0) as u8 as f32 / 255.0)
);
for color in uniform.colors {
assert_eq!(color[3], 127.0 / 255.0);
}
}
for (x, y, z, range, fast) in [
(13.0, 101.0, 1.0, 2, false),
+12 -8
View File
@@ -467,13 +467,16 @@ impl FrameStats {
}
let total: f64 = sorted.iter().map(|&m| f64::from(m)).sum();
let percentile = |p: f64| sorted[((n as f64 * p).ceil() as usize).clamp(1, n) - 1];
// Average frame time of the slowest 1% of frames, as frames per second.
let slowest = n.div_ceil(100);
let slow: f64 = sorted[n - slowest..]
.iter()
.map(|&m| f64::from(m))
.sum::<f64>()
/ slowest as f64;
// Average frame time of the slowest 1% (0.1%) of frames, as frames per second.
let low = |per: usize| {
let slowest = n.div_ceil(per);
let slow: f64 = sorted[n - slowest..]
.iter()
.map(|&m| f64::from(m))
.sum::<f64>()
/ slowest as f64;
1000.0 / slow
};
// Where the slowest 1% of frames by CPU time go.
let slow_phases = {
let mut cpu = self.cpu.clone();
@@ -487,7 +490,8 @@ impl FrameStats {
"frames": n,
"seconds": total / 1000.0,
"avg_fps": n as f64 * 1000.0 / total,
"low_1pct_fps": 1000.0 / slow,
"low_1pct_fps": low(100),
"low_01pct_fps": low(1000),
"p50_ms": percentile(0.5),
"p95_ms": percentile(0.95),
"p99_ms": percentile(0.99),
+27 -12
View File
@@ -14,7 +14,7 @@ use serde_json::Value;
use std::{
collections::{HashMap, HashSet},
fs,
path::Path,
path::{Path, PathBuf},
sync::Arc,
};
@@ -1182,18 +1182,33 @@ impl Recipes {
let mut crafting = Vec::new();
let mut cooking = Vec::new();
let mut meta = HashMap::new();
let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe"))?
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "json"))
let json_files = |dir: &Path| -> Result<Vec<PathBuf>> {
let mut files: Vec<_> = fs::read_dir(dir)?
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "json"))
.collect();
files.sort();
Ok(files)
};
// Vanilla's recipes by bare name, then content mods' as `<ns>:<name>`.
let mut files: Vec<(String, PathBuf)> = json_files(&root.join("data/minecraft/recipe"))?
.into_iter()
.map(|p| (String::new(), p))
.collect();
files.sort();
for path in files {
let name = path
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_owned();
for namespace in crate::mod_content::namespaces(root) {
let dir = root.join(format!("data/{namespace}/recipe"));
if dir.is_dir() {
files.extend(
json_files(&dir)?
.into_iter()
.map(|p| (format!("{namespace}:"), p)),
);
}
}
for (prefix, path) in files {
let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");
let name = format!("{prefix}{stem}");
let v: Value = serde_json::from_slice(&fs::read(&path)?)?;
let text = |k: &str| v[k].as_str().unwrap_or("").to_owned();
meta.insert(name.clone(), (text("category"), text("group")));
+14 -7
View File
@@ -49,17 +49,24 @@ pub struct Names {
}
impl Names {
pub fn load(root: &Path) -> Self {
let map = fs::read(root.join("assets/minecraft/lang/en_us.json"))
.ok()
.and_then(|b| serde_json::from_slice::<HashMap<String, String>>(&b).ok())
.unwrap_or_default();
let read = |namespace: &str| {
fs::read(root.join(format!("assets/{namespace}/lang/en_us.json")))
.ok()
.and_then(|b| serde_json::from_slice::<HashMap<String, String>>(&b).ok())
.unwrap_or_default()
};
let mut map = read("minecraft");
// Content mods' names (docs/modpacks.md); none in a vanilla root.
for namespace in crate::mod_content::namespaces(root) {
map.extend(read(&namespace));
}
Self { map }
}
pub fn item(&self, id: &str) -> String {
let path = id.trim_start_matches("minecraft:");
let (namespace, path) = id.split_once(':').unwrap_or(("minecraft", id));
self.map
.get(&format!("item.minecraft.{path}"))
.or_else(|| self.map.get(&format!("block.minecraft.{path}")))
.get(&format!("item.{namespace}.{path}"))
.or_else(|| self.map.get(&format!("block.{namespace}.{path}")))
.cloned()
.unwrap_or_else(|| path.replace('_', " "))
}
+38 -7
View File
@@ -1046,12 +1046,15 @@ pub fn arrow_from_nbt(
}
/// `FallingBlockEntity`: BlockState, Time, DropItem, HurtEntities.
#[allow(clippy::too_many_arguments)]
pub fn falling_block_to_nbt(
state: Tag,
position: Vec3,
motion: Vec3,
time: i32,
drop_item: bool,
damage: crate::falling_block::Damage,
fall_distance: f64,
uuid: [i32; 4],
) -> Tag {
let base = Base {
@@ -1061,29 +1064,27 @@ pub fn falling_block_to_nbt(
motion,
rotation: [0.0, 0.0],
on_ground: false,
fall_distance: 0.0,
fall_distance,
};
let mut tag = base.tag(None);
for (key, value) in [
("BlockState", state),
("Time", Tag::Int(time)),
("DropItem", Tag::Byte(i8::from(drop_item))),
("HurtEntities", Tag::Byte(0)),
("CancelDrop", Tag::Byte(0)),
("FallHurtAmount", Tag::Float(0)),
("FallHurtMax", Tag::Int(40)),
] {
put(&mut tag, key, value);
}
damage.save(&mut tag);
tag
}
/// (block state tag, position, motion, time)
pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, i32)> {
/// (block state tag, position, motion, time, fall distance)
pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, i32, f64)> {
Some((
tag.get("BlockState")?.clone(),
position(tag)?,
motion(tag),
number(tag.get("Time")).unwrap_or(0) as i32,
float(tag.get("fall_distance")).unwrap_or(0.0),
))
}
@@ -1493,6 +1494,36 @@ mod tests {
use super::*;
use crate::items::ItemStack;
#[test]
fn falling_block_round_trip_keeps_impact_distance_and_settings() {
let state = Tag::compound([("Name", string("minecraft:damaged_anvil"))]);
let position = Vec3::new(3.5, 100.0, -7.5);
let velocity = Vec3::new(0.0, -1.25, 0.0);
let damage = crate::falling_block::Damage {
cancel_drop: true,
..crate::falling_block::Damage::anvil()
};
let tag = falling_block_to_nbt(
state.clone(),
position,
velocity,
30,
false,
damage,
19.75,
[1, 2, 3, 4],
);
let (loaded_state, pos, motion, age, distance) = falling_block_from_nbt(&tag).unwrap();
assert_eq!(loaded_state, state);
assert_eq!(
(pos, motion, age, distance),
(position, velocity, 30, 19.75)
);
assert_eq!(falling_block_flags(&tag), (false, false));
assert_eq!(crate::falling_block::Damage::from_nbt(&tag, true), damage);
assert_eq!(uuid(&tag), Some([1, 2, 3, 4]));
}
#[test]
fn item_entities_round_trip() {
let e = ItemEntity {
+192
View File
@@ -0,0 +1,192 @@
//! FallingBlockEntity's impact damage, anvil wear and saved impact settings.
use crate::{
mobs::{Damage as MobDamage, DamageKind, Mob},
save::{float, number, put},
};
use horizon_core::geometry::{Aabb, Vec3};
use horizon_world::{chunk::BlockState, nbt::Tag};
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Damage {
pub hurt_entities: bool,
pub cancel_drop: bool,
pub per_distance: f32,
pub max: i32,
}
impl Default for Damage {
fn default() -> Self {
Self {
hurt_entities: false,
cancel_drop: false,
per_distance: 0.0,
max: 40,
}
}
}
impl Damage {
pub fn anvil() -> Self {
Self {
hurt_entities: true,
per_distance: 2.0,
..Self::default()
}
}
pub fn from_nbt(tag: &Tag, anvil: bool) -> Self {
Self {
hurt_entities: number(tag.get("HurtEntities")).map_or(anvil, |v| v != 0),
cancel_drop: number(tag.get("CancelDrop")).is_some_and(|v| v != 0),
per_distance: float(tag.get("FallHurtAmount")).unwrap_or(0.0) as f32,
max: number(tag.get("FallHurtMax")).unwrap_or(40) as i32,
}
}
pub fn save(self, tag: &mut Tag) {
for (key, value) in [
("HurtEntities", Tag::Byte(i8::from(self.hurt_entities))),
("CancelDrop", Tag::Byte(i8::from(self.cancel_drop))),
("FallHurtAmount", Tag::Float(self.per_distance.to_bits())),
("FallHurtMax", Tag::Int(self.max)),
] {
put(tag, key, value);
}
}
pub fn impact(self, fall_distance: f64) -> Option<Impact> {
if !self.hurt_entities {
return None;
}
let steps = (fall_distance - 1.0).ceil() as i32;
if steps < 0 {
return None;
}
let amount = ((steps as f32 * self.per_distance).floor() as i32).min(self.max) as f32;
Some(Impact {
amount,
wear_chance: if amount > 0.0 {
0.05 + steps as f32 * 0.05
} else {
0.0
},
})
}
}
#[derive(Clone, Copy, Debug)]
pub struct Impact {
pub amount: f32,
pub wear_chance: f32,
}
/// AnvilBlock.damage: advance wear without changing facing; false means broken.
pub fn wear_anvil(state: &mut BlockState) -> bool {
state.name = match state.name.as_str() {
"minecraft:anvil" => "minecraft:chipped_anvil",
"minecraft:chipped_anvil" => "minecraft:damaged_anvil",
_ => return false,
}
.into();
true
}
pub fn bounds(position: Vec3) -> Aabb {
let size = f64::from(0.98_f32);
Aabb::new(
Vec3::new(position.x - size / 2.0, position.y, position.z - size / 2.0),
Vec3::new(
position.x + size / 2.0,
position.y + size,
position.z + size / 2.0,
),
)
}
pub fn hurt_mobs(mobs: &mut [Mob], position: Vec3, amount: f32) {
if amount <= 0.0 {
return;
}
let bounds = bounds(position);
let source = MobDamage {
kind: DamageKind::FallingBlock,
attacker: None,
from: Some([position.x, position.y, position.z]),
};
for mob in mobs
.iter_mut()
.filter(|m| m.alive() && bounds.intersects(m.bounds()))
{
mob.damage(amount, source);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn impact_uses_ceil_distance_capped_damage_and_positive_damage_wear() {
let damage = Damage::anvil();
assert!(Damage::default().impact(50.0).is_none());
assert!(damage.impact(0.0).is_none());
let short = damage.impact(1.0).unwrap();
assert_eq!((short.amount, short.wear_chance), (0.0, 0.0));
assert_eq!(damage.impact(1.01).unwrap().amount, 2.0);
assert_eq!(damage.impact(5.0).unwrap().amount, 8.0);
assert_eq!(damage.impact(100.0).unwrap().amount, 40.0);
assert!(damage.impact(21.0).unwrap().wear_chance > 1.0);
}
#[test]
fn damage_settings_round_trip_and_keep_vanilla_load_defaults() {
let empty = Tag::Compound(Default::default());
assert_eq!(Damage::from_nbt(&empty, false), Damage::default());
let loaded_anvil = Damage::from_nbt(&empty, true);
assert!(loaded_anvil.hurt_entities);
assert_eq!(loaded_anvil.per_distance, 0.0);
let damage = Damage {
hurt_entities: true,
cancel_drop: true,
per_distance: 3.5,
max: 17,
};
let mut tag = empty;
damage.save(&mut tag);
assert_eq!(Damage::from_nbt(&tag, false), damage);
}
#[test]
fn anvil_wears_twice_then_breaks_preserving_facing() {
for facing in ["north", "south", "east", "west"] {
let mut state = BlockState {
name: "minecraft:anvil".into(),
properties: [("facing".into(), facing.into())].into(),
};
for name in ["minecraft:chipped_anvil", "minecraft:damaged_anvil"] {
assert!(wear_anvil(&mut state));
assert_eq!(state.name, name);
assert_eq!(state.properties["facing"], facing);
}
assert!(!wear_anvil(&mut state));
}
}
#[test]
#[ignore = "requires prepared entity models/data in HORIZON_TEST_RESOURCES"]
fn impact_hurts_only_living_intersecting_noninvulnerable_mobs() {
use crate::mobs::{Mob, MobTypes};
use std::{path::Path, sync::Arc};
let root = std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES");
let types = MobTypes::load(Path::new(&root)).unwrap();
let cow = Arc::new(types.types["minecraft:cow"].clone());
let mut mobs = vec![
Mob::new(1, cow.clone(), Vec3::ZERO, 0.0),
Mob::new(2, cow.clone(), Vec3::new(3.0, 0.0, 0.0), 0.0),
Mob::new(3, cow.clone(), Vec3::ZERO, 0.0),
Mob::new(4, cow, Vec3::ZERO, 0.0),
];
mobs[2].invulnerable_flag = true;
mobs[3].extra.head = Some("minecraft:carved_pumpkin".into());
let initial = mobs.iter().map(|m| m.health).collect::<Vec<_>>();
hurt_mobs(
&mut mobs,
Vec3::ZERO,
Damage::anvil().impact(5.0).unwrap().amount,
);
assert_eq!(mobs[0].health, initial[0] - 8.0);
assert_eq!(mobs[1].health, initial[1]);
assert_eq!(mobs[2].health, initial[2]);
assert_eq!(mobs[3].health, initial[3] - 6.0);
}
}
-16
View File
@@ -119,22 +119,6 @@ impl FogState {
}
}
/// 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]));
File diff suppressed because it is too large Load Diff
@@ -109,7 +109,7 @@ impl adv::World for View<'_, '_> {
let name = self.0.res.facts.get(state).name.to_string();
let props = self
.0
.res
.pack
.assets
.registry
.state(state)
@@ -613,7 +613,7 @@ impl Game<'_> {
}
/// `EnterBlockTrigger`: the block, its state properties and the player.
pub(super) fn trigger_enter_block(&mut self, state: horizon_world::registry::BlockStateId) {
let Some(definition) = self.res.assets.registry.state(state).cloned() else {
let Some(definition) = self.pack.assets.registry.state(state).cloned() else {
return;
};
let me = self.player_entity();
@@ -746,11 +746,11 @@ impl Game<'_> {
if let Some((station, item)) = recipe {
// RecipeToast: black description under a purple title, the
// station at 0.6 scale in the corner over the cycling result.
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0);
let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!");
let description = self.translate("recipe.toast.description", "Check your recipe book");
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false);
batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false);
let start = batch.vertices.len();
@@ -759,7 +759,7 @@ impl Game<'_> {
self.draw_item_model(batch, &item, x + 8.0, 8.0);
return;
}
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0);
let (key, color) = match frame {
Frame::Task => ("advancements.toast.task", 0xFF00_FFFF),
@@ -257,7 +257,7 @@ impl Game<'_> {
}
/// `AdvancementWidget`'s title lines, description lines and width.
fn adv_widget_text(&self, i: usize) -> (Vec<Text>, Vec<Text>, f32) {
let font = &self.res.atlas.font;
let font = &self.atlas.font;
let a = &self.adv.tree.list[i];
let Some(d) = &a.display else {
return (Vec::new(), Vec::new(), 0.0);
@@ -320,7 +320,7 @@ impl Game<'_> {
let (sx, sy) = self.adv_ui.scroll.unwrap_or_default();
let (sx, sy) = (sx.floor() as i32, sy.floor() as i32);
self.adv_tick_hover(&view, sx, sy, left, top);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
let title = Text::translate("gui.advancements", &[]);
let tw = atlas.font.width_text(&title);
@@ -432,7 +432,7 @@ impl Game<'_> {
}
let (x, y) = pos(i);
let (x, y) = ((ox + x) as f32, (oy + y) as f32);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.sprite_scaled(
atlas,
frame_sprite(d.frame, done),
@@ -449,7 +449,7 @@ impl Game<'_> {
}
}
// The window, tabs and title.
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.sprite_region(
atlas,
"gui/advancements/window",
@@ -463,7 +463,7 @@ impl Game<'_> {
let (x, y) = tab_pos(ty, i);
let sprite = tab_sprite(ty, i, ty.3, Some(t) == tab);
batch.sprite_scaled(
&self.res.atlas,
&self.atlas,
&sprite,
left + x,
top + y,
@@ -482,7 +482,7 @@ impl Game<'_> {
}
}
}
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let title = tab.and_then(|t| tree.list[t].display.as_ref()).map_or_else(
|| Text::translate("gui.advancements", &[]),
|d| text_of(&d.title),
@@ -497,7 +497,7 @@ impl Game<'_> {
}
}
// Done.
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (bx, by) = ((w / 2.0 - 100.0).floor(), h - FOOTER + 6.0);
let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0);
ui::button(
@@ -520,7 +520,7 @@ impl Game<'_> {
let (cx, cy) = self.cursor;
if cx > x && cx < x + ty.1 && cy > y && cy < y + ty.2 {
if let Some(d) = &tree.list[t].display {
ui::tooltip(batch, &self.res.atlas, &[text_of(&d.title)], self.cursor);
ui::tooltip(batch, &self.atlas, &[text_of(&d.title)], self.cursor);
}
break;
}
@@ -604,7 +604,7 @@ impl Game<'_> {
],
)
});
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let progress_w = progress.as_ref().map_or(0.0, |t| atlas.font.width_text(t)) as i32;
let top_side = title_bottom + desc_h >= INSIDE_H;
let amount = if a.criteria.is_empty() || total == 0 {
+1 -1
View File
@@ -301,7 +301,7 @@ pub(super) enum Handled {
impl Game<'_> {
pub(super) fn state_string(&self, state: BlockStateId) -> String {
let Some(s) = self.res.assets.registry.state(state) else {
let Some(s) = self.pack.assets.registry.state(state) else {
return "?".into();
};
if s.properties.is_empty() {
@@ -124,7 +124,7 @@ impl Game<'_> {
continue;
};
let (Some(r), Some(part)) = (
self.res.atlas.sprites.get(texture.as_str()),
self.atlas.sprites.get(texture.as_str()),
assets.player.get(layer),
) else {
continue;
@@ -379,7 +379,7 @@ impl Game<'_> {
let mut dead = Vec::new();
for (i, a) in self.armor_stands.iter_mut().enumerate() {
a.tick(&mut scene);
if !a.environment_tick(&self.world, &self.res.facts, self.res.assets.registry) {
if !a.environment_tick(&self.world, &self.res.facts, self.pack.assets.registry) {
dead.push(i);
}
}
@@ -403,7 +403,7 @@ impl Game<'_> {
out: &mut Vec<Vertex>,
) {
let assets = &self.armor_stand_assets;
let sprites = &self.res.atlas.sprites;
let sprites = &self.atlas.sprites;
let uv_of = |name: &str| sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let Some(wood) = uv_of("entity/armorstand/armorstand") else {
return;
@@ -668,12 +668,12 @@ impl Game<'_> {
self.dim == super::Dim::Nether,
)),
};
self.res.item_renderer.submit_special(
self.pack.item_renderer.submit_special(
&special,
&serde_json::Value::Null,
false,
pose,
&self.res.atlas.sprites,
&self.atlas.sprites,
&self.item_host(),
&mut sink,
);
+4 -4
View File
@@ -150,11 +150,11 @@ impl Game<'_> {
.join("backdrop");
std::fs::create_dir_all(&root)?;
let save = Arc::new(SaveDir::new(root.join(format!("{seed}"))));
let res = &*self.res;
let (res, pack) = (&*self.res, &self.pack);
let inner = Arc::new(
VanillaTerrain::new(
&self.options.resources.join("worldgen"),
res.assets.registry,
pack.assets.registry,
&res.biomes,
seed,
)
@@ -164,10 +164,10 @@ impl Game<'_> {
Arc::new(Persistent {
inner: inner.clone(),
save: save.clone(),
registry: res.assets.clone(),
registry: pack.assets.clone(),
biomes: res.biomes.clone(),
}),
res.context.clone(),
pack.context.clone(),
res.threads.min(6),
);
streaming.radius = self.settings.render_distance.clamp(4, 10);
+5 -11
View File
@@ -385,7 +385,7 @@ impl Game<'_> {
let levels = self.beacon_levels();
let sel = self.station.as_ref().map_or([None; 2], |s| s.beacon);
let paid = self.station.as_ref().is_some_and(|s| s.inputs[0].is_some());
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.fill(
atlas,
0.0,
@@ -406,7 +406,7 @@ impl Game<'_> {
("block.minecraft.beacon.secondary", "Secondary Power", 169.0),
] {
let text = self.translate(key, fallback);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let w = HudBatch::text_width(atlas, &text);
batch.text(
atlas,
@@ -421,7 +421,7 @@ impl Game<'_> {
let x = [20.0, 41.0, 63.0, 86.0, 108.0][i];
self.draw_item(batch, &ItemStack::new(item, 1), bx + x, by + 109.0);
}
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let mut tooltip = None;
let button =
|batch: &mut HudBatch, x: f32, y: f32, active: bool, selected: bool, icon: &str| {
@@ -503,7 +503,7 @@ impl Game<'_> {
if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) {
let (sx, sy) = self.slot_position(slot);
batch.fill(
&self.res.atlas,
&self.atlas,
ox + sx,
oy + sy,
16.0,
@@ -524,13 +524,7 @@ impl Game<'_> {
}
/// `BeaconRenderer`: each section's rotating solid beam and its glow.
pub(super) fn beacon_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let Some(s) = self
.res
.atlas
.sprites
.get("entity/beacon/beacon_beam")
.copied()
else {
let Some(s) = self.atlas.sprites.get("entity/beacon/beacon_beam").copied() else {
return;
};
let time = (self.world.game_time.rem_euclid(40)) as f32 + alpha as f32;
+2 -2
View File
@@ -63,7 +63,7 @@ impl HiveHost for GameHive<'_, '_> {
impl Game<'_> {
fn hive_with_honey(&self, state: BlockStateId, level: i32) -> Option<BlockStateId> {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let mut s = registry.state(state)?.clone();
s.properties
.insert("honey_level".to_owned(), level.to_string());
@@ -82,7 +82,7 @@ impl Game<'_> {
{
return None;
}
let props = &self.res.assets.registry.state(state)?.properties;
let props = &self.pack.assets.registry.state(state)?.properties;
let honey = props.get("honey_level").and_then(|v| v.parse().ok());
let facing = beehive::facing_step(props.get("facing").map(String::as_str));
Some((honey, facing))
@@ -280,7 +280,7 @@ impl Game<'_> {
Ticker::Conduit => {
let world = &self.world;
let facts = &self.res.facts;
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let is_water = |p: [i32; 3]| {
facts.get(world.block(p[0], p[1], p[2])).fluid
== horizon_client::blocks::Fluid::Water
@@ -46,7 +46,7 @@ impl Game<'_> {
// BeehiveBlock.getCloneItemStack: the honey level as the item's block state.
if include_data
&& let Some(level) = self
.res
.pack
.assets
.registry
.state(state)
+3 -3
View File
@@ -33,7 +33,7 @@ fn parse_state(text: &str) -> Result<BlockState> {
impl Game<'_> {
fn state_text(&self, state: BlockStateId) -> String {
let Some(s) = self.res.assets.registry.state(state) else {
let Some(s) = self.pack.assets.registry.state(state) else {
return "?".into();
};
if s.properties.is_empty() {
@@ -69,7 +69,7 @@ impl Game<'_> {
"setblock" => {
let pos = [int(1)?, int(2)?, int(3)?];
let state = self
.res
.pack
.assets
.registry
.resolve(&parse_state(words.get(4).ok_or("missing block")?)?)?;
@@ -81,7 +81,7 @@ impl Game<'_> {
"fill" => {
let (a, b) = ([int(1)?, int(2)?, int(3)?], [int(4)?, int(5)?, int(6)?]);
let state = self
.res
.pack
.assets
.registry
.resolve(&parse_state(words.get(7).ok_or("missing block")?)?)?;
-1
View File
@@ -712,7 +712,6 @@ impl Game<'_> {
};
let folder = if b.chest { "chest_boat" } else { "boat" };
let Some(uv) = self
.res
.atlas
.sprites
.get(&format!("entity/{folder}/{}", b.wood))
+4 -4
View File
@@ -45,7 +45,7 @@ pub(super) enum BookScreen {
}
impl Game<'_> {
fn book_lines(&self, page: &str) -> Vec<Text> {
self.res.atlas.font.split(&Text::literal(page), 114.0)
self.atlas.font.split(&Text::literal(page), 114.0)
}
/// `WritableBookItem.use` / `WrittenBookItem.use`.
pub(super) fn use_book(&mut self, stack: &ItemStack) -> bool {
@@ -242,7 +242,7 @@ impl Game<'_> {
/// the page (`MultilineTextField.insertText`: line breaks kept, cut to
/// the 1024 characters left, rejected when it overflows the 14 lines).
fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) {
let font = &self.res.atlas.font;
let font = &self.atlas.font;
match self.book.as_mut() {
Some(BookScreen::Edit {
signing: true,
@@ -363,7 +363,7 @@ impl Game<'_> {
}
fn set_lectern_property(&mut self, key: (i32, i32, i32), name: &str, value: bool) {
let state = self.world.block(key.0, key.1, key.2);
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let Some(mut s) = registry.state(state).cloned() else {
return;
};
@@ -549,7 +549,7 @@ impl Game<'_> {
}
pub(super) fn draw_book(&self, batch: &mut HudBatch) {
let Some(book) = &self.book else { return };
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
let (mx, my) = self.cursor;
let hover =
@@ -89,17 +89,17 @@ impl Game<'_> {
if is_locked {
locked = true;
if scaling || locking {
batch.sprite(&self.res.atlas, error, ox + 35.0, oy + 31.0);
batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0);
}
}
if scaling && scale >= 4 {
locked = true;
batch.sprite(&self.res.atlas, error, ox + 35.0, oy + 31.0);
batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0);
}
}
let sprite = |batch: &mut HudBatch, game: &Self, name: &str, x: f32, y: f32| {
batch.sprite(
&game.res.atlas,
&game.atlas,
&format!("gui/sprites/container/cartography_table/{name}"),
ox + x,
oy + y,
+14 -16
View File
@@ -226,7 +226,7 @@ impl Game<'_> {
.map(|k| horizon_client::command::args::normalize(k))
.collect();
reg.block_tags.sort();
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let mut blocks: BTreeMap<String, BTreeMap<String, Vec<String>>> = BTreeMap::new();
for id in 0..registry.len() {
let Some(state) = registry.state(horizon_world::registry::BlockStateId(id as u32))
@@ -389,7 +389,7 @@ impl Game<'_> {
.as_ref()
.map_or([1280, 720], |r| [r.config.width, r.config.height]);
let b = HudBatch::new(size);
let m = Measure(&self.res.atlas.font);
let m = Measure(&self.atlas.font);
let c = Commands {
dispatcher: self.mods.dispatcher(),
registries: &self.ui.registries,
@@ -428,7 +428,7 @@ impl Game<'_> {
let focused = self.screen == Screen::Chat;
let heard = self.mods.mods.is_running().then(|| text.plain());
self.ui.chat.add(
&self.res.atlas,
&self.atlas,
text,
Some(SYSTEM_INDICATOR),
self.ticks,
@@ -441,7 +441,7 @@ impl Game<'_> {
/// Keys while the chat screen is open.
pub(super) fn chat_key(&mut self, event: &KeyEvent) {
if let Some(shortcut) = self.edit_shortcut(event) {
let m = Measure(&self.res.atlas.font);
let m = Measure(&self.atlas.font);
let c = Commands {
dispatcher: self.mods.dispatcher(),
registries: &self.ui.registries,
@@ -487,7 +487,7 @@ impl Game<'_> {
let Some(mut screen) = self.ui.chat_screen.take() else {
return;
};
let m = Measure(&self.res.atlas.font);
let m = Measure(&self.atlas.font);
let c = Commands {
dispatcher: self.mods.dispatcher(),
registries: &self.ui.registries,
@@ -513,7 +513,7 @@ impl Game<'_> {
}
/// Text typed into the chat box (control socket `chat`).
pub(super) fn chat_type(&mut self, text: &str) {
let m = Measure(&self.res.atlas.font);
let m = Measure(&self.atlas.font);
let c = Commands {
dispatcher: self.mods.dispatcher(),
registries: &self.ui.registries,
@@ -536,7 +536,7 @@ impl Game<'_> {
let heard = self.mods.mods.is_running().then(|| line.plain());
self.ui
.chat
.add(&self.res.atlas, line, None, self.ticks, focused);
.add(&self.atlas, line, None, self.ticks, focused);
if let Some(line) = heard {
self.mods_chat(&line);
}
@@ -564,7 +564,7 @@ impl Game<'_> {
let height = self.renderer.as_ref().map_or(720.0, |r| {
HudBatch::new([r.config.width, r.config.height]).height
});
let m = Measure(&self.res.atlas.font);
let m = Measure(&self.atlas.font);
let c = Commands {
dispatcher: self.mods.dispatcher(),
registries: &self.ui.registries,
@@ -577,7 +577,7 @@ impl Game<'_> {
return;
}
match self.ui.chat.click_at(
&self.res.atlas.font,
&self.atlas.font,
height as i32,
cursor.0 as f64,
cursor.1 as f64,
@@ -603,15 +603,13 @@ impl Game<'_> {
if self.ui.hide_gui && !focused {
return;
}
self.ui
.chat
.draw(batch, &self.res.atlas, self.ticks, focused);
self.ui.chat.draw(batch, &self.atlas, self.ticks, focused);
}
pub(super) fn draw_chat_screen(&mut self, batch: &mut HudBatch) {
let Some(mut screen) = self.ui.chat_screen.take() else {
return;
};
let m = Measure(&self.res.atlas.font);
let m = Measure(&self.atlas.font);
let c = Commands {
dispatcher: self.mods.dispatcher(),
registries: &self.ui.registries,
@@ -629,7 +627,7 @@ impl Game<'_> {
.chat_opened
.map_or(0, |t| t.elapsed().as_millis() as u64);
let draws = screen.draw(&m, mouse, blink, background);
horizon_client::screen_draw::paint(batch, &self.res.atlas, &draws);
horizon_client::screen_draw::paint(batch, &self.atlas, &draws);
self.ui.chat_screen = Some(screen);
}
/// Advance the overworld clock (ServerClockManager.tick) when
@@ -821,11 +819,11 @@ impl Game<'_> {
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.res.atlas, message, None, self.ticks, focused);
.add(&self.atlas, message, None, self.ticks, focused);
}
#[allow(dead_code)]
fn chat_debug_fill(&self, batch: &mut HudBatch) {
batch.fill(&self.res.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0));
batch.fill(&self.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0));
}
}
/// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time
@@ -193,7 +193,7 @@ impl Game<'_> {
}
}
fn block_state_at(&self, pos: Pos) -> Option<&'static BlockState> {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
state_of(registry, self.world.block(pos.0, pos.1, pos.2))
}
fn schedule_command_block(&mut self, pos: Pos) {
@@ -202,7 +202,7 @@ impl Game<'_> {
}
/// `CommandBlockEntity.scheduleTick`.
fn schedule_command_block_tick(&mut self, pos: Pos) {
mark_condition_met(&mut self.world, self.res.assets.registry, pos);
mark_condition_met(&mut self.world, self.pack.assets.registry, pos);
self.schedule_command_block(pos);
}
fn update_output_signal(&mut self, pos: Pos) {
@@ -225,7 +225,7 @@ impl Game<'_> {
}
let at = BlockPos::new(pos.0, pos.1, pos.2);
let signal = self.with_level(|b, level, ticks| b.has_neighbor_signal(level, ticks, at));
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
if let Some((was, auto)) = set_powered(&mut self.world, registry, pos, signal)
&& signal
&& !was
@@ -249,7 +249,7 @@ impl Game<'_> {
return;
};
if mode == Mode::Auto {
mark_condition_met(&mut self.world, self.res.assets.registry, key);
mark_condition_met(&mut self.world, self.pack.assets.registry, key);
}
match command_block::tick_action(mode, was_met, conditional(state)) {
Some(true) => self.command_block_execute(key, state),
@@ -283,7 +283,7 @@ impl Game<'_> {
/// `CommandBlock.executeChain`: the chain command blocks in front, each
/// facing on to the next, up to `max_command_sequence_length`.
fn execute_chain(&mut self, start: Pos, mut step: [i32; 3]) {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let limit = self.ui.rules.int("max_command_sequence_length");
let mut remaining = limit;
let mut pos = start;
@@ -458,7 +458,7 @@ impl Game<'_> {
self.close_command_block();
return;
}
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
let mid = (w / 2.0).floor();
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
@@ -578,7 +578,7 @@ impl Game<'_> {
return;
}
let pos = s.pos;
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let Some(current) = self.block_state_at(pos) else {
return;
};
+8 -8
View File
@@ -340,7 +340,7 @@ impl Game<'_> {
.find(|i| i.id == id)
.map(|i| i.stack.item.to_string())
.unwrap_or_default();
Text::literal(self.res.names.item(&item))
Text::literal(self.pack.names.item(&item))
}
Target::Mob(id)
if self
@@ -783,7 +783,7 @@ impl Game<'_> {
_ => text::WHITE,
};
Text::literal("[")
.append(Text::literal(self.res.names.item(item)))
.append(Text::literal(self.pack.names.item(item)))
.append("]")
.with_color(color)
}
@@ -816,7 +816,7 @@ impl Game<'_> {
&[],
)
} else {
Text::literal(self.res.names.item(item))
Text::literal(self.pack.names.item(item))
};
let wrapped = Text::translate("chat.square_brackets", &[hover]);
if empty {
@@ -1456,7 +1456,7 @@ impl Game<'_> {
name: b.id.clone(),
properties: b.properties.iter().cloned().collect(),
};
self.res
self.pack
.assets
.registry
.resolve(&state)
@@ -1464,7 +1464,7 @@ impl Game<'_> {
}
/// BlockPredicateArgument test.
fn block_matches(&self, b: &BlockInput, state: BlockStateId) -> bool {
let Some(s) = self.res.assets.registry.state(state) else {
let Some(s) = self.pack.assets.registry.state(state) else {
return false;
};
let name_ok = if b.tag {
@@ -1739,7 +1739,7 @@ impl Game<'_> {
let strict = ctx.has("strict");
// CloneCommands.clone sets every destination to a barrier first, so
// each copied state but a barrier counts as placed.
let barrier = self.res.assets.registry.default_state("minecraft:barrier");
let barrier = self.pack.assets.registry.default_state("minecraft:barrier");
let mut count = 0;
for (_, to, s, entity) in copies {
self.place_state(to, s, strict)?;
@@ -2266,7 +2266,7 @@ impl Game<'_> {
}
/// `PoiTypes`: the point of interest type of a block state.
fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> {
let s = self.res.assets.registry.state(state)?;
let s = self.pack.assets.registry.state(state)?;
let name = s.name.strip_prefix("minecraft:")?;
Some(match name {
"blast_furnace" => "minecraft:armorer",
@@ -2542,7 +2542,7 @@ impl Game<'_> {
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.res.atlas, line, None, self.ticks, focused);
.add(&self.atlas, line, None, self.ticks, focused);
Ok(1)
}
/// MessageArgument: `@p`-style selectors in a message become names.
@@ -494,7 +494,7 @@ impl Game<'_> {
return false;
};
let state = self.world.block(p[0], p[1], p[2]);
let Some(s) = self.res.assets.registry.state(state) else {
let Some(s) = self.pack.assets.registry.state(state) else {
return false;
};
let name = s.name.to_string();
@@ -180,7 +180,7 @@ impl Game<'_> {
}
pub(in crate::game) fn data_block_name(&self, p: [i32; 3]) -> String {
let state = self.world.block(p[0], p[1], p[2]);
self.res
self.pack
.assets
.registry
.state(state)
@@ -227,7 +227,7 @@ impl Game<'_> {
return Err(err(
"commands.enchant.failed.incompatible",
&[&stack.custom_name().map_or_else(
|| self.res.names.item(&stack.item).to_string(),
|| self.pack.names.item(&stack.item).to_string(),
str::to_owned,
)],
));
@@ -247,7 +247,7 @@ impl Game<'_> {
),
Some(item) => err(
"commands.enchant.failed.incompatible",
&[&self.res.names.item(&item)],
&[&self.pack.names.item(&item)],
),
});
}
@@ -652,7 +652,7 @@ impl Game<'_> {
let facts = self.res.facts.get(state);
let blocks = facts.legacy_solid || facts.fluid != horizon_client::blocks::Fluid::None;
let leaves = self
.res
.pack
.assets
.registry
.state(state)
@@ -25,7 +25,7 @@ impl Game<'_> {
.join("worldgen/blocks/structure-blocks.json"),
)
.ok()?;
StateTransforms::from_json(&json, self.res.assets.registry.len()).ok()
StateTransforms::from_json(&json, self.pack.assets.registry.len()).ok()
})
.as_ref()
}
@@ -64,7 +64,7 @@ impl Game<'_> {
};
return Some(Arc::new(StructureTemplate::from_nbt(
&named.tag,
self.res.assets.registry,
self.pack.assets.registry,
transforms,
)));
}
@@ -551,14 +551,14 @@ impl Game<'_> {
Some(seq) => {
let random = self.rand_sequences.get(&seq, self.level.seed);
self.res.items.block_drops(
self.res.assets.registry,
self.pack.assets.registry,
state,
tool.as_ref(),
random,
)
}
None => self.res.items.block_drops(
self.res.assets.registry,
self.pack.assets.registry,
state,
tool.as_ref(),
&mut self.world.random,
+1 -1
View File
@@ -13,7 +13,7 @@ impl Game<'_> {
/// The composter's `level` at `pos`, None when it isn't a composter.
pub(super) fn composter_level(&self, pos: [i32; 3]) -> Option<i32> {
let state = self.world.block(pos[0], pos[1], pos[2]);
let s = self.res.assets.registry.state(state)?;
let s = self.pack.assets.registry.state(state)?;
if &*s.name != "minecraft:composter" {
return None;
}
+1 -1
View File
@@ -427,7 +427,7 @@ impl Game<'_> {
match self.screen {
Screen::Chat => self.chat_type(text),
Screen::CommandBlock => self.command_block_type(text),
Screen::Options => self.ui.options.type_text(&self.res.atlas, text),
Screen::Options => self.ui.options.type_text(&self.atlas, text),
// The port, or the game rules' search and number boxes.
Screen::WorldOptions if text == "\\b" => self.world_options_text(None),
Screen::WorldOptions => self.world_options_text(Some(text)),
@@ -168,7 +168,7 @@ impl Game<'_> {
]
.into(),
};
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let Some(id) = registry.id(&state) else {
return;
};
+4 -4
View File
@@ -84,7 +84,7 @@ impl HeartHost for Host<'_> {
impl Game<'_> {
fn heart_state_name(&self, state: BlockStateId) -> String {
self.res
self.pack
.assets
.registry
.state(state)
@@ -177,7 +177,7 @@ impl Game<'_> {
}
/// `Creaking.tearDown`: the crumble particles.
pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let crumble = |this: &mut Self, name: &str, props: &[(&str, &str)], count: i32| {
let Some(mut state) = registry
.default_state(name)
@@ -229,7 +229,7 @@ impl Game<'_> {
});
let state = self.world.block(key.0, key.1, key.2);
let natural = self
.res
.pack
.assets
.registry
.state(state)
@@ -297,7 +297,7 @@ impl Game<'_> {
/// entity (`newBlockEntity`) the first time their chunk is seen.
fn scan_for_hearts(&mut self) {
let Some(heart) = self
.res
.pack
.assets
.registry
.default_state("minecraft:creaking_heart")
+7 -6
View File
@@ -378,7 +378,7 @@ impl Game<'_> {
let (rain, thunder) = self.world.weather.levels(1.0);
MobWorld {
world: &self.world,
registry: self.res.assets.registry,
registry: self.pack.assets.registry,
facts: &self.res.facts,
movement: &self.motion.blocks,
collision: self.collision,
@@ -995,7 +995,7 @@ impl Game<'_> {
0.8,
);
}
if let Some(state) = self.res.assets.registry.default_state(name) {
if let Some(state) = self.pack.assets.registry.default_state(name) {
self.world.set(pos[0], pos[1], pos[2], state)?;
}
}
@@ -1004,7 +1004,7 @@ impl Game<'_> {
self.destroy_particles(pos, old);
if drop {
let drops = self.res.items.block_drops_in(
self.res.assets.registry,
self.pack.assets.registry,
old,
None,
&mut self.world.random,
@@ -1752,7 +1752,7 @@ impl Game<'_> {
) -> horizon_client::arrows::ArrowScene<'s, 's> {
horizon_client::arrows::ArrowScene {
world: &self.world,
registry: self.res.assets.registry,
registry: self.pack.assets.registry,
facts: &self.res.facts,
collision: self.collision,
fluids: &self.motion.fluids,
@@ -2008,7 +2008,7 @@ impl Game<'_> {
.facts
.is_air(self.world.block(fire[0], fire[1], fire[2]))
&& let Some(state) =
self.res.assets.registry.default_state("minecraft:fire")
self.pack.assets.registry.default_state("minecraft:fire")
{
self.world.set(fire[0], fire[1], fire[2], state)?;
}
@@ -2767,7 +2767,7 @@ impl Game<'_> {
}
/// Mob models and projectiles for the entity pass.
pub(super) fn mob_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let scale = f64::from(self.settings.entity_distance);
for mob in &self.mobs {
@@ -2985,6 +2985,7 @@ fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static
K::Explosion if player => "minecraft:player_explosion",
K::Explosion => "minecraft:explosion",
K::Fall => "minecraft:fall",
K::FallingBlock => "minecraft:falling_block",
K::OnFire => "minecraft:on_fire",
K::InFire => "minecraft:in_fire",
K::Lava => "minecraft:lava",
+1 -1
View File
@@ -423,7 +423,7 @@ impl Game<'_> {
));
}
let (left, right) = d.columns(&self.debug_chart_lines());
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let mut draws = debug_overlay::draw(&atlas.font, [&left, &right], scale, width);
let charts = self.debug_charts.draw(
&atlas.font,
+3 -2
View File
@@ -418,6 +418,7 @@ impl Game<'_> {
enforces_secure_chat: false,
accepts_transfers: props.accepts_transfers,
announce: false,
listen: true,
bypasses_limit: Some(Arc::new(move |uuid| {
bypass_lists
.lock()
@@ -525,7 +526,7 @@ impl Game<'_> {
/// Load the spawn area and find the world spawn as single player does,
/// without keeping a player there.
fn settle_spawn(&mut self) -> Result<()> {
pub(super) fn settle_spawn(&mut self) -> Result<()> {
let deadline = Instant::now() + Duration::from_secs(600);
while self.player.is_none() {
self.update_world();
@@ -541,7 +542,7 @@ impl Game<'_> {
/// The chunks to keep loaded: the players' (lan_update_streaming), or
/// the spawn chunk while nobody is online.
fn update_dedicated_streaming(&mut self) {
pub(super) fn update_dedicated_streaming(&mut self) {
let center = self
.lan
.as_ref()
@@ -224,7 +224,7 @@ impl Game<'_> {
for p in crafter_positions {
let state = self.world.block(p.0, p.1, p.2);
let triggered = self
.res
.pack
.assets
.registry
.state(state)
+9 -9
View File
@@ -308,7 +308,7 @@ pub(super) fn mob_set_slot(m: &mut Mob, slot: Slot, stack: ItemStack) {
impl Game<'_> {
fn prop(&self, state: BlockStateId, key: &str) -> Option<String> {
self.res
self.pack
.assets
.registry
.state(state)?
@@ -318,11 +318,11 @@ impl Game<'_> {
}
/// The same block with other properties (`withProperty`).
fn with_props(&self, state: BlockStateId, props: &[(&str, &str)]) -> Option<BlockStateId> {
let mut s = self.res.assets.registry.state(state)?.clone();
let mut s = self.pack.assets.registry.state(state)?.clone();
for (k, v) in props {
s.properties.insert((*k).to_owned(), (*v).to_owned());
}
self.res.assets.registry.resolve(&s).ok()
self.pack.assets.registry.resolve(&s).ok()
}
fn block_at(&self, p: Pos) -> BlockStateId {
self.world.block(p.0, p.1, p.2)
@@ -1407,7 +1407,7 @@ impl Game<'_> {
}
};
let skull = self
.res
.pack
.assets
.registry
.default_state("minecraft:wither_skeleton_skull")
@@ -1470,7 +1470,7 @@ impl Game<'_> {
&& self.can_spawn_golem([target.0, target.1, target.2])
{
if let Some(pumpkin) = self
.res
.pack
.assets
.registry
.default_state("minecraft:carved_pumpkin")
@@ -2046,10 +2046,10 @@ impl Game<'_> {
return None;
}
let twin = format!("minecraft:waxed_{n}");
let mut s = self.res.assets.registry.state(state)?.clone();
self.res.assets.registry.default_state(&twin)?;
let mut s = self.pack.assets.registry.state(state)?.clone();
self.pack.assets.registry.default_state(&twin)?;
s.name = twin;
self.res.assets.registry.resolve(&s).ok()
self.pack.assets.registry.resolve(&s).ok()
});
let Some(waxed) =
waxed.filter(|_| name.contains("copper") || name.contains("lightning_rod"))
@@ -2108,7 +2108,7 @@ impl Game<'_> {
1.0,
);
self.post_block_game_event("minecraft:fluid_place", [pos.0, pos.1, pos.2], None, None);
if let Some(mud) = self.res.assets.registry.default_state("minecraft:mud") {
if let Some(mud) = self.pack.assets.registry.default_state("minecraft:mud") {
self.level_set([target.0, target.1, target.2], mud)?;
}
let bottle = ItemStack::new("minecraft:glass_bottle", 1);
+8 -16
View File
@@ -582,7 +582,7 @@ impl Game<'_> {
}
/// `EndCrystal.tick`: the time and the fire below it in the End.
fn tick_crystals(&mut self) {
let fire = self.res.assets.registry.default_state("minecraft:fire");
let fire = self.pack.assets.registry.default_state("minecraft:fire");
for i in 0..self.crystals.len() {
self.crystals[i].time += 1;
let p = self.crystals[i].position;
@@ -1702,7 +1702,7 @@ impl Game<'_> {
}
if !self.fight.previously_killed
&& let Some(egg) = self
.res
.pack
.assets
.registry
.default_state("minecraft:dragon_egg")
@@ -1866,9 +1866,9 @@ impl Game<'_> {
batch.width as i32,
batch.height as i32,
&bars,
&self.res.atlas.font,
&self.atlas.font,
);
hud_layout::paint(batch, &self.res.atlas, &draws);
hud_layout::paint(batch, &self.atlas, &draws);
}
/// The dragon fight's boss bar shows (`EnderDragonFight.dragonEvent`,
/// with `setCreateWorldFog`).
@@ -1906,13 +1906,7 @@ impl Game<'_> {
return;
};
let a = alpha as f32;
let sprite = |n: &str| {
self.res
.atlas
.sprites
.get(n)
.map(|r| [r.u0, r.v0, r.u1, r.v1])
};
let sprite = |n: &str| self.atlas.sprites.get(n).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let (Some(skin), Some(eyes)) = (
sprite("entity/enderdragon/dragon"),
sprite("entity/enderdragon/dragon_eyes"),
@@ -2078,7 +2072,7 @@ impl Game<'_> {
}
/// `submitRays`: the death rays from a fixed seed, fading in white to magenta.
fn dragon_rays(&self, base: glam::Mat4, t: f32, out: &mut Vec<Vertex>) {
let white = self.res.atlas.font.white();
let white = self.atlas.font.white();
let uv = [white.u0, white.v0];
let over = if t > 0.8 {
((t - 0.8) / 0.2).min(1.0)
@@ -2134,7 +2128,6 @@ impl Game<'_> {
out: &mut Vec<Vertex>,
) {
let Some(s) = self
.res
.atlas
.sprites
.get("entity/end_crystal/end_crystal_beam")
@@ -2196,7 +2189,6 @@ impl Game<'_> {
out: &mut Vec<Vertex>,
) {
let Some(s) = self
.res
.atlas
.sprites
.get("entity/enderdragon/dragon_fireball")
@@ -2610,7 +2602,7 @@ impl Game<'_> {
/// and grown again with a guarded crystal.
fn rebuild_spike(&mut self, spike: &horizon_world::worldgen::end_spike::EndSpike) {
let (cx, cz, h) = (spike.center_x, spike.center_z, spike.height);
let air = self.res.assets.registry.default_state("minecraft:air");
let air = self.pack.assets.registry.default_state("minecraft:air");
let Some(air) = air else {
return;
};
@@ -2685,7 +2677,7 @@ impl Game<'_> {
}
/// Iron bars connected north, south, west and east.
fn set_bars(&mut self, pos: [i32; 3], sides: [bool; 4]) {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let Some(mut state) = registry
.default_state("minecraft:iron_bars")
.and_then(|d| registry.state(d).cloned())
+6 -8
View File
@@ -142,7 +142,7 @@ impl Game<'_> {
/// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads.
pub(super) fn end_sky_geometry(&self) -> Vec<Vertex> {
let mut out = Vec::with_capacity(6 * 256 * 4);
let Some(r) = self.res.atlas.sprites.get("environment/end_sky").copied() else {
let Some(r) = self.atlas.sprites.get("environment/end_sky").copied() else {
return out;
};
use std::f32::consts::FRAC_PI_2;
@@ -184,7 +184,6 @@ impl Game<'_> {
let intensity = self.end.flash.intensity(self.clock.fraction() as f32);
if intensity > 1e-5
&& let Some(r) = self
.res
.atlas
.sprites
.get("environment/celestial/end_flash")
@@ -237,7 +236,7 @@ impl Game<'_> {
if &*stack.item != "minecraft:ender_eye" {
return Ok(false);
}
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let target = self.pick().and_then(|hit| {
let state = registry.state(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]))?;
(state.name == "minecraft:end_portal_frame").then(|| (hit, state.clone()))
@@ -303,7 +302,7 @@ impl Game<'_> {
/// ring (corners free) of filled frames, all facing the centre or all
/// facing away from it. Returns the centre of the 3×3 opening.
fn portal_ring_center(&self, frame: [i32; 3]) -> Option<[i32; 3]> {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
// (offset from the centre, facing when the frames face the centre)
let mut ring = Vec::with_capacity(12);
for i in -1..=1 {
@@ -630,7 +629,7 @@ impl Game<'_> {
&[],
)?;
}
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
for (facing, d) in [
("north", [0, -1]),
("south", [0, 1]),
@@ -898,8 +897,7 @@ impl Game<'_> {
fn end_crystal_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let (Some(model), Some(r)) = (
self.crystal_model.as_ref(),
self.res
.atlas
self.atlas
.sprites
.get("entity/end_crystal/end_crystal")
.copied(),
@@ -1052,7 +1050,7 @@ impl Game<'_> {
/// ThrownItemRenderer: the ender eye item facing the camera.
fn eye_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let Some(r) = self.res.atlas.sprites.get("item/ender_eye").copied() else {
let Some(r) = self.atlas.sprites.get("item/ender_eye").copied() else {
return;
};
let alpha = self.clock.fraction();
+1 -1
View File
@@ -511,7 +511,7 @@ impl Game<'_> {
// random sequence.
let decay = (interaction == BlockInteraction::DestroyWithDecay).then_some(radius);
let drops = self.res.items.block_drops_exploded(
self.res.assets.registry,
self.pack.assets.registry,
state,
None,
&dynamic,
+4 -4
View File
@@ -193,10 +193,10 @@ impl Game<'_> {
if !self.extras.minimap.compose(view) {
return;
}
let Some(rect) = self.res.atlas.sprites.get(MINIMAP_SPRITE).copied() else {
let Some(rect) = self.atlas.sprites.get(MINIMAP_SPRITE).copied() else {
return;
};
let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32);
let (w, h) = (self.atlas.width as f32, self.atlas.height as f32);
self.map_patches.push(horizon_client::font::Patch {
x: (rect.u0 * w).round() as u32,
y: (rect.v0 * h).round() as u32,
@@ -242,7 +242,7 @@ impl Game<'_> {
let (map_corner, map_size) = (e.minimap_corner, f32::from(e.minimap_size));
let visible = |corner| !(self.debug && corner == Corner::TopLeft);
let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height());
let atlas = &self.res.atlas;
let atlas = &self.atlas;
if let Some(view) = self.minimap_view()
&& visible(map_corner)
&& !self.extras.minimap.image.is_empty()
@@ -286,7 +286,7 @@ impl Game<'_> {
use_: self.extras.mouse[1],
cps,
};
extras_hud::draw_keystrokes(batch, &self.res.atlas, &mut corners, keys_corner, &k);
extras_hud::draw_keystrokes(batch, &self.atlas, &mut corners, keys_corner, &k);
}
if mod_panels {
self.draw_mod_panels(batch, &mut corners);
@@ -0,0 +1,123 @@
//! Landing impacts for falling blocks, before their placement/drop decision.
use super::{FallingBlock, Game, Landing};
use horizon_client::{falling_block, items::ItemStack};
use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource};
use horizon_world::level::LevelEvent;
impl Game<'_> {
pub(super) fn finish_falling_block(&mut self, mut block: FallingBlock, pos: [i32; 3]) {
let anvil = self.res.facts.get(block.state).name.ends_with("anvil");
if let Some(impact) = block.damage.impact(block.fall_distance) {
if impact.amount > 0.0 {
falling_block::hurt_mobs(&mut self.mobs, block.position, impact.amount);
let kind = if anvil {
"minecraft:falling_anvil"
} else {
"minecraft:falling_block"
};
self.falling_hurt_player(block.position, impact.amount, kind);
if let Some(mut host) = self.lan.take() {
let bounds = falling_block::bounds(block.position);
let conns = host
.hub
.guests
.iter()
.filter(|g| {
g.placed
&& g.loaded
&& !g.dead
&& !g.creative()
&& !g.spectator()
&& bounds.intersects(super::lan_mobs::guest_bounds(g))
})
.map(|g| g.conn)
.collect::<Vec<_>>();
for conn in conns {
self.guest_hit_by(&mut host, conn, |g| {
g.falling_hurt_player(block.position, impact.amount, kind)
});
}
self.lan = Some(host);
}
}
if anvil
&& impact.wear_chance > 0.0
&& self.world.random.next_float() < impact.wear_chance
&& let Some(mut state) = self.res.assets.registry.state(block.state).cloned()
{
if falling_block::wear_anvil(&mut state) {
block.state = self
.res
.assets
.registry
.resolve(&state)
.unwrap_or(block.state);
} else {
block.damage.cancel_drop = true;
}
}
}
if block.damage.cancel_drop {
if anvil {
self.level_events.push(LevelEvent::LevelEvent {
id: 1029,
pos: BlockPos::new(pos[0], pos[1], pos[2]),
data: 0,
});
}
return;
}
let landing = self.with_level(|b, level, ticks| {
b.falling_block_landed(
level,
ticks,
BlockPos::new(pos[0], pos[1], pos[2]),
block.state,
false,
)
});
if matches!(landing, Landing::Broken)
&& block.drop_item
&& self.ui.rules.bool("entity_drops")
{
let item = self.res.facts.get(block.state).item.clone();
if &*item != "minecraft:air" {
self.pop_resource(
pos,
ItemStack {
item,
count: 1,
damage: 0,
extra: None,
},
);
}
}
}
fn falling_hurt_player(&mut self, position: Vec3, amount: f32, kind: &str) {
if self.creative || self.spectator() {
return;
}
if self.player.as_ref().is_none_or(|p| {
p.health.dead_or_dying() || !falling_block::bounds(position).intersects(p.bounds())
}) {
return;
}
let amount = if self.armor[0].is_some() {
amount * 0.75
} else {
amount
};
let hurt = if let Some(p) = self.player.as_mut()
&& let Some(id) = self.motion.health.damage.id(kind)
{
p.hurt(&self.motion.health, self.world.health_rules, id, amount)
.unwrap_or(false)
} else {
false
};
if hurt {
self.hurt_armor(amount);
}
}
}
-1
View File
@@ -108,7 +108,6 @@ impl Game<'_> {
return;
};
let Some(r) = self
.res
.atlas
.sprites
.get("entity/illager/evoker_fangs")
@@ -565,7 +565,6 @@ impl Game<'_> {
return;
};
let Some(r) = self
.res
.atlas
.sprites
.get("entity/fishing/fishing_hook")
+1 -1
View File
@@ -171,6 +171,6 @@ impl Game<'_> {
}
let draws =
hud_overlays::spyglass(batch.width as i32, batch.height as i32, self.scope_scale);
hud_layout::paint(batch, &self.res.atlas, &draws);
hud_layout::paint(batch, &self.atlas, &draws);
}
}
+1 -1
View File
@@ -301,7 +301,7 @@ impl Game<'_> {
}
/// ItemFrameRenderer: the frame model, then the item half size on its face.
pub(super) fn frame_geometry(&mut self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let sprites = &self.res.atlas.sprites;
let sprites = &self.atlas.sprites;
let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new();
let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new();
for f in &self.item_frames {
@@ -39,7 +39,7 @@ impl Game<'_> {
};
switcher.hover(w, h, (self.cursor.0 as i32, self.cursor.1 as i32));
let selected = switcher.selected;
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.sprite_region(
atlas,
"gui/container/gamemode_switcher",
@@ -62,14 +62,14 @@ impl Game<'_> {
for (index, mode) in MODES.into_iter().enumerate() {
let (x, y) = slot_origin(w, h, index);
batch.sprite(
&self.res.atlas,
&self.atlas,
"gui/sprites/gamemode_switcher/slot",
x as f32,
y as f32,
);
if mode == selected {
batch.sprite(
&self.res.atlas,
&self.atlas,
"gui/sprites/gamemode_switcher/selection",
x as f32,
y as f32,
+1 -1
View File
@@ -110,7 +110,7 @@ impl Game<'_> {
f64::from(pos[2]) + 0.5,
];
let facing = self
.res
.pack
.assets
.registry
.state(state)
+1 -1
View File
@@ -146,7 +146,7 @@ impl Game<'_> {
let below = [head[0], head[1] - 1, head[2]];
let copper = self.world.block(below[0], below[1], below[2]);
let pumpkin = self.world.block(head[0], head[1], head[2]);
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let facing = registry
.state(pumpkin)
.and_then(|s| s.properties.get("facing").cloned())
+1 -1
View File
@@ -15,7 +15,7 @@ impl Game<'_> {
}
let dir = self.options.resources.join("worldgen");
let started = std::time::Instant::now();
let features = vanillagen::shared_data(&dir, self.res.assets.registry)
let features = vanillagen::shared_data(&dir, self.pack.assets.registry)
.map_err(|e| e.to_string())
.and_then(|data| LiveFeatures::new(&data).map_err(|e| e.to_string()));
match features {
+1 -1
View File
@@ -257,7 +257,7 @@ impl Game<'_> {
.or_else(|| self.held());
if let Some(stack) = active {
let components = self
.res
.pack
.item_renderer
.models
.components(&horizon_client::item_render::stack_view(stack));
@@ -72,7 +72,7 @@ impl Game<'_> {
fn spawn_columns(&self) -> Columns<'_, '_> {
Columns {
world: &self.world,
properties: &self.res.assets.properties,
properties: &self.pack.assets.properties,
binding: self.collision,
}
}
@@ -82,7 +82,7 @@ impl Game<'_> {
horizon_client::save::world_gen_settings(&self.world_root).and_then(|s| {
horizon_client::flatgen::FlatTerrain::from_settings(
&s,
self.res.assets.registry,
self.pack.assets.registry,
&self.res.biomes,
)
})
@@ -0,0 +1,289 @@
//! The integrated server (`IntegratedServer`): single player's world runs on
//! its own "Server thread", as vanilla's does, and the window joins it as a
//! player through memory, so a world tick never holds up a frame.
//!
//! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the
//! player joins as a network player, and the server side of a network player
//! does not do everything single player does yet. Worlds whose player is
//! outside the Overworld open the usual way, since network players stay in
//! the Overworld so far.
use super::{
Dim, Game, Options, PackResources, Resources,
lan::{LanSettings, Owner},
};
use horizon_client::{
Result,
audio::Audio,
hud::HudAtlas,
lan::{MAX_PLAYERS, NetConfig, hub::HubConfig},
save::Level,
settings::Settings,
title::WorldOptions,
};
use horizon_protocol::connection::Pipe;
use horizon_protocol::{crypto::offline_uuid, text::translatable};
use std::{
path::Path,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc::{Sender, channel},
},
thread::JoinHandle,
time::{Duration, Instant},
};
/// What the window tells its server thread.
#[derive(Default)]
struct Flags {
/// `Minecraft.pause`: a single-player pause screen is open.
paused: AtomicBool,
stop: AtomicBool,
}
/// The window's handle on its server thread.
pub(super) struct Integrated {
flags: Arc<Flags>,
thread: Option<JoinHandle<()>>,
}
impl Integrated {
/// `IntegratedServer.tickServer` skips the world while the game is paused.
pub fn set_paused(&self, paused: bool) {
self.flags.paused.store(paused, Ordering::Relaxed);
}
/// `IntegratedServer.halt(true)`: returns once the world is saved and let go.
pub fn stop(mut self) {
self.halt();
}
fn halt(&mut self) {
self.flags.stop.store(true, Ordering::Relaxed);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
impl Drop for Integrated {
fn drop(&mut self) {
self.halt();
}
}
/// The world to open and the player who owns it.
struct Launch {
folder: String,
name: Option<String>,
seed: Option<i64>,
creative: bool,
create: Option<WorldOptions>,
/// The window's profile: the only one let in, and the world's player.
owner: u128,
}
/// Whether this world opens on a server thread: asked for, and its player
/// (if any yet) in the Overworld.
pub(super) fn wanted(options: &Options, world: &Path) -> bool {
options.server_thread
&& options.dedicated.is_none()
&& Level::read(world).is_none_or(|l| Dim::from_id(&l.dimension) == Dim::Overworld)
}
impl Game<'_> {
/// `Minecraft.doWorldLoad`: start the server thread on the world, wait
/// until it can be joined, then join it through memory.
pub(super) fn open_integrated(
&mut self,
folder: &str,
name: Option<&str>,
seed: Option<i64>,
creative: bool,
create: Option<&WorldOptions>,
) -> Result<()> {
let auth = horizon_client::auth::current();
let player = auth
.as_ref()
.map_or_else(|| self.options.player_name(), |a| a.name.clone());
let launch = Launch {
folder: folder.to_owned(),
name: name.map(str::to_owned),
seed,
creative,
create: create.cloned(),
// An offline-mode server names its players by their offline profile.
owner: offline_uuid(&player),
};
let mut options = self.options.clone();
// A server without a console: no local player, no window, no control socket.
options.dedicated = Some(Vec::new());
options.server_thread = false;
options.integrated = true;
options.control = None;
options.benchmark = None;
options.frames = None;
options.world_frames = None;
options.report = None;
options.server = None;
options.world = None;
options.dev_mods.clear();
let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone());
let flags = Arc::new(Flags::default());
let (ready_tx, ready) = channel();
let server_flags = flags.clone();
let thread = std::thread::Builder::new()
.name("Server thread".into())
.spawn(move || {
let result = serve(
&res,
pack,
options,
settings,
launch,
&server_flags,
&ready_tx,
);
if let Err(e) = result {
log::error!("Horizon: integrated server: {e}");
let _ = ready_tx.send(Err(e.to_string()));
}
})?;
let handle = Integrated {
flags,
thread: Some(thread),
};
let pipe = match ready.recv() {
Ok(Ok(pipe)) => pipe,
Ok(Err(e)) => return Err(e.into()),
Err(_) => return Err("the integrated server stopped".into()),
};
self.connect_local(pipe, &player)?;
self.integrated = Some(handle);
Ok(())
}
/// The server thread's loop (`MinecraftServer.runServer`): 20 ticks a
/// second, the world held while the window is paused.
fn run_integrated(
&mut self,
launch: Launch,
flags: &Flags,
ready: &Sender<std::result::Result<Pipe, String>>,
) -> Result<()> {
self.open_world(
&launch.folder,
launch.name.as_deref(),
launch.seed,
launch.creative,
launch.create.as_ref(),
)?;
let saved = Box::new(self.level.clone());
let view_distance = self.settings.render_distance.clamp(2, 32);
let config = HubConfig {
default_game_mode: self.level.mode(),
guest_commands: true,
force_game_mode: false,
hardcore: self.level.hardcore,
view_distance,
simulation_distance: self.settings.simulation_distance.clamp(2, 32),
dimension: self.dim.id().to_owned(),
seed: self.level.seed,
max_players: MAX_PLAYERS,
// No player of its own: the hub runs without a host.
dedicated: true,
};
let owner = launch.owner;
let net = NetConfig {
// No network until it is opened to the LAN.
listen: false,
// A memory connection is not compressed (`Connection.isMemoryConnection`).
compression_threshold: -1,
enable_status: false,
announce: false,
gate: Some(Arc::new(move |_, uuid, _| {
(uuid != owner).then(|| translatable("multiplayer.disconnect.not_whitelisted", &[]))
})),
..NetConfig::lan(0, self.level.name.clone(), MAX_PLAYERS)
};
let settings = LanSettings {
port: 0,
guest_commands: true,
force_game_mode: false,
};
self.lan_host(settings, net, config, None)?;
let commands = self.allow_commands();
let pipe = {
let host = self
.lan
.as_mut()
.ok_or("the integrated server did not start")?;
// The owner is an operator when the world allows commands
// (`IntegratedPlayerList`, `MinecraftServer.getProfilePermissions`).
host.hub.ops.insert(owner, if commands { 4 } else { 0 });
host.owner = Some(Owner {
uuid: owner,
saved: Some(saved),
});
host.hub.lan.connect_local()?
};
let _ = ready.send(Ok(pipe));
self.settle_spawn()?;
let mut next = Instant::now();
while !flags.stop.load(Ordering::Relaxed) {
self.update_dedicated_streaming();
self.update_world();
if flags.paused.load(Ordering::Relaxed) {
// Only the connections run.
self.tick_lan();
} else {
self.tick()?;
}
let rate = self.clock.rate().max(1.0);
next += Duration::from_secs_f64(1.0 / f64::from(rate));
let now = Instant::now();
if next > now {
std::thread::sleep(next - now);
} else if now - next > Duration::from_secs(2) {
next = now;
}
}
self.stop_integrated()
}
/// `MinecraftServer.stopServer`: the players are saved and sent away,
/// then the world is saved.
fn stop_integrated(&mut self) -> Result<()> {
if let Some(mut host) = self.lan.take() {
for g in &host.hub.guests {
self.save_guest(&host, g);
}
let conns: Vec<u32> = host.hub.guests.iter().map(|g| g.conn).collect();
for conn in conns {
host.hub.kick(
conn,
translatable("multiplayer.disconnect.server_shutdown", &[]),
);
}
self.lan = Some(host);
}
std::thread::sleep(Duration::from_millis(100));
self.save_game()?;
self.lan_close(false);
self.save.flush();
self.session_lock = None;
Ok(())
}
}
/// The server thread: a game of its own over the shared resources.
fn serve(
res: &Arc<Resources>,
pack: PackResources,
options: Options,
settings: Settings,
launch: Launch,
flags: &Flags,
ready: &Sender<std::result::Result<Pipe, String>>,
) -> Result<()> {
let atlas = HudAtlas::build(&options.resources)?;
let audio = Audio::silent(&options.resources);
let mut server = Game::new(res, pack, atlas, options, settings, audio)?;
server.run_integrated(launch, flags, ready)
}
+11 -11
View File
@@ -31,7 +31,7 @@ impl ItemEnv for Env<'_, '_> {
}
fn grass_color(&self, temperature: f64, downfall: f64) -> i32 {
self.game
.res
.pack
.item_renderer
.grass_color(temperature, downfall)
}
@@ -43,7 +43,7 @@ impl ItemEnv for Env<'_, '_> {
else {
return 0.0;
};
let prototypes = &self.game.res.item_renderer.models.prototypes;
let prototypes = &self.game.pack.item_renderer.models.prototypes;
let mut total = 0.0f64;
for item in items {
let id = item["id"].as_str().unwrap_or("");
@@ -216,7 +216,7 @@ impl Game<'_> {
&& self.inventory.get(slot).and_then(Option::as_ref) == Some(stack)
{
let view = item_render::stack_view(stack);
let duration = use_duration(&self.res.item_renderer.models.components(&view));
let duration = use_duration(&self.pack.item_renderer.models.components(&view));
owner.using_this_item = true;
owner.use_duration = duration;
owner.use_item_remaining_ticks = duration - ticks as i32;
@@ -239,7 +239,7 @@ impl Game<'_> {
seed: i32,
) -> ItemRenderState {
let level = self.item_level();
self.res.item_renderer.resolve(
self.pack.item_renderer.resolve(
&item_render::stack_view(stack),
display,
owner,
@@ -254,8 +254,8 @@ impl Game<'_> {
let state = self.resolve_item(stack, DisplayContext::Gui, Some(&owner), 0);
item_render::gui::draw(
&state,
&self.res.item_renderer,
&self.res.atlas.sprites,
&self.pack.item_renderer,
&self.atlas.sprites,
&self.item_host(),
batch,
x,
@@ -278,8 +278,8 @@ impl Game<'_> {
lights: Some(diffuse_lights(self.dim == Dim::Nether)),
};
state.submit(
&self.res.item_renderer,
&self.res.atlas.sprites,
&self.pack.item_renderer,
&self.atlas.sprites,
&self.item_host(),
pose,
&mut sink,
@@ -299,8 +299,8 @@ impl Game<'_> {
lights: None,
};
state.submit(
&self.res.item_renderer,
&self.res.atlas.sprites,
&self.pack.item_renderer,
&self.atlas.sprites,
&self.item_host(),
pose,
&mut sink,
@@ -360,7 +360,7 @@ impl Game<'_> {
(q.y + 0.1).floor() as i32,
q.z.floor() as i32,
);
let seed = i64::from(self.res.item_renderer.item_id(&item.stack.item))
let seed = i64::from(self.pack.item_renderer.item_id(&item.stack.item))
+ i64::from(item.stack.damage);
for copy in item_render::cluster_poses(
&state,
+1 -1
View File
@@ -21,7 +21,7 @@ impl Game<'_> {
}
fn set_has_record(&mut self, pos: [i32; 3], has: bool) {
let state = self.world.block(pos[0], pos[1], pos[2]);
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let Some(mut s) = registry.state(state).cloned() else {
return;
};
+51 -5
View File
@@ -55,6 +55,17 @@ pub(super) struct LanHost {
mob_state: HashMap<u32, (i32, bool)>,
/// The guest each mob sees as its player, when not the host (game/lan_mobs.rs).
pub mob_players: HashMap<u32, u32>,
/// An integrated server's owner (game/integrated.rs).
pub owner: Option<Owner>,
}
/// The player who owns an integrated server's world: a guest whose state is
/// the world's own player (`players/data/<singleplayer_uuid>.dat`), as in
/// single player.
pub(super) struct Owner {
pub uuid: u128,
/// The world's player as loaded, until the owner joins.
pub saved: Option<Box<horizon_client::save::Level>>,
}
/// A stable UUID for an entity that has none.
@@ -440,7 +451,7 @@ impl Game<'_> {
encoder.tables = Some(
self.save
.tables
.get_or_init(|| Arc::new(horizon_client::save::SaveTables::new(&self.res.assets)))
.get_or_init(|| Arc::new(horizon_client::save::SaveTables::new(&self.pack.assets)))
.clone(),
);
let lan = Lan::start_with(sync.clone(), net)?;
@@ -465,6 +476,7 @@ impl Game<'_> {
broken: Vec::new(),
mob_state: HashMap::new(),
mob_players: HashMap::new(),
owner: None,
});
self.audio.capture = Some(Vec::new());
Ok(())
@@ -477,7 +489,7 @@ impl Game<'_> {
return;
};
for g in &host.hub.guests {
playerdata::save(g, &self.world_root);
self.save_guest(&host, g);
}
host.hub.disconnect_all();
// Give the writer threads a moment to flush the disconnect packets.
@@ -494,6 +506,30 @@ impl Game<'_> {
}
}
/// Save a guest when they leave or the world closes: an integrated
/// server's owner with the world (`save_game`), anyone else in their file.
pub(super) fn save_guest(&mut self, host: &LanHost, guest: &horizon_client::lan::guest::Guest) {
if host.owner.as_ref().is_some_and(|o| o.uuid == guest.uuid) {
if guest.placed {
playerdata::store(guest, &mut self.level);
}
} else {
playerdata::save(guest, &self.world_root);
}
}
/// The integrated server's owner into the world's player, for `Level::write`.
pub(super) fn store_owner(&mut self) {
let Some(host) = &self.lan else {
return;
};
let Some(uuid) = host.owner.as_ref().map(|o| o.uuid) else {
return;
};
if let Some(g) = host.hub.guests.iter().find(|g| g.uuid == uuid && g.placed) {
playerdata::store(g, &mut self.level);
}
}
/// The world's default game mode (`defaultgamemode`).
pub(super) fn set_default_game_mode(&mut self, mode: i32) {
self.level.game_mode = mode;
@@ -664,7 +700,7 @@ impl Game<'_> {
self.container_openers_changed(pos, false);
}
self.lan_crafting_left(&mut host, &mut guest);
playerdata::save(&guest, &self.world_root);
self.save_guest(&host, &guest);
host.models.remove(&guest.conn);
if self.options.dedicated.is_some() && guest.placed {
super::dedicated::log(
@@ -707,10 +743,20 @@ impl Game<'_> {
let default_mode = host.hub.config.default_game_mode;
let force = host.hub.config.force_game_mode;
let root = self.world_root.clone();
let owner = host.owner.as_mut();
let Some(g) = host.hub.guest_mut(conn) else {
return;
};
let known = playerdata::load(g, &root);
let saved = owner
.filter(|o| o.uuid == g.uuid)
.and_then(|o| o.saved.take());
let known = match saved {
Some(level) => {
playerdata::apply(g, &level);
level.position.is_some()
}
None => playerdata::load(g, &root),
};
if !known || force {
g.game_mode = default_mode;
}
@@ -886,7 +932,7 @@ impl Game<'_> {
let Some(host) = &self.lan else {
return;
};
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
for m in host.models.values() {
let entity_start = out.len();
@@ -859,7 +859,7 @@ impl Game<'_> {
entities: &[],
player,
scene: &mut game.world,
assets: &game.res.assets,
assets: &game.pack.assets,
collision_binding: game.collision,
resources: game.motion,
};
+7 -8
View File
@@ -502,7 +502,7 @@ impl Game<'_> {
View::Restrictions => self.draw_restrictions(batch),
View::GameRules => {
if let Some(rules) = o.rules.as_mut() {
rules.draw(batch, &self.res.atlas, self.cursor);
rules.draw(batch, &self.atlas, self.cursor);
}
}
}
@@ -510,7 +510,7 @@ impl Game<'_> {
}
fn draw_lock_question(&self, o: &WorldOptions, batch: &mut HudBatch) {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
// Screen.extractTransparentBackground.
batch.fill_gradient(
@@ -552,7 +552,7 @@ impl Game<'_> {
}
fn draw_restrictions(&self, batch: &mut HudBatch) {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
let title = Text::translate("restrictions_screen.title", &[]);
@@ -583,7 +583,7 @@ impl Game<'_> {
}
fn draw_options_view(&self, o: &mut WorldOptions, batch: &mut HudBatch, cursor: (f32, f32)) {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
o.scroll = o.scroll.clamp(0.0, WorldOptions::max_scroll(h));
// extractMenuBackground: the in-world background, the list
@@ -701,7 +701,7 @@ impl Game<'_> {
match o.view {
View::Options => {}
View::GameRules => {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let exit = o.rules.as_mut().and_then(|rules| {
if rules.clicks_button(atlas, self.cursor, (w, h)) {
self.audio.play_button_click();
@@ -715,7 +715,7 @@ impl Game<'_> {
return;
}
View::LockQuestion => {
let p = Popup::lock_question(&self.res.atlas.font, o.difficulty, (w, h));
let p = Popup::lock_question(&self.atlas.font, o.difficulty, (w, h));
let hit = p
.buttons
.iter()
@@ -733,8 +733,7 @@ impl Game<'_> {
return;
}
View::Restrictions => {
let r =
Restrictions::new(&self.res.atlas.font, self.settings.chat_visibility, (w, h));
let r = Restrictions::new(&self.atlas.font, self.settings.chat_visibility, (w, h));
let in_body = self.cursor.1 >= r.area.0 && self.cursor.1 < r.area.1;
let action = r.action.is_some_and(|(ax, ay)| {
in_body && ui::hovered(self.cursor, ax, ay, 200.0, 20.0)
+1 -1
View File
@@ -283,7 +283,7 @@ impl Game<'_> {
}
/// `LeashFeatureRenderer` for every lead and `LeashKnotRenderer` for the knots.
pub(super) fn leash_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let white = atlas.font.white();
let uv = [
[white.u0, white.v1],
+3 -3
View File
@@ -174,7 +174,7 @@ impl Game<'_> {
if below.sturdy_full >> 1 & 1 == 0 {
continue;
}
if let Some(fire) = self.res.assets.registry.default_state(name) {
if let Some(fire) = self.pack.assets.registry.default_state(name) {
let _ = self.level_set(p, fire);
}
}
@@ -239,7 +239,7 @@ impl Game<'_> {
if !self.res.facts.get(state).name.ends_with("lightning_rod") {
return;
}
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
if let Some(mut s) = registry.state(state).cloned() {
s.properties.insert("powered".into(), "true".into());
if let Some(powered) = registry.id(&s) {
@@ -348,7 +348,7 @@ impl Game<'_> {
/// `LightningBoltRenderer`: 4 layers of a trunk and two branches, 8
/// segments of 16 blocks, from the bolt's seed.
pub(super) fn bolt_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let white = self.res.atlas.font.white();
let white = self.atlas.font.white();
let uv = [white.u0, white.v0];
// ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA.
let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114;
+3 -3
View File
@@ -198,8 +198,8 @@ impl Game<'_> {
.map(|l| (banners.banner_texture(&l.pattern), l.color.to_string()))
.collect();
horizon_client::item_render::gui::draw_banner_result(
&self.res.item_renderer,
&self.res.atlas.sprites,
&self.pack.item_renderer,
&self.atlas.sprites,
batch,
x,
y,
@@ -217,7 +217,7 @@ impl Game<'_> {
draws: &[ScreenDraw],
background: bool,
) -> Option<Vec<(String, u32)>> {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let mut tooltip = None;
let mut sheet: Option<String> = None;
for d in draws {
+3 -3
View File
@@ -363,7 +363,7 @@ impl Game<'_> {
world: &self.world,
behaviours: &self.res.behaviours,
items: &self.res.items,
registry: self.res.assets.registry,
registry: self.pack.assets.registry,
brewing: Some(&self.res.stations.brewing),
bone_meal: bone_meal(),
}
@@ -500,7 +500,7 @@ impl Game<'_> {
/// Every hopper's `pushItemsTick`, in a stable position order.
pub(super) fn tick_hoppers(&mut self) -> Result<()> {
let hopper = self
.res
.pack
.assets
.registry
.default_state("minecraft:hopper")
@@ -833,7 +833,7 @@ impl Game<'_> {
let Some(screen) = self.machine_screen() else {
return false;
};
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let key_is_cart = self
.container
.is_some_and(|k| k.1 == super::minecarts::CART_KEY_Y);
@@ -33,7 +33,7 @@ fn recipe_matches(condition: &Value, id: &str) -> bool {
impl Game<'_> {
/// `Level.setBlock` of one boolean property of the block at `pos`.
fn set_bool_prop(&mut self, pos: Pos, key: &str, value: bool, flags: i32) {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let old = self.world.block(pos.0, pos.1, pos.2);
let Some(mut state) = registry.state(old).cloned() else {
return;
@@ -254,7 +254,7 @@ impl Game<'_> {
// The background goes first, then the labels, then the slot decorations.
let (background, rest) = draws.split_at(2.min(draws.len()));
self.paint_screen(batch, ox, oy, background, true);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let grey = rgba(64, 64, 64, 255);
let title = self.container_title(self.translate("container.crafter", "Crafter"));
let tw = HudBatch::text_width(atlas, &title);
+3 -4
View File
@@ -789,7 +789,6 @@ impl Game<'_> {
}
let slot = self.maps.slots.last()?.1;
let rect = self
.res
.atlas
.sprites
.get(&format!("horizon/map{slot}"))
@@ -798,7 +797,7 @@ impl Game<'_> {
if m.texture_dirty {
m.texture_dirty = false;
let rgba: Vec<u8> = m.colors.iter().flat_map(|&c| packed_rgba(c)).collect();
let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32);
let (w, h) = (self.atlas.width as f32, self.atlas.height as f32);
self.map_patches.push(horizon_client::font::Patch {
x: (rect.u0 * w).round() as u32,
y: (rect.v0 * h).round() as u32,
@@ -856,7 +855,7 @@ impl Game<'_> {
.map(|m| m.decorations.clone())
.unwrap_or_default();
for (i, d) in decorations.iter().enumerate() {
let Some(s) = self.res.atlas.sprites.get(d.sprite).copied() else {
let Some(s) = self.atlas.sprites.get(d.sprite).copied() else {
continue;
};
let dm = glam::Mat4::from_translation(glam::Vec3::new(
@@ -932,7 +931,7 @@ impl Game<'_> {
} else {
"map/map_background"
};
if let Some(r) = self.res.atlas.sprites.get(background).copied() {
if let Some(r) = self.atlas.sprites.get(background).copied() {
for (c, uv) in [
([-7.0, 135.0, 0.0], [r.u0, r.v1]),
([135.0, 135.0, 0.0], [r.u1, r.v1]),
+7 -8
View File
@@ -221,7 +221,7 @@ impl Game<'_> {
) {
return None;
}
let s = self.res.assets.registry.state(state)?;
let s = self.pack.assets.registry.state(state)?;
let shape = Shape::parse(s.properties.get("shape").map_or("", String::as_str));
let powered = s.properties.get("powered").is_some_and(|v| v == "true");
Some(Rail {
@@ -1148,16 +1148,16 @@ impl Game<'_> {
light: u32,
out: &mut Vec<Vertex>,
) {
let Ok(models) = self.res.assets.model_catalog.collect(state, seed_pos) else {
let Ok(models) = self.pack.assets.model_catalog.collect(state, seed_pos) else {
return;
};
for (_, model) in &models {
for face in &model.faces {
let Some(s) = self
.res
.pack
.layer_names
.get(&face.layer)
.and_then(|n| self.res.atlas.sprites.get(n))
.and_then(|n| self.atlas.sprites.get(n))
else {
continue;
};
@@ -1185,7 +1185,7 @@ impl Game<'_> {
}
}
fn display_state(&self, c: &Minecart) -> Option<BlockStateId> {
let registry = &self.res.assets.registry;
let registry = &self.pack.assets.registry;
let with = |name: &str, props: &[(&str, &str)]| {
let mut s = registry.state(registry.default_state(name)?)?.clone();
for (k, v) in props {
@@ -1218,7 +1218,6 @@ impl Game<'_> {
continue;
};
let Some(uv) = self
.res
.atlas
.sprites
.get("entity/minecart/minecart")
@@ -1325,12 +1324,12 @@ impl Game<'_> {
game_time: self.world.game_time,
max_y: self.dim.max_y(),
world: &self.world,
sprites: &self.res.atlas.sprites,
sprites: &self.atlas.sprites,
nether: self.dim == super::Dim::Nether,
lid: &lid,
sign: &|_| None,
banner: &|_| Vec::new(),
glyph: &|c| self.res.atlas.glyph_cell(c),
glyph: &|c| self.atlas.glyph_cell(c),
};
self.res
.block_entity_render
+3 -3
View File
@@ -78,7 +78,7 @@ impl Game<'_> {
let Some(kind) = self.res.mob_types.get("minecraft:elder_guardian") else {
return;
};
let Some(r) = self.res.atlas.sprites.get("entity/guardian_elder").copied() else {
let Some(r) = self.atlas.sprites.get("entity/guardian_elder").copied() else {
return;
};
let age = (APPARITION_TICKS - left) as f32 + alpha as f32;
@@ -147,7 +147,7 @@ impl Game<'_> {
return;
};
let m = banner_matrix(head);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let uv = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
// BannerRenderer: the flag sways with a per-banner phase.
let phase =
@@ -187,7 +187,7 @@ impl Game<'_> {
) {
for (corners, shade, side) in FACES {
let name = cube.sprites[usize::from(side)];
let Some(r) = self.res.atlas.sprites.get(name).copied() else {
let Some(r) = self.atlas.sprites.get(name).copied() else {
continue;
};
let tint = if side == 0 { cube.tint } else { 0xFF_FFFF };
+56 -2
View File
@@ -47,6 +47,60 @@ fn vanilla_command(name: &str) -> bool {
.any(|&c| d.nodes[c].name() == name)
}
/// `root` with the content mods that are on layered over it
/// (docs/modpacks.md): their blocks, items, data and assets. Read once at
/// start, before the resources load; a mod whose content is refused is left
/// out here and its row on the Mods page says why.
pub(super) fn content_root(
root: &std::path::Path,
enabled: &std::collections::BTreeSet<String>,
dev: &[std::path::PathBuf],
) -> std::path::PathBuf {
use horizon_client::mod_content::{self, ContentMod};
use horizon_mods::{Capability, Content, Package};
let here = std::env::current_dir().unwrap_or_default();
let mut paths = horizon_mods::find(&here.join(mod_list::DIR));
paths.retain(|p| !dev.contains(p));
paths.extend(dev.iter().cloned());
let mut mods: Vec<ContentMod> = Vec::new();
for path in &paths {
let Ok(package) = Package::read(path) else {
continue;
};
let m = &package.manifest;
let on = enabled.contains(&m.id) || dev.contains(path);
if !on
|| !m.capabilities.contains(&Capability::Registries)
|| mods.iter().any(|c| c.id == m.id)
{
continue;
}
match Content::read(path, m) {
Ok(content) => mods.push(ContentMod {
id: m.id.clone(),
content,
}),
Err(e) => log::warn!("Horizon: mod {} content not loaded: {e}", m.id),
}
}
match mod_content::resource_root(root, &mods, &here.join(".horizon-cache")) {
Ok(out) => {
if out != root {
log::info!(
"Horizon: content from {} mod(s) in {}",
mods.len(),
out.display()
);
}
out
}
Err(e) => {
log::warn!("Horizon: content mods not loaded: {e}");
root.to_owned()
}
}
}
impl Game<'_> {
/// Reads `horizon-mods/` and the dev mods, and starts the ones turned on.
pub(super) fn start_mods(&mut self) {
@@ -230,7 +284,7 @@ impl Game<'_> {
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.res.atlas, line, None, self.ticks, focused);
.add(&self.atlas, line, None, self.ticks, focused);
}
}
/// The mods' HUD panels, stacked with the extras in their corners.
@@ -251,7 +305,7 @@ impl Game<'_> {
.iter()
.map(|l| (l.text.as_str(), l.color))
.collect();
extras_hud::draw_lines(batch, &self.res.atlas, corners, corner, &lines);
extras_hud::draw_lines(batch, &self.atlas, corners, corner, &lines);
}
}
}
+2 -2
View File
@@ -283,7 +283,7 @@ impl Game<'_> {
let Some(open) = self.mount_menu.open.as_ref() else {
return;
};
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.sprite_region(
atlas,
"gui/container/horse",
@@ -376,7 +376,7 @@ impl Game<'_> {
m.hurt_time = 0;
m.death_time = 0;
let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let mut verts = Vec::new();
horizon_client::mobs::render::render_with(
+1 -1
View File
@@ -457,7 +457,7 @@ impl Game<'_> {
return (0, false);
};
let m = &self.mobs[i];
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let hearts = horizon_client::hud_layout::vehicle_max_hearts(m.attrs.max_health);
let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health);
horizon_client::hud_layout::paint(batch, atlas, &draws);
+1 -1
View File
@@ -122,7 +122,7 @@ impl Game<'_> {
f64::from(p.dimensions.width / 2.0),
f64::from(p.dimensions.height),
);
let registry = &self.res.assets.registry;
let registry = &self.pack.assets.registry;
let facts = &self.res.facts;
let bubble_column = horizon_client::ambience::bubble_column_in(
[
+3 -3
View File
@@ -218,7 +218,7 @@ impl Game<'_> {
let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch));
let right = forward.cross(glam::DVec3::Y).normalize_or_zero();
let up = right.cross(forward).normalize_or_zero();
let white = self.res.atlas.font.white();
let white = self.atlas.font.white();
let away = forward.as_vec3() * 0.002;
for (text, lift) in lines {
let o = (o + glam::DVec3::new(0.0, *lift, 0.0)).as_vec3();
@@ -240,7 +240,7 @@ impl Game<'_> {
.collect();
let width: f32 = chars
.iter()
.map(|(c, _)| self.res.atlas.glyph(*c).map_or(6.0, |g| g.1))
.map(|(c, _)| self.atlas.glyph(*c).map_or(6.0, |g| g.1))
.sum();
let x0 = -(width / 2.0).trunc();
let y0 = if text.plain() == "deadmau5" {
@@ -278,7 +278,7 @@ impl Game<'_> {
}
let mut x = x0;
for (ch, color) in chars {
let Some((g, advance)) = self.res.atlas.glyph(ch) else {
let Some((g, advance)) = self.atlas.glyph(ch) else {
x += 6.0;
continue;
};
@@ -161,7 +161,7 @@ impl Game<'_> {
Some(c) => &**c,
None => match self
.save
.load(x, z, self.res.assets.registry, &self.res.biomes)
.load(x, z, self.pack.assets.registry, &self.res.biomes)
{
Some(c) => {
saved = c;
@@ -390,7 +390,7 @@ impl Game<'_> {
self.capture(true);
}
}
if self.res.screen_fx.portal == 0.0 {
if self.screen_fx.portal == 0.0 {
let pitch = self.world.random.next_float() * 0.4 + 0.8;
self.audio
.play("minecraft:block.portal.trigger", None, 0.25, pitch);
@@ -160,7 +160,7 @@ impl Game<'_> {
* glam::Mat4::from_scale(glam::Vec3::splat(scale))
* glam::Mat4::from_rotation_y(spin.to_radians());
let seed =
i64::from(self.res.item_renderer.item_id(&s.item.item)) + i64::from(s.item.damage);
i64::from(self.pack.item_renderer.item_id(&s.item.item)) + i64::from(s.item.damage);
for copy in item_render::cluster_poses(
&state,
pose,
+9 -9
View File
@@ -100,7 +100,7 @@ impl Game<'_> {
}
pub(super) fn draw_options(&mut self, batch: &mut HudBatch) {
let mut ui = std::mem::take(&mut self.ui.options);
ui.draw(&self.settings, batch, &self.res.atlas, self.cursor);
ui.draw(&self.settings, batch, &self.atlas, self.cursor);
self.ui.options = ui;
}
pub(super) fn options_mouse(&mut self, pressed: bool, right: bool) -> Result<()> {
@@ -122,7 +122,7 @@ impl Game<'_> {
let mut ui = std::mem::take(&mut self.ui.options);
let events = ui.click(
&mut self.settings,
&self.res.atlas,
&self.atlas,
self.cursor.0,
self.cursor.1,
size,
@@ -141,7 +141,7 @@ impl Game<'_> {
let mut ui = std::mem::take(&mut self.ui.options);
let events = ui.click(
&mut self.settings,
&self.res.atlas,
&self.atlas,
self.cursor.0,
self.cursor.1,
size,
@@ -154,7 +154,7 @@ impl Game<'_> {
}
pub(super) fn options_key(&mut self, key: KeyCode, text: Option<&str>) -> Result<()> {
let mut ui = std::mem::take(&mut self.ui.options);
let events = ui.key(&mut self.settings, &self.res.atlas, key, text);
let events = ui.key(&mut self.settings, &self.atlas, key, text);
self.ui.options = ui;
self.handle_option_events(events)
}
@@ -165,7 +165,7 @@ impl Game<'_> {
) -> bool {
self.ui
.options
.shortcut(&self.res.atlas, shortcut, &mut self.clipboard)
.shortcut(&self.atlas, shortcut, &mut self.clipboard)
}
pub(super) fn options_scroll(&mut self, amount: f32) {
let size = self.gui_size();
@@ -226,7 +226,7 @@ impl Game<'_> {
pub(super) fn load_language(&mut self, code: &str) {
let root = self.options.resources.clone();
lang::set(lang::Language::load(&[&root], code));
self.ui.chat.rescale(&self.res.atlas);
self.ui.chat.rescale(&self.atlas);
}
/// Settings that Horizon applies beyond render distance, volume and GUI scale.
pub(super) fn apply_ui_settings(&mut self) {
@@ -256,14 +256,14 @@ impl Game<'_> {
};
self.ui.chat.options = chat;
if rescale {
self.ui.chat.rescale(&self.res.atlas);
self.ui.chat.rescale(&self.atlas);
}
let font = &mut self.res.atlas.font;
let font = &mut self.atlas.font;
if font.uniform != s.force_unicode || font.japanese != s.japanese_glyphs {
font.uniform = s.force_unicode;
font.japanese = s.japanese_glyphs;
font.reset_cache();
self.ui.chat.rescale(&self.res.atlas);
self.ui.chat.rescale(&self.atlas);
}
// A new renderer (resource reload, first window) takes the loaded pack.
let stale = self
+18 -30
View File
@@ -110,43 +110,31 @@ impl Game<'_> {
}
}
fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> {
let assets = std::sync::Arc::new(self.res.assets.reload(root)?);
let assets = std::sync::Arc::new(self.pack.assets.reload(root)?);
let mut atlas = HudAtlas::build(root)?;
let panorama = horizon_client::gfx::panorama::Faces::load(root);
atlas.font.uniform = self.settings.force_unicode;
atlas.font.japanese = self.settings.japanese_glyphs;
let item_renderer = horizon_client::item_render::ItemRenderer::load_with_library(
let pack = super::PackResources::load(
root,
assets.model_library.clone(),
)?;
let visibility = horizon_client::models::load_visibility(root, assets.registry)?;
let tables = std::sync::Arc::new(horizon_client::mesher::MeshTables::new(
&assets,
assets,
&self.res.facts,
visibility,
)?);
self.pack.context.biomes.clone(),
self.pack.context.light.clone(),
)?;
// Everything loaded: switch over.
self.random_tick_sections.clear();
self.options.resources = root.to_path_buf();
let context = std::sync::Arc::new(horizon_client::streaming::WorkerContext {
assets: assets.clone(),
tables,
biomes: self.res.context.biomes.clone(),
light: self.res.context.light.clone(),
});
self.res.layer_names = assets
.sprite_layers
.iter()
.map(|(name, layer)| (*layer, name.trim_start_matches("minecraft:").to_owned()))
.collect();
self.res.assets = assets;
self.res.context = context.clone();
self.res.atlas = atlas;
self.res.panorama = panorama;
self.res.item_renderer = std::sync::Arc::new(item_renderer);
self.res.clouds = super::load_clouds(root);
self.res.forcefield = super::load_forcefield(root);
self.res.names = super::Names::load(root);
let context = pack.context.clone();
self.pack = pack;
self.atlas = atlas;
// Villager hats come from the pack's texture metadata (shared data, swapped in place).
*self
.res
.mob_data
.villager_hats
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) =
horizon_client::mobs::villager_hats::VillagerHats::load(root);
horizon_client::ui::load_metadata(root);
lang::set(lang::Language::load(&[&root.to_path_buf()], &lang::code()));
self.audio.reload(root);
@@ -159,7 +147,7 @@ impl Game<'_> {
self.renderer = Some(self.new_renderer(window)?);
self.apply_ui_settings();
}
self.ui.chat.rescale(&self.res.atlas);
self.ui.chat.rescale(&self.atlas);
Ok(())
}
}
+5 -5
View File
@@ -942,7 +942,7 @@ impl Game<'_> {
} else if self.screen == Screen::Options {
let result = match text {
Some(t) => {
self.ui.options.type_text(&self.res.atlas, t);
self.ui.options.type_text(&self.atlas, t);
Ok(())
}
None => self.options_key(key.expect("a key"), None),
@@ -987,7 +987,7 @@ impl Game<'_> {
.is_some_and(|f| f.center().1 > batch.height / 2.0)
|| self.screen == Screen::Chat
|| self.remote_chat_open();
let mut ui = horizon_client::ui_theme::Ui::new(&self.res.atlas, batch, self.cursor);
let mut ui = horizon_client::ui_theme::Ui::new(&self.atlas, batch, self.cursor);
keyboard.draw(&mut ui, at_top, self.ui.options.pad_style);
ui.finish();
return;
@@ -1002,7 +1002,7 @@ impl Game<'_> {
return;
}
// An arrow, outlined, pointing up-left at (x, y).
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (x, y) = (x.floor(), y.floor());
const ROWS: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 4, 2, 1];
for (i, &w) in ROWS.iter().enumerate() {
@@ -1047,7 +1047,7 @@ impl Game<'_> {
};
if horizon {
use horizon_client::ui_theme::{self as theme, Ui, color};
let mut ui = Ui::new(&self.res.atlas, batch, self.cursor);
let mut ui = Ui::new(&self.atlas, batch, self.cursor);
let k = ui.batch.scale / ui.density;
let (x, y, w, h) = (x * k, y * k, w * k, h * k);
let radius = match focus.kind {
@@ -1070,7 +1070,7 @@ impl Game<'_> {
return;
}
if matches!(focus.kind, Kind::Row | Kind::Field) {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let white = rgba(255, 255, 255, 255);
batch.fill(atlas, x, y, w, 1.0, white);
batch.fill(atlas, x, y + h - 1.0, w, 1.0, white);
+1 -1
View File
@@ -249,7 +249,7 @@ impl Game<'_> {
/// PaintingRenderer: the variant on the front, the back texture behind and
/// on the edges.
pub(super) fn painting_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let sprites = &self.res.atlas.sprites;
let sprites = &self.atlas.sprites;
let Some(back) = sprites.get("painting/back").copied() else {
return;
};
+11 -14
View File
@@ -49,16 +49,7 @@ fn with_raw(modelled: Tag, raw: Option<&Tag>) -> Tag {
// Defaults Horizon invents for fields it does not simulate give way to the save.
let invented = matches!(
k.to_string_lossy().as_str(),
"Fire"
| "Air"
| "Invulnerable"
| "PortalCooldown"
| "HasBeenShot"
// FallingBlockEntity fields Horizon does not simulate.
| "HurtEntities"
| "CancelDrop"
| "FallHurtAmount"
| "FallHurtMax"
"Fire" | "Air" | "Invulnerable" | "PortalCooldown" | "HasBeenShot"
);
if !(invented && out.contains_key(k)) {
out.insert(k.clone(), v.clone());
@@ -199,7 +190,7 @@ impl Game<'_> {
}
}
"minecraft:falling_block" => {
if let Some((state, position, velocity, age)) =
if let Some((state, position, velocity, age, fall_distance)) =
entity_nbt::falling_block_from_nbt(&tag)
&& let Some(state) = self.state_from_nbt(&state)
{
@@ -214,7 +205,11 @@ impl Game<'_> {
age,
no_gravity,
drop_item,
fall_distance: 0.0,
fall_distance,
damage: horizon_client::falling_block::Damage::from_nbt(
&tag,
self.res.facts.get(state).name.ends_with("anvil"),
),
saved: uuid.map(|u| Box::new((u, tag.clone()))),
});
}
@@ -506,7 +501,7 @@ impl Game<'_> {
}
/// `BlockState.CODEC`: a block name or `{id, properties}` (or legacy `{Name, Properties}`).
fn state_from_nbt(&self, tag: &Tag) -> Option<BlockStateId> {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let state = match tag.get("Name") {
Some(Tag::String(name)) => BlockState {
name: name.to_string_lossy(),
@@ -528,7 +523,7 @@ impl Game<'_> {
.or_else(|| registry.default_state(&state.name))
}
pub(in crate::game) fn state_to_nbt(&self, state: BlockStateId) -> Tag {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
match registry.state(state) {
Some(s) if registry.default_state(&s.name) == Some(state) => {
Tag::String(s.name.as_str().into())
@@ -620,6 +615,8 @@ impl Game<'_> {
f.velocity,
f.age,
f.drop_item,
f.damage,
f.fall_distance,
uuid,
);
out.entry(chunk_of(f.position))
+11 -7
View File
@@ -203,7 +203,12 @@ impl Game<'_> {
let p = self.player.as_ref()?;
let sleeping = self.sleeping.map(|(head, _)| {
let state = self.world.block(head[0], head[1], head[2]);
let props = self.res.assets.registry.state(state).map(|s| &s.properties);
let props = self
.pack
.assets
.registry
.state(state)
.map(|s| &s.properties);
// BedBlock.getBedOrientation as Direction.toYRot.
props.and_then(|props| match props.get("facing").map(String::as_str) {
Some("south") => Some(0.0),
@@ -405,7 +410,7 @@ impl Game<'_> {
m.position.z.floor() as i32,
);
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
horizon_client::mobs::render::render_with(
m,
@@ -459,7 +464,7 @@ impl Game<'_> {
m.position.y += 0.125 * f64::from(u8::from(m.extra.crouching));
m.previous = m.position;
let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
let mut verts = Vec::new();
horizon_client::mobs::render::render_with(
@@ -530,10 +535,9 @@ impl Game<'_> {
let Some((texture, _)) = assets.equipment.get(asset).and_then(|k| k.get("wings")) else {
return;
};
let (Some(model), Some(rect)) = (
assets.player.get("elytra"),
self.res.atlas.sprites.get(texture),
) else {
let (Some(model), Some(rect)) =
(assets.player.get("elytra"), self.atlas.sprites.get(texture))
else {
return;
};
let base = horizon_client::mobs::render::base_transform(m, partial, camera)
+4 -4
View File
@@ -576,7 +576,7 @@ impl Game<'_> {
.map(hud_overlays::EffectIcon::from)
.collect();
let draws = hud_overlays::effects(batch.width as i32, false, &icons);
hud_layout::paint(batch, &self.res.atlas, &draws);
hud_layout::paint(batch, &self.atlas, &draws);
}
/// `EffectsInInventory`: panels to the right of survival/creative inventory.
pub(super) fn draw_inventory_effects(
@@ -591,12 +591,12 @@ impl Game<'_> {
image_width,
&self.potions.effects.list,
self.clock.rate(),
&|key| self.res.names.get(key).map(str::to_owned),
&|text| self.res.atlas.font.width(text).ceil() as i32,
&|key| self.pack.names.get(key).map(str::to_owned),
&|text| self.atlas.font.width(text).ceil() as i32,
);
if let Some(lines) = inventory_effects::paint(
batch,
&self.res.atlas,
&self.atlas,
&panels,
[self.cursor.0 as i32, self.cursor.1 as i32],
) {
+1 -1
View File
@@ -976,7 +976,7 @@ impl Game<'_> {
}
let bed = *known.entry(state.0).or_insert_with(|| {
self.res.facts.get(state).name.ends_with("_bed")
&& self.res.assets.registry.state(state).is_some_and(|s| {
&& self.pack.assets.registry.state(state).is_some_and(|s| {
s.properties.get("part").map(String::as_str) == Some("head")
})
});
@@ -467,7 +467,7 @@ impl Game<'_> {
horizon_client::item_tooltip::lines(
stack,
self.res.items.get(&stack.item),
&|k| self.res.names.get(k).map(str::to_owned),
&|k| self.pack.names.get(k).map(str::to_owned),
)
})
{
@@ -629,7 +629,7 @@ impl Game<'_> {
search.focused = true;
search.reset_blink();
if !magnifier {
let idx = search.index_at(&self.res.atlas, cursor.0);
let idx = search.index_at(&self.atlas, cursor.0);
search.set_cursor(idx, false);
}
return true;
@@ -871,7 +871,7 @@ impl Game<'_> {
let (bx, by) = self.book_button_pos(book_type, ox, batch);
let hover = inside(cursor, bx, by, 20.0, 18.0);
batch.sprite(
&self.res.atlas,
&self.atlas,
&sprite(if hover {
"button_highlighted"
} else {
@@ -919,7 +919,7 @@ impl Game<'_> {
fn draw_book_panel(&mut self, batch: &mut HudBatch, book_type: BookType) {
let (xo, yo) = self.book_origin(batch);
let cursor = self.cursor;
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let search = match self.recipe_ui.search.as_mut() {
Some(edit) => {
// The box's place, for clicks and typing.
@@ -1042,7 +1042,7 @@ impl Game<'_> {
let mut tooltip: Option<Vec<(String, u32)>> = None;
for d in calls {
let start = batch.vertices.len();
let atlas = &self.res.atlas;
let atlas = &self.atlas;
match &d.call {
Call::Blit {
x, y, w, h, u, v, ..
+51 -13
View File
@@ -153,6 +153,22 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo
impl Game<'_> {
/// Leave the title for a server (ConnectScreen): an empty world fed by the connection.
pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> {
self.join_server(address, name, None)
}
/// Join single player's integrated server through memory.
pub(super) fn connect_local(
&mut self,
pipe: horizon_protocol::connection::Pipe,
name: &str,
) -> Result<()> {
self.join_server("local", name, Some(pipe))
}
fn join_server(
&mut self,
address: &str,
name: &str,
local: Option<horizon_protocol::connection::Pipe>,
) -> Result<()> {
self.perf.world_opening();
let root = self.options.resources.clone();
let builtin = Builtin::find(&root)
@@ -160,16 +176,26 @@ impl Game<'_> {
.ok_or("registries.json not found next to the resources; run the data generator reports (horizon-prepare)")?;
let lang = Arc::new(horizon_client::net::load_language(&root));
let view = self.settings.render_distance.clamp(2, 32) as i8;
horizon_client::crash::set_detail("Server", horizon_client::net::shown_address(address));
if local.is_none() {
horizon_client::crash::set_detail(
"Server",
horizon_client::net::shown_address(address),
);
}
// A signed-in account always plays under its own name.
let auth = horizon_client::auth::current();
let name = auth.as_ref().map_or(name, |a| a.name.as_str());
let session = Session::connect(address, name, auth.clone(), view, lang.clone());
self.extras_connecting(address, name);
let session = match local {
Some(pipe) => Session::connect_local(pipe, name, view, lang.clone()),
None => {
self.extras_connecting(address, name);
Session::connect(address, name, auth.clone(), view, lang.clone())
}
};
let player_type = super::perspective::player_type(&root);
let mut streaming = Streaming::new(
Arc::new(NoTerrain),
self.res.context.clone(),
self.pack.context.clone(),
self.res.threads,
);
streaming.remote = true;
@@ -274,11 +300,19 @@ impl Game<'_> {
if let Some(mut r) = self.remote.take() {
r.session.disconnect();
}
// Single player's server thread saves the world before the title shows.
let single_player = match self.integrated.take() {
Some(server) => {
server.stop();
true
}
None => false,
};
horizon_client::crash::clear_detail("Server");
self.debug_charts.reset();
self.tab_list.reset();
self.score.board = Default::default();
self.streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), 1);
self.streaming = Streaming::new(Arc::new(NoTerrain), self.pack.context.clone(), 1);
self.streaming.paused = true;
self.world = World::new(self.res.facts.air, 0);
self.player = None;
@@ -296,6 +330,11 @@ impl Game<'_> {
}
let saves = std::env::current_dir()?.join("saves");
let mut title = horizon_client::title::Title::new(saves.clone(), &self.options.resources);
if single_player && reason.is_none() {
self.title = Some(title);
self.capture(false);
return Ok(());
}
title.mode = horizon_client::title::Mode::Multiplayer(match reason {
Some(reason) => horizon_client::multiplayer::Screen::Disconnected {
reason,
@@ -465,7 +504,7 @@ impl Game<'_> {
if !same {
let mut streaming = Streaming::new(
Arc::new(NoTerrain),
self.res.context.clone(),
self.pack.context.clone(),
self.res.threads,
);
streaming.remote = true;
@@ -1545,11 +1584,10 @@ impl Game<'_> {
self.skin_slots.len()
} else {
let (old, slot) = self.skin_slots.remove(0);
self.res.atlas.sprites.remove(&old);
self.atlas.sprites.remove(&old);
slot
};
let Some(rect) = self
.res
.atlas
.sprites
.get(&format!("horizon/skin{slot}"))
@@ -1557,7 +1595,7 @@ impl Game<'_> {
else {
return;
};
let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32);
let (w, h) = (self.atlas.width as f32, self.atlas.height as f32);
self.map_patches.push(horizon_client::font::Patch {
x: (rect.u0 * w).round() as u32,
y: (rect.v0 * h).round() as u32,
@@ -1565,7 +1603,7 @@ impl Game<'_> {
height: 64,
rgba,
});
self.res.atlas.sprites.insert(location.clone(), rect);
self.atlas.sprites.insert(location.clone(), rect);
self.skin_slots.push((location, slot));
}
/// Whether a downloaded skin is in the atlas, marking it recently shown.
@@ -1807,7 +1845,7 @@ impl Game<'_> {
entities: &ghast_collisions,
player,
scene: &mut self.world,
assets: &self.res.assets,
assets: &self.pack.assets,
collision_binding: self.collision,
resources: self.motion,
}
@@ -2742,7 +2780,7 @@ impl Game<'_> {
if self.player.is_some() {
return false;
}
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255));
let shown = horizon_client::net::shown_address(&r.session.address);
@@ -2767,7 +2805,7 @@ impl Game<'_> {
/// Chat (ChatComponent), the chat input line and the action bar.
pub(super) fn remote_hud(&self, batch: &mut HudBatch) {
let Some(r) = &self.remote else { return };
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
let open = r.chat_input.is_some();
let now = Instant::now();
@@ -25,7 +25,7 @@ impl Game<'_> {
} else {
format!("minecraft:{name}")
};
let registry = &self.res.assets.registry;
let registry = &self.pack.assets.registry;
let default = registry
.default_state(&name)
.ok_or_else(|| format!("unknown block {name}"))?;
+35 -31
View File
@@ -73,29 +73,33 @@ impl Game<'_> {
} 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,
cloud_range_chunks: self.settings.cloud_range,
camera_y: camera.y,
// level.getMinY(): the Nether and the End start at y 0.
min_y: if self.dim == Dim::Overworld { MIN_Y } else { 0 },
flat: false,
forward: forward.map(|c| c as f32),
rain,
thunder,
skybox: self.dim == Dim::Overworld,
blindness: None,
darkness: self.darkness_fog(),
boss_world_fog: self.dragon_bar_shown(),
})
horizon_client::fog::setup_fog(
&self.res.fog,
&self.fog,
&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,
cloud_range_chunks: self.settings.cloud_range,
camera_y: camera.y,
// level.getMinY(): the Nether and the End start at y 0.
min_y: if self.dim == Dim::Overworld { MIN_Y } else { 0 },
flat: false,
forward: forward.map(|c| c as f32),
rain,
thunder,
skybox: self.dim == Dim::Overworld,
blindness: None,
darkness: self.darkness_fog(),
boss_world_fog: self.dragon_bar_shown(),
},
)
}
/// What a shader pack's `Frame` uniform reads of the game this frame.
pub(super) fn shader_inputs(
@@ -181,7 +185,7 @@ impl Game<'_> {
(in_water && !spectator).then(|| (self.eye_brightness(eye), self.yaw, self.pitch));
// Hud.extractCameraOverlays; the spyglass scope (and its easing) is
// drawn on the HUD by draw_spyglass.
let fx = &self.res.screen_fx;
let fx = &self.screen_fx;
let overlays = hud_overlays::CameraOverlays {
vignette: self.settings.vignette.then_some((
fx.vignette_brightness,
@@ -206,8 +210,8 @@ impl Game<'_> {
let mut scope = self.scope_scale;
let gui_overlays =
hud_overlays::camera_overlays(size[0] as i32, size[1] as i32, &overlays, &mut scope);
self.res.screen_fx.build(&ScreenInputs {
sprites: &self.res.atlas.sprites,
self.screen_fx.build(&ScreenInputs {
sprites: &self.atlas.sprites,
aspect: size[0] as f32 / size[1].max(1) as f32,
partial,
block_overlay,
@@ -231,16 +235,16 @@ impl Game<'_> {
lightmap_brightness(if self.dim == Dim::Nether { 0.1 } else { 0.0 }, raw)
}
pub(super) fn tick_particles(&mut self) {
self.res.fog.state.tick_flicker();
self.fog.tick_flicker();
let eye = self.eye_position();
if let Some(e) = eye {
let brightness = self.eye_brightness(e);
let inside_portal = self.client_portal_effect();
self.res.screen_fx.tick(brightness, inside_portal);
self.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);
self.fog.tick(in_water);
let b = [
e[0].floor() as i32,
e[1].floor() as i32,
@@ -258,7 +262,7 @@ impl Game<'_> {
.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,
&mut self.fog,
rain,
self.world.light(b[0], b[1], b[2]) >> 4,
rains,
@@ -287,7 +291,7 @@ impl Game<'_> {
facts,
collision: self.collision,
biomes,
registry: self.res.assets.registry,
registry: self.pack.assets.registry,
raining_at: &raining_at,
};
if let Some(e) = eye {
@@ -66,7 +66,7 @@ impl Game<'_> {
&*self.res.facts.get(state).name == "minecraft:respawn_anchor"
}
fn anchor_charges(&self, state: BlockStateId) -> i32 {
self.res
self.pack
.assets
.registry
.state(state)
@@ -75,9 +75,9 @@ impl Game<'_> {
.unwrap_or(0)
}
fn anchor_with_charges(&self, state: BlockStateId, charges: i32) -> Option<BlockStateId> {
let mut s = self.res.assets.registry.state(state)?.clone();
let mut s = self.pack.assets.registry.state(state)?.clone();
s.properties.insert("charges".into(), charges.to_string());
self.res.assets.registry.resolve(&s).ok()
self.pack.assets.registry.resolve(&s).ok()
}
/// `RespawnAnchorBlock.canSetSpawn`: the `respawn_anchor_works` attribute
/// (only the Nether's dimension type sets it).
@@ -243,7 +243,7 @@ impl Game<'_> {
}
// removeBlock(head), then the foot behind it if it is still this bed.
let facing = self
.res
.pack
.assets
.registry
.state(state)
@@ -300,7 +300,7 @@ impl Game<'_> {
let name = &self.res.facts.get(state).name;
let open_trapdoor = name.ends_with("_trapdoor")
&& self
.res
.pack
.assets
.registry
.state(state)
@@ -337,7 +337,7 @@ impl Game<'_> {
let name = &*self.res.facts.get(state).name;
let lit_campfire = (name == "minecraft:campfire" || name == "minecraft:soul_campfire")
&& self
.res
.pack
.assets
.registry
.state(state)
+4 -4
View File
@@ -573,11 +573,11 @@ impl Game<'_> {
batch.height as i32,
board,
objective,
&self.res.atlas.font,
&self.atlas.font,
self.settings.text_background(0.3),
self.settings.text_background(0.4),
);
hud_layout::paint(batch, &self.res.atlas, &draws);
hud_layout::paint(batch, &self.atlas, &draws);
}
}
@@ -639,8 +639,8 @@ impl Game<'_> {
),
upside_down: &up,
};
let draws = self.tab_list.layout(&inputs, &self.res.atlas.font);
horizon_client::hud_layout::paint(batch, &self.res.atlas, &draws);
let draws = self.tab_list.layout(&inputs, &self.atlas.font);
horizon_client::hud_layout::paint(batch, &self.atlas, &draws);
}
}
+4 -4
View File
@@ -78,12 +78,12 @@ impl Game<'_> {
let (world, quit) = self.pause_labels();
self.tick_friends();
let friends = self.friends_view();
let mut ui = horizon_client::ui_theme::Ui::new(&self.res.atlas, batch, self.cursor);
let mut ui = horizon_client::ui_theme::Ui::new(&self.atlas, batch, self.cursor);
horizon_client::front::pause::draw(&mut ui, &world, quit, opened, &friends);
ui.finish();
return;
}
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
let title = Text::translate("menu.game", &[]);
@@ -135,7 +135,7 @@ impl Game<'_> {
let mut b = HudBatch::new(size);
let (world, quit) = self.pause_labels();
horizon_client::front::pause::click(
&self.res.atlas,
&self.atlas,
&mut b,
self.cursor.0,
self.cursor.1,
@@ -175,7 +175,7 @@ impl Game<'_> {
}
/// DeathScreen: gradient, the title at double size, the cause and score.
pub(super) fn draw_death_screen(&mut self, batch: &mut HudBatch) {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (w, h) = (batch.width, batch.height);
// fillGradient(0x60500000 -> 0xA0803030).
let rows = h.ceil() as i32;
+3 -3
View File
@@ -262,7 +262,7 @@ impl Game<'_> {
if self.sculk.tables.built {
return;
}
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let n = registry.len();
let tag = |name: &str| {
self.res
@@ -640,7 +640,7 @@ impl Game<'_> {
self.state_property(state, "shrieking") == Some("true")
}
fn state_property(&self, state: BlockStateId, key: &str) -> Option<&str> {
self.res
self.pack
.assets
.registry
.state(state)
@@ -1156,7 +1156,7 @@ impl Game<'_> {
let in_water =
horizon_client::fog::fog_type(&self.world, &self.res.facts, eye, self.forward())
== FogType::Water;
return self.res.fog.state.water_vision(in_water);
return self.fog.water_vision(in_water);
}
0.0
}
@@ -177,7 +177,7 @@ impl Game<'_> {
Some((n, rest)) => (n, rest.trim_end_matches(']')),
None => (text, ""),
};
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let base = registry
.default_state(name)
.ok_or_else(|| format!("unknown block {name}"))?;
@@ -197,7 +197,7 @@ impl Game<'_> {
/// `BlockStateParser.serialize`.
fn fixture_state_text(&self, state: BlockStateId) -> String {
let Some(s) = self.res.assets.registry.state(state) else {
let Some(s) = self.pack.assets.registry.state(state) else {
return "?".into();
};
if s.properties.is_empty() {
+3 -3
View File
@@ -88,7 +88,7 @@ impl Game<'_> {
return;
};
let line = edit.line;
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let width = |s: &str| HudBatch::text_width(atlas, s);
let Some(key) = self.sign_edit.as_ref().map(|e| e.pos) else {
return;
@@ -130,7 +130,7 @@ impl Game<'_> {
} else {
&mut sign.back
};
let atlas = &self.res.atlas;
let atlas = &self.atlas;
self.text_selection.apply(
sign_line_id(front, line),
&mut text.lines[line],
@@ -163,7 +163,7 @@ impl Game<'_> {
let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) else {
return;
};
let atlas = &self.res.atlas;
let atlas = &self.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 {
+1 -1
View File
@@ -399,7 +399,7 @@ impl Game<'_> {
alpha: f64,
out: &mut Vec<horizon_client::mesher::Vertex>,
) {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
for (key, (_, mob)) in &self.spawners.displays {
let at = glam::DVec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2));
+19 -19
View File
@@ -398,7 +398,7 @@ impl Game<'_> {
fn anvil_item_name(&self, s: &Station) -> String {
match &s.inputs[0] {
Some(input)
if input.custom_name().is_none() && s.name == self.res.names.item(&input.item) =>
if input.custom_name().is_none() && s.name == self.pack.names.item(&input.item) =>
{
String::new()
}
@@ -429,7 +429,7 @@ impl Game<'_> {
let name = self.anvil_item_name(&s);
let hover = s.inputs[0]
.as_ref()
.map(|i| stations::hover_name(&|id| self.res.names.item(id), i))
.map(|i| stations::hover_name(&|id| self.pack.names.item(id), i))
.unwrap_or_default();
s.anvil = stations::anvil_result(
&data.enchantments,
@@ -1157,7 +1157,7 @@ impl Game<'_> {
s.anvil_last = s.inputs[0].clone();
s.name = s.inputs[0]
.as_ref()
.map(|i| stations::hover_name(&|id| self.res.names.item(id), i))
.map(|i| stations::hover_name(&|id| self.pack.names.item(id), i))
.unwrap_or_default();
}
self.station_changed();
@@ -1249,7 +1249,7 @@ impl Game<'_> {
}
/// Text in the Standard Galactic alphabet (`minecraft:alt`), cut to `max` pixels.
fn galactic(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32, max: f32, color: u32) {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let Some(sheet) = atlas.sprites.get("font/ascii_sga").copied() else {
batch.text(atlas, text, x, y, color, false);
return;
@@ -1325,7 +1325,7 @@ impl Game<'_> {
let local = (self.cursor.0 - ox, self.cursor.1 - oy);
let mut tooltip: Option<Vec<(String, u32)>> = None;
{
let atlas = &self.res.atlas;
let atlas = &self.atlas;
batch.fill(
atlas,
0.0,
@@ -1342,7 +1342,7 @@ impl Game<'_> {
};
let (fuel, total_fuel, brew, total_brew) =
(b.fuel, b.total_fuel, b.brew_time, b.total_brew_time);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
Self::part(
batch,
atlas,
@@ -1417,7 +1417,7 @@ impl Game<'_> {
if self.slot_mut(i).is_none() {
let (sx, sy) = self.station_slot_position(i).unwrap_or_default();
batch.sprite(
&self.res.atlas,
&self.atlas,
&format!("gui/sprites/container/slot/{icon}"),
ox + sx,
oy + sy,
@@ -1427,7 +1427,7 @@ impl Game<'_> {
} else if let Some(kind) = self.station.as_ref().map(|s| s.kind) {
let title = self.translate(kind.title_key(), "");
{
let atlas = &self.res.atlas;
let atlas = &self.atlas;
Self::part(
batch,
atlas,
@@ -1446,7 +1446,7 @@ impl Game<'_> {
if kind == Kind::Loom {
tooltip = self.draw_loom(batch, ox, oy, local);
}
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let s = self.station.as_ref().expect("open station");
let has_input = s.inputs.iter().any(Option::is_some);
match kind {
@@ -1552,7 +1552,7 @@ impl Game<'_> {
);
-8323296
};
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let cw = HudBatch::text_width(atlas, &cost_text);
batch.text(
atlas,
@@ -1679,7 +1679,7 @@ impl Game<'_> {
)
};
if let Some(line) = line {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let tw = HudBatch::text_width(atlas, &line);
let tx = 176.0 - 8.0 - tw - 2.0;
batch.fill(
@@ -1788,7 +1788,7 @@ impl Game<'_> {
"recipe"
};
batch.sprite_scaled(
&self.res.atlas,
&self.atlas,
&format!("gui/sprites/container/stonecutter/{sprite}"),
ox + x,
oy + y - 1.0,
@@ -1816,7 +1816,7 @@ impl Game<'_> {
if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) {
let (sx, sy) = self.slot_position(slot);
batch.fill(
&self.res.atlas,
&self.atlas,
ox + sx,
oy + sy,
16.0,
@@ -1881,16 +1881,16 @@ impl Game<'_> {
{
let key = brewing::potion_name_key(&stack.item, stack.potion());
e.translate(&key)
.map_or_else(|| self.res.names.item(&stack.item), str::to_owned)
.map_or_else(|| self.pack.names.item(&stack.item), str::to_owned)
} else {
self.res.names.item(&stack.item)
self.pack.names.item(&stack.item)
};
let mut lines = vec![(name, color)];
let translate = |k: &str| e.translate(k).map(str::to_owned);
// ItemContainerContents.addToTooltip.
let hover_name = |s: &ItemStack| {
s.custom_name()
.map_or_else(|| self.res.names.item(&s.item), str::to_owned)
.map_or_else(|| self.pack.names.item(&s.item), str::to_owned)
};
for line in horizon_client::item_tooltip::container_lines(stack, &hover_name, &translate) {
lines.push((line, u32::MAX));
@@ -2037,7 +2037,7 @@ impl Game<'_> {
if lines.is_empty() {
return;
}
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let w = lines
.iter()
.map(|(t, _)| HudBatch::text_width(atlas, t))
@@ -2141,14 +2141,14 @@ impl Game<'_> {
}
if let Some(bottles) = out.bottles {
let state = self.world.block(x, y, z);
if let Some(mut s) = self.res.assets.registry.state(state).cloned()
if let Some(mut s) = self.pack.assets.registry.state(state).cloned()
&& AsRef::<str>::as_ref(&s.name) == "minecraft:brewing_stand"
{
for (i, has) in bottles.iter().enumerate() {
s.properties
.insert(format!("has_bottle_{i}"), has.to_string());
}
if let Ok(id) = self.res.assets.registry.resolve(&s) {
if let Ok(id) = self.pack.assets.registry.resolve(&s) {
self.world.set(x, y, z, id)?;
}
}
@@ -216,7 +216,7 @@ impl Game<'_> {
}
pub(super) fn draw_stats(&mut self, batch: &mut HudBatch) {
let (w, h) = (batch.width, batch.height);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true);
let (top, bottom) = (TAB_H, h - FOOTER);
ui::separators(batch, atlas, top, bottom, true);
@@ -327,13 +327,13 @@ impl Game<'_> {
}
let stack = ItemStack::new(item, 1);
batch.sprite(
&self.res.atlas,
&self.atlas,
"gui/sprites/container/slot",
left + 1.0,
y + 1.0,
);
self.draw_item(batch, &stack, left + 2.0, y + 2.0);
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let color = if (i + 1) % 2 == 0 {
u32::MAX
} else {
@@ -394,7 +394,7 @@ impl Game<'_> {
}
}
}
let atlas = &self.res.atlas;
let atlas = &self.atlas;
ui::scrollbar(
batch,
atlas,
@@ -407,7 +407,7 @@ impl Game<'_> {
self.draw_stats_footer(batch, w, h);
}
fn draw_stats_footer(&self, batch: &mut HudBatch, w: f32, h: f32) {
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let (bx, by) = ((w / 2.0 - 100.0).floor(), h - FOOTER + 6.0);
let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0);
ui::button(
+2 -2
View File
@@ -76,7 +76,7 @@ impl Game<'_> {
/// The other half of the open double chest and whether the open one is
/// the right half (`ChestBlock.getConnectedDirection`).
pub(super) fn chest_partner(&self, key: (i32, i32, i32)) -> Option<((i32, i32, i32), bool)> {
let registry = self.res.assets.registry;
let registry = self.pack.assets.registry;
let state = registry.state(self.world.block(key.0, key.1, key.2))?;
if !matches!(
state.name.as_str(),
@@ -211,7 +211,7 @@ impl Game<'_> {
oy: f32,
) {
use horizon_client::hud::rgba;
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let grey = rgba(64, 64, 64, 255);
if self
.container_block()
@@ -47,7 +47,7 @@ impl Game<'_> {
width: batch.width as i32,
height: batch.height as i32,
};
let atlas = &self.res.atlas;
let atlas = &self.atlas;
let draws = self
.subtitles
.overlay

Some files were not shown because too many files have changed in this diff Show More