Choose situational music exactly as Minecraft.getSituationalMusic does

Situation captures the screen music, the menu without a player, End boss
music, creative abilities and underwater selection and the music volume;
the harness calls the real getSituationalMusic/getMusicVolume with a real
camera attribute probe for every dimension and biome.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 22:10:06 +02:00
parent b93f72c0da
commit 1357e2f01b
5 changed files with 300 additions and 20 deletions
@@ -0,0 +1,47 @@
//! `getSituationalMusic`/`getMusicVolume` through Horizon's `Situation` for
//! `tools/test_situational_music_parity.py`:
//! `situational_music_fixture ROOT INPUT OUTPUT`.
use horizon_client::music::{BackgroundMusic, Music, MusicTables, Situation};
use horizon_client::sound_events::normalize;
use std::io::Write;
fn main() {
let args: Vec<String> = std::env::args().collect();
let tables = MusicTables::load(std::path::Path::new(&args[1]));
let input = std::fs::read_to_string(&args[2]).expect("input");
let mut out = std::io::BufWriter::new(std::fs::File::create(&args[3]).expect("output"));
for line in input.lines() {
let f: Vec<&str> = line.split(' ').collect();
let in_world = f[1] == "1";
let (background, probe_volume) = if in_world {
(tables.background(f[2], f[3]), tables.volume(f[2], f[3]))
} else {
(BackgroundMusic::default(), 1.0)
};
let situation = Situation {
screen_music: (f[0] == "win").then(Music::credits),
in_world,
in_end: f[2] == "minecraft:the_end",
boss_music: f[4].contains("music"),
background: &background,
probe_volume,
creative: f[5] == "1" && f[6] == "1",
underwater: f[7] == "1",
};
let music = situation.music().map_or("-".to_owned(), |m| {
format!(
"{},{},{},{}",
normalize(&m.sound),
m.min_delay,
m.max_delay,
m.replace_current_music
)
});
writeln!(
out,
"{line} music={music} volume={:08x}",
situation.volume().to_bits()
)
.expect("write");
}
}
+33 -20
View File
@@ -1,7 +1,11 @@
//! `Minecraft.getSituationalMusic` and `getMusicVolume` for the music manager,
//! the local player's ambient sound handlers and the sound engine tick.
use super::Game;
use horizon_client::{blocks::Fluid, music::Music, sound_engine::TickContext};
use horizon_client::{
blocks::Fluid,
music::{BackgroundMusic, Music, Situation},
sound_engine::TickContext,
};
impl Game<'_> {
/// `Minecraft.tick` -> `MusicManager.tick`, once per client tick.
@@ -32,26 +36,35 @@ impl Game<'_> {
}
/// `getSituationalMusic` and `getMusicVolume`.
fn situational_music(&self) -> (Option<Music>, f32) {
// Title screen: no player, Musics.MENU at full volume.
if self.title.is_some() {
return (Some(Music::menu()), 1.0);
}
let Some(eye) = self.eye_position() else {
return (Some(Music::menu()), 1.0);
let empty = BackgroundMusic::default();
// The title screen has no player (and no level for the camera probe).
let eye = if self.title.is_some() {
None
} else {
self.eye_position()
};
let biome = self.biome_at(eye);
let dimension = self.dim.id();
let tables = &self.res.music;
let volume = tables.volume(dimension, biome);
// Minecraft.getSituationalMusic: the boss overlay's music in the End.
if self.dim == super::Dim::End && self.boss_music() {
return (Some(Music::end_boss()), volume);
}
let music = tables
.background(dimension, biome)
.select(self.creative, self.ambience.was_underwater())
.cloned();
(music, volume)
let (background, probe_volume) = match eye {
Some(eye) => {
let (dimension, biome) = (self.dim.id(), self.biome_at(eye));
let tables = &self.res.music;
(
tables.background(dimension, biome),
tables.volume(dimension, biome),
)
}
None => (empty, 1.0),
};
let situation = Situation {
screen_music: None,
in_world: eye.is_some(),
in_end: self.dim == super::Dim::End,
boss_music: self.boss_music(),
background: &background,
probe_volume,
creative: self.creative,
underwater: self.ambience.was_underwater(),
};
(situation.music(), situation.volume())
}
/// `BiomeManager.getNoiseBiomeAtPosition`: the quart cell holding a position.
fn biome_at(&self, p: [f64; 3]) -> &str {
+45
View File
@@ -107,6 +107,51 @@ impl Layer {
}
}
}
/// What `Minecraft.getSituationalMusic` and `getMusicVolume` read.
#[derive(Clone, Debug)]
pub struct Situation<'a> {
/// `Screen.getBackgroundMusic` of the open screen.
pub screen_music: Option<Music>,
/// `Minecraft.player != null`.
pub in_world: bool,
/// The player's level is the End.
pub in_end: bool,
/// `BossHealthOverlay.shouldPlayMusic`: a boss bar asks for music.
pub boss_music: bool,
/// `BACKGROUND_MUSIC` at the camera.
pub background: &'a BackgroundMusic,
/// `MUSIC_VOLUME` at the camera (1 without a level).
pub probe_volume: f32,
/// `abilities.instabuild && abilities.mayfly`.
pub creative: bool,
/// `LocalPlayer.isUnderWater`.
pub underwater: bool,
}
impl Situation<'_> {
/// `Minecraft.getSituationalMusic`.
pub fn music(&self) -> Option<Music> {
if let Some(music) = &self.screen_music {
return Some(music.clone());
}
if !self.in_world {
return Some(Music::menu());
}
if self.in_end && self.boss_music {
return Some(Music::end_boss());
}
self.background
.select(self.creative, self.underwater)
.cloned()
}
/// `Minecraft.getMusicVolume`.
pub fn volume(&self) -> f32 {
if self.screen_music.is_some() {
1.0
} else {
self.probe_volume
}
}
}
/// Music attributes by dimension type and biome.
#[derive(Clone, Debug, Default)]
pub struct MusicTables {
@@ -0,0 +1,130 @@
package dev.horizonlab.parity;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.SharedConstants;
import net.minecraft.client.Camera;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.Hud;
import net.minecraft.client.gui.components.BossHealthOverlay;
import net.minecraft.client.gui.components.LerpingBossEvent;
import net.minecraft.client.gui.screens.WinScreen;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.core.*;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.RegistryDataLoader;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.Bootstrap;
import net.minecraft.server.RegistryLayer;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.repository.ServerPacksSource;
import net.minecraft.server.packs.resources.MultiPackResourceManager;
import net.minecraft.sounds.Music;
import net.minecraft.tags.TagLoader;
import net.minecraft.world.BossEvent;
import net.minecraft.world.attribute.*;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Abilities;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.dimension.DimensionType;
import net.minecraft.world.phys.Vec3;
/**
* Calls the real Minecraft.getSituationalMusic and getMusicVolume on shells
* holding the open screen (none or the credits' WinScreen), the boss overlay's
* events, the player (its level's dimension, abilities and underwater state)
* and a real camera EnvironmentAttributeProbe over the dimension and biome's
* attribute layers from the vanilla data pack. Lines: "screen player
* dimension biome boss instabuild mayfly underwater".
*/
public final class VanillaSituationalMusicOracle {
static String music(Music m) {
return m == null ? "-" : m.sound().value().location() + "," + m.minDelay() + "," + m.maxDelay() + "," + m.replaceCurrentMusic();
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static void addBiome(EnvironmentAttributeSystem.Builder b, EnvironmentAttribute attr, Biome biome) {
b.addPositionalLayer(attr, (base, pos, w) -> biome.getAttributes().applyModifier(attr, base));
}
static LerpingBossEvent bar(boolean darken, boolean music) {
return new LerpingBossEvent(UUID.randomUUID(), Component.empty(), 1.0F, BossEvent.BossBarColor.PINK, BossEvent.BossBarOverlay.PROGRESS,
darken, music, false);
}
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
var repo = ServerPacksSource.createVanillaTrustedRepository();
repo.reload();
repo.setSelected(List.of("vanilla"));
var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected());
var layers = RegistryLayer.createRegistryAccess();
var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC));
var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags);
RegistryAccess.Frozen world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join();
staticTags.forEach(Registry.PendingTags::apply);
var dimensions = world.lookupOrThrow(Registries.DIMENSION_TYPE);
var biomes = world.lookupOrThrow(Registries.BIOME);
Minecraft mc = VanillaSoundRig.make(Minecraft.class);
Gui gui = VanillaSoundRig.make(Gui.class);
Hud hud = VanillaSoundRig.make(Hud.class);
BossHealthOverlay overlay = VanillaSoundRig.make(BossHealthOverlay.class);
Map<UUID, LerpingBossEvent> events = new LinkedHashMap<>();
VanillaSoundRig.set(overlay, BossHealthOverlay.class, "events", events);
VanillaSoundRig.set(hud, Hud.class, "bossOverlay", overlay);
VanillaSoundRig.set(gui, Gui.class, "hud", hud);
VanillaSoundRig.set(mc, Minecraft.class, "gui", gui);
GameRenderer renderer = VanillaSoundRig.make(GameRenderer.class);
Camera camera = VanillaSoundRig.make(Camera.class);
VanillaSoundRig.set(renderer, GameRenderer.class, "mainCamera", camera);
VanillaSoundRig.set(mc, Minecraft.class, "gameRenderer", renderer);
WinScreen credits = VanillaSoundRig.make(WinScreen.class);
try (var w = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8))) {
for (String line : Files.readAllLines(Path.of(args[0]), StandardCharsets.UTF_8)) {
String[] f = line.split(" ");
VanillaSoundRig.set(gui, Gui.class, "screen", f[0].equals("win") ? credits : null);
events.clear();
if (f[4].contains("dark")) events.put(UUID.randomUUID(), bar(true, false));
if (f[4].contains("music")) events.put(UUID.randomUUID(), bar(false, true));
var probe = new EnvironmentAttributeProbe();
VanillaSoundRig.set(camera, Camera.class, "attributeProbe", probe);
if (f[1].equals("1")) {
DimensionType dim = dimensions.getOrThrow(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse(f[2]))).value();
Biome biome = biomes.getOrThrow(ResourceKey.create(Registries.BIOME, Identifier.parse(f[3]))).value();
var b = EnvironmentAttributeSystem.builder();
b.addConstantLayer(dim.attributes());
for (EnvironmentAttribute<?> attr : biome.getAttributes().keySet()) addBiome(b, attr, biome);
ClientLevel level = VanillaSoundRig.make(ClientLevel.class);
VanillaSoundRig.set(level, ClientLevel.class, "environmentAttributes", b.build());
VanillaSoundRig.set(level, Level.class, "dimension", f[2].equals("minecraft:the_end") ? Level.END
: f[2].equals("minecraft:the_nether") ? Level.NETHER : Level.OVERWORLD);
VanillaSoundRig.set(probe, EnvironmentAttributeProbe.class, "level", level);
VanillaSoundRig.set(probe, EnvironmentAttributeProbe.class, "position", new Vec3(0.5, 64.0, 0.5));
LocalPlayer player = VanillaSoundRig.make(LocalPlayer.class);
VanillaSoundRig.set(player, Entity.class, "level", level);
var abilities = new Abilities();
abilities.instabuild = f[5].equals("1");
abilities.mayfly = f[6].equals("1");
VanillaSoundRig.set(player, Player.class, "abilities", abilities);
VanillaSoundRig.set(player, Player.class, "wasUnderwater", f[7].equals("1"));
mc.player = player;
} else {
mc.player = null;
}
w.printf("%s music=%s volume=%08x%n", line, music(mc.getSituationalMusic()), Float.floatToRawIntBits(mc.getMusicVolume()));
}
}
System.exit(0);
}
}
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Compare the situational music choice with the vanilla 26.3 client.
The oracle calls the real `Minecraft.getSituationalMusic` and
`getMusicVolume` with the open screen (none or the credits), the boss
overlay's bars (none, darkening, music), the player (absent, or in a dimension
with creative abilities and an underwater state) and a real camera
`EnvironmentAttributeProbe` over the dimension and biome attribute layers of
the vanilla data pack. Horizon's `Situation` with `MusicTables` answers the
same, for every dimension type x biome and every combination of the rest.
"""
import itertools
try:
from . import audio_harness as h
except ImportError:
import audio_harness as h
def fixtures():
data = h.RESOURCES / 'data/minecraft'
biomes = sorted('minecraft:' + p.stem for p in (data / 'worldgen/biome').glob('*.json'))
dimensions = ['minecraft:overworld', 'minecraft:the_nether', 'minecraft:the_end']
lines = []
for screen, boss in itertools.product(['none', 'win'], ['none', 'dark', 'music', 'dark+music']):
lines.append(f'{screen} 0 minecraft:overworld minecraft:plains {boss} 0 0 0')
for d, b in itertools.product(dimensions, biomes):
for screen, boss, instabuild, mayfly, water in itertools.product(['none', 'win'], ['none', 'dark', 'music'], '01', '01', '01'):
lines.append(f'{screen} 1 {d} {b} {boss} {instabuild} {mayfly} {water}')
return lines
def main():
lines = fixtures()
matched, report = h.run_harness(
'situational-music', 'VanillaSituationalMusicOracle', 'situational_music_fixture', ''.join(l + '\n' for l in lines),
extra_sources=[h.lab.ROOT / 'crates/horizon-client/src/music.rs'], rust_args=[h.RESOURCES],
scope='Real Minecraft.getSituationalMusic/getMusicVolume: screen music (credits), menu without a player, End boss music from '
'the boss overlay, BACKGROUND_MUSIC and MUSIC_VOLUME through a real camera EnvironmentAttributeProbe, creative abilities '
'(instabuild && mayfly) and underwater selection, for every dimension x biome.')
print(f'{matched:,} situational music lines match the pinned client: {report}', flush=True)
if __name__ == '__main__':
main()