Files
horizon-airdef/crates/horizon-client/src/lang.rs
T
Ludovic Marie 0d0378916b Resource packs: reload everything in game and merge stacked files like vanilla (#72)
Choosing packs in the Resource Packs screen only reloaded the GUI atlas
(and only when it kept its size), item models and languages; block
textures and models changed after a restart, and sounds, clouds and the
world border never did. Block textures were also squeezed to 16x16, and
the pack overlay took every file from the top pack, so a pack's own
en_us.json, sounds.json, font or atlas definition replaced vanilla's
instead of adding to it (all other text, or every vanilla sound, gone).

- Minecraft.reloadResourcePacks: rebuild block sprites and models, mesh
  tables, the shared atlas, item models, sounds, languages, GUI
  metadata, clouds.png and forcefield.png from the new overlay; swap the
  mesher's context (workers read it per job), mesh every loaded section
  again (LevelRenderer.allChanged) and build a renderer with the new
  textures. Nothing switches if loading fails.
- The block sprite array takes the largest texture's resolution (power
  of two, at most 256 MiB), so 32x/64x packs keep their detail;
  animations upload at that size.
- Files vanilla reads as resource stacks are merged in the overlay:
  ClientLanguage (keys override), SoundManager (sounds add up unless an
  event replaces; a sounds.json Gson rejects is skipped whole),
  FontManager (top pack's providers first), SpriteSourceList (sources
  bottom up). Languages are read from every namespace, not only
  minecraft.
- Missing or broken block textures use vanilla's missing texture; packs
  that still break startup fall back to the default resources
  (Minecraft.rollbackResourcePacks).
- Open Pack Folder opens the folder on macOS and Windows too.

tools/test_resource_pack_parity.py checks pack discovery, overlays,
filters, which pack provides a file and the merged languages, sounds,
fonts and atlases against vanilla's FolderRepositorySource,
MultiPackResourceManager and reload listeners.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 15:33:34 +02:00

237 lines
8.1 KiB
Rust

//! Languages (ClientLanguage / LanguageManager): `lang/<code>.json` from the
//! resource root and enabled packs layered over `en_us`, the language list
//! from `pack.mcmeta` `language` sections, and a process-wide current
//! language used by every screen.
use std::{
collections::{BTreeMap, HashMap},
sync::{Arc, RwLock},
};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LanguageInfo {
pub code: String,
pub name: String,
pub region: String,
pub bidirectional: bool,
}
impl LanguageInfo {
/// LanguageInfo.toComponent: "Name (Region)".
pub fn label(&self) -> String {
format!("{} ({})", self.name, self.region)
}
}
#[derive(Default)]
pub struct Language {
pub code: String,
map: HashMap<String, String>,
}
pub const DEFAULT: &str = "en_us";
static CURRENT: RwLock<Option<Arc<Language>>> = RwLock::new(None);
/// A source of resource files: the prepared root plus packs, highest priority last.
pub trait ResourceSource {
fn read(&self, path: &str) -> Option<Vec<u8>>;
/// The namespaces under `assets/` (resource packs may add their own).
fn namespaces(&self) -> Vec<String> {
vec!["minecraft".into()]
}
}
impl ResourceSource for std::path::PathBuf {
fn read(&self, path: &str) -> Option<Vec<u8>> {
std::fs::read(self.join(path)).ok()
}
fn namespaces(&self) -> Vec<String> {
std::fs::read_dir(self.join("assets"))
.into_iter()
.flatten()
.flatten()
.filter(|e| e.path().is_dir())
.filter_map(|e| e.file_name().to_str().map(str::to_owned))
.collect()
}
}
/// DeprecatedTranslationsInfo.applyToMap: drop removed keys, then move each
/// renamed key's text to its new key (a missing old key removes the new one).
pub fn apply_deprecated(map: &mut HashMap<String, String>, json: &[u8]) {
let Ok(info) = serde_json::from_slice::<serde_json::Value>(json) else {
return;
};
for key in info["removed"].as_array().into_iter().flatten() {
if let Some(k) = key.as_str() {
map.remove(k);
}
}
for (from, to) in info["renamed"].as_object().into_iter().flatten() {
let Some(to) = to.as_str() else { continue };
match map.remove(from) {
Some(value) => {
map.insert(to.to_owned(), value);
}
None => {
map.remove(to);
}
}
}
}
impl Language {
pub fn from_map(code: &str, map: HashMap<String, String>) -> Self {
Self {
code: code.to_owned(),
map,
}
}
/// ClientLanguage.loadFrom: en_us first, then the selected language, each
/// from every namespace and every source in priority order (later sources
/// override).
pub fn load(sources: &[&dyn ResourceSource], code: &str) -> Self {
let mut map = HashMap::new();
let mut codes = vec![DEFAULT];
if code != DEFAULT {
codes.push(code);
}
let namespaces: std::collections::BTreeSet<String> =
sources.iter().flat_map(|s| s.namespaces()).collect();
for c in codes {
for namespace in &namespaces {
for source in sources {
let Some(bytes) = source.read(&format!("assets/{namespace}/lang/{c}.json"))
else {
continue;
};
if let Ok(entries) = serde_json::from_slice::<HashMap<String, String>>(&bytes) {
map.extend(entries);
}
}
}
}
// DeprecatedTranslationsInfo.loadFromDefaultResource().applyToMap: the
// game's own deprecated.json, not a resource pack's.
if let Some(bytes) = sources
.iter()
.find_map(|s| s.read("assets/minecraft/lang/deprecated.json"))
{
apply_deprecated(&mut map, &bytes);
}
Self {
code: code.to_owned(),
map,
}
}
pub fn get(&self, key: &str) -> Option<&str> {
self.map.get(key).map(String::as_str)
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
}
/// Languages declared by `pack.mcmeta` files (the vanilla asset root first).
pub fn available(sources: &[&dyn ResourceSource]) -> Vec<LanguageInfo> {
let mut found: BTreeMap<String, LanguageInfo> = BTreeMap::new();
found.insert(
DEFAULT.into(),
LanguageInfo {
code: DEFAULT.into(),
name: "English".into(),
region: "US".into(),
bidirectional: false,
},
);
for source in sources {
for path in ["assets/pack.mcmeta", "pack.mcmeta"] {
let Some(bytes) = source.read(path) else {
continue;
};
let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes) else {
continue;
};
for (code, info) in value["language"].as_object().into_iter().flatten() {
// Only languages whose file exists somewhere are selectable.
let file = format!("assets/minecraft/lang/{code}.json");
if code != DEFAULT && !sources.iter().any(|s| s.read(&file).is_some()) {
continue;
}
found.insert(
code.clone(),
LanguageInfo {
code: code.clone(),
name: info["name"].as_str().unwrap_or(code).to_owned(),
region: info["region"].as_str().unwrap_or("").to_owned(),
bidirectional: info["bidirectional"].as_bool().unwrap_or(false),
},
);
}
}
}
found.into_values().collect()
}
pub fn set(language: Language) {
*CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(language));
}
pub fn current() -> Option<Arc<Language>> {
CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone()
}
pub fn code() -> String {
current().map_or_else(|| DEFAULT.to_owned(), |l| l.code.clone())
}
/// Language.getOrDefault: the translation, or the key itself.
pub fn get(key: &str) -> String {
current()
.and_then(|l| l.get(key).map(str::to_owned))
.unwrap_or_else(|| key.to_owned())
}
/// The translation, or `fallback` when the key is missing.
pub fn get_or(key: &str, fallback: &str) -> String {
current()
.and_then(|l| l.get(key).map(str::to_owned))
.unwrap_or_else(|| fallback.to_owned())
}
pub fn has(key: &str) -> bool {
current().is_some_and(|l| l.get(key).is_some())
}
/// I18n.get with plain string arguments.
pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> String {
crate::text::Text::tr(key, args).plain()
}
#[cfg(test)]
mod tests {
use super::*;
struct Mem(HashMap<String, Vec<u8>>);
impl ResourceSource for Mem {
fn read(&self, path: &str) -> Option<Vec<u8>> {
self.0.get(path).cloned()
}
}
#[test]
fn layers_selected_language_over_english() {
let base = Mem(HashMap::from([
("assets/minecraft/lang/en_us.json".into(), br#"{"a":"Apple","b":"Banana"}"#.to_vec()),
("assets/minecraft/lang/fr_fr.json".into(), br#"{"a":"Pomme"}"#.to_vec()),
("assets/pack.mcmeta".into(), r#"{"language":{"fr_fr":{"name":"Français","region":"France"},"de_de":{"name":"Deutsch","region":"Deutschland"}}}"#.as_bytes().to_vec()),
]));
let pack = Mem(HashMap::from([(
"assets/minecraft/lang/fr_fr.json".into(),
br#"{"b":"Banane"}"#.to_vec(),
)]));
let sources: [&dyn ResourceSource; 2] = [&base, &pack];
let fr = Language::load(&sources, "fr_fr");
assert_eq!(fr.get("a"), Some("Pomme"));
assert_eq!(fr.get("b"), Some("Banane"));
let langs = available(&sources);
// de_de has no file, so only English and French are offered.
assert_eq!(
langs.iter().map(|l| l.code.as_str()).collect::<Vec<_>>(),
["en_us", "fr_fr"]
);
assert_eq!(langs[1].label(), "Français (France)");
}
}