Skip to main content

yog_cli/yres/
mod.rs

1//! `.yres` resource files — a mod's texts, images, sounds, files, colors,
2//! numbers and flags, like a C# project's `Resources/*.resx`. See
3//! Yog-IDLE's `docs/yres.md` for the format.
4//!
5//! `yog build` reads `resources/**/*.yres`: `<Set>.yres` is the neutral
6//! (en_us) file of resource set `<Set>`, `<Set>.<locale>.yres` its culture
7//! variants (texts only). It
8//!
9//! - writes the texts into `assets/<mod id>/lang/<locale>.json` (merged with
10//!   a hand-written one), `{name}`/`{0}` placeholders turned into `%1$s`;
11//! - bundles image/file/sound entries' files under `assets/<mod id>/...`
12//!   (sounds as Ogg Vorbis: `.ysound` events name them);
13//! - generates `obj/generated/resources/<Set>.g.rs` — a type per
14//!   set with a typed accessor per entry — and `resources.g.rs` including
15//!   them, pulled in as `crate::res` by `yog_api::resources!();`;
16//! - resolves `@<Set>.<name>` references for `.yui` screens and `yog.toml`.
17
18mod accessors;
19mod compile;
20mod load;
21mod names;
22mod outputs;
23mod placeholders;
24mod resource_ids;
25
26pub use compile::compile;
27pub(crate) use names::{accessor_name, default_key, name_problem};
28pub use outputs::write_sources;
29
30use crate::diagnostics::Diagnostic;
31use std::collections::{BTreeMap, HashMap};
32use std::path::{Path, PathBuf};
33
34/// The locale of the neutral `<Set>.yres` files.
35pub const NEUTRAL_LOCALE: &str = "en_us";
36/// Where resource files live, under the mod root.
37pub(crate) const RESOURCES_DIR: &str = yog_ids::project::RESOURCES;
38/// Where the generated accessors go, under the mod root.
39/// The file `yog_api::resources!()` includes; it includes one
40/// `resources/<Set>.g.rs` per set (shown under its `.yres` in Yog-IDLE).
41pub const GENERATED_FILE: &str = yog_ids::concatcp!(
42    yog_ids::project::GENERATED,
43    yog_ids::sep::PATH,
44    "resources.g.rs"
45);
46/// Where the per-set `<Set>.g.rs` files go.
47pub const GENERATED_DIR: &str =
48    yog_ids::concatcp!(yog_ids::project::GENERATED, yog_ids::sep::PATH, "resources");
49
50/// A generated file: path inside the `.yog` and its bytes.
51pub(crate) type Output = (String, Vec<u8>);
52
53pub use yog_formats::yres::{Entry, Kind, Value, parse, write};
54
55/// What `.yui` screens and `yog.toml` can refer to as `@<Set>.<name>`.
56#[derive(Debug, Clone, Default)]
57pub struct Refs {
58    /// `Set.name` → (translation key, neutral text).
59    pub(crate) texts: HashMap<String, (String, String)>,
60    /// `Set.name` → image source (`<mod id>:<texture>`).
61    pub(crate) images: HashMap<String, String>,
62    /// `Set.name` → color (`0xAARRGGBB`).
63    pub(crate) colors: HashMap<String, u32>,
64    /// `Set.name` → an image's picture, as the build writes it.
65    pub(crate) pictures: HashMap<String, Picture>,
66    /// `Set.name` → a sound's file as `sounds.json` names it (`<mod id>:<path>`).
67    pub(crate) sounds: HashMap<String, String>,
68}
69
70impl Refs {
71    /// Text `r`: its translation key and neutral words.
72    pub(crate) fn text(&self, r: &yog_data::Res) -> Result<&(String, String), String> {
73        self.texts
74            .get(&r.name())
75            .ok_or_else(|| format!("`{r}`: no text `{}` in resources/*.yres", r.name()))
76    }
77
78    /// Sound `r`: its file as `sounds.json` names it.
79    pub(crate) fn sound(&self, r: &yog_data::Res) -> Result<&str, String> {
80        self.sounds
81            .get(&r.name())
82            .map(String::as_str)
83            .ok_or_else(|| format!("`{r}`: no sound `{}` in resources/*.yres", r.name()))
84    }
85
86    /// Color `r` (`0xAARRGGBB`).
87    pub fn color(&self, r: &yog_data::Res) -> Result<u32, String> {
88        self.colors
89            .get(&r.name())
90            .copied()
91            .ok_or_else(|| format!("`{r}`: no color `{}` in resources/*.yres", r.name()))
92    }
93
94    /// The translation key text `t` names — `@lang:key`, a thing's name, a
95    /// `.yres` text; none for words, which aren't one.
96    pub(crate) fn key_of(&self, t: &yog_data::Text) -> Result<Option<String>, String> {
97        use yog_data::Text;
98        Ok(match t {
99            Text::Literal(_) => None,
100            Text::Lang(k) => Some(k.clone()),
101            Text::NameOf(r) => Some(yog_ids::lang_key(
102                &r.kind,
103                yog_formats::book::refs::bare(&r.id),
104            )),
105            Text::Res(r) => Some(self.text(r)?.0.clone()),
106        })
107    }
108}
109
110/// An image's picture: its PNG and the file the build writes it to — which
111/// a texture packed into an atlas takes the place of.
112#[derive(Debug, Clone, Default, PartialEq)]
113pub(crate) struct Picture {
114    pub(crate) png: Vec<u8>,
115    pub(crate) output: String,
116}
117
118/// Everything `yog build` makes of a mod's resources.
119#[derive(Debug, Default)]
120pub struct Compiled {
121    /// Files to add to the `.yog` (lang JSON, images, sounds, sounds.json) —
122    /// they replace a hand-written asset at the same path (merged into them).
123    /// The files it made: `(path in the .yog, bytes)`.
124    pub outputs: Vec<Output>,
125    /// `<Set>` → generated Rust source.
126    pub sources: BTreeMap<String, String>,
127    /// What screens and `yog.toml` can refer to (`@<Set>.<name>`).
128    pub refs: Refs,
129    /// What to warn of.
130    pub warnings: Vec<Diagnostic>,
131    /// Number of `.yres` files read.
132    pub files: usize,
133}
134
135/// Every `resources/**/*.yres` of the mod at `root`, sorted.
136pub(crate) fn find(root: &Path) -> Vec<PathBuf> {
137    yog_analysis::files::under(&root.join(RESOURCES_DIR), &|p| yog_ids::Format::Res.is(p))
138}
139
140/// What's wrong with `e`'s value for its type, if anything — the build's
141/// rule, which editors show too.
142pub(crate) fn value_problem(e: &Entry) -> Option<String> {
143    match (e.kind, &e.value) {
144        (k, Value::Bytes(_))
145            if k.holds_bytes()
146                && !yog_ids::valid_path(&e.name.replace('.', yog_ids::sep::PATH)) =>
147        {
148            Some(format!(
149                "{:?}: Minecraft resource paths are lower case — only a-z, 0-9, `_`, `-`, `.`",
150                e.name
151            ))
152        }
153        (k, Value::Bytes(_)) if k.holds_bytes() => None,
154        (k, _) if k.holds_bytes() => Some(format!(
155            "{:?}: a {} entry is bytes (`@bytes:…`)",
156            e.name,
157            k.name()
158        )),
159        (Kind::Color, _) => parse_color(e.text()).is_none().then(|| {
160            format!(
161                "{:?}: `{}` isn't a color — #RRGGBB or #AARRGGBB",
162                e.name,
163                e.text()
164            )
165        }),
166        (Kind::Number, Value::Num(_))
167        | (Kind::Bool, Value::Bool(_))
168        | (Kind::String, Value::Str(_)) => None,
169        (Kind::Number, _) => Some(format!("{:?}: a number", e.name)),
170        (Kind::Bool, _) => Some(format!("{:?}: true or false", e.name)),
171        (Kind::String, _) => Some(format!("{:?}: a text", e.name)),
172        (Kind::Image | Kind::File | Kind::Sound | Kind::Video, _) => None,
173    }
174}
175
176/// A color entry's value as ARGB, when it is one.
177pub(crate) fn color_of(e: &Entry) -> Option<u32> {
178    (e.kind == Kind::Color)
179        .then(|| parse_color(e.text()))
180        .flatten()
181}
182
183/// `#RRGGBB` / `#AARRGGBB`: a `.yres` color is written with its `#`.
184fn parse_color(s: &str) -> Option<u32> {
185    crate::ui::yui::color(s).filter(|_| s.trim().starts_with(crate::ui::yui::HEX_MARK))
186}
187
188/// Resolves a `yog.toml` value: `@<Set>.<name>` of a text → (neutral text,
189/// Some(key)); anything else as is. Errors on an unknown reference.
190pub fn resolve_text(refs: &Refs, value: &str) -> Result<(String, Option<String>), String> {
191    match value.strip_prefix('@') {
192        Some(rest) if rest.starts_with('@') => Ok((rest.to_string(), None)),
193        Some(rest) => match refs.texts.get(rest) {
194            Some((key, text)) => Ok((text.clone(), Some(key.clone()))),
195            None => Err(format!("`{value}`: no text `{rest}` in resources/*.yres")),
196        },
197        None => Ok((value.to_string(), None)),
198    }
199}
200
201/// Resolves a `yog.toml` image value: `@<Set>.<name>` → its image source.
202pub fn resolve_image(refs: &Refs, value: &str) -> Result<String, String> {
203    match value.strip_prefix('@') {
204        Some(rest) => refs
205            .images
206            .get(rest)
207            .cloned()
208            .ok_or_else(|| format!("`{value}`: no image `{rest}` in resources/*.yres")),
209        None => Ok(value.to_string()),
210    }
211}
212
213#[cfg(test)]
214mod tests;
215
216/// A resources error (`YB0003`), where it is to be said by the caller.
217pub(crate) fn problem(msg: impl std::fmt::Display) -> crate::diagnostics::Diagnostic {
218    crate::diagnostics::Diagnostic::error(yog_ids::build_problem::RESOURCES, msg)
219}
220
221/// A resources warning (`YB0003`).
222pub(crate) fn caveat(msg: impl std::fmt::Display) -> crate::diagnostics::Diagnostic {
223    crate::diagnostics::Diagnostic::warning(yog_ids::build_problem::RESOURCES, msg)
224}