Merge remote-tracking branch 'origin/refactor/port-pack-legacy-structure-mods' into feat/yung-port-as-written
This commit is contained in:
@@ -140,8 +140,9 @@ pub(super) struct Remote {
|
||||
stepped: HashMap<i32, SteppedInterpolation>,
|
||||
/// `LivingEntity.lerpHeadTo`: the head yaw and the ticks left to reach it.
|
||||
head_lerps: HashMap<i32, (f32, u32)>,
|
||||
/// Item entities waiting for their item data.
|
||||
pending_items: HashMap<i32, [f64; 3]>,
|
||||
/// Item entities waiting for their item data: where they are and their
|
||||
/// motion.
|
||||
pending_items: HashMap<i32, ([f64; 3], Vec3)>,
|
||||
health: (f32, i32, f32),
|
||||
/// `LocalPlayer.flashOnSetHealth`: set by the first health the server
|
||||
/// sends; from then on a drop starts the hurt animation.
|
||||
@@ -1386,7 +1387,7 @@ impl Game<'_> {
|
||||
}
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
if kind == "minecraft:item" {
|
||||
r.pending_items.insert(id, position);
|
||||
r.pending_items.insert(id, (position, Vec3::ZERO));
|
||||
}
|
||||
r.entities.insert(
|
||||
id,
|
||||
@@ -1465,6 +1466,23 @@ impl Game<'_> {
|
||||
m.on_ground = on_ground;
|
||||
return;
|
||||
}
|
||||
if let Some(p) = r.pending_items.get_mut(&id) {
|
||||
p.0 = position;
|
||||
}
|
||||
// ItemEntity and FallingBlockEntity keep Entity's NO_OP
|
||||
// InterpolationHandler: moveOrInterpolateTo puts them there at
|
||||
// once, and their own tick moves them on between the server's
|
||||
// updates (`tick_remote_entities`).
|
||||
let at = Vec3::new(position[0], position[1], position[2]);
|
||||
if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) {
|
||||
d.position = at;
|
||||
d.on_ground = on_ground;
|
||||
return;
|
||||
}
|
||||
if let Some(f) = self.falling.iter_mut().find(|f| f.id == id as u32) {
|
||||
f.position = at;
|
||||
return;
|
||||
}
|
||||
// AbstractInterpolationHandler.interpolateTo: without a rotation,
|
||||
// the one it was heading for.
|
||||
let rotation = rotation.or_else(|| r.lerps.get(&id).and_then(|l| l.rotation));
|
||||
@@ -1476,9 +1494,6 @@ impl Game<'_> {
|
||||
steps: 3,
|
||||
},
|
||||
);
|
||||
if let Some(p) = r.pending_items.get_mut(&id) {
|
||||
*p = position;
|
||||
}
|
||||
}
|
||||
self.turn_remote_object(id, rotation.map(|(yaw, _)| yaw), on_ground);
|
||||
self.turn_remote_projectile(id, rotation);
|
||||
@@ -1811,6 +1826,8 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
self.spawn_entity(p.id, &kind, p.position, rotation);
|
||||
// Entity.recreateFromPacket: setDeltaMovement(packet.getMovement()).
|
||||
self.remote_motion(p.id, p.velocity);
|
||||
if !self.spawn_remote_object(p.id, &kind, p.position, rotation[0], p.data) {
|
||||
self.spawn_remote_projectile(
|
||||
p.id,
|
||||
@@ -2129,6 +2146,8 @@ impl Game<'_> {
|
||||
pl.velocity = Vec3::new(p.velocity[0], p.velocity[1], p.velocity[2]);
|
||||
}
|
||||
}
|
||||
// The same packet for another entity: Entity.lerpMotion.
|
||||
C::SetEntityMotion(p) => self.remote_motion(p.id, p.velocity),
|
||||
// ClientPacketListener.handleDamageEvent: LivingEntity.handleDamageEvent
|
||||
// jolts the walk animation and restarts the hurt flash. Its hurt
|
||||
// sound comes as a sound from Horizon's host, which plays it itself.
|
||||
@@ -2952,7 +2971,9 @@ impl Game<'_> {
|
||||
item.stack = stack;
|
||||
return;
|
||||
}
|
||||
let Some(p) = position else { return };
|
||||
let Some((p, velocity)) = position else {
|
||||
return;
|
||||
};
|
||||
let at = Vec3::new(p[0], p[1], p[2]);
|
||||
let bob_offset = self.world.random.next_float() * std::f32::consts::PI * 2.0;
|
||||
self.dropped.push(ItemEntity {
|
||||
@@ -2963,7 +2984,7 @@ impl Game<'_> {
|
||||
stack,
|
||||
position: at,
|
||||
previous: at,
|
||||
velocity: Vec3::ZERO,
|
||||
velocity,
|
||||
on_ground: false,
|
||||
age: 0,
|
||||
pickup_delay: 0,
|
||||
@@ -2971,6 +2992,23 @@ impl Game<'_> {
|
||||
ticks: 0,
|
||||
});
|
||||
}
|
||||
/// `Entity.lerpMotion` (and `recreateFromPacket`'s motion) for the
|
||||
/// entities whose own tick moves them on a client: dropped items and
|
||||
/// falling blocks.
|
||||
fn remote_motion(&mut self, id: i32, velocity: [f64; 3]) {
|
||||
let v = Vec3::new(velocity[0], velocity[1], velocity[2]);
|
||||
if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) {
|
||||
d.velocity = v;
|
||||
} else if let Some(f) = self.falling.iter_mut().find(|f| f.id == id as u32) {
|
||||
f.velocity = v;
|
||||
} else if let Some(p) = self
|
||||
.remote
|
||||
.as_mut()
|
||||
.and_then(|r| r.pending_items.get_mut(&id))
|
||||
{
|
||||
p.1 = v;
|
||||
}
|
||||
}
|
||||
fn apply_remote_health(&mut self) {
|
||||
let Some((health, food, saturation)) = self.remote.as_ref().map(|r| r.health) else {
|
||||
return;
|
||||
@@ -3491,20 +3529,12 @@ impl Game<'_> {
|
||||
l.steps -= 1;
|
||||
}
|
||||
}
|
||||
// ItemEntity.tick runs on a client too: gravity, collisions and
|
||||
// friction move the item between the server's updates (every 20
|
||||
// ticks), and only the server removes it.
|
||||
let (world, facts, collision) = (&self.world, self.res.facts(), self.collision);
|
||||
for d in self.dropped.iter_mut().filter(|_| running) {
|
||||
d.previous = d.position;
|
||||
d.age += 1;
|
||||
if let Some(l) = lerps.get_mut(&(d.id as i32))
|
||||
&& l.steps > 0
|
||||
{
|
||||
let n = f64::from(l.steps);
|
||||
d.position = Vec3::new(
|
||||
d.position.x + (l.target[0] - d.position.x) / n,
|
||||
d.position.y + (l.target[1] - d.position.y) / n,
|
||||
d.position.z + (l.target[2] - d.position.z) / n,
|
||||
);
|
||||
l.steps -= 1;
|
||||
}
|
||||
d.tick(world, facts, collision, false);
|
||||
}
|
||||
head_lerps.retain(|_, (_, steps)| *steps > 0);
|
||||
for (item, ticks, at, eye, pitch, yaw) in using {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! end crystals on a server's client (`ClientPacketListener.handleAddEntity`
|
||||
//! and `handleSetEntityData`): the server simulates them, the client draws
|
||||
//! them where it says and interpolates their moves.
|
||||
use super::{FallingBlock, Game};
|
||||
use super::{FallStep, FallingBlock, Game};
|
||||
use horizon_client::projectiles::{Projectile, ProjectileKind};
|
||||
use horizon_core::{geometry::Vec3, position::BlockPos};
|
||||
use horizon_protocol::entity_data::Value;
|
||||
@@ -185,11 +185,17 @@ impl Game<'_> {
|
||||
t.previous = t.position;
|
||||
t.position = step(t.id, t.position);
|
||||
}
|
||||
for f in &mut self.falling {
|
||||
f.previous = f.position;
|
||||
f.age += 1;
|
||||
f.position = step(f.id, f.position);
|
||||
// FallingBlockEntity.tick runs on a client too: the block falls by
|
||||
// itself between the server's updates (every 20 ticks), then waits
|
||||
// where it lands for the server to place it and remove it.
|
||||
let mut falling = std::mem::take(&mut self.falling);
|
||||
for f in &mut falling {
|
||||
if let Ok(FallStep::Landed(_)) = self.fall_step(f, false) {
|
||||
// Block.updateEntityMovementAfterFallOn, then the air drag.
|
||||
f.velocity = Vec3::new(f.velocity.x * 0.98, 0.0, f.velocity.z * 0.98);
|
||||
}
|
||||
}
|
||||
self.falling = falling;
|
||||
for p in &mut self.creatures.projectiles {
|
||||
p.previous = p.position;
|
||||
p.age += 1;
|
||||
|
||||
@@ -814,7 +814,7 @@ pub fn carry(
|
||||
if kind == "structure" {
|
||||
let path = rel.trim_start_matches("worldgen/structure/");
|
||||
let structure = format!("{ns}:{}", path.trim_end_matches(".json"));
|
||||
changed |= crate::worldgen::disables(&structure, &mut v);
|
||||
changed |= crate::legacy_structure_mods::yung::disables(&structure, &mut v);
|
||||
changed |=
|
||||
crate::worldgen::add_piece_counts(&structure, &mut v, &piece_counts);
|
||||
}
|
||||
@@ -829,9 +829,9 @@ pub fn carry(
|
||||
// Additions to other sets and pools, as files the game merges.
|
||||
let modifier = serde_json::from_slice::<Value>(&bytes).ok();
|
||||
let types = &mut report.worldgen_types;
|
||||
if let Some((kind, mut added)) =
|
||||
modifier.and_then(|v| crate::worldgen::modifier(&v, loaded, types))
|
||||
{
|
||||
if let Some((kind, mut added)) = modifier.and_then(|v| {
|
||||
crate::legacy_structure_mods::lithostitched::modifier(&v, loaded, types)
|
||||
}) {
|
||||
crate::processors::carry(
|
||||
kind,
|
||||
&mut added,
|
||||
@@ -910,7 +910,7 @@ pub fn carry(
|
||||
}
|
||||
// Entries the mod adds to other structure sets in Java code, for the
|
||||
// structures it has.
|
||||
for (file, set, entries) in crate::worldgen::code_set_entries(id) {
|
||||
for (file, set, entries) in crate::legacy_structure_mods::ctov::code_set_entries(id) {
|
||||
let entries: Vec<Value> = entries
|
||||
.into_iter()
|
||||
.filter(|(s, _)| {
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
//! Choice Theorem's Overhauled Village: the entries it adds to other
|
||||
//! structure sets in Java code, and its `modular_compat` processor.
|
||||
use crate::processors::{ProcessorData, referenced};
|
||||
use serde_json::Value;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// ChoiceTheorem's Overhauled Village's villages and outposts, which it adds
|
||||
/// to vanilla's `villages` and `pillager_outposts` sets in Java code
|
||||
/// (`CTOV.registerstructure`, through lithostitched), with its default
|
||||
/// config: every village type in three sizes, weighted 10, 4 and 1, and
|
||||
/// every outpost weighted 1. Vanilla's own entries stay (weight 1 each).
|
||||
const CTOV_VILLAGES: [&str; 21] = [
|
||||
"beach",
|
||||
"christmas",
|
||||
"desert",
|
||||
"desert_oasis",
|
||||
"dark_forest",
|
||||
"jungle",
|
||||
"jungle_tree",
|
||||
"mesa",
|
||||
"mesa_fortified",
|
||||
"mountain",
|
||||
"mountain_alpine",
|
||||
"mushroom",
|
||||
"plains",
|
||||
"plains_fortified",
|
||||
"savanna",
|
||||
"savanna_na",
|
||||
"snowy_igloo",
|
||||
"swamp",
|
||||
"swamp_fortified",
|
||||
"taiga",
|
||||
"taiga_fortified",
|
||||
];
|
||||
const CTOV_OUTPOSTS: [&str; 11] = [
|
||||
"beach",
|
||||
"dark_forest",
|
||||
"desert",
|
||||
"jungle",
|
||||
"badlands",
|
||||
"mountain",
|
||||
"plains",
|
||||
"savanna",
|
||||
"snowy",
|
||||
"swamp",
|
||||
"taiga",
|
||||
];
|
||||
|
||||
/// The entries a mod adds to other structure sets in Java code, as its
|
||||
/// default config has them: (file name, set, `[(structure, weight)]`).
|
||||
/// Lithostitched appends them in the order of a hash map of every modifier
|
||||
/// in the pack, which carry cannot know; they are written in the order the
|
||||
/// mod registers them. Each set picks by weight, so how often each starts
|
||||
/// is the same.
|
||||
pub(crate) fn code_set_entries(
|
||||
mod_id: &str,
|
||||
) -> Vec<(&'static str, &'static str, Vec<(String, u32)>)> {
|
||||
match mod_id {
|
||||
"ctov" => {
|
||||
let outposts = CTOV_OUTPOSTS
|
||||
.iter()
|
||||
.map(|v| (format!("ctov:pillager_outpost_{v}"), 1))
|
||||
.collect();
|
||||
let villages = [("small", 10), ("medium", 4), ("large", 1)]
|
||||
.into_iter()
|
||||
.flat_map(|(size, weight)| {
|
||||
CTOV_VILLAGES
|
||||
.iter()
|
||||
.map(move |v| (format!("ctov:{size}/village_{v}"), weight))
|
||||
})
|
||||
.collect();
|
||||
vec![
|
||||
("pillager_outposts", "minecraft:pillager_outposts", outposts),
|
||||
("villages", "minecraft:villages", villages),
|
||||
]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Choice Theorem's Overhauled Village's processor that runs the list
|
||||
/// `reference` when mod `modid` is loaded (ModularCompatProcessor).
|
||||
const MODULAR_COMPAT: &str = "ctov:modular_compat";
|
||||
|
||||
/// Notes which mods its compat processors name are `loaded`.
|
||||
pub(crate) fn mark_loaded(data: &mut ProcessorData, loaded: &dyn Fn(&str) -> bool) {
|
||||
fn walk(v: &Value, out: &mut BTreeSet<String>) {
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("processor_type").and_then(Value::as_str) == Some(MODULAR_COMPAT) {
|
||||
if let Some(id) = o.get("modid").and_then(Value::as_str) {
|
||||
out.insert(id.to_owned());
|
||||
}
|
||||
}
|
||||
o.values().for_each(|v| walk(v, out));
|
||||
}
|
||||
Value::Array(a) => a.iter().for_each(|v| walk(v, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut named = BTreeSet::new();
|
||||
data.lists.values().for_each(|l| walk(l, &mut named));
|
||||
data.compat_loaded = named.into_iter().filter(|m| loaded(m)).collect();
|
||||
}
|
||||
|
||||
/// A `ctov:modular_compat` processor in a list being carried, at `depth`
|
||||
/// (see [`super::lithostitched`]'s references): counted in `carried`, and
|
||||
/// the processors of the list it names when its mod is loaded, else none.
|
||||
/// `None` for any other processor, or past the depth limit.
|
||||
pub(super) fn modular_compat(
|
||||
p: &Value,
|
||||
data: &ProcessorData,
|
||||
carried: &mut BTreeMap<String, usize>,
|
||||
depth: usize,
|
||||
) -> Option<Vec<Value>> {
|
||||
if p["processor_type"] != MODULAR_COMPAT || depth >= 8 {
|
||||
return None;
|
||||
}
|
||||
*carried.entry(MODULAR_COMPAT.into()).or_default() += 1;
|
||||
let loaded = p["modid"]
|
||||
.as_str()
|
||||
.is_some_and(|m| data.compat_loaded.contains(m));
|
||||
Some(
|
||||
loaded
|
||||
.then(|| referenced(&p["reference"], data))
|
||||
.flatten()
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::processors::carry;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn ctov_joins_vanillas_villages_and_outposts() {
|
||||
let sets = code_set_entries("ctov");
|
||||
let (file, set, outposts) = &sets[0];
|
||||
assert_eq!(
|
||||
(*file, *set),
|
||||
("pillager_outposts", "minecraft:pillager_outposts")
|
||||
);
|
||||
assert_eq!(outposts.len(), 11);
|
||||
assert!(outposts.iter().all(|(_, w)| *w == 1));
|
||||
let (_, set, villages) = &sets[1];
|
||||
assert_eq!(*set, "minecraft:villages");
|
||||
assert_eq!(villages.len(), 63);
|
||||
assert_eq!(villages[0], ("ctov:small/village_beach".into(), 10));
|
||||
assert_eq!(villages[21], ("ctov:medium/village_beach".into(), 4));
|
||||
assert_eq!(
|
||||
villages[62],
|
||||
("ctov:large/village_taiga_fortified".into(), 1)
|
||||
);
|
||||
assert!(code_set_entries("mvs").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modular_compat_runs_its_list_only_with_its_mod() {
|
||||
let mut data = ProcessorData::default();
|
||||
let swap = json!({"processor_type": "minecraft:rule", "rules": []});
|
||||
data.lists
|
||||
.insert("v:house_ns".into(), json!({"processors": [swap.clone()]}));
|
||||
let compat = |m: &str| json!({"processor_type": "ctov:modular_compat", "modid": m, "reference": "v:house_ns"});
|
||||
let gravity = json!({"processor_type": "minecraft:gravity"});
|
||||
data.lists.insert(
|
||||
"v:house".into(),
|
||||
json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}),
|
||||
);
|
||||
data.mark_loaded(&|m| m == "ns");
|
||||
assert_eq!(data.compat_loaded, BTreeSet::from(["ns".to_owned()]));
|
||||
let mut v = json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]});
|
||||
let mut carried = BTreeMap::new();
|
||||
assert!(carry("processor_list", &mut v, &data, &mut carried));
|
||||
assert_eq!(v, json!({"processors": [swap, gravity]}));
|
||||
assert_eq!(carried["ctov:modular_compat"], 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
//! Lithostitched: its jigsaw structure, its worldgen modifiers and its
|
||||
//! processors.
|
||||
use super::ctov;
|
||||
use crate::processors::{ProcessorData, carry_all, processors, referenced};
|
||||
use crate::worldgen::{ENHANCED_TERRAIN, Upgrade, start_checks};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// A `structure` file of Lithostitched's jigsaw type as vanilla's, with the
|
||||
/// start rules it shares with the other libraries' jigsaws (`worldgen`'s
|
||||
/// `start_checks`). `None` for any other file.
|
||||
pub(crate) fn upgrade(
|
||||
kind: &str,
|
||||
v: &mut Value,
|
||||
lost: &mut BTreeMap<String, usize>,
|
||||
) -> Option<bool> {
|
||||
if kind != "structure" || v["type"] != "lithostitched:jigsaw" {
|
||||
return None;
|
||||
}
|
||||
start_checks(v, "lowest", lost, false);
|
||||
if v.as_object_mut()
|
||||
.and_then(|o| o.remove(ENHANCED_TERRAIN))
|
||||
.is_some()
|
||||
{
|
||||
*lost.entry(ENHANCED_TERRAIN.into()).or_default() += 1;
|
||||
}
|
||||
v["type"] = "minecraft:jigsaw".into();
|
||||
Some(true)
|
||||
}
|
||||
|
||||
/// A lithostitched worldgen modifier
|
||||
/// (`data/<ns>/lithostitched/worldgen_modifier/`) that adds to structure
|
||||
/// sets or template pools, as a file the game merges into them (the key
|
||||
/// `horizon:add_to`, `horizon_client::mod_content`): (kind, file). The
|
||||
/// modifier's conditions are checked against `loaded`, the mods ported
|
||||
/// along: a compat addition for a mod that is not would place that mod's
|
||||
/// blocks, which the game does not have. Other modifier types are left out.
|
||||
/// Both are counted in `report`.
|
||||
pub(crate) fn modifier(
|
||||
v: &Value,
|
||||
loaded: &dyn Fn(&str) -> bool,
|
||||
report: &mut Upgrade,
|
||||
) -> Option<(&'static str, Value)> {
|
||||
let t = v["type"].as_str().unwrap_or_default();
|
||||
let mut left = |why: &str| *report.modifiers_left.entry(why.to_owned()).or_default() += 1;
|
||||
let (kind, targets, from, to) = match t {
|
||||
"lithostitched:add_structure_set_entries" => {
|
||||
("structure_set", "structure_sets", "entries", "structures")
|
||||
}
|
||||
"lithostitched:add_template_pool_elements" => {
|
||||
("template_pool", "template_pools", "elements", "elements")
|
||||
}
|
||||
_ => {
|
||||
left(t);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if !conditions_hold(v, loaded) {
|
||||
left("conditions");
|
||||
return None;
|
||||
}
|
||||
let targets: Option<Vec<&str>> = match &v[targets] {
|
||||
Value::String(s) => Some(vec![s.as_str()]),
|
||||
Value::Array(a) => a.iter().map(Value::as_str).collect(),
|
||||
_ => None,
|
||||
};
|
||||
let Some(targets) = targets.filter(|t| !t.is_empty() && t.iter().all(|t| !t.starts_with('#')))
|
||||
else {
|
||||
left("target");
|
||||
return None;
|
||||
};
|
||||
let entries = v[from].as_array().cloned().unwrap_or_default();
|
||||
for target in &targets {
|
||||
*report.added_to.entry((*target).to_owned()).or_default() += entries.len();
|
||||
}
|
||||
Some((
|
||||
kind,
|
||||
serde_json::json!({"horizon:add_to": targets, to: entries}),
|
||||
))
|
||||
}
|
||||
|
||||
/// Whether a modifier's load conditions hold: lithostitched's `predicate`,
|
||||
/// and the loader's conditions (NeoForge's, else Fabric's). A condition
|
||||
/// type not known here does not hold.
|
||||
fn conditions_hold(v: &Value, loaded: &dyn Fn(&str) -> bool) -> bool {
|
||||
let all = |list: &Value, test: &dyn Fn(&Value) -> bool| {
|
||||
list.as_array().is_some_and(|a| a.iter().all(test))
|
||||
};
|
||||
fn predicate(p: &Value, loaded: &dyn Fn(&str) -> bool) -> bool {
|
||||
let test = |q: &Value| predicate(q, loaded);
|
||||
let list = &p["predicates"];
|
||||
match p["type"]
|
||||
.as_str()
|
||||
.map(|t| t.trim_start_matches("lithostitched:"))
|
||||
{
|
||||
Some("true") => true,
|
||||
Some("mod_loaded") => p["mod_id"].as_str().is_some_and(loaded),
|
||||
Some("not") => !predicate(&p["predicate"], loaded),
|
||||
Some("all_of") => list.as_array().is_some_and(|a| a.iter().all(test)),
|
||||
Some("any_of") => list.as_array().is_some_and(|a| a.iter().any(test)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn neoforge(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool {
|
||||
let test = |q: &Value| neoforge(q, loaded);
|
||||
match c["type"].as_str() {
|
||||
Some("neoforge:true") => true,
|
||||
Some("neoforge:mod_loaded") => c["modid"].as_str().is_some_and(loaded),
|
||||
Some("neoforge:not") => !neoforge(&c["value"], loaded),
|
||||
Some("neoforge:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)),
|
||||
Some("neoforge:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn fabric(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool {
|
||||
let test = |q: &Value| fabric(q, loaded);
|
||||
let mods = || {
|
||||
c["values"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(Value::as_str)
|
||||
};
|
||||
match c["condition"].as_str() {
|
||||
Some("fabric:true") => true,
|
||||
Some("fabric:all_mods_loaded") => mods().all(|m| m.is_some_and(loaded)),
|
||||
Some("fabric:any_mods_loaded") => mods().any(|m| m.is_some_and(loaded)),
|
||||
Some("fabric:not") => !fabric(&c["value"], loaded),
|
||||
Some("fabric:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)),
|
||||
Some("fabric:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
let litho = v.get("predicate").is_none_or(|p| predicate(p, loaded));
|
||||
let loader = match (
|
||||
v.get("neoforge:conditions"),
|
||||
v.get("fabric:load_conditions"),
|
||||
) {
|
||||
(Some(c), _) => all(c, &|c| neoforge(c, loaded)),
|
||||
// One condition or a list of them.
|
||||
(None, Some(c)) if c.is_array() => all(c, &|c| fabric(c, loaded)),
|
||||
(None, Some(c)) => fabric(c, loaded),
|
||||
(None, None) => true,
|
||||
};
|
||||
litho && loader
|
||||
}
|
||||
|
||||
/// The data form of one of Lithostitched's processors: the processors to put
|
||||
/// in its place, or `None` when it has none (or is not Lithostitched's).
|
||||
pub(crate) fn processor(
|
||||
kind: &str,
|
||||
p: &Value,
|
||||
data: &ProcessorData,
|
||||
carried: &mut BTreeMap<String, usize>,
|
||||
) -> Option<Vec<Value>> {
|
||||
match kind {
|
||||
"lithostitched:apply_random" => apply_random(p, data, carried).map(|p| vec![p]),
|
||||
"lithostitched:condition" => condition(p, data, carried).map(|p| vec![p]),
|
||||
"lithostitched:block_swap" => {
|
||||
// The same map; the game's swap keeps the properties both have.
|
||||
p["blocks"].as_object()?;
|
||||
Some(vec![
|
||||
json!({"processor_type": "horizon:block_swap", "blocks": p["blocks"]}),
|
||||
])
|
||||
}
|
||||
"lithostitched:set_block" => {
|
||||
// A simple or weighted state provider, the block entity left as
|
||||
// it is.
|
||||
let provider = p["state_provider"]["type"].as_str()?;
|
||||
let modifier = p["block_entity_modifier"]["type"].as_str();
|
||||
let plain =
|
||||
modifier.is_none_or(|m| m.trim_start_matches("minecraft:") == "passthrough");
|
||||
if !plain
|
||||
|| !matches!(
|
||||
provider,
|
||||
"minecraft:simple_state_provider" | "minecraft:weighted_state_provider"
|
||||
)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut out = p.clone();
|
||||
out["processor_type"] = "horizon:set_block".into();
|
||||
if let Some(o) = out.as_object_mut() {
|
||||
o.remove("block_entity_modifier");
|
||||
}
|
||||
Some(vec![out])
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The references (Lithostitched's, and CTOV's compat processors) in a
|
||||
/// processor list written in; whether any was.
|
||||
pub(crate) fn expand_references(
|
||||
list: Vec<Value>,
|
||||
data: &ProcessorData,
|
||||
carried: &mut BTreeMap<String, usize>,
|
||||
) -> (Vec<Value>, bool) {
|
||||
references(list, data, carried, 0)
|
||||
}
|
||||
|
||||
/// A processor list inside a carried processor: an id stays (the game reads
|
||||
/// that file, carried on its own); an inline one is carried here.
|
||||
fn nested(list: &Value, data: &ProcessorData, carried: &mut BTreeMap<String, usize>) -> Value {
|
||||
let mut list = list.clone();
|
||||
if let Some(ps) = processors(&mut list) {
|
||||
*ps = carry_all(std::mem::take(ps), data, carried).0;
|
||||
}
|
||||
list
|
||||
}
|
||||
|
||||
/// Lithostitched's `apply_random` as `horizon:apply_random`: its weighted
|
||||
/// lists, or its set of lists at weight 1. A tag is not carried.
|
||||
fn apply_random(
|
||||
p: &Value,
|
||||
data: &ProcessorData,
|
||||
carried: &mut BTreeMap<String, usize>,
|
||||
) -> Option<Value> {
|
||||
let lists = &p["processor_lists"];
|
||||
let weighted = lists.as_array().is_some_and(|a| {
|
||||
a.iter()
|
||||
.all(|e| e.get("weight").is_some() && e.get("data").is_some())
|
||||
});
|
||||
let entries: Vec<(Value, Value)> = if weighted {
|
||||
lists
|
||||
.as_array()?
|
||||
.iter()
|
||||
.map(|e| (e["weight"].clone(), e["data"].clone()))
|
||||
.collect()
|
||||
} else {
|
||||
match lists {
|
||||
Value::String(id) if !id.starts_with('#') => vec![(1.into(), lists.clone())],
|
||||
Value::Array(a) if a.iter().any(|x| x.get("processor_type").is_some()) => {
|
||||
vec![(1.into(), lists.clone())]
|
||||
}
|
||||
Value::Array(a)
|
||||
if a.iter()
|
||||
.all(|x| x.as_str().is_some_and(|s| !s.starts_with('#')) || x.is_object()) =>
|
||||
{
|
||||
a.iter().map(|x| (1.into(), x.clone())).collect()
|
||||
}
|
||||
Value::Object(_) => vec![(1.into(), lists.clone())],
|
||||
_ => return None,
|
||||
}
|
||||
};
|
||||
let lists: Vec<Value> = entries
|
||||
.into_iter()
|
||||
.map(|(weight, list)| json!({"weight": weight, "data": nested(&list, data, carried)}))
|
||||
.collect();
|
||||
let mut out = json!({"processor_type": "horizon:apply_random", "processor_lists": lists});
|
||||
if let Some(mode) = p.get("mode") {
|
||||
out["mode"] = mode.clone();
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Lithostitched's `condition` as `horizon:condition`, when the game runs
|
||||
/// every condition in it (true, all_of, any_of, not, random_chance,
|
||||
/// matching_blocks with plain property values); else it stays Java.
|
||||
fn condition(
|
||||
p: &Value,
|
||||
data: &ProcessorData,
|
||||
carried: &mut BTreeMap<String, usize>,
|
||||
) -> Option<Value> {
|
||||
fn runs(c: &Value) -> bool {
|
||||
if let Some(all) = c.as_array() {
|
||||
return all.iter().all(runs);
|
||||
}
|
||||
let kind = c["type"].as_str().unwrap_or_default();
|
||||
match kind.strip_prefix("lithostitched:").unwrap_or(kind) {
|
||||
"true" | "random_chance" => true,
|
||||
"all_of" | "any_of" => c["conditions"]
|
||||
.as_array()
|
||||
.is_some_and(|a| a.iter().all(runs)),
|
||||
"not" => runs(&c["condition"]),
|
||||
"matching_blocks" => c.get("properties").is_none_or(|p| {
|
||||
p.as_object()
|
||||
.is_some_and(|o| o.values().all(Value::is_string))
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
if !runs(&p["if_true"]) {
|
||||
return None;
|
||||
}
|
||||
// One processor or a list of them.
|
||||
let mut branch = |key: &str| -> Value {
|
||||
let list = match p.get(key) {
|
||||
None => Vec::new(),
|
||||
Some(Value::Array(a)) => a.clone(),
|
||||
Some(one) => vec![one.clone()],
|
||||
};
|
||||
carry_all(list, data, carried).0.into()
|
||||
};
|
||||
let (then, otherwise) = (branch("then"), branch("else"));
|
||||
let mut out = json!({"processor_type": "horizon:condition", "if_true": p["if_true"],
|
||||
"then": then, "else": otherwise});
|
||||
if let Some(mode) = p.get("random_mode") {
|
||||
out["random_mode"] = mode.clone();
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Lithostitched's references in a list, each replaced by the processors of
|
||||
/// the lists it names, in order (references in them too, to a depth of 8).
|
||||
/// One naming a tag or a list the mod does not have stays, to be dropped.
|
||||
/// Whether any was replaced.
|
||||
fn references(
|
||||
list: Vec<Value>,
|
||||
data: &ProcessorData,
|
||||
carried: &mut BTreeMap<String, usize>,
|
||||
depth: usize,
|
||||
) -> (Vec<Value>, bool) {
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
let mut changed = false;
|
||||
for p in list {
|
||||
if let Some(inner) = ctov::modular_compat(&p, data, carried, depth) {
|
||||
changed = true;
|
||||
out.extend(references(inner, data, carried, depth + 1).0);
|
||||
continue;
|
||||
}
|
||||
let named = (p["processor_type"] == "lithostitched:reference" && depth < 8)
|
||||
.then(|| referenced(&p["processor_lists"], data))
|
||||
.flatten();
|
||||
match named {
|
||||
Some(inner) => {
|
||||
*carried.entry("lithostitched:reference".into()).or_default() += 1;
|
||||
out.extend(references(inner, data, carried, depth + 1).0);
|
||||
changed = true;
|
||||
}
|
||||
None => out.push(p),
|
||||
}
|
||||
}
|
||||
(out, changed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::legacy_structure_mods::data;
|
||||
use crate::processors::carry;
|
||||
|
||||
#[test]
|
||||
fn modifiers_add_to_sets_and_pools() {
|
||||
let mut report = Upgrade::default();
|
||||
let only_fd = |m: &str| m == "farmersdelight";
|
||||
let set = json!({"type": "lithostitched:add_structure_set_entries",
|
||||
"structure_sets": "minecraft:villages",
|
||||
"entries": [{"structure": "x:village", "weight": 4}]});
|
||||
let (kind, added) = modifier(&set, &only_fd, &mut report).unwrap();
|
||||
assert_eq!(kind, "structure_set");
|
||||
assert_eq!(
|
||||
added,
|
||||
json!({"horizon:add_to": ["minecraft:villages"],
|
||||
"structures": [{"structure": "x:village", "weight": 4}]})
|
||||
);
|
||||
// A compat addition holds only when its mod is ported along.
|
||||
let pool = |modid: &str| {
|
||||
json!({"type": "lithostitched:add_template_pool_elements",
|
||||
"neoforge:conditions": [{"type": "neoforge:mod_loaded", "modid": modid}],
|
||||
"fabric:load_conditions": {"condition": "fabric:all_mods_loaded", "values": ["other"]},
|
||||
"template_pools": ["x:houses", "y:houses"],
|
||||
"elements": [{"weight": 5, "element": {"element_type": "minecraft:single_pool_element",
|
||||
"location": "x:fd_farm", "projection": "rigid", "processors": "minecraft:empty"}}]})
|
||||
};
|
||||
let (kind, added) = modifier(&pool("farmersdelight"), &only_fd, &mut report).unwrap();
|
||||
assert_eq!(kind, "template_pool");
|
||||
assert_eq!(added["horizon:add_to"], json!(["x:houses", "y:houses"]));
|
||||
assert_eq!(added["elements"][0]["weight"], 5);
|
||||
assert!(modifier(&pool("create"), &only_fd, &mut report).is_none());
|
||||
// Fabric's conditions when there are no NeoForge ones; lithostitched's own.
|
||||
let fabric = json!({"type": "lithostitched:add_structure_set_entries",
|
||||
"fabric:load_conditions": [{"condition": "fabric:not",
|
||||
"value": {"condition": "fabric:any_mods_loaded", "values": ["create"]}}],
|
||||
"predicate": {"type": "lithostitched:all_of", "predicates": [
|
||||
{"type": "lithostitched:mod_loaded", "mod_id": "farmersdelight"},
|
||||
{"type": "lithostitched:true"}]},
|
||||
"structure_sets": "minecraft:villages", "entries": []});
|
||||
assert!(modifier(&fabric, &only_fd, &mut report).is_some());
|
||||
let tagged = json!({"type": "lithostitched:add_structure_set_entries",
|
||||
"structure_sets": "#x:sets", "entries": []});
|
||||
assert!(modifier(&tagged, &only_fd, &mut report).is_none());
|
||||
let features = json!({"type": "lithostitched:add_features"});
|
||||
assert!(modifier(&features, &only_fd, &mut report).is_none());
|
||||
assert_eq!(
|
||||
report.added_to,
|
||||
BTreeMap::from([
|
||||
("minecraft:villages".into(), 1),
|
||||
("x:houses".into(), 1),
|
||||
("y:houses".into(), 1),
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
report.modifiers_left,
|
||||
BTreeMap::from([
|
||||
("conditions".into(), 1),
|
||||
("lithostitched:add_features".into(), 1),
|
||||
("target".into(), 1),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lithostitched_block_swaps_become_the_games() {
|
||||
let mut list = json!({"processors": [
|
||||
{"processor_type": "lithostitched:block_swap",
|
||||
"blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}},
|
||||
{"processor_type": "lithostitched:block_swap", "blocks": []}]});
|
||||
let mut carried = BTreeMap::new();
|
||||
assert!(carry("processor_list", &mut list, &data(), &mut carried));
|
||||
let p = list["processors"].as_array().unwrap();
|
||||
assert_eq!(
|
||||
p[0],
|
||||
json!({"processor_type": "horizon:block_swap",
|
||||
"blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}})
|
||||
);
|
||||
// A map that is not one stays Java (dropped later).
|
||||
assert_eq!(p[1]["processor_type"], "lithostitched:block_swap");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lithostitched_references_are_written_in() {
|
||||
let mut data = data();
|
||||
let gravity = json!({"processor_type": "minecraft:gravity", "heightmap": "WORLD_SURFACE_WG", "offset": 0});
|
||||
data.lists
|
||||
.insert("v:road".into(), json!({"processors": [gravity.clone()]}));
|
||||
data.lists.insert(
|
||||
"v:house".into(),
|
||||
json!({"processors": [
|
||||
{"processor_type": "lithostitched:reference", "processor_lists": "v:road"},
|
||||
{"processor_type": "lithostitched:block_swap", "blocks": {"minecraft:dirt": "minecraft:grass_block"}}]}),
|
||||
);
|
||||
let mut list = json!({"processors": [
|
||||
{"processor_type": "lithostitched:reference", "processor_lists": ["v:house", "v:road"]},
|
||||
{"processor_type": "lithostitched:reference", "processor_lists": "#v:roads"},
|
||||
{"processor_type": "lithostitched:reference", "processor_lists": ["v:nowhere"]}]});
|
||||
let mut carried = BTreeMap::new();
|
||||
assert!(carry("processor_list", &mut list, &data, &mut carried));
|
||||
let p = list["processors"].as_array().unwrap();
|
||||
// House (its own reference to road first, then its swap), then road;
|
||||
// the swap inside is carried too.
|
||||
assert_eq!(p[0], gravity);
|
||||
assert_eq!(p[1]["processor_type"], "horizon:block_swap");
|
||||
assert_eq!(p[2], gravity);
|
||||
// A tag or a list the mod lacks stays, to be dropped.
|
||||
assert_eq!(p[3]["processor_lists"], "#v:roads");
|
||||
assert_eq!(p[4]["processor_lists"], json!(["v:nowhere"]));
|
||||
assert_eq!(carried["lithostitched:reference"], 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lithostitched_random_and_condition_become_the_games() {
|
||||
let mut data = data();
|
||||
let swap = json!({"processor_type": "lithostitched:block_swap",
|
||||
"blocks": {"minecraft:dirt": "minecraft:grass_block"}});
|
||||
data.lists
|
||||
.insert("v:green".into(), json!({"processors": [swap.clone()]}));
|
||||
let mut list = json!({"processors": [
|
||||
{"processor_type": "lithostitched:apply_random", "mode": "per_piece", "processor_lists": [
|
||||
{"weight": 3, "data": "minecraft:empty"},
|
||||
{"weight": 1, "data": {"processors": [
|
||||
{"processor_type": "lithostitched:reference", "processor_lists": "v:green"},
|
||||
{"processor_type": "v:java"}]}}]},
|
||||
{"processor_type": "lithostitched:apply_random", "mode": "per_block",
|
||||
"processor_lists": ["v:green", "v:red"]},
|
||||
{"processor_type": "lithostitched:apply_random", "mode": "per_block",
|
||||
"processor_lists": "#v:colours"},
|
||||
{"processor_type": "lithostitched:condition",
|
||||
"if_true": [{"type": "lithostitched:matching_blocks", "blocks": "minecraft:cobblestone"}],
|
||||
"then": swap, "else": {"processor_type": "lithostitched:set_block", "state_provider":
|
||||
{"type": "minecraft:simple_state_provider", "state": {"Name": "minecraft:stone"}}}},
|
||||
{"processor_type": "lithostitched:condition",
|
||||
"if_true": {"type": "lithostitched:matching_biomes", "biomes": "#c:is_cold"},
|
||||
"then": []}]});
|
||||
let mut carried = BTreeMap::new();
|
||||
assert!(carry("processor_list", &mut list, &data, &mut carried));
|
||||
let p = list["processors"].as_array().unwrap();
|
||||
let green = json!({"processor_type": "horizon:block_swap",
|
||||
"blocks": {"minecraft:dirt": "minecraft:grass_block"}});
|
||||
// Inline lists are carried; Java left in them is dropped later.
|
||||
assert_eq!(
|
||||
p[0],
|
||||
json!({"processor_type": "horizon:apply_random", "mode": "per_piece", "processor_lists": [
|
||||
{"weight": 3, "data": "minecraft:empty"},
|
||||
{"weight": 1, "data": {"processors": [green.clone(), {"processor_type": "v:java"}]}}]})
|
||||
);
|
||||
assert_eq!(
|
||||
p[1]["processor_lists"],
|
||||
json!([{"weight": 1, "data": "v:green"}, {"weight": 1, "data": "v:red"}])
|
||||
);
|
||||
assert_eq!(p[2]["processor_type"], "lithostitched:apply_random");
|
||||
assert_eq!(
|
||||
p[3],
|
||||
json!({"processor_type": "horizon:condition",
|
||||
"if_true": [{"type": "lithostitched:matching_blocks", "blocks": "minecraft:cobblestone"}],
|
||||
"then": [green], "else": [{"processor_type": "horizon:set_block", "state_provider":
|
||||
{"type": "minecraft:simple_state_provider", "state": {"Name": "minecraft:stone"}}}]})
|
||||
);
|
||||
assert_eq!(p[4]["processor_type"], "lithostitched:condition");
|
||||
assert_eq!(carried["lithostitched:apply_random"], 2);
|
||||
assert_eq!(carried["lithostitched:condition"], 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
//! The conversion of three families of structure mods' data, kept apart from
|
||||
//! the general conversion code (`worldgen`, `processors`, `carry`):
|
||||
//!
|
||||
//! - [`yung`]: YUNG's API and the mods built on it (Better Dungeons, Desert
|
||||
//! Temples, Jungle Temples, Witch Huts, Ocean Monuments, Strongholds,
|
||||
//! Fortresses, Mineshafts), written under `horizon:yungsapi` and the other
|
||||
//! keys `horizon_world::worldgen::structure::yung` reads.
|
||||
//! - [`lithostitched`]: Lithostitched's jigsaw, worldgen modifiers and
|
||||
//! processors.
|
||||
//! - [`ctov`]: Choice Theorem's Overhauled Village's code-registered set
|
||||
//! entries and its modular compat processor.
|
||||
//!
|
||||
//! The general code reaches them only through the `pub(crate)` entry points
|
||||
//! of these three modules. Nothing in them is used by another mod's
|
||||
//! conversion.
|
||||
pub(crate) mod ctov;
|
||||
pub(crate) mod lithostitched;
|
||||
pub(crate) mod yung;
|
||||
|
||||
#[cfg(test)]
|
||||
fn data() -> crate::processors::ProcessorData {
|
||||
let mut d = crate::processors::ProcessorData::default();
|
||||
d.spawners.insert(
|
||||
"repurposed_structures:dungeons/badlands".into(),
|
||||
vec![
|
||||
("minecraft:husk".into(), 10.),
|
||||
("minecraft:cave_spider".into(), 3.),
|
||||
],
|
||||
);
|
||||
d.replace_vanilla.insert(("mvs".into(), "village".into()));
|
||||
d
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -13,6 +13,7 @@ pub mod fetch;
|
||||
pub mod import;
|
||||
pub mod inventory;
|
||||
pub mod jar;
|
||||
pub(crate) mod legacy_structure_mods;
|
||||
pub mod modrinth;
|
||||
pub mod oracle;
|
||||
pub mod pipeline;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -13,6 +13,11 @@
|
||||
//! by name. Each rewrite is counted in the carry report, and every type left
|
||||
//! as it is is listed, so the coverage report can say what generates and how
|
||||
//! closely.
|
||||
//!
|
||||
//! YUNG's, Lithostitched's and CTOV's worldgen files are converted by
|
||||
//! `legacy_structure_mods`, called from [`upgrade`], [`crate::carry`] and the
|
||||
//! processors.
|
||||
use crate::legacy_structure_mods::{lithostitched, yung};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
@@ -21,8 +26,7 @@ use std::{
|
||||
};
|
||||
|
||||
/// Structure types that are vanilla's jigsaw with extra start rules.
|
||||
const JIGSAWS: [&str; 3] = [
|
||||
"lithostitched:jigsaw",
|
||||
const JIGSAWS: [&str; 2] = [
|
||||
"moogs_structures:moogs_structures_generic_jigsaw_structure",
|
||||
"repurposed_structures:generic_jigsaw_structure",
|
||||
];
|
||||
@@ -57,35 +61,6 @@ const SPREADS: [&str; 2] = [
|
||||
"moogs_structures:advanced_random_spread",
|
||||
"repurposed_structures:advanced_random_spread",
|
||||
];
|
||||
/// YUNG's placements: vanilla's random spread with an enhanced exclusion
|
||||
/// zone (several sets), plus, for the temples, no start near an ocean or a
|
||||
/// river, and for strongholds, starts only in odd rings around the origin.
|
||||
const YUNG_SPREADS: [&str; 4] = [
|
||||
"yungsapi:enhanced_random_spread",
|
||||
"betterdeserttemples:desert_temple",
|
||||
"betterjungletemples:jungle_temple",
|
||||
"betterstrongholds:stronghold",
|
||||
];
|
||||
/// YUNG's structures and the vanilla structure type each one's mod turns
|
||||
/// off (its DisableVanilla*Mixin, on by default in each mod's config).
|
||||
const YUNG_REPLACES: [(&str, &str); 7] = [
|
||||
(
|
||||
"betterdeserttemples:desert_temple",
|
||||
"minecraft:desert_pyramid",
|
||||
),
|
||||
(
|
||||
"betterjungletemples:jungle_temple",
|
||||
"minecraft:jungle_temple",
|
||||
),
|
||||
("betterwitchhuts:witch_hut", "minecraft:swamp_hut"),
|
||||
(
|
||||
"betteroceanmonuments:ocean_monument",
|
||||
"minecraft:ocean_monument",
|
||||
),
|
||||
("betterstrongholds:stronghold", "minecraft:stronghold"),
|
||||
("betterfortresses:fortress", "minecraft:fortress"),
|
||||
("bettermineshafts:mineshaft_", "minecraft:mineshaft"),
|
||||
];
|
||||
/// Mo' Structures' placement (`mostructures:type`) takes its spacing and
|
||||
/// separation from the mod's config, not its files: the defaults it writes
|
||||
/// (MoStructuresConfig), by config key, as (spacing, separation).
|
||||
@@ -130,8 +105,8 @@ const LAYOUT_RULES: [&str; 4] = [
|
||||
];
|
||||
/// The libraries' terrain kernel field, the game's
|
||||
/// `horizon:enhanced_terrain_adaptation` (docs/mods.md).
|
||||
const ENHANCED_TERRAIN: &str = "enhanced_terrain_adaptation";
|
||||
const HORIZON_ENHANCED_TERRAIN: &str = "horizon:enhanced_terrain_adaptation";
|
||||
pub(crate) const ENHANCED_TERRAIN: &str = "enhanced_terrain_adaptation";
|
||||
pub(crate) const HORIZON_ENHANCED_TERRAIN: &str = "horizon:enhanced_terrain_adaptation";
|
||||
/// Fields of older versions the mods' codecs no longer read: their own
|
||||
/// structures ignore them, and so does carry. Repurposed's jungle fortress
|
||||
/// and End stronghold still write `vertical_distance_from_start_piece`.
|
||||
@@ -181,195 +156,6 @@ pub struct Upgrade {
|
||||
/// `data/<id>/worldgen/<kind>/horizon_added/<name>.json`.
|
||||
pub const ADDED: &str = "horizon_added";
|
||||
|
||||
/// A lithostitched worldgen modifier
|
||||
/// (`data/<ns>/lithostitched/worldgen_modifier/`) that adds to structure
|
||||
/// sets or template pools, as a file the game merges into them (the key
|
||||
/// `horizon:add_to`, `horizon_client::mod_content`): (kind, file). The
|
||||
/// modifier's conditions are checked against `loaded`, the mods ported
|
||||
/// along: a compat addition for a mod that is not would place that mod's
|
||||
/// blocks, which the game does not have. Other modifier types are left out.
|
||||
/// Both are counted in `report`.
|
||||
pub fn modifier(
|
||||
v: &Value,
|
||||
loaded: &dyn Fn(&str) -> bool,
|
||||
report: &mut Upgrade,
|
||||
) -> Option<(&'static str, Value)> {
|
||||
let t = v["type"].as_str().unwrap_or_default();
|
||||
let mut left = |why: &str| *report.modifiers_left.entry(why.to_owned()).or_default() += 1;
|
||||
let (kind, targets, from, to) = match t {
|
||||
"lithostitched:add_structure_set_entries" => {
|
||||
("structure_set", "structure_sets", "entries", "structures")
|
||||
}
|
||||
"lithostitched:add_template_pool_elements" => {
|
||||
("template_pool", "template_pools", "elements", "elements")
|
||||
}
|
||||
_ => {
|
||||
left(t);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if !conditions_hold(v, loaded) {
|
||||
left("conditions");
|
||||
return None;
|
||||
}
|
||||
let targets: Option<Vec<&str>> = match &v[targets] {
|
||||
Value::String(s) => Some(vec![s.as_str()]),
|
||||
Value::Array(a) => a.iter().map(Value::as_str).collect(),
|
||||
_ => None,
|
||||
};
|
||||
let Some(targets) = targets.filter(|t| !t.is_empty() && t.iter().all(|t| !t.starts_with('#')))
|
||||
else {
|
||||
left("target");
|
||||
return None;
|
||||
};
|
||||
let entries = v[from].as_array().cloned().unwrap_or_default();
|
||||
for target in &targets {
|
||||
*report.added_to.entry((*target).to_owned()).or_default() += entries.len();
|
||||
}
|
||||
Some((
|
||||
kind,
|
||||
serde_json::json!({"horizon:add_to": targets, to: entries}),
|
||||
))
|
||||
}
|
||||
|
||||
/// Whether a modifier's load conditions hold: lithostitched's `predicate`,
|
||||
/// and the loader's conditions (NeoForge's, else Fabric's). A condition
|
||||
/// type not known here does not hold.
|
||||
fn conditions_hold(v: &Value, loaded: &dyn Fn(&str) -> bool) -> bool {
|
||||
let all = |list: &Value, test: &dyn Fn(&Value) -> bool| {
|
||||
list.as_array().is_some_and(|a| a.iter().all(test))
|
||||
};
|
||||
fn predicate(p: &Value, loaded: &dyn Fn(&str) -> bool) -> bool {
|
||||
let test = |q: &Value| predicate(q, loaded);
|
||||
let list = &p["predicates"];
|
||||
match p["type"]
|
||||
.as_str()
|
||||
.map(|t| t.trim_start_matches("lithostitched:"))
|
||||
{
|
||||
Some("true") => true,
|
||||
Some("mod_loaded") => p["mod_id"].as_str().is_some_and(loaded),
|
||||
Some("not") => !predicate(&p["predicate"], loaded),
|
||||
Some("all_of") => list.as_array().is_some_and(|a| a.iter().all(test)),
|
||||
Some("any_of") => list.as_array().is_some_and(|a| a.iter().any(test)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn neoforge(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool {
|
||||
let test = |q: &Value| neoforge(q, loaded);
|
||||
match c["type"].as_str() {
|
||||
Some("neoforge:true") => true,
|
||||
Some("neoforge:mod_loaded") => c["modid"].as_str().is_some_and(loaded),
|
||||
Some("neoforge:not") => !neoforge(&c["value"], loaded),
|
||||
Some("neoforge:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)),
|
||||
Some("neoforge:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
fn fabric(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool {
|
||||
let test = |q: &Value| fabric(q, loaded);
|
||||
let mods = || {
|
||||
c["values"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(Value::as_str)
|
||||
};
|
||||
match c["condition"].as_str() {
|
||||
Some("fabric:true") => true,
|
||||
Some("fabric:all_mods_loaded") => mods().all(|m| m.is_some_and(loaded)),
|
||||
Some("fabric:any_mods_loaded") => mods().any(|m| m.is_some_and(loaded)),
|
||||
Some("fabric:not") => !fabric(&c["value"], loaded),
|
||||
Some("fabric:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)),
|
||||
Some("fabric:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
let litho = v.get("predicate").is_none_or(|p| predicate(p, loaded));
|
||||
let loader = match (
|
||||
v.get("neoforge:conditions"),
|
||||
v.get("fabric:load_conditions"),
|
||||
) {
|
||||
(Some(c), _) => all(c, &|c| neoforge(c, loaded)),
|
||||
// One condition or a list of them.
|
||||
(None, Some(c)) if c.is_array() => all(c, &|c| fabric(c, loaded)),
|
||||
(None, Some(c)) => fabric(c, loaded),
|
||||
(None, None) => true,
|
||||
};
|
||||
litho && loader
|
||||
}
|
||||
|
||||
/// ChoiceTheorem's Overhauled Village's villages and outposts, which it adds
|
||||
/// to vanilla's `villages` and `pillager_outposts` sets in Java code
|
||||
/// (`CTOV.registerstructure`, through lithostitched), with its default
|
||||
/// config: every village type in three sizes, weighted 10, 4 and 1, and
|
||||
/// every outpost weighted 1. Vanilla's own entries stay (weight 1 each).
|
||||
const CTOV_VILLAGES: [&str; 21] = [
|
||||
"beach",
|
||||
"christmas",
|
||||
"desert",
|
||||
"desert_oasis",
|
||||
"dark_forest",
|
||||
"jungle",
|
||||
"jungle_tree",
|
||||
"mesa",
|
||||
"mesa_fortified",
|
||||
"mountain",
|
||||
"mountain_alpine",
|
||||
"mushroom",
|
||||
"plains",
|
||||
"plains_fortified",
|
||||
"savanna",
|
||||
"savanna_na",
|
||||
"snowy_igloo",
|
||||
"swamp",
|
||||
"swamp_fortified",
|
||||
"taiga",
|
||||
"taiga_fortified",
|
||||
];
|
||||
const CTOV_OUTPOSTS: [&str; 11] = [
|
||||
"beach",
|
||||
"dark_forest",
|
||||
"desert",
|
||||
"jungle",
|
||||
"badlands",
|
||||
"mountain",
|
||||
"plains",
|
||||
"savanna",
|
||||
"snowy",
|
||||
"swamp",
|
||||
"taiga",
|
||||
];
|
||||
|
||||
/// The entries a mod adds to other structure sets in Java code, as its
|
||||
/// default config has them: (file name, set, `[(structure, weight)]`).
|
||||
/// Lithostitched appends them in the order of a hash map of every modifier
|
||||
/// in the pack, which carry cannot know; they are written in the order the
|
||||
/// mod registers them. Each set picks by weight, so how often each starts
|
||||
/// is the same.
|
||||
pub fn code_set_entries(mod_id: &str) -> Vec<(&'static str, &'static str, Vec<(String, u32)>)> {
|
||||
match mod_id {
|
||||
"ctov" => {
|
||||
let outposts = CTOV_OUTPOSTS
|
||||
.iter()
|
||||
.map(|v| (format!("ctov:pillager_outpost_{v}"), 1))
|
||||
.collect();
|
||||
let villages = [("small", 10), ("medium", 4), ("large", 1)]
|
||||
.into_iter()
|
||||
.flat_map(|(size, weight)| {
|
||||
CTOV_VILLAGES
|
||||
.iter()
|
||||
.map(move |v| (format!("ctov:{size}/village_{v}"), weight))
|
||||
})
|
||||
.collect();
|
||||
vec![
|
||||
("pillager_outposts", "minecraft:pillager_outposts", outposts),
|
||||
("villages", "minecraft:villages", villages),
|
||||
]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rewrites one `data/<ns>/worldgen/<kind>/...` file in place; whether it
|
||||
/// changed.
|
||||
/// `set_tags` are the mod's structure set tags, expanded
|
||||
@@ -474,15 +260,16 @@ fn upgrade_types(
|
||||
set_tags: &BTreeMap<String, Vec<String>>,
|
||||
) -> bool {
|
||||
let lost = &mut report.rules_lost;
|
||||
// YUNG's and Lithostitched's types are converted apart from this code.
|
||||
if let Some(changed) =
|
||||
yung::upgrade(kind, v, set_tags, lost).or_else(|| lithostitched::upgrade(kind, v, lost))
|
||||
{
|
||||
report.mapped += usize::from(changed);
|
||||
return changed;
|
||||
}
|
||||
let mut unsupported = |t: &str| *report.unsupported.entry(t.to_owned()).or_default() += 1;
|
||||
let changed = match kind {
|
||||
"structure" => match v["type"].as_str() {
|
||||
// Better Dungeons' small Nether dungeon is YUNG's jigsaw behind a
|
||||
// config switch that ships on.
|
||||
Some("yungsapi:yung_jigsaw" | "betterdungeons:small_nether_dungeon") => {
|
||||
yung_structure(v, lost);
|
||||
true
|
||||
}
|
||||
Some(t)
|
||||
if JIGSAWS.contains(&t)
|
||||
|| NETHER_JIGSAWS.contains(&t)
|
||||
@@ -591,11 +378,6 @@ fn upgrade_types(
|
||||
true
|
||||
}
|
||||
Some("mostructures:type") => mo_placement(&mut v["placement"], lost),
|
||||
Some(t) if YUNG_SPREADS.contains(&t) => {
|
||||
let t = t.to_owned();
|
||||
yung_placement(&t, &mut v["placement"], set_tags, lost);
|
||||
true
|
||||
}
|
||||
Some(t) if !t.starts_with("minecraft:") => {
|
||||
unsupported(t);
|
||||
false
|
||||
@@ -615,6 +397,10 @@ fn upgrade_types(
|
||||
}
|
||||
}
|
||||
for element in elements {
|
||||
if yung::upgrade_pool_element(element, lost) {
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
let Some(t) = element["element_type"].as_str() else {
|
||||
continue;
|
||||
};
|
||||
@@ -629,9 +415,6 @@ fn upgrade_types(
|
||||
}
|
||||
element["element_type"] = (*to).into();
|
||||
changed = true;
|
||||
} else if t == "yungsapi:yung_single_element" {
|
||||
yung_element(element, lost);
|
||||
changed = true;
|
||||
} else if t == "formations:single_pool_element" {
|
||||
// Vanilla's element with its own ground level (1 when
|
||||
// missing, as its codec reads it).
|
||||
@@ -653,167 +436,10 @@ fn upgrade_types(
|
||||
changed
|
||||
}
|
||||
|
||||
/// YUNG's API's jigsaw as vanilla's, laid out by its own assembler in the
|
||||
/// game (`horizon:yungsapi`, `horizon_world::worldgen::structure::yung`):
|
||||
/// the heights pieces stay within move under the key, its terrain
|
||||
/// adaptation under `horizon:enhanced_terrain_adaptation`. A start offset in
|
||||
/// the chunk is lost.
|
||||
fn yung_structure(v: &mut Value, lost: &mut BTreeMap<String, usize>) {
|
||||
let Some(o) = v.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
o.insert("type".into(), "minecraft:jigsaw".into());
|
||||
let mut rules = serde_json::Map::new();
|
||||
for key in ["min_y", "max_y"] {
|
||||
if let Some(y) = o.remove(key) {
|
||||
rules.insert(key.into(), y);
|
||||
}
|
||||
}
|
||||
// YungJigsawStructure's adaptation (NONE by default): every piece's
|
||||
// junctions, and the start's box grown by its radius.
|
||||
let own = o.remove(ENHANCED_TERRAIN);
|
||||
let mut kernel = yung_terrain(own.as_ref().unwrap_or(&Value::Null), lost);
|
||||
kernel["rigid_junctions"] = true.into();
|
||||
kernel["inflate"] = true.into();
|
||||
o.insert(HORIZON_ENHANCED_TERRAIN.into(), kernel);
|
||||
for key in ["x_offset_in_chunk", "z_offset_in_chunk"] {
|
||||
if o.remove(key).is_some_and(|n| n != 0) {
|
||||
*lost.entry(key.into()).or_default() += 1;
|
||||
}
|
||||
}
|
||||
o.insert("horizon:yungsapi".into(), rules.into());
|
||||
}
|
||||
|
||||
/// YUNG's single pool element as vanilla's, its rules under
|
||||
/// `horizon:yungsapi`: name and `max_count`, depth range, priority,
|
||||
/// `ignore_bounds`, its condition, dead-end pool and modifiers; its terrain
|
||||
/// adaptation under `horizon:enhanced_terrain_adaptation`.
|
||||
fn yung_element(element: &mut Value, lost: &mut BTreeMap<String, usize>) {
|
||||
let Some(o) = element.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
o.insert(
|
||||
"element_type".into(),
|
||||
"minecraft:single_pool_element".into(),
|
||||
);
|
||||
let mut rules = serde_json::Map::new();
|
||||
for (from, to) in [
|
||||
("name", "name"),
|
||||
("max_count", "max_count"),
|
||||
("min_required_depth", "min_depth"),
|
||||
("max_possible_depth", "max_depth"),
|
||||
("is_priority", "priority"),
|
||||
("ignore_bounds", "ignore_bounds"),
|
||||
] {
|
||||
if let Some(x) = o.remove(from) {
|
||||
rules.insert(to.into(), x);
|
||||
}
|
||||
}
|
||||
if let Some(c) = o.remove("condition") {
|
||||
rules.insert("condition".into(), yung_condition(&c, lost));
|
||||
}
|
||||
// A piece's own adaptation, NONE included, replaces its structure's.
|
||||
if let Some(a) = o.remove(ENHANCED_TERRAIN) {
|
||||
o.insert(HORIZON_ENHANCED_TERRAIN.into(), yung_terrain(&a, lost));
|
||||
}
|
||||
if let Some(pool) = o.remove("deadend_pool").filter(Value::is_string) {
|
||||
rules.insert("deadend_pool".into(), pool);
|
||||
}
|
||||
let modifiers: Vec<Value> = o
|
||||
.remove("modifiers")
|
||||
.and_then(|m| m.as_array().cloned())
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(|m| yung_modifier(m, lost))
|
||||
.collect();
|
||||
if !modifiers.is_empty() {
|
||||
rules.insert("modifiers".into(), modifiers.into());
|
||||
}
|
||||
o.insert("horizon:yungsapi".into(), rules.into());
|
||||
}
|
||||
|
||||
/// One of YUNG's structure modifiers in the game's terms: its condition and
|
||||
/// its transform and delay_generation actions, on the piece itself (`self`,
|
||||
/// the API's only target). Another target loses the modifier, another action
|
||||
/// just that action.
|
||||
fn yung_modifier(m: &Value, lost: &mut BTreeMap<String, usize>) -> Option<Value> {
|
||||
let target = m["target_selector"]["type"].as_str().unwrap_or_default();
|
||||
if target != "yungsapi:self" {
|
||||
*lost
|
||||
.entry(format!("yungsapi modifier target {target}"))
|
||||
.or_default() += 1;
|
||||
return None;
|
||||
}
|
||||
let mut actions = Vec::new();
|
||||
for a in m["actions"].as_array().into_iter().flatten() {
|
||||
let int = |k: &str| a[k].as_i64().unwrap_or(0);
|
||||
match a["type"].as_str().unwrap_or_default() {
|
||||
"yungsapi:transform" => actions.push(serde_json::json!({"type": "transform",
|
||||
"output": a["output"].clone(),
|
||||
"offset": [int("x_offset"), int("y_offset"), int("z_offset")]})),
|
||||
"yungsapi:delay_generation" => {
|
||||
actions.push(serde_json::json!({"type": "delay_generation"}))
|
||||
}
|
||||
other => {
|
||||
*lost
|
||||
.entry(format!("yungsapi modifier action {other}"))
|
||||
.or_default() += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
let condition = match m.get("condition") {
|
||||
Some(c) => yung_condition(c, lost),
|
||||
None => serde_json::json!({"type": "true"}),
|
||||
};
|
||||
Some(serde_json::json!({"condition": condition, "actions": actions}))
|
||||
}
|
||||
|
||||
/// YUNG's API's terrain adaptation as the game's kernel: its two presets
|
||||
/// spelled out, NONE (also the default) as size 0. An aquifer override
|
||||
/// (none of ATM10's) is lost.
|
||||
fn yung_terrain(a: &Value, lost: &mut BTreeMap<String, usize>) -> Value {
|
||||
let kernel = |size: i32, distance: i32, top: &str, bottom: &str| {
|
||||
serde_json::json!({"kernel_size": size, "kernel_distance": distance,
|
||||
"top": top, "bottom": bottom})
|
||||
};
|
||||
match a["type"].as_str() {
|
||||
Some("yungsapi:carved_top_no_beard_large") => kernel(24, 16, "carve", "none"),
|
||||
Some("yungsapi:carved_top_no_beard_small") => kernel(12, 6, "carve", "none"),
|
||||
Some("yungsapi:custom") => {
|
||||
let mut out = serde_json::Map::new();
|
||||
for key in [
|
||||
"kernel_size",
|
||||
"kernel_distance",
|
||||
"top",
|
||||
"bottom",
|
||||
"bottom_offset",
|
||||
"padding",
|
||||
] {
|
||||
if let Some(x) = a.get(key) {
|
||||
out.insert(key.into(), x.clone());
|
||||
}
|
||||
}
|
||||
if a.get("aquifer_override")
|
||||
.is_some_and(|x| x["type"] != "yungsapi:none")
|
||||
{
|
||||
*lost.entry("yungsapi aquifer_override".into()).or_default() += 1;
|
||||
}
|
||||
moogs_terrain(&out.into(), lost).unwrap_or_else(|| kernel(0, 0, "none", "none"))
|
||||
}
|
||||
None | Some("yungsapi:none") => kernel(0, 0, "none", "none"),
|
||||
Some(other) => {
|
||||
*lost
|
||||
.entry(format!("yungsapi terrain adaptation {other}"))
|
||||
.or_default() += 1;
|
||||
kernel(0, 0, "none", "none")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// MoogsStructureLib's terrain adaptation: already the game's shape (with
|
||||
/// its band), when it has the fields the game needs (else it is lost, as
|
||||
/// the library's codec would refuse it).
|
||||
fn moogs_terrain(a: &Value, lost: &mut BTreeMap<String, usize>) -> Option<Value> {
|
||||
pub(crate) fn moogs_terrain(a: &Value, lost: &mut BTreeMap<String, usize>) -> Option<Value> {
|
||||
let ok = ["kernel_size", "kernel_distance"]
|
||||
.iter()
|
||||
.all(|k| a[k].is_u64())
|
||||
@@ -824,58 +450,15 @@ fn moogs_terrain(a: &Value, lost: &mut BTreeMap<String, usize>) -> Option<Value>
|
||||
ok.then(|| a.clone())
|
||||
}
|
||||
|
||||
/// One of YUNG's structure conditions in the game's terms. `mod_loaded`
|
||||
/// holds for Minecraft alone: a mod that needs code is not ported, and the
|
||||
/// pieces it guards would place its blocks. A condition the game does not
|
||||
/// have does not hold, and is counted.
|
||||
fn yung_condition(c: &Value, lost: &mut BTreeMap<String, usize>) -> Value {
|
||||
let t = c["type"].as_str().unwrap_or_default();
|
||||
let list = |lost: &mut BTreeMap<String, usize>| -> Value {
|
||||
let all = c["conditions"].as_array().into_iter().flatten();
|
||||
all.map(|x| yung_condition(x, lost))
|
||||
.collect::<Vec<_>>()
|
||||
.into()
|
||||
};
|
||||
let opt = |k: &str| c.get(k).cloned().unwrap_or(Value::Null);
|
||||
match t.trim_start_matches("yungsapi:") {
|
||||
"always_true" => serde_json::json!({"type": "true"}),
|
||||
"not" => {
|
||||
serde_json::json!({"type": "not", "condition": yung_condition(&c["condition"], lost)})
|
||||
}
|
||||
"all_of" => serde_json::json!({"type": "all_of", "conditions": list(lost)}),
|
||||
"any_of" => serde_json::json!({"type": "any_of", "conditions": list(lost)}),
|
||||
"depth" => serde_json::json!({"type": "depth",
|
||||
"min_depth": opt("min_required_depth"), "max_depth": opt("max_possible_depth")}),
|
||||
"altitude" => serde_json::json!({"type": "altitude",
|
||||
"bottom": opt("bottom_cutoff_y"), "top": opt("top_cutoff_y")}),
|
||||
"random_chance" => serde_json::json!({"type": "random_chance", "chance": opt("chance")}),
|
||||
"rotation" => serde_json::json!({"type": "rotation", "rotations": opt("rotations")}),
|
||||
"piece_in_horizontal_direction" => {
|
||||
// "yungsapi:all" (or no list) matches any piece.
|
||||
let pieces: Vec<Value> = c["pieces"].as_array().cloned().unwrap_or_default();
|
||||
let any = pieces.is_empty() || pieces.iter().any(|p| p == "yungsapi:all");
|
||||
serde_json::json!({"type": "piece_in_horizontal_direction",
|
||||
"pieces": if any { Vec::new() } else { pieces },
|
||||
"range": opt("range"), "rotation": opt("rotation")})
|
||||
}
|
||||
// The game reads "yungsapi:all" (or no list) as any piece.
|
||||
"piece_in_range" => serde_json::json!({"type": "piece_in_range",
|
||||
"pieces": c.get("pieces").cloned().unwrap_or_else(|| Vec::<Value>::new().into()),
|
||||
"horizontal_range": opt("horizontal_range"), "above_range": opt("above_range"),
|
||||
"below_range": opt("below_range")}),
|
||||
"mod_loaded" if c["modid"] == "minecraft" => serde_json::json!({"type": "true"}),
|
||||
"mod_loaded" => serde_json::json!({"type": "false"}),
|
||||
_ => {
|
||||
*lost.entry(format!("yungsapi condition {t}")).or_default() += 1;
|
||||
serde_json::json!({"type": "false"})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves a Repurposed Structures or Moog's jigsaw's start rules under
|
||||
/// `horizon:start_checks`, and counts the layout rules it loses. `liquid` is
|
||||
/// the block its no-start-in-liquid rule reads.
|
||||
fn start_checks(v: &mut Value, liquid: &str, lost: &mut BTreeMap<String, usize>, limited: bool) {
|
||||
pub(crate) fn start_checks(
|
||||
v: &mut Value,
|
||||
liquid: &str,
|
||||
lost: &mut BTreeMap<String, usize>,
|
||||
limited: bool,
|
||||
) {
|
||||
let Some(o) = v.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
@@ -1043,7 +626,7 @@ fn moogs_spacing(p: &mut Value, lost: &mut BTreeMap<String, usize>) {
|
||||
|
||||
/// An advanced random spread's minimum distance from the world origin and
|
||||
/// its super exclusion zone (sets named by a tag) under `horizon:` keys.
|
||||
fn placement_rules(
|
||||
pub(crate) fn placement_rules(
|
||||
p: &mut Value,
|
||||
set_tags: &BTreeMap<String, Vec<String>>,
|
||||
lost: &mut BTreeMap<String, usize>,
|
||||
@@ -1115,65 +698,6 @@ fn mo_placement(p: &mut Value, lost: &mut BTreeMap<String, usize>) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// One of YUNG's placements as vanilla's random spread with `horizon:` keys:
|
||||
/// the enhanced exclusion zone as `horizon:exclusion_zone`; the temples'
|
||||
/// ocean and river search (findBiomeHorizontal around the chunk's middle
|
||||
/// block at y 120, 48 blocks, every 2 quarts) as `horizon:avoid_biomes`; the
|
||||
/// strongholds' rings as `horizon:ring_sections`.
|
||||
fn yung_placement(
|
||||
t: &str,
|
||||
p: &mut Value,
|
||||
set_tags: &BTreeMap<String, Vec<String>>,
|
||||
lost: &mut BTreeMap<String, usize>,
|
||||
) {
|
||||
placement_rules(p, set_tags, lost);
|
||||
p["type"] = "minecraft:random_spread".into();
|
||||
let Some(o) = p.as_object_mut() else {
|
||||
return;
|
||||
};
|
||||
match t {
|
||||
"betterdeserttemples:desert_temple" | "betterjungletemples:jungle_temple" => {
|
||||
o.insert(
|
||||
"horizon:avoid_biomes".into(),
|
||||
serde_json::json!({"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"],
|
||||
"radius": 48, "step": 2, "y": 120}),
|
||||
);
|
||||
}
|
||||
"betterstrongholds:stronghold" => {
|
||||
let mut rings = serde_json::Map::new();
|
||||
for (from, to) in [
|
||||
("chunk_distance_to_first_ring", "distance_to_first_ring"),
|
||||
("ring_chunk_thickness", "thickness"),
|
||||
("max_ring_section", "max_section"),
|
||||
] {
|
||||
if let Some(n) = o.remove(from) {
|
||||
rings.insert(to.into(), n);
|
||||
}
|
||||
}
|
||||
o.insert("horizon:ring_sections".into(), rings.into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks a YUNG's structure that the game can start (its type is vanilla's
|
||||
/// after the upgrade) with the vanilla type its mod turns off, under
|
||||
/// `horizon:disables`. One the game cannot start leaves the vanilla
|
||||
/// structure in place, so the world keeps one of the two.
|
||||
pub fn disables(id: &str, v: &mut Value) -> bool {
|
||||
let Some((_, vanilla)) = YUNG_REPLACES.iter().find(|(s, _)| id.starts_with(s)) else {
|
||||
return false;
|
||||
};
|
||||
if !v["type"]
|
||||
.as_str()
|
||||
.is_some_and(|t| t.starts_with("minecraft:"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
v["horizon:disables"] = serde_json::json!([vanilla]);
|
||||
true
|
||||
}
|
||||
|
||||
/// The mod's structure set tags (`data/<ns>/tags/worldgen/structure_set/`),
|
||||
/// by tag id, with the tags they include expanded. Optional entries
|
||||
/// (`{"id": ..., "required": false}`) count as their id.
|
||||
@@ -1590,94 +1114,6 @@ mod tests {
|
||||
assert_eq!(report.rules_lost["super_exclusion_zone"], 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yungs_jigsaws_keep_their_rules() {
|
||||
let mut report = Upgrade::default();
|
||||
let mut s = json!({"type": "yungsapi:yung_jigsaw", "start_pool": "y:start", "size": 20,
|
||||
"max_y": 60, "x_offset_in_chunk": 0, "max_distance_from_center": 80,
|
||||
"enhanced_terrain_adaptation": {"type": "yungsapi:custom", "kernel_size": 24,
|
||||
"kernel_distance": 24, "top": "carve", "bottom": "none"}});
|
||||
assert!(upgrade("structure", &mut s, &mut report, &NO_TAGS));
|
||||
assert_eq!(s["type"], "minecraft:jigsaw");
|
||||
assert_eq!(s["horizon:yungsapi"], json!({"max_y": 60}));
|
||||
assert_eq!(
|
||||
s["horizon:enhanced_terrain_adaptation"],
|
||||
json!({"kernel_size": 24, "kernel_distance": 24, "top": "carve", "bottom": "none",
|
||||
"rigid_junctions": true, "inflate": true})
|
||||
);
|
||||
for gone in ["max_y", "x_offset_in_chunk", "enhanced_terrain_adaptation"] {
|
||||
assert!(s.get(gone).is_none(), "{gone}");
|
||||
}
|
||||
// Better Dungeons' small Nether dungeon is the same jigsaw.
|
||||
let mut nether = json!({"type": "betterdungeons:small_nether_dungeon",
|
||||
"start_pool": "betterdungeons:small_nether_dungeon", "size": 10,
|
||||
"start_jigsaw_name": "betterdungeons:small_nether_dungeon_anchor",
|
||||
"max_distance_from_center": 80, "liquid_settings": "ignore_waterlogging"});
|
||||
assert!(upgrade("structure", &mut nether, &mut report, &NO_TAGS));
|
||||
assert_eq!(nether["type"], "minecraft:jigsaw");
|
||||
assert_eq!(nether["horizon:yungsapi"], json!({}));
|
||||
assert_eq!(
|
||||
nether["horizon:enhanced_terrain_adaptation"],
|
||||
json!({"kernel_size": 0, "kernel_distance": 0, "top": "none", "bottom": "none",
|
||||
"rigid_junctions": true, "inflate": true})
|
||||
);
|
||||
assert_eq!(
|
||||
nether["start_jigsaw_name"],
|
||||
"betterdungeons:small_nether_dungeon_anchor"
|
||||
);
|
||||
assert!(report.unsupported.is_empty());
|
||||
let mut pool = json!({"elements": [{"weight": 3, "element": {
|
||||
"element_type": "yungsapi:yung_single_element", "location": "y:room",
|
||||
"processors": "minecraft:empty", "projection": "rigid",
|
||||
"name": "room", "max_count": 2, "min_required_depth": 1, "is_priority": true,
|
||||
"ignore_bounds": false, "deadend_pool": "y:end",
|
||||
"modifiers": [
|
||||
{"condition": {"type": "yungsapi:piece_in_range", "pieces": ["y:pillar"],
|
||||
"above_range": 40},
|
||||
"target_selector": {"type": "yungsapi:self"},
|
||||
"actions": [{"type": "yungsapi:transform", "output": ["y:covered"], "x_offset": -1},
|
||||
{"type": "yungsapi:delay_generation"}, {"type": "yungsapi:spin"}]},
|
||||
{"condition": {"type": "yungsapi:always_true"},
|
||||
"target_selector": {"type": "yungsapi:all"}, "actions": []}],
|
||||
"enhanced_terrain_adaptation": {"type": "yungsapi:carved_top_no_beard_small"},
|
||||
"condition": {"type": "yungsapi:all_of", "conditions": [
|
||||
{"type": "yungsapi:piece_in_horizontal_direction", "pieces": ["yungsapi:all"],
|
||||
"range": 5, "rotation": "none"},
|
||||
{"type": "yungsapi:not", "condition": {"type": "yungsapi:mod_loaded", "modid": "create"}},
|
||||
{"type": "yungsapi:biome", "biomes": []}]}}}]});
|
||||
assert!(upgrade("template_pool", &mut pool, &mut report, &NO_TAGS));
|
||||
let e = &pool["elements"][0]["element"];
|
||||
assert_eq!(e["element_type"], "minecraft:single_pool_element");
|
||||
assert_eq!(e["location"], "y:room");
|
||||
assert_eq!(
|
||||
e["horizon:yungsapi"],
|
||||
json!({"name": "room", "max_count": 2, "min_depth": 1, "priority": true,
|
||||
"ignore_bounds": false, "condition": {"type": "all_of", "conditions": [
|
||||
{"type": "piece_in_horizontal_direction", "pieces": [], "range": 5, "rotation": "none"},
|
||||
{"type": "not", "condition": {"type": "false"}},
|
||||
{"type": "false"}]},
|
||||
"deadend_pool": "y:end",
|
||||
"modifiers": [{"condition": {"type": "piece_in_range", "pieces": ["y:pillar"],
|
||||
"horizontal_range": null, "above_range": 40, "below_range": null},
|
||||
"actions": [{"type": "transform", "output": ["y:covered"], "offset": [-1, 0, 0]},
|
||||
{"type": "delay_generation"}]}]})
|
||||
);
|
||||
assert!(e.get("deadend_pool").is_none() && e.get("modifiers").is_none());
|
||||
assert_eq!(
|
||||
e["horizon:enhanced_terrain_adaptation"],
|
||||
json!({"kernel_size": 12, "kernel_distance": 6, "top": "carve", "bottom": "none"})
|
||||
);
|
||||
assert_eq!(
|
||||
report.rules_lost,
|
||||
BTreeMap::from([
|
||||
("yungsapi condition yungsapi:biome".into(), 1),
|
||||
("yungsapi modifier action yungsapi:spin".into(), 1),
|
||||
("yungsapi modifier target yungsapi:all".into(), 1),
|
||||
])
|
||||
);
|
||||
assert!(report.unsupported.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drops_processors_written_in_java() {
|
||||
let mut report = Upgrade::default();
|
||||
@@ -1722,59 +1158,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yungs_placements_keep_their_rules() {
|
||||
let tags = BTreeMap::from([(
|
||||
"bf:avoid".to_owned(),
|
||||
vec!["minecraft:nether_complexes".to_owned()],
|
||||
)]);
|
||||
let mut report = Upgrade::default();
|
||||
let mut fortress = json!({"placement": {"type": "yungsapi:enhanced_random_spread",
|
||||
"salt": 1, "spacing": 30, "separation": 20,
|
||||
"enhanced_exclusion_zone": {"other_set": "#bf:avoid", "chunk_count": 10}}});
|
||||
assert!(upgrade("structure_set", &mut fortress, &mut report, &tags));
|
||||
assert_eq!(
|
||||
fortress["placement"],
|
||||
json!({"type": "minecraft:random_spread", "salt": 1, "spacing": 30, "separation": 20,
|
||||
"horizon:exclusion_zone": {"other_sets": ["minecraft:nether_complexes"], "chunk_count": 10}})
|
||||
);
|
||||
let mut temple = json!({"placement": {"type": "betterdeserttemples:desert_temple",
|
||||
"salt": 2, "spacing": 30, "separation": 20,
|
||||
"exclusion_zone": {"other_set": "minecraft:villages", "chunk_count": 6}}});
|
||||
assert!(upgrade("structure_set", &mut temple, &mut report, &tags));
|
||||
assert_eq!(temple["placement"]["type"], "minecraft:random_spread");
|
||||
assert_eq!(temple["placement"]["exclusion_zone"]["chunk_count"], 6);
|
||||
assert_eq!(
|
||||
temple["placement"]["horizon:avoid_biomes"],
|
||||
json!({"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"],
|
||||
"radius": 48, "step": 2, "y": 120})
|
||||
);
|
||||
let mut stronghold = json!({"placement": {"type": "betterstrongholds:stronghold",
|
||||
"salt": 3, "spacing": 85, "separation": 50,
|
||||
"chunk_distance_to_first_ring": 80, "ring_chunk_thickness": 96}});
|
||||
assert!(upgrade(
|
||||
"structure_set",
|
||||
&mut stronghold,
|
||||
&mut report,
|
||||
&tags
|
||||
));
|
||||
assert_eq!(
|
||||
stronghold["placement"],
|
||||
json!({"type": "minecraft:random_spread", "salt": 3, "spacing": 85, "separation": 50,
|
||||
"horizon:ring_sections": {"distance_to_first_ring": 80, "thickness": 96}})
|
||||
);
|
||||
assert_eq!(report.mapped, 3);
|
||||
assert!(report.unsupported.is_empty());
|
||||
// The vanilla counterpart is turned off only for a structure the game starts.
|
||||
let mut ported = json!({"type": "minecraft:jigsaw"});
|
||||
assert!(disables("betterstrongholds:stronghold", &mut ported));
|
||||
assert_eq!(ported["horizon:disables"], json!(["minecraft:stronghold"]));
|
||||
let mut java = json!({"type": "bettermineshafts:mineshaft"});
|
||||
assert!(!disables("bettermineshafts:mineshaft_oak", &mut java));
|
||||
let mut circle = json!({"type": "minecraft:jigsaw"});
|
||||
assert!(!disables("betterwitchhuts:witch_circle", &mut circle));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn piece_limited_jigsaws_keep_their_layout() {
|
||||
let mut report = Upgrade::default();
|
||||
@@ -1886,88 +1269,6 @@ mod tests {
|
||||
assert_eq!(report.mapped, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modifiers_add_to_sets_and_pools() {
|
||||
let mut report = Upgrade::default();
|
||||
let only_fd = |m: &str| m == "farmersdelight";
|
||||
let set = json!({"type": "lithostitched:add_structure_set_entries",
|
||||
"structure_sets": "minecraft:villages",
|
||||
"entries": [{"structure": "x:village", "weight": 4}]});
|
||||
let (kind, added) = modifier(&set, &only_fd, &mut report).unwrap();
|
||||
assert_eq!(kind, "structure_set");
|
||||
assert_eq!(
|
||||
added,
|
||||
json!({"horizon:add_to": ["minecraft:villages"],
|
||||
"structures": [{"structure": "x:village", "weight": 4}]})
|
||||
);
|
||||
// A compat addition holds only when its mod is ported along.
|
||||
let pool = |modid: &str| {
|
||||
json!({"type": "lithostitched:add_template_pool_elements",
|
||||
"neoforge:conditions": [{"type": "neoforge:mod_loaded", "modid": modid}],
|
||||
"fabric:load_conditions": {"condition": "fabric:all_mods_loaded", "values": ["other"]},
|
||||
"template_pools": ["x:houses", "y:houses"],
|
||||
"elements": [{"weight": 5, "element": {"element_type": "minecraft:single_pool_element",
|
||||
"location": "x:fd_farm", "projection": "rigid", "processors": "minecraft:empty"}}]})
|
||||
};
|
||||
let (kind, added) = modifier(&pool("farmersdelight"), &only_fd, &mut report).unwrap();
|
||||
assert_eq!(kind, "template_pool");
|
||||
assert_eq!(added["horizon:add_to"], json!(["x:houses", "y:houses"]));
|
||||
assert_eq!(added["elements"][0]["weight"], 5);
|
||||
assert!(modifier(&pool("create"), &only_fd, &mut report).is_none());
|
||||
// Fabric's conditions when there are no NeoForge ones; lithostitched's own.
|
||||
let fabric = json!({"type": "lithostitched:add_structure_set_entries",
|
||||
"fabric:load_conditions": [{"condition": "fabric:not",
|
||||
"value": {"condition": "fabric:any_mods_loaded", "values": ["create"]}}],
|
||||
"predicate": {"type": "lithostitched:all_of", "predicates": [
|
||||
{"type": "lithostitched:mod_loaded", "mod_id": "farmersdelight"},
|
||||
{"type": "lithostitched:true"}]},
|
||||
"structure_sets": "minecraft:villages", "entries": []});
|
||||
assert!(modifier(&fabric, &only_fd, &mut report).is_some());
|
||||
let tagged = json!({"type": "lithostitched:add_structure_set_entries",
|
||||
"structure_sets": "#x:sets", "entries": []});
|
||||
assert!(modifier(&tagged, &only_fd, &mut report).is_none());
|
||||
let features = json!({"type": "lithostitched:add_features"});
|
||||
assert!(modifier(&features, &only_fd, &mut report).is_none());
|
||||
assert_eq!(
|
||||
report.added_to,
|
||||
BTreeMap::from([
|
||||
("minecraft:villages".into(), 1),
|
||||
("x:houses".into(), 1),
|
||||
("y:houses".into(), 1),
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
report.modifiers_left,
|
||||
BTreeMap::from([
|
||||
("conditions".into(), 1),
|
||||
("lithostitched:add_features".into(), 1),
|
||||
("target".into(), 1),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ctov_joins_vanillas_villages_and_outposts() {
|
||||
let sets = code_set_entries("ctov");
|
||||
let (file, set, outposts) = &sets[0];
|
||||
assert_eq!(
|
||||
(*file, *set),
|
||||
("pillager_outposts", "minecraft:pillager_outposts")
|
||||
);
|
||||
assert_eq!(outposts.len(), 11);
|
||||
assert!(outposts.iter().all(|(_, w)| *w == 1));
|
||||
let (_, set, villages) = &sets[1];
|
||||
assert_eq!(*set, "minecraft:villages");
|
||||
assert_eq!(villages.len(), 63);
|
||||
assert_eq!(villages[0], ("ctov:small/village_beach".into(), 10));
|
||||
assert_eq!(villages[21], ("ctov:medium/village_beach".into(), 4));
|
||||
assert_eq!(
|
||||
villages[62],
|
||||
("ctov:large/village_taiga_fortified".into(), 1)
|
||||
);
|
||||
assert!(code_set_entries("mvs").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convention_tags_include_theirs() {
|
||||
let conventions = BTreeMap::from([
|
||||
|
||||
@@ -32,6 +32,10 @@ Passes are shared between worktrees. A harness's key depends only on the content
|
||||
|
||||
Every runner on the machine shares `PARITY_MACHINE_JOBS` slots (default: half the CPU threads), so several agents' runs together can't overload it. Parallel harnesses are also admitted by memory: each harness's recorded peak is reserved, within three quarters of the memory available at the start, and a harness starts only if the memory free at that moment still leaves 2 GB. `-j` caps the count here (default: `PARITY_LOCAL_JOBS`, else 3 while other machines help or a third of the CPU threads alone, within `$FLEET_LOAD_JOBS`).
|
||||
|
||||
### Harnesses that start the game
|
||||
|
||||
The game logs into `HORIZON_HOME` and falls back to the player's own game folder when it is unset, so a harness that starts the game, `horizon-ctl`, the launcher or the dedicated server builds the environment with `lab.game_env(**extra)`: no audio, and fresh scratch folders for `HORIZON_HOME`, `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and `XDG_CONFIG_HOME`, removed when the harness exits (a folder you pass, or that the environment already has, is kept). The runner also gives each harness its own `HORIZON_HOME` under `.local/parity-runner/game-home/`. `tests/test_game_home.py` fails for a script in `tools/` that starts the game without it.
|
||||
|
||||
### Other machines
|
||||
|
||||
Harnesses can also run on the Mac mini and the ThinkPad (`tools/parity_hosts.json` describes them; its `default` list is empty, so pass `--hosts macmini,thinkpad` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/<host><path>`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 3 and only those under 800 MB. Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here.
|
||||
|
||||
@@ -2170,6 +2170,8 @@ pub enum Msg {
|
||||
Links(Links),
|
||||
Progress(String, f32),
|
||||
Installed(String, Result<(), String>),
|
||||
/// A version's files are gone (or could not be deleted).
|
||||
Removed(String, Result<(), String>),
|
||||
Line(Job, String),
|
||||
Exit(Job, Result<(), String>),
|
||||
Updates(Result<Updates, String>),
|
||||
|
||||
+67
-9
@@ -144,6 +144,9 @@ struct Launcher {
|
||||
releases: Load<Vec<Release>>,
|
||||
installed: Vec<String>,
|
||||
installing: Option<(String, f32)>,
|
||||
/// The version being deleted on a background thread. It is already out of `installed`, so
|
||||
/// nothing can launch, select or prepare it, and its row can't install or remove it again.
|
||||
removing: Option<String>,
|
||||
install_error: Option<(String, String)>,
|
||||
confirm_remove: Option<String>,
|
||||
picker_open: bool,
|
||||
@@ -286,6 +289,7 @@ impl Launcher {
|
||||
releases: Load::Loading,
|
||||
installed,
|
||||
installing: None,
|
||||
removing: None,
|
||||
install_error: None,
|
||||
confirm_remove: None,
|
||||
picker_open: false,
|
||||
@@ -415,7 +419,7 @@ impl Launcher {
|
||||
let Some(release) = self.updates.horizon.clone() else {
|
||||
return;
|
||||
};
|
||||
if self.installing.is_some() {
|
||||
if self.installing.is_some() || self.removing.as_ref() == Some(&release.tag) {
|
||||
return;
|
||||
}
|
||||
let select =
|
||||
@@ -542,6 +546,17 @@ impl Launcher {
|
||||
Err(e) => self.install_error = Some((tag, e)),
|
||||
}
|
||||
}
|
||||
Msg::Removed(tag, result) => {
|
||||
if self.removing.as_ref() == Some(&tag) {
|
||||
self.removing = None;
|
||||
}
|
||||
self.installed = backend::installed();
|
||||
self.settings.selected =
|
||||
selection_after_removal(&self.installed, Settings::load().selected);
|
||||
if let Err(e) = result {
|
||||
self.install_error = Some((tag, e));
|
||||
}
|
||||
}
|
||||
Msg::Updates(Ok(updates)) => {
|
||||
self.update_error = None;
|
||||
self.updates = updates;
|
||||
@@ -706,7 +721,7 @@ impl Launcher {
|
||||
}
|
||||
|
||||
fn install(&mut self, release: &Release) {
|
||||
if release.asset.is_none() {
|
||||
if release.asset.is_none() || self.removing.as_ref() == Some(&release.tag) {
|
||||
return;
|
||||
}
|
||||
let (release, tx) = (release.clone(), self.tx.clone());
|
||||
@@ -724,15 +739,26 @@ impl Launcher {
|
||||
});
|
||||
}
|
||||
|
||||
/// Deletes an installed version on a background thread: a version is thousands of files and
|
||||
/// the window must keep drawing meanwhile. `Msg::Removed` ends it.
|
||||
fn remove(&mut self, tag: &str) {
|
||||
if let Err(e) = backend::remove_version(tag) {
|
||||
self.install_error = Some((tag.to_string(), e));
|
||||
}
|
||||
self.confirm_remove = None;
|
||||
self.installed = backend::installed();
|
||||
self.settings.selected = Settings::load()
|
||||
.selected
|
||||
.or_else(|| self.installed.first().cloned());
|
||||
if self.removing.is_some()
|
||||
|| self.installing.as_ref().is_some_and(|(t, _)| t == tag)
|
||||
|| !self.installed.iter().any(|t| t == tag)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.install_error = None;
|
||||
self.removing = Some(tag.to_string());
|
||||
self.installed.retain(|t| t != tag);
|
||||
self.settings.selected =
|
||||
selection_after_removal(&self.installed, self.settings.selected.take());
|
||||
let (tag, tx) = (tag.to_string(), self.tx.clone());
|
||||
std::thread::spawn(move || {
|
||||
let result = backend::remove_version(&tag);
|
||||
let _ = tx.send(Msg::Removed(tag, result));
|
||||
});
|
||||
}
|
||||
|
||||
fn prepare(&mut self) {
|
||||
@@ -1158,6 +1184,14 @@ fn segments<T: Copy + PartialEq + 'static>(
|
||||
}))
|
||||
}
|
||||
|
||||
/// The selected version once one has been removed: the saved choice if it is still installed,
|
||||
/// else the newest left.
|
||||
fn selection_after_removal(installed: &[String], saved: Option<String>) -> Option<String> {
|
||||
saved
|
||||
.filter(|s| installed.contains(s))
|
||||
.or_else(|| installed.first().cloned())
|
||||
}
|
||||
|
||||
fn disabled(b: Stateful<Div>) -> Stateful<Div> {
|
||||
b.opacity(theme::DISABLED).cursor_default().tab_stop(false)
|
||||
}
|
||||
@@ -2923,6 +2957,7 @@ impl Launcher {
|
||||
self.installing.as_ref().is_some_and(|(t, _)| t == tag)
|
||||
|| self.install_error.as_ref().is_some_and(|(t, _)| t == tag)
|
||||
|| self.confirm_remove.as_ref() == Some(tag)
|
||||
|| self.removing.as_ref() == Some(tag)
|
||||
};
|
||||
let list = self.long_list.clone().column(
|
||||
&self.content_scroll.handle,
|
||||
@@ -2959,6 +2994,15 @@ impl Launcher {
|
||||
.child(format!("{:.0}%", p * 100.)),
|
||||
)
|
||||
.into_any_element()
|
||||
} else if self.removing.as_ref() == Some(&tag) {
|
||||
div()
|
||||
.flex()
|
||||
.items_center()
|
||||
.gap(px(10.))
|
||||
.w(px(180.))
|
||||
.child(progress_bar(None, &t))
|
||||
.child(text(theme::MICRO).text_color(t.muted).child("Removing…"))
|
||||
.into_any_element()
|
||||
} else if installed {
|
||||
let confirming = self.confirm_remove.as_ref() == Some(&tag);
|
||||
let (t1, t2) = (tag.clone(), tag.clone());
|
||||
@@ -3587,6 +3631,20 @@ mod tests {
|
||||
assert!(hit.iter().any(|b| b.action().partial_eq(&CloseWindow)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_selection_survives_a_removal_or_moves_to_the_newest_left() {
|
||||
let left = ["v0.2.49".to_string(), "v0.2.48".to_string()];
|
||||
let pick =
|
||||
|saved: Option<&str>| super::selection_after_removal(&left, saved.map(String::from));
|
||||
assert_eq!(pick(Some("v0.2.48")).as_deref(), Some("v0.2.48"));
|
||||
assert_eq!(pick(Some("v0.2.47")).as_deref(), Some("v0.2.49"));
|
||||
assert_eq!(pick(None).as_deref(), Some("v0.2.49"));
|
||||
assert_eq!(
|
||||
super::selection_after_removal(&[], Some("v0.2.47".into())),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_app_menu_has_quit() {
|
||||
let menus = super::menus();
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""A tool or harness that starts the game must not write into a real player's folders.
|
||||
|
||||
The game logs into HORIZON_HOME and falls back to the player's own game folder when it is unset, so every
|
||||
spawn goes through lab.game_env, which sets fresh scratch folders. This test fails for a script in tools/
|
||||
that starts the game (or horizon-ctl, the launcher or the dedicated server) without it."""
|
||||
|
||||
import ast
|
||||
import os
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from tools import lab
|
||||
|
||||
TOOLS = Path(lab.ROOT) / "tools"
|
||||
|
||||
# Strings that mean "this script starts the game": a binary a harness runs, or the audio switch every game run sets.
|
||||
SPAWN_MARKERS = {
|
||||
"HORIZON_NO_AUDIO", "horizon-ctl", "horizon-ctl.exe", "horizon-server", "horizon-server.exe",
|
||||
"horizon-client.exe", "release/horizon-client", "fast/horizon-client", "debug/horizon-client",
|
||||
}
|
||||
|
||||
# Scripts that mention those strings without starting a game themselves, and why.
|
||||
EXEMPT = {
|
||||
"lab.py": "defines game_env",
|
||||
"parity.py": "runs the harnesses and gives each its own HORIZON_HOME",
|
||||
"package_native_client.py": "packs the binaries into an archive",
|
||||
"build_release.py": "builds and packs the release",
|
||||
"release_train.py": "release bookkeeping",
|
||||
"pr_ready.py": "runs cargo checks and parity.py",
|
||||
"port_harness.py": "ports Java code, starts no game",
|
||||
}
|
||||
|
||||
|
||||
def constants(tree):
|
||||
"""Every string in a script that is a whole literal or a keyword name (docstrings are longer text)."""
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
||||
yield node.value
|
||||
elif isinstance(node, ast.keyword) and node.arg:
|
||||
yield node.arg
|
||||
|
||||
|
||||
def uses_game_env(tree):
|
||||
"""The script calls lab.game_env, or starts its servers through test_dedicated_server_parity.Server, which does."""
|
||||
return any(isinstance(node, ast.Attribute) and node.attr == "game_env"
|
||||
or isinstance(node, ast.Name) and node.id == "game_env"
|
||||
or isinstance(node, ast.ImportFrom) and (node.module or "").endswith("test_dedicated_server_parity")
|
||||
for node in ast.walk(tree))
|
||||
|
||||
|
||||
def sets_audio_by_hand(tree):
|
||||
return "HORIZON_NO_AUDIO" in set(constants(tree))
|
||||
|
||||
|
||||
class GameEnvTests(unittest.TestCase):
|
||||
def test_gives_every_game_scratch_folders(self):
|
||||
with mock.patch.dict(os.environ, {}, clear=False):
|
||||
for key in ("HORIZON_HOME", "HORIZON_LAUNCHER_HOME", "XDG_DATA_HOME", "XDG_CONFIG_HOME"):
|
||||
os.environ.pop(key, None)
|
||||
first, second = lab.game_env(), lab.game_env()
|
||||
self.assertEqual(first["HORIZON_NO_AUDIO"], "1")
|
||||
self.assertEqual(first["HORIZON_LAUNCHER_NO_SELF_UPDATE"], "1")
|
||||
for key in ("HORIZON_HOME", "HORIZON_LAUNCHER_HOME", "XDG_DATA_HOME", "XDG_CONFIG_HOME"):
|
||||
self.assertTrue(Path(first[key]).is_dir(), key)
|
||||
self.assertNotEqual(first[key], second[key], key)
|
||||
|
||||
def test_keeps_the_callers_folders(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
env = lab.game_env({"PATH": "x", "HORIZON_HOME": "/from/base"}, HORIZON_LAUNCHER_HOME=Path(temp), A=1)
|
||||
self.assertEqual(env["HORIZON_HOME"], "/from/base")
|
||||
self.assertEqual(env["HORIZON_LAUNCHER_HOME"], temp)
|
||||
self.assertEqual((env["PATH"], env["A"]), ("x", "1"))
|
||||
|
||||
def test_does_not_touch_the_process_environment(self):
|
||||
before = dict(os.environ)
|
||||
lab.game_env()
|
||||
self.assertEqual(dict(os.environ), before)
|
||||
|
||||
|
||||
class SpawnerTests(unittest.TestCase):
|
||||
def test_every_script_that_starts_the_game_uses_game_env(self):
|
||||
offenders = []
|
||||
for path in sorted(TOOLS.rglob("*.py")):
|
||||
if path.name in EXEMPT:
|
||||
continue
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||||
if SPAWN_MARKERS & set(constants(tree)) and not uses_game_env(tree):
|
||||
offenders.append(str(path.relative_to(lab.ROOT)))
|
||||
self.assertEqual(offenders, [], "these start the game without lab.game_env (HORIZON_HOME falls back to a "
|
||||
"real player's folder); use it, or list the script in EXEMPT")
|
||||
|
||||
def test_nobody_sets_the_audio_switch_by_hand(self):
|
||||
offenders = [str(path.relative_to(lab.ROOT)) for path in sorted(TOOLS.rglob("*.py"))
|
||||
if path.name not in EXEMPT
|
||||
and sets_audio_by_hand(ast.parse(path.read_text(encoding="utf-8"), filename=str(path)))]
|
||||
self.assertEqual(offenders, [], "set it through lab.game_env, which also gives the game scratch folders")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -67,17 +67,20 @@ class Failed(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def game_env(screen):
|
||||
def game_env(screen, home=None):
|
||||
"""The environment of a game: lab.game_env with HORIZON_HOME `home` (a scratch folder when None), no live-count
|
||||
ping, and on Linux the virtual screen `screen`."""
|
||||
extra = {'HORIZON_TELEMETRY_URL': 'off'} # no live-count ping from test games
|
||||
if home is not None:
|
||||
extra['HORIZON_HOME'] = home
|
||||
if sys.platform == 'darwin':
|
||||
return dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
|
||||
env = dict(os.environ, VSCREEN=screen)
|
||||
return lab.game_env(**extra)
|
||||
env = lab.game_env(VSCREEN=screen, **extra)
|
||||
subprocess.run(['vscreen', 'up'], env=env, check=False, capture_output=True)
|
||||
text = subprocess.run(['vscreen', 'env'], env=env, capture_output=True, text=True, check=True).stdout
|
||||
env.pop('DISPLAY', None)
|
||||
for match in re.finditer(r'(\w+)=(\S+)', text.split('unset')[0]):
|
||||
env[match.group(1)] = match.group(2)
|
||||
env['HORIZON_NO_AUDIO'] = '1'
|
||||
env['HORIZON_TELEMETRY_URL'] = 'off' # no live-count ping from test games
|
||||
if LAVAPIPE.exists():
|
||||
env['VK_ICD_FILENAMES'] = str(LAVAPIPE)
|
||||
return env
|
||||
@@ -632,7 +635,7 @@ def scratch(mode, resources):
|
||||
(work / '.local/horizon-client').mkdir()
|
||||
os.symlink(resources, work / '.local/horizon-client' / lab.VERSION)
|
||||
# horizon-ctl reads No AI in the game home: this one, not the player's.
|
||||
env = dict(game_env(os.environ.get('VSCREEN', 'agent-control')), HORIZON_HOME=str(work))
|
||||
env = game_env(os.environ.get('VSCREEN', 'agent-control'), home=work)
|
||||
return work, env
|
||||
|
||||
|
||||
|
||||
@@ -53,15 +53,14 @@ guiScale:0
|
||||
|
||||
def vscreen_env():
|
||||
out = subprocess.run(["vscreen", "env"], cwd=ROOT, capture_output=True, text=True, check=True)
|
||||
env = dict(os.environ)
|
||||
env = lab.game_env()
|
||||
for part in out.stdout.replace(";", " ").split():
|
||||
if "=" in part and not part.startswith("export"):
|
||||
k, v = part.split("=", 1)
|
||||
env[k] = v
|
||||
env.pop("DISPLAY", None)
|
||||
# Benchmark games never play sound on the machine's speakers.
|
||||
env["HORIZON_NO_AUDIO"] = "1"
|
||||
# Nor reach the telemetry server (docs/telemetry.md).
|
||||
# lab.game_env: no sound on the machine's speakers, and scratch folders instead of the player's.
|
||||
# Benchmark games do not reach the telemetry server (docs/telemetry.md).
|
||||
env["HORIZON_TELEMETRY_URL"] = "off"
|
||||
return env
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ generated files stay in .local/. Also the small helpers the harnesses share
|
||||
(free ports, offline UUIDs, VarInts, float bits)."""
|
||||
|
||||
import argparse
|
||||
import atexit
|
||||
from collections import Counter
|
||||
import hashlib
|
||||
import json
|
||||
@@ -54,6 +55,38 @@ def cargo_target():
|
||||
return ROOT / os.environ.get("CARGO_TARGET_DIR", "target")
|
||||
|
||||
|
||||
_SCRATCH_DIRS = []
|
||||
|
||||
|
||||
def _scratch_dir(prefix):
|
||||
path = tempfile.mkdtemp(prefix=prefix)
|
||||
_SCRATCH_DIRS.append(path)
|
||||
return path
|
||||
|
||||
|
||||
@atexit.register
|
||||
def _remove_scratch_dirs():
|
||||
for path in _SCRATCH_DIRS:
|
||||
shutil.rmtree(path, ignore_errors=True)
|
||||
|
||||
|
||||
def game_env(base=None, **extra):
|
||||
"""The environment for every run of the game, the launcher or horizon-ctl from a tool or a harness: no audio,
|
||||
and fresh scratch folders for the game's home (logs, saves, options), the launcher's home and the XDG folders,
|
||||
so a run never writes into a real player's folders (the game falls back to them when HORIZON_HOME is unset).
|
||||
A folder the caller already has in `base` (default os.environ) or passes in `extra` is kept. The scratch folders
|
||||
are removed when this process exits."""
|
||||
env = dict(os.environ if base is None else base)
|
||||
env.update({key: str(value) for key, value in extra.items()})
|
||||
env["HORIZON_NO_AUDIO"] = "1"
|
||||
env["HORIZON_LAUNCHER_NO_SELF_UPDATE"] = "1"
|
||||
for key, prefix in (("HORIZON_HOME", "horizon-home-"), ("HORIZON_LAUNCHER_HOME", "horizon-launcher-home-"),
|
||||
("XDG_DATA_HOME", "horizon-xdg-data-"), ("XDG_CONFIG_HOME", "horizon-xdg-config-")):
|
||||
if not env.get(key):
|
||||
env[key] = _scratch_dir(prefix)
|
||||
return env
|
||||
|
||||
|
||||
def write_json(path, data):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
+45
-2
@@ -228,6 +228,9 @@ address. The script then checks, from both sides, what a guest's game used to ge
|
||||
- villagers: the guest sees each villager's and zombie villager's type, profession and level as the
|
||||
host has them, and an unemployed villager that takes a composter becomes a farmer on
|
||||
the guest too (the guest used to draw every villager as an unemployed plains one).
|
||||
- falling: an item and a falling block the host summons high up fall smoothly on the guest, a
|
||||
little further every tick between the server's updates (every 20 ticks), as their own
|
||||
client tick moves them (they used to hang, then jump down once a second, #1568).
|
||||
|
||||
Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of
|
||||
both sides go to --out (host-*.png, guest-*.png).
|
||||
@@ -275,8 +278,7 @@ class Game:
|
||||
(self.work / '.local/horizon-client').mkdir(parents=True)
|
||||
os.symlink(resources, self.work / '.local/horizon-client' / lab.VERSION)
|
||||
self.socket = self.work / 'c.sock'
|
||||
env = game_env(os.environ.get('VSCREEN', 'lan-e2e'))
|
||||
env['HORIZON_HOME'] = str(self.work / 'home')
|
||||
env = game_env(os.environ.get('VSCREEN', 'lan-e2e'), home=self.work / 'home')
|
||||
self.d = Cli(ctl, self.socket, self.work, env)
|
||||
self.d.name = name
|
||||
|
||||
@@ -5496,5 +5498,46 @@ CHECKS += ['villagers']
|
||||
CHECK_FNS.update(villagers=check_villagers)
|
||||
|
||||
|
||||
def check_falling(host, guest, out):
|
||||
"""ItemEntity and FallingBlockEntity tick on a client too (gravity, collisions, drag), and their
|
||||
position packets snap them (Entity's NO_OP InterpolationHandler). The server sends an item's
|
||||
and a falling block's position every 20 ticks, so between two updates the guest's own tick is
|
||||
what moves them: sampled every 2 ticks over the first 16, both are lower nearly every time."""
|
||||
x, y, z = (int(v // 1) for v in pos_of(guest))
|
||||
top = y + 30
|
||||
tag = 'falling_e2e'
|
||||
host('command', command=f'fill {x + 2} {y} {z - 1} {x + 4} {top + 2} {z + 1} minecraft:air')
|
||||
host('command', command=f'summon minecraft:item {x + 3.5} {top} {z + 0.5} '
|
||||
f'{{Tags:["{tag}"],Item:{{id:"minecraft:diamond",count:1}},PickupDelay:32767}}')
|
||||
host('command', command=f'summon minecraft:falling_block {x + 2.5} {top} {z - 0.5} '
|
||||
f'{{Tags:["{tag}"],BlockState:{{Name:"minecraft:sand"}},DropItem:0b}}')
|
||||
heights = {'item': [], 'falling block': []}
|
||||
try:
|
||||
for _ in range(8):
|
||||
items = [e['pos'][1] for e in guest.raw('entities', 48, 'minecraft:item')['entities']
|
||||
if abs(e['pos'][0] - x - 3.5) < 0.5 and abs(e['pos'][2] - z - 0.5) < 0.5]
|
||||
blocks = [o['position'][1] for o in guest('status')['projectiles']
|
||||
if o.get('kind') == 'minecraft:falling_block'
|
||||
and abs(o['position'][0] - x - 2.5) < 0.5 and abs(o['position'][2] - z + 0.5) < 0.5]
|
||||
heights['item'].append(items[0] if items else None)
|
||||
heights['falling block'].append(blocks[0] if blocks else None)
|
||||
guest.wait(2)
|
||||
guest.shot(out, 'falling')
|
||||
finally:
|
||||
host('command', command=f'kill @e[tag={tag}]')
|
||||
host('command', command=f'fill {x + 2} {y} {z - 1} {x + 4} {top + 2} {z + 1} minecraft:air')
|
||||
for name, ys in heights.items():
|
||||
seen = [h for h in ys if h is not None]
|
||||
assert len(seen) >= 6, f'the guest saw the {name} {len(seen)} times of 8: {heights}'
|
||||
drops = sum(b < a for a, b in zip(seen, seen[1:]))
|
||||
# A tick or two can pass between two samples with no move; never most of them.
|
||||
assert drops >= len(seen) - 2, f'the {name} fell in {drops} of {len(seen) - 1} samples: {heights}'
|
||||
return heights
|
||||
|
||||
|
||||
CHECKS += ['falling']
|
||||
CHECK_FNS.update(falling=check_falling)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
||||
@@ -167,8 +167,7 @@ def main():
|
||||
os.symlink(bins / name, version / name)
|
||||
os.symlink(resources, version / '.local/horizon-client' / lab.VERSION)
|
||||
(version / '.installed').write_text('')
|
||||
env = dict(os.environ, HORIZON_LAUNCHER_HOME=str(work / 'launcher'), HORIZON_HOME=str(work / 'home'),
|
||||
HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
|
||||
env = lab.game_env(HORIZON_LAUNCHER_HOME=work / 'launcher', HORIZON_HOME=work / 'home', HORIZON_TELEMETRY_URL='off')
|
||||
m = Mcp(Path(args.launcher).resolve(), env)
|
||||
try:
|
||||
summary = scenario(m, out)
|
||||
|
||||
@@ -33,6 +33,11 @@ import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from . import lab
|
||||
except ImportError:
|
||||
import lab
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@@ -154,8 +159,7 @@ def main():
|
||||
args = ap.parse_args()
|
||||
|
||||
home = Path(tempfile.mkdtemp(prefix="horizon-mod-browser-"))
|
||||
env = dict(os.environ, HORIZON_HOME=str(home), HORIZON_NO_AUDIO="1", HORIZON_NO_HEARTBEAT="1",
|
||||
HORIZON_CONTROL=str(home / "ctl.sock"))
|
||||
env = lab.game_env(HORIZON_HOME=home, HORIZON_NO_HEARTBEAT="1", HORIZON_CONTROL=home / "ctl.sock")
|
||||
launcher = [args.launcher]
|
||||
game = Game(str(Path(args.bin) / "horizon-ctl"), str(Path(args.bin) / "horizon-client"),
|
||||
args.resources, home, env)
|
||||
|
||||
@@ -39,6 +39,7 @@ import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -812,6 +813,12 @@ class LocalExecutor:
|
||||
trace.unlink(missing_ok=True)
|
||||
log = (STATE_DIR / "logs" / f"{name}.log").open("w")
|
||||
environment = run_environment(reuse)
|
||||
# A game the harness starts logs into HORIZON_HOME, which is a real player's folder when it is unset
|
||||
# (lab.game_env keeps this one).
|
||||
game_home = STATE_DIR / "game-home" / name
|
||||
shutil.rmtree(game_home, ignore_errors=True)
|
||||
game_home.mkdir(parents=True)
|
||||
environment.setdefault("HORIZON_HOME", str(game_home))
|
||||
environment["PARITY_SHIM_OUTPUTS"] = str(outputs_listing(name, fresh=True))
|
||||
environment.pop("PARITY_SHARD", None)
|
||||
if shard:
|
||||
|
||||
+1
-1
@@ -400,7 +400,7 @@ def run_horizon(args, distance):
|
||||
for carry in dev_mods(args):
|
||||
command += ["--dev-mod", str(carry)]
|
||||
# Benchmark runs stay out of the live count and send nothing (docs/telemetry.md).
|
||||
env = dict(os.environ, HORIZON_NO_AUDIO="1", HORIZON_TELEMETRY_URL="off")
|
||||
env = lab.game_env(HORIZON_TELEMETRY_URL="off")
|
||||
if args.warm:
|
||||
# A first start to the title screen builds what later starts reuse (the content-mod
|
||||
# root, the block behaviour snapshot). It is not measured: players see it once.
|
||||
|
||||
@@ -120,7 +120,7 @@ class Server:
|
||||
self.process = subprocess.Popen([str(c) for c in command], cwd=directory, stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
|
||||
encoding='utf-8', errors='replace',
|
||||
env=dict(os.environ, HORIZON_NO_AUDIO='1'))
|
||||
env=lab.game_env())
|
||||
threading.Thread(target=self._read, daemon=True).start()
|
||||
|
||||
def _read(self):
|
||||
|
||||
@@ -206,9 +206,8 @@ class Game:
|
||||
self.home = work / 'home'
|
||||
for d in ('home', 'launcher', 'data', 'config'):
|
||||
(work / d).mkdir(parents=True)
|
||||
self.env = dict(os.environ, HORIZON_HOME=str(self.home), HORIZON_LAUNCHER_HOME=str(work / 'launcher'),
|
||||
XDG_DATA_HOME=str(work / 'data'), XDG_CONFIG_HOME=str(work / 'config'),
|
||||
HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
|
||||
self.env = lab.game_env(HORIZON_HOME=self.home, HORIZON_LAUNCHER_HOME=work / 'launcher',
|
||||
XDG_DATA_HOME=work / 'data', XDG_CONFIG_HOME=work / 'config', HORIZON_TELEMETRY_URL='off')
|
||||
self.base = [str(bins / 'horizon-ctl'), '--socket', str(work / 'c.sock')]
|
||||
self.log = work / 'c.log'
|
||||
reply = self('launch', '--game', bins / 'horizon-client', '--offscreen', '--resources', resources)
|
||||
@@ -343,7 +342,7 @@ class Run:
|
||||
('XDG_CONFIG_HOME', 'config')):
|
||||
(work / 'servers' / sub).mkdir(parents=True)
|
||||
os.environ[var] = str(work / 'servers' / sub)
|
||||
os.environ.update(HORIZON_LAUNCHER_NO_SELF_UPDATE='1', HORIZON_NO_AUDIO='1', HORIZON_TELEMETRY_URL='off')
|
||||
os.environ.update(lab.game_env(HORIZON_TELEMETRY_URL='off'))
|
||||
game = self.game = Game(Path(self.args.bin), self.resources, work / 'game')
|
||||
servers_dat = game.home / 'servers.dat'
|
||||
downloads = game.home / 'downloads'
|
||||
|
||||
@@ -183,7 +183,7 @@ def main():
|
||||
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
|
||||
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
|
||||
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
|
||||
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
|
||||
# Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared.
|
||||
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
|
||||
native = h.split_cases((work / 'native.txt').read_text(), ignore)
|
||||
|
||||
@@ -82,7 +82,7 @@ def main():
|
||||
rust_dir = build / 'rust'
|
||||
shutil.rmtree(rust_dir, ignore_errors=True)
|
||||
rust_dir.mkdir()
|
||||
env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_COMMAND_SCRIPT=str(script_path), HORIZON_COMMAND_OUTPUT=str(build / 'rust.jsonl'))
|
||||
env = lab.game_env(HORIZON_COMMAND_SCRIPT=script_path, HORIZON_COMMAND_OUTPUT=build / 'rust.jsonl')
|
||||
run([binary, '--resources', lab.RESOURCES, '--world', 'harness', '--seed', SEED, '--radius', 4], 'rust', cwd=rust_dir, env=env)
|
||||
|
||||
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').open(encoding='utf-8')]
|
||||
|
||||
@@ -125,7 +125,7 @@ def main():
|
||||
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
|
||||
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
|
||||
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
|
||||
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
|
||||
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
|
||||
native = h.split_cases((work / 'native.txt').read_text(), ignore)
|
||||
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
|
||||
|
||||
@@ -245,7 +245,7 @@ def main():
|
||||
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
|
||||
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
|
||||
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
|
||||
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
|
||||
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
|
||||
native = h.split_cases((work / 'native.txt').read_text(), ignore)
|
||||
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
|
||||
|
||||
@@ -126,7 +126,7 @@ class Server:
|
||||
self.lines = []
|
||||
self.process = subprocess.Popen(list(map(str, command)), cwd=directory, stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
|
||||
encoding='utf-8', errors='replace')
|
||||
encoding='utf-8', errors='replace', env=lab.game_env())
|
||||
self.reader = threading.Thread(target=self._read, daemon=True)
|
||||
self.reader.start()
|
||||
|
||||
@@ -352,7 +352,7 @@ def horizon_client_joins(vanilla_server, binary, world, build, reference):
|
||||
server = Server(vanilla_server, directory, label)
|
||||
try:
|
||||
server.wait_for(r'Done \(')
|
||||
env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_NET_REPORT=str(report))
|
||||
env = lab.game_env(HORIZON_NET_REPORT=report)
|
||||
with (build / 'horizon-client-run.log').open('w') as log:
|
||||
subprocess.run([str(c) for c in [binary, '--resources', lab.RESOURCES, '--render-distance', 2,
|
||||
'--server', f'127.0.0.1:{port}', '--name', PLAYER]],
|
||||
|
||||
@@ -417,7 +417,7 @@ def main():
|
||||
run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
|
||||
run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
|
||||
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
|
||||
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
|
||||
# Loot table names (D) are vanilla's bookkeeping; the drops themselves are compared.
|
||||
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
|
||||
native = h.split_cases((work / 'native.txt').read_text(), ignore)
|
||||
|
||||
@@ -96,7 +96,7 @@ class Game:
|
||||
self.process = subprocess.Popen(Game.prefix + [
|
||||
str(client), '--resources', str(resources), '--render-distance', '2', '--test-terrain',
|
||||
'--control-socket', str(self.endpoint), '--timeout-seconds', '600',
|
||||
] + Game.extra, cwd=self.home, env=dict(os.environ, HORIZON_HOME=str(self.home), HORIZON_NO_AUDIO='1', **env),
|
||||
] + Game.extra, cwd=self.home, env=lab.game_env(HORIZON_HOME=self.home, **env),
|
||||
stdout=self.log, stderr=subprocess.STDOUT)
|
||||
wait_for(self.endpoint, 'screen', lambda v: v['screen'] == 'title', 120, f'{name} title')
|
||||
|
||||
|
||||
@@ -170,7 +170,7 @@ def main():
|
||||
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
|
||||
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
|
||||
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
|
||||
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
|
||||
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
|
||||
native = h.split_cases((work / 'native.txt').read_text(), ignore)
|
||||
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
|
||||
|
||||
@@ -71,7 +71,7 @@ def main():
|
||||
str(executable), '--radius', '1', '--frames', '30',
|
||||
'--smoke-report', str(report), '--timeout-seconds', '60']
|
||||
with (root / 'startup-smoke.log').open('w') as log:
|
||||
subprocess.run(command, cwd=lab.ROOT, env=environment, check=True,
|
||||
subprocess.run(command, cwd=lab.ROOT, env=lab.game_env(environment), check=True,
|
||||
stdout=log, stderr=subprocess.STDOUT, timeout=120)
|
||||
result = json.loads(report.read_text())
|
||||
if (result.get('error') is not None or result.get('presented_frames') != 30
|
||||
|
||||
@@ -179,7 +179,7 @@ def run_client(binary, build, port, label, token, discovery):
|
||||
shutil.rmtree(directory, ignore_errors=True)
|
||||
directory.mkdir()
|
||||
report = directory / 'report.json'
|
||||
env = dict(os.environ, HORIZON_NO_AUDIO='1', HORIZON_NET_REPORT=str(report), HORIZON_API_DISCOVERY=discovery)
|
||||
env = lab.game_env(HORIZON_NET_REPORT=report, HORIZON_API_DISCOVERY=discovery)
|
||||
command = [binary, '--resources', lab.RESOURCES, '--render-distance', 2,
|
||||
'--server', f'127.0.0.1:{port}', '--name', PLAYER]
|
||||
if token:
|
||||
@@ -246,7 +246,7 @@ def run_side(label, command, binary, build, services, discovery):
|
||||
props = dict(PROPERTIES, **{'server-port': str(port)})
|
||||
(directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()))
|
||||
(directory / 'eula.txt').write_text('eula=true\n')
|
||||
os.environ.update(HORIZON_NO_AUDIO='1', HORIZON_API_DISCOVERY=discovery)
|
||||
os.environ.update(lab.game_env(HORIZON_API_DISCOVERY=discovery))
|
||||
server = Server(command, directory, f'{label}-online')
|
||||
checks = []
|
||||
starts = []
|
||||
|
||||
@@ -330,7 +330,7 @@ def entity_uuid_text(i):
|
||||
|
||||
def vscreen_env():
|
||||
text = subprocess.run(['vscreen', 'env'], capture_output=True, text=True, check=True).stdout
|
||||
env = dict(os.environ)
|
||||
env = lab.game_env()
|
||||
env.pop('DISPLAY', None)
|
||||
for match in re.finditer(r'(\w+)=(\S+)', text.split('unset')[0]):
|
||||
env[match.group(1)] = match.group(2)
|
||||
@@ -346,7 +346,7 @@ def horizon_resave(source, destination, bin_dir):
|
||||
ctl = [str(bin_dir / 'horizon-ctl'), '--socket', str(socket)]
|
||||
extra = []
|
||||
if sys.platform == 'darwin':
|
||||
env = dict(os.environ, HORIZON_NO_AUDIO='1')
|
||||
env = lab.game_env()
|
||||
extra = ['--offscreen']
|
||||
else:
|
||||
alsa = destination / 'null-asound.conf'
|
||||
|
||||
@@ -339,7 +339,7 @@ def main():
|
||||
oracle_harness.run_logged(['cargo', 'build', '--locked', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'],
|
||||
build, 'compile-rust')
|
||||
oracle_harness.run_logged([lab.cargo_target() / 'release/horizon-client', '--resources', resources], build, 'horizon',
|
||||
env={**os.environ, 'HORIZON_SCULK_FIXTURE': f'{inputs},{build / "horizon.txt"}', 'HORIZON_NO_AUDIO': '1'})
|
||||
env=lab.game_env(HORIZON_SCULK_FIXTURE=f'{inputs},{build / "horizon.txt"}'))
|
||||
if args.java_only:
|
||||
return
|
||||
names = {s[0] for _, s in chosen}
|
||||
|
||||
@@ -264,7 +264,7 @@ def main():
|
||||
oh.run_logged([*java, 'keys', build], build, 'keys')
|
||||
services = Services(json.loads((build / 'publickeys.json').read_text()))
|
||||
discovery = services.url + '/minecraft/client'
|
||||
os.environ.update(HORIZON_NO_AUDIO='1', HORIZON_API_DISCOVERY=discovery)
|
||||
os.environ.update(lab.game_env(HORIZON_API_DISCOVERY=discovery))
|
||||
servers = {
|
||||
'vanilla': ['java', '-Xmx2g', '-Duser.timezone=UTC', f'-Dminecraft.api.discovery.host={discovery}',
|
||||
'-cp', dependencies, 'net.minecraft.server.Main', 'nogui'],
|
||||
|
||||
@@ -375,7 +375,7 @@ def main():
|
||||
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
|
||||
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
|
||||
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
|
||||
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
|
||||
env=lab.game_env(HORIZON_DISPENSE_FIXTURE=f'{work / "cases.jsonl"},{work / "rust.txt"}'))
|
||||
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
|
||||
native = h.split_cases((work / 'native.txt').read_text(), ignore)
|
||||
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
|
||||
|
||||
@@ -24,6 +24,9 @@ import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import lab # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
RESOURCES = ROOT / '.local' / 'horizon-client' / '26.3'
|
||||
RUN = ROOT / '.local' / 'world-reopen'
|
||||
@@ -32,7 +35,7 @@ CYCLES = 3
|
||||
|
||||
def game_env():
|
||||
"""macOS renders offscreen; Linux uses the virtual screen (as test_save_roundtrip_parity)."""
|
||||
env = dict(os.environ, HORIZON_NO_AUDIO='1')
|
||||
env = lab.game_env()
|
||||
if sys.platform == 'darwin':
|
||||
return env, ['--offscreen']
|
||||
subprocess.run(['vscreen', 'up'], check=False, capture_output=True)
|
||||
|
||||
@@ -140,7 +140,7 @@ def main():
|
||||
# One worker thread: the chunks decorated in a fixed order (see above).
|
||||
vanilla_server = ['java', '-Xmx2g', '-Dmax.bg.threads=1', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui']
|
||||
horizon_server = [binary, '--resources', RESOURCES, '--dedicated', '--nogui']
|
||||
os.environ['HORIZON_NO_AUDIO'] = '1'
|
||||
os.environ.update(lab.game_env())
|
||||
|
||||
def one(seed):
|
||||
t0 = time.time()
|
||||
|
||||
Reference in New Issue
Block a user