Merge pull request #82 from ludovic111/fix/gamerules-persist-74

Game rules: save them with the world once, as they are now; save on Quit
This commit is contained in:
Ludovic Marie
2026-10-14 15:42:01 +02:00
committed by GitHub
5 changed files with 82 additions and 20 deletions
+28 -7
View File
@@ -819,6 +819,8 @@ struct Game<'a> {
/// This world is open to the network (game/lan.rs).
lan: Option<lan::LanHost>,
world_options: Option<lan_screen::WorldOptions>,
/// The world was saved for the application ending (`save_for_exit`).
saved_for_exit: bool,
/// The block a guest is acting on (game/lan_actions.rs).
forced_hit: Option<Hit>,
/// Level events of this tick for the guests, and the guest acting now.
@@ -5714,6 +5716,20 @@ impl Game<'_> {
}
Ok(())
}
/// Leaving the game with a world open (window closed, Quit, `quit`):
/// menu items go back (Player.closeContainer), then the world is saved,
/// once.
pub(super) fn save_for_exit(&mut self) -> Result<()> {
if self.title.is_some() || self.saved_for_exit {
return Ok(());
}
self.saved_for_exit = true;
self.close_container();
if self.remote.is_none() {
self.stats.custom("leave_game", 1);
}
self.save_game()
}
fn close_world(&mut self) -> Result<()> {
self.ambience.clear(&mut self.audio);
// updateLevelInEngines(null): every sound stops; the music manager
@@ -7108,6 +7124,8 @@ impl Game<'_> {
}
/// Copy the live player and world state into the `Level` that gets saved.
pub(super) fn sync_level(&mut self) {
// Level.write saves the game rules (game_rules.dat) with the rest.
self.level.game_rules = self.ui.rules.by_name();
self.level.selected_slot = self.selected as i32;
let mode = self.mode_id();
let level = &mut self.level;
@@ -7819,13 +7837,7 @@ impl ApplicationHandler for Game<'_> {
let result: Result<()> = (|| {
match event {
WindowEvent::CloseRequested => {
if self.title.is_none() {
self.close_container();
if self.remote.is_none() {
self.stats.custom("leave_game", 1);
}
self.save_game()?;
}
self.save_for_exit()?;
event_loop.exit();
}
WindowEvent::Resized(size) => {
@@ -8339,6 +8351,14 @@ impl ApplicationHandler for Game<'_> {
}
event_loop.set_control_flow(ControlFlow::Poll);
}
/// The application is ending. On macOS, Quit (Cmd+Q) ends it through
/// applicationWillTerminate without a CloseRequested; vanilla's GLFW
/// window turns it into a window close, so Minecraft.stop saves the world.
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
if let Err(e) = self.save_for_exit() {
eprintln!("Horizon: failed to save the world on exit: {e}");
}
}
}
pub fn run() -> Result<()> {
let Some(mut options) = Options::read()? else {
@@ -8694,6 +8714,7 @@ pub fn run() -> Result<()> {
remote: None,
lan: None,
world_options: None,
saved_for_exit: false,
forced_hit: None,
lan_events: Vec::new(),
lan_acting: None,
+3 -4
View File
@@ -642,14 +642,13 @@ impl Game<'_> {
self.build_registries();
self.sync_rules();
}
/// Save game rules, the clock and the difficulty beside level.dat.
/// Save the clock and the difficulty beside level.dat (Level.write saves
/// the game rules: a second writer of game_rules.dat could leave it with
/// the rules loaded when the world opened).
pub(super) fn save_world_state(&mut self) {
if self.world_root.as_os_str().is_empty() {
return;
}
if let Err(e) = self.ui.rules.save(&self.world_root) {
eprintln!("Horizon: failed to save game rules: {e}");
}
use horizon_world::nbt::Tag;
let c = self.ui.clock;
// The other clocks stay as saved; the overworld one keeps the fields Horizon
+1 -8
View File
@@ -480,14 +480,7 @@ impl Game<'_> {
ok()
}
"quit" => {
if self.title.is_none() {
// Player.closeContainer: menu items go back before saving.
self.close_container();
if self.remote.is_none() {
self.stats.custom("leave_game", 1);
}
self.save_game()?;
}
self.save_for_exit()?;
event_loop.exit();
ok()
}
+37
View File
@@ -164,6 +164,20 @@ impl GameRules {
}
ok
}
/// Every rule's value by name without namespace, as `save::Level` holds
/// them (booleans as 0 or 1).
pub fn by_name(&self) -> BTreeMap<String, i32> {
RULES
.iter()
.map(|r| {
let v = match self.values.get(r.name).copied().unwrap_or(r.default) {
Value::Bool(b) => i32::from(b),
Value::Int(i) => i,
};
(r.name.to_owned(), v)
})
.collect()
}
/// GameRuleMap codec: `{data: {"minecraft:<rule>": value...}, DataVersion}`.
pub fn to_nbt(&self) -> NamedTag {
let data: Vec<(horizon_world::nbt::JavaString, Tag)> = RULES
@@ -253,4 +267,27 @@ mod tests {
assert_eq!(GameRules::load(&dir), rules);
let _ = fs::remove_dir_all(dir);
}
/// The world's save (Level.write) writes the rules as they are now, and a
/// world opened again reads them back (#74).
#[test]
fn level_save_keeps_changed_rules() {
let dir =
std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let mut level = crate::save::Level::default();
level.write(&dir).unwrap();
// Rules changed while playing, then saved and loaded again.
let mut rules = GameRules::load(&dir);
assert_eq!(rules, GameRules::default());
assert!(rules.set("advance_time", Value::Bool(false)));
assert!(rules.set("advance_weather", Value::Bool(false)));
assert!(rules.set("random_tick_speed", Value::Int(0)));
level.game_rules = rules.by_name();
level.write(&dir).unwrap();
assert_eq!(GameRules::load(&dir), rules);
let read = crate::save::Level::read(&dir).unwrap();
assert_eq!(read.game_rules, rules.by_name());
assert_eq!(read.game_rule("advance_time"), 0);
let _ = fs::remove_dir_all(dir);
}
}
+13 -1
View File
@@ -46,6 +46,10 @@ SERVER = LOCAL / 'minecraft' / '26.3' / 'jars' / 'server.jar'
RUN = LOCAL / 'save-roundtrip' / 'run'
PORT = 25000 + (os.getpid() % 5000) + 1000
# Game rules Horizon's player changes before saving: rule -> (vanilla's value, Horizon's).
# The new value must be in Horizon's save, and nothing else may differ (#74).
HORIZON_RULES = {'max_entity_cramming': (24, 30)}
# Differences that do not change what vanilla reads: path pattern (list indices as [])
# -> reason. Anything else is a failure.
IGNORED = {
@@ -335,7 +339,9 @@ def horizon_resave(source, destination, bin_dir):
print(launch.stdout.strip())
if launch.returncode:
sys.exit('horizon failed to launch: ' + launch.stdout + launch.stderr)
steps = [['wait-ready', '240'], ['save-all'], ['quit']]
steps = [['wait-ready', '240']]
steps += [['chat', f'/gamerule {rule} {new}'] for rule, (_, new) in HORIZON_RULES.items()]
steps += [['save-all'], ['quit']]
for step in steps:
result = subprocess.run(ctl + step, cwd=destination, env=env, capture_output=True, text=True)
print(' '.join(step), '->', result.stdout.strip() or result.stderr.strip())
@@ -545,6 +551,12 @@ def compare_worlds(vanilla, horizon):
if rel.endswith('scoreboard.dat'):
va, hb = normalize_scoreboard(va), normalize_scoreboard(hb)
compare_dat(rel, va, hb, report)
for rule, (old, new) in HORIZON_RULES.items():
changed = (f'data/minecraft/game_rules.dat.data.minecraft:{rule}', old, new)
if changed in report:
report.remove(changed)
else:
report.append((changed[0], f'{new} set in Horizon', 'not saved'))
return report