Merge main into fix/1482-evoker-fangs
Preserve both fang and sonic-wave integration checks. Co-Authored-By: OpenCode GPT-6.1 Sol <noreply@openai.com>
This commit is contained in:
@@ -8,7 +8,7 @@ name: nightly audit
|
||||
# gh workflow run "nightly audit" -f dry_run=true # the audit, without touching issues
|
||||
on:
|
||||
schedule:
|
||||
# GitHub's schedules are in UTC: both, and the first step keeps the one that is 03:00 in Paris.
|
||||
# GitHub's schedules are in UTC: both, and the first step keeps the one that is 03:07 in Paris today.
|
||||
- cron: '7 1 * * *'
|
||||
- cron: '7 2 * * *'
|
||||
workflow_dispatch:
|
||||
@@ -31,14 +31,19 @@ jobs:
|
||||
audit:
|
||||
# The Mac mini's runners only: the audit compares with the previous one, so it stays on one platform.
|
||||
runs-on: [self-hosted, horizon-game, macOS]
|
||||
timeout-minutes: 150
|
||||
timeout-minutes: 240 # every harness (~80 min) plus lan_integration (~40 min an attempt under load, retried)
|
||||
steps:
|
||||
- name: 03:00 in Paris
|
||||
- name: 03:07 in Paris
|
||||
id: when
|
||||
env:
|
||||
SCHEDULE: ${{ github.event.schedule }}
|
||||
run: |
|
||||
hour=$(TZ=Europe/Paris date +%H)
|
||||
if [[ "${{ github.event_name }}" == schedule && "$hour" != 03 ]]; then
|
||||
echo "It is ${hour}:00 in Paris: the other schedule runs the audit."
|
||||
# Which cron is 03:07 in Paris, from Paris's offset today: GitHub can start a schedule hours late, so the
|
||||
# clock at start time can't tell (on 2026-10-26 both started after 04:00 Paris and both skipped).
|
||||
offset=$(TZ=Europe/Paris date +%z)
|
||||
ours=$([ "$offset" = +0200 ] && echo '7 1 * * *' || echo '7 2 * * *')
|
||||
if [[ "${{ github.event_name }}" == schedule && "$SCHEDULE" != "$ours" ]]; then
|
||||
echo "Paris is at UTC${offset} today: the '$ours' schedule runs the audit."
|
||||
echo "run=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "run=true" >> "$GITHUB_OUTPUT"
|
||||
@@ -66,7 +71,8 @@ jobs:
|
||||
run: |
|
||||
echo "since=$(date +%Y-%m-%dT%H:%M:%S)" >> "$GITHUB_OUTPUT"
|
||||
set +e
|
||||
python3 tools/parity.py --all --timeout 1800 2>&1 | tee "$RUNNER_TEMP/audit.log"
|
||||
# lan_integration (the whole lan_e2e suite) takes ~2,400 s under load, past the usual 1,800.
|
||||
python3 tools/parity.py --all --timeout 3000 2>&1 | tee "$RUNNER_TEMP/audit.log"
|
||||
echo "exit=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
|
||||
{ echo '```'; tail -40 "$RUNNER_TEMP/audit.log"; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
|
||||
- name: Issues for the harnesses that regressed
|
||||
|
||||
@@ -48,6 +48,9 @@ jobs:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: echo "sha=$(python3 tools/parity_main.py base)" >> "$GITHUB_OUTPUT"
|
||||
- name: The harnesses the merges since then can affect
|
||||
id: harnesses
|
||||
# A failure here is judged by the next step: the run passes when every failed harness passes again at HEAD.
|
||||
continue-on-error: true
|
||||
env:
|
||||
PARITY_HOSTS: ''
|
||||
BASE_SHA: ${{ steps.base.outputs.sha }}
|
||||
@@ -55,8 +58,8 @@ jobs:
|
||||
echo "Merges since ${BASE_SHA}:"
|
||||
git log --first-parent --format=' %h %s' "$BASE_SHA..HEAD"
|
||||
python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400
|
||||
- name: The merge that broke them
|
||||
if: failure()
|
||||
- name: A flake, or the merge that broke them
|
||||
if: steps.harnesses.outcome == 'failure'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PARITY_HOSTS: ''
|
||||
@@ -65,7 +68,7 @@ jobs:
|
||||
rm -rf .local/parity-main-logs && cp -R .local/parity-runner/logs .local/parity-main-logs 2>/dev/null || true
|
||||
python3 tools/parity_main.py bisect "$BASE_SHA" --comment
|
||||
- name: Logs of the failed harnesses
|
||||
if: failure()
|
||||
if: steps.harnesses.outcome == 'failure'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: parity-main-logs
|
||||
|
||||
@@ -66,7 +66,7 @@ cargo build --profile fast -p horizon-client # optimized, quick to link:
|
||||
python3 tools/parity.py --changed origin/main # the harnesses your branch can affect (CI's parity job)
|
||||
python3 tools/parity.py --changed-files paths.txt --list # which harnesses cover these files, without running them
|
||||
python3 tools/parity.py mob_ai sculk # named harnesses
|
||||
python3 tools/lan_e2e.py --check chest # two real games over LAN (host in-frame); --server-thread for the host on its server thread
|
||||
python3 tools/lan_e2e.py --check chest # two real games over LAN (server-thread host); --in-frame compares the fallback
|
||||
python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
|
||||
```
|
||||
|
||||
@@ -156,7 +156,7 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
|
||||
exactly as a LAN guest or a dedicated server's player does. This is what players run. Open
|
||||
`[server-thread]` issues list the gaps left.
|
||||
2. **In-frame (`--in-frame`, `--no-server-thread` or `HORIZON_SERVER_THREAD=0`):** the window's `Game` ticks
|
||||
the world itself, one level that follows the player (`fn enter_dimension`). Most harnesses test this path.
|
||||
the world itself, one level that follows the player (`fn enter_dimension`). Deterministic rule fixtures still use this path; player-facing integration uses the default server thread.
|
||||
|
||||
LAN guests and dedicated servers always use the server code, so a fix there serves both. Test both paths
|
||||
when you touch player-facing gameplay:
|
||||
@@ -164,8 +164,8 @@ when you touch player-facing gameplay:
|
||||
```sh
|
||||
cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T # server thread
|
||||
cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T --in-frame # in-frame
|
||||
python3 tools/lan_e2e.py --check <name> # host in-frame, guest is a server client
|
||||
python3 tools/lan_e2e.py --server-thread --check <name> # host on its server thread (portals, levels, distance, lava need it)
|
||||
python3 tools/lan_e2e.py --check <name> # host on its server thread, guest is a server client
|
||||
python3 tools/lan_e2e.py --in-frame --check <name> # comparison (portals, levels, distance, lava need server-thread mode)
|
||||
python3 tools/parity.py dedicated_server server_entities server_player_damage
|
||||
```
|
||||
|
||||
|
||||
Generated
+24
@@ -1444,6 +1444,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"toml",
|
||||
"wasmparser",
|
||||
"wasmtime",
|
||||
"wit-component",
|
||||
"wit-parser",
|
||||
@@ -4148,6 +4149,28 @@ dependencies = [
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wast"
|
||||
version = "254.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "febc59cde513fc8f39b8ffd487893723c555fdd024e2e3dc7d165181e6397ea0"
|
||||
dependencies = [
|
||||
"bumpalo",
|
||||
"leb128fmt",
|
||||
"memchr",
|
||||
"unicode-width",
|
||||
"wasm-encoder",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wat"
|
||||
version = "1.254.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7db96351e51a3a1bbe6812f029e1100b4d9a5e02161fb63104bd2271fc847e7e"
|
||||
dependencies = [
|
||||
"wast",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wayland-backend"
|
||||
version = "0.3.17"
|
||||
@@ -5013,6 +5036,7 @@ dependencies = [
|
||||
"wasm-encoder",
|
||||
"wasm-metadata",
|
||||
"wasmparser",
|
||||
"wat",
|
||||
"wit-parser",
|
||||
]
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ impl Report {
|
||||
"api": self.facts.api,
|
||||
"side": self.facts.side,
|
||||
"capabilities": self.facts.capabilities,
|
||||
"api_level": self.facts.api_level,
|
||||
"game": self.facts.game,
|
||||
"requires": requires,
|
||||
"sha256": self.sha256,
|
||||
@@ -87,6 +88,9 @@ impl Report {
|
||||
")\n {} bytes, SHA-256 {}, {signed}\n",
|
||||
self.size, self.sha256
|
||||
);
|
||||
if let Some(level) = f.api_level {
|
||||
out += &format!(" needs mod API level {level} or newer\n");
|
||||
}
|
||||
for c in &f.capabilities {
|
||||
out += &format!(" may {}\n", c.describe());
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ use horizon_client::mesher::Vertex;
|
||||
use horizon_client::mobs::{
|
||||
Mob, MobData, MobTypes, Part, Species, allay,
|
||||
anim::{self, Poses, State},
|
||||
aquatic, body_anim as b_anim, equine, guardian,
|
||||
aquatic, bat, body_anim as b_anim, equine, guardian,
|
||||
keyframes::AnimationState,
|
||||
render, shulker, sniffer, species, tame,
|
||||
};
|
||||
@@ -108,6 +108,22 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) {
|
||||
let flag = |k: &str| case[k].as_bool().unwrap_or(false);
|
||||
let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32;
|
||||
match species {
|
||||
Species::Bat => {
|
||||
mob.extra.flag = flag("isResting");
|
||||
mob.anim.states[0].started = case["flyAnimationState"].as_f64().map(|v| v as f32);
|
||||
mob.anim.states[1].started = case["restAnimationState"].as_f64().map(|v| v as f32);
|
||||
if let Some(ticks) = case["@batTicks"].as_array() {
|
||||
for (i, flags) in ticks.iter().enumerate() {
|
||||
mob.age = i as u32 + 1;
|
||||
bat::set_resting(mob, flags.as_i64().unwrap_or(0) & 1 != 0);
|
||||
if flag("@batInFrame") {
|
||||
bat::tick(mob);
|
||||
} else {
|
||||
bat::setup_animation_states(mob);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Species::Sheep => mob.extra.anim_ticks = num("eatTick") as i32,
|
||||
Species::Guardian | Species::ElderGuardian => {
|
||||
mob.anim.v[guardian::TAIL] = num("tailAnimation");
|
||||
@@ -377,7 +393,7 @@ pub fn main() -> horizon_client::Result<()> {
|
||||
mob.extra.age = -24000;
|
||||
}
|
||||
mob.age = f("ageInTicks") as u32;
|
||||
let state = State {
|
||||
let mut state = State {
|
||||
pos: f("walkAnimationPos"),
|
||||
speed: f("walkAnimationSpeed"),
|
||||
age: f("ageInTicks"),
|
||||
@@ -389,6 +405,20 @@ pub fn main() -> horizon_client::Result<()> {
|
||||
};
|
||||
let mut poses = Poses::new(&model);
|
||||
entity_state(&mut mob, def.species, case);
|
||||
if let Some(ticks) = case["@walkTicks"].as_array() {
|
||||
for speed in ticks {
|
||||
mob.previous_limb_speed = mob.limb_speed;
|
||||
mob.limb_speed += (speed.as_f64().unwrap() as f32 - mob.limb_speed) * 0.4;
|
||||
mob.limb_position += mob.limb_speed;
|
||||
}
|
||||
if !case["@alive"].as_bool().unwrap() {
|
||||
mob.health = 0.0;
|
||||
}
|
||||
let extracted = anim::state(&mob, f("@partial"));
|
||||
state.pos = extracted.pos;
|
||||
state.speed = extracted.speed;
|
||||
}
|
||||
|
||||
let flag = |k: &str| case[k].as_bool().unwrap_or(false);
|
||||
let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32;
|
||||
let started = |k: &str| AnimationState {
|
||||
@@ -456,14 +486,6 @@ pub fn main() -> horizon_client::Result<()> {
|
||||
roll_amount: num("rollAmount"),
|
||||
},
|
||||
),
|
||||
Species::Bat => b_anim::bat(
|
||||
p,
|
||||
s,
|
||||
flag("isResting"),
|
||||
&started("flyAnimationState"),
|
||||
&started("restAnimationState"),
|
||||
&animations,
|
||||
),
|
||||
Species::Armadillo => b_anim::armadillo(
|
||||
p,
|
||||
s,
|
||||
@@ -590,7 +612,11 @@ pub fn main() -> horizon_client::Result<()> {
|
||||
}
|
||||
_ => anim::setup(&mob, s, p, &animations),
|
||||
}
|
||||
out.push_str(&format!("{}\n", emit(&model, &mut poses, case, layer)));
|
||||
let mut result = emit(&model, &mut poses, case, layer);
|
||||
if case["@walkTicks"].is_array() {
|
||||
result["walk"] = json!([state.pos, state.speed]);
|
||||
}
|
||||
out.push_str(&format!("{result}\n"));
|
||||
}
|
||||
fs::write(&args[2], out)?;
|
||||
Ok(())
|
||||
|
||||
@@ -49,6 +49,7 @@ struct Scenario {
|
||||
name: String,
|
||||
ticks: i32,
|
||||
time: i64,
|
||||
difficulty: u8,
|
||||
rain: bool,
|
||||
thunder: bool,
|
||||
origin: [i32; 2],
|
||||
@@ -85,11 +86,13 @@ fn parse(text: &str) -> Vec<Scenario> {
|
||||
"scenario" => {
|
||||
s.name = f[1].to_owned();
|
||||
s.time = 6000;
|
||||
s.difficulty = 2;
|
||||
for kv in &f[2..] {
|
||||
let (k, v) = kv.split_once('=').unwrap_or((kv, ""));
|
||||
match k {
|
||||
"ticks" => s.ticks = v.parse().unwrap(),
|
||||
"time" => s.time = v.parse().unwrap(),
|
||||
"difficulty" => s.difficulty = v.parse().unwrap(),
|
||||
"rain" => s.rain = true,
|
||||
"thunder" => s.thunder = true,
|
||||
"levelseed" => {}
|
||||
@@ -954,6 +957,10 @@ pub fn main() -> horizon_client::Result<()> {
|
||||
for flag in &spec.flags {
|
||||
match flag.as_str() {
|
||||
"persistent" => m.persistent = true,
|
||||
"named" => {
|
||||
m.custom_name = Some("Peaceful regression".into());
|
||||
m.persistent = true;
|
||||
}
|
||||
"ridden" => {
|
||||
m.extra.head = Some("minecraft:red_harness".into());
|
||||
m.rider = Some(horizon_client::mobs::equine::Rider::default());
|
||||
@@ -1090,7 +1097,7 @@ pub fn main() -> horizon_client::Result<()> {
|
||||
block_tags: &items.block_tags,
|
||||
biomes: &biomes,
|
||||
mob_griefing: true,
|
||||
difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0),
|
||||
difficulty: LocalDifficulty::new(s.difficulty, world.day_time, 0, 0.0),
|
||||
end: false,
|
||||
world_seed: 0,
|
||||
// FlatLevelSource.getSeaLevel.
|
||||
|
||||
@@ -323,10 +323,15 @@ const QUIET_MESHES_PER_S: f64 = 100.0;
|
||||
/// happened (`tools/perf_bench.py`'s `wait_loaded`). With `status.streaming`, the sections are
|
||||
/// drawn once no stage has held work for half a second: blocks changing after the load (fluids
|
||||
/// settling, random ticks) only remesh in bursts. Without it, meshing has to go quiet.
|
||||
///
|
||||
/// Right after a teleport (and at spawn) the game reports nothing queued and steady counts for over
|
||||
/// a second before it starts loading: the counts must change once, or stay full for 5 s, and the
|
||||
/// resident chunks reach [`view_chunks`], before "steady" means loaded.
|
||||
fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result<Instant, String> {
|
||||
let deadline = Instant::now() + LOAD_LIMIT;
|
||||
let (mut last, mut changed, mut meshing) = (None, Instant::now(), Instant::now());
|
||||
let mut previous: Option<(Instant, f64)> = None;
|
||||
let (mut first, mut moved, began) = (None, false, Instant::now());
|
||||
while Instant::now() < deadline {
|
||||
let s = control.status();
|
||||
let now = Instant::now();
|
||||
@@ -339,6 +344,19 @@ fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result<Insta
|
||||
(last, changed, previous, meshing) = (None, now, None, now);
|
||||
} else {
|
||||
let counts = (s["chunks"].as_u64(), s["generated_chunks"].as_u64());
|
||||
let resident = counts.0.unwrap_or(0);
|
||||
let min_chunks = view_chunks(s["render_distance"].as_u64().unwrap_or(0));
|
||||
let first = *first.get_or_insert(counts);
|
||||
moved = moved
|
||||
|| counts != first
|
||||
|| (min_chunks > 0
|
||||
&& resident >= min_chunks
|
||||
&& now - began > Duration::from_secs(5));
|
||||
if min_chunks > 0 && (!moved || resident < min_chunks) {
|
||||
(last, changed, previous, meshing) = (None, now, None, now);
|
||||
thread::sleep(Duration::from_millis(50));
|
||||
continue;
|
||||
}
|
||||
if last != Some(counts) {
|
||||
(last, changed) = (Some(counts), now);
|
||||
}
|
||||
@@ -370,6 +388,12 @@ fn wait_loaded(control: &Control, near: impl Fn(&Value) -> bool) -> Result<Insta
|
||||
Err(format!("not loaded after {} s", LOAD_LIMIT.as_secs()))
|
||||
}
|
||||
|
||||
/// 80% of the view circle (pi x RD^2): the game keeps 637 columns at RD 12 and 3725 at RD 32
|
||||
/// (`tools/perf_bench.py`'s `view_chunks`).
|
||||
fn view_chunks(distance: u64) -> u64 {
|
||||
(0.8 * std::f64::consts::PI * (distance * distance) as f64) as u64
|
||||
}
|
||||
|
||||
/// Vanilla's yaw facing from `start` to `end`.
|
||||
fn yaw(start: [f64; 3], end: [f64; 3]) -> f64 {
|
||||
(-(end[0] - start[0])).atan2(end[2] - start[2]).to_degrees()
|
||||
@@ -420,6 +444,13 @@ mod tests {
|
||||
assert!(scenes("nether").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_chunks_matches_perf_bench() {
|
||||
assert_eq!(view_chunks(12), 361);
|
||||
assert_eq!(view_chunks(32), 2573);
|
||||
assert_eq!(view_chunks(0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yaw_matches_vanilla() {
|
||||
// South (+Z) is 0, west (-X) 90, east (+X) -90.
|
||||
|
||||
@@ -610,12 +610,17 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn unreachable_games_fail_with_status_3() {
|
||||
let mut s = Session::new(std::env::temp_dir().join("horizon-ctl-nobody.sock"), None);
|
||||
let home =
|
||||
std::env::temp_dir().join(format!("horizon-ctl-unreachable-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
let mut s = Session::new(home.join("nobody.sock"), None);
|
||||
s.home = home.clone();
|
||||
let f = s.run(&["state".to_owned()]).unwrap_err();
|
||||
assert_eq!(f.status, UNREACHABLE);
|
||||
assert_eq!(f.reply["kind"], "connection");
|
||||
let f = s.run(&["sleep".to_owned(), "x".to_owned()]).unwrap_err();
|
||||
assert_eq!(f.status, USAGE);
|
||||
std::fs::remove_dir_all(home).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -558,12 +558,11 @@ fn frac(x: f32) -> f32 {
|
||||
/// `StringSplitter.splitLines(...).get(0)` for plain text: the first line,
|
||||
/// wrapped at the last space that fits or mid-word when none does.
|
||||
fn first_line(line: &str, max_width: f32, advance: &dyn Fn(char) -> f32) -> String {
|
||||
let chars: Vec<char> = line.chars().collect();
|
||||
let mut width = 0.0;
|
||||
let mut last_space = None;
|
||||
for (i, &c) in chars.iter().enumerate() {
|
||||
for (i, c) in line.char_indices() {
|
||||
if c == '\n' {
|
||||
return chars[..i].iter().collect();
|
||||
return line[..i].to_owned();
|
||||
}
|
||||
if c == ' ' {
|
||||
last_space = Some(i);
|
||||
@@ -572,9 +571,11 @@ fn first_line(line: &str, max_width: f32, advance: &dyn Fn(char) -> f32) -> Stri
|
||||
if width > max_width {
|
||||
let end = match last_space {
|
||||
Some(s) if s > 0 => s,
|
||||
_ => i.max(1),
|
||||
_ if i > 0 => i,
|
||||
// The first char alone is too wide: take that one char.
|
||||
_ => c.len_utf8(),
|
||||
};
|
||||
return chars[..end].iter().collect();
|
||||
return line[..end].to_owned();
|
||||
}
|
||||
}
|
||||
line.to_owned()
|
||||
@@ -2098,4 +2099,13 @@ mod tests {
|
||||
assert_eq!(out[1].pos, [2.0, 0.0, 0.0]);
|
||||
assert_eq!(out[2].uv, [0.5, 0.5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_line_wraps_on_bytes_without_splitting_a_char() {
|
||||
let advance = |c: char| if c == ' ' { 4.0 } else { 6.0 };
|
||||
assert_eq!(first_line("ab cd ef", 13.0, &advance), "ab");
|
||||
assert_eq!(first_line("abcdef", 13.0, &advance), "ab");
|
||||
assert_eq!(first_line("\u{6771}", 3.0, &advance), "\u{6771}");
|
||||
assert_eq!(first_line("ab\ncd", 100.0, &advance), "ab");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -436,3 +436,34 @@ fn the_chat_option_filters_the_lines_both_ways() {
|
||||
chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::Full));
|
||||
assert_eq!(shown(&chat), ["client", "server", "player"]);
|
||||
}
|
||||
|
||||
/// The in-frame LAN host's chat: a guest's line is a player message, so the
|
||||
/// Chat option's player-message permission hides it at Commands Only and
|
||||
/// Hidden; command feedback (`/list`, `/tp`) is a system message and stays
|
||||
/// at Commands Only.
|
||||
#[test]
|
||||
fn a_guests_line_follows_the_player_message_permission() {
|
||||
let font = font();
|
||||
let shown = |visibility, source| {
|
||||
let mut chat = Chat::default();
|
||||
chat.set_abilities(&font, ChatAbilities::new(visibility));
|
||||
chat.add_message(&font, Text::literal("line"), None, source, 0, false);
|
||||
chat.messages.len()
|
||||
};
|
||||
for (visibility, player, system) in [
|
||||
(ChatVisibility::Full, 1, 1),
|
||||
(ChatVisibility::System, 0, 1),
|
||||
(ChatVisibility::Hidden, 0, 0),
|
||||
] {
|
||||
assert_eq!(
|
||||
shown(visibility, ChatSource::Player),
|
||||
player,
|
||||
"{visibility:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
shown(visibility, ChatSource::Server),
|
||||
system,
|
||||
"{visibility:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,20 @@ pub fn block_strategy() -> Strategy {
|
||||
Strategy::blocks(BLOCK_BITS.load(std::sync::atomic::Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// Frees `columns` (`count` of them) on a short-lived thread of its own
|
||||
/// when there are many: a teleport or a dimension change drops a few
|
||||
/// thousand columns at once, and freeing their sections took the frame
|
||||
/// 15-20 ms. A few are freed here.
|
||||
pub fn free_columns<T: Send + 'static>(columns: T, count: usize) {
|
||||
if count < 64 {
|
||||
return;
|
||||
}
|
||||
// Should the thread not start, the closure drops `columns` here.
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("Chunk freeing".into())
|
||||
.spawn(move || drop(columns));
|
||||
}
|
||||
|
||||
/// Sizes the block states' global palette for a registry of `states`.
|
||||
pub fn set_block_states(states: usize) {
|
||||
let bits = horizon_core::paletted::ceil_log2(states).max(16);
|
||||
|
||||
@@ -221,18 +221,17 @@ pub fn scale(
|
||||
pub fn draw(font: &Font, columns: [&[String]; 2], scale: f32, width: i32) -> Vec<GuiDraw> {
|
||||
let mut out = vec![GuiDraw::Push(vec![PoseOp::Scale(scale, scale)])];
|
||||
for (lines, align_left) in [(columns[0], true), (columns[1], false)] {
|
||||
let placed: Vec<(&String, i32, i32)> = lines
|
||||
let placed: Vec<(&String, i32, i32, i32)> = lines
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, l)| !l.is_empty())
|
||||
.map(|(i, l)| {
|
||||
let w = font.width(l) as i32;
|
||||
let left = if align_left { 2 } else { width - 2 - w };
|
||||
(l, left, 2 + LINE_HEIGHT * i as i32)
|
||||
(l, left, 2 + LINE_HEIGHT * i as i32, w)
|
||||
})
|
||||
.collect();
|
||||
for (line, left, top) in &placed {
|
||||
let w = font.width(line) as i32;
|
||||
for (_, left, top, w) in &placed {
|
||||
out.push(fill(
|
||||
left - 1,
|
||||
top - 1,
|
||||
@@ -241,7 +240,7 @@ pub fn draw(font: &Font, columns: [&[String]; 2], scale: f32, width: i32) -> Vec
|
||||
BACKGROUND,
|
||||
));
|
||||
}
|
||||
for (line, left, top) in placed {
|
||||
for (line, left, top, _) in placed {
|
||||
out.push(GuiDraw::Text {
|
||||
text: Text::literal(line.clone()),
|
||||
x: left,
|
||||
|
||||
@@ -1201,6 +1201,31 @@ mod tests {
|
||||
assert!(!font.take_patches().is_empty());
|
||||
}
|
||||
|
||||
/// A renderer rebuilt over the same font (the loading screen's handoff)
|
||||
/// makes its atlas texture from the textures alone, so the glyphs it had
|
||||
/// rasterized into the previous texture must be placed into the new one.
|
||||
#[test]
|
||||
fn a_rebuilt_atlas_gets_its_glyphs_again() {
|
||||
let sheet = png(16, 8, |x, _| x < 2 || (8..14).contains(&x));
|
||||
let default = br#"{"providers":[{"type":"bitmap","file":"minecraft:font/a.png","ascent":7,"chars":["ab"]}]}"#;
|
||||
let root = root(
|
||||
"rebuild",
|
||||
&[
|
||||
("assets/minecraft/font/default.json", default),
|
||||
("assets/minecraft/textures/font/a.png", &sheet),
|
||||
],
|
||||
);
|
||||
let font = load(&root);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let first = font.glyph('a');
|
||||
assert_eq!(font.take_patches().len(), 1);
|
||||
font.reset_cache();
|
||||
// Nothing is left over: drawing the character again places its pixels.
|
||||
assert!(font.take_patches().is_empty());
|
||||
assert_eq!(font.glyph('a').advance, first.advance);
|
||||
assert_eq!(font.take_patches().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_filters_follow_the_font_options() {
|
||||
let sheet = png(8, 8, |x, _| x < 4);
|
||||
|
||||
@@ -1580,6 +1580,8 @@ struct Game<'a> {
|
||||
/// position) for the guests.
|
||||
lan_block_events: Vec<([i32; 3], i32, i32, u32)>,
|
||||
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
|
||||
/// Successful crits (attacking guest, hit entity), queued while the hub is taken.
|
||||
lan_critical_hits: Vec<(Option<u32>, i32)>,
|
||||
/// Global level events for every guest (`ServerLevel.globalLevelEvent`).
|
||||
lan_global_events: Vec<(i32, [i32; 3], i32)>,
|
||||
/// `ContainerOpenersCounter`: how many players (the host and the guests)
|
||||
@@ -4200,6 +4202,9 @@ impl Game<'_> {
|
||||
self.with_level(|b, level, ticks| b.notify_written(level, ticks, position, flags));
|
||||
}
|
||||
fn tick(&mut self) -> Result<()> {
|
||||
if self.agent.hold_server {
|
||||
return Ok(());
|
||||
}
|
||||
self.tick_debug_keys()?;
|
||||
self.tick_debug_charts();
|
||||
if self.remote.is_some() {
|
||||
@@ -5607,6 +5612,8 @@ impl Game<'_> {
|
||||
self.craft_size = 2;
|
||||
self.craft_table = None;
|
||||
if let Some(key) = self.container.take() {
|
||||
// A cart's or chest boat's items go back to it.
|
||||
self.close_cart_container(key);
|
||||
self.container_opener_event(key, false);
|
||||
self.post_block_game_event(
|
||||
"minecraft:container_close",
|
||||
@@ -5646,7 +5653,6 @@ impl Game<'_> {
|
||||
self.world.modified.insert((key.0 >> 4, key.2 >> 4));
|
||||
}
|
||||
self.close_ender_chest();
|
||||
self.close_cart_container();
|
||||
}
|
||||
/// `quickMoveStack` of the open plain menu for a shift-click.
|
||||
fn inventory_quick_move(&mut self, slot: usize) -> bool {
|
||||
@@ -6891,6 +6897,9 @@ impl Game<'_> {
|
||||
self.prepare_entity_culling(camera);
|
||||
self.prepare_trims();
|
||||
self.mark_entity(out.len(), "minecraft:entity_flame");
|
||||
// One scan for both passes that draw them (block entities below and the
|
||||
// overlay near the end of this function).
|
||||
let cracks = self.cracks(camera);
|
||||
let fire_yaw = if self.camera_type == perspective::CameraType::ThirdPersonFront {
|
||||
self.yaw + 180.0
|
||||
} else {
|
||||
@@ -7116,7 +7125,7 @@ impl Game<'_> {
|
||||
.render(&scene, visible, &mut out);
|
||||
}
|
||||
self.mark_stage(out.len(), "DESTROY");
|
||||
for (pos, stage) in self.cracks(camera) {
|
||||
for &(pos, stage) in &cracks {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
self.res
|
||||
.block_entity_render()
|
||||
@@ -7259,7 +7268,7 @@ impl Game<'_> {
|
||||
);
|
||||
// Breaking progress overlays (destroy_stage_0..9): ours and the other players'.
|
||||
self.mark_stage(out.len(), "DESTROY");
|
||||
for (pos, stage) in self.cracks(camera) {
|
||||
for &(pos, stage) in &cracks {
|
||||
let o = (glam::DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2]))
|
||||
- camera)
|
||||
.as_vec3();
|
||||
@@ -7307,6 +7316,20 @@ impl Game<'_> {
|
||||
/// other players' (`renderBlockDestroyAnimation`: within 32 blocks of the camera, the
|
||||
/// furthest progress on each block).
|
||||
fn cracks(&self, camera: glam::DVec3) -> Vec<([i32; 3], [f32; 2])> {
|
||||
// `destroy_stage_0` .. `destroy_stage_9`: the sprite name by stage, so the
|
||||
// lookup does not format a string per crack.
|
||||
const DESTROY_STAGES: [&str; 10] = [
|
||||
"block/destroy_stage_0",
|
||||
"block/destroy_stage_1",
|
||||
"block/destroy_stage_2",
|
||||
"block/destroy_stage_3",
|
||||
"block/destroy_stage_4",
|
||||
"block/destroy_stage_5",
|
||||
"block/destroy_stage_6",
|
||||
"block/destroy_stage_7",
|
||||
"block/destroy_stage_8",
|
||||
"block/destroy_stage_9",
|
||||
];
|
||||
let mut stages: Vec<([i32; 3], u32)> = Vec::new();
|
||||
let mut add = |pos: [i32; 3], stage: u32| match stages.iter_mut().find(|c| c.0 == pos) {
|
||||
Some(c) => c.1 = c.1.max(stage),
|
||||
@@ -7332,11 +7355,8 @@ impl Game<'_> {
|
||||
d.length_squared() <= 1024.0
|
||||
})
|
||||
.filter_map(|(pos, stage)| {
|
||||
let r = self
|
||||
.gui
|
||||
.atlas
|
||||
.sprites
|
||||
.get(&format!("block/destroy_stage_{stage}"))?;
|
||||
let name = DESTROY_STAGES.get(stage as usize)?;
|
||||
let r = self.gui.atlas.sprites.get(*name)?;
|
||||
Some((pos, [r.u0, r.v0]))
|
||||
})
|
||||
.collect()
|
||||
@@ -7601,10 +7621,9 @@ impl Game<'_> {
|
||||
self.stats
|
||||
.custom("damage_dealt", (actual * 10.0).round() as i32);
|
||||
if crit {
|
||||
self.particles.tracking_emitter(
|
||||
horizon_client::particles::ParticleOptions::simple(
|
||||
horizon_client::particles::ParticleType::Crit,
|
||||
),
|
||||
self.critical_hit(
|
||||
self.lan_acting,
|
||||
self.mobs[index].id as i32,
|
||||
feet,
|
||||
width,
|
||||
height,
|
||||
@@ -10299,8 +10318,6 @@ impl Game<'_> {
|
||||
Vec::new()
|
||||
};
|
||||
let mut hud = horizon_client::spans::time("hud", || self.hud(size));
|
||||
// Map textures changed since the last drawn frame (game/maps.rs).
|
||||
hud.patches.append(&mut self.map_patches);
|
||||
// LevelLoadingScreen (Reason.OTHER) draws the title's panorama.
|
||||
let title = self.title.is_some()
|
||||
|| self.loading_reason() == Some(horizon_client::level_loading::Reason::Other);
|
||||
@@ -10402,6 +10419,10 @@ impl Game<'_> {
|
||||
} else {
|
||||
self.shader_pack_inputs(camera, alpha as f32)
|
||||
};
|
||||
// Map textures and font glyphs changed while building this frame's
|
||||
// geometry (game/maps.rs, world text) upload with this batch; draining
|
||||
// map_patches any earlier leaves them a frame behind.
|
||||
hud.patches.append(&mut self.map_patches);
|
||||
let entity_spans = std::mem::take(self.entity_spans.get_mut());
|
||||
let frame = Frame {
|
||||
weather: &weather,
|
||||
@@ -11017,11 +11038,7 @@ impl Game<'_> {
|
||||
bytes += size;
|
||||
}
|
||||
}
|
||||
for c in unloaded {
|
||||
for sy in 0..(HEIGHT / 16) {
|
||||
renderer.remove((c.x, sy, c.z));
|
||||
}
|
||||
}
|
||||
renderer.remove_columns(unloaded.iter().map(|c| (c.x, c.z)));
|
||||
if let (Some(lod), Some(player)) = (&mut self.lod, &self.player) {
|
||||
let lod_distance = self.settings.horizon.lod_distance_on(&renderer.info);
|
||||
lod.set_near_loading(self.streaming.busy());
|
||||
@@ -12361,6 +12378,7 @@ impl<'a> Game<'a> {
|
||||
lan_events: Vec::new(),
|
||||
lan_block_events: Vec::new(),
|
||||
lan_entity_events: Vec::new(),
|
||||
lan_critical_hits: Vec::new(),
|
||||
lan_global_events: Vec::new(),
|
||||
lid_openers: HashMap::new(),
|
||||
lan_acting: None,
|
||||
@@ -12991,6 +13009,14 @@ fn build_renderer(
|
||||
) -> Result<Renderer> {
|
||||
let assets = &pack.render;
|
||||
let atlas = &gui.atlas;
|
||||
// The new renderer's atlas texture starts from `HudAtlas.pixels`, which
|
||||
// holds the textures but never a glyph rasterized at run time. The font's
|
||||
// cache still answers with the rects it drew into the previous renderer's
|
||||
// texture, so forget them: the glyphs that are drawn again are placed into
|
||||
// this texture (as `ui_theme` does when its atlas changes). Without this,
|
||||
// Chinese and Japanese menu labels go blank when the loading screen hands
|
||||
// over to the game.
|
||||
atlas.font.reset_cache();
|
||||
let mut renderer = pollster::block_on(Renderer::new(
|
||||
window,
|
||||
offscreen,
|
||||
@@ -13037,6 +13063,12 @@ fn loading_renderer(
|
||||
Some(atlas) => (atlas.pixels.as_slice(), atlas.width, atlas.height),
|
||||
None => (EMPTY_HUD.as_slice(), 1, 1),
|
||||
};
|
||||
// A glyph rasterized into an earlier texture is not in these pixels; the
|
||||
// new texture gets it again when the character is drawn (see
|
||||
// `build_renderer`).
|
||||
if let Some(atlas) = atlas {
|
||||
atlas.font.reset_cache();
|
||||
}
|
||||
let mut renderer = pollster::block_on(Renderer::new(
|
||||
window,
|
||||
offscreen,
|
||||
|
||||
@@ -300,6 +300,8 @@ struct Glide {
|
||||
pub(super) struct Agent {
|
||||
task: Option<Task>,
|
||||
glide: Option<Glide>,
|
||||
/// Control-fixture barrier: hold simulation and packet handling, not transport threads.
|
||||
pub hold_server: bool,
|
||||
}
|
||||
|
||||
pub(super) enum Handled {
|
||||
@@ -479,6 +481,8 @@ impl Game<'_> {
|
||||
"absorption": p.health.absorption(),
|
||||
// The hurt animation's ticks left (the camera's hurt tilt).
|
||||
"hurt_time": p.health.hurt_animation_time,
|
||||
// LivingEntity.deathTime while dead (the camera's death roll).
|
||||
"death_time": self.death_time(),
|
||||
"air": p.air,
|
||||
"food": p.health.food.food,
|
||||
"saturation": p.health.food.saturation,
|
||||
@@ -667,6 +671,7 @@ impl Game<'_> {
|
||||
});
|
||||
if let Some(chat) = &self.ui.chat_screen {
|
||||
v["chat_input"] = json!(chat.input.value);
|
||||
v["chat_suggestions"] = json!(chat.suggestions_visible());
|
||||
}
|
||||
if self.title.is_some() {
|
||||
v["menu"] = self.title_value();
|
||||
|
||||
@@ -219,6 +219,11 @@ impl Game<'_> {
|
||||
/// client tick (`ClientLevel.tickBlockEntities`).
|
||||
pub(super) fn tick_block_entity_anims(&mut self) {
|
||||
let Some(r) = &self.renderer else {
|
||||
// A server has no window, but its gateways still run their
|
||||
// server ticker.
|
||||
if self.remote.is_none() {
|
||||
self.tick_gateway_servers();
|
||||
}
|
||||
return;
|
||||
};
|
||||
// Sorted by position: the order they tick in, and a quick lookup.
|
||||
@@ -378,6 +383,31 @@ impl Game<'_> {
|
||||
}
|
||||
self.be_anims.present = positions;
|
||||
}
|
||||
/// `TheEndGatewayBlockEntity.portalTick` (the server ticker) of the
|
||||
/// gateways a server keeps a copy of, in block-ticking chunks
|
||||
/// (`Level.tickBlockEntities`): the cooldown an entry started runs out,
|
||||
/// and every 2400 ticks `triggerCooldown` sends its block event.
|
||||
fn tick_gateway_servers(&mut self) {
|
||||
let levels = self.tickets.levels();
|
||||
let mut positions: Vec<[i32; 3]> = self
|
||||
.be_anims
|
||||
.gateway_servers
|
||||
.keys()
|
||||
.copied()
|
||||
.filter(|p| levels.block_ticking_at(p[0], p[2]))
|
||||
.collect();
|
||||
positions.sort_unstable();
|
||||
for pos in positions {
|
||||
let triggered = self
|
||||
.be_anims
|
||||
.gateway_servers
|
||||
.get_mut(&pos)
|
||||
.is_some_and(EndGateway::portal_tick);
|
||||
if triggered {
|
||||
self.block_entity_event(pos, 1, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `EndGatewayBlock.entityInside` on the server: whether the gateway at
|
||||
/// `pos` let the entity in (`triggerCooldown`, with its block event).
|
||||
pub(super) fn gateway_enter(&mut self, pos: [i32; 3]) -> bool {
|
||||
|
||||
@@ -464,7 +464,28 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
// The Chat option's Hidden level takes the server's messages too.
|
||||
if !self.ui.chat.shows(ChatSource::Server) {
|
||||
self.local_chat_line(text, Some(SYSTEM_INDICATOR), ChatSource::Server);
|
||||
}
|
||||
/// A player's chat line on the window's own chat: a LAN guest's message
|
||||
/// while the host runs in-frame (`HostEvent::Chat`). `ChatListener`
|
||||
/// checks `canReceivePlayerMessages` for these, so Commands Only and
|
||||
/// Hidden drop them; command feedback (`/list`, `/tp`) is a system
|
||||
/// message and takes the system-message permission instead.
|
||||
pub(super) fn player_message(&mut self, text: Text) {
|
||||
if let Some(capture) = self.chat_capture.as_mut() {
|
||||
capture.push(text);
|
||||
return;
|
||||
}
|
||||
// A server's client receives the line as a packet (PlayerChat or
|
||||
// DisguisedChat) and filters it there.
|
||||
if self.remote.is_none() {
|
||||
self.local_chat_line(text, None, ChatSource::Player);
|
||||
}
|
||||
}
|
||||
/// A line on the window's own chat when the Chat option lets `source`
|
||||
/// through; running mods hear it.
|
||||
fn local_chat_line(&mut self, text: Text, indicator: Option<u32>, source: ChatSource) {
|
||||
if !self.ui.chat.shows(source) {
|
||||
return;
|
||||
}
|
||||
let focused = self.screen == Screen::Chat;
|
||||
@@ -472,8 +493,8 @@ impl Game<'_> {
|
||||
self.ui.chat.add(
|
||||
&self.gui.atlas,
|
||||
text,
|
||||
Some(SYSTEM_INDICATOR),
|
||||
ChatSource::Server,
|
||||
indicator,
|
||||
source,
|
||||
self.ticks,
|
||||
focused,
|
||||
);
|
||||
|
||||
@@ -52,11 +52,16 @@ impl Game<'_> {
|
||||
/// Remember who deals the next `damage_type` damage to the player.
|
||||
pub(super) fn note_attacker(&mut self, damage_type: &str, mob: u32) {
|
||||
if let Some(name) = self.mob_display_name(mob) {
|
||||
self.combat
|
||||
.pending
|
||||
.push((damage_type.to_owned(), (mob, name)));
|
||||
self.note_named_attacker(damage_type, mob, name);
|
||||
}
|
||||
}
|
||||
/// `note_attacker` for an entity that is not one of `self.mobs` (the
|
||||
/// ender dragon).
|
||||
pub(super) fn note_named_attacker(&mut self, damage_type: &str, id: u32, name: Text) {
|
||||
self.combat
|
||||
.pending
|
||||
.push((damage_type.to_owned(), (id, name)));
|
||||
}
|
||||
/// `LivingEntity.handleDamageEvent` for the player: the hurt sound of the
|
||||
/// source's `DamageEffects` (`Player.getHurtSound`).
|
||||
pub(super) fn player_hurt_sound(&mut self, sound: &str, at: [f64; 3]) {
|
||||
|
||||
@@ -1097,6 +1097,12 @@ impl Game<'_> {
|
||||
Target::Player => {
|
||||
// ServerPlayer.teleport: removeVehicle before placing the player.
|
||||
self.stop_riding();
|
||||
// A server's player teleported within their level is placed
|
||||
// there at once: the arrival they were waiting for elsewhere
|
||||
// in it (whose chunks lose their tickets) is abandoned.
|
||||
if let Some(conn) = self.lan_acting {
|
||||
self.server_trips.retain(|trip| !trip.is(conn));
|
||||
}
|
||||
if let Some(p) = self.player.as_mut() {
|
||||
p.position = v;
|
||||
p.velocity = Vec3::new(0.0, 0.0, 0.0);
|
||||
|
||||
@@ -11,6 +11,9 @@ use winit::{event::MouseButton, event_loop::ActiveEventLoop, keyboard::KeyCode};
|
||||
|
||||
const HELP: &[&str] = &[
|
||||
"status game, player, streaming and renderer state",
|
||||
"simulation authoritative projectiles in the owner's level",
|
||||
"server-hold on|off hold simulation and player packets at a control-fixture barrier",
|
||||
"stall MILLISECONDS stall the window thread (0..5000), leaving transport alive",
|
||||
"key KEY down|up|tap|repeat press, release or auto-repeat a key (w a s d space shift ctrl e q esc f3 1-9 arrows ...)",
|
||||
"release release every key and mouse button",
|
||||
"mouse left|right|middle down|up|click",
|
||||
@@ -238,6 +241,47 @@ impl Game<'_> {
|
||||
}
|
||||
"sculk" => Ok(Some(self.sculk_command(&words)?)),
|
||||
"status" => Ok(Some(self.control_status())),
|
||||
"stall" => {
|
||||
let millis: u64 = arg(1)?.parse()?;
|
||||
if millis > 5000 {
|
||||
return Err("stall is limited to 5000 milliseconds".into());
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(millis));
|
||||
ok()
|
||||
}
|
||||
"simulation" => {
|
||||
self.require_world()?;
|
||||
let value = if let Some(server) = &self.integrated {
|
||||
server
|
||||
.call(|g| {
|
||||
g.in_owner_level(|g| {
|
||||
json!({ "game_time": g.world.game_time, "projectiles": g.projectiles_status() })
|
||||
})
|
||||
})
|
||||
.ok_or("the integrated server stopped")?
|
||||
} else {
|
||||
json!({ "game_time": self.world.game_time, "projectiles": self.projectiles_status() })
|
||||
};
|
||||
Ok(Some(value))
|
||||
}
|
||||
"server-hold" => {
|
||||
self.require_world()?;
|
||||
let held = match arg(1)? {
|
||||
"on" => true,
|
||||
"off" => false,
|
||||
_ => return Err("server-hold on|off".into()),
|
||||
};
|
||||
if let Some(server) = &self.integrated {
|
||||
server
|
||||
.call(move |g| g.agent.hold_server = held)
|
||||
.ok_or("the integrated server stopped")?;
|
||||
} else if self.remote.is_some() {
|
||||
return Err("server-hold requires the world's host".into());
|
||||
} else {
|
||||
self.agent.hold_server = held;
|
||||
}
|
||||
ok()
|
||||
}
|
||||
"pad" => Ok(Some(self.pad_command(&words)?)),
|
||||
"key" => {
|
||||
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
|
||||
@@ -508,10 +552,23 @@ impl Game<'_> {
|
||||
"mobs" => {
|
||||
self.require_world()?;
|
||||
let radius: f64 = words.get(1).map_or(Ok(64.0), |r| r.parse())?;
|
||||
if let Some(server) = &self.integrated {
|
||||
let center = self.player.as_ref().map_or(Vec3::ZERO, |p| p.position);
|
||||
let value = server
|
||||
.call(move |g| g.in_owner_level(|g| g.control_mobs_at(radius, center)))
|
||||
.ok_or("the integrated server stopped")?;
|
||||
return Ok(Some(value));
|
||||
}
|
||||
Ok(Some(self.control_mobs(radius)))
|
||||
}
|
||||
"hurtlog" => {
|
||||
self.require_world()?;
|
||||
if let Some(server) = &self.integrated {
|
||||
let value = server
|
||||
.call(|g| g.control_hurt_log())
|
||||
.ok_or("the integrated server stopped")?;
|
||||
return Ok(Some(value));
|
||||
}
|
||||
Ok(Some(self.control_hurt_log()))
|
||||
}
|
||||
"resume" => {
|
||||
|
||||
@@ -312,6 +312,9 @@ impl Game<'_> {
|
||||
/// The `mobs` command: nearby mobs with position, health and running goals.
|
||||
pub(super) fn control_mobs(&self, radius: f64) -> serde_json::Value {
|
||||
let center = self.player.as_ref().map_or(Vec3::ZERO, |p| p.position);
|
||||
self.control_mobs_at(radius, center)
|
||||
}
|
||||
pub(super) fn control_mobs_at(&self, radius: f64, center: Vec3) -> serde_json::Value {
|
||||
let list: Vec<serde_json::Value> = self
|
||||
.mobs
|
||||
.iter()
|
||||
@@ -388,6 +391,9 @@ impl Game<'_> {
|
||||
}
|
||||
pub(super) fn mob_world_base<'s>(&'s self, others: &'s [Seen]) -> MobWorld<'s> {
|
||||
let (rain, thunder) = self.world.weather.levels(1.0);
|
||||
// Level.canHaveWeather: only the overworld's rain and thunder levels
|
||||
// ever rise, so nothing rains or thunders in the Nether or the End.
|
||||
let weather = self.dim == Dim::Overworld;
|
||||
let player = self.player_view();
|
||||
MobWorld {
|
||||
world: &self.world,
|
||||
@@ -404,8 +410,8 @@ impl Game<'_> {
|
||||
daylight: self.dim != Dim::Nether && self.sky_darken() < 4,
|
||||
game_time: self.world.game_time,
|
||||
day_time: self.world.day_time,
|
||||
raining: rain > 0.2,
|
||||
thundering: thunder > 0.9,
|
||||
raining: weather && rain > 0.2,
|
||||
thundering: weather && thunder > 0.9,
|
||||
nether: self.dim == Dim::Nether,
|
||||
block_tags: &self.res.items().block_tags,
|
||||
biomes: self.res.biomes(),
|
||||
@@ -1081,6 +1087,9 @@ impl Game<'_> {
|
||||
self.ensure_item_particle_sprites();
|
||||
}
|
||||
let options = horizon_client::particles::ParticleOptions::simple(ty);
|
||||
if ty == horizon_client::particles::ParticleType::SonicBoom {
|
||||
self.lan_sonic_boom(&options, at);
|
||||
}
|
||||
// Count 0: one particle exactly there, at rest.
|
||||
if count == 0 {
|
||||
self.particles.add(&options, at, [0.0; 3]);
|
||||
|
||||
@@ -12,6 +12,7 @@ use horizon_client::{
|
||||
hud_layout, hud_overlays,
|
||||
mesher::Vertex,
|
||||
particles::{ParticleOptions, ParticleType},
|
||||
text::Text,
|
||||
};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3},
|
||||
@@ -1870,7 +1871,7 @@ impl Game<'_> {
|
||||
pl.velocity.z += zd / dd * 4.0;
|
||||
}
|
||||
if !sitting {
|
||||
g.hurt_player_by("minecraft:mob_attack", 5.0);
|
||||
g.dragon_hurts_player("minecraft:mob_attack", 5.0);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1879,7 +1880,7 @@ impl Game<'_> {
|
||||
for h in heads {
|
||||
if h.inflate(Vec3::new(1.0, 1.0, 1.0)).intersects(p.bounds) {
|
||||
self.as_fight_player(p.who, |g| {
|
||||
g.hurt_player_by("minecraft:mob_attack", 10.0);
|
||||
g.dragon_hurts_player("minecraft:mob_attack", 10.0);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2161,10 +2162,20 @@ impl Game<'_> {
|
||||
self.breath_clouds.append(&mut clouds);
|
||||
for (who, amount) in harmed {
|
||||
self.as_fight_player(who, |g| {
|
||||
g.hurt_player_by("minecraft:indirect_magic", amount);
|
||||
g.dragon_hurts_player("minecraft:indirect_magic", amount);
|
||||
});
|
||||
}
|
||||
}
|
||||
/// Damage from the dragon, which is its causing entity
|
||||
/// (`DamageSources.mobAttack(dragon)`, `indirectMagic(cloud, dragon)`): the
|
||||
/// death message names it.
|
||||
fn dragon_hurts_player(&mut self, damage_type: &str, amount: f32) {
|
||||
if let Some(id) = self.dragon.as_ref().map(|d| d.id) {
|
||||
let name = Text::translate("entity.minecraft.ender_dragon", &[]);
|
||||
self.note_named_attacker(damage_type, id, name);
|
||||
}
|
||||
self.hurt_player_by(damage_type, amount);
|
||||
}
|
||||
/// `BossHealthOverlay.extractRenderState`: whatever `publish_boss_bars`
|
||||
/// (or a server's packets) put on this client's overlay.
|
||||
pub(super) fn draw_boss_bars(&self, batch: &mut HudBatch) {
|
||||
|
||||
@@ -71,6 +71,18 @@ impl Rocket {
|
||||
(self.position, self.velocity)
|
||||
}
|
||||
}
|
||||
/// `damageAmount * (float)Math.sqrt((5.0 - this.distanceTo(target)) / 5.0)`
|
||||
/// from the rocket at `from` to a target at `to`; `Entity.distanceTo` sums
|
||||
/// the squared offsets in floats.
|
||||
fn blast_damage(damage: f32, from: Vec3, to: Vec3) -> f32 {
|
||||
let (x, y, z) = (
|
||||
(from.x - to.x) as f32,
|
||||
(from.y - to.y) as f32,
|
||||
(from.z - to.z) as f32,
|
||||
);
|
||||
let distance = f64::from(x * x + y * y + z * z).sqrt() as f32;
|
||||
damage * ((5.0 - f64::from(distance)) / 5.0).sqrt() as f32
|
||||
}
|
||||
pub(super) fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
|
||||
// The item's default component: flight 1, no explosions.
|
||||
stack
|
||||
@@ -251,21 +263,24 @@ impl Game<'_> {
|
||||
let at = [r.position.x, r.position.y, r.position.z];
|
||||
if !r.explosions.is_empty() {
|
||||
let damage = 5.0 + r.explosions.len() as f32 * 2.0;
|
||||
// The player it boosts takes the full damage, a guest as well.
|
||||
if r.attached {
|
||||
match r.guest {
|
||||
None => self.hurt_player_by("minecraft:fireworks", damage),
|
||||
Some(conn) => {
|
||||
if let Some(mut host) = self.lan.take() {
|
||||
self.as_guest(&mut host, conn, |g| {
|
||||
g.hurt_player_by("minecraft:fireworks", damage);
|
||||
});
|
||||
self.lan = Some(host);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let from = r.position;
|
||||
// `attachedToEntity` takes the full damage, a guest as well; every
|
||||
// other player in range and in sight takes the blast.
|
||||
let boosted = r.guest.filter(|_| r.attached);
|
||||
if r.attached && boosted.is_none() {
|
||||
self.rocket_hurt_player(damage);
|
||||
} else {
|
||||
self.rocket_blast_player(from, damage);
|
||||
}
|
||||
if let Some(conn) = boosted
|
||||
&& let Some(mut host) = self.lan.take()
|
||||
{
|
||||
self.as_guest(&mut host, conn, |g| g.rocket_hurt_player(damage));
|
||||
self.lan = Some(host);
|
||||
}
|
||||
// Every other player in the level (LAN guests, the players of a
|
||||
// server thread), each swapped in as the player.
|
||||
self.each_guest_hit_except(boosted, |g| g.rocket_blast_player(from, damage));
|
||||
let hits: Vec<(u32, f32)> = {
|
||||
let world = self.mob_world_base(&[]);
|
||||
self.mobs
|
||||
@@ -285,7 +300,7 @@ impl Game<'_> {
|
||||
);
|
||||
world.clear_between(from, to, false)
|
||||
});
|
||||
sees.then(|| (m.id, damage * ((5.0 - d2.sqrt()) / 5.0).sqrt() as f32))
|
||||
sees.then(|| (m.id, blast_damage(damage, from, m.position)))
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
@@ -307,6 +322,49 @@ impl Game<'_> {
|
||||
self.particles
|
||||
.fireworks(at, v, r.explosions.clone(), camera);
|
||||
}
|
||||
/// `dealExplosionDamage` on a player that is not the rocket's
|
||||
/// `attachedToEntity`: within 5 blocks, when the rocket sees its feet or
|
||||
/// its middle (`ClipContext.Block.COLLIDER`, no fluids).
|
||||
fn rocket_blast_player(&mut self, from: Vec3, damage: f32) {
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let feet = p.position;
|
||||
let d2 = (feet.x - from.x).powi(2) + (feet.y - from.y).powi(2) + (feet.z - from.z).powi(2);
|
||||
if d2 > 25.0 {
|
||||
return;
|
||||
}
|
||||
let height = f64::from(p.dimensions.height);
|
||||
let sees = {
|
||||
let world = self.mob_world_base(&[]);
|
||||
(0..2).any(|step| {
|
||||
let to = Vec3::new(feet.x, feet.y + height * 0.5 * f64::from(step), feet.z);
|
||||
world.clear_between(from, to, false)
|
||||
})
|
||||
};
|
||||
if sees {
|
||||
self.rocket_hurt_player(blast_damage(damage, from, feet));
|
||||
}
|
||||
}
|
||||
/// `hurtServer` with `damageSources().fireworks`: armor absorbs it and
|
||||
/// wears (`hurtArmor`); creative and spectator players are immune.
|
||||
fn rocket_hurt_player(&mut self, amount: f32) {
|
||||
if self.creative || self.spectator() {
|
||||
return;
|
||||
}
|
||||
let hurt = if let Some(p) = self.player.as_mut()
|
||||
&& !p.health.dead_or_dying()
|
||||
&& let Some(id) = self.motion.health.damage.id("minecraft:fireworks")
|
||||
{
|
||||
p.hurt(&self.motion.health, self.world.health_rules, id, amount)
|
||||
.unwrap_or(false)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if hurt {
|
||||
self.hurt_armor(amount);
|
||||
}
|
||||
}
|
||||
/// `FireworkEntityRenderer.submit`: the item (GROUND) facing the camera,
|
||||
/// lit at the rocket's light probe.
|
||||
pub(super) fn rocket_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
|
||||
|
||||
@@ -64,14 +64,14 @@ impl Game<'_> {
|
||||
});
|
||||
self.view.tick(eye, target);
|
||||
}
|
||||
/// The player's `deathTime` while dead or dying.
|
||||
fn death_time(&self) -> Option<i32> {
|
||||
/// The player's `deathTime` while dead or dying: whole ticks counted by
|
||||
/// `LivingEntity.tickDeath`, so `deathTime + partialTicks` in
|
||||
/// `Camera.extractRenderState` rises smoothly across frames.
|
||||
pub(super) fn death_time(&self) -> Option<i32> {
|
||||
let p = self.player.as_ref()?;
|
||||
p.health.dead_or_dying().then(|| {
|
||||
self.ui
|
||||
.died_at
|
||||
.map_or(0, |t| (t.elapsed().as_secs_f32() * 20.0) as i32)
|
||||
})
|
||||
p.health
|
||||
.dead_or_dying()
|
||||
.then(|| self.ui.death_time.min(i32::MAX as u32) as i32)
|
||||
}
|
||||
/// The fluid at the camera, as `Camera.getFluidInCamera` reports it.
|
||||
pub(super) fn camera_fluid(&self, camera: [f64; 3]) -> CameraFluid {
|
||||
|
||||
@@ -370,6 +370,12 @@ impl Game<'_> {
|
||||
let mut next = Instant::now();
|
||||
while !flags.stop.load(Ordering::Relaxed) {
|
||||
self.run_tasks();
|
||||
if self.agent.hold_server {
|
||||
// Keep servicing control requests so the fixture can release the barrier.
|
||||
// Unlike /tick freeze, no player's queued packets are applied here.
|
||||
self.wait_for_next_server_tick(&mut next, true);
|
||||
continue;
|
||||
}
|
||||
let paused = flags.paused.load(Ordering::Relaxed);
|
||||
if paused {
|
||||
// Only the connections run.
|
||||
|
||||
@@ -194,6 +194,13 @@ fn mob_meta(
|
||||
let e = &m.extra;
|
||||
let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}"));
|
||||
match kind {
|
||||
// Bat.DATA_ID_FLAGS: resting in bit 0, flying by default.
|
||||
"minecraft:bat" => {
|
||||
if e.flag {
|
||||
meta.push((16, serializer::BYTE, Value::Byte(1)));
|
||||
}
|
||||
defaults.push((16, serializer::BYTE, Value::Byte(0)));
|
||||
}
|
||||
// Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 when sheared.
|
||||
"minecraft:sheep" => {
|
||||
let value = (e.color & 15) | if e.sheared { 16 } else { 0 };
|
||||
@@ -634,6 +641,7 @@ impl Game<'_> {
|
||||
self.world.light_log = None;
|
||||
self.audio.capture = None;
|
||||
self.lan_events.clear();
|
||||
self.lan_critical_hits.clear();
|
||||
self.streaming.extra.clear();
|
||||
if announce {
|
||||
self.system_message(Text::translate(
|
||||
@@ -1162,8 +1170,30 @@ impl Game<'_> {
|
||||
self.lan_entity_events.push((id, event, at));
|
||||
}
|
||||
}
|
||||
/// `ServerPlayer.crit`: this window's emitter, and an animation for the
|
||||
/// attacker's client and observers once the hub is back in place.
|
||||
pub(super) fn critical_hit(
|
||||
&mut self,
|
||||
attacker: Option<u32>,
|
||||
id: i32,
|
||||
feet: [f64; 3],
|
||||
width: f64,
|
||||
height: f64,
|
||||
) {
|
||||
use horizon_client::particles::{ParticleOptions, ParticleType};
|
||||
self.particles.tracking_emitter(
|
||||
ParticleOptions::simple(ParticleType::Crit),
|
||||
feet,
|
||||
width,
|
||||
height,
|
||||
);
|
||||
if self.audio.capture.is_some() {
|
||||
self.lan_critical_hits.push((attacker, id));
|
||||
}
|
||||
}
|
||||
/// Send the tick's level events, sounds and mob animations.
|
||||
fn lan_flush_effects(&mut self, host: &mut LanHost) {
|
||||
let critical_hits = std::mem::take(&mut self.lan_critical_hits);
|
||||
for (kind, pos, data, acting) in std::mem::take(&mut self.lan_events) {
|
||||
if kind == 2001 {
|
||||
host.broken
|
||||
@@ -1236,6 +1266,14 @@ impl Game<'_> {
|
||||
seen.insert(m.id, (m.hurt_time, dead, swing));
|
||||
}
|
||||
host.mob_state.insert(self.dim, seen);
|
||||
for (attacker, target) in critical_hits {
|
||||
let Some(attacker) = attacker.map_or(Some(host.host_entity), |conn| {
|
||||
host.hub.guest(conn).map(|g| g.entity_id)
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
host.hub.critical_hit(attacker, target);
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the chunks around every guest loaded.
|
||||
@@ -1403,7 +1441,11 @@ impl Game<'_> {
|
||||
let tag = if secure { "" } else { "[Not Secure] " };
|
||||
super::dedicated::log("INFO", &format!("{tag}{line}"));
|
||||
}
|
||||
HostEvent::Chat { line, .. } => self.system_message(Text::literal(line)),
|
||||
// Player chat (and `/say`'s or `/me`'s, which are chat messages
|
||||
// too): the host's Chat option decides, as `ChatListener` does
|
||||
// for the guests' packets. Command feedback is a system message
|
||||
// and takes the system-message permission instead.
|
||||
HostEvent::Chat { line, .. } => self.player_message(Text::literal(line)),
|
||||
HostEvent::Warn(line) if dedicated => super::dedicated::log("WARN", &line),
|
||||
HostEvent::Warn(line) => log::warn!("{line}"),
|
||||
HostEvent::Error(line) if dedicated => super::dedicated::log("ERROR", &line),
|
||||
|
||||
@@ -1192,6 +1192,10 @@ impl Game<'_> {
|
||||
{
|
||||
self.container_changed(key);
|
||||
}
|
||||
// A vehicle's menu edits the vehicle's own items.
|
||||
if let Some(Slots::Block(key)) = slots {
|
||||
self.store_cart_items(key);
|
||||
}
|
||||
self.drop_guest_items(host, gi, drops);
|
||||
}
|
||||
S::ContainerClose(p) => {
|
||||
@@ -2183,6 +2187,9 @@ impl Game<'_> {
|
||||
let _ = w.tick_environment_damage();
|
||||
let _ = w.apply_fire_contact();
|
||||
let _ = w.server_hazards_tick(in_wall);
|
||||
// Player.tick ends with updatePlayerPose: a swimmer, or a player
|
||||
// crawling under a block, takes the short box its moves are checked with.
|
||||
let _ = w.update_player_pose();
|
||||
let mut events = std::mem::take(&mut w.player.events);
|
||||
// LayeredCauldronBlock.handleEntityOnFireInside along those moves.
|
||||
for event in &events {
|
||||
|
||||
@@ -291,6 +291,11 @@ impl Game<'_> {
|
||||
let at = host.hub.guests[gi].position;
|
||||
self.award_furnace_recipes(pos, at);
|
||||
}
|
||||
// Slot.setChanged on a changed container slot: BlockEntity.setChanged,
|
||||
// so the chunk is saved and comparators read the block again.
|
||||
if changed.iter().any(|&s| s < items.len()) {
|
||||
self.container_changed(pos);
|
||||
}
|
||||
host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu));
|
||||
host.hub.inventory_clicked(conn, p, &self.world, &changed);
|
||||
true
|
||||
|
||||
@@ -119,7 +119,17 @@ impl Game<'_> {
|
||||
|
||||
/// Runs `f` as each guest in play here, for what strikes every player in
|
||||
/// an area (`Level.getEntities`), not only the window's own.
|
||||
pub(super) fn each_guest_hit(&mut self, mut f: impl FnMut(&mut Self)) {
|
||||
pub(super) fn each_guest_hit(&mut self, f: impl FnMut(&mut Self)) {
|
||||
self.each_guest_hit_except(None, f);
|
||||
}
|
||||
|
||||
/// [`Self::each_guest_hit`] leaving out the guest `except` (the one a
|
||||
/// firework rocket is attached to, which it hurts on its own).
|
||||
pub(super) fn each_guest_hit_except(
|
||||
&mut self,
|
||||
except: Option<u32>,
|
||||
mut f: impl FnMut(&mut Self),
|
||||
) {
|
||||
let Some(mut host) = self.lan.take() else {
|
||||
return;
|
||||
};
|
||||
@@ -127,7 +137,7 @@ impl Game<'_> {
|
||||
.hub
|
||||
.guests
|
||||
.iter()
|
||||
.filter(|g| host.hub.here(g) && g.loaded && !g.dead)
|
||||
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && Some(g.conn) != except)
|
||||
.map(|g| g.conn)
|
||||
.collect();
|
||||
for conn in conns {
|
||||
|
||||
@@ -25,6 +25,33 @@ fn rgb(c: [f32; 4]) -> [f32; 3] {
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `SonicBoom.tick` uses `ServerLevel.sendParticles` for each ray point.
|
||||
/// Keep the local event's rendering; connected players receive one at rest.
|
||||
pub(super) fn lan_sonic_boom(&self, options: &ParticleOptions, at: [f64; 3]) {
|
||||
let (Some(host), Some(particle)) = (&self.lan, self.network_particle(options, None)) else {
|
||||
return;
|
||||
};
|
||||
let packet = C::LevelParticles(play::LevelParticles {
|
||||
particle,
|
||||
override_limiter: false,
|
||||
always_show: false,
|
||||
pos: at,
|
||||
dist: [0.0; 3],
|
||||
max_speed: [0.0; 3],
|
||||
count: 0,
|
||||
randomization: 0,
|
||||
});
|
||||
for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) {
|
||||
// ServerLevel compares the player's block centre, strictly within 32.
|
||||
let distance: f64 = (0..3)
|
||||
.map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2))
|
||||
.sum();
|
||||
if distance < 32.0 * 32.0 {
|
||||
g.send(&packet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `ParticleTypes.STREAM_CODEC`'s value for `options`: the type's
|
||||
/// network id and the data it carries (`state` for the block particles).
|
||||
/// None while not serving, or for a particle whose data isn't sent from
|
||||
|
||||
@@ -32,6 +32,8 @@ pub(super) enum Victim {
|
||||
|
||||
/// The attacker's side of the hit.
|
||||
pub(super) struct Strike {
|
||||
/// The attacking guest, kept after their turn through `as_guest` ends.
|
||||
attacker: Option<u32>,
|
||||
amount: f32,
|
||||
scale: f32,
|
||||
crit: bool,
|
||||
@@ -119,6 +121,7 @@ impl Game<'_> {
|
||||
}
|
||||
self.swing_arm();
|
||||
Some(Strike {
|
||||
attacker: self.lan_acting,
|
||||
amount,
|
||||
scale,
|
||||
crit,
|
||||
@@ -250,6 +253,25 @@ impl Game<'_> {
|
||||
Victim::Host => land(self),
|
||||
Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or(false),
|
||||
};
|
||||
if hurt && s.crit {
|
||||
let target = match victim {
|
||||
Victim::Host => self.player.as_ref().map(|p| (host.host_entity, p)),
|
||||
Victim::Guest(conn) => host
|
||||
.hub
|
||||
.guest(conn)
|
||||
.and_then(|g| g.motion.as_deref().map(|p| (g.entity_id, p))),
|
||||
};
|
||||
if let Some((id, p)) = target {
|
||||
let d = p.dimensions;
|
||||
self.critical_hit(
|
||||
s.attacker,
|
||||
id,
|
||||
[p.position.x, p.position.y, p.position.z],
|
||||
f64::from(d.width),
|
||||
f64::from(d.height),
|
||||
);
|
||||
}
|
||||
}
|
||||
let sound = match (hurt, s.crit, s.scale > 0.9) {
|
||||
(false, ..) => "minecraft:entity.player.attack.nodamage",
|
||||
(true, true, _) => "minecraft:entity.player.attack.crit",
|
||||
|
||||
@@ -74,6 +74,7 @@ pub(super) struct Parked {
|
||||
lan_events: Vec<(i32, [i32; 3], i32, Option<u32>)>,
|
||||
lan_block_events: Vec<([i32; 3], i32, i32, u32)>,
|
||||
lan_entity_events: Vec<(i32, i8, [f64; 3])>,
|
||||
lan_critical_hits: Vec<(Option<u32>, i32)>,
|
||||
/// Only the per-level parts of these are used (`swap_level`).
|
||||
anims: BlockEntityAnims,
|
||||
raiding: Raiding,
|
||||
@@ -159,6 +160,7 @@ impl Game<'_> {
|
||||
lan_events: Vec::new(),
|
||||
lan_block_events: Vec::new(),
|
||||
lan_entity_events: Vec::new(),
|
||||
lan_critical_hits: Vec::new(),
|
||||
anims: Default::default(),
|
||||
raiding: Default::default(),
|
||||
sculk: Default::default(),
|
||||
@@ -209,6 +211,7 @@ impl Game<'_> {
|
||||
swap(&mut self.lan_events, &mut p.lan_events);
|
||||
swap(&mut self.lan_block_events, &mut p.lan_block_events);
|
||||
swap(&mut self.lan_entity_events, &mut p.lan_entity_events);
|
||||
swap(&mut self.lan_critical_hits, &mut p.lan_critical_hits);
|
||||
let (a, b) = (&mut self.be_anims, &mut p.anims);
|
||||
swap(&mut a.chests, &mut b.chests);
|
||||
swap(&mut a.books, &mut b.books);
|
||||
|
||||
@@ -1117,22 +1117,35 @@ impl Game<'_> {
|
||||
self.swing_arm();
|
||||
true
|
||||
}
|
||||
/// Closing a cart's container copies the items back.
|
||||
pub(super) fn close_cart_container(&mut self) {
|
||||
let Some(key) = self.container.filter(|k| k.1 == CART_KEY_Y) else {
|
||||
return;
|
||||
};
|
||||
let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key) else {
|
||||
/// Closing the cart's container open under `key` copies the items back.
|
||||
pub(super) fn close_cart_container(&mut self, key: (i32, i32, i32)) {
|
||||
if key.1 != CART_KEY_Y {
|
||||
return;
|
||||
}
|
||||
self.store_cart_items(key);
|
||||
self.world.block_entities.remove(&key);
|
||||
if let Some(c) = self.carts.iter().find(|c| c.id as i32 == key.2)
|
||||
&& c.kind == CartKind::Chest
|
||||
{
|
||||
let at = [c.position.x, c.position.y, c.position.z];
|
||||
let pitch = self.world.random.next_float() * 0.1 + 0.9;
|
||||
self.audio
|
||||
.play("minecraft:block.chest.close", Some(at), 0.5, pitch);
|
||||
}
|
||||
}
|
||||
/// The menu of a chest or hopper minecart or a chest boat works on the
|
||||
/// vehicle's own items (`ContainerEntity`): the placeholder under `key`
|
||||
/// that the menu edits is copied back to the vehicle.
|
||||
pub(super) fn store_cart_items(&mut self, key: (i32, i32, i32)) {
|
||||
if key.1 != CART_KEY_Y {
|
||||
return;
|
||||
}
|
||||
let Some(BlockEntity::Chest(items)) = self.world.block_entities.get(&key) else {
|
||||
return;
|
||||
};
|
||||
let items = items.clone();
|
||||
if let Some(c) = self.carts.iter_mut().find(|c| c.id as i32 == key.2) {
|
||||
c.items = items;
|
||||
let at = [c.position.x, c.position.y, c.position.z];
|
||||
if c.kind == CartKind::Chest {
|
||||
let pitch = self.world.random.next_float() * 0.1 + 0.9;
|
||||
self.audio
|
||||
.play("minecraft:block.chest.close", Some(at), 0.5, pitch);
|
||||
}
|
||||
} else if let Some(b) = self.boats.iter_mut().find(|b| b.id as i32 == key.2) {
|
||||
b.items = items;
|
||||
}
|
||||
|
||||
@@ -415,8 +415,65 @@ impl Game<'_> {
|
||||
cps,
|
||||
font_widths: self.mods.font_widths.clone(),
|
||||
players: Vec::new(),
|
||||
view_hit: self.mod_view_hit(),
|
||||
}
|
||||
}
|
||||
/// The first block along the player's view within
|
||||
/// [`horizon_mods::RAYCAST_MAX`] and its distance from the eye
|
||||
/// (`game.raycast`): through the loaded chunks as the crosshair's ray
|
||||
/// goes (fluids pass), then across the distant terrain's ground heights,
|
||||
/// a block at a time.
|
||||
fn mod_view_hit(&self) -> Option<(f32, horizon_mods::Hit)> {
|
||||
if !self.mods.mods.wants_raycast() {
|
||||
return None;
|
||||
}
|
||||
let eye = self.eye_position()?;
|
||||
let dir = super::view_vector(self.yaw, self.pitch);
|
||||
let reach = f64::from(horizon_mods::RAYCAST_MAX);
|
||||
let (pos, point, state) = match self.clip_ray(eye, dir, reach) {
|
||||
Some(hit) => (
|
||||
hit.pos,
|
||||
hit.point,
|
||||
self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]),
|
||||
),
|
||||
None => self.lod_ray(eye, dir, reach)?,
|
||||
};
|
||||
let distance = (0..3).map(|i| (point[i] - eye[i]).powi(2)).sum::<f64>();
|
||||
let hit = horizon_mods::Hit {
|
||||
block_x: pos[0],
|
||||
block_y: pos[1],
|
||||
block_z: pos[2],
|
||||
x: point[0],
|
||||
y: point[1],
|
||||
z: point[2],
|
||||
block: self.res.facts().get(state).name.to_string(),
|
||||
};
|
||||
Some((distance.sqrt() as f32, hit))
|
||||
}
|
||||
/// Past the resident chunks: the view walked across the distant
|
||||
/// terrain's ground heights (`Lod::ground`), a block at a time. Columns in
|
||||
/// loaded chunks are left to `clip_ray`, which has already missed them.
|
||||
fn lod_ray(
|
||||
&self,
|
||||
eye: [f64; 3],
|
||||
dir: [f64; 3],
|
||||
reach: f64,
|
||||
) -> Option<([i32; 3], [f64; 3], horizon_world::registry::BlockStateId)> {
|
||||
let lod = self.lod.as_ref()?;
|
||||
let mut t = 0.0;
|
||||
while t <= reach {
|
||||
let p = [0, 1, 2].map(|i| eye[i] + dir[i] * t);
|
||||
let (x, z) = (p[0].floor() as i32, p[2].floor() as i32);
|
||||
if !self.world.loaded(x, z)
|
||||
&& let Some((height, state)) = lod.ground(x, z)
|
||||
&& p[1] <= f64::from(height)
|
||||
{
|
||||
return Some(([x, height - 1, z], [p[0], f64::from(height), p[2]], state));
|
||||
}
|
||||
t += 1.0;
|
||||
}
|
||||
None
|
||||
}
|
||||
/// A game tick.
|
||||
pub(super) fn tick_mods(&mut self) {
|
||||
// Here, at the player's level: shown inside a console call (a control
|
||||
|
||||
@@ -86,6 +86,10 @@ impl Game<'_> {
|
||||
.iter()
|
||||
.filter_map(|m| Some((m, m.custom_name.clone()?, false)));
|
||||
let players = players.into_iter().map(|(m, name)| (m, name, true));
|
||||
// Who is riding whom: asked once per tag below, and rescanning every mob
|
||||
// for each tag made this quadratic in the number of loaded mobs.
|
||||
let ridden: std::collections::HashSet<u32> =
|
||||
self.mobs.iter().filter_map(|o| o.extra.mount).collect();
|
||||
for (m, name, player) in named.chain(players) {
|
||||
if !m.alive() {
|
||||
continue;
|
||||
@@ -134,7 +138,7 @@ impl Game<'_> {
|
||||
invisible_to_viewer: invisible,
|
||||
hud_hidden: self.ui.hide_gui,
|
||||
is_camera: false,
|
||||
is_vehicle: self.mobs.iter().any(|o| o.extra.mount == Some(m.id)),
|
||||
is_vehicle: ridden.contains(&m.id),
|
||||
};
|
||||
// MobRenderer.shouldShowName: a visible name, or the mob under the
|
||||
// crosshair; players (LivingEntityRenderer) need neither.
|
||||
@@ -310,7 +314,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// The lines of one name tag, `o` from the camera: the text at
|
||||
/// `text_alpha` in its layer, on the translucent black background
|
||||
/// (unlit, a hair behind) when `background`.
|
||||
/// (in `text_layer` like the glyphs, a hair behind) when `background`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn name_tag_quads(
|
||||
&self,
|
||||
@@ -382,7 +386,7 @@ impl Game<'_> {
|
||||
[white.u0, white.v0, white.u1, white.v1],
|
||||
BACKGROUND,
|
||||
true,
|
||||
2,
|
||||
text_layer,
|
||||
);
|
||||
}
|
||||
let mut x = x0;
|
||||
|
||||
@@ -11,7 +11,7 @@ use super::{Dim, Game, Mining, Screen};
|
||||
use horizon_client::first_person::{Hand, SwingAnimation};
|
||||
use horizon_client::{
|
||||
Result,
|
||||
chunk::{Chunk, SECTIONS},
|
||||
chunk::Chunk,
|
||||
containers::{BlockEntity, Furnace, FurnaceKind},
|
||||
entities::{Experience, ExperienceOrb, ItemEntity},
|
||||
hud::{HudBatch, rgba},
|
||||
@@ -998,6 +998,9 @@ impl Game<'_> {
|
||||
self.world.day_time,
|
||||
self.world.weather,
|
||||
);
|
||||
let old = std::mem::take(&mut self.world.chunks);
|
||||
let count = old.len();
|
||||
horizon_client::chunk::free_columns(old, count);
|
||||
self.world = World::new(self.res.facts().air, spawn.seed);
|
||||
self.world.game_time = time;
|
||||
self.world.day_time = day;
|
||||
@@ -1059,14 +1062,14 @@ impl Game<'_> {
|
||||
if gone.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut freed = Vec::with_capacity(gone.len());
|
||||
for &(x, z) in &gone {
|
||||
self.streaming.forget(&mut self.world, x, z);
|
||||
if let Some(renderer) = self.renderer.as_mut() {
|
||||
for sy in 0..SECTIONS as i32 {
|
||||
renderer.remove((x, sy, z));
|
||||
}
|
||||
}
|
||||
freed.extend(self.streaming.forget(&mut self.world, x, z));
|
||||
}
|
||||
if let Some(renderer) = self.renderer.as_mut() {
|
||||
renderer.remove_columns(gone.iter().copied());
|
||||
}
|
||||
horizon_client::chunk::free_columns(freed, gone.len());
|
||||
// One pass for all of them.
|
||||
self.world
|
||||
.block_entities
|
||||
@@ -1631,9 +1634,7 @@ impl Game<'_> {
|
||||
.block_entities
|
||||
.retain(|k, _| (k.0 >> 4, k.2 >> 4) != (x, z));
|
||||
if let Some(renderer) = self.renderer.as_mut() {
|
||||
for sy in 0..SECTIONS as i32 {
|
||||
renderer.remove((x, sy, z));
|
||||
}
|
||||
renderer.remove_columns([(x, z)]);
|
||||
}
|
||||
}
|
||||
C::ChunkBatchFinished(_) => {
|
||||
@@ -2124,6 +2125,7 @@ impl Game<'_> {
|
||||
self.apply_remote_health();
|
||||
if p.health <= 0.0 && self.screen != Screen::Dead && self.player.is_some() {
|
||||
self.screen = Screen::Dead;
|
||||
self.ui.death_time = 0;
|
||||
self.capture(false);
|
||||
}
|
||||
}
|
||||
@@ -2140,6 +2142,7 @@ impl Game<'_> {
|
||||
// screen, whatever health was last sent.
|
||||
if me && self.screen != Screen::Dead && self.player.is_some() {
|
||||
self.screen = Screen::Dead;
|
||||
self.ui.death_time = 0;
|
||||
self.capture(false);
|
||||
}
|
||||
}
|
||||
@@ -3060,6 +3063,12 @@ impl Game<'_> {
|
||||
fn tick_remote_level(&mut self) -> Result<()> {
|
||||
self.ticks += 1;
|
||||
self.track_experience_display();
|
||||
// Player.tick's ItemCooldowns.tick: this path replaces `tick_world`'s
|
||||
// for a server's client (multiplayer and the default single player),
|
||||
// so the entries advance here or the slot stays shaded until the
|
||||
// server says the entry ended. `onCooldownEnded` is the plain
|
||||
// ItemCooldowns' no-op on a client.
|
||||
self.cooldowns.tick();
|
||||
// Options.broadcastOptions: a changed render distance or Chat option
|
||||
// is sent again.
|
||||
let view = client_view_distance(self.settings.render_distance);
|
||||
@@ -3178,6 +3187,11 @@ impl Game<'_> {
|
||||
);
|
||||
let was_flying = player.flying;
|
||||
self.sync_player_body();
|
||||
// LivingEntity.tickDeath: the local player counts its deathTime once
|
||||
// per client tick while dead (the camera's death roll and zoom).
|
||||
if self.screen == Screen::Dead {
|
||||
self.ui.death_time = self.ui.death_time.saturating_add(1);
|
||||
}
|
||||
let Some(player) = self.player.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -3485,6 +3499,9 @@ impl Game<'_> {
|
||||
if m.species() == horizon_client::mobs::Species::Rabbit {
|
||||
horizon_client::mobs::rabbit::post_tick(m);
|
||||
}
|
||||
if m.species() == horizon_client::mobs::Species::Bat {
|
||||
horizon_client::mobs::bat::setup_animation_states(m);
|
||||
}
|
||||
}
|
||||
for o in self.orbs.iter_mut().filter(|_| running) {
|
||||
o.previous = o.position;
|
||||
@@ -3814,19 +3831,25 @@ impl Game<'_> {
|
||||
.and_modify(|p| p.0 = sequence)
|
||||
.or_insert((sequence, state.0 as i32));
|
||||
}
|
||||
let s = self.res.facts().get(state).sounds.clone();
|
||||
let at = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
self.audio.play(
|
||||
&s.break_sound,
|
||||
Some(at),
|
||||
(s.volume + 1.0) / 2.0,
|
||||
s.pitch * 0.8,
|
||||
);
|
||||
self.destroy_particles(pos, state);
|
||||
// Block.playerWillDestroy's destroy event (particles and the break
|
||||
// sound), which BaseFireBlock skips: the server's extinguish sound
|
||||
// is all a player hears.
|
||||
let facts = self.res.facts().get(state);
|
||||
if !facts.has_class("BaseFireBlock") {
|
||||
let s = facts.sounds.clone();
|
||||
let at = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 0.5,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
self.audio.play(
|
||||
&s.break_sound,
|
||||
Some(at),
|
||||
(s.volume + 1.0) / 2.0,
|
||||
s.pitch * 0.8,
|
||||
);
|
||||
self.destroy_particles(pos, state);
|
||||
}
|
||||
// The server's block update follows (waterlogged blocks leave water).
|
||||
let air = self.world.air;
|
||||
if self.world.set(pos[0], pos[1], pos[2], air).is_ok() {
|
||||
@@ -3956,6 +3979,10 @@ impl Game<'_> {
|
||||
if let Some(placed) = &placed {
|
||||
self.predict_place(placed, seq);
|
||||
self.with_hand(hand, Game::consume_held);
|
||||
} else if let Some(r) = self.remote.as_mut() {
|
||||
// BlockItem.place plays its sound only once the block is set: the
|
||||
// server's resend of the target it refused is no placement.
|
||||
r.placing = None;
|
||||
}
|
||||
if reacts || placed.is_some() {
|
||||
self.with_hand(hand, Game::swing_arm);
|
||||
@@ -4496,6 +4523,7 @@ impl Game<'_> {
|
||||
}
|
||||
KeyCode::KeyE => {
|
||||
// The inventory opens without telling the server.
|
||||
self.recipe_ui.reset_screen();
|
||||
self.screen = if self.creative {
|
||||
Screen::Creative
|
||||
} else {
|
||||
@@ -4762,6 +4790,7 @@ impl Game<'_> {
|
||||
self.remote_close_local();
|
||||
}
|
||||
fn remote_close_local(&mut self) {
|
||||
self.recipe_ui.reset_screen();
|
||||
if let Some(r) = self.remote.as_mut() {
|
||||
r.menu = None;
|
||||
r.menu_title = None;
|
||||
@@ -4832,6 +4861,9 @@ impl Game<'_> {
|
||||
}
|
||||
/// ClientboundOpenScreenPacket for the menus Horizon draws.
|
||||
fn remote_open_screen(&mut self, p: play::OpenScreen) {
|
||||
// A new RecipeBookComponent owns fresh ghost slots and an overlay,
|
||||
// even when the server replaces a menu without a close packet.
|
||||
self.recipe_ui.reset_screen();
|
||||
let menu = self
|
||||
.remote
|
||||
.as_ref()
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! own simulation, which a client of a server doesn't run.
|
||||
use super::Game;
|
||||
use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES};
|
||||
use horizon_client::mobs::{Mob, Species, tame};
|
||||
use horizon_client::mobs::{Mob, Species, bat, tame};
|
||||
use horizon_protocol::entity_data::Value;
|
||||
use horizon_protocol::registry::Builtin;
|
||||
|
||||
@@ -46,6 +46,8 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) {
|
||||
_ => {}
|
||||
}
|
||||
match (species, *index, value) {
|
||||
// Bat.DATA_ID_FLAGS: resting in bit 0.
|
||||
(Species::Bat, 16, Value::Byte(flags)) => bat::set_resting(m, flags & 1 != 0),
|
||||
// Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared.
|
||||
(Species::Sheep, 18, Value::Byte(wool)) => {
|
||||
m.extra.color = (*wool & 15) as u8;
|
||||
@@ -126,6 +128,10 @@ pub(super) fn client_defaults(m: &mut Mob) {
|
||||
if matches!(m.species(), Species::Wolf | Species::Cat) {
|
||||
m.extra.color = tame::RED;
|
||||
}
|
||||
if m.species() == Species::Bat {
|
||||
// Bat's constructor sets resting only on the server; the data default is 0.
|
||||
bat::set_resting(m, false);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -174,6 +180,69 @@ mod tests {
|
||||
assert!(!calf.is_baby());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bat_flags_select_continuous_client_clocks_without_changing_motion() {
|
||||
use horizon_client::mobs::{MobTypes, anim, keyframes::Animation};
|
||||
use horizon_core::geometry::Vec3;
|
||||
use serde_json::json;
|
||||
use std::{collections::HashMap, fs, sync::Arc};
|
||||
|
||||
// Original minimal resources keep this regression runnable without vanilla data.
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("horizon-bat-animation-{}", std::process::id()));
|
||||
fs::create_dir(&root).unwrap();
|
||||
fs::write(root.join("entity-types.json"), r#"{"minecraft:bat": {}}"#).unwrap();
|
||||
fs::write(
|
||||
root.join("entity-models.json"),
|
||||
r#"{"minecraft:bat#main": {"children": {"right_wing": {}, "head": {}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let mut types = MobTypes::load(&root).unwrap();
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
let position = Vec3::new(1.0, 2.25, 3.0);
|
||||
let velocity = Vec3::new(0.2, 0.3, 0.4);
|
||||
let mut m = Mob::new(
|
||||
1,
|
||||
Arc::new(types.types.remove("minecraft:bat").unwrap()),
|
||||
position,
|
||||
0.0,
|
||||
);
|
||||
assert!(bat::resting(&m));
|
||||
client_defaults(&mut m);
|
||||
assert!(!bat::resting(&m));
|
||||
m.velocity = velocity;
|
||||
m.age = 1;
|
||||
bat::setup_animation_states(&mut m);
|
||||
m.age = 4;
|
||||
apply(&mut m, &[(16, s::BYTE, Value::Byte(2))]);
|
||||
bat::setup_animation_states(&mut m);
|
||||
assert_eq!(m.anim.states[0].started, Some(1.0));
|
||||
|
||||
let curve = Animation::parse(&json!({"length": 1, "looping": true,
|
||||
"bones": {"right_wing": [{"target": "rotation", "keyframes":
|
||||
[[0,[0,0,0],[0,0,0],"linear"],[1,[0,1,0],[0,1,0],"linear"]]}]}}));
|
||||
let animations = HashMap::from([("BatAnimation.BAT_FLYING".into(), curve)]);
|
||||
let wing = |partial| {
|
||||
let mut poses = anim::Poses::new(&m.kind.model);
|
||||
anim::setup(&m, &anim::state(&m, partial), &mut poses, &animations);
|
||||
poses.get("right_wing")[4]
|
||||
};
|
||||
assert!(wing(0.5) > wing(0.0));
|
||||
|
||||
m.age = 5;
|
||||
apply(&mut m, &[(16, s::BYTE, Value::Byte(3))]);
|
||||
bat::setup_animation_states(&mut m);
|
||||
assert!(bat::resting(&m));
|
||||
assert_eq!(m.anim.states[0].started, None);
|
||||
assert_eq!(m.anim.states[1].started, Some(5.0));
|
||||
m.age = 7;
|
||||
apply(&mut m, &[(16, s::BYTE, Value::Byte(0))]);
|
||||
bat::setup_animation_states(&mut m);
|
||||
assert_eq!(m.anim.states[0].started, Some(7.0));
|
||||
assert_eq!(m.anim.states[1].started, None);
|
||||
assert_eq!((m.position, m.velocity), (position, velocity));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wolf_takes_its_owner_flags_and_collar() {
|
||||
let Some(mut m) = mob("minecraft:wolf") else {
|
||||
|
||||
@@ -363,7 +363,8 @@ impl Game<'_> {
|
||||
out.push(json!({"id": t.id, "kind": "minecraft:trident", "position": at(t.position)}));
|
||||
}
|
||||
for p in &self.creatures.projectiles {
|
||||
out.push(json!({"id": p.id, "kind": format!("{:?}", p.kind).split([' ', '{']).next().unwrap_or(""), "position": at(p.position)}));
|
||||
out.push(json!({"id": p.id, "kind": format!("{:?}", p.kind).split([' ', '{']).next().unwrap_or(""), "position": at(p.position), "velocity": at(p.velocity),
|
||||
"player_owned": p.owner == Some(horizon_client::mobs::Who::Player)}));
|
||||
}
|
||||
for (kind, p, _) in self.potions.thrown_entities() {
|
||||
out.push(json!({"kind": kind, "position": at(p)}));
|
||||
|
||||
@@ -210,6 +210,7 @@ impl Game<'_> {
|
||||
if bg != 0 {
|
||||
batch.fill(
|
||||
atlas,
|
||||
// submitTextBackground(-1, -1, width, height): corners, not a size.
|
||||
-1.0,
|
||||
-1.0,
|
||||
width + 1.0,
|
||||
|
||||
@@ -67,6 +67,7 @@ mod end_sky;
|
||||
mod flat;
|
||||
pub mod lightning;
|
||||
mod lod;
|
||||
mod native_material;
|
||||
mod native_pack;
|
||||
mod native_post;
|
||||
mod native_sky;
|
||||
@@ -88,6 +89,7 @@ mod stars;
|
||||
mod timing;
|
||||
pub mod translucency;
|
||||
pub(crate) mod upload;
|
||||
mod wgsl_prefix;
|
||||
mod world_post;
|
||||
|
||||
/// A column whose every section has its mesh (`Renderer::lod_detail_columns`).
|
||||
@@ -428,6 +430,8 @@ pub struct Renderer {
|
||||
/// The mipmap levels sampled (the Mipmap Levels option), at most `mip_levels - 1`.
|
||||
mipmaps: u32,
|
||||
terrain_layout: wgpu::BindGroupLayout,
|
||||
/// terrain.wgsl's `SPRITE_ARRAYS` and `SPRITE_SPLIT`, for a shader pack's terrain.
|
||||
terrain_sprites: [f64; 2],
|
||||
sprite_sampler: wgpu::Sampler,
|
||||
lightmap_view: wgpu::TextureView,
|
||||
lightmap_sampler: wgpu::Sampler,
|
||||
@@ -459,7 +463,7 @@ pub struct Renderer {
|
||||
lod_retiring: crate::fast_hash::FxHashSet<SectionKey>,
|
||||
/// Finished tile meshes `upload_lods` has yet to upload.
|
||||
lod_pending: Option<lod::Pending>,
|
||||
detail_columns: HashMap<(i32, i32), u32>,
|
||||
detail_columns: crate::fast_hash::FxHashMap<(i32, i32), u32>,
|
||||
/// Bumped whenever a column becomes or stops being complete.
|
||||
detail_revision: u64,
|
||||
arena: arena::Arena,
|
||||
@@ -493,7 +497,7 @@ pub struct Renderer {
|
||||
/// The shadow camera's draws by page, in bands of distance from the light.
|
||||
shadow_runs: page_runs::PageRuns,
|
||||
/// Block-entity blocks per meshed section (world position, state id).
|
||||
block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>,
|
||||
block_entities: crate::fast_hash::FxHashMap<SectionKey, Vec<([i32; 3], u32)>>,
|
||||
/// Changes whenever `block_entities` does (unique across renderers).
|
||||
block_entity_revision: u64,
|
||||
/// VisGraph face connectivity per meshed section (cave culling).
|
||||
@@ -2369,6 +2373,7 @@ impl Renderer {
|
||||
mip_levels,
|
||||
mipmaps: mip_levels - 1,
|
||||
terrain_layout: bindings,
|
||||
terrain_sprites: sprite_constants.map(|(_, v)| v),
|
||||
sprite_sampler,
|
||||
lightmap_view,
|
||||
lightmap_sampler,
|
||||
@@ -2390,7 +2395,7 @@ impl Renderer {
|
||||
lod_cutout: Default::default(),
|
||||
lod_retiring: Default::default(),
|
||||
lod_pending: None,
|
||||
detail_columns: HashMap::new(),
|
||||
detail_columns: Default::default(),
|
||||
detail_revision: 0,
|
||||
arena,
|
||||
sorted_indices,
|
||||
@@ -2411,7 +2416,7 @@ impl Renderer {
|
||||
solid_runs: page_runs::PageRuns::default(),
|
||||
phase2_runs: page_runs::PageRuns::default(),
|
||||
shadow_runs: page_runs::PageRuns::default(),
|
||||
block_entities: HashMap::new(),
|
||||
block_entities: Default::default(),
|
||||
block_entity_revision: next_block_entity_revision(),
|
||||
occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16),
|
||||
world_post,
|
||||
@@ -2847,18 +2852,47 @@ impl Renderer {
|
||||
self.detail_columns.insert(column, next);
|
||||
}
|
||||
}
|
||||
pub fn remove(&mut self, key: SectionKey) {
|
||||
self.set_detail(key, false);
|
||||
if self.block_entities.remove(&key).is_some() {
|
||||
/// Every section of these columns goes: one lookup per column where the
|
||||
/// tables are by column, and the meshes' ranges freed in one batch. A
|
||||
/// teleport removes a few thousand columns in one frame.
|
||||
pub fn remove_columns(&mut self, columns: impl IntoIterator<Item = (i32, i32)>) {
|
||||
let mut released = Vec::new();
|
||||
let mut block_entities = false;
|
||||
for (x, z) in columns {
|
||||
if self.detail_columns.remove(&(x, z)) == Some(COMPLETE_COLUMN) {
|
||||
self.detail_revision += 1;
|
||||
}
|
||||
self.occlusion.remove_column(x, z);
|
||||
let retiring = !self.lod_cutout.is_empty() && self.lod_cutout.contains(&(x, z));
|
||||
for sy in 0..crate::chunk::SECTIONS as i32 {
|
||||
let key = (x, sy, z);
|
||||
block_entities |= self.block_entities.remove(&key).is_some();
|
||||
if retiring {
|
||||
// Distant tiles still leave its column out: drawn until they don't.
|
||||
self.lod_retiring.insert(key);
|
||||
} else if let Some(section) = self.sections.remove(key) {
|
||||
released.push(section);
|
||||
}
|
||||
}
|
||||
}
|
||||
if block_entities {
|
||||
self.block_entity_revision = next_block_entity_revision();
|
||||
}
|
||||
self.occlusion.remove(key);
|
||||
if !self.lod_cutout.is_empty() && self.lod_cutout.contains(&(key.0, key.2)) {
|
||||
// Distant tiles still leave its column out: drawn until they don't.
|
||||
self.lod_retiring.insert(key);
|
||||
} else {
|
||||
self.release_section(key);
|
||||
if let Some(flat) = &mut self.flat {
|
||||
for id in released.iter().filter_map(|s| s.flat_id) {
|
||||
flat.remove(id);
|
||||
}
|
||||
}
|
||||
self.sorted_indices
|
||||
.release_all(released.iter().filter_map(|s| {
|
||||
let (page, start) = s.sorted_indices?;
|
||||
Some((page, start, u64::from(s.translucent) * 6))
|
||||
}));
|
||||
self.arena.release_all(
|
||||
released
|
||||
.iter()
|
||||
.map(|s| (s.page, s.start, u64::from(s.solid + s.translucent) * 4)),
|
||||
);
|
||||
}
|
||||
/// Horizon's resolution scale (world pixels per window pixel) and FXAA.
|
||||
pub fn set_world_post(&mut self, scale: f32, antialias: bool) {
|
||||
@@ -2936,9 +2970,9 @@ impl Renderer {
|
||||
self.native = None;
|
||||
self.pack_atlas = None;
|
||||
}
|
||||
/// Runs the sky and post stages of one of Horizon's own shader packs from now on (`None`:
|
||||
/// no pack), with its options' values; replaces a `shaders/` pack. Returns the stages'
|
||||
/// labels; on an error the pack that ran keeps running.
|
||||
/// Runs the sky, material and post stages of one of Horizon's own shader packs from now
|
||||
/// on (`None`: no pack), with its options' values; replaces a `shaders/` pack. Returns the
|
||||
/// stages' labels; on an error the pack that ran keeps running.
|
||||
pub fn set_native_shader_pack(
|
||||
&mut self,
|
||||
pack: Option<(horizon_shader_api::Report, Vec<(String, f64)>)>,
|
||||
@@ -2947,14 +2981,14 @@ impl Renderer {
|
||||
self.native = None;
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let format = self.config.format.remove_srgb_suffix();
|
||||
let (pack, labels) = native_pack::NativePack::new(
|
||||
&self.device,
|
||||
&self.terrain_layout,
|
||||
report,
|
||||
&constants,
|
||||
format,
|
||||
)?;
|
||||
let terrain = native_material::TerrainShape {
|
||||
globals: &self.terrain_layout,
|
||||
flat: self.flat.as_ref().map(|f| &f.draw_layout),
|
||||
sprites: self.terrain_sprites,
|
||||
format: self.config.format.remove_srgb_suffix(),
|
||||
};
|
||||
let (pack, labels) =
|
||||
native_pack::NativePack::new(&self.device, &terrain, report, &constants)?;
|
||||
self.native = pack.draws().then_some(pack);
|
||||
if self.native.is_some() {
|
||||
self.pack_post = None;
|
||||
@@ -4178,6 +4212,21 @@ impl Renderer {
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
sky.draw(&mut pass, &native.frame);
|
||||
}
|
||||
// One of Horizon's own packs with a material stage: terrain draws with its pipelines,
|
||||
// which read the pack's frame at group 3.
|
||||
let material = self
|
||||
.native
|
||||
.as_ref()
|
||||
.filter(|_| !frame.title)
|
||||
.and_then(|n| Some((n.material.as_ref()?, &n.frame.group)));
|
||||
let solid_pipeline = material.map_or(&self.solid, |(m, _)| &m.solid);
|
||||
let translucent_pipeline = material.map_or(&self.translucent, |(m, _)| &m.translucent);
|
||||
let pack_flat = material.and_then(|(m, _)| m.flat.as_ref());
|
||||
let pack_frame = |pass: &mut wgpu::RenderPass<'_>| {
|
||||
if let Some((_, group)) = material {
|
||||
pass.set_bind_group(horizon_shader_api::stages::GROUP, group, &[]);
|
||||
}
|
||||
};
|
||||
{
|
||||
let attachments = [Some(wgpu::RenderPassColorAttachment {
|
||||
view: world_view,
|
||||
@@ -4211,6 +4260,7 @@ impl Renderer {
|
||||
..Default::default()
|
||||
});
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
pack_frame(&mut pass);
|
||||
if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) {
|
||||
if !frame.title && frame.skybox && !pack_draws_sky && !native_sky_pass {
|
||||
match self
|
||||
@@ -4259,7 +4309,7 @@ impl Renderer {
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
}
|
||||
Some(flat) => {
|
||||
pass.set_pipeline(&flat.solid);
|
||||
pass.set_pipeline(pack_flat.map_or(&flat.solid, |p| &p.0));
|
||||
let vertices = |p| self.arena.buffer(p);
|
||||
match cull {
|
||||
// As below: phase 1, the test, then phase 2's draws
|
||||
@@ -4277,7 +4327,8 @@ impl Renderer {
|
||||
pack_reads_world,
|
||||
);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
pass.set_pipeline(&flat.solid);
|
||||
pack_frame(&mut pass);
|
||||
pass.set_pipeline(pack_flat.map_or(&flat.solid, |p| &p.0));
|
||||
flat.draw_phase2(&mut pass, vertices);
|
||||
}
|
||||
None => flat.draw(&mut pass, &flat.calls[..flat.solid_calls], vertices),
|
||||
@@ -4286,7 +4337,7 @@ impl Renderer {
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
}
|
||||
None => {
|
||||
pass.set_pipeline(&self.solid);
|
||||
pass.set_pipeline(solid_pipeline);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
match cull {
|
||||
@@ -4306,7 +4357,8 @@ impl Renderer {
|
||||
pack_reads_world,
|
||||
);
|
||||
pass.set_bind_group(0, &self.group, &[]);
|
||||
pass.set_pipeline(&self.solid);
|
||||
pack_frame(&mut pass);
|
||||
pass.set_pipeline(solid_pipeline);
|
||||
pass.set_index_buffer(
|
||||
self.indices.slice(..),
|
||||
wgpu::IndexFormat::Uint32,
|
||||
@@ -4398,7 +4450,7 @@ impl Renderer {
|
||||
// The pack draws translucent terrain after its deferred programs.
|
||||
_ if pack_draws_water => {}
|
||||
Some(flat) => {
|
||||
pass.set_pipeline(&flat.translucent);
|
||||
pass.set_pipeline(pack_flat.map_or(&flat.translucent, |p| &p.1));
|
||||
flat.draw(&mut pass, flat.translucent_calls(), |p| {
|
||||
self.arena.buffer(p)
|
||||
});
|
||||
@@ -4406,7 +4458,7 @@ impl Renderer {
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
}
|
||||
None => {
|
||||
pass.set_pipeline(&self.translucent);
|
||||
pass.set_pipeline(translucent_pipeline);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
self.draw_sections(
|
||||
|
||||
@@ -39,6 +39,35 @@ impl FreeList {
|
||||
}
|
||||
self.0.insert(start, len);
|
||||
}
|
||||
/// `give` for many ranges: one merge of the sorted ranges into the list,
|
||||
/// where giving them one by one costs a few tree lookups each.
|
||||
fn give_all(&mut self, mut ranges: Vec<(u64, u64)>) {
|
||||
if ranges.len() < 64 {
|
||||
for (start, len) in ranges {
|
||||
self.give(start, len);
|
||||
}
|
||||
return;
|
||||
}
|
||||
ranges.sort_unstable();
|
||||
let mut free = std::mem::take(&mut self.0).into_iter().peekable();
|
||||
let mut given = ranges.into_iter().peekable();
|
||||
let mut merged: Vec<(u64, u64)> = Vec::new();
|
||||
loop {
|
||||
let next = match (free.peek(), given.peek()) {
|
||||
(Some(a), Some(b)) if a.0 <= b.0 => free.next(),
|
||||
(_, Some(_)) => given.next(),
|
||||
(Some(_), None) => free.next(),
|
||||
(None, None) => break,
|
||||
};
|
||||
let (start, len) = next.expect("peeked");
|
||||
match merged.last_mut() {
|
||||
Some(last) if last.0 + last.1 == start => last.1 += len,
|
||||
_ => merged.push((start, len)),
|
||||
}
|
||||
}
|
||||
// Sorted: the tree is built in one pass.
|
||||
self.0 = merged.into_iter().collect();
|
||||
}
|
||||
}
|
||||
|
||||
/// One vertex buffer of the arena; only the newest page grows.
|
||||
@@ -237,6 +266,26 @@ impl Arena {
|
||||
.free
|
||||
.give(start, len);
|
||||
}
|
||||
/// `release` for many ranges (page, start, vertices) at once.
|
||||
pub fn release_all(&mut self, ranges: impl IntoIterator<Item = (u32, u64, u64)>) {
|
||||
let mut by_page: Vec<Vec<(u64, u64)>> = Vec::new();
|
||||
for (page, start, vertices) in ranges {
|
||||
let page = page as usize;
|
||||
if by_page.len() <= page {
|
||||
by_page.resize_with(page + 1, Vec::new);
|
||||
}
|
||||
by_page[page].push((start, Self::span(vertices).min(self.page_limit)));
|
||||
}
|
||||
for (page, ranges) in by_page.into_iter().enumerate() {
|
||||
if !ranges.is_empty() {
|
||||
self.pages[page]
|
||||
.as_mut()
|
||||
.expect("live arena page")
|
||||
.free
|
||||
.give_all(ranges);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Moves a page into a larger buffer; false (the page unchanged) when
|
||||
/// there is no memory for it.
|
||||
fn grow(
|
||||
@@ -435,6 +484,44 @@ mod tests {
|
||||
assert_eq!(free, FreeList::new(4 * GRAIN));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_ranges_given_at_once_coalesce_as_one_by_one() {
|
||||
let fill = || {
|
||||
let mut free = FreeList::new(1 << 30);
|
||||
let taken: Vec<(u64, u64)> = (0..500u64)
|
||||
.map(|i| {
|
||||
let len = GRAIN * (1 + i * 7 % 5);
|
||||
(free.take(len).unwrap(), len)
|
||||
})
|
||||
.collect();
|
||||
for &(start, len) in taken.iter().step_by(3) {
|
||||
free.give(start, len);
|
||||
}
|
||||
(free, taken)
|
||||
};
|
||||
// Every other range of those still taken, in a scattered order.
|
||||
let (mut one_by_one, taken) = fill();
|
||||
let (mut at_once, _) = fill();
|
||||
let mut given: Vec<(u64, u64)> = (0..taken.len())
|
||||
.filter(|i| i % 3 != 0 && i % 2 == 0)
|
||||
.map(|i| taken[i])
|
||||
.collect();
|
||||
given.sort_by_key(|&(start, _)| start.wrapping_mul(0x9E37_79B9_7F4A_7C15));
|
||||
assert!(given.len() >= 64);
|
||||
for &(start, len) in &given {
|
||||
one_by_one.give(start, len);
|
||||
}
|
||||
at_once.give_all(given);
|
||||
assert_eq!(at_once, one_by_one);
|
||||
// The rest too: everything is free again, in one range.
|
||||
let rest: Vec<(u64, u64)> = (0..taken.len())
|
||||
.filter(|i| i % 3 != 0 && i % 2 != 0)
|
||||
.map(|i| taken[i])
|
||||
.collect();
|
||||
at_once.give_all(rest);
|
||||
assert_eq!(at_once, FreeList::new(1 << 30));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_fit_reuses_the_lowest_hole() {
|
||||
let mut free = FreeList::new(8 * GRAIN);
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
//! The material stage of Horizon's own shader packs (docs/shaders.md): the pack's `material`
|
||||
//! function gives the lit colour of each point of a block's surface, before the alpha test and
|
||||
//! fog. Terrain still draws with Horizon's meshes, culling and draw lists; only its pipelines
|
||||
//! change. Their shader is the pack's stage (`CheckedStage::source`), then a copy of
|
||||
//! terrain.wgsl's terrain section whose names all take a `horizon_terrain_` prefix
|
||||
//! (`wgsl_prefix.rs`), then entries that hand the pack what vanilla's `fs_solid` and
|
||||
//! `fs_translucent` combine: the texture, the vertex tint, the light levels and the lightmap's
|
||||
//! colour. They read the terrain's group 0, the flat draws' group 1 where those run, and the
|
||||
//! pack's frame at group 3.
|
||||
|
||||
use horizon_shader_api::{check::CheckedStage, stages::GROUP};
|
||||
|
||||
use super::native_post::{NativeFrame, present_constants};
|
||||
use super::wgsl_prefix::{TERRAIN, prefixed, section};
|
||||
|
||||
const PREFIX: &str = "horizon_terrain_";
|
||||
|
||||
/// The entries around the pack's `material`: vanilla's vertex work without the lightmap
|
||||
/// product, then the material, the alpha test and fog as `fs_solid` and `fs_translucent` do.
|
||||
const ENTRIES: &str = "
|
||||
struct HorizonMaterialOut {
|
||||
@builtin(position) clip: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
@location(1) @interpolate(flat) layer: u32,
|
||||
@location(2) tint: vec4<f32>,
|
||||
@location(3) light: vec2<f32>,
|
||||
@location(4) lightmap: vec3<f32>,
|
||||
@location(5) position: vec3<f32>,
|
||||
@location(6) spherical: f32,
|
||||
@location(7) cylindrical: f32,
|
||||
}
|
||||
fn horizon_material_vertex(position: vec3<f32>, uv: vec2<f32>, layer: u32, color: vec4<f32>,
|
||||
light: vec2<u32>, origin: vec3<f32>) -> HorizonMaterialOut {
|
||||
let pos = position + origin;
|
||||
var out: HorizonMaterialOut;
|
||||
out.clip = horizon_terrain_globals.view_proj * vec4(pos, 1.0);
|
||||
out.uv = uv;
|
||||
out.layer = layer;
|
||||
out.tint = color;
|
||||
let block = max(f32(light.y), horizon_terrain_dynamic_block_light(pos));
|
||||
let sky = f32(light.x);
|
||||
// 16 per level, 15 levels.
|
||||
out.light = min(vec2(block, sky) / 240.0, vec2(1.0));
|
||||
out.lightmap = horizon_terrain_sample_lightmap(sky / 16.0, block / 16.0).rgb;
|
||||
out.position = pos;
|
||||
out.spherical = length(pos);
|
||||
out.cylindrical = max(length(pos.xz), abs(pos.y));
|
||||
return out;
|
||||
}
|
||||
@vertex fn horizon_material_vs(
|
||||
@location(0) position: vec3<f32>, @location(1) uv: vec2<u32>,
|
||||
@location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec2<u32>,
|
||||
@location(5) origin: vec4<f32>) -> HorizonMaterialOut {
|
||||
return horizon_material_vertex(position, horizon_terrain_terrain_uv(uv, origin.w), layer,
|
||||
color, light, origin.xyz);
|
||||
}
|
||||
@vertex fn horizon_material_vs_flat(
|
||||
@builtin(vertex_index) vertex: u32,
|
||||
@location(0) position: vec3<f32>, @location(1) uv: vec2<u32>,
|
||||
@location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec2<u32>
|
||||
) -> HorizonMaterialOut {
|
||||
let origin = horizon_terrain_slot_origins[horizon_terrain_block_slots[vertex >> 8u]];
|
||||
return horizon_material_vertex(position, horizon_terrain_terrain_uv(uv, origin.w), layer,
|
||||
color, light, origin.xyz);
|
||||
}
|
||||
fn horizon_material_color(in: HorizonMaterialOut, translucent: bool) -> vec4<f32> {
|
||||
let albedo = horizon_terrain_sprite(in.uv, in.layer & 0x7fffu);
|
||||
return material(MaterialInput(albedo, in.tint, in.light, in.lightmap, in.position, in.uv,
|
||||
translucent)).color;
|
||||
}
|
||||
@fragment fn horizon_material_fs_solid(in: HorizonMaterialOut) -> @location(0) vec4<f32> {
|
||||
let color = horizon_material_color(in, false);
|
||||
// Bit 15 of the layer marks opaque leaves (forceOpaque): no alpha cutout.
|
||||
if color.a < 0.5 && (in.layer & 0x8000u) == 0u { discard; }
|
||||
return horizon_terrain_apply_fog(vec4(color.rgb, 1.0), in.spherical, in.cylindrical);
|
||||
}
|
||||
@fragment fn horizon_material_fs_translucent(in: HorizonMaterialOut) -> @location(0) vec4<f32> {
|
||||
let color = horizon_material_color(in, true);
|
||||
if color.a < 0.01 { discard; }
|
||||
return horizon_terrain_apply_fog(color, in.spherical, in.cylindrical);
|
||||
}
|
||||
";
|
||||
|
||||
/// What terrain pipelines are built against: the renderer's layouts and constants.
|
||||
pub struct TerrainShape<'a> {
|
||||
/// The terrain's group 0.
|
||||
pub globals: &'a wgpu::BindGroupLayout,
|
||||
/// The flat draws' group 1, where they run (`flat.rs`).
|
||||
pub flat: Option<&'a wgpu::BindGroupLayout>,
|
||||
/// terrain.wgsl's `SPRITE_ARRAYS` and `SPRITE_SPLIT`.
|
||||
pub sprites: [f64; 2],
|
||||
/// The world target's colour format.
|
||||
pub format: wgpu::TextureFormat,
|
||||
}
|
||||
|
||||
/// The pack's terrain pipelines: solid (with the cutout test) and translucent, for the
|
||||
/// renderer's instanced draws and, where they run, its flat ones.
|
||||
pub struct NativeMaterial {
|
||||
pub solid: wgpu::RenderPipeline,
|
||||
pub translucent: wgpu::RenderPipeline,
|
||||
pub flat: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline)>,
|
||||
}
|
||||
|
||||
/// terrain.wgsl's terrain section (its globals, bindings, sampling, lighting and fog), with
|
||||
/// every name it declares prefixed.
|
||||
fn vanilla_terrain() -> String {
|
||||
prefixed(
|
||||
section(TERRAIN, "struct Globals {", "// Sky (SkyRenderer)"),
|
||||
PREFIX,
|
||||
)
|
||||
}
|
||||
|
||||
/// The terrain shader for the pack's material stage `source`.
|
||||
fn shader_source(source: &str) -> String {
|
||||
format!(
|
||||
"{source}\n// Horizon's terrain (terrain.wgsl)\n{}{ENTRIES}",
|
||||
vanilla_terrain()
|
||||
)
|
||||
}
|
||||
|
||||
/// The material's naga module, its errors in the stage's file.
|
||||
fn module(stage: &CheckedStage) -> Result<naga::Module, String> {
|
||||
let text = shader_source(&stage.source);
|
||||
naga::front::wgsl::parse_str(&text)
|
||||
.map_err(|e| format!("{}: {}", stage.file, e.emit_to_string(&text)))
|
||||
}
|
||||
|
||||
impl NativeMaterial {
|
||||
/// The pipelines of the pack's material `stage` with the option values `constants`.
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
shape: &TerrainShape<'_>,
|
||||
frame: &NativeFrame,
|
||||
stage: &CheckedStage,
|
||||
constants: &[(String, f64)],
|
||||
) -> Result<Self, String> {
|
||||
let module = module(stage)?;
|
||||
let mut constants = present_constants(&module, constants);
|
||||
let sprite_names = [
|
||||
"horizon_terrain_SPRITE_ARRAYS",
|
||||
"horizon_terrain_SPRITE_SPLIT",
|
||||
];
|
||||
constants.extend(sprite_names.into_iter().zip(shape.sprites));
|
||||
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some(&stage.label),
|
||||
source: wgpu::ShaderSource::Naga(std::borrow::Cow::Owned(module)),
|
||||
});
|
||||
let layout = |flat: Option<&wgpu::BindGroupLayout>| {
|
||||
let mut groups: [Option<&wgpu::BindGroupLayout>; GROUP as usize + 1] =
|
||||
Default::default();
|
||||
groups[0] = Some(shape.globals);
|
||||
groups[1] = flat;
|
||||
groups[GROUP as usize] = Some(&frame.layout);
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Native shader pack terrain"),
|
||||
bind_group_layouts: &groups,
|
||||
..Default::default()
|
||||
})
|
||||
};
|
||||
let instance_attributes = wgpu::vertex_attr_array![5=>Float32x4];
|
||||
let vertices = wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<super::TerrainVertex>() as u64,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &super::TERRAIN_ATTRIBUTES,
|
||||
};
|
||||
let instances = wgpu::VertexBufferLayout {
|
||||
array_stride: 16,
|
||||
step_mode: wgpu::VertexStepMode::Instance,
|
||||
attributes: &instance_attributes,
|
||||
};
|
||||
// As the renderer's terrain pipelines (gfx.rs): back faces culled, reversed depth.
|
||||
let pipeline = |layout: &wgpu::PipelineLayout,
|
||||
vertex: &str,
|
||||
buffers: &[Option<wgpu::VertexBufferLayout<'_>>],
|
||||
fragment: &str,
|
||||
blend: Option<wgpu::BlendState>| {
|
||||
let options = wgpu::PipelineCompilationOptions {
|
||||
constants: &constants,
|
||||
..Default::default()
|
||||
};
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some(&stage.label),
|
||||
layout: Some(layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &module,
|
||||
entry_point: Some(vertex),
|
||||
compilation_options: options.clone(),
|
||||
buffers,
|
||||
},
|
||||
primitive: wgpu::PrimitiveState {
|
||||
cull_mode: Some(wgpu::Face::Back),
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: wgpu::TextureFormat::Depth32Float,
|
||||
depth_write_enabled: Some(true),
|
||||
depth_compare: Some(wgpu::CompareFunction::GreaterEqual),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &module,
|
||||
entry_point: Some(fragment),
|
||||
compilation_options: options,
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: shape.format,
|
||||
blend,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let blend = Some(wgpu::BlendState::ALPHA_BLENDING);
|
||||
let instanced = layout(None);
|
||||
let buffers = [Some(vertices.clone()), Some(instances)];
|
||||
let solid = pipeline(
|
||||
&instanced,
|
||||
"horizon_material_vs",
|
||||
&buffers,
|
||||
"horizon_material_fs_solid",
|
||||
None,
|
||||
);
|
||||
let translucent = pipeline(
|
||||
&instanced,
|
||||
"horizon_material_vs",
|
||||
&buffers,
|
||||
"horizon_material_fs_translucent",
|
||||
blend,
|
||||
);
|
||||
let flat = shape.flat.map(|group| {
|
||||
let layout = layout(Some(group));
|
||||
let buffers = [Some(vertices.clone())];
|
||||
let vs = "horizon_material_vs_flat";
|
||||
(
|
||||
pipeline(&layout, vs, &buffers, "horizon_material_fs_solid", None),
|
||||
pipeline(
|
||||
&layout,
|
||||
vs,
|
||||
&buffers,
|
||||
"horizon_material_fs_translucent",
|
||||
blend,
|
||||
),
|
||||
)
|
||||
});
|
||||
if let Some(e) = pollster::block_on(scope.pop()) {
|
||||
return Err(format!("{}: {e}", stage.file));
|
||||
}
|
||||
Ok(Self {
|
||||
solid,
|
||||
translucent,
|
||||
flat,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use horizon_shader_api::{MANIFEST, Pack, StageKind, check};
|
||||
|
||||
fn stage(material: &str) -> CheckedStage {
|
||||
let manifest = "schema = 1\nid = \"t\"\nname = \"T\"\nversion = \"1\"\napi = \"0.1\"\n\
|
||||
[material]\nfile = \"material.wgsl\"\n\
|
||||
[[options]]\nid = \"gain\"\nname = \"Gain\"\ntype = \"float\"\n\
|
||||
default = 1.0\nmin = 0.0\nmax = 2.0\n";
|
||||
let files = [(MANIFEST, manifest), ("material.wgsl", material)]
|
||||
.map(|(n, t)| (n.to_owned(), t.as_bytes().to_vec()))
|
||||
.into();
|
||||
let mut report = check(&Pack::from_files(files).unwrap()).unwrap();
|
||||
assert_eq!(report.stages[0].kind, StageKind::Material);
|
||||
report.stages.remove(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_terrain_takes_a_prefix_and_validates_with_a_pack() {
|
||||
let terrain = vanilla_terrain();
|
||||
for name in [
|
||||
"Globals",
|
||||
"globals",
|
||||
"sprites_7",
|
||||
"sprite",
|
||||
"SPRITE_SPLIT",
|
||||
"block_slots",
|
||||
"sample_lightmap",
|
||||
"apply_fog",
|
||||
] {
|
||||
assert!(terrain.contains(&format!("{PREFIX}{name}")), "{name}");
|
||||
}
|
||||
assert!(!terrain.contains("fs_sky"), "the sky stays out");
|
||||
// A pack may use any name Horizon's terrain uses unprefixed.
|
||||
let own = "override gain: f32;\nconst PI: f32 = 3.0;\n\
|
||||
fn sprite(c: vec4<f32>) -> vec4<f32> { return c * PI; }\n\
|
||||
fn apply_fog(c: vec4<f32>) -> vec4<f32> { return c * gain; }\n\
|
||||
fn material(input: MaterialInput) -> Surface {\n \
|
||||
let lit = input.albedo * input.tint * vec4(input.lightmap, 1.0);\n \
|
||||
return Surface(apply_fog(sprite(lit)));\n}\n";
|
||||
let stage = stage(own);
|
||||
let module = module(&stage).unwrap();
|
||||
let info = naga::valid::Validator::new(
|
||||
naga::valid::ValidationFlags::all(),
|
||||
naga::valid::Capabilities::all(),
|
||||
)
|
||||
.validate(&module)
|
||||
.unwrap_or_else(|e| panic!("{}", e.emit_to_string(&shader_source(&stage.source))));
|
||||
let entries: Vec<&str> = module
|
||||
.entry_points
|
||||
.iter()
|
||||
.map(|e| e.name.as_str())
|
||||
.collect();
|
||||
for entry in [
|
||||
"horizon_material_vs",
|
||||
"horizon_material_vs_flat",
|
||||
"horizon_material_fs_solid",
|
||||
"horizon_material_fs_translucent",
|
||||
] {
|
||||
assert!(entries.contains(&entry), "{entry}");
|
||||
}
|
||||
drop(info);
|
||||
assert_eq!(
|
||||
present_constants(&module, &[("gain".into(), 1.5), ("other".into(), 1.0)]),
|
||||
[("gain", 1.5)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
//! One of Horizon's own shader packs while it runs (docs/shaders.md): the frame its stages
|
||||
//! read, its sky and post stages, and the timer of their passes.
|
||||
//! read, its sky, material and post stages, and the timer of their passes.
|
||||
|
||||
use horizon_shader_api::{Report, StageKind};
|
||||
|
||||
use super::native_material::{NativeMaterial, TerrainShape};
|
||||
use super::native_post::{NativeFrame, NativePost};
|
||||
use super::native_sky::NativeSky;
|
||||
use super::pack_timing::PassTiming;
|
||||
@@ -10,6 +11,7 @@ use super::pack_timing::PassTiming;
|
||||
pub struct NativePack {
|
||||
pub frame: NativeFrame,
|
||||
pub sky: Option<NativeSky>,
|
||||
pub material: Option<NativeMaterial>,
|
||||
pub post: Option<NativePost>,
|
||||
/// GPU time of each pass, while the renderer asks for it (`pack_timing.rs`).
|
||||
pub timing: Option<PassTiming>,
|
||||
@@ -17,16 +19,16 @@ pub struct NativePack {
|
||||
|
||||
impl NativePack {
|
||||
/// The pack of the checked stages `report` with the option values `constants`, drawing
|
||||
/// onto targets of `format`; `globals` is the terrain's group 0, which the sky reads.
|
||||
/// onto the world's targets as `terrain` describes; the sky reads the terrain's group 0.
|
||||
/// Also returns its stages' labels, in the order they draw. Errors name the stage wgpu
|
||||
/// refused.
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
globals: &wgpu::BindGroupLayout,
|
||||
terrain: &TerrainShape<'_>,
|
||||
report: Report,
|
||||
constants: &[(String, f64)],
|
||||
format: wgpu::TextureFormat,
|
||||
) -> Result<(Self, Vec<String>), String> {
|
||||
let (globals, format) = (terrain.globals, terrain.format);
|
||||
let frame = NativeFrame::new(device);
|
||||
let (post, others): (Vec<_>, Vec<_>) = report
|
||||
.stages
|
||||
@@ -37,16 +39,28 @@ impl NativePack {
|
||||
.find(|s| s.kind == StageKind::Sky)
|
||||
.map(|stage| NativeSky::new(device, globals, &frame, stage, constants, format))
|
||||
.transpose()?;
|
||||
let material = others
|
||||
.iter()
|
||||
.find(|s| s.kind == StageKind::Material)
|
||||
.map(|stage| NativeMaterial::new(device, terrain, &frame, stage, constants))
|
||||
.transpose()?;
|
||||
let post = (!post.is_empty())
|
||||
.then(|| NativePost::new(device, post, constants, format, &frame))
|
||||
.transpose()?;
|
||||
let mut labels: Vec<String> = sky.iter().map(|s| s.label.clone()).collect();
|
||||
labels.extend(
|
||||
others
|
||||
.iter()
|
||||
.filter(|s| material.is_some() && s.kind == StageKind::Material)
|
||||
.map(|s| s.label.clone()),
|
||||
);
|
||||
if let Some(post) = &post {
|
||||
labels.extend(post.labels().into_iter().map(str::to_owned));
|
||||
}
|
||||
let pack = Self {
|
||||
frame,
|
||||
sky,
|
||||
material,
|
||||
post,
|
||||
timing: None,
|
||||
};
|
||||
@@ -55,6 +69,6 @@ impl NativePack {
|
||||
|
||||
/// Whether the pack draws anything the game runs today.
|
||||
pub fn draws(&self) -> bool {
|
||||
self.sky.is_some() || self.post.is_some()
|
||||
self.sky.is_some() || self.material.is_some() || self.post.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,9 +9,9 @@
|
||||
use horizon_shader_api::{check::CheckedStage, stages::GROUP};
|
||||
|
||||
use super::native_post::{NativeFrame, present_constants};
|
||||
use super::wgsl_prefix::{TERRAIN, prefixed, section};
|
||||
|
||||
const PREFIX: &str = "horizon_sky_";
|
||||
const TERRAIN: &str = include_str!("../terrain.wgsl");
|
||||
|
||||
/// The fragment entry that calls the pack: vanilla's colour in, an opaque colour out.
|
||||
const PACK_ENTRY: &str = "
|
||||
@@ -26,62 +26,15 @@ pub struct NativeSky {
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
/// The text of `source` from the line starting with `start` up to (not including) the one
|
||||
/// starting with `end`.
|
||||
fn section<'a>(source: &'a str, start: &str, end: &str) -> &'a str {
|
||||
let from = source
|
||||
.find(&format!("\n{start}"))
|
||||
.expect("terrain.wgsl has the section")
|
||||
+ 1;
|
||||
let to = from
|
||||
+ source[from..]
|
||||
.find(&format!("\n{end}"))
|
||||
.expect("terrain.wgsl ends the section")
|
||||
+ 1;
|
||||
&source[from..to]
|
||||
}
|
||||
|
||||
/// terrain.wgsl's sky with every name it declares (and `globals`) prefixed.
|
||||
fn vanilla_sky() -> String {
|
||||
let text = [
|
||||
section(TERRAIN, "struct Globals {", "@group(0) @binding(0)"),
|
||||
section(TERRAIN, "struct Globals {", "@group(0) @binding(1)"),
|
||||
section(TERRAIN, "fn linear_fog(", "fn apply_fog("),
|
||||
section(TERRAIN, "struct SkyOut {", "// rendertype_lines"),
|
||||
]
|
||||
.concat();
|
||||
let mut names = vec!["globals"];
|
||||
for line in text.lines() {
|
||||
let line = line
|
||||
.trim_start_matches("@vertex ")
|
||||
.trim_start_matches("@fragment ");
|
||||
for keyword in ["fn ", "struct ", "const "] {
|
||||
if let Some(rest) = line.strip_prefix(keyword) {
|
||||
let end = rest
|
||||
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
|
||||
.unwrap_or(rest.len());
|
||||
names.push(&rest[..end]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = String::with_capacity(text.len() * 2);
|
||||
let mut word = String::new();
|
||||
let flush = |word: &mut String, out: &mut String| {
|
||||
if names.contains(&word.as_str()) {
|
||||
out.push_str(PREFIX);
|
||||
}
|
||||
out.push_str(word);
|
||||
word.clear();
|
||||
};
|
||||
for c in text.chars() {
|
||||
if c.is_ascii_alphanumeric() || c == '_' {
|
||||
word.push(c);
|
||||
} else {
|
||||
flush(&mut word, &mut out);
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
flush(&mut word, &mut out);
|
||||
out + &format!("@group(0) @binding(0) var<uniform> {PREFIX}globals: {PREFIX}Globals;\n")
|
||||
prefixed(&text, PREFIX)
|
||||
}
|
||||
|
||||
/// The sky shader for the pack's sky stage `source`.
|
||||
|
||||
@@ -522,16 +522,27 @@ impl Occlusion {
|
||||
}
|
||||
pub fn set(&mut self, key: SectionKey, vis: u64) {
|
||||
if self.columns.set(key, vis) {
|
||||
self.edits.push(Edit::Set(key, vis));
|
||||
self.dirty = true;
|
||||
self.changed.push(key);
|
||||
if self.running.is_some() {
|
||||
self.changed_late.push(key);
|
||||
}
|
||||
self.changed(key, vis);
|
||||
}
|
||||
}
|
||||
pub fn remove(&mut self, key: SectionKey) {
|
||||
self.set(key, ALL_VISIBLE);
|
||||
fn changed(&mut self, key: SectionKey, vis: u64) {
|
||||
self.edits.push(Edit::Set(key, vis));
|
||||
self.dirty = true;
|
||||
self.changed.push(key);
|
||||
if self.running.is_some() {
|
||||
self.changed_late.push(key);
|
||||
}
|
||||
}
|
||||
/// Every section of the column `x`, `z` goes (sees through every face).
|
||||
pub fn remove_column(&mut self, x: i32, z: i32) {
|
||||
let Some(column) = self.columns.map.remove(&(x, z)) else {
|
||||
return;
|
||||
};
|
||||
for (y, &vis) in column.iter().enumerate() {
|
||||
if vis != ALL_VISIBLE {
|
||||
self.changed((x, y as i32, z), ALL_VISIBLE);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn clear(&mut self) {
|
||||
self.columns.map.clear();
|
||||
|
||||
@@ -399,7 +399,8 @@ impl FrameUniforms {
|
||||
_ => Value::i(&[0]),
|
||||
}
|
||||
};
|
||||
self.values = NAMES.iter().map(|n| value(n)).collect();
|
||||
self.values.clear();
|
||||
self.values.extend(NAMES.iter().map(|n| value(n)));
|
||||
self.frame = (self.frame + 1) % 720_720;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//! Copies of the renderer's own WGSL that run beside a shader pack's code in one module (the
|
||||
//! sky and material stages of Horizon's packs, docs/shaders.md): every name such a copy
|
||||
//! declares takes a prefix starting with `horizon_`, which the pack check refuses in a pack,
|
||||
//! so no pack name can meet one of Horizon's.
|
||||
|
||||
/// terrain.wgsl, which the copies are taken from.
|
||||
pub const TERRAIN: &str = include_str!("../terrain.wgsl");
|
||||
|
||||
/// The text of `source` from the line starting with `start` up to (not including) the one
|
||||
/// starting with `end`.
|
||||
pub fn section<'a>(source: &'a str, start: &str, end: &str) -> &'a str {
|
||||
let from = source
|
||||
.find(&format!("\n{start}"))
|
||||
.expect("the source has the section")
|
||||
+ 1;
|
||||
let to = from
|
||||
+ source[from..]
|
||||
.find(&format!("\n{end}"))
|
||||
.expect("the source ends the section")
|
||||
+ 1;
|
||||
&source[from..to]
|
||||
}
|
||||
|
||||
/// The names `text` declares at its top level: functions, structs, constants, overrides and
|
||||
/// module variables (bindings).
|
||||
fn declared(text: &str) -> Vec<&str> {
|
||||
let mut names = Vec::new();
|
||||
for line in text.lines() {
|
||||
// Top level only: a function's own `var` and `let` stay as they are.
|
||||
if line.starts_with(char::is_whitespace) {
|
||||
continue;
|
||||
}
|
||||
let mut line = line;
|
||||
while let Some(rest) = line.strip_prefix('@') {
|
||||
// An attribute: `@vertex`, `@group(0)`, `@binding(1)`.
|
||||
let end = rest.find(' ').unwrap_or(rest.len());
|
||||
line = rest[end..].trim_start();
|
||||
}
|
||||
let rest = ["fn ", "struct ", "const ", "override ", "var "]
|
||||
.iter()
|
||||
.find_map(|k| line.strip_prefix(k))
|
||||
.or_else(|| {
|
||||
// `var<uniform> name`, `var<storage, read> name`.
|
||||
let rest = line.strip_prefix("var<")?;
|
||||
Some(rest[rest.find('>')? + 1..].trim_start())
|
||||
});
|
||||
if let Some(rest) = rest {
|
||||
let end = rest
|
||||
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
|
||||
.unwrap_or(rest.len());
|
||||
names.push(&rest[..end]);
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// `text` with every name it declares at its top level, and every use of one, prefixed by
|
||||
/// `prefix`. Comments are rewritten too, which is harmless.
|
||||
pub fn prefixed(text: &str, prefix: &str) -> String {
|
||||
let names = declared(text);
|
||||
let mut out = String::with_capacity(text.len() * 2);
|
||||
let mut word = String::new();
|
||||
let flush = |word: &mut String, out: &mut String| {
|
||||
if names.contains(&word.as_str()) {
|
||||
out.push_str(prefix);
|
||||
}
|
||||
out.push_str(word);
|
||||
word.clear();
|
||||
};
|
||||
for c in text.chars() {
|
||||
if c.is_ascii_alphanumeric() || c == '_' {
|
||||
word.push(c);
|
||||
} else {
|
||||
flush(&mut word, &mut out);
|
||||
out.push(c);
|
||||
}
|
||||
}
|
||||
flush(&mut word, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn prefixes_top_level_names_and_their_uses_only() {
|
||||
let text = "struct S { a: f32, }\n\
|
||||
@group(0) @binding(0) var<uniform> g: S;\n\
|
||||
@group(1) @binding(2) var<storage, read> list: array<u32>;\n\
|
||||
override N: u32 = 1u;\n\
|
||||
const K: f32 = 2.0;\n\
|
||||
@fragment fn f(x: f32) -> @location(0) vec4<f32> {\n \
|
||||
var a = g.a * K;\n \
|
||||
return vec4(a + f32(list[N]) + x);\n\
|
||||
}\n";
|
||||
let out = prefixed(text, "p_");
|
||||
assert_eq!(
|
||||
out,
|
||||
"struct p_S { a: f32, }\n\
|
||||
@group(0) @binding(0) var<uniform> p_g: p_S;\n\
|
||||
@group(1) @binding(2) var<storage, read> p_list: array<u32>;\n\
|
||||
override p_N: u32 = 1u;\n\
|
||||
const p_K: f32 = 2.0;\n\
|
||||
@fragment fn p_f(x: f32) -> @location(0) vec4<f32> {\n \
|
||||
var a = p_g.a * p_K;\n \
|
||||
return vec4(a + f32(p_list[p_N]) + x);\n\
|
||||
}\n"
|
||||
);
|
||||
// Every top-level declaration of terrain.wgsl is found.
|
||||
let names = declared(TERRAIN);
|
||||
for name in [
|
||||
"Globals",
|
||||
"globals",
|
||||
"sprites_7",
|
||||
"SPRITE_SPLIT",
|
||||
"block_slots",
|
||||
"fs_sky",
|
||||
] {
|
||||
assert!(names.contains(&name), "{name}");
|
||||
}
|
||||
assert!(!names.contains(&"out"));
|
||||
}
|
||||
}
|
||||
@@ -444,7 +444,7 @@ pub fn apply_preset(preset: Preset, s: &mut crate::settings::Settings) {
|
||||
let g = &mut s.horizon;
|
||||
g.preset = preset;
|
||||
g.cave_culling = true;
|
||||
g.animated_textures = preset != Preset::Performance;
|
||||
g.animated_textures = true;
|
||||
g.chunk_updates = 0;
|
||||
g.upload_budget_kib = 0;
|
||||
g.sky = true;
|
||||
|
||||
@@ -1111,8 +1111,9 @@ impl SubtitleOverlay {
|
||||
s.purge_old_instances(3000.0 * frame.multiplier, now);
|
||||
}
|
||||
if s.audible_from(position) && !s.played.is_empty() {
|
||||
width = width.max(width_of(&Text::translate(&s.key, &[])));
|
||||
audible.push(i);
|
||||
let text_width = width_of(&Text::translate(&s.key, &[]));
|
||||
width = width.max(text_width);
|
||||
audible.push((i, text_width));
|
||||
}
|
||||
}
|
||||
if audible.is_empty() {
|
||||
@@ -1121,7 +1122,7 @@ impl SubtitleOverlay {
|
||||
let w = |s: &str| font.width(s) as i32;
|
||||
width += w("<") + w(" ") + w(">") + w(" ");
|
||||
let mut row = 0;
|
||||
for i in audible {
|
||||
for (i, text_width) in audible {
|
||||
let s = &self.subtitles[i];
|
||||
let text_value = Text::translate(&s.key, &[]);
|
||||
let Some(closest) = s.best_candidate(position) else {
|
||||
@@ -1145,7 +1146,6 @@ impl SubtitleOverlay {
|
||||
let half_width = width / 2;
|
||||
let height = 9;
|
||||
let half_height = height / 2;
|
||||
let text_width = width_of(&text_value);
|
||||
let brightness = s.brightness(closest, frame.multiplier, now);
|
||||
out.push(GuiDraw::Push(vec![
|
||||
PoseOp::Translate(
|
||||
|
||||
@@ -56,10 +56,9 @@ impl<'a> TooltipDisplay<'a> {
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let component = horizon_world::nbt::JavaString::from(component);
|
||||
!hidden
|
||||
.iter()
|
||||
.any(|tag| matches!(tag, Tag::String(id) if id == &component))
|
||||
!hidden.iter().any(|tag| {
|
||||
matches!(tag, Tag::String(id) if id.0.iter().copied().eq(component.encode_utf16()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -120,6 +120,21 @@ impl Hub {
|
||||
);
|
||||
}
|
||||
|
||||
/// `ServerPlayer.crit`: send the victim's animation to the players tracking
|
||||
/// the attacker and the attacker themselves (`sendToTrackingPlayersAndSelf`).
|
||||
pub fn critical_hit(&self, attacker: i32, target: i32) {
|
||||
let body = C::Animate(play::Animate {
|
||||
id: target,
|
||||
action: 1,
|
||||
})
|
||||
.encode();
|
||||
for g in self.guests.iter().filter(|g| {
|
||||
self.here(g) && (g.entity_id == attacker || g.tracker.is_tracking(attacker))
|
||||
}) {
|
||||
g.sender.send(body.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// `ServerLevel.broadcastDamageEvent`: the clients around show the hurt
|
||||
/// entity's flash and hear its hurt sound.
|
||||
pub fn damage_event(
|
||||
|
||||
@@ -2175,17 +2175,24 @@ impl Hub {
|
||||
if g.spectator() || g.sleeping {
|
||||
return (false, false);
|
||||
}
|
||||
let height = if g.fall_flying {
|
||||
0.6
|
||||
// getBoundingBox: the box of the body's pose (swimming and crawling
|
||||
// are 0.6 tall), so a swimmer under a ceiling isn't sent back.
|
||||
let (half, height) = if g.fall_flying {
|
||||
(0.3, 0.6)
|
||||
} else if let Some(m) = &g.motion {
|
||||
(
|
||||
f64::from(m.dimensions.width) / 2.0,
|
||||
f64::from(m.dimensions.height),
|
||||
)
|
||||
} else if g.sneaking {
|
||||
1.5
|
||||
(0.3, 1.5)
|
||||
} else {
|
||||
1.8
|
||||
(0.3, 1.8)
|
||||
};
|
||||
let at = |p: [f64; 3]| {
|
||||
Aabb::new(
|
||||
Vec3::new(p[0] - 0.3, p[1], p[2] - 0.3),
|
||||
Vec3::new(p[0] + 0.3, p[1] + height, p[2] + 0.3),
|
||||
Vec3::new(p[0] - half, p[1], p[2] - half),
|
||||
Vec3::new(p[0] + half, p[1] + height, p[2] + half),
|
||||
)
|
||||
};
|
||||
let (old, new) = (at(g.position), at(to));
|
||||
|
||||
@@ -752,6 +752,25 @@ impl Lod {
|
||||
saved_order: VecDeque::new(),
|
||||
}
|
||||
}
|
||||
/// The solid ground at block column (x, z): its top face's height and
|
||||
/// its block, from the finest tile sampled there. For aiming past the
|
||||
/// resident chunks (`game.raycast`); water is passed, as the view's ray
|
||||
/// passes it.
|
||||
pub fn ground(&self, x: i32, z: i32) -> Option<(i32, BlockStateId)> {
|
||||
(0..=MAX_LEVEL).find_map(|level| {
|
||||
let size = 16 << level;
|
||||
let key = TileKey {
|
||||
x: x.div_euclid(size),
|
||||
z: z.div_euclid(size),
|
||||
level,
|
||||
};
|
||||
let columns = self.ready.get(&key).filter(|c| c.len() == CELLS * CELLS)?;
|
||||
let cell = size / CELLS as i32;
|
||||
let (cx, cz) = ((x - key.x * size) / cell, (z - key.z * size) / cell);
|
||||
let surface = columns[cz as usize * CELLS + cx as usize].surface?;
|
||||
Some((surface.height, surface.state))
|
||||
})
|
||||
}
|
||||
pub fn stats(&self) -> (usize, usize) {
|
||||
(self.active.len(), self.ready.len())
|
||||
}
|
||||
|
||||
@@ -4,7 +4,13 @@ mod game;
|
||||
|
||||
use horizon_client::{crash, logging};
|
||||
|
||||
/// The mod API level this game serves, kept in the program for the launcher
|
||||
/// to read without running it (`horizon_mods::api_level::MARK`). `main`
|
||||
/// reads it, so the linker keeps it.
|
||||
static MOD_API_LEVEL: [u8; 27] = horizon_mods::api_level::MARK;
|
||||
|
||||
fn main() {
|
||||
std::hint::black_box(&MOD_API_LEVEL);
|
||||
horizon_client::telemetry::mark_start();
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let game_args = args.iter().take_while(|a| *a != "--dedicated");
|
||||
|
||||
@@ -1024,6 +1024,10 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool {
|
||||
if m.species() == Species::Mannequin {
|
||||
return true;
|
||||
}
|
||||
// Mob.checkDespawn discards disallowed types even when persistent or NoAI.
|
||||
if w.difficulty.effective == 0.0 && !super::spawn_rules::allowed_in_peaceful(m.species()) {
|
||||
return false;
|
||||
}
|
||||
let Some(p) = w.nearest_player else {
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -102,7 +102,7 @@ impl AnimState {
|
||||
pub fn end_tick(&mut self, _swinging: bool) {}
|
||||
}
|
||||
/// Part poses for one draw, keyed by part name.
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, Default)]
|
||||
pub struct Poses {
|
||||
map: HashMap<String, [f32; 9]>,
|
||||
dummy: [f32; 9],
|
||||
@@ -113,20 +113,24 @@ pub struct Poses {
|
||||
}
|
||||
impl Poses {
|
||||
pub fn new(model: &Part) -> Self {
|
||||
let mut map = HashMap::new();
|
||||
let mut poses = Self::default();
|
||||
poses.reset(model);
|
||||
poses
|
||||
}
|
||||
/// Refills this for another model, keeping the map and the sets' capacity:
|
||||
/// a mob draws its body and every equipment layer each frame.
|
||||
pub fn reset(&mut self, model: &Part) {
|
||||
fn walk(p: &Part, map: &mut HashMap<String, [f32; 9]>) {
|
||||
map.insert(p.name.clone(), p.pose);
|
||||
for c in &p.children {
|
||||
walk(c, map);
|
||||
}
|
||||
}
|
||||
walk(model, &mut map);
|
||||
Self {
|
||||
map,
|
||||
dummy: [0.0; 9],
|
||||
skipped: Default::default(),
|
||||
hidden: Default::default(),
|
||||
}
|
||||
self.map.clear();
|
||||
self.dummy = [0.0; 9];
|
||||
self.skipped.clear();
|
||||
self.hidden.clear();
|
||||
walk(model, &mut self.map);
|
||||
}
|
||||
pub fn get(&mut self, name: &str) -> &mut [f32; 9] {
|
||||
match self.map.get_mut(name) {
|
||||
@@ -189,14 +193,15 @@ pub fn state(m: &Mob, alpha: f32) -> State {
|
||||
swing += 1.0;
|
||||
}
|
||||
let swing = m.anim.attack_anim_o + swing * alpha;
|
||||
let alive = m.alive();
|
||||
// LivingEntityRenderer.extractRenderState: riding motion is not walking.
|
||||
let walking = m.alive() && !m.extra.passenger;
|
||||
State {
|
||||
pos: if alive {
|
||||
pos: if walking {
|
||||
m.limb_position - m.limb_speed * (1.0 - alpha)
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
speed: if alive {
|
||||
speed: if walking {
|
||||
(m.previous_limb_speed + (m.limb_speed - m.previous_limb_speed) * alpha).min(1.0)
|
||||
} else {
|
||||
0.0
|
||||
|
||||
@@ -132,6 +132,10 @@ pub fn tick(m: &mut Mob) {
|
||||
} else {
|
||||
m.velocity.y *= 0.6;
|
||||
}
|
||||
setup_animation_states(m);
|
||||
}
|
||||
/// `Bat.setupAnimationStates`: client visuals, without changing server motion.
|
||||
pub fn setup_animation_states(m: &mut Mob) {
|
||||
let age = m.age as f32;
|
||||
if resting(m) {
|
||||
m.anim.states[0].stop();
|
||||
|
||||
@@ -138,9 +138,10 @@ fn teleport_towards(
|
||||
let z = m.position.z + (m.random.next_double() - 0.5) * 8.0 - d[2] * 16.0;
|
||||
teleport_to(m, w, x, y, z, events)
|
||||
}
|
||||
/// Enderman.customServerAiStep: in daylight, flee by teleporting.
|
||||
/// Enderman.customServerAiStep: in daylight, flee by teleporting. The End has a
|
||||
/// fixed time, so `Level.isBrightOutside` is never true there.
|
||||
pub fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
|
||||
if cx.w.daylight && m.age as i32 >= m.extra.counter + 600 {
|
||||
if cx.w.daylight && !cx.w.end && m.age as i32 >= m.extra.counter + 600 {
|
||||
let br = super::hostile::mob_brightness(m, cx.w);
|
||||
let (x, y, z) = (
|
||||
m.position.x.floor() as i32,
|
||||
|
||||
@@ -951,21 +951,25 @@ fn draw_normals(
|
||||
return;
|
||||
}
|
||||
let normals = normals.part(p);
|
||||
for poly in part.polygons.iter().filter(|_| !poses.skips(part)) {
|
||||
let normal = poly.vertex_normal(normals);
|
||||
for v in poly.vertices {
|
||||
let pos = m.transform_point3(glam::Vec3::new(v[0], v[1], v[2]) / 16.0);
|
||||
out.push(Vertex {
|
||||
normal,
|
||||
pos: pos.to_array(),
|
||||
uv: [
|
||||
uv[0] + (uv[2] - uv[0]) * v[3],
|
||||
uv[1] + (uv[3] - uv[1]) * v[4],
|
||||
],
|
||||
layer: overlay,
|
||||
color,
|
||||
light,
|
||||
});
|
||||
// `skips` is a name lookup: ask once per part, not once per polygon. A part
|
||||
// hidden this way still draws its children, so only the polygons are gated.
|
||||
if !poses.skips(part) {
|
||||
for poly in &part.polygons {
|
||||
let normal = poly.vertex_normal(normals);
|
||||
for v in poly.vertices {
|
||||
let pos = m.transform_point3(glam::Vec3::new(v[0], v[1], v[2]) / 16.0);
|
||||
out.push(Vertex {
|
||||
normal,
|
||||
pos: pos.to_array(),
|
||||
uv: [
|
||||
uv[0] + (uv[2] - uv[0]) * v[3],
|
||||
uv[1] + (uv[3] - uv[1]) * v[4],
|
||||
],
|
||||
layer: overlay,
|
||||
color,
|
||||
light,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
for c in &part.children {
|
||||
@@ -1094,6 +1098,9 @@ fn render_visible(
|
||||
}
|
||||
}
|
||||
}
|
||||
// One Poses refilled for every layer (armour draws up to seven): it keeps
|
||||
// its maps' capacity.
|
||||
let mut layer_poses = Poses::default();
|
||||
for layer in all_layers {
|
||||
let Some(part) = m.kind.layer(&layer.model).cloned() else {
|
||||
continue;
|
||||
@@ -1101,8 +1108,8 @@ fn render_visible(
|
||||
let Some(uv) = atlas(&layer.texture) else {
|
||||
continue;
|
||||
};
|
||||
let mut poses = Poses::new(&part);
|
||||
anim::setup(m, &s, &mut poses, &data.animations);
|
||||
layer_poses.reset(&part);
|
||||
anim::setup(m, &s, &mut layer_poses, &data.animations);
|
||||
if matches!(m.species(), Species::Villager | Species::ZombieVillager)
|
||||
&& let Some((folder, variant)) = layer
|
||||
.texture
|
||||
@@ -1113,7 +1120,7 @@ fn render_visible(
|
||||
data.villager_hats
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.apply(folder, variant, profession, &mut poses);
|
||||
.apply(folder, variant, profession, &mut layer_poses);
|
||||
}
|
||||
let light = if layer.full_bright {
|
||||
240 | 240 << 8
|
||||
@@ -1128,7 +1135,16 @@ fn render_visible(
|
||||
None => overlay,
|
||||
};
|
||||
let start = out.len();
|
||||
draw(&part, base, &poses, uv, layer.color, light, overlay, out);
|
||||
draw(
|
||||
&part,
|
||||
base,
|
||||
&layer_poses,
|
||||
uv,
|
||||
layer.color,
|
||||
light,
|
||||
overlay,
|
||||
out,
|
||||
);
|
||||
if layer.full_bright && m.species() != Species::Warden {
|
||||
for vertex in &mut out[start..] {
|
||||
vertex.normal = [0; 4];
|
||||
|
||||
@@ -284,12 +284,14 @@ pub fn xp(m: &Mob) -> i32 {
|
||||
m.extra.trade.as_ref().map_or(0, |t| t.xp)
|
||||
}
|
||||
/// `Villager.setVillagerData(withProfession)`: a new profession forgets the
|
||||
/// offers.
|
||||
/// offers (`offers = null`), so the next `getOffers` rolls the new
|
||||
/// profession's trades.
|
||||
pub fn set_profession(m: &mut Mob, profession: u8) {
|
||||
if m.extra.variant2 != profession {
|
||||
m.extra.variant2 = profession;
|
||||
if let Some(t) = m.extra.trade.as_mut() {
|
||||
t.offers.clear();
|
||||
t.unset = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -846,6 +848,70 @@ pub fn read_nbt(m: &mut Mob, tag: &horizon_world::nbt::Tag) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn villager() -> Mob {
|
||||
use crate::mobs::{Anim, Brain, Flags, MobType, Part, Species};
|
||||
use std::{collections::HashMap, sync::Arc};
|
||||
let kind = Arc::new(MobType {
|
||||
id: "minecraft:villager".into(),
|
||||
species: Species::Villager,
|
||||
width: 0.6,
|
||||
height: 1.95,
|
||||
eye_height: 1.62,
|
||||
category: "misc".into(),
|
||||
max_health: 20.0,
|
||||
speed: 0.5,
|
||||
flying_speed: 0.02,
|
||||
attack_damage: 0.0,
|
||||
attack_knockback: 0.0,
|
||||
follow_range: 48.0,
|
||||
step_height: 0.6,
|
||||
armor: 0.0,
|
||||
armor_toughness: 0.0,
|
||||
knockback_resistance: 0.0,
|
||||
jump_strength: 0.42,
|
||||
attributes: Arc::default(),
|
||||
gravity: 0.08,
|
||||
safe_fall_distance: 3.0,
|
||||
fall_damage_multiplier: 1.0,
|
||||
water_efficiency: 0.0,
|
||||
water_slowdown: 0.8,
|
||||
air_speed: 0.02,
|
||||
baby_scale: 0.5,
|
||||
head_rot_speed: 10.0,
|
||||
max_head_x_rot: 40.0,
|
||||
max_head_y_rot: 75.0,
|
||||
ambient_interval: 80,
|
||||
flags: Flags::default(),
|
||||
model: Arc::new(Part::parse("root", &serde_json::json!({}))),
|
||||
layers: HashMap::new(),
|
||||
texture: String::new(),
|
||||
brain: Brain::Passive,
|
||||
anim: Anim::Villager,
|
||||
sounds: [""; 3],
|
||||
step_sound: None,
|
||||
food: Arc::default(),
|
||||
tempt: Arc::default(),
|
||||
});
|
||||
Mob::new(1, kind, horizon_core::geometry::Vec3::ZERO, 0.0)
|
||||
}
|
||||
#[test]
|
||||
fn a_new_profession_rolls_new_offers() {
|
||||
let mut m = villager();
|
||||
set_profession(&mut m, 1);
|
||||
// Offers made for the first profession.
|
||||
m.extra.trade.get_or_insert_default().unset = false;
|
||||
// The same profession keeps them.
|
||||
set_profession(&mut m, 1);
|
||||
assert!(!m.extra.trade.as_ref().unwrap().unset);
|
||||
// A new one forgets them (offers = null), so the next getOffers
|
||||
// (ensure_offers) rolls the new profession's trades.
|
||||
set_profession(&mut m, 2);
|
||||
let t = m.extra.trade.as_ref().unwrap();
|
||||
assert!(t.offers.is_empty());
|
||||
assert!(t.unset);
|
||||
assert_eq!(m.extra.variant2, 2);
|
||||
}
|
||||
|
||||
fn stack(item: &str, count: u32) -> ItemStack {
|
||||
ItemStack::new(item, count)
|
||||
}
|
||||
|
||||
@@ -164,21 +164,21 @@ pub fn fetch_index() -> Result<Index, String> {
|
||||
|
||||
/// Installs `m` into the game folder `dir` (where `options.txt` is), for a
|
||||
/// player whose extras were `e`: its newest version for this game that
|
||||
/// wasn't taken down, checked against the index (size, SHA-256, signature,
|
||||
/// manifest), as `horizon-mods/<id>.hmod`, turned on, with the extra's
|
||||
/// settings in its storage unless the mod has its own already.
|
||||
/// wasn't taken down and that this Horizon's mod API level runs, checked
|
||||
/// against the index (size, SHA-256, signature, manifest), as
|
||||
/// `horizon-mods/<id>.hmod`, turned on, with the extra's settings in its
|
||||
/// storage unless the mod has its own already.
|
||||
pub fn install(index: &Index, m: &Moved, e: &Extras, dir: &Path) -> Result<(), String> {
|
||||
let project = index
|
||||
.project(m.id)
|
||||
.ok_or_else(|| format!("{} isn't in Horizon's registry yet", m.id))?;
|
||||
let version = project
|
||||
.versions
|
||||
.iter()
|
||||
.find(|v| {
|
||||
v.game == horizon_core::version::VERSION_ID
|
||||
&& index.revoked(&project.id, &v.file.sha256).is_none()
|
||||
})
|
||||
.ok_or_else(|| format!("{} has no version for this game", m.id))?;
|
||||
let version = index
|
||||
.installable(
|
||||
project,
|
||||
horizon_core::version::VERSION_ID,
|
||||
horizon_mods::api_level::LEVEL,
|
||||
)
|
||||
.ok_or_else(|| format!("{} has no version this Horizon can run", m.id))?;
|
||||
let mods = dir.join(crate::mod_list::DIR);
|
||||
fs::create_dir_all(&mods).map_err(|e| format!("{}: {e}", mods.display()))?;
|
||||
let target = mods.join(format!("{}.hmod", m.id));
|
||||
|
||||
@@ -491,7 +491,7 @@ impl Screen {
|
||||
w / 2.0 - 100.0,
|
||||
h / 4.0 + 96.0 + 18.0,
|
||||
200.0,
|
||||
"Done",
|
||||
&crate::lang::get_or("gui.done", "Done"),
|
||||
servers::parse_address(address).is_some(),
|
||||
50,
|
||||
),
|
||||
@@ -499,7 +499,7 @@ impl Screen {
|
||||
w / 2.0 - 100.0,
|
||||
h / 4.0 + 120.0 + 18.0,
|
||||
200.0,
|
||||
"Cancel",
|
||||
&crate::lang::get_or("gui.cancel", "Cancel"),
|
||||
true,
|
||||
51,
|
||||
),
|
||||
@@ -532,7 +532,7 @@ impl Screen {
|
||||
w / 2.0 - 100.0,
|
||||
h / 4.0 + 96.0 + 12.0,
|
||||
200.0,
|
||||
"Join Server",
|
||||
&crate::lang::get_or("selectServer.select", "Join Server"),
|
||||
servers::parse_address(address).is_some(),
|
||||
52,
|
||||
),
|
||||
@@ -540,7 +540,7 @@ impl Screen {
|
||||
w / 2.0 - 100.0,
|
||||
h / 4.0 + 120.0 + 12.0,
|
||||
200.0,
|
||||
"Cancel",
|
||||
&crate::lang::get_or("gui.cancel", "Cancel"),
|
||||
true,
|
||||
53,
|
||||
),
|
||||
@@ -558,7 +558,7 @@ impl Screen {
|
||||
w / 2.0 - 100.0,
|
||||
h / 4.0 + 120.0 + 18.0,
|
||||
200.0,
|
||||
"Cancel",
|
||||
&crate::lang::get_or("gui.cancel", "Cancel"),
|
||||
true,
|
||||
57,
|
||||
),
|
||||
@@ -568,7 +568,7 @@ impl Screen {
|
||||
w / 2.0 - 100.0,
|
||||
h / 2.0 + 30.0,
|
||||
200.0,
|
||||
"Back to Server List",
|
||||
&crate::lang::get_or("gui.toMenu", "Back to Server List"),
|
||||
true,
|
||||
54,
|
||||
)];
|
||||
@@ -876,10 +876,10 @@ impl Screen {
|
||||
} => {
|
||||
centered(
|
||||
batch,
|
||||
if index.is_some() {
|
||||
"Edit Server Info"
|
||||
&if index.is_some() {
|
||||
crate::lang::get_or("manageServer.edit.title", "Edit Server Info")
|
||||
} else {
|
||||
"Add Server"
|
||||
crate::lang::get_or("manageServer.add.title", "Add Server")
|
||||
},
|
||||
17.0,
|
||||
u32::MAX,
|
||||
@@ -888,7 +888,7 @@ impl Screen {
|
||||
Self::field(
|
||||
atlas,
|
||||
batch,
|
||||
"Server Name",
|
||||
&crate::lang::get_or("manageServer.enterName", "Server Name"),
|
||||
name,
|
||||
(53.0, 66.0),
|
||||
*focus == 0,
|
||||
@@ -897,7 +897,7 @@ impl Screen {
|
||||
Self::field(
|
||||
atlas,
|
||||
batch,
|
||||
"Server Address",
|
||||
&crate::lang::get_or("manageServer.enterIp", "Server Address"),
|
||||
address,
|
||||
(94.0, 106.0),
|
||||
*focus == 1,
|
||||
@@ -916,7 +916,7 @@ impl Screen {
|
||||
Self::field(
|
||||
atlas,
|
||||
batch,
|
||||
&crate::lang::get_or("addServer.enterIp", "Server Address"),
|
||||
&crate::lang::get_or("manageServer.enterIp", "Server Address"),
|
||||
address,
|
||||
(100.0, 116.0),
|
||||
true,
|
||||
@@ -973,7 +973,7 @@ impl Screen {
|
||||
Self::Disconnected { reason, retry } => {
|
||||
centered(
|
||||
batch,
|
||||
"Connection Lost",
|
||||
&crate::lang::get_or("disconnect.lost", "Connection Lost"),
|
||||
h / 2.0 - 40.0,
|
||||
rgba(170, 170, 170, 255),
|
||||
);
|
||||
@@ -1019,7 +1019,7 @@ impl Screen {
|
||||
(Self::List { .. }, Some(42)) => {
|
||||
*self = Self::Edit {
|
||||
index: None,
|
||||
name: "Minecraft Server".into(),
|
||||
name: crate::lang::get_or("selectServer.defaultName", "Minecraft Server"),
|
||||
address: String::new(),
|
||||
focus: 1,
|
||||
packs: None,
|
||||
|
||||
@@ -192,7 +192,7 @@ pub fn list_worlds(saves: &Path) -> Vec<WorldEntry> {
|
||||
commands: matches!(data.get("allowCommands"), Some(horizon_world::nbt::Tag::Byte(v)) if *v != 0),
|
||||
version: data.get("Version").and_then(|v| v.get("Name"))
|
||||
.and_then(|v| match v { horizon_world::nbt::Tag::String(s) => Some(s.to_string_lossy()), _ => None })
|
||||
.unwrap_or_else(|| "Unknown".into()),
|
||||
.unwrap_or_else(|| lang::get_or("selectWorld.versionUnknown", "Unknown")),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -272,7 +272,7 @@ impl Title {
|
||||
}
|
||||
pub(crate) fn new_world() -> Mode {
|
||||
Mode::Create {
|
||||
name: "New World".into(),
|
||||
name: lang::get_or("selectWorld.newWorld", "New World"),
|
||||
seed: String::new(),
|
||||
creative: false,
|
||||
focus: 0,
|
||||
@@ -867,7 +867,13 @@ impl Title {
|
||||
}
|
||||
Mode::Select { worlds, selected } => {
|
||||
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
|
||||
centered(atlas, batch, "Select World", 8.0, u32::MAX);
|
||||
centered(
|
||||
atlas,
|
||||
batch,
|
||||
&lang::get_or("selectWorld.title", "Select World"),
|
||||
8.0,
|
||||
u32::MAX,
|
||||
);
|
||||
self.caret.borrow_mut().draw(
|
||||
batch,
|
||||
atlas,
|
||||
|
||||
@@ -339,7 +339,9 @@ pub fn shared_data(
|
||||
if let Some((_, data)) = cache.iter().find(|(path, _)| path == dir) {
|
||||
return Ok(data.clone());
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let data = GeneratorData::load(dir, registry)?;
|
||||
log::info!("Horizon: worldgen data loaded in {:?}", started.elapsed());
|
||||
cache.push((dir.to_owned(), data.clone()));
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
Generated
+102
-4
@@ -294,6 +294,18 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fallible-iterator"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
|
||||
|
||||
[[package]]
|
||||
name = "fallible-streaming-iterator"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.15"
|
||||
@@ -310,6 +322,12 @@ dependencies = [
|
||||
"miniz_oxide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
@@ -394,13 +412,33 @@ dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.15.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
|
||||
dependencies = [
|
||||
"foldhash 0.1.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
"foldhash 0.2.0",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashlink"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"
|
||||
dependencies = [
|
||||
"hashbrown 0.15.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -422,6 +460,7 @@ dependencies = [
|
||||
"hmac",
|
||||
"horizon-mods",
|
||||
"http-body-util",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
@@ -442,6 +481,7 @@ dependencies = [
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"toml",
|
||||
"wasmparser",
|
||||
"zip",
|
||||
]
|
||||
|
||||
@@ -648,7 +688,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||
dependencies = [
|
||||
"equivalent",
|
||||
"hashbrown",
|
||||
"hashbrown 0.17.1",
|
||||
"serde",
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -669,6 +711,17 @@ version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "libsqlite3-sys"
|
||||
version = "0.35.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "133c182a6a2c87864fe97778797e46c7e999672690dc9fa3ee8e241aa4a9c13f"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "litemap"
|
||||
version = "0.8.3"
|
||||
@@ -762,7 +815,7 @@ dependencies = [
|
||||
"cfg_aliases",
|
||||
"codespan-reporting",
|
||||
"half",
|
||||
"hashbrown",
|
||||
"hashbrown 0.17.1",
|
||||
"indexmap",
|
||||
"libm",
|
||||
"log",
|
||||
@@ -781,7 +834,7 @@ version = "30.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49"
|
||||
dependencies = [
|
||||
"hashbrown",
|
||||
"hashbrown 0.17.1",
|
||||
"indexmap",
|
||||
"rustc-hash",
|
||||
"thiserror",
|
||||
@@ -815,6 +868,12 @@ version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
|
||||
|
||||
[[package]]
|
||||
name = "potential_utf"
|
||||
version = "0.1.6"
|
||||
@@ -862,6 +921,20 @@ dependencies = [
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rusqlite"
|
||||
version = "0.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "165ca6e57b20e1351573e3729b958bc62f0e48025386970b6e4d29e7a7e71f3f"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"fallible-iterator",
|
||||
"fallible-streaming-iterator",
|
||||
"hashlink",
|
||||
"libsqlite3-sys",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "1.1.0"
|
||||
@@ -921,6 +994,12 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "semver"
|
||||
version = "1.0.28"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.229"
|
||||
@@ -1305,6 +1384,12 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||
|
||||
[[package]]
|
||||
name = "vcpkg"
|
||||
version = "0.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
@@ -1326,6 +1411,19 @@ dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasmparser"
|
||||
version = "0.254.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c5ff8685b587722894b6f25958fc608d315b93b8d23647bfb567664e7006d757"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"hashbrown 0.17.1",
|
||||
"indexmap",
|
||||
"semver",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "webpki-roots"
|
||||
version = "0.26.11"
|
||||
|
||||
@@ -23,6 +23,8 @@ hmac = "0.12"
|
||||
sha2 = "0.10"
|
||||
base64 = "0.22"
|
||||
getrandom = "0.3"
|
||||
# Ratings: one SQLite file on a small volume, as the telemetry server keeps its data.
|
||||
rusqlite = { version = "0.37", features = ["bundled"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
|
||||
@@ -4,11 +4,15 @@ WORKDIR /src
|
||||
# The root manifest only for the shared crate's workspace settings (edition, lints).
|
||||
COPY Cargo.toml Cargo.toml
|
||||
COPY crates/horizon-mods crates/horizon-mods
|
||||
# horizon-mods' optional dependency: cargo needs its manifest even with the feature off.
|
||||
COPY crates/horizon-shader-api crates/horizon-shader-api
|
||||
COPY crates/horizon-mod-registry crates/horizon-mod-registry
|
||||
RUN cargo build --release --locked --manifest-path crates/horizon-mod-registry/Cargo.toml
|
||||
|
||||
FROM debian:stable-slim
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
|
||||
COPY --from=build /src/crates/horizon-mod-registry/target/release/horizon-mod-registry /usr/local/bin/
|
||||
USER nobody
|
||||
CMD ["horizon-mod-registry"]
|
||||
ENV REGISTRY_DB=/data/registry.sqlite3
|
||||
# Railway mounts the ratings' volume at /data owned by root: hand it to nobody, then run as nobody (setpriv is
|
||||
# util-linux's, in every Debian image).
|
||||
CMD ["sh", "-c", "mkdir -p /data && chown nobody:nogroup /data && exec setpriv --reuid=nobody --regid=nogroup --clear-groups horizon-mod-registry"]
|
||||
|
||||
@@ -7,20 +7,26 @@ entry's fields), uploads it to the `staging` release of
|
||||
request adding or updating `mods/<id>.toml`. That repository's CI checks it again, with a trial run of a mod in the
|
||||
sandbox; reviewers decide, and merging publishes. Formats and rules: [docs/api/mod-index.md](../../docs/api/mod-index.md).
|
||||
|
||||
It keeps no data: a session is a signed cookie holding the GitHub login, and the user's OAuth token is used once, to
|
||||
read that login, and dropped. The sign-in asks for no scope.
|
||||
Signed-in players also rate published projects, 1 to 5 stars: one rating per GitHub account and project, which they can
|
||||
change, never their own project's. That is the only data it keeps, in one SQLite file (`REGISTRY_DB`); it only ever
|
||||
shows totals, never who rated. A session is a signed cookie holding the GitHub login and id, and the user's OAuth token
|
||||
is used once, to read them, and dropped. The sign-in asks for no scope.
|
||||
|
||||
| Route | |
|
||||
| --- | --- |
|
||||
| `GET /api/mods/auth/login` | Starts the GitHub sign-in |
|
||||
| `GET /api/mods/auth/callback` | GitHub's redirect: sets the session, back to `/mods/submit` |
|
||||
| `GET /api/mods/auth/login` | Starts the GitHub sign-in; `?back=/mods/<id>` (or `/mods`) comes back to that page |
|
||||
| `GET /api/mods/auth/callback` | GitHub's redirect: sets the session, back to `/mods/submit` or the `back` page |
|
||||
| `POST /api/mods/auth/logout` | Ends it |
|
||||
| `GET /api/mods/me` | `{login, csrf}`, or 401 |
|
||||
| `POST /api/mods/submit` | Multipart: `entry` (JSON: `id kind name summary description authors license source icon key signature version game changelog`) and `file`; `{pull_request}` or `{error}` |
|
||||
| `GET /api/mods/ratings` | `{projects: {<id>: {average, count}}}` for every rated project; cached a minute |
|
||||
| `GET /api/mods/<id>/rating` | The signed-in account's own `{stars}` (null when it hasn't rated), or 401 |
|
||||
| `POST /api/mods/<id>/rating` | JSON `{stars}`, 1 to 5: sets or changes it; `{stars, average, count}` or `{error}` |
|
||||
| `GET /healthz` | `ok` |
|
||||
|
||||
A submission must come from `REGISTRY_PUBLIC_URL`'s origin with the session's `X-CSRF-Token`. Six per account and sixty
|
||||
in all per hour. Only an entry's `owners` publish its updates; a key change, an icon in the repository or anything else
|
||||
A submission or a rating must come from `REGISTRY_PUBLIC_URL`'s origin with the session's `X-CSRF-Token`. Six
|
||||
submissions per account and sixty in all per hour; thirty ratings per account and 600 in all. A project's owners can't
|
||||
rate it, and only projects on the registry's `main` can be rated. Only an entry's `owners` publish its updates; a key change, an icon in the repository or anything else
|
||||
is a pull request by hand.
|
||||
|
||||
## Running it
|
||||
@@ -28,7 +34,7 @@ is a pull request by hand.
|
||||
```sh
|
||||
cargo test # against a mock GitHub (tests/submit.rs)
|
||||
REGISTRY_PUBLIC_URL=http://localhost:4173 REGISTRY_SESSION_KEY=... GITHUB_CLIENT_ID=... GITHUB_CLIENT_SECRET=... \
|
||||
GITHUB_BOT_TOKEN=... REGISTRY_REPO=you/horizon-mods-test cargo run
|
||||
GITHUB_BOT_TOKEN=... REGISTRY_REPO=you/horizon-mods-test REGISTRY_DB=/tmp/registry.sqlite3 cargo run
|
||||
```
|
||||
|
||||
| Variable | |
|
||||
@@ -38,10 +44,12 @@ REGISTRY_PUBLIC_URL=http://localhost:4173 REGISTRY_SESSION_KEY=... GITHUB_CLIENT
|
||||
| `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET` | The OAuth app |
|
||||
| `GITHUB_BOT_TOKEN` | Fine-grained, the registry repository only: Contents and Pull requests read and write |
|
||||
| `REGISTRY_REPO` | Default `ludovic111/horizon-mods` |
|
||||
| `REGISTRY_DB` | The ratings' SQLite file: default `/data/registry.sqlite3`, the volume |
|
||||
| `PORT` | Default 8080 |
|
||||
|
||||
On Railway it is the service `horizon-mod-registry` of the project `horizon-site`, next to the website: built from
|
||||
`main` with this `Dockerfile` from the repository root, health check `/healthz`, no public domain and no volume. The
|
||||
`main` with this `Dockerfile` from the repository root, health check `/healthz`, no public domain, and the volume
|
||||
`registry-data` at `/data` for the ratings. The
|
||||
website's Caddy sends `/api/mods/*` to it over Railway's private network (`REGISTRY_UPSTREAM` on the website service:
|
||||
`http://horizon-mod-registry.railway.internal:8080`). `railway.json` lists the same settings; Railway reads them from
|
||||
the service, not from the file.
|
||||
|
||||
@@ -2,13 +2,15 @@
|
||||
//! `playhorizon.dev/api/mods/*` (docs/api/mod-index.md). A creator signs in
|
||||
//! with GitHub, sends a file and its page; the service runs the file's own
|
||||
//! checks, uploads it to the registry's `staging` release and opens a pull
|
||||
//! request with the entry. Reviewers decide; merging publishes. It keeps no
|
||||
//! data: sessions are signed cookies, and GitHub holds everything else.
|
||||
//! request with the entry. Reviewers decide; merging publishes. Signed-in
|
||||
//! players also rate published projects (`ratings`, its only data: sessions
|
||||
//! are signed cookies, and GitHub holds everything else).
|
||||
pub mod github;
|
||||
pub mod ratings;
|
||||
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{DefaultBodyLimit, Multipart, Query, State},
|
||||
extract::{DefaultBodyLimit, Multipart, Path as UrlPath, Query, State},
|
||||
http::{HeaderMap, StatusCode, header},
|
||||
response::{IntoResponse, Redirect, Response},
|
||||
routing::{get, post},
|
||||
@@ -20,6 +22,7 @@ use horizon_mods::index::{
|
||||
self, Kind,
|
||||
registry::{self, Entry, EntryVersion, Sources},
|
||||
};
|
||||
use ratings::Ratings;
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use sha2::Sha256;
|
||||
@@ -37,6 +40,12 @@ const PER_ACCOUNT: usize = 6;
|
||||
const PER_HOUR: usize = 60;
|
||||
/// The page's JSON.
|
||||
const MAX_FORM: usize = 64 << 10;
|
||||
/// Ratings set per account per hour, and by everyone.
|
||||
const RATINGS_PER_ACCOUNT: usize = 30;
|
||||
const RATINGS_PER_HOUR: usize = 600;
|
||||
/// How long the ratings' totals are served from memory (and cached by
|
||||
/// browsers and the launcher).
|
||||
const TOTALS_FOR: Duration = Duration::from_secs(60);
|
||||
|
||||
pub struct Config {
|
||||
/// `https://playhorizon.dev`: where the form is, and the only origin it
|
||||
@@ -47,11 +56,14 @@ pub struct Config {
|
||||
pub github: GitHub,
|
||||
/// Where files wait during a submission.
|
||||
pub scratch: PathBuf,
|
||||
/// The ratings' SQLite file (a volume): `:memory:` keeps them in memory.
|
||||
pub database: PathBuf,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// `REGISTRY_PUBLIC_URL`, `REGISTRY_SESSION_KEY`, `REGISTRY_REPO`,
|
||||
/// `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `GITHUB_BOT_TOKEN`.
|
||||
/// `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `GITHUB_BOT_TOKEN`,
|
||||
/// `REGISTRY_DB` (default `/data/registry.sqlite3`).
|
||||
pub fn from_env() -> Result<Config, String> {
|
||||
let var = |name: &str| std::env::var(name).map_err(|_| format!("{name} is not set"));
|
||||
let key = var("REGISTRY_SESSION_KEY")?;
|
||||
@@ -69,6 +81,8 @@ impl Config {
|
||||
var("GITHUB_BOT_TOKEN")?,
|
||||
),
|
||||
scratch: std::env::temp_dir().join("horizon-mod-registry"),
|
||||
database: std::env::var_os("REGISTRY_DB")
|
||||
.map_or_else(|| PathBuf::from("/data/registry.sqlite3"), PathBuf::from),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -80,17 +94,31 @@ impl Config {
|
||||
#[derive(Clone)]
|
||||
pub struct App(Arc<Inner>);
|
||||
|
||||
type Windows = Mutex<HashMap<String, VecDeque<Instant>>>;
|
||||
|
||||
struct Inner {
|
||||
config: Config,
|
||||
recent: Mutex<HashMap<String, VecDeque<Instant>>>,
|
||||
/// Submissions in the last hour, by account ("" for everyone's).
|
||||
recent: Windows,
|
||||
/// Ratings set in the last hour, the same way.
|
||||
rated: Windows,
|
||||
ratings: Mutex<Ratings>,
|
||||
/// `GET /api/mods/ratings`' body, and when it was made.
|
||||
totals: Mutex<Option<(Instant, String)>>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new(config: Config) -> App {
|
||||
App(Arc::new(Inner {
|
||||
/// Fails when the ratings' file can't be opened.
|
||||
pub fn new(config: Config) -> Result<App, String> {
|
||||
let ratings = Ratings::open(&config.database)
|
||||
.map_err(|e| format!("{}: {e}", config.database.display()))?;
|
||||
Ok(App(Arc::new(Inner {
|
||||
config,
|
||||
recent: Mutex::new(HashMap::new()),
|
||||
}))
|
||||
recent: Mutex::default(),
|
||||
rated: Mutex::default(),
|
||||
ratings: Mutex::new(ratings),
|
||||
totals: Mutex::default(),
|
||||
})))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,6 +129,8 @@ pub fn router(app: App) -> Router {
|
||||
.route("/api/mods/auth/callback", get(callback))
|
||||
.route("/api/mods/auth/logout", post(logout))
|
||||
.route("/api/mods/me", get(me))
|
||||
.route("/api/mods/ratings", get(totals))
|
||||
.route("/api/mods/{id}/rating", get(my_rating).post(rate))
|
||||
.route(
|
||||
"/api/mods/submit",
|
||||
post(submit).layer(DefaultBodyLimit::max(
|
||||
@@ -203,9 +233,29 @@ fn csrf(app: &Inner, headers: &HeaderMap) -> Option<String> {
|
||||
Some(signed.rsplit('.').next()?.chars().take(32).collect())
|
||||
}
|
||||
|
||||
async fn login(State(app): State<App>) -> Response {
|
||||
#[derive(Deserialize)]
|
||||
struct Login {
|
||||
/// The site's page to come back to: `/mods`, `/mods/submit` (the
|
||||
/// default) or `/mods/<id>`.
|
||||
back: Option<String>,
|
||||
}
|
||||
|
||||
/// Whether `path` is a registry page a sign-in may come back to.
|
||||
fn registry_page(path: &str) -> bool {
|
||||
match path.strip_prefix("/mods") {
|
||||
Some("") => true,
|
||||
Some(rest) => rest.strip_prefix('/').is_some_and(index::valid_id) || rest == "/submit",
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
async fn login(State(app): State<App>, Query(q): Query<Login>) -> Response {
|
||||
let state = random_hex();
|
||||
let signed = sign(&app.0.config.session_key, &state);
|
||||
let back = q
|
||||
.back
|
||||
.filter(|b| registry_page(b))
|
||||
.unwrap_or_else(|| "/mods/submit".into());
|
||||
let signed = sign(&app.0.config.session_key, &format!("{state}\n{back}"));
|
||||
let url = app
|
||||
.0
|
||||
.config
|
||||
@@ -229,13 +279,17 @@ async fn callback(
|
||||
headers: HeaderMap,
|
||||
Query(q): Query<Callback>,
|
||||
) -> Result<Response, Refusal> {
|
||||
let expected = cookie(&headers, "hm_state").and_then(|v| unsign(&app.0.config.session_key, &v));
|
||||
if expected.as_deref() != Some(q.state.as_str()) {
|
||||
let started = cookie(&headers, "hm_state").and_then(|v| unsign(&app.0.config.session_key, &v));
|
||||
let Some((_, back)) = started
|
||||
.as_deref()
|
||||
.and_then(|s| s.split_once('\n'))
|
||||
.filter(|(state, _)| *state == q.state)
|
||||
else {
|
||||
return Err(Refusal::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
"the sign-in expired or didn't start here: try again",
|
||||
));
|
||||
}
|
||||
};
|
||||
let inner = app.0.clone();
|
||||
let (login, id) = tokio::task::spawn_blocking(move || {
|
||||
inner
|
||||
@@ -250,7 +304,7 @@ async fn callback(
|
||||
&app.0.config.session_key,
|
||||
&format!("{login}\n{id}\n{}", now() + SESSION),
|
||||
);
|
||||
let back = format!("{}/mods/submit", app.0.config.public_url);
|
||||
let back = format!("{}{back}", app.0.config.public_url);
|
||||
let mut response = Redirect::to(&back).into_response();
|
||||
let headers = response.headers_mut();
|
||||
headers.append(
|
||||
@@ -283,6 +337,131 @@ async fn me(
|
||||
))
|
||||
}
|
||||
|
||||
fn database(e: rusqlite::Error) -> Refusal {
|
||||
eprintln!("horizon-mod-registry: ratings: {e}");
|
||||
Refusal::new(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"the ratings can't be read right now",
|
||||
)
|
||||
}
|
||||
|
||||
/// A mean as the pages show it: two decimals.
|
||||
fn rounded(average: f64) -> f64 {
|
||||
(average * 100.0).round() / 100.0
|
||||
}
|
||||
|
||||
/// `GET /api/mods/ratings`: `{"projects": {"<id>": {"average", "count"}}}` for
|
||||
/// every rated project. Totals only: never who rated.
|
||||
async fn totals(State(app): State<App>) -> Result<Response, Refusal> {
|
||||
let mut cached = app.0.totals.lock().unwrap();
|
||||
let body = match cached.as_ref().filter(|(at, _)| at.elapsed() < TOTALS_FOR) {
|
||||
Some((_, body)) => body.clone(),
|
||||
None => {
|
||||
let all = app
|
||||
.0
|
||||
.ratings
|
||||
.lock()
|
||||
.unwrap()
|
||||
.summaries()
|
||||
.map_err(database)?;
|
||||
let projects: serde_json::Map<String, serde_json::Value> = all
|
||||
.into_iter()
|
||||
.map(|(id, s)| (id, json!({"average": rounded(s.average), "count": s.count})))
|
||||
.collect();
|
||||
let body = json!({ "projects": projects }).to_string();
|
||||
*cached = Some((Instant::now(), body.clone()));
|
||||
body
|
||||
}
|
||||
};
|
||||
Ok((
|
||||
[
|
||||
(header::CONTENT_TYPE, "application/json"),
|
||||
(header::CACHE_CONTROL, "public, max-age=60"),
|
||||
],
|
||||
body,
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
|
||||
/// `GET /api/mods/{id}/rating`: the signed-in account's own rating,
|
||||
/// `{"stars": 1..5}` or `{"stars": null}`.
|
||||
async fn my_rating(
|
||||
State(app): State<App>,
|
||||
headers: HeaderMap,
|
||||
UrlPath(id): UrlPath<String>,
|
||||
) -> Result<Json<serde_json::Value>, Refusal> {
|
||||
let (_, account) = session(&app.0, &headers)
|
||||
.ok_or_else(|| Refusal::new(StatusCode::UNAUTHORIZED, "not signed in"))?;
|
||||
let stars = app
|
||||
.0
|
||||
.ratings
|
||||
.lock()
|
||||
.unwrap()
|
||||
.mine(&id, account)
|
||||
.map_err(database)?;
|
||||
Ok(Json(json!({ "stars": stars })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Rating {
|
||||
stars: u8,
|
||||
}
|
||||
|
||||
/// `POST /api/mods/{id}/rating` with `{"stars": 1..5}`: sets or changes the
|
||||
/// signed-in account's rating of a published project, not its own. Answers
|
||||
/// the project's new totals and `stars`.
|
||||
async fn rate(
|
||||
State(app): State<App>,
|
||||
headers: HeaderMap,
|
||||
UrlPath(id): UrlPath<String>,
|
||||
Json(rating): Json<Rating>,
|
||||
) -> Result<Json<serde_json::Value>, Refusal> {
|
||||
let inner = app.0.clone();
|
||||
let (login, account) = signed_in_here(&inner, &headers)?;
|
||||
if !(1..=5).contains(&rating.stars) {
|
||||
return Err(bad("a rating is 1 to 5 stars"));
|
||||
}
|
||||
if !index::valid_id(&id) {
|
||||
return Err(Refusal::new(StatusCode::NOT_FOUND, "no such project"));
|
||||
}
|
||||
if !allow(&inner.rated, &login, RATINGS_PER_ACCOUNT, RATINGS_PER_HOUR) {
|
||||
return Err(Refusal::new(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"too many ratings this hour: try again later",
|
||||
));
|
||||
}
|
||||
let lookup = inner.clone();
|
||||
let wanted = id.clone();
|
||||
let entry = tokio::task::spawn_blocking(move || lookup.config.github.entry(&wanted))
|
||||
.await
|
||||
.map_err(|_| Refusal::new(StatusCode::INTERNAL_SERVER_ERROR, "the check crashed"))?
|
||||
.map_err(github_down)?;
|
||||
let Some((entry, _)) = entry else {
|
||||
return Err(Refusal::new(
|
||||
StatusCode::NOT_FOUND,
|
||||
format!("{id} isn't published in the registry"),
|
||||
));
|
||||
};
|
||||
if entry.owners.iter().any(|o| o.eq_ignore_ascii_case(&login)) {
|
||||
return Err(Refusal::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
"you publish this project: its players rate it",
|
||||
));
|
||||
}
|
||||
let summary = {
|
||||
let ratings = inner.ratings.lock().unwrap();
|
||||
ratings
|
||||
.rate(&id, account, rating.stars, now())
|
||||
.map_err(database)?;
|
||||
ratings.summary(&id).map_err(database)?
|
||||
};
|
||||
*inner.totals.lock().unwrap() = None;
|
||||
let (average, count) = summary.map_or((0.0, 0), |s| (rounded(s.average), s.count));
|
||||
Ok(Json(
|
||||
json!({"stars": rating.stars, "average": average, "count": count}),
|
||||
))
|
||||
}
|
||||
|
||||
/// The page a submission fills in: a project's fields, and the version's.
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -322,45 +501,56 @@ fn take(window: &mut VecDeque<Instant>, max: usize) -> bool {
|
||||
window.len() < max
|
||||
}
|
||||
|
||||
/// A change sent by the site's own pages: from its origin, signed in, with
|
||||
/// the session's CSRF token. The account: (login, id).
|
||||
fn signed_in_here(app: &Inner, headers: &HeaderMap) -> Result<(String, u64), Refusal> {
|
||||
let origin = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok());
|
||||
if origin != Some(app.config.public_url.as_str()) {
|
||||
return Err(Refusal::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
"send it from the registry's pages",
|
||||
));
|
||||
}
|
||||
let account = session(app, headers)
|
||||
.ok_or_else(|| Refusal::new(StatusCode::UNAUTHORIZED, "sign in with GitHub first"))?;
|
||||
let sent = headers.get("x-csrf-token").and_then(|v| v.to_str().ok());
|
||||
if sent.is_none() || sent.map(str::to_owned) != csrf(app, headers) {
|
||||
return Err(Refusal::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
"reload the page and try again",
|
||||
));
|
||||
}
|
||||
Ok(account)
|
||||
}
|
||||
|
||||
/// Counts one more for `login` and for everyone, unless either is at its
|
||||
/// hourly limit.
|
||||
fn allow(windows: &Windows, login: &str, per_account: usize, per_hour: usize) -> bool {
|
||||
let mut windows = windows.lock().unwrap();
|
||||
let account = login.to_lowercase();
|
||||
let ok = take(windows.entry(String::new()).or_default(), per_hour)
|
||||
&& take(windows.entry(account.clone()).or_default(), per_account);
|
||||
if ok {
|
||||
let at = Instant::now();
|
||||
windows.entry(String::new()).or_default().push_back(at);
|
||||
windows.entry(account).or_default().push_back(at);
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
async fn submit(
|
||||
State(app): State<App>,
|
||||
headers: HeaderMap,
|
||||
mut multipart: Multipart,
|
||||
) -> Result<Json<serde_json::Value>, Refusal> {
|
||||
let inner = app.0.clone();
|
||||
let origin = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok());
|
||||
if origin != Some(inner.config.public_url.as_str()) {
|
||||
let (login, user_id) = signed_in_here(&inner, &headers)?;
|
||||
if !allow(&inner.recent, &login, PER_ACCOUNT, PER_HOUR) {
|
||||
return Err(Refusal::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
"submit from the registry's form",
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"too many submissions this hour: try again later",
|
||||
));
|
||||
}
|
||||
let (login, user_id) = session(&inner, &headers)
|
||||
.ok_or_else(|| Refusal::new(StatusCode::UNAUTHORIZED, "sign in with GitHub first"))?;
|
||||
let sent = headers.get("x-csrf-token").and_then(|v| v.to_str().ok());
|
||||
if sent.is_none() || sent.map(str::to_owned) != csrf(&inner, &headers) {
|
||||
return Err(Refusal::new(
|
||||
StatusCode::FORBIDDEN,
|
||||
"reload the form and try again",
|
||||
));
|
||||
}
|
||||
{
|
||||
let mut recent = inner.recent.lock().unwrap();
|
||||
let ok = take(recent.entry(String::new()).or_default(), PER_HOUR)
|
||||
&& take(recent.entry(login.to_lowercase()).or_default(), PER_ACCOUNT);
|
||||
if !ok {
|
||||
return Err(Refusal::new(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"too many submissions this hour: try again later",
|
||||
));
|
||||
}
|
||||
let at = Instant::now();
|
||||
recent.entry(String::new()).or_default().push_back(at);
|
||||
recent
|
||||
.entry(login.to_lowercase())
|
||||
.or_default()
|
||||
.push_back(at);
|
||||
}
|
||||
let dir = inner.config.scratch.join(random_hex());
|
||||
std::fs::create_dir_all(&dir)
|
||||
.map_err(|e| Refusal::new(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! `horizon-mod-registry`: serves on `PORT` (default 8080). Configured by the
|
||||
//! environment (see `Config::from_env`); keeps no data.
|
||||
//! environment (see `Config::from_env`); keeps the ratings in `REGISTRY_DB`.
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use horizon_mod_registry::{App, Config, router};
|
||||
@@ -16,7 +16,8 @@ async fn main() {
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("port {port}: {e}"));
|
||||
eprintln!("horizon-mod-registry: listening on {port}, submitting to {repo}");
|
||||
axum::serve(listener, router(App::new(config)))
|
||||
let app = App::new(config).unwrap_or_else(|e| panic!("horizon-mod-registry: {e}"));
|
||||
axum::serve(listener, router(app))
|
||||
.with_graceful_shutdown(async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
})
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
//! Players' ratings of published projects, 1 to 5 stars: one per GitHub
|
||||
//! account and project, which its rater can change. Stored in one SQLite
|
||||
//! file (a Railway volume). Only totals leave it: never who rated what,
|
||||
//! except a signed-in account's own rating, to that account.
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
|
||||
const SCHEMA: &str = "
|
||||
PRAGMA journal_mode = WAL;
|
||||
PRAGMA synchronous = NORMAL;
|
||||
CREATE TABLE IF NOT EXISTS ratings (
|
||||
project TEXT NOT NULL,
|
||||
account INTEGER NOT NULL,
|
||||
stars INTEGER NOT NULL CHECK (stars BETWEEN 1 AND 5),
|
||||
updated INTEGER NOT NULL,
|
||||
PRIMARY KEY (project, account)
|
||||
) WITHOUT ROWID;
|
||||
";
|
||||
|
||||
/// A project's ratings: their mean, and how many.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Summary {
|
||||
pub average: f64,
|
||||
pub count: u64,
|
||||
}
|
||||
|
||||
pub struct Ratings {
|
||||
db: Connection,
|
||||
}
|
||||
|
||||
impl Ratings {
|
||||
/// Opens (or creates) the file at `path`; `:memory:` for a test.
|
||||
pub fn open(path: &Path) -> rusqlite::Result<Ratings> {
|
||||
let db = Connection::open(path)?;
|
||||
db.execute_batch(SCHEMA)?;
|
||||
Ok(Ratings { db })
|
||||
}
|
||||
|
||||
/// Sets `account`'s rating of `project`, replacing an earlier one.
|
||||
pub fn rate(&self, project: &str, account: u64, stars: u8, now: u64) -> rusqlite::Result<()> {
|
||||
self.db.execute(
|
||||
"INSERT INTO ratings (project, account, stars, updated) VALUES (?1, ?2, ?3, ?4)
|
||||
ON CONFLICT (project, account) DO UPDATE SET stars = excluded.stars, updated = excluded.updated",
|
||||
params![project, account as i64, stars, now as i64],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `account`'s own rating of `project`.
|
||||
pub fn mine(&self, project: &str, account: u64) -> rusqlite::Result<Option<u8>> {
|
||||
self.db
|
||||
.query_row(
|
||||
"SELECT stars FROM ratings WHERE project = ?1 AND account = ?2",
|
||||
params![project, account as i64],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()
|
||||
}
|
||||
|
||||
/// `project`'s summary; None when nobody rated it.
|
||||
pub fn summary(&self, project: &str) -> rusqlite::Result<Option<Summary>> {
|
||||
self.db
|
||||
.query_row(
|
||||
"SELECT avg(stars), count(*) FROM ratings WHERE project = ?1 HAVING count(*) > 0",
|
||||
[project],
|
||||
|r| {
|
||||
Ok(Summary {
|
||||
average: r.get(0)?,
|
||||
count: r.get::<_, i64>(1)? as u64,
|
||||
})
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
}
|
||||
|
||||
/// Every rated project's summary.
|
||||
pub fn summaries(&self) -> rusqlite::Result<BTreeMap<String, Summary>> {
|
||||
let mut statement = self
|
||||
.db
|
||||
.prepare("SELECT project, avg(stars), count(*) FROM ratings GROUP BY project")?;
|
||||
let rows = statement.query_map([], |r| {
|
||||
Ok((
|
||||
r.get::<_, String>(0)?,
|
||||
Summary {
|
||||
average: r.get(1)?,
|
||||
count: r.get::<_, i64>(2)? as u64,
|
||||
},
|
||||
))
|
||||
})?;
|
||||
rows.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn one_rating_per_account_and_project() {
|
||||
let r = Ratings::open(Path::new(":memory:")).unwrap();
|
||||
r.rate("zoom", 1, 5, 10).unwrap();
|
||||
r.rate("zoom", 2, 2, 10).unwrap();
|
||||
r.rate("zoom", 1, 4, 11).unwrap();
|
||||
r.rate("minimap", 1, 3, 11).unwrap();
|
||||
assert_eq!(r.mine("zoom", 1).unwrap(), Some(4));
|
||||
assert_eq!(r.mine("zoom", 3).unwrap(), None);
|
||||
let all = r.summaries().unwrap();
|
||||
assert_eq!(
|
||||
all["zoom"],
|
||||
Summary {
|
||||
average: 3.0,
|
||||
count: 2
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
all["minimap"],
|
||||
Summary {
|
||||
average: 3.0,
|
||||
count: 1
|
||||
}
|
||||
);
|
||||
assert_eq!(r.summary("zoom").unwrap(), Some(all["zoom"]));
|
||||
assert_eq!(r.summary("nothing").unwrap(), None);
|
||||
assert!(
|
||||
r.rate("zoom", 1, 6, 12).is_err(),
|
||||
"the table checks the range too"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The whole submission against a mock GitHub: sign in, submit the sample
|
||||
//! signed mod (`crates/horizon-mods/tests/index`), and what lands on GitHub;
|
||||
//! then what is refused.
|
||||
//! then what is refused. Then ratings: who may rate what, and what is shown.
|
||||
use axum::{
|
||||
Json, Router,
|
||||
body::{Body, Bytes},
|
||||
@@ -55,7 +55,9 @@ async fn mock_github() -> (String, Shared) {
|
||||
.route(
|
||||
"/user",
|
||||
get(|State(s): State<Shared>| async move {
|
||||
Json(json!({"login": s.lock().unwrap().login, "id": 7}))
|
||||
let login = s.lock().unwrap().login.clone();
|
||||
let id = if login == "alice" { 7 } else { 8 };
|
||||
Json(json!({"login": login, "id": id}))
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
@@ -174,7 +176,16 @@ impl Client {
|
||||
}
|
||||
|
||||
async fn sign_in(&mut self) -> String {
|
||||
let (status, _, location) = self.send(self.get("/api/mods/auth/login")).await;
|
||||
self.sign_in_from("").await
|
||||
}
|
||||
|
||||
/// Signs in from the page `back` (`?back=` of the sign-in; "" for none).
|
||||
async fn sign_in_from(&mut self, back: &str) -> String {
|
||||
let login = match back {
|
||||
"" => "/api/mods/auth/login".to_owned(),
|
||||
back => format!("/api/mods/auth/login?back={back}"),
|
||||
};
|
||||
let (status, _, location) = self.send(self.get(&login)).await;
|
||||
assert_eq!(status, StatusCode::SEE_OTHER);
|
||||
let location = location.unwrap();
|
||||
assert!(location.contains(
|
||||
@@ -197,10 +208,11 @@ impl Client {
|
||||
.send(self.get(&format!("/api/mods/auth/callback?code=good&state={state}")))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::SEE_OTHER);
|
||||
assert_eq!(
|
||||
location.as_deref(),
|
||||
Some("https://playhorizon.test/mods/submit")
|
||||
);
|
||||
let page = match back {
|
||||
"/mods" | "/mods/zoom" => back,
|
||||
_ => "/mods/submit",
|
||||
};
|
||||
assert_eq!(location, Some(format!("https://playhorizon.test{page}")));
|
||||
let (status, me, _) = self.send(self.get("/api/mods/me")).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
me["csrf"].as_str().unwrap().to_owned()
|
||||
@@ -265,9 +277,10 @@ async fn setup() -> (Client, Shared) {
|
||||
"bot".into(),
|
||||
),
|
||||
scratch,
|
||||
database: ":memory:".into(),
|
||||
};
|
||||
let client = Client {
|
||||
app: router(App::new(config)),
|
||||
app: router(App::new(config).unwrap()),
|
||||
cookies: HashMap::new(),
|
||||
};
|
||||
(client, mock)
|
||||
@@ -376,3 +389,95 @@ async fn what_the_form_refuses() {
|
||||
"nothing reached GitHub"
|
||||
);
|
||||
}
|
||||
|
||||
const ENTRY: &str = "kind = \"mod\"\nname = \"N\"\nsummary = \"s\"\nlicense = \"MIT\"\nsource = \"https://x.test\"\n\n[[versions]]\nversion = \"1.0.0\"\npublished = \"2026-01-01\"\ngame = \"26.3\"\nfile = \"f.hmod\"\nsha256 = \"0000000000000000000000000000000000000000000000000000000000000000\"\n";
|
||||
|
||||
impl Client {
|
||||
async fn rate(&mut self, csrf: &str, id: &str, body: &str) -> (StatusCode, Value) {
|
||||
let request = Request::post(format!("/api/mods/{id}/rating"))
|
||||
.header(header::COOKIE, self.cookie_header())
|
||||
.header(header::ORIGIN, PUBLIC)
|
||||
.header("x-csrf-token", csrf)
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(body.to_owned()))
|
||||
.unwrap();
|
||||
let (status, json, _) = self.send(request).await;
|
||||
(status, json)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ratings() {
|
||||
let (mut client, mock) = setup().await;
|
||||
{
|
||||
let mut m = mock.lock().unwrap();
|
||||
m.main.insert(
|
||||
"mods/zoom.toml".into(),
|
||||
format!("id = \"zoom\"\nowners = [\"bob\"]\n{ENTRY}"),
|
||||
);
|
||||
m.main.insert(
|
||||
"mods/mine.toml".into(),
|
||||
format!("id = \"mine\"\nowners = [\"Alice\"]\n{ENTRY}"),
|
||||
);
|
||||
}
|
||||
// Nothing rated yet; signed out, no own rating and no rating at all.
|
||||
let (status, json, _) = client.send(client.get("/api/mods/ratings")).await;
|
||||
assert_eq!((status, json), (StatusCode::OK, json!({"projects": {}})));
|
||||
let (status, ..) = client.send(client.get("/api/mods/zoom/rating")).await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||
let (status, _) = client.rate("x", "zoom", r#"{"stars": 4}"#).await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||
|
||||
// A sign-in from a project's page comes back to it; anywhere else is the form.
|
||||
client.sign_in_from("https://evil.test/").await;
|
||||
let csrf = client.sign_in_from("/mods/zoom").await;
|
||||
let (status, json) = client.rate("wrong", "zoom", r#"{"stars": 4}"#).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN, "{json}");
|
||||
for stars in ["0", "6"] {
|
||||
let (status, json) = client
|
||||
.rate(&csrf, "zoom", &format!(r#"{{"stars": {stars}}}"#))
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{json}");
|
||||
}
|
||||
let (status, json) = client.rate(&csrf, "zoom", r#"{"stars": 4}"#).await;
|
||||
assert_eq!(status, StatusCode::OK, "{json}");
|
||||
assert_eq!(json, json!({"stars": 4, "average": 4.0, "count": 1}));
|
||||
// Changing it replaces it.
|
||||
let (status, json) = client.rate(&csrf, "zoom", r#"{"stars": 2}"#).await;
|
||||
assert_eq!(status, StatusCode::OK, "{json}");
|
||||
assert_eq!(json["count"], 1);
|
||||
let (_, json, _) = client.send(client.get("/api/mods/zoom/rating")).await;
|
||||
assert_eq!(json, json!({"stars": 2}));
|
||||
let (_, json, _) = client.send(client.get("/api/mods/minimap/rating")).await;
|
||||
assert_eq!(json, json!({"stars": null}));
|
||||
|
||||
// Not one's own project, nor one that isn't published.
|
||||
let (status, json) = client.rate(&csrf, "mine", r#"{"stars": 5}"#).await;
|
||||
assert_eq!(status, StatusCode::FORBIDDEN, "{json}");
|
||||
let (status, json) = client.rate(&csrf, "nothing", r#"{"stars": 5}"#).await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND, "{json}");
|
||||
|
||||
// Another account's rating counts once more; the totals never say whose.
|
||||
let mut other = Client {
|
||||
app: client.app.clone(),
|
||||
cookies: HashMap::new(),
|
||||
};
|
||||
mock.lock().unwrap().login = "carol".into();
|
||||
let carol = other.sign_in().await;
|
||||
let (status, json) = other.rate(&carol, "zoom", r#"{"stars": 5}"#).await;
|
||||
assert_eq!(status, StatusCode::OK, "{json}");
|
||||
assert_eq!(json, json!({"stars": 5, "average": 3.5, "count": 2}));
|
||||
let (status, json, _) = client.send(client.get("/api/mods/ratings")).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(
|
||||
json,
|
||||
json!({"projects": {"zoom": {"average": 3.5, "count": 2}}})
|
||||
);
|
||||
|
||||
// The limit per account and hour.
|
||||
let mut last = StatusCode::OK;
|
||||
for _ in 0..40 {
|
||||
(last, _) = client.rate(&csrf, "zoom", r#"{"stars": 3}"#).await;
|
||||
}
|
||||
assert_eq!(last, StatusCode::TOO_MANY_REQUESTS);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# /online lists the players and their dimension; /mined counts the acting player's blocks.
|
||||
|
||||
[[step]]
|
||||
join = "Alex"
|
||||
expect.commands = ["online", "mined"]
|
||||
|
||||
[[step]]
|
||||
join = "Steve"
|
||||
as = "Steve"
|
||||
player = { dimension = "minecraft:the_nether" }
|
||||
command = "online"
|
||||
expect.feedback = "Alex (overworld), Steve (the_nether)"
|
||||
|
||||
[[step]]
|
||||
as = "Alex"
|
||||
break = { x = 1, y = 63, z = 0, state = "minecraft:stone" }
|
||||
|
||||
[[step]]
|
||||
as = "Alex"
|
||||
break = { x = 2, y = 63, z = 0, state = "minecraft:dirt" }
|
||||
|
||||
# A step's command comes before its break and place.
|
||||
[[step]]
|
||||
as = "Alex"
|
||||
command = "mined"
|
||||
expect.feedback = "You broke 2 block(s)"
|
||||
|
||||
[[step]]
|
||||
as = "Steve"
|
||||
command = "mined"
|
||||
expect.feedback = "You broke 0 block(s)"
|
||||
@@ -0,0 +1,21 @@
|
||||
# Joins are greeted; a newcomer is announced once, even after a reload (storage).
|
||||
|
||||
[[step]]
|
||||
join = "Alex"
|
||||
expect.told = ["Alex: Welcome, Alex! 0 other player(s) online."]
|
||||
expect.broadcast = ["Alex is here for the first time"]
|
||||
|
||||
[[step]]
|
||||
join = "Steve"
|
||||
expect.told = ["Steve: Welcome, Steve! 1 other player(s) online."]
|
||||
expect.broadcast = ["Steve is here for the first time"]
|
||||
|
||||
[[step]]
|
||||
leave = "Alex"
|
||||
expect.told = []
|
||||
|
||||
[[step]]
|
||||
reload = true
|
||||
join = "Alex"
|
||||
expect.told = ["Alex: Welcome, Alex! 1 other player(s) online."]
|
||||
expect.broadcast = []
|
||||
@@ -18,7 +18,8 @@ interface log {
|
||||
write: func(level: level, message: string);
|
||||
}
|
||||
|
||||
/// Capability `game-read`: the local player and the world clock.
|
||||
/// Capability `game-read`: the local player, the world clock and the block
|
||||
/// the player looks at.
|
||||
interface game {
|
||||
record player {
|
||||
/// Feet position, in blocks.
|
||||
@@ -46,6 +47,24 @@ interface game {
|
||||
get-player: func() -> option<player>;
|
||||
/// None on the title screen.
|
||||
get-clock: func() -> option<clock>;
|
||||
/// A block along the player's view.
|
||||
record hit {
|
||||
/// The block hit.
|
||||
block-x: s32,
|
||||
block-y: s32,
|
||||
block-z: s32,
|
||||
/// The point on its face where the view meets it.
|
||||
x: f64,
|
||||
y: f64,
|
||||
z: f64,
|
||||
/// `minecraft:stone`, ...
|
||||
block: string,
|
||||
}
|
||||
/// The first block along the player's view (fluids pass), up to
|
||||
/// `distance` blocks (at most 1024; past the loaded chunks, across the
|
||||
/// distant terrain when LOD Distance is on), as of this tick. None when
|
||||
/// nothing is hit, and on the title screen.
|
||||
raycast: func(distance: f32) -> option<hit>;
|
||||
}
|
||||
|
||||
/// Capability `chat`: messages only the local player sees.
|
||||
|
||||
@@ -17,20 +17,27 @@ wasmtime = { version = "48.0.7", default-features = false, features = ["runtime"
|
||||
# Turns a mod's core module into a component (cargo horizon-mod build, the tests).
|
||||
wit-component = { version = "0.254", optional = true }
|
||||
wit-parser = { version = "0.254", optional = true }
|
||||
# The functions a mod imports, for its API level (src/api_level.rs): the game and the registry index.
|
||||
wasmparser = { version = "0.254", optional = true }
|
||||
# The registry index's checks (feature `index`): SHA-256, and minisign signatures (no dependencies of its own).
|
||||
sha2 = { version = "0.10", optional = true }
|
||||
minisign-verify = { version = "0.3", optional = true }
|
||||
# A shader pack's check (kind `shader`): the one the game runs before it loads a pack.
|
||||
horizon-shader-api = { path = "../horizon-shader-api", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# A component made for a newer Horizon, from the WIT alone (tests/sandbox.rs).
|
||||
wit-component = { version = "0.254", features = ["dummy-module"] }
|
||||
wit-parser = "0.254"
|
||||
|
||||
[features]
|
||||
# Loads and runs mods (the game's `mods` feature); without it only manifests,
|
||||
# content and packaging. Off by default so builds that don't run mods (the
|
||||
# game's tests and probes) skip wasmtime and cranelift.
|
||||
runtime = ["dep:wasmtime"]
|
||||
runtime = ["dep:wasmtime", "dep:wasmparser"]
|
||||
pack = ["dep:wit-component", "dep:wit-parser"]
|
||||
# The mod registry's index (docs/api/mod-index.md): the launcher, the registry server and its CI.
|
||||
index = ["dep:sha2", "dep:minisign-verify", "dep:horizon-shader-api"]
|
||||
index = ["dep:sha2", "dep:minisign-verify", "dep:horizon-shader-api", "dep:wasmparser"]
|
||||
|
||||
# Runs real mods: `cargo test -p horizon-mods --features runtime,pack`.
|
||||
[[test]]
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Mod API levels: which of the WIT contract's functions a Horizon has
|
||||
//! (`docs/api/stability.md`). Every function the game offers mods has the
|
||||
//! level it arrived at; a Horizon serves every level up to its [`LEVEL`].
|
||||
//! A mod needs the level of the newest function it imports, so a mod that
|
||||
//! calls a function this Horizon doesn't have is refused with "update
|
||||
//! Horizon" instead of a linking error, and the registry lists each
|
||||
//! version's level so the launcher can tell before it installs.
|
||||
|
||||
/// The newest level this Horizon serves.
|
||||
pub const LEVEL: u32 = 2;
|
||||
|
||||
/// Every function the game offers mods, as `interface.function`, with its
|
||||
/// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new
|
||||
/// function takes the next level and raises [`LEVEL`] (the `api_reference`
|
||||
/// test fails until it is listed here).
|
||||
pub const FUNCTIONS: [(&str, u32); 33] = [
|
||||
("log.write", 0),
|
||||
("game.get-player", 0),
|
||||
("game.get-clock", 0),
|
||||
("chat.show", 0),
|
||||
("hud.set-panel", 0),
|
||||
("hud.clear", 0),
|
||||
("storage.get", 0),
|
||||
("storage.set", 0),
|
||||
("storage.delete", 0),
|
||||
("command.run", 0),
|
||||
("ui.open-screen", 0),
|
||||
("ui.close-screen", 0),
|
||||
("ui.set-settings", 0),
|
||||
("input.claim-items", 0),
|
||||
("input.register-key", 0),
|
||||
("input.held", 0),
|
||||
("input.poll", 0),
|
||||
("input.claim-wheel", 0),
|
||||
("input.mapping", 0),
|
||||
("input.clicks-per-second", 0),
|
||||
("render.set-hud", 0),
|
||||
("render.gui-size", 0),
|
||||
("render.shake", 0),
|
||||
("render.set-corner", 0),
|
||||
("render.clear-corner", 0),
|
||||
("render.text-width", 0),
|
||||
("render.frame-stats", 0),
|
||||
("render.set-zoom", 0),
|
||||
("render.set-minimap", 1),
|
||||
("players.online", 1),
|
||||
("players.tell", 1),
|
||||
("players.broadcast", 1),
|
||||
("game.raycast", 2),
|
||||
];
|
||||
|
||||
/// What the game's program carries so the launcher can read its level
|
||||
/// without running it: `horizon-mod-api-level:0001;` (four digits). A
|
||||
/// program from before the mark serves level 0.
|
||||
pub const MARK: [u8; 27] = {
|
||||
let mut mark = *b"horizon-mod-api-level:0000;";
|
||||
let mut level = LEVEL;
|
||||
let mut i = 25;
|
||||
while level > 0 {
|
||||
mark[i] = b'0' + (level % 10) as u8;
|
||||
level /= 10;
|
||||
i -= 1;
|
||||
}
|
||||
mark
|
||||
};
|
||||
|
||||
/// The level a program's bytes carry in their [`MARK`], if any.
|
||||
pub fn read_mark(program: &[u8]) -> Option<u32> {
|
||||
let prefix = &MARK[..22];
|
||||
program
|
||||
.windows(MARK.len())
|
||||
.filter(|w| w.starts_with(prefix) && w[26] == b';')
|
||||
.find_map(|w| std::str::from_utf8(&w[22..26]).ok()?.parse().ok())
|
||||
}
|
||||
|
||||
/// A function's level; None for one this Horizon doesn't have.
|
||||
pub fn level_of(function: &str) -> Option<u32> {
|
||||
FUNCTIONS
|
||||
.iter()
|
||||
.find(|(name, _)| *name == function)
|
||||
.map(|&(_, level)| level)
|
||||
}
|
||||
|
||||
/// The level a mod needs, from the functions it imports (as [`imports`]
|
||||
/// names them): its newest function's. A function this Horizon doesn't
|
||||
/// know comes from a newer one, so it needs more than [`LEVEL`]; that
|
||||
/// function is returned with it, for the message.
|
||||
pub fn needed<'a>(imports: impl IntoIterator<Item = &'a str>) -> (u32, Option<&'a str>) {
|
||||
let mut needed = (0, None);
|
||||
for name in imports {
|
||||
match level_of(name) {
|
||||
Some(level) if level > needed.0 => needed = (level, Some(name)),
|
||||
Some(_) => {}
|
||||
None => return (LEVEL + 1, Some(name)),
|
||||
}
|
||||
}
|
||||
needed
|
||||
}
|
||||
|
||||
/// Why this Horizon can't run a mod that needs `level`, or None when it can.
|
||||
pub fn too_new(level: u32, function: Option<&str>) -> Option<String> {
|
||||
(level > LEVEL).then(|| {
|
||||
let uses = function.map_or(String::new(), |f| format!(" (it uses {f})"));
|
||||
format!("made for a newer Horizon{uses}: update Horizon to run it")
|
||||
})
|
||||
}
|
||||
|
||||
/// The functions a mod's component imports from Horizon (`horizon:mods/*`),
|
||||
/// as `interface.function`, in the component's order.
|
||||
#[cfg(any(feature = "runtime", feature = "index"))]
|
||||
pub fn imports(wasm: &[u8]) -> Result<Vec<String>, String> {
|
||||
use wasmparser::{
|
||||
Parser, Payload, Validator, WasmFeatures, component_types::ComponentEntityType,
|
||||
};
|
||||
let types = Validator::new_with_features(WasmFeatures::all())
|
||||
.validate_all(wasm)
|
||||
.map_err(|e| format!("not a component: {e}"))?;
|
||||
let types = types.as_ref();
|
||||
let mut out = Vec::new();
|
||||
for payload in Parser::new(0).parse_all(wasm) {
|
||||
let Payload::ComponentImportSection(section) = payload.map_err(|e| e.to_string())? else {
|
||||
continue;
|
||||
};
|
||||
for import in section {
|
||||
let name = import.map_err(|e| e.to_string())?.name.name;
|
||||
// `horizon:mods/render@0.1.0` → `render`.
|
||||
let Some(interface) = name.strip_prefix("horizon:mods/") else {
|
||||
continue;
|
||||
};
|
||||
let interface = interface.split('@').next().unwrap_or(interface);
|
||||
let Some(item) = types.component_item_for_import(name) else {
|
||||
continue;
|
||||
};
|
||||
if let ComponentEntityType::Instance(id) = item.ty {
|
||||
for (function, export) in &types[id].exports {
|
||||
if matches!(export.ty, ComponentEntityType::Func(_)) {
|
||||
out.push(format!("{interface}.{function}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn levels_are_listed_once_and_up_to_this_horizons() {
|
||||
for (i, (name, level)) in FUNCTIONS.iter().enumerate() {
|
||||
assert!(*level <= LEVEL, "{name}");
|
||||
assert!(
|
||||
FUNCTIONS[..i].iter().all(|(other, _)| other != name),
|
||||
"{name} twice"
|
||||
);
|
||||
}
|
||||
assert!(FUNCTIONS.iter().any(|&(_, level)| level == LEVEL));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mark_carries_the_level() {
|
||||
assert_eq!(read_mark(&MARK), Some(LEVEL));
|
||||
let mut program = b"\0\x7fELF horizon-mod-api-level: horizon-mod-api-level:".to_vec();
|
||||
program.extend_from_slice(&MARK);
|
||||
program.extend_from_slice(b"\0rest");
|
||||
assert_eq!(read_mark(&program), Some(LEVEL));
|
||||
assert_eq!(read_mark(b"horizon-mod-api-level:12;"), None);
|
||||
assert_eq!(read_mark(b"no mark"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mod_needs_its_newest_function() {
|
||||
assert_eq!(needed(["log.write", "hud.set-panel"]), (0, None));
|
||||
assert_eq!(
|
||||
needed(["log.write", "render.set-minimap", "hud.clear"]),
|
||||
(1, Some("render.set-minimap"))
|
||||
);
|
||||
assert_eq!(
|
||||
needed(["render.set-minimap", "render.set-sky"]),
|
||||
(LEVEL + 1, Some("render.set-sky"))
|
||||
);
|
||||
assert_eq!(too_new(LEVEL, None), None);
|
||||
assert_eq!(
|
||||
too_new(LEVEL + 1, Some("render.set-sky")).as_deref(),
|
||||
Some("made for a newer Horizon (it uses render.set-sky): update Horizon to run it")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -138,6 +138,11 @@ pub struct Version {
|
||||
pub side: Option<Side>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub capabilities: Vec<Capability>,
|
||||
/// The mod API level a mod's code needs ([`crate::api_level`]), read
|
||||
/// from its file; none for content and other kinds, and in indexes
|
||||
/// built before levels.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub api_level: Option<u32>,
|
||||
/// The Minecraft version it is for.
|
||||
pub game: String,
|
||||
/// A modpack's mods, as its manifest lists them.
|
||||
@@ -317,6 +322,21 @@ impl Index {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A project's newest version for Minecraft `game` that wasn't taken
|
||||
/// down and that a Horizon serving mod API `level` can run (an unknown
|
||||
/// level counts as runnable: the game still checks when it starts it).
|
||||
pub fn installable<'a>(
|
||||
&self,
|
||||
project: &'a Project,
|
||||
game: &str,
|
||||
level: u32,
|
||||
) -> Option<&'a Version> {
|
||||
project.versions.iter().find(|v| {
|
||||
v.game == game
|
||||
&& v.api_level.is_none_or(|l| l <= level)
|
||||
&& self.revoked(&project.id, &v.file.sha256).is_none()
|
||||
})
|
||||
}
|
||||
pub fn project(&self, id: &str) -> Option<&Project> {
|
||||
self.projects.iter().find(|p| p.id == id)
|
||||
}
|
||||
@@ -472,6 +492,8 @@ pub struct Facts {
|
||||
pub side: Option<Side>,
|
||||
/// In the manifest's order.
|
||||
pub capabilities: Vec<Capability>,
|
||||
/// The mod API level a mod's code needs, from the functions it imports.
|
||||
pub api_level: Option<u32>,
|
||||
/// The Minecraft version, when the file names one (a modpack does).
|
||||
pub game: Option<String>,
|
||||
pub requires: Vec<Requirement>,
|
||||
@@ -488,6 +510,7 @@ impl Facts {
|
||||
|| self.api != version.api
|
||||
|| self.side != version.side
|
||||
|| caps != listed
|
||||
|| version.api_level.is_some() && self.api_level != version.api_level
|
||||
|| self.game.as_ref().is_some_and(|g| *g != version.game)
|
||||
|| self.requires != version.requires;
|
||||
if !differs {
|
||||
@@ -522,9 +545,17 @@ impl Facts {
|
||||
pub fn inspect(kind: &Kind, path: &Path) -> Result<Facts, String> {
|
||||
match kind {
|
||||
Kind::Mod => {
|
||||
let m = Package::read(path)?.manifest;
|
||||
let Package { manifest: m, wasm } = Package::read(path)?;
|
||||
crate::Content::read(path, &m)?;
|
||||
let api_level = match wasm {
|
||||
Some(wasm) => {
|
||||
let functions = crate::api_level::imports(&wasm)?;
|
||||
Some(crate::api_level::needed(functions.iter().map(String::as_str)).0)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
Ok(Facts {
|
||||
api_level,
|
||||
capabilities: m.capabilities,
|
||||
id: Some(m.id),
|
||||
version: Some(m.version),
|
||||
|
||||
@@ -283,6 +283,7 @@ fn version(entry: &Entry, v: &EntryVersion, src: &Sources) -> Result<Version, St
|
||||
api: facts.api,
|
||||
side: facts.side,
|
||||
capabilities: facts.capabilities,
|
||||
api_level: facts.api_level,
|
||||
game: v.game.clone(),
|
||||
requires: facts.requires,
|
||||
file: File {
|
||||
|
||||
@@ -76,6 +76,15 @@ fn a_changed_file_key_or_manifest_is_refused() {
|
||||
let e = check(&more_caps, "coords_hud", &hmod).unwrap_err();
|
||||
assert!(e.contains("isn't what the index lists"), "{e}");
|
||||
|
||||
let mut other_level = index.clone();
|
||||
other_level.projects[0].versions[0].api_level = Some(1);
|
||||
let e = check(&other_level, "coords_hud", &hmod).unwrap_err();
|
||||
assert!(e.contains("isn't what the index lists"), "{e}");
|
||||
// An index built before levels lists none: the file still passes.
|
||||
let mut no_level = index.clone();
|
||||
no_level.projects[0].versions[0].api_level = None;
|
||||
assert_eq!(check(&no_level, "coords_hud", &hmod), Ok(Trust::Verified));
|
||||
|
||||
let mut revoked = index.clone();
|
||||
revoked.revoked.push(Revoked {
|
||||
id: "coords_hud".into(),
|
||||
@@ -167,6 +176,30 @@ fn resource_packs_need_a_pack_mcmeta() {
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newest_version_this_horizon_runs_is_installed() {
|
||||
let mut index = sample();
|
||||
let mut newer = index.projects[0].versions[0].clone();
|
||||
newer.version = "0.2.0".into();
|
||||
newer.file.sha256 = "2".repeat(64);
|
||||
newer.api_level = Some(crate::api_level::LEVEL + 1);
|
||||
index.projects[0].versions.insert(0, newer);
|
||||
let p = index.project("coords_hud").unwrap();
|
||||
let pick = |level| {
|
||||
index
|
||||
.installable(p, "26.3", level)
|
||||
.map(|v| v.version.as_str())
|
||||
};
|
||||
assert_eq!(pick(crate::api_level::LEVEL), Some("0.1.0"));
|
||||
assert_eq!(pick(crate::api_level::LEVEL + 1), Some("0.2.0"));
|
||||
assert_eq!(index.installable(p, "26.4", crate::api_level::LEVEL), None);
|
||||
// No level listed: runnable as far as the index knows.
|
||||
index.projects[0].versions[0].api_level = None;
|
||||
let p = index.project("coords_hud").unwrap();
|
||||
let v = index.installable(p, "26.3", 0).unwrap();
|
||||
assert_eq!(v.version, "0.2.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shader_packs_pass_the_game_s_own_check() {
|
||||
let manifest = "schema = 1\nid = \"glow\"\nname = \"Glow\"\nversion = \"1.0.0\"\napi = \"0.1\"\n\
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
//!
|
||||
//! Nothing here runs unless a mod is installed and turned on: an empty
|
||||
//! [`Mods`] makes no engine and every hook returns at once.
|
||||
pub mod api_level;
|
||||
pub mod content;
|
||||
#[cfg(feature = "index")]
|
||||
pub mod index;
|
||||
|
||||
@@ -41,7 +41,7 @@ mod ui_bindings {
|
||||
});
|
||||
}
|
||||
pub use bindings::horizon::mods::{
|
||||
game::{Clock, Player},
|
||||
game::{Clock, Hit, Player},
|
||||
hud::{Corner, Line},
|
||||
};
|
||||
use bindings::{
|
||||
@@ -89,6 +89,8 @@ const FUEL_FRAME: u64 = 10_000_000;
|
||||
const FUEL_EVENT: u64 = 100_000_000;
|
||||
/// Chat lines a mod may show per call, HUD lines and their length.
|
||||
const CHAT_PER_CALL: usize = 8;
|
||||
/// How far `game.raycast` sees, in blocks.
|
||||
pub const RAYCAST_MAX: f32 = 1024.0;
|
||||
const HUD_LINES: usize = 16;
|
||||
const LINE_CHARS: usize = 256;
|
||||
/// Total bytes a mod's `storage` may hold on disk, across all its keys.
|
||||
@@ -124,6 +126,10 @@ pub struct Snapshot {
|
||||
pub font_widths: Arc<[f32]>,
|
||||
/// The players on the server, for server mods.
|
||||
pub players: Vec<ServerPlayer>,
|
||||
/// The first block along the player's view within [`RAYCAST_MAX`] and
|
||||
/// its distance from the eye, for `game.raycast`; the game works it out
|
||||
/// only while a mod calls it ([`Mods::wants_raycast`]).
|
||||
pub view_hit: Option<(f32, Hit)>,
|
||||
}
|
||||
|
||||
/// Which mods a game starts: the window's game the client mods, the game
|
||||
@@ -227,6 +233,8 @@ struct Running {
|
||||
/// server mod.
|
||||
ui: Option<UiHost>,
|
||||
hooks: Hooks,
|
||||
/// It imports `game.raycast`.
|
||||
raycasts: bool,
|
||||
}
|
||||
|
||||
/// A running mod's exports and the hooks its `init` asked for.
|
||||
@@ -424,6 +432,12 @@ impl Mods {
|
||||
.map(|(name, _)| name.to_string())
|
||||
.collect();
|
||||
m.check_imports(imports.iter().map(String::as_str))?;
|
||||
// A function this Horizon doesn't have: say so, not wasmtime's linking error.
|
||||
let functions = crate::api_level::imports(wasm)?;
|
||||
let (level, function) = crate::api_level::needed(functions.iter().map(String::as_str));
|
||||
if let Some(why) = crate::api_level::too_new(level, function) {
|
||||
return Err(why);
|
||||
}
|
||||
let data_dir = path
|
||||
.parent()
|
||||
.unwrap_or(Path::new("."))
|
||||
@@ -484,7 +498,12 @@ impl Mods {
|
||||
free
|
||||
});
|
||||
self.out.append(&mut store.data_mut().out);
|
||||
Ok(Some(Running { store, ui, hooks }))
|
||||
Ok(Some(Running {
|
||||
store,
|
||||
ui,
|
||||
hooks,
|
||||
raycasts: functions.iter().any(|f| f == "game.raycast"),
|
||||
}))
|
||||
}
|
||||
|
||||
/// True when at least one mod runs: the game skips its mod work otherwise.
|
||||
@@ -737,6 +756,13 @@ impl Mods {
|
||||
.iter()
|
||||
.filter_map(|e| e.run.as_ref()?.store.data().corner.as_ref())
|
||||
}
|
||||
/// Some running mod calls `game.raycast`: the snapshot needs a
|
||||
/// [`Snapshot::view_hit`].
|
||||
pub fn wants_raycast(&self) -> bool {
|
||||
self.entries
|
||||
.iter()
|
||||
.any(|e| e.run.as_ref().is_some_and(|r| r.raycasts))
|
||||
}
|
||||
/// Some running mod has a `frame` hook: the game refreshes the snapshot
|
||||
/// every frame for it.
|
||||
pub fn wants_frames(&self) -> bool {
|
||||
@@ -1087,6 +1113,11 @@ impl game::Host for State {
|
||||
fn get_clock(&mut self) -> Option<Clock> {
|
||||
self.snapshot.clock
|
||||
}
|
||||
fn raycast(&mut self, distance: f32) -> Option<Hit> {
|
||||
let (at, hit) = self.snapshot.view_hit.as_ref()?;
|
||||
// NaN compares false: no hit.
|
||||
(*at <= distance.min(RAYCAST_MAX) && !distance.is_nan()).then(|| hit.clone())
|
||||
}
|
||||
}
|
||||
impl State {
|
||||
/// Queues a chat line unless the call already sent [`CHAT_PER_CALL`].
|
||||
|
||||
@@ -2,10 +2,14 @@
|
||||
//!
|
||||
//! [`TestGame`] loads one `.hmod` from a scratch copy (its `storage` lives and
|
||||
//! dies with the run) into the same sandbox the game uses, and plays the game's
|
||||
//! part: the snapshot, ticks, frames, chat lines and commands. [`Script`] is a
|
||||
//! part: the snapshot, ticks, frames, chat lines and commands, and for a
|
||||
//! server mod the players joining, leaving, chatting and breaking or placing
|
||||
//! blocks. [`Script`] is a
|
||||
//! test written in TOML, `tests/<name>.toml` in the mod's folder: steps, each
|
||||
//! saying what happens and what the mod must have shown by then.
|
||||
use crate::{Clock, Corner, Mods, Output, Panel, Player, Snapshot, Status};
|
||||
use crate::{
|
||||
BlockPos, Clock, Corner, GameMode, Mods, Output, Panel, Player, ServerPlayer, Snapshot, Status,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
@@ -20,6 +24,10 @@ pub struct TestGame {
|
||||
/// What the mod reads with `game-read`; ticks move the clock as the game does.
|
||||
pub player: Option<Player>,
|
||||
pub clock: Option<Clock>,
|
||||
/// The players on the server, for a server mod, in join order.
|
||||
pub players: Vec<ServerPlayer>,
|
||||
/// Every name that joined, for their id.
|
||||
names: Vec<String>,
|
||||
tick: u64,
|
||||
}
|
||||
|
||||
@@ -60,6 +68,8 @@ impl TestGame {
|
||||
game_time: 0,
|
||||
day_time: 0,
|
||||
}),
|
||||
players: Vec::new(),
|
||||
names: Vec::new(),
|
||||
tick: 0,
|
||||
};
|
||||
copy_mod(hmod, ©)?;
|
||||
@@ -87,11 +97,16 @@ impl TestGame {
|
||||
self.mods.set_snapshot(Snapshot {
|
||||
player: self.player.clone(),
|
||||
clock: self.clock,
|
||||
players: self.players.clone(),
|
||||
// The GUI of a 1280 x 720 window at scale 3, as the trial run's.
|
||||
gui_size: (427.0, 240.0),
|
||||
..Snapshot::default()
|
||||
});
|
||||
}
|
||||
/// Whether the mod is a server mod.
|
||||
pub fn server(&self) -> bool {
|
||||
self.mods.runs_server()
|
||||
}
|
||||
|
||||
/// `n` game ticks; each moves the clock one tick on, as the game does.
|
||||
pub fn tick(&mut self, n: u64) {
|
||||
@@ -103,6 +118,7 @@ impl TestGame {
|
||||
}
|
||||
self.snapshot();
|
||||
self.mods.tick(self.tick);
|
||||
self.mods.server_tick(self.tick);
|
||||
}
|
||||
}
|
||||
/// `n` frames, 1/60 s apart.
|
||||
@@ -124,13 +140,76 @@ impl TestGame {
|
||||
self.mods.command(line)
|
||||
}
|
||||
|
||||
/// A player named `name` joins the server, standing where a script starts
|
||||
/// in survival. Their id is `00000000-0000-4000-8000-000000000001` for
|
||||
/// the first name that joined, `...0002` for the second, and so on.
|
||||
pub fn join(&mut self, name: &str) -> ServerPlayer {
|
||||
let n = match self.names.iter().position(|n| n == name) {
|
||||
Some(i) => i + 1,
|
||||
None => {
|
||||
self.names.push(name.to_owned());
|
||||
self.names.len()
|
||||
}
|
||||
};
|
||||
let p = default_player();
|
||||
let player = ServerPlayer {
|
||||
id: format!("00000000-0000-4000-8000-{n:012x}"),
|
||||
name: name.to_owned(),
|
||||
x: p.x,
|
||||
y: p.y,
|
||||
z: p.z,
|
||||
dimension: p.dimension,
|
||||
game_mode: GameMode::Survival,
|
||||
health: p.health,
|
||||
};
|
||||
self.players.push(player.clone());
|
||||
self.snapshot();
|
||||
self.mods.player_joined(&player);
|
||||
player
|
||||
}
|
||||
/// The player named `name` leaves; false when no such player is on.
|
||||
pub fn leave(&mut self, name: &str) -> bool {
|
||||
let Some(i) = self.players.iter().position(|p| p.name == name) else {
|
||||
return false;
|
||||
};
|
||||
let player = self.players.remove(i);
|
||||
self.snapshot();
|
||||
self.mods.player_left(&player);
|
||||
true
|
||||
}
|
||||
/// A chat message `player` sends, for a server mod.
|
||||
pub fn player_chat(&mut self, player: &ServerPlayer, line: &str) {
|
||||
self.snapshot();
|
||||
self.mods.player_chat(player, line);
|
||||
}
|
||||
/// `/line` typed by `player`, for a server mod; false when the mod owns
|
||||
/// no such command.
|
||||
pub fn player_command(&mut self, player: &ServerPlayer, line: &str) -> bool {
|
||||
self.snapshot();
|
||||
self.mods.server_command(player, line)
|
||||
}
|
||||
/// `player` breaks (or places) `state` at `pos`.
|
||||
pub fn block(&mut self, player: &ServerPlayer, pos: BlockPos, state: &str, placed: bool) {
|
||||
self.snapshot();
|
||||
if placed {
|
||||
self.mods.block_placed(player, pos, state);
|
||||
} else {
|
||||
self.mods.block_broken(player, pos, state);
|
||||
}
|
||||
}
|
||||
|
||||
/// The scratch copy the mod runs from; its `storage` is beside it.
|
||||
pub fn hmod(&self) -> &Path {
|
||||
&self.hmod
|
||||
}
|
||||
/// The commands the mod registered.
|
||||
pub fn commands(&self) -> Vec<String> {
|
||||
self.mods.commands().map(str::to_owned).collect()
|
||||
let server = self.mods.server_commands();
|
||||
self.mods
|
||||
.commands()
|
||||
.chain(server)
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
}
|
||||
pub fn panel(&self) -> Option<&Panel> {
|
||||
self.mods.panels().next()
|
||||
@@ -166,7 +245,7 @@ fn copy_mod(from: &Path, to: &Path) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A test in TOML: where the player starts, then steps run in order.
|
||||
/// A test in TOML: where a client mod's player starts, then steps run in order.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct Script {
|
||||
@@ -178,9 +257,11 @@ pub struct Script {
|
||||
pub steps: Vec<Step>,
|
||||
}
|
||||
|
||||
/// Fields of the player to change; the others keep their values.
|
||||
/// Fields of the player to change; the others keep their values. A server
|
||||
/// mod's players have no `yaw`, `pitch` or `food`, and a client mod's player
|
||||
/// no `game-mode`.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct PlayerSet {
|
||||
x: Option<f64>,
|
||||
y: Option<f64>,
|
||||
@@ -190,6 +271,37 @@ pub struct PlayerSet {
|
||||
health: Option<f32>,
|
||||
food: Option<u32>,
|
||||
dimension: Option<String>,
|
||||
game_mode: Option<Mode>,
|
||||
}
|
||||
|
||||
/// `players.game-mode` as a script spells it.
|
||||
#[derive(Clone, Copy, Debug, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum Mode {
|
||||
Survival,
|
||||
Creative,
|
||||
Adventure,
|
||||
Spectator,
|
||||
}
|
||||
impl From<Mode> for GameMode {
|
||||
fn from(m: Mode) -> GameMode {
|
||||
match m {
|
||||
Mode::Survival => GameMode::Survival,
|
||||
Mode::Creative => GameMode::Creative,
|
||||
Mode::Adventure => GameMode::Adventure,
|
||||
Mode::Spectator => GameMode::Spectator,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A block a player breaks or places.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct BlockSet {
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
state: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
@@ -200,8 +312,11 @@ pub struct ClockSet {
|
||||
}
|
||||
|
||||
/// One step. Its parts happen in this order: `reload`, `title-screen`,
|
||||
/// `player`, `clock`, `ticks`, `frames`, `chat`, `command`; then `expect` is
|
||||
/// checked against what the mod showed during the step.
|
||||
/// `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`, `break`,
|
||||
/// `place`, `leave`; then `expect` is checked against what the mod showed
|
||||
/// during the step. For a server mod, `player`, `chat`, `command`, `break`
|
||||
/// and `place` are the doing of the player named by `as`, or of the first
|
||||
/// player on.
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "kebab-case")]
|
||||
pub struct Step {
|
||||
@@ -218,6 +333,14 @@ pub struct Step {
|
||||
frames: u64,
|
||||
chat: Option<String>,
|
||||
command: Option<String>,
|
||||
/// Server mods: a player joins, leaves, breaks or places a block.
|
||||
join: Option<String>,
|
||||
leave: Option<String>,
|
||||
#[serde(rename = "as")]
|
||||
actor: Option<String>,
|
||||
#[serde(rename = "break")]
|
||||
broken: Option<BlockSet>,
|
||||
place: Option<BlockSet>,
|
||||
#[serde(default)]
|
||||
expect: Expect,
|
||||
}
|
||||
@@ -233,6 +356,10 @@ pub struct Expect {
|
||||
/// The command's feedback, and its red error.
|
||||
feedback: Option<String>,
|
||||
error: Option<String>,
|
||||
/// Server mods: every `players.tell` as `"Name: text"`, and every
|
||||
/// `players.broadcast`, in order.
|
||||
told: Option<Vec<String>>,
|
||||
broadcast: Option<Vec<String>>,
|
||||
/// The panel's lines (`[]`: no panel) and its corner.
|
||||
panel: Option<Vec<String>>,
|
||||
corner: Option<String>,
|
||||
@@ -276,6 +403,17 @@ impl PlayerSet {
|
||||
p.dimension.clone_from(d);
|
||||
}
|
||||
}
|
||||
fn apply_server(&self, p: &mut ServerPlayer) {
|
||||
let set = |to: &mut f64, v: Option<f64>| *to = v.unwrap_or(*to);
|
||||
set(&mut p.x, self.x);
|
||||
set(&mut p.y, self.y);
|
||||
set(&mut p.z, self.z);
|
||||
p.health = self.health.unwrap_or(p.health);
|
||||
p.game_mode = self.game_mode.map_or(p.game_mode, GameMode::from);
|
||||
if let Some(d) = &self.dimension {
|
||||
p.dimension.clone_from(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ClockSet {
|
||||
@@ -304,6 +442,17 @@ impl Step {
|
||||
if let Some(line) = &self.command {
|
||||
parts.push(format!("/{line}"));
|
||||
}
|
||||
if let Some(name) = &self.join {
|
||||
parts.insert(0, format!("{name} joins"));
|
||||
}
|
||||
for (what, b) in [("breaks", &self.broken), ("places", &self.place)] {
|
||||
if let Some(b) = b {
|
||||
parts.push(format!("{what} {} at {} {} {}", b.state, b.x, b.y, b.z));
|
||||
}
|
||||
}
|
||||
if let Some(name) = &self.leave {
|
||||
parts.push(format!("{name} leaves"));
|
||||
}
|
||||
if parts.is_empty() {
|
||||
parts.push("checks".into());
|
||||
}
|
||||
@@ -318,8 +467,35 @@ impl Step {
|
||||
game.player = None;
|
||||
game.clock = None;
|
||||
}
|
||||
if let Some(name) = &self.join {
|
||||
game.join(name);
|
||||
}
|
||||
let server = game.server();
|
||||
let actor = |game: &TestGame| match &self.actor {
|
||||
Some(name) => game
|
||||
.players
|
||||
.iter()
|
||||
.position(|p| p.name == *name)
|
||||
.ok_or_else(|| format!("{name} is not on the server")),
|
||||
None => (!game.players.is_empty())
|
||||
.then_some(0)
|
||||
.ok_or_else(|| "no player is on the server: add join = \"Name\"".to_string()),
|
||||
};
|
||||
let acts = self.player.is_some()
|
||||
|| self.chat.is_some()
|
||||
|| self.command.is_some()
|
||||
|| self.broken.is_some()
|
||||
|| self.place.is_some();
|
||||
let actor = if server && acts {
|
||||
Some(actor(game)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(set) = &self.player {
|
||||
set.apply(game.player.get_or_insert_with(default_player));
|
||||
match actor {
|
||||
Some(i) => set.apply_server(&mut game.players[i]),
|
||||
None => set.apply(game.player.get_or_insert_with(default_player)),
|
||||
}
|
||||
}
|
||||
if let Some(set) = &self.clock {
|
||||
set.apply(game.clock.get_or_insert(Clock {
|
||||
@@ -329,10 +505,32 @@ impl Step {
|
||||
}
|
||||
game.tick(self.ticks);
|
||||
game.frames(self.frames);
|
||||
let who = actor.map(|i| game.players[i].clone());
|
||||
if let Some(line) = &self.chat {
|
||||
game.chat(line);
|
||||
match &who {
|
||||
Some(p) => game.player_chat(p, line),
|
||||
None => game.chat(line),
|
||||
}
|
||||
}
|
||||
let owned = self.command.as_ref().map(|line| match &who {
|
||||
Some(p) => game.player_command(p, line),
|
||||
None => game.command(line),
|
||||
});
|
||||
for (b, placed) in [(&self.broken, false), (&self.place, true)] {
|
||||
if let (Some(b), Some(p)) = (b, &who) {
|
||||
let pos = BlockPos {
|
||||
x: b.x,
|
||||
y: b.y,
|
||||
z: b.z,
|
||||
};
|
||||
game.block(p, pos, &b.state, placed);
|
||||
}
|
||||
}
|
||||
if let Some(name) = &self.leave
|
||||
&& !game.leave(name)
|
||||
{
|
||||
return Err(format!("{name} is not on the server"));
|
||||
}
|
||||
let owned = self.command.as_ref().map(|line| game.command(line));
|
||||
let out = game.drain();
|
||||
let stopped = out.iter().find_map(|o| match o {
|
||||
Output::Stopped { reason, .. } => Some(reason.as_str()),
|
||||
@@ -372,10 +570,38 @@ impl Step {
|
||||
}
|
||||
let feedback = |error: bool| {
|
||||
out.iter().rev().find_map(|o| match o {
|
||||
Output::Feedback { text, error: e } if *e == error => Some(text.clone()),
|
||||
Output::Feedback { text, error: e } | Output::Reply { text, error: e, .. }
|
||||
if *e == error =>
|
||||
{
|
||||
Some(text.clone())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
if let Some(want) = &e.told {
|
||||
let name = |id: &str| {
|
||||
let p = game.players.iter().find(|p| p.id == id);
|
||||
p.map_or(id.to_owned(), |p| p.name.clone())
|
||||
};
|
||||
let got: Vec<String> = out
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
Output::Tell { player, text, .. } => Some(format!("{}: {text}", name(player))),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
same("told", want, &got)?;
|
||||
}
|
||||
if let Some(want) = &e.broadcast {
|
||||
let got: Vec<String> = out
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
Output::Broadcast { text, .. } => Some(text.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
same("broadcast", want, &got)?;
|
||||
}
|
||||
if let Some(want) = &e.feedback {
|
||||
same("feedback", &Some(want.clone()), &feedback(false))?;
|
||||
}
|
||||
|
||||
@@ -302,3 +302,38 @@ fn every_capability_with_an_interface_is_in_the_contract() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every function the game offers (an interface some world imports and none
|
||||
/// exports) has an API level, and the levels list nothing else.
|
||||
#[test]
|
||||
fn every_function_has_an_api_level() {
|
||||
let mut resolve = Resolve::default();
|
||||
let package = resolve.push_file(root().join(WIT)).unwrap();
|
||||
let package = &resolve.packages[package];
|
||||
let exported: Vec<_> = package
|
||||
.worlds
|
||||
.values()
|
||||
.flat_map(|&w| resolve.worlds[w].exports.values())
|
||||
.filter_map(|item| match item {
|
||||
WorldItem::Interface { id, .. } => Some(*id),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let mut offered = Vec::new();
|
||||
for (name, &id) in &package.interfaces {
|
||||
if !exported.contains(&id) {
|
||||
for function in resolve.interfaces[id].functions.keys() {
|
||||
offered.push(format!("{name}.{function}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
for f in &offered {
|
||||
assert!(
|
||||
horizon_mods::api_level::level_of(f).is_some(),
|
||||
"{f} has no level in crates/horizon-mods/src/api_level.rs: add it at the next level"
|
||||
);
|
||||
}
|
||||
for (f, _) in horizon_mods::api_level::FUNCTIONS {
|
||||
assert!(offered.iter().any(|o| o == f), "{f} isn't in the WIT");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
"hud",
|
||||
"chat"
|
||||
],
|
||||
"api_level": 0,
|
||||
"game": "26.3",
|
||||
"file": {
|
||||
"name": "coords_hud-0.1.0.hmod",
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
//! examples and a guest
|
||||
//! that misbehaves on command. Needs `rustup target add wasm32-unknown-unknown`.
|
||||
use horizon_mods::{
|
||||
BlockPos, Clock, Corner, GameMode, HeldItem, Mods, Output, Package, Player, Runs, ServerPlayer,
|
||||
Shape, Snapshot, Status,
|
||||
BlockPos, Clock, Corner, GameMode, HeldItem, Hit, Mods, Output, Package, Player, Runs,
|
||||
ServerPlayer, Shape, Snapshot, Status,
|
||||
manifest::componentize,
|
||||
testing::{Script, TestGame},
|
||||
};
|
||||
@@ -26,7 +26,7 @@ id = "test_ui_guest"
|
||||
name = "Test UI Guest"
|
||||
version = "0.1.0"
|
||||
api = "0.1"
|
||||
capabilities = ["chat", "ui", "render", "input"]
|
||||
capabilities = ["game-read", "chat", "ui", "render", "input"]
|
||||
experimental = ["ui", "render", "input"]
|
||||
"#;
|
||||
|
||||
@@ -197,6 +197,65 @@ fn undeclared_capabilities_are_refused() {
|
||||
assert_eq!(mods.entries()[0].status, refused);
|
||||
}
|
||||
|
||||
/// A mod calling a function this Horizon doesn't have is refused with
|
||||
/// "update Horizon", not a linking error; the test mods' levels are read
|
||||
/// from the functions they import.
|
||||
#[test]
|
||||
fn a_mod_for_a_newer_horizon_is_refused() {
|
||||
use horizon_mods::api_level::{LEVEL, imports, needed};
|
||||
use wit_parser::{ManglingAndAbi, Resolve};
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
|
||||
let wit = std::fs::read_to_string(root.join("crates/horizon-mod-sdk/wit/horizon.wit"))
|
||||
.unwrap()
|
||||
.replace(
|
||||
" set-minimap: func(minimap: option<minimap>);",
|
||||
" set-minimap: func(minimap: option<minimap>);\n set-sky: func(on: bool);",
|
||||
);
|
||||
let mut resolve = Resolve::default();
|
||||
let package = resolve.push_str("horizon.wit", &wit).unwrap();
|
||||
let world = resolve
|
||||
.select_world(&[package], Some("horizon-ui-mod"))
|
||||
.unwrap();
|
||||
let mut module = wit_component::dummy_module(&resolve, world, ManglingAndAbi::Standard32);
|
||||
wit_component::embed_component_metadata(
|
||||
&mut module,
|
||||
&resolve,
|
||||
world,
|
||||
wit_component::StringEncoding::UTF8,
|
||||
)
|
||||
.unwrap();
|
||||
let wasm = wit_component::ComponentEncoder::default()
|
||||
.module(&module)
|
||||
.unwrap()
|
||||
.encode()
|
||||
.unwrap();
|
||||
let functions = imports(&wasm).unwrap();
|
||||
assert!(functions.iter().any(|f| f == "render.set-sky"));
|
||||
let dir = mods_dir().join("too_new");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let manifest = r#"
|
||||
id = "too_new"
|
||||
name = "Too New"
|
||||
version = "0.1.0"
|
||||
api = "0.1"
|
||||
capabilities = ["game-read", "chat", "hud", "storage", "command", "ui", "render", "input"]
|
||||
experimental = ["ui", "render", "input"]
|
||||
"#;
|
||||
std::fs::write(dir.join("horizon-mod.toml"), manifest).unwrap();
|
||||
std::fs::write(dir.join("mod.wasm"), wasm).unwrap();
|
||||
let mods = Mods::load(&[dir], |_| true, |_| false);
|
||||
let refused = "made for a newer Horizon (it uses render.set-sky): update Horizon to run it";
|
||||
assert_eq!(mods.entries()[0].status, Status::Failed(refused.into()));
|
||||
|
||||
let level = |file: &str| {
|
||||
let wasm = Package::read(&mods_dir().join(file)).unwrap().wasm.unwrap();
|
||||
needed(imports(&wasm).unwrap().iter().map(String::as_str)).0
|
||||
};
|
||||
assert_eq!(level("coords_hud.hmod"), 0);
|
||||
// The UI guest shows a minimap (`render.set-minimap`).
|
||||
assert_eq!(level("horizon_mods_test_ui_guest.hmod"), LEVEL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vanilla_commands_win() {
|
||||
let mods = Mods::load(
|
||||
@@ -663,6 +722,47 @@ fn render_minimap_is_clamped_and_hidden() {
|
||||
assert_eq!(map(&mut mods, "off"), None);
|
||||
}
|
||||
|
||||
/// `game.raycast`: the view's hit the game worked out, up to the distance
|
||||
/// asked for; the game works it out only while a mod imports the call.
|
||||
#[test]
|
||||
fn game_raycast_sees_the_view_hit_within_its_distance() {
|
||||
let mut mods = load("horizon_mods_test_ui_guest.hmod");
|
||||
assert!(mods.wants_raycast());
|
||||
assert!(!load("coords_hud.hmod").wants_raycast());
|
||||
let said = |mods: &mut Mods, args: &str| -> Vec<String> {
|
||||
assert!(mods.command(&format!("raycast {args}")));
|
||||
mods.drain()
|
||||
.into_iter()
|
||||
.filter_map(|o| match o {
|
||||
Output::Chat { text, .. } => Some(text),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
assert_eq!(said(&mut mods, "100"), ["no hit"]);
|
||||
mods.set_snapshot(Snapshot {
|
||||
view_hit: Some((
|
||||
40.5,
|
||||
Hit {
|
||||
block_x: 12,
|
||||
block_y: 63,
|
||||
block_z: -44,
|
||||
x: 12.5,
|
||||
y: 64.0,
|
||||
z: -43.75,
|
||||
block: "minecraft:grass_block".into(),
|
||||
},
|
||||
)),
|
||||
..player()
|
||||
});
|
||||
let hit = "hit minecraft:grass_block at 12 63 -44 (12.5 64.0 -43.8)";
|
||||
assert_eq!(said(&mut mods, "100"), [hit]);
|
||||
assert_eq!(said(&mut mods, "40"), ["no hit"]);
|
||||
// NaN asks for nothing; past 1024 is 1024.
|
||||
assert_eq!(said(&mut mods, "x"), ["no hit"]);
|
||||
assert_eq!(said(&mut mods, "1e9"), [hit]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corner_panels_text_width_and_readings() {
|
||||
let mut mods = load("horizon_mods_test_ui_guest.hmod");
|
||||
@@ -735,22 +835,23 @@ capabilities = ["registries"]
|
||||
assert!(!mods.is_running());
|
||||
}
|
||||
|
||||
/// `cargo horizon-mod test` on the example: its own `tests/*.toml` pass.
|
||||
/// `cargo horizon-mod test` on the examples: their own `tests/*.toml` pass.
|
||||
#[test]
|
||||
fn the_examples_test_scripts_pass() {
|
||||
let tests =
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("../horizon-mod-sdk/examples/coords-hud/tests");
|
||||
let examples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../horizon-mod-sdk/examples");
|
||||
let mut ran = 0;
|
||||
for entry in std::fs::read_dir(tests).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
let script = Script::parse(&std::fs::read_to_string(&path).unwrap()).unwrap();
|
||||
let mut game = TestGame::load(&mods_dir().join("coords_hud.hmod")).unwrap();
|
||||
script
|
||||
.run(&mut game)
|
||||
.unwrap_or_else(|e| panic!("{}: {e}", path.display()));
|
||||
ran += 1;
|
||||
for (example, hmod) in [("coords-hud", "coords_hud"), ("welcome", "welcome")] {
|
||||
for entry in std::fs::read_dir(examples.join(example).join("tests")).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
let script = Script::parse(&std::fs::read_to_string(&path).unwrap()).unwrap();
|
||||
let mut game = TestGame::load(&mods_dir().join(format!("{hmod}.hmod"))).unwrap();
|
||||
script
|
||||
.run(&mut game)
|
||||
.unwrap_or_else(|e| panic!("{}: {e}", path.display()));
|
||||
ran += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(ran, 2);
|
||||
assert_eq!(ran, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -774,6 +875,13 @@ fn a_test_script_says_which_step_failed_and_why() {
|
||||
Script::parse("[[step]]\ntick = 1").is_err(),
|
||||
"a typo is an error"
|
||||
);
|
||||
|
||||
let mut game = TestGame::load(&mods_dir().join("welcome.hmod")).unwrap();
|
||||
let script = "[[step]]\njoin = \"Alex\"\n\n[[step]]\nas = \"Steve\"\ncommand = \"mined\"";
|
||||
assert_eq!(
|
||||
Script::parse(script).unwrap().run(&mut game).unwrap_err(),
|
||||
"step 2 (/mined): Steve is not on the server"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
//! `/render_hud`, `/render_clear` and `/render_shake` test `render`;
|
||||
//! `/input_claim`, `/input_poll`, `/input_held` and `/input_wheel` test
|
||||
//! `input`; `/zoom FACTOR SMOOTH TURN` tests `render.set-zoom`;
|
||||
//! `/corner` and `/readings` the calls the official extras mods use.
|
||||
//! `/corner` and `/readings` the calls the official extras mods use;
|
||||
//! `/raycast DISTANCE` says what `game.raycast` sees.
|
||||
use horizon_mod_sdk::{
|
||||
Mod, Registration, chat,
|
||||
Mod, Registration, chat, game,
|
||||
input::{self, Event},
|
||||
render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape},
|
||||
ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget},
|
||||
@@ -97,6 +98,7 @@ impl Mod for Guest {
|
||||
"input_wheel",
|
||||
"zoom",
|
||||
"minimap",
|
||||
"raycast",
|
||||
"corner",
|
||||
"readings",
|
||||
]
|
||||
@@ -217,6 +219,16 @@ impl Mod for Guest {
|
||||
});
|
||||
render::set_minimap(map);
|
||||
}
|
||||
"raycast" => {
|
||||
let distance = args.parse().unwrap_or(f32::NAN);
|
||||
chat::show(&match game::raycast(distance) {
|
||||
Some(h) => format!(
|
||||
"hit {} at {} {} {} ({:.1} {:.1} {:.1})",
|
||||
h.block, h.block_x, h.block_y, h.block_z, h.x, h.y, h.z
|
||||
),
|
||||
None => "no hit".into(),
|
||||
});
|
||||
}
|
||||
// Clamped to (1, 10); the two after it shake nothing.
|
||||
"render_shake" => {
|
||||
render::shake(2.0, 99.0);
|
||||
|
||||
@@ -828,9 +828,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::legacy_structure_mods::lithostitched::modifier(&v, loaded, types)
|
||||
}) {
|
||||
if let Some((kind, mut added)) =
|
||||
modifier.and_then(|v| crate::lithostitched::modifier(&v, loaded, types))
|
||||
{
|
||||
crate::processors::carry(
|
||||
kind,
|
||||
&mut added,
|
||||
|
||||
@@ -157,6 +157,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "modular compat is crate::lithostitched's now (its tests)"]
|
||||
fn modular_compat_runs_its_list_only_with_its_mod() {
|
||||
let mut data = ProcessorData::default();
|
||||
let swap = json!({"processor_type": "minecraft:rule", "rules": []});
|
||||
|
||||
@@ -1,503 +0,0 @@
|
||||
//! 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);
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,11 @@
|
||||
//! 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.
|
||||
#[allow(dead_code)] // its modular compat is `crate::lithostitched`'s now; the rest goes with C1
|
||||
pub(crate) mod ctov;
|
||||
pub(crate) mod lithostitched;
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(dead_code)] // the old Lithostitched tests used it
|
||||
fn data() -> crate::processors::ProcessorData {
|
||||
let mut d = crate::processors::ProcessorData::default();
|
||||
d.spawners.insert(
|
||||
|
||||
@@ -14,6 +14,7 @@ pub mod import;
|
||||
pub mod inventory;
|
||||
pub mod jar;
|
||||
pub(crate) mod legacy_structure_mods;
|
||||
mod lithostitched;
|
||||
pub mod modrinth;
|
||||
pub mod oracle;
|
||||
pub mod pipeline;
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
//! Lithostitched's worldgen, carried as the game reads it (clean room:
|
||||
//! `cleanroom/structures/spec-lithostitched.md`; CTOV's processor:
|
||||
//! `spec-ctov.md` §4).
|
||||
//!
|
||||
//! - `lithostitched:jigsaw` structures become vanilla's jigsaw. Lithostitched
|
||||
//! lays jigsaws out its own way (OPEN-L5): Horizon keeps vanilla's layouts.
|
||||
//! - Its processors (`block_swap`, `reference`, `apply_random`, `condition`,
|
||||
//! `set_block`, `discard_input`) are the game's own types
|
||||
//! (`horizon_world`'s `structure::processor`): they are carried as written,
|
||||
//! the processors nested in them carried in turn. CTOV's
|
||||
//! `ctov:modular_compat` (a reference that runs only when its mod is loaded)
|
||||
//! becomes a `reference` when the mod is ported along, else nothing.
|
||||
//! - `add_template_pool_elements` modifiers become `horizon:add_to` pool files
|
||||
//! (`docs/mods.md`), when their load conditions pass. Lithostitched's own
|
||||
//! pool elements (`limited`, `guaranteed`, `delegating`) place their
|
||||
//! `delegate`; what they add to it is counted as lost.
|
||||
use crate::{processors::ProcessorData, worldgen::Upgrade};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const JIGSAW: &str = "lithostitched:jigsaw";
|
||||
/// Vanilla's JigsawStructure.MAX_DEPTH.
|
||||
const MAX_SIZE: i64 = 20;
|
||||
const MODULAR_COMPAT: &str = "ctov:modular_compat";
|
||||
/// The processor types the game reads.
|
||||
const PROCESSORS: [&str; 6] = [
|
||||
"lithostitched:block_swap",
|
||||
"lithostitched:reference",
|
||||
"lithostitched:apply_random",
|
||||
"lithostitched:condition",
|
||||
"lithostitched:set_block",
|
||||
"lithostitched:discard_input",
|
||||
];
|
||||
|
||||
fn count(map: &mut BTreeMap<String, usize>, name: &str) {
|
||||
*map.entry(name.to_owned()).or_default() += 1;
|
||||
}
|
||||
|
||||
/// A `lithostitched:jigsaw` structure as vanilla's jigsaw: `Some(true)`, else
|
||||
/// `None`.
|
||||
pub(crate) fn upgrade(
|
||||
kind: &str,
|
||||
v: &mut Value,
|
||||
lost: &mut BTreeMap<String, usize>,
|
||||
) -> Option<bool> {
|
||||
if kind != "structure" || v["type"] != JIGSAW {
|
||||
return None;
|
||||
}
|
||||
v["type"] = "minecraft:jigsaw".into();
|
||||
// `size` may be an int provider (sampled per start): its largest value.
|
||||
let size = match &v["size"] {
|
||||
Value::Null => None,
|
||||
Value::Number(n) => n.as_i64(),
|
||||
provider => {
|
||||
count(lost, "lithostitched:jigsaw size provider");
|
||||
["max_inclusive", "value"]
|
||||
.iter()
|
||||
.find_map(|k| provider[k].as_i64())
|
||||
}
|
||||
};
|
||||
if let Some(size) = size {
|
||||
if size > MAX_SIZE {
|
||||
count(lost, "lithostitched:jigsaw size over 20");
|
||||
}
|
||||
v["size"] = size.clamp(0, MAX_SIZE).into();
|
||||
}
|
||||
let o = v.as_object_mut()?;
|
||||
match o.remove("start_projection") {
|
||||
Some(Value::String(heightmap)) if heightmap != "floor" && heightmap != "ceiling" => {
|
||||
o.entry("project_start_to_heightmap")
|
||||
.or_insert(heightmap.into());
|
||||
}
|
||||
Some(_) => count(lost, "lithostitched:jigsaw start_projection"),
|
||||
None => {}
|
||||
}
|
||||
if o.remove("fixed_rotation").is_some_and(|f| f == true) {
|
||||
count(lost, "lithostitched:jigsaw fixed_rotation");
|
||||
}
|
||||
Some(true)
|
||||
}
|
||||
|
||||
/// Lithostitched's pool elements as the element they wrap; whether `element`
|
||||
/// was one.
|
||||
pub(crate) fn upgrade_pool_element(
|
||||
element: &mut Value,
|
||||
lost: &mut BTreeMap<String, usize>,
|
||||
) -> bool {
|
||||
let Some(kind) = element["element_type"].as_str() else {
|
||||
return false;
|
||||
};
|
||||
match kind {
|
||||
"lithostitched:limited" | "lithostitched:guaranteed" | "lithostitched:delegating" => {
|
||||
count(lost, kind);
|
||||
let delegate = element["delegate"].take();
|
||||
*element = delegate;
|
||||
// A delegate wrapping another (only `delegating` allows it).
|
||||
upgrade_pool_element(element, lost);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids a modifier targets: an id or a list of ids (`None` for tags and
|
||||
/// Lithostitched's object forms).
|
||||
fn ids(v: &Value) -> Option<Vec<String>> {
|
||||
let id = |v: &Value| {
|
||||
v.as_str()
|
||||
.filter(|s| !s.starts_with('#'))
|
||||
.map(str::to_owned)
|
||||
};
|
||||
match v {
|
||||
Value::Array(a) => a.iter().map(id).collect(),
|
||||
other => Some(vec![id(other)?]),
|
||||
}
|
||||
}
|
||||
|
||||
/// NeoForge's load conditions (`neoforge:conditions`): all must pass.
|
||||
fn conditions_pass(v: &Value, loaded: &dyn Fn(&str) -> bool) -> bool {
|
||||
fn pass(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool {
|
||||
let all = |key: &str| {
|
||||
c[key]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.all(|c| pass(c, loaded))
|
||||
};
|
||||
match c["type"].as_str() {
|
||||
Some("neoforge:mod_loaded") => c["modid"].as_str().is_some_and(loaded),
|
||||
Some("neoforge:true") => true,
|
||||
Some("neoforge:not") => !pass(&c["value"], loaded),
|
||||
Some("neoforge:and") => all("values"),
|
||||
Some("neoforge:or") => {
|
||||
(c["values"].as_array().into_iter().flatten()).any(|c| pass(c, loaded))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
(v["neoforge:conditions"].as_array().into_iter().flatten()).all(|c| pass(c, loaded))
|
||||
}
|
||||
|
||||
/// A worldgen modifier as a file the game merges: `("template_pool", file)`
|
||||
/// for `add_template_pool_elements`; the others are counted in
|
||||
/// `report.modifiers_left`.
|
||||
pub(crate) fn modifier(
|
||||
v: &Value,
|
||||
loaded: &dyn Fn(&str) -> bool,
|
||||
report: &mut Upgrade,
|
||||
) -> Option<(&'static str, Value)> {
|
||||
let kind = v["type"].as_str().unwrap_or("no type");
|
||||
if !conditions_pass(v, loaded) {
|
||||
count(&mut report.modifiers_left, "conditions");
|
||||
return None;
|
||||
}
|
||||
if kind != "lithostitched:add_template_pool_elements" {
|
||||
count(&mut report.modifiers_left, kind);
|
||||
return None;
|
||||
}
|
||||
let (Some(targets), Some(elements)) = (ids(&v["template_pools"]), v["elements"].as_array())
|
||||
else {
|
||||
count(&mut report.modifiers_left, "target");
|
||||
return None;
|
||||
};
|
||||
for target in &targets {
|
||||
*report.added_to.entry(target.clone()).or_default() += elements.len();
|
||||
}
|
||||
Some((
|
||||
"template_pool",
|
||||
json!({"horizon:add_to": targets, "elements": elements}),
|
||||
))
|
||||
}
|
||||
|
||||
/// Whether the game reads a Lithostitched processor as it is: one of its
|
||||
/// types, with no processor list named by tag (the game has no processor
|
||||
/// list tags) and a state provider it runs.
|
||||
pub(crate) fn game_reads(p: &Value) -> bool {
|
||||
let Some(kind) = p["processor_type"]
|
||||
.as_str()
|
||||
.filter(|t| PROCESSORS.contains(t))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let tag = |v: &Value| v.as_str().is_some_and(|s| s.starts_with('#'));
|
||||
match kind {
|
||||
"lithostitched:reference" => match &p["processor_lists"] {
|
||||
Value::Array(a) => !a.iter().any(tag),
|
||||
other => other.is_string() && !tag(other),
|
||||
},
|
||||
"lithostitched:apply_random" => p["processor_lists"]
|
||||
.as_array()
|
||||
.is_some_and(|a| a.iter().all(|e| !tag(e) && !tag(&e["data"]))),
|
||||
"lithostitched:set_block" => matches!(
|
||||
p["state_provider"]["type"].as_str(),
|
||||
Some("minecraft:simple_state_provider" | "minecraft:weighted_state_provider")
|
||||
),
|
||||
"lithostitched:block_swap" => p["blocks"].is_object(),
|
||||
"lithostitched:condition" => !p["if_true"].is_null(),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The processor lists inside a Lithostitched processor, for the general
|
||||
/// code that walks lists (`then`, `else`, `apply_random`'s inline data).
|
||||
pub(crate) fn inner_lists(p: &mut Value) -> Vec<&mut Value> {
|
||||
match p["processor_type"].as_str() {
|
||||
Some("lithostitched:apply_random") => (p["processor_lists"].as_array_mut().into_iter())
|
||||
.flatten()
|
||||
.filter_map(|e| e.get_mut("data").filter(|d| !d.is_string()))
|
||||
.collect(),
|
||||
Some("lithostitched:condition") => (p.as_object_mut().into_iter())
|
||||
.flat_map(|o| o.iter_mut())
|
||||
.filter(|(k, _)| *k == "then" || *k == "else")
|
||||
.map(|(_, v)| v)
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A Lithostitched processor with the processors nested in it carried
|
||||
/// (`Some`, when one of them changed); `None` for any other processor.
|
||||
pub(crate) fn processor(
|
||||
kind: &str,
|
||||
p: &Value,
|
||||
data: &ProcessorData,
|
||||
carried: &mut BTreeMap<String, usize>,
|
||||
) -> Option<Vec<Value>> {
|
||||
if !PROCESSORS.contains(&kind) {
|
||||
return None;
|
||||
}
|
||||
let mut out = p.clone();
|
||||
let mut changed = false;
|
||||
for list in inner_lists(&mut out) {
|
||||
// One processor alone is a list of one.
|
||||
if list.get("processor_type").is_some() {
|
||||
*list = Value::Array(vec![list.take()]);
|
||||
changed = true;
|
||||
}
|
||||
if let Some(processors) = crate::processors::processors(list) {
|
||||
let (inner, inner_changed) =
|
||||
crate::processors::carry_all(std::mem::take(processors), data, carried);
|
||||
*processors = inner;
|
||||
changed |= inner_changed;
|
||||
}
|
||||
}
|
||||
changed.then(|| vec![out])
|
||||
}
|
||||
|
||||
/// The list with CTOV's modular compat processors written as the game's
|
||||
/// `reference` (its mod is ported along) or taken out; whether any was.
|
||||
pub(crate) fn expand_references(
|
||||
list: Vec<Value>,
|
||||
data: &ProcessorData,
|
||||
carried: &mut BTreeMap<String, usize>,
|
||||
) -> (Vec<Value>, bool) {
|
||||
let mut changed = false;
|
||||
let mut out = Vec::with_capacity(list.len());
|
||||
for p in list {
|
||||
if p["processor_type"] != MODULAR_COMPAT {
|
||||
out.push(p);
|
||||
continue;
|
||||
}
|
||||
changed = true;
|
||||
count(carried, MODULAR_COMPAT);
|
||||
let loaded = p["modid"]
|
||||
.as_str()
|
||||
.is_some_and(|m| data.compat_loaded.contains(m));
|
||||
if loaded {
|
||||
out.push(json!({"processor_type": "lithostitched:reference",
|
||||
"processor_lists": p["reference"].clone()}));
|
||||
}
|
||||
}
|
||||
(out, changed)
|
||||
}
|
||||
|
||||
/// Notes which mods CTOV's modular compat processors name are `loaded`.
|
||||
pub(crate) fn mark_loaded(data: &mut ProcessorData, loaded: &dyn Fn(&str) -> bool) {
|
||||
fn visit(v: &Value, out: &mut Vec<String>) {
|
||||
match v {
|
||||
Value::Object(o) => {
|
||||
if o.get("processor_type").and_then(Value::as_str) == Some(MODULAR_COMPAT)
|
||||
&& let Some(m) = o.get("modid").and_then(Value::as_str)
|
||||
{
|
||||
out.push(m.to_owned());
|
||||
}
|
||||
o.values().for_each(|v| visit(v, out));
|
||||
}
|
||||
Value::Array(a) => a.iter().for_each(|v| visit(v, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut named = Vec::new();
|
||||
data.lists.values().for_each(|l| visit(l, &mut named));
|
||||
data.compat_loaded
|
||||
.extend(named.into_iter().filter(|m| loaded(m)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::worldgen::upgrade as upgrade_file;
|
||||
|
||||
#[test]
|
||||
fn jigsaws_become_vanillas() {
|
||||
let mut lost = BTreeMap::new();
|
||||
let mut s = json!({"type": JIGSAW, "size": {"type": "uniform", "min_inclusive": 3,
|
||||
"max_inclusive": 40}, "start_projection": "WORLD_SURFACE_WG", "fixed_rotation": true});
|
||||
assert_eq!(upgrade("structure", &mut s, &mut lost), Some(true));
|
||||
assert_eq!(
|
||||
s,
|
||||
json!({"type": "minecraft:jigsaw", "size": 20,
|
||||
"project_start_to_heightmap": "WORLD_SURFACE_WG"})
|
||||
);
|
||||
assert_eq!(lost.len(), 3);
|
||||
assert_eq!(
|
||||
upgrade(
|
||||
"structure",
|
||||
&mut json!({"type": "minecraft:jigsaw"}),
|
||||
&mut lost
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrapped_elements_place_their_delegate() {
|
||||
let mut lost = BTreeMap::new();
|
||||
let delegate = json!({"element_type": "minecraft:single_pool_element", "location": "a:b",
|
||||
"projection": "rigid", "processors": "minecraft:empty"});
|
||||
let mut e =
|
||||
json!({"element_type": "lithostitched:limited", "limit": 1, "delegate": delegate});
|
||||
assert!(upgrade_pool_element(&mut e, &mut lost));
|
||||
assert_eq!(e, delegate);
|
||||
assert_eq!(lost["lithostitched:limited"], 1);
|
||||
assert!(!upgrade_pool_element(&mut e, &mut lost));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modifiers_add_to_pools_when_their_mods_are_loaded() {
|
||||
let mut report = Upgrade::default();
|
||||
let loaded = |m: &str| m == "waystones";
|
||||
let add = |modid: &str, pools: Value| {
|
||||
json!({"type": "lithostitched:add_template_pool_elements", "template_pools": pools,
|
||||
"elements": [{"weight": 2, "element": {"element_type": "minecraft:empty_pool_element"}}],
|
||||
"neoforge:conditions": [{"type": "neoforge:mod_loaded", "modid": modid}]})
|
||||
};
|
||||
let (kind, file) = modifier(
|
||||
&add("waystones", json!("ctov:village/plains/house")),
|
||||
&loaded,
|
||||
&mut report,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(kind, "template_pool");
|
||||
assert_eq!(file["horizon:add_to"], json!(["ctov:village/plains/house"]));
|
||||
assert_eq!(file["elements"][0]["weight"], 2);
|
||||
assert_eq!(report.added_to["ctov:village/plains/house"], 1);
|
||||
assert!(modifier(&add("sawmill", json!("a:b")), &loaded, &mut report).is_none());
|
||||
assert!(modifier(&add("waystones", json!("#a:pools")), &loaded, &mut report).is_none());
|
||||
let aliases = json!({"type": "lithostitched:set_pool_aliases"});
|
||||
assert!(modifier(&aliases, &loaded, &mut report).is_none());
|
||||
assert_eq!(
|
||||
report.modifiers_left,
|
||||
BTreeMap::from([
|
||||
("conditions".into(), 1),
|
||||
("lithostitched:set_pool_aliases".into(), 1),
|
||||
("target".into(), 1),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
/// A CTOV list (spec-ctov §4): references, a condition with a single
|
||||
/// processor and a nested condition, a random list holding the compat
|
||||
/// hook, and processors the game cannot read.
|
||||
#[test]
|
||||
fn processors_stay_lithostitcheds_with_their_insides_carried() {
|
||||
let hook = json!({"processor_type": MODULAR_COMPAT, "modid": "natures_spirit",
|
||||
"reference": "ctov:village/mesa/house_wisteria"});
|
||||
let list = json!({"processors": [
|
||||
{"processor_type": "lithostitched:reference", "processor_lists": ["ctov:village/mesa/house"]},
|
||||
{"processor_type": "lithostitched:condition", "random_mode": "per_block",
|
||||
"if_true": {"type": "lithostitched:matching_blocks", "blocks": "minecraft:water",
|
||||
"match_type": "location"},
|
||||
"then": {"processor_type": "lithostitched:set_block", "state_provider": {
|
||||
"type": "minecraft:simple_state_provider", "state": {"Name": "minecraft:spruce_planks"}}},
|
||||
"else": [{"processor_type": "somemod:java_processor"}]},
|
||||
{"processor_type": "lithostitched:apply_random", "mode": "per_piece", "processor_lists": [
|
||||
{"weight": 1, "data": "minecraft:empty"},
|
||||
{"weight": 1, "data": {"processors": [hook]}}]},
|
||||
{"processor_type": "lithostitched:reference", "processor_lists": "#ctov:palettes"},
|
||||
{"processor_type": "lithostitched:set_block", "state_provider": {
|
||||
"type": "minecraft:noise_provider"}}]});
|
||||
for (loaded, wisteria) in [
|
||||
(false, json!([])),
|
||||
(
|
||||
true,
|
||||
json!([{"processor_type":
|
||||
"lithostitched:reference", "processor_lists": "ctov:village/mesa/house_wisteria"}]),
|
||||
),
|
||||
] {
|
||||
let mut data = ProcessorData::default();
|
||||
data.lists
|
||||
.insert("ctov:village/mesa/house".into(), list.clone());
|
||||
mark_loaded(&mut data, &|m| loaded && m == "natures_spirit");
|
||||
let mut v = list.clone();
|
||||
let mut report = Upgrade::default();
|
||||
crate::processors::carry(
|
||||
"processor_list",
|
||||
&mut v,
|
||||
&data,
|
||||
&mut report.processors_carried,
|
||||
);
|
||||
upgrade_file("processor_list", &mut v, &mut report, &BTreeMap::new());
|
||||
let p = &v["processors"];
|
||||
assert_eq!(p.as_array().unwrap().len(), 3, "{p}");
|
||||
assert_eq!(p[0], list["processors"][0]);
|
||||
// One processor is a list of one; the Java one is taken out.
|
||||
assert_eq!(
|
||||
p[1]["then"][0]["state_provider"]["state"]["id"],
|
||||
"minecraft:spruce_planks"
|
||||
);
|
||||
assert_eq!(p[1]["else"], json!([]));
|
||||
assert_eq!(p[2]["processor_lists"][0]["data"], "minecraft:empty");
|
||||
assert_eq!(p[2]["processor_lists"][1]["data"]["processors"], wisteria);
|
||||
assert_eq!(report.processors_carried[MODULAR_COMPAT], 1);
|
||||
assert_eq!(
|
||||
report.processors_dropped,
|
||||
BTreeMap::from([
|
||||
("lithostitched:reference".into(), 1),
|
||||
("lithostitched:set_block".into(), 1),
|
||||
("somemod:java_processor".into(), 1),
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,13 +10,13 @@
|
||||
//! - Repurposed Structures' mineshaft sky view becomes the game's
|
||||
//! `horizon:mineshaft_sky_view`.
|
||||
//!
|
||||
//! The processors of YUNG's mods, Lithostitched and Choice Theorem's Overhauled
|
||||
//! Village are carried by `legacy_structure_mods`, called from [`carry`].
|
||||
//! Lithostitched's processors and Choice Theorem's Overhauled Village's
|
||||
//! compat hook are carried by `crate::lithostitched`, called from [`carry`].
|
||||
//!
|
||||
//! What is not here is taken out of its list later and counted
|
||||
//! (`worldgen::upgrade`). The entity NBT is written in 26.3's shape (an
|
||||
//! `equipment` map, not 1.21.1's `HandItems` and `ArmorItems`).
|
||||
use crate::legacy_structure_mods::{ctov, lithostitched};
|
||||
use crate::lithostitched;
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
@@ -42,7 +42,7 @@ pub struct ProcessorData {
|
||||
impl ProcessorData {
|
||||
/// Notes which mods its compat processors name are `loaded`.
|
||||
pub fn mark_loaded(&mut self, loaded: &dyn Fn(&str) -> bool) {
|
||||
ctov::mark_loaded(self, loaded);
|
||||
lithostitched::mark_loaded(self, loaded);
|
||||
}
|
||||
|
||||
pub fn read<R: Read + Seek>(zip: &mut zip::ZipArchive<R>) -> Self {
|
||||
@@ -177,8 +177,7 @@ fn carry_at(
|
||||
let mut out = Vec::with_capacity(expanded.len());
|
||||
for p in expanded {
|
||||
let kind = p["processor_type"].as_str().unwrap_or_default().to_owned();
|
||||
// Lithostitched's processors are carried apart from this code
|
||||
// (`legacy_structure_mods`).
|
||||
// Lithostitched's processors stay theirs, with what they hold carried.
|
||||
let replacement = lithostitched::processor(&kind, &p, data, carried).or_else(|| {
|
||||
match pillar_type(&kind) {
|
||||
Some(to) => Some(vec![pillar(&p, to, data, carried, depth)]),
|
||||
|
||||
@@ -15,10 +15,10 @@
|
||||
//! closely.
|
||||
//!
|
||||
//! YUNG's API's files are carried as written ([`crate::yung`]).
|
||||
//! 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};
|
||||
//! Lithostitched's jigsaws, elements, modifiers and processors are carried by
|
||||
//! [`crate::lithostitched`]; the entries CTOV adds to vanilla's structure sets
|
||||
//! by `legacy_structure_mods`, called from [`crate::carry`].
|
||||
use crate::{lithostitched, yung};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
@@ -191,28 +191,19 @@ fn drop_java_processors(list: &mut Value, dropped: &mut BTreeMap<String, usize>)
|
||||
let before = processors.len();
|
||||
processors.retain(|p| {
|
||||
let t = p["processor_type"].as_str().unwrap_or_default();
|
||||
let java = !t.starts_with("minecraft:") && !t.starts_with("horizon:");
|
||||
let java = !t.starts_with("minecraft:")
|
||||
&& !t.starts_with("horizon:")
|
||||
&& !lithostitched::game_reads(p);
|
||||
if java {
|
||||
*dropped.entry(t.to_owned()).or_default() += 1;
|
||||
}
|
||||
!java
|
||||
});
|
||||
let mut changed = processors.len() != before;
|
||||
// The inline lists inside the game's apply_random and condition.
|
||||
// The inline lists inside Lithostitched's apply_random and condition.
|
||||
for p in processors.iter_mut() {
|
||||
let inner: Vec<&mut Value> = match p["processor_type"].as_str() {
|
||||
Some("horizon:apply_random") => p["processor_lists"]
|
||||
.as_array_mut()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|e| &mut e["data"])
|
||||
.collect(),
|
||||
Some("horizon:condition") => {
|
||||
let o = p.as_object_mut().into_iter().flat_map(|o| o.iter_mut());
|
||||
o.filter(|(k, _)| *k == "then" || *k == "else")
|
||||
.map(|(_, v)| v)
|
||||
.collect()
|
||||
}
|
||||
Some(t) if t.starts_with("lithostitched:") => lithostitched::inner_lists(p),
|
||||
Some("horizon:pillar" | "horizon:bottom_pillar") => {
|
||||
p.get_mut("pillar_processor_list").into_iter().collect()
|
||||
}
|
||||
@@ -398,7 +389,9 @@ fn upgrade_types(
|
||||
}
|
||||
}
|
||||
for element in elements {
|
||||
if yung::upgrade_pool_element(element, lost) {
|
||||
if yung::upgrade_pool_element(element, lost)
|
||||
|| lithostitched::upgrade_pool_element(element, lost)
|
||||
{
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The player's own game files: the pinned version JSON, client jar and libraries from their
|
||||
//! official launcher install, and the server jar they downloaded, each checked against
|
||||
//! official launcher or ATLauncher install, and the server jar they downloaded, each checked against
|
||||
//! research-lock.json before it is copied to `.local/minecraft/<version>` (tools/lab.py's
|
||||
//! `prepare`, which the Python preparer ran first), then checked again on every run
|
||||
//! (tools/test_rust_parity.py's `verify_artifacts`).
|
||||
@@ -12,9 +12,10 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
const LAUNCHER_HINT: &str =
|
||||
"Horizon does not download the game: play {version} once in the launcher you play \
|
||||
Minecraft Java Edition with (the official launcher, Prism Launcher, MultiMC...) so it downloads \
|
||||
the game's files, then rerun. If that launcher keeps them in another folder, pass \
|
||||
--minecraft-dir or set HORIZON_MINECRAFT_DIR.";
|
||||
Minecraft Java Edition with so it downloads the game's files, then rerun. Horizon reads the \
|
||||
official launcher's folder, ATLauncher's and the CurseForge app's; for Prism Launcher, MultiMC, \
|
||||
the Modrinth App or GDLauncher, prepare from the Horizon launcher, which finds their files. If your launcher keeps \
|
||||
them in another folder, pass --minecraft-dir or set HORIZON_MINECRAFT_DIR.";
|
||||
const SERVER_HINT: &str = "Horizon does not download the game: download the {version} server jar yourself (minecraft.net/download/server \
|
||||
while {version} is the current release, otherwise the downloads.server.url in your launcher's \
|
||||
versions/{version}/{version}.json), then pass --server-jar PATH or set HORIZON_SERVER_JAR.";
|
||||
@@ -23,11 +24,6 @@ fn hint(text: &str, version: &str) -> String {
|
||||
text.replace("{version}", version)
|
||||
}
|
||||
|
||||
/// What to do when the player's launcher install lacks the pinned version's files.
|
||||
pub(crate) fn launcher_hint(version: &str) -> String {
|
||||
hint(LAUNCHER_HINT, version)
|
||||
}
|
||||
|
||||
/// research-lock.json and the folder the pinned version's files go to.
|
||||
pub struct Lock {
|
||||
pub json: Value,
|
||||
@@ -134,6 +130,137 @@ pub fn minecraft_dir(chosen: Option<&Path>) -> PathBuf {
|
||||
}
|
||||
}
|
||||
|
||||
/// One launcher's copy of the pinned version: its version JSON (Mojang's file, checked by its
|
||||
/// sha1), the client jar, and the folder holding its `libraries` (at the version JSON's paths)
|
||||
/// and `assets`.
|
||||
pub struct GameFiles {
|
||||
pub folder: PathBuf,
|
||||
pub manifest: PathBuf,
|
||||
pub client: PathBuf,
|
||||
/// Mojang's Java runtimes the launcher downloaded (java::minecraft_runtimes).
|
||||
pub runtimes: PathBuf,
|
||||
/// The folders looked in, each with its launcher, when none held the version.
|
||||
searched: Vec<(&'static str, PathBuf)>,
|
||||
}
|
||||
|
||||
impl GameFiles {
|
||||
/// What to do when these files are missing, with the folders looked in.
|
||||
pub(crate) fn hint(&self, version: &str) -> String {
|
||||
let mut text = hint(LAUNCHER_HINT, version);
|
||||
if !self.searched.is_empty() {
|
||||
text += &format!(" Horizon looked for {version} in:");
|
||||
for (launcher, folder) in &self.searched {
|
||||
text += &format!("\n {} ({launcher})", folder.display());
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
/// The layouts horizon-prepare reads in `folder`: the official launcher's, then ATLauncher's,
|
||||
/// which saves Mojang's version JSON as is in `configs/json/minecraft` and the client jar as
|
||||
/// the library `net.minecraft:client:<version>`.
|
||||
fn layouts(folder: &Path, version: &str) -> [GameFiles; 2] {
|
||||
let files = |manifest: String, client: String, runtimes: &str| GameFiles {
|
||||
folder: folder.to_path_buf(),
|
||||
manifest: folder.join(manifest),
|
||||
client: folder.join(client),
|
||||
runtimes: folder.join(runtimes),
|
||||
searched: Vec::new(),
|
||||
};
|
||||
let v = version;
|
||||
[
|
||||
files(
|
||||
format!("versions/{v}/{v}.json"),
|
||||
format!("versions/{v}/{v}.jar"),
|
||||
"runtime",
|
||||
),
|
||||
files(
|
||||
format!("configs/json/minecraft/{v}.json"),
|
||||
format!("libraries/net/minecraft/client/{v}/client-{v}.jar"),
|
||||
"runtimes/minecraft",
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The launchers whose folders are looked in when none is chosen: the official launcher's
|
||||
/// (`minecraft_dir`), ATLauncher's, then the CurseForge app's `Install` folder, where it runs
|
||||
/// the official launcher (its default modding folder, `curseforge/minecraft`, is in the home
|
||||
/// folder on Windows and in Documents elsewhere). ATLauncher keeps its files in its working folder:
|
||||
/// where its Windows installer puts it, inside the macOS app, and the folders its Linux
|
||||
/// packages and Flatpak start it in.
|
||||
fn launcher_folders() -> Vec<(&'static str, PathBuf)> {
|
||||
let mut folders = vec![("the official launcher", minecraft_dir(None))];
|
||||
// The same folders as the Horizon launcher's (launcher/src/sources.rs `known_folders`).
|
||||
let atlauncher: Vec<PathBuf> = if cfg!(target_os = "macos") {
|
||||
let app = Path::new("Applications/ATLauncher.app/Contents/Java");
|
||||
vec![
|
||||
home().join("Library/Application Support/ATLauncher"),
|
||||
Path::new("/").join(app),
|
||||
home().join(app),
|
||||
]
|
||||
} else if cfg!(windows) {
|
||||
std::env::var_os("APPDATA")
|
||||
.map(|d| PathBuf::from(d).join("ATLauncher"))
|
||||
.into_iter()
|
||||
.collect()
|
||||
} else {
|
||||
let data = std::env::var_os("XDG_DATA_HOME")
|
||||
.filter(|d| !d.is_empty())
|
||||
.map_or_else(|| home().join(".local/share"), PathBuf::from);
|
||||
let flatpak = home().join(".var/app/com.atlauncher.ATLauncher/data");
|
||||
vec![data.join("atlauncher"), flatpak.join("atlauncher"), flatpak]
|
||||
};
|
||||
folders.extend(atlauncher.into_iter().map(|dir| ("ATLauncher", dir)));
|
||||
let curseforge = if cfg!(windows) { "" } else { "Documents" };
|
||||
folders.push((
|
||||
"the CurseForge app",
|
||||
home().join(curseforge).join("curseforge/minecraft/Install"),
|
||||
));
|
||||
folders
|
||||
}
|
||||
|
||||
/// The pinned version's files in the chosen folder (`--minecraft-dir`, HORIZON_MINECRAFT_DIR),
|
||||
/// or the launcher above it when an instance folder (`instances/<name>`) is chosen; with no
|
||||
/// folder chosen, in the first launcher folder that has them. When none does, the official
|
||||
/// layout of the first folder is returned, for the errors to name, with the folders looked in.
|
||||
pub fn game_files(chosen: Option<&Path>, version: &str) -> GameFiles {
|
||||
let chosen = chosen
|
||||
.filter(|d| !d.as_os_str().is_empty())
|
||||
.map(Path::to_path_buf)
|
||||
.or_else(|| std::env::var_os("HORIZON_MINECRAFT_DIR").map(PathBuf::from))
|
||||
.filter(|d| !d.as_os_str().is_empty())
|
||||
.map(|d| expand_user(&d));
|
||||
let folders = match chosen {
|
||||
Some(dir) => {
|
||||
let launcher = dir
|
||||
.ancestors()
|
||||
.find(|a| a.file_name().is_some_and(|n| n == "instances"))
|
||||
.and_then(Path::parent)
|
||||
.map(Path::to_path_buf);
|
||||
let mut folders = vec![("the folder chosen", dir)];
|
||||
folders.extend(launcher.map(|dir| ("the launcher above it", dir)));
|
||||
folders
|
||||
}
|
||||
None => launcher_folders(),
|
||||
};
|
||||
// A folder with both files first: a version JSON left without its jar is used, for the
|
||||
// error to name the jar, only when no folder has both.
|
||||
let complete = |files: &GameFiles| files.manifest.is_file() && files.client.is_file();
|
||||
let partial = |files: &GameFiles| files.manifest.is_file();
|
||||
for found in [complete, partial] {
|
||||
let mut all = folders
|
||||
.iter()
|
||||
.flat_map(|(_, folder)| layouts(folder, version));
|
||||
if let Some(files) = all.find(found) {
|
||||
return files;
|
||||
}
|
||||
}
|
||||
let [mut files, _] = layouts(&folders[0].1, version);
|
||||
files.searched = folders;
|
||||
files
|
||||
}
|
||||
|
||||
/// Copy one file from the player's install, checked like a download; an existing verified
|
||||
/// copy is kept.
|
||||
pub(crate) fn import_copy(
|
||||
@@ -156,17 +283,14 @@ pub(crate) fn import_copy(
|
||||
.commit()
|
||||
}
|
||||
|
||||
/// The pinned version JSON from the launcher's versions/ directory. The launcher's copy wins
|
||||
/// over the cached one so the manifest matches the asset index installed alongside it.
|
||||
pub(crate) fn import_manifest(lock: &Lock, minecraft: &Path) -> Result<Value, String> {
|
||||
/// The pinned version JSON from the launcher's install. The launcher's copy wins over the
|
||||
/// cached one so the manifest matches the asset index installed alongside it.
|
||||
pub(crate) fn import_manifest(lock: &Lock, files: &GameFiles) -> Result<Value, String> {
|
||||
let version = &lock.version;
|
||||
let destination = lock.directory.join("manifest.json");
|
||||
let source = minecraft
|
||||
.join("versions")
|
||||
.join(version)
|
||||
.join(format!("{version}.json"));
|
||||
let source = &files.manifest;
|
||||
if source.is_file() {
|
||||
let manifest = read_json(&source)?;
|
||||
let manifest = read_json(source)?;
|
||||
let downloads = manifest.get("downloads");
|
||||
let sha1 = |side: &str| {
|
||||
downloads
|
||||
@@ -183,7 +307,7 @@ pub(crate) fn import_manifest(lock: &Lock, minecraft: &Path) -> Result<Value, St
|
||||
source.display()
|
||||
));
|
||||
}
|
||||
let checksum = digest(&source, "sha1")?;
|
||||
let checksum = digest(source, "sha1")?;
|
||||
if !lock.manifest_accepted(&checksum) {
|
||||
// Another launcher's rewrite of Mojang's file (HMCL and PCL add their own fields to
|
||||
// the same jars, #1772), or one Mojang republished: Mojang's own copy saved as the
|
||||
@@ -202,13 +326,13 @@ pub(crate) fn import_manifest(lock: &Lock, minecraft: &Path) -> Result<Value, St
|
||||
}
|
||||
} else if !(destination.exists() && digest(&destination, "sha1")? == checksum) {
|
||||
fs::create_dir_all(&lock.directory).map_err(|e| e.to_string())?;
|
||||
fs::copy(&source, &destination).map_err(|e| e.to_string())?;
|
||||
fs::copy(source, &destination).map_err(|e| e.to_string())?;
|
||||
}
|
||||
} else if !(destination.exists() && lock.manifest_accepted(&digest(&destination, "sha1")?)) {
|
||||
return Err(format!(
|
||||
"Missing {}. {}",
|
||||
source.display(),
|
||||
hint(LAUNCHER_HINT, version)
|
||||
files.hint(version)
|
||||
));
|
||||
}
|
||||
let manifest = read_json(&destination)?;
|
||||
@@ -519,18 +643,15 @@ pub fn import(
|
||||
server_jar: Option<&Path>,
|
||||
log: Log,
|
||||
) -> Result<(), String> {
|
||||
let minecraft = minecraft_dir(minecraft);
|
||||
let version = &lock.version;
|
||||
let manifest = import_manifest(lock, &minecraft)?;
|
||||
let files = game_files(minecraft, &lock.version);
|
||||
let minecraft = &files.folder;
|
||||
let manifest = import_manifest(lock, &files)?;
|
||||
let client = import_copy(
|
||||
&minecraft
|
||||
.join("versions")
|
||||
.join(version)
|
||||
.join(format!("{version}.jar")),
|
||||
&files.client,
|
||||
&lock.directory.join("jars/client.jar"),
|
||||
lock.pin("client_sha1")?,
|
||||
"sha1",
|
||||
&hint(LAUNCHER_HINT, version),
|
||||
&files.hint(&lock.version),
|
||||
)?;
|
||||
let downloads = manifest.get("downloads");
|
||||
if downloads.and_then(|d| d.get("client_mappings")).is_some()
|
||||
@@ -555,7 +676,7 @@ pub fn import(
|
||||
for (name, artifact) in client_library_artifacts(&manifest)? {
|
||||
let (path, sha1) = artifact_fields(artifact)?;
|
||||
let relative = safe_relative(path).ok_or("Unsafe library path")?;
|
||||
let source = launcher_library(&minecraft, name, &relative);
|
||||
let source = launcher_library(minecraft, name, &relative);
|
||||
let destination = lock.directory.join("libraries/client").join(&relative);
|
||||
if runs_without(name) && !source.is_file() && !destination.exists() {
|
||||
log(&format!(
|
||||
@@ -569,7 +690,7 @@ pub fn import(
|
||||
&destination,
|
||||
sha1,
|
||||
"sha1",
|
||||
&hint(LAUNCHER_HINT, version),
|
||||
&files.hint(&lock.version),
|
||||
)?);
|
||||
}
|
||||
write_import_metadata(
|
||||
@@ -1122,7 +1243,7 @@ mod tests {
|
||||
let lock = Lock::read(&root).unwrap();
|
||||
let destination = lock.directory.join("manifest.json");
|
||||
|
||||
let error = import_manifest(&lock, &minecraft).unwrap_err();
|
||||
let error = import_manifest(&lock, &game_files(Some(&minecraft), "9.9")).unwrap_err();
|
||||
assert!(error.contains("may have rewritten it"), "{error}");
|
||||
assert!(
|
||||
error.contains(&format!("packages/{pinned}/9.9.json")),
|
||||
@@ -1136,7 +1257,7 @@ mod tests {
|
||||
|
||||
fs::create_dir_all(&lock.directory).unwrap();
|
||||
fs::copy(root.join("mojang.json"), &destination).unwrap();
|
||||
let manifest = import_manifest(&lock, &minecraft).unwrap();
|
||||
let manifest = import_manifest(&lock, &game_files(Some(&minecraft), "9.9")).unwrap();
|
||||
assert!(manifest.get("patches").is_none());
|
||||
assert_eq!(digest(&destination, "sha1").unwrap(), pinned);
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
@@ -1253,6 +1374,103 @@ mod tests {
|
||||
assert!(prepare().unwrap_err().starts_with("Missing "));
|
||||
}
|
||||
|
||||
/// ATLauncher keeps Mojang's version JSON in `configs/json/minecraft` and the client jar as
|
||||
/// a library; its folder, or one of its instances, prepares like the official launcher's,
|
||||
/// with the same pins.
|
||||
#[test]
|
||||
fn an_atlauncher_install_prepares() {
|
||||
let fixture = Imports::new();
|
||||
let old = fixture.imported(&fixture.source);
|
||||
let atlauncher = fixture.directory.join("ATLauncher");
|
||||
let put = |path: &str, data: &[u8]| {
|
||||
let path = atlauncher.join(path);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, data).unwrap();
|
||||
};
|
||||
let client = fs::read(old.join("jars/client.jar")).unwrap();
|
||||
put("libraries/net/minecraft/client/9.9/client-9.9.jar", &client);
|
||||
put("libraries/client.jar", b"client library");
|
||||
put("instances/Minecraft99/instance.json", b"{}");
|
||||
// A version JSON left without its jar does not hide the launcher's complete copy.
|
||||
put("instances/Minecraft99/versions/9.9/9.9.json", b"{}");
|
||||
let manifest = fs::read_to_string(old.join("manifest.json")).unwrap();
|
||||
let manifest = manifest.replacen('{', r#"{"javaVersion":{"majorVersion":25},"#, 1);
|
||||
put("configs/json/minecraft/9.9.json", manifest.as_bytes());
|
||||
let pinned = digest(&atlauncher.join("configs/json/minecraft/9.9.json"), "sha1").unwrap();
|
||||
let lock_path = fixture.target.join("research-lock.json");
|
||||
let text = fs::read_to_string(&lock_path).unwrap();
|
||||
let old_sha1 = digest(&old.join("manifest.json"), "sha1").unwrap();
|
||||
fs::write(&lock_path, text.replace(&old_sha1, &pinned)).unwrap();
|
||||
let lock = Lock::read(&fixture.target).unwrap();
|
||||
let server = old.join("jars/server.jar");
|
||||
let prepare = |dir: &Path| {
|
||||
let _ = fs::remove_dir_all(&lock.directory);
|
||||
import(&fixture.target, &lock, Some(dir), Some(&server), &|_| {})
|
||||
};
|
||||
|
||||
for chosen in [atlauncher.clone(), atlauncher.join("instances/Minecraft99")] {
|
||||
prepare(&chosen).unwrap();
|
||||
let artifacts = verify(&lock).unwrap();
|
||||
assert_eq!(fs::read(&artifacts.jars["client"]).unwrap(), client);
|
||||
assert_eq!(
|
||||
client_libraries(&lock, &artifacts.manifest).unwrap().len(),
|
||||
1
|
||||
);
|
||||
}
|
||||
let files = game_files(Some(&atlauncher), "9.9");
|
||||
assert_eq!(files.runtimes, atlauncher.join("runtimes/minecraft"));
|
||||
|
||||
// The pins gate it as they gate the official layout.
|
||||
put(
|
||||
"libraries/net/minecraft/client/9.9/client-9.9.jar",
|
||||
b"other",
|
||||
);
|
||||
assert!(prepare(&atlauncher)
|
||||
.unwrap_err()
|
||||
.contains("is not the pinned file"));
|
||||
put("libraries/net/minecraft/client/9.9/client-9.9.jar", &client);
|
||||
put(
|
||||
"configs/json/minecraft/9.9.json",
|
||||
manifest.replace(',', ", ").as_bytes(),
|
||||
);
|
||||
assert!(prepare(&atlauncher)
|
||||
.unwrap_err()
|
||||
.contains("may have rewritten it"));
|
||||
}
|
||||
|
||||
/// With no launcher's files in the chosen folder, the error names where Horizon looked and
|
||||
/// the launchers it reads.
|
||||
#[test]
|
||||
fn the_error_names_the_folders_looked_in() {
|
||||
let fixture = Imports::new();
|
||||
let empty = fixture.directory.join("instances/empty");
|
||||
fs::create_dir_all(&empty).unwrap();
|
||||
let lock = Lock::read(&fixture.target).unwrap();
|
||||
let error = import(&fixture.target, &lock, Some(&empty), None, &|_| {}).unwrap_err();
|
||||
assert!(error.starts_with(&format!(
|
||||
"Missing {}",
|
||||
empty.join("versions/9.9/9.9.json").display()
|
||||
)));
|
||||
assert!(error.contains("Horizon looked for 9.9 in:"), "{error}");
|
||||
assert!(error.contains(&format!("\n {} (the folder chosen)", empty.display())));
|
||||
assert!(error.contains(&format!(
|
||||
"\n {} (the launcher above it)",
|
||||
fixture.directory.display()
|
||||
)));
|
||||
assert!(error.contains("ATLauncher"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_launcher_horizon_reads_is_looked_in() {
|
||||
let launchers: Vec<_> = launcher_folders()
|
||||
.into_iter()
|
||||
.map(|(name, _)| name)
|
||||
.collect();
|
||||
for name in ["the official launcher", "ATLauncher", "the CurseForge app"] {
|
||||
assert!(launchers.contains(&name), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runs_without_only_netty_native_transports() {
|
||||
assert!(runs_without(
|
||||
|
||||
@@ -434,7 +434,7 @@ fn prepare_impl(options: &Options, log: Log, compile_only: bool) -> Result<PathB
|
||||
// Java first: nothing below can finish without it, and the player should hear it at once.
|
||||
let mut homes: Vec<PathBuf> = options.java_home.iter().cloned().collect();
|
||||
homes.extend(java::minecraft_runtimes(
|
||||
&artifacts::minecraft_dir(options.minecraft_dir.as_deref()).join("runtime"),
|
||||
&artifacts::game_files(options.minecraft_dir.as_deref(), &lock.version).runtimes,
|
||||
));
|
||||
let jdk = java::find_runtime(lock.java_major, &homes)?;
|
||||
let reused = if options.import {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The pinned version's sounds, title panorama, Unifont glyphs and built-in resource packs
|
||||
//! from the player's own official launcher install, each object checked against the asset index's SHA-1, copied into
|
||||
//! from the player's own launcher install, each object checked against the asset index's SHA-1, copied into
|
||||
//! `.local/horizon-client/<version>/assets` where the game reads them (tools/fetch_sounds.py and
|
||||
//! the tools/lab.py functions it called). Nothing is downloaded.
|
||||
|
||||
@@ -18,11 +18,11 @@ use std::path::{Path, PathBuf};
|
||||
fn launcher_assets(
|
||||
lock: &Lock,
|
||||
manifest: &Value,
|
||||
minecraft: &Path,
|
||||
files: &artifacts::GameFiles,
|
||||
cached_index: &Path,
|
||||
log: Log,
|
||||
) -> Result<(PathBuf, PathBuf, Vec<u8>), String> {
|
||||
let assets = minecraft.join("assets");
|
||||
let assets = files.folder.join("assets");
|
||||
let info = manifest
|
||||
.get("assetIndex")
|
||||
.ok_or("The version JSON has no assetIndex")?;
|
||||
@@ -44,7 +44,7 @@ fn launcher_assets(
|
||||
return Err(format!(
|
||||
"Missing {}. {}",
|
||||
index.display(),
|
||||
artifacts::launcher_hint(version)
|
||||
files.hint(version)
|
||||
));
|
||||
}
|
||||
let bytes = fs::read(&index).map_err(|e| format!("{}: {e}", index.display()))?;
|
||||
@@ -240,13 +240,13 @@ pub(crate) struct Assets {
|
||||
impl Assets {
|
||||
pub(crate) fn load(root: &Path, minecraft: Option<&Path>, log: Log) -> Result<Self, String> {
|
||||
let lock = Lock::read(root)?;
|
||||
let minecraft = artifacts::minecraft_dir(minecraft);
|
||||
let manifest = artifacts::import_manifest(&lock, &minecraft)?;
|
||||
let files = artifacts::game_files(minecraft, &lock.version);
|
||||
let manifest = artifacts::import_manifest(&lock, &files)?;
|
||||
let target = root.join(".local/horizon-client").join(&lock.version);
|
||||
let (store, index, bytes) = launcher_assets(
|
||||
&lock,
|
||||
&manifest,
|
||||
&minecraft,
|
||||
&files,
|
||||
&target.join("asset-index.json"),
|
||||
log,
|
||||
)?;
|
||||
@@ -677,7 +677,11 @@ mod tests {
|
||||
for missing in ["store", "install", "last-object"] {
|
||||
let f = Fixture::new(&format!("optional-panorama-{missing}"));
|
||||
// The JARs and manifest were imported earlier; the launcher need not remain.
|
||||
artifacts::import_manifest(&Lock::read(&f.root).unwrap(), &f.minecraft).unwrap();
|
||||
artifacts::import_manifest(
|
||||
&Lock::read(&f.root).unwrap(),
|
||||
&artifacts::game_files(Some(&f.minecraft), "9.9"),
|
||||
)
|
||||
.unwrap();
|
||||
let target = f.root.join(".local/horizon-client/9.9/assets");
|
||||
for name in PANORAMA {
|
||||
let path = target.join(name);
|
||||
|
||||
@@ -16,7 +16,7 @@ use serde_json::Value;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
fs::{self, File},
|
||||
io::{self, BufReader},
|
||||
io,
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
};
|
||||
@@ -582,8 +582,10 @@ fn fail(message: &str) -> io::Error {
|
||||
invalid(message)
|
||||
}
|
||||
|
||||
/// From the file's bytes in memory: several times faster than through a
|
||||
/// reader on gameplay-facts.json (55 MB), which a first start parses.
|
||||
fn read_json(path: &Path) -> io::Result<Value> {
|
||||
serde_json::from_reader(BufReader::new(File::open(path)?)).map_err(|e| invalid(e.to_string()))
|
||||
serde_json::from_slice(&fs::read(path)?).map_err(|e| invalid(e.to_string()))
|
||||
}
|
||||
|
||||
fn interned(cache: &mut HashMap<String, Arc<str>>, text: &str) -> Arc<str> {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user