From 132fb82e56b56792c86947824e37a5a9a3913d24 Mon Sep 17 00:00:00 2001 From: Philippe Date: Sun, 22 Nov 2026 20:24:45 +0100 Subject: [PATCH] PSO writer: edits in .oiv packages install and uninstall MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - rage-formats: XML → PSO (`Pso::from_xml`), using the original file as the template: its schema and other sections stay, the data and block map are rebuilt with the game's layout (one type per block, original block order, depth-first items, 0x70 padding, GTA V and RDR2 block maps and pointers). Structures, pointers, arrays (inline and external), strings, hashes, enums, flags, maps, vectors and matrices. CHKS is dropped when the data changes. - Reader fixes found by the round trip: RDR2 enum values are 16 bytes (flag and enum names were wrong), unknown enum values print as numbers, string arrays were escaped twice. - names::parse_value: the hash behind a printed name. - openrage verify --meta --rebuild and rpf8 --meta --rebuild: every PSO file to XML and back. GTA V Enhanced: 4,943 files, 3,973 byte-identical, all read back to the same XML. RDR2: 69,246 files, 52,656 identical, all others the same XML (2 not fully readable, skipped). - oiv: parses its XML commands and is applied like on the file's XML, then written back; preview shows the lines changed, journal and undo as for other edits. Names compared in XPaths are registered so hashes match them. - Docs: modding (supported kinds, what is still refused), cli, index table. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/openrage-app/src/oiv/install.rs | 102 ++- crates/openrage-app/src/oiv/package.rs | 78 ++- crates/openrage-app/tests/oiv.rs | 45 +- crates/openrage-cli/src/cli.rs | 6 + crates/openrage-cli/src/cmd/rdr2.rs | 46 +- crates/openrage-cli/src/cmd/verify.rs | 97 +++ crates/openrage-cli/src/main.rs | 18 +- crates/rage-formats/Cargo.toml | 1 + crates/rage-formats/src/names.rs | 35 ++ crates/rage-formats/src/pso.rs | 37 +- crates/rage-formats/src/pso/write.rs | 831 +++++++++++++++++++++++++ site/content/_index.md | 2 +- site/content/cli.md | 2 + site/content/modding.md | 12 +- 15 files changed, 1254 insertions(+), 59 deletions(-) create mode 100644 crates/rage-formats/src/pso/write.rs diff --git a/Cargo.lock b/Cargo.lock index 296e4c5..0e7dc6e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4550,6 +4550,7 @@ dependencies = [ "png", "rage-core", "rage-resource", + "roxmltree", "symphonia", "texpresso", "texture2ddecoder", diff --git a/crates/openrage-app/src/oiv/install.rs b/crates/openrage-app/src/oiv/install.rs index d8611e1..5d156b5 100644 --- a/crates/openrage-app/src/oiv/install.rs +++ b/crates/openrage-app/src/oiv/install.rs @@ -3,20 +3,20 @@ //! The same walk over the package script runs in two modes: a dry run that //! reads everything and reports what would happen (and what cannot work), and //! the real installation. Archive changes are batched per top-level archive -//! and written with the in-place editor; text and XML edits read the current -//! file (including earlier changes of the same package). All journal entries +//! and written with the in-place editor; text, XML and PSO edits read the +//! current file (including earlier changes of the same package). All journal entries //! carry the package's group, so the package can be uninstalled as a whole. use std::collections::{HashMap, HashSet}; use std::path::Path; use std::sync::Arc; -use anyhow::{Result, bail}; +use anyhow::{Context, Result, bail}; use rage_crypto::GtaVKeys; use rage_rpf::ArchiveWriter; use rage_rpf::vfs::{self, Node}; -use super::package::{Command, Package}; +use super::package::{Command, Package, XmlCmd}; use super::{text, xml}; use crate::install::{self, Op}; use crate::journal::{Entry, Journal}; @@ -55,8 +55,11 @@ fn norm(p: &str) -> String { fn escaping_path(cmd: &Command) -> Option<&str> { let raw = match cmd { Command::Add { target, .. } | Command::Delete { target } => target, - Command::Archive { path, .. } | Command::Text { path, .. } | Command::Xml { path, .. } => path, - Command::Pso { .. } | Command::Defragment { .. } => return None, + Command::Archive { path, .. } + | Command::Text { path, .. } + | Command::Xml { path, .. } + | Command::Pso { path, .. } => path, + Command::Defragment { .. } => return None, }; let n = norm(raw); (!n.is_empty() && vfs::safe_relative_path(&n).is_none()).then_some(raw.as_str()) @@ -70,6 +73,16 @@ fn join(a: &str, b: &str) -> String { } } +#[cfg(test)] +mod tests { + #[test] + fn xpath_literals() { + assert_eq!(super::quoted("/A/Item[Name = 'adder']/B[@x=\"1\"]"), ["adder", "1"]); + assert!(super::quoted("/A/B").is_empty()); + assert_eq!(super::changed_lines("a\n b\nc", "a\nb\nd\ne"), (2, 1)); + } +} + #[derive(Clone, Copy)] enum Encoding { Utf8, @@ -348,10 +361,19 @@ impl Run<'_> { self.step("Edit", &vpath, format!("{} XML command(s)", commands.len())); self.write_edited(scope, path, encode(&doc, enc))?; } - Command::Pso { path } => { - self.report - .blockers - .push(format!("{}: PSO/META edits are not supported yet", Self::vpath(scope, path))); + Command::Pso { path, commands } => { + let vpath = Self::vpath(scope, path); + let Some(bytes) = self.read(&vpath) else { + self.report.blockers.push(format!("PSO file {vpath} does not exist")); + continue; + }; + match edit_pso(&bytes, commands) { + Ok((data, detail)) => { + self.step("Edit", &vpath, detail); + self.write_edited(scope, path, data)?; + } + Err(e) => self.report.blockers.push(format!("{vpath}: {e:#}")), + } } Command::Defragment { archive } => { self.report.warnings.push(format!("defragmentation of {archive} skipped (only saves disk space)")); @@ -362,6 +384,66 @@ impl Run<'_> { } } +/// Applies XML edits to a PSO file: converts it to XML, edits that, and +/// writes it back with the file's own schema. Returns the new file and a +/// summary of the change for the preview. +fn edit_pso(bytes: &[u8], commands: &[XmlCmd]) -> Result<(Vec, String)> { + use rage_formats::pso; + if !pso::is_pso(bytes) { + bail!("not a PSO file (only PSO metadata can be edited with ; resource metadata cannot yet)"); + } + // Hashes print as names only when the name is known: names the XPaths + // compare with (`Item[Name = 'adder']`) are made known first, so they + // select what the author meant. + rage_formats::names::register(commands.iter().flat_map(|c| { + let xpath = match c { + XmlCmd::Add { xpath, .. } | XmlCmd::Replace { xpath, .. } | XmlCmd::Remove { xpath } => xpath, + }; + quoted(xpath) + })); + let file = pso::parse(bytes)?; + let (before, problems) = file.to_xml_with_limit(1 << 30); + if let Some(p) = problems.first() { + bail!("parts of the file cannot be read ({p}), so it cannot be written back safely"); + } + let mut doc = before.clone(); + for c in commands { + doc = xml::apply(&doc, c)?; + } + let data = file.from_xml(&doc).context("the edited XML does not fit the file's structure")?; + let (added, removed) = changed_lines(&before, &doc); + let detail = format!("{} XML command(s) on the PSO data: {added} line(s) added, {removed} removed", commands.len()); + Ok((data, detail)) +} + +/// The quoted literals of an XPath (`'…'` or `"…"`). +fn quoted(xpath: &str) -> Vec { + let mut out = Vec::new(); + let mut rest = xpath; + while let Some(start) = rest.find(['\'', '"']) { + let q = &rest[start..start + 1]; + let Some(len) = rest[start + 1..].find(q) else { break }; + out.push(rest[start + 1..start + 1 + len].to_owned()); + rest = &rest[start + 2 + len..]; + } + out +} + +/// Lines only in `after` and lines only in `before` (counted with repeats). +fn changed_lines(before: &str, after: &str) -> (usize, usize) { + let mut count: HashMap<&str, isize> = HashMap::new(); + // Trimmed, so that re-indented lines do not count as changed. + for l in before.lines() { + *count.entry(l.trim()).or_default() -= 1; + } + for l in after.lines() { + *count.entry(l.trim()).or_default() += 1; + } + let added = count.values().filter(|n| **n > 0).map(|n| *n as usize).sum(); + let removed = count.values().filter(|n| **n < 0).map(|n| n.unsigned_abs()).sum(); + (added, removed) +} + fn run(game_dir: &Path, keys: Option>, pkg: &Package, dry: bool) -> Result { let mut r = Run { game_dir, diff --git a/crates/openrage-app/src/oiv/package.rs b/crates/openrage-app/src/oiv/package.rs index 834110d..6fd1933 100644 --- a/crates/openrage-app/src/oiv/package.rs +++ b/crates/openrage-app/src/oiv/package.rs @@ -98,9 +98,11 @@ pub enum Command { path: String, commands: Vec, }, - /// PSO/META edits (``); need a PSO converter, not supported yet. + /// Edits of a binary PSO metadata file (``): converted to XML, edited + /// with the same commands as ``, and written back as PSO. Pso { path: String, + commands: Vec, }, /// Archive rebuild to reclaim space; optional, skipped. Defragment { @@ -275,33 +277,14 @@ fn parse_commands(source: &str, node: roxmltree::Node<'_, '_>) -> Result { - let mut commands = Vec::new(); - for x in c.children().filter(|x| x.is_element()) { - let xpath = attr(x, "xpath").context("XML command without xpath")?; - commands.push(match x.tag_name().name().to_ascii_lowercase().as_str() { - "add" => XmlCmd::Add { - append: match attr(x, "append") - .unwrap_or_else(|| "Last".into()) - .to_ascii_lowercase() - .as_str() - { - "first" => Append::First, - "before" => Append::Before, - "after" => Append::After, - _ => Append::Last, - }, - content: inner_xml(source, x), - xpath, - }, - "replace" => XmlCmd::Replace { content: inner_xml(source, x), xpath }, - "remove" => XmlCmd::Remove { xpath }, - other => bail!("unknown XML command <{other}>"), - }); - } - Command::Xml { path: attr(c, "path").context(" without path")?, commands } - } - "pso" => Command::Pso { path: attr(c, "path").unwrap_or_default() }, + "xml" => Command::Xml { + path: attr(c, "path").context(" without path")?, + commands: xml_commands(source, c)?, + }, + "pso" => Command::Pso { + path: attr(c, "path").context(" without path")?, + commands: xml_commands(source, c)?, + }, "defragmentation" => Command::Defragment { archive: attr(c, "archive").unwrap_or_default() }, other => bail!("unknown package command <{other}>"), }; @@ -310,6 +293,30 @@ fn parse_commands(source: &str, node: roxmltree::Node<'_, '_>) -> Result` or `` command. +fn xml_commands(source: &str, c: roxmltree::Node<'_, '_>) -> Result> { + let mut commands = Vec::new(); + for x in c.children().filter(|x| x.is_element()) { + let xpath = attr(x, "xpath").context("XML command without xpath")?; + commands.push(match x.tag_name().name().to_ascii_lowercase().as_str() { + "add" => XmlCmd::Add { + append: match attr(x, "append").unwrap_or_else(|| "Last".into()).to_ascii_lowercase().as_str() { + "first" => Append::First, + "before" => Append::Before, + "after" => Append::After, + _ => Append::Last, + }, + content: inner_xml(source, x), + xpath, + }, + "replace" => XmlCmd::Replace { content: inner_xml(source, x), xpath }, + "remove" => XmlCmd::Remove { xpath }, + other => bail!("unknown XML command <{other}>"), + }); + } + Ok(commands) +} + fn parse_assembly(text: &str) -> Result { let doc = roxmltree::Document::parse(text).context("assembly.xml is not valid XML")?; let root = doc.root_element(); @@ -414,6 +421,21 @@ mod tests { assert_eq!(text[1], TextCmd::Delete { line: "#*".into(), condition: Condition::Mask }); } + #[test] + fn parses_pso_edits() { + let pso = ASSEMBLY.replace( + "", + r#""#, + ); + let p = parse_assembly(&pso).unwrap(); + let Command::Pso { path, commands } = &p.commands[2] else { panic!("{:?}", p.commands[2]) }; + assert_eq!(path, "x64\\data\\carcols.ymt"); + assert_eq!(commands, &[XmlCmd::Remove { xpath: "/CVehicleModColors/kits/Item[1]".into() }]); + assert!( + parse_assembly(&ASSEMBLY.replace("", "")).is_err() + ); + } + #[test] fn rejects_other_games() { let other = ASSEMBLY.replace("target=\"Five\"", "target=\"IV\""); diff --git a/crates/openrage-app/tests/oiv.rs b/crates/openrage-app/tests/oiv.rs index 50e71ce..4a69ba9 100644 --- a/crates/openrage-app/tests/oiv.rs +++ b/crates/openrage-app/tests/oiv.rs @@ -18,11 +18,35 @@ fn fake_game(name: &str) -> PathBuf { w.add_file("common/data/dlclist.xml", DLCLIST.as_bytes().to_vec()).unwrap(); w.add_file("common/data/settings.txt", b"a=1\nb=2\n".to_vec()).unwrap(); w.add_file("common/data/old.dat", b"old".to_vec()).unwrap(); + w.add_file("common/data/peds.ymt", tiny_pso()).unwrap(); std::fs::write(root.join("update/update.rpf"), w.build().unwrap()).unwrap(); std::fs::write(root.join("GTA5.exe"), b"").unwrap(); root } +/// A PSO file like the game's: a list of two items (a hash and a float each), +/// the items in block 1 and the root structure in block 2. +fn tiny_pso() -> Vec { + use rage_core::hash::{jenkins_bytes, joaat}; + let h = |name: &str| jenkins_bytes(name.as_bytes()); + let (root, item) = (h("CPedModelInfo__InitDataList"), h("CPedModelInfo__InitData")); + let be = |values: &[u32]| values.iter().flat_map(|v| v.to_be_bytes()).collect::>(); + let mut psin = b"PSIN\0\0\0\0pppppppp".to_vec(); + psin.extend(be(&[joaat("adder"), 1.5f32.to_bits(), joaat("banshee"), 2f32.to_bits()])); + psin.extend(be(&[1, 0, 0x0002_0002, 0])); // pointer to block 1, count and capacity 2 + psin[4..8].copy_from_slice(&48u32.to_be_bytes()); + let mut pmap = b"PMAP".to_vec(); + pmap.extend(be(&[48, 2, 0x0002_7070, item, 16, 0, 16, root, 32, 0, 16])); + // Structure infos: entry count, length, 0, then (name, type << 24 | subtype << 16 | offset, key). + let root_info = be(&[2, 16, 0, 0x100, 0x0c00_0000, item, h("InitDatas"), 0x0d00_0000, 0]); + let item_info = be(&[2, 8, 0, h("Name"), 0x0b07_0000, 0, h("Radius"), 0x0700_0004, 0]); + let mut psch = b"PSCH".to_vec(); + psch.extend(be(&[28 + 36 + 36, 2, root, 28, item, 28 + 36])); + psch.extend(root_info); + psch.extend(item_info); + [psin, pmap, psch].concat() +} + fn package(assembly: &str, files: &[(&str, &[u8])]) -> Package { let mut buf = std::io::Cursor::new(Vec::new()); { @@ -65,6 +89,17 @@ const ASSEMBLY: &str = r#" b=42 c=3 + + + + + + + zentorno + + + + dlcpacks:/testmod/ @@ -92,6 +127,8 @@ fn installs_and_uninstalls() { assert!(actions.contains(&"Add plugin.asi".to_owned()), "{actions:?}"); assert!(actions.contains(&"Delete update/update.rpf/common/data/old.dat".to_owned())); assert!(actions.contains(&"Create update/x64/dlcpacks/testmod/dlc.rpf".to_owned())); + let pso_step = plan.steps.iter().find(|s| s.target.ends_with("peds.ymt")).expect("PSO edit planned"); + assert_eq!(pso_step.detail, "2 XML command(s) on the PSO data: 5 line(s) added, 1 removed"); // The dry run changed nothing. assert!(!game.join("mods").exists() && !game.join("plugin.asi").exists()); @@ -107,6 +144,11 @@ fn installs_and_uninstalls() { "{dlclist}" ); assert_eq!(read(&game, "update/x64/dlcpacks/testmod/dlc.rpf/setup2.xml").unwrap(), b""); + let peds = read(&game, "update/update.rpf/common/data/peds.ymt").unwrap(); + let (xml, errors) = rage_formats::pso::to_xml(&peds).unwrap(); + assert!(errors.is_empty(), "{errors:?}"); + assert!(xml.contains("") && xml.contains(""), "{xml}"); + assert_eq!(xml.matches("").count(), 3, "{xml}"); assert_eq!(std::fs::read(game.join("update/update.rpf")).unwrap(), original, "game archive untouched"); let undone = uninstall(&game, "Test Mod 1.0").unwrap(); @@ -115,6 +157,7 @@ fn installs_and_uninstalls() { assert!(!game.join("mods/update/x64/dlcpacks/testmod/dlc.rpf").exists()); assert!(!game.join("mods/update/update.rpf").exists()); assert_eq!(read(&game, "update/update.rpf/common/data/old.dat").unwrap(), b"old"); + assert_eq!(read(&game, "update/update.rpf/common/data/peds.ymt").unwrap(), tiny_pso()); } #[test] @@ -124,7 +167,7 @@ fn reports_blockers() { r#"createIfNotExist="False" type="RPF7"> "#, r#"createIfNotExist="False" type="RPF7"> - + "#, ); let pkg = package(&bad, &[("plugin.asi", b"ASI")]); diff --git a/crates/openrage-cli/src/cli.rs b/crates/openrage-cli/src/cli.rs index 2eac94e..08146a8 100644 --- a/crates/openrage-cli/src/cli.rs +++ b/crates/openrage-cli/src/cli.rs @@ -96,6 +96,8 @@ pub(crate) enum Command { /// With --textures: also rebuild every dictionary and check that it reads back identically. /// With --models: write every GTA V Enhanced drawable (.ydr) anew with its own meshes and /// check that it reads back identically. + /// With --meta: convert every PSO file (.ymt, .ymf, .pso, …) to XML and back, and check + /// that it comes out byte for byte the same or at least reads back to the same XML. /// GTA IV without --textures: rebuild the table of every .rpf package in memory and /// check that it matches the stored one byte for byte (nothing is written). #[arg(long)] @@ -208,6 +210,10 @@ pub(crate) enum Command { /// Instead of only reading files, convert all metadata (.ymap, .ytyp, .ymt, .ymf) to XML. #[arg(long, conflicts_with_all = ["textures", "models", "text"])] meta: bool, + /// With --meta: convert every PSO file to XML and back, and check that it comes out the + /// same bytes or at least reads back to the same XML. + #[arg(long, requires = "meta")] + rebuild: bool, /// Instead of only reading files, decode every sound of every audio container. #[arg(long, conflicts_with_all = ["textures", "models", "text", "meta"])] audio: bool, diff --git a/crates/openrage-cli/src/cmd/rdr2.rs b/crates/openrage-cli/src/cmd/rdr2.rs index 2aa2ed8..55de401 100644 --- a/crates/openrage-cli/src/cmd/rdr2.rs +++ b/crates/openrage-cli/src/cmd/rdr2.rs @@ -9,12 +9,14 @@ pub(crate) struct Checks { pub(crate) models: bool, pub(crate) texts: bool, pub(crate) meta: bool, + /// With `meta`: convert every PSO file to XML and back instead. + pub(crate) rebuild: bool, pub(crate) audio: bool, pub(crate) anims: bool, } pub(crate) fn cmd_rpf8(path: &Path, list: bool, checks: Checks) -> Result<()> { - let Checks { textures, models, texts: text, meta, audio, anims } = checks; + let Checks { textures, models, texts: text, meta, rebuild, audio, anims } = checks; use rage_rpf::rpf8::{Compression, Rpf8}; let keys = openrage_app::rdr2::load_keys()?; let start = if path.is_dir() { path } else { path.parent().unwrap_or(path) }; @@ -49,6 +51,9 @@ pub(crate) fn cmd_rpf8(path: &Path, list: bool, checks: Checks) -> Result<()> { textures: usize, /// Triangles of the models, or strings of the text tables. triangles: usize, + /// PSO files rebuilt byte for byte, and ones not fully readable. + identical: usize, + unreadable: usize, lines: Vec, } /// Parses a texture dictionary and decodes all its textures; returns how many. @@ -129,7 +134,7 @@ pub(crate) fn cmd_rpf8(path: &Path, list: bool, checks: Checks) -> Result<()> { Ok(Some((awc.sounds.len(), secs))) } fn walk(rpf: &Rpf8, depth: usize, list: bool, checks: Checks, t: &mut Tally) { - let Checks { textures, models, texts, meta, audio, anims } = checks; + let Checks { textures, models, texts, meta, rebuild, audio, anims } = checks; let h = rpf.header(); let Some(entries) = rpf.entries() else { return }; t.readable += 1; @@ -198,6 +203,32 @@ pub(crate) fn cmd_rpf8(path: &Path, list: bool, checks: Checks) -> Result<()> { } } } + } else if meta && rebuild { + if matches!(e.ext_id, 1 | 11 | 73 | 74) && !e.is_resource { + let result = rpf.read(e).map_err(|err| err.to_string()).and_then(|d| { + if rage_formats::pso::is_pso(&d) { + super::verify::pso_round_trip(&d, true).map(Some) + } else { + Ok(None) + } + }); + use super::verify::PsoRoundTrip; + match result { + Ok(None) => {} + Ok(Some(r)) => { + t.textures += 1; + match r { + PsoRoundTrip::Identical => t.identical += 1, + PsoRoundTrip::SameXml => {} + PsoRoundTrip::Unreadable => t.unreadable += 1, + } + } + Err(err) => { + t.failed += 1; + t.lines.push(format!("{indent}{name}: {err}")); + } + } + } } else if meta { // .ymap 73, .ytyp 74, .ymt 11, .ymf 1 if matches!(e.ext_id, 1 | 11 | 73 | 74) { @@ -307,6 +338,7 @@ pub(crate) fn cmd_rpf8(path: &Path, list: bool, checks: Checks) -> Result<()> { let (mut ok, mut nested, mut plain, mut entries_total, mut failed, mut empty) = (0, 0, 0, 0usize, 0, 0); let mut textures_total = 0; let mut triangles_total = 0; + let (mut identical, mut unreadable) = (0, 0); for (_, t) in &tallies { for l in &t.lines { outln!("{l}"); @@ -321,6 +353,8 @@ pub(crate) fn cmd_rpf8(path: &Path, list: bool, checks: Checks) -> Result<()> { failed += t.failed; textures_total += t.textures; triangles_total += t.triangles; + identical += t.identical; + unreadable += t.unreadable; } if textures { outln!("\n{textures_total} textures decoded"); @@ -331,7 +365,13 @@ pub(crate) fn cmd_rpf8(path: &Path, list: bool, checks: Checks) -> Result<()> { if text { outln!("\n{textures_total} text tables read ({triangles_total} strings)"); } - if meta { + if meta && rebuild { + outln!( + "\n{textures_total} PSO files converted to XML and back: {identical} identical, {} with other bytes but \ + the same XML, {unreadable} not fully readable (skipped)", + textures_total - identical - unreadable + ); + } else if meta { outln!("\n{textures_total} metadata files converted ({triangles_total} parts not read)"); } if audio { diff --git a/crates/openrage-cli/src/cmd/verify.rs b/crates/openrage-cli/src/cmd/verify.rs index 093fc23..8a7bd45 100644 --- a/crates/openrage-cli/src/cmd/verify.rs +++ b/crates/openrage-cli/src/cmd/verify.rs @@ -817,6 +817,103 @@ pub(crate) fn cmd_verify_meta(game_dir: &Path, within: &str, keys: Option Result { + use rage_formats::pso; + let parse = |d: &[u8]| if rdr2 { pso::parse_rdr2(d) } else { pso::parse(d) }; + let original = parse(data).map_err(|e| e.to_string())?; + let (xml, problems) = original.to_xml_with_limit(1 << 30); + if !problems.is_empty() { + return Ok(PsoRoundTrip::Unreadable); + } + let written = original.from_xml(&xml).map_err(|e| format!("writing: {e}"))?; + if written == data { + return Ok(PsoRoundTrip::Identical); + } + let (again, problems) = parse(&written).map_err(|e| format!("reading back: {e}"))?.to_xml_with_limit(1 << 30); + if let Some(p) = problems.first() { + return Err(format!("reading back: {p}")); + } + if again != xml { + let line = xml.lines().zip(again.lines()).position(|(a, b)| a != b).unwrap_or(0); + let show = |t: &str| t.lines().nth(line).unwrap_or("(end)").trim().chars().take(120).collect::(); + return Err(format!("XML differs at line {}: {} → {}", line + 1, show(&xml), show(&again))); + } + Ok(PsoRoundTrip::SameXml) +} + +pub(crate) fn cmd_verify_pso_rebuild(game_dir: &Path, within: &str, keys: Option>) -> Result<()> { + let starts = archive_roots(game_dir, within, keys)?; + let started = Instant::now(); + // Per archive: identical, same XML, unreadable, errors. + let all: Vec<(usize, usize, usize, Vec)> = starts + .par_iter() + .map(|(prefix, rpf, dir)| { + let (mut same, mut xml, mut unreadable, mut errors) = (0, 0, 0, Vec::new()); + let mut nested = Vec::new(); + vfs::walk( + rpf, + *dir, + prefix, + true, + &mut |a, id, p| { + let e = a.entry(id); + if e.is_dir() || e.is_archive() || e.resource_version().is_some() { + return; + } + if !openrage_app::metadata::is_metadata(&e.name) { + return; + } + let data = match a.read(id) { + Ok(d) => d, + Err(err) => return errors.push(format!("{p}: {err}")), + }; + if !rage_formats::pso::is_pso(&data) { + return; + } + match pso_round_trip(&data, false) { + Ok(PsoRoundTrip::Identical) => same += 1, + Ok(PsoRoundTrip::SameXml) => xml += 1, + Ok(PsoRoundTrip::Unreadable) => unreadable += 1, + Err(err) => errors.push(format!("{p}: {err}")), + } + }, + &mut |e| nested.push(e.to_string()), + ); + errors.extend(nested); + (same, xml, unreadable, errors) + }) + .collect(); + let same: usize = all.iter().map(|x| x.0).sum(); + let xml: usize = all.iter().map(|x| x.1).sum(); + let unreadable: usize = all.iter().map(|x| x.2).sum(); + let errors: Vec<&String> = all.iter().flat_map(|x| &x.3).collect(); + for e in errors.iter().take(40) { + outln!("FAIL {e}"); + } + outln!( + "{} PSO files: {same} identical, {xml} with other bytes but the same XML, {unreadable} not fully readable \ + (skipped), {} errors ({:.1}s)", + same + xml + unreadable + errors.len(), + errors.len(), + started.elapsed().as_secs_f32() + ); + if !errors.is_empty() { + bail!("{} PSO files do not convert back", errors.len()); + } + Ok(()) +} + pub(crate) fn hex(b: &[u8]) -> String { b.iter().map(|x| format!("{x:02x}")).collect::>().join(" ") } diff --git a/crates/openrage-cli/src/main.rs b/crates/openrage-cli/src/main.rs index e6a5d17..31fbe31 100644 --- a/crates/openrage-cli/src/main.rs +++ b/crates/openrage-cli/src/main.rs @@ -107,12 +107,17 @@ fn run() -> Result<()> { return Ok(()); } - if let Command::Rpf8 { path, list, textures, models, text, meta, audio, anims } = &cli.command { - return cmd_rpf8( - path, - *list, - Checks { textures: *textures, models: *models, texts: *text, meta: *meta, audio: *audio, anims: *anims }, - ); + if let Command::Rpf8 { path, list, textures, models, text, meta, rebuild, audio, anims } = &cli.command { + let checks = Checks { + textures: *textures, + models: *models, + texts: *text, + meta: *meta, + rebuild: *rebuild, + audio: *audio, + anims: *anims, + }; + return cmd_rpf8(path, *list, checks); } // Managing plugins needs no game; previews and actions use it when there is one. if let Command::Plugin(cmd) = &cli.command @@ -179,6 +184,7 @@ fn run() -> Result<()> { Command::Verify { path, particles: true, .. } => cmd_verify_particles(&game_dir, &path, keys), Command::Verify { path, text: true, .. } if gta4 => cmd_verify_gta4_text(&game_dir, &path), Command::Verify { path, text: true, .. } => cmd_verify_text(&game_dir, &path, keys), + Command::Verify { path, meta: true, rebuild: true, .. } => cmd_verify_pso_rebuild(&game_dir, &path, keys), Command::Verify { path, meta: true, .. } => cmd_verify_meta(&game_dir, &path, keys), Command::Verify { path, cutscenes: true, .. } if gta4 => cmd_verify_gta4_cutscenes(&game_dir, &path), Command::Verify { cutscenes: true, .. } => bail!("--cutscenes checks GTA IV cutscenes; this is not GTA IV"), diff --git a/crates/rage-formats/Cargo.toml b/crates/rage-formats/Cargo.toml index a70ff48..63b1c54 100644 --- a/crates/rage-formats/Cargo.toml +++ b/crates/rage-formats/Cargo.toml @@ -13,5 +13,6 @@ texture2ddecoder = "0.1" symphonia = { version = "0.6", default-features = false, features = ["mp3"] } lewton = { version = "0.10", default-features = false } thiserror.workspace = true +roxmltree.workspace = true flate2.workspace = true texpresso = { version = "2.0.2", features = ["rayon"] } diff --git a/crates/rage-formats/src/names.rs b/crates/rage-formats/src/names.rs index 54003f4..3718e55 100644 --- a/crates/rage-formats/src/names.rs +++ b/crates/rage-formats/src/names.rs @@ -82,6 +82,37 @@ pub fn value(hash: u32) -> String { lookup(hash, false).unwrap_or_else(|| format!("hash_{hash:08X}")) } +/// Built-in names to their hashes (a name listed under several hashes keeps the first). +fn builtin_reverse() -> &'static HashMap<&'static str, u32> { + static TABLE: OnceLock> = OnceLock::new(); + TABLE.get_or_init(|| { + let mut by_hash: Vec<(u32, &str)> = builtin().iter().map(|(h, n)| (*h, *n)).collect(); + by_hash.sort_unstable(); + let mut map = HashMap::new(); + for (h, n) in by_hash { + map.entry(n).or_insert(h); + } + map + }) +} + +/// The hash behind text written by [`value`]: `hash_XXXXXXXX`, a registered +/// or built-in name, or else the lowercase joaat of the text (how the games +/// hash asset names), so a new name typed into the XML gets its usual hash. +pub fn parse_value(text: &str) -> u32 { + if let Some(h) = text.strip_prefix("hash_").and_then(|h| u32::from_str_radix(h, 16).ok()) { + return h; + } + if text.is_empty() { + return 0; + } + let lower = joaat(text); + if extra().read().ok().is_some_and(|m| m.get(&lower).is_some_and(|n| n == text)) { + return lower; + } + builtin_reverse().get(text).copied().unwrap_or(lower) +} + /// The hash a name in the XML stands for (`hash_XXXXXXXX` or a name). pub fn parse(text: &str) -> u32 { match text.strip_prefix("hash_").and_then(|h| u32::from_str_radix(h, 16).ok()) { @@ -108,6 +139,10 @@ mod tests { assert_eq!(parse("hash_00000001"), 1); assert_eq!(parse("AABB"), jenkins_bytes(b"AABB")); assert_eq!(parse("adder"), 0xB779_A091); + for h in [jenkins_bytes(b"CMapData"), jenkins_bytes(b"aabb"), 0x1234_5678, 0] { + assert_eq!(parse_value(&value(h)), h); + } + assert_eq!(parse_value("adder"), 0xB779_A091); } #[test] diff --git a/crates/rage-formats/src/pso.rs b/crates/rage-formats/src/pso.rs index 91e0091..a17623f 100644 --- a/crates/rage-formats/src/pso.rs +++ b/crates/rage-formats/src/pso.rs @@ -7,8 +7,10 @@ //! (structure name, offset, unused, length). //! * `PSCH`: schema: count, (name, offset) index, then structure infos //! (`type<<24 | count`, length, unused, 12-byte entries: name, type, subtype, -//! offset u16, reference key) and enum infos (`type<<24 | count`, (name, value)). -//! * `STRF`, `STRS`, `STRE`, `PSIG`, `CHKS`: strings and checksums (not needed). +//! offset u16, reference key) and enum infos (`type<<24 | count`, (name, value); +//! RDR2 has 8 zero bytes between name and value). +//! * `STRF`, `STRS`, `STRE`, `PSIG`, `CHKS`: strings and checksums (not needed +//! to read; kept as they are when the file is written back, see [`Pso::from_xml`]). //! //! Pointers are 8 bytes; the first big-endian u32 holds the 1-based block //! (bits 0–11) and the offset (bits 12–31). @@ -20,6 +22,8 @@ use std::collections::HashMap; use crate::names; use crate::xml::{self, Writer}; +mod write; + pub const MAGIC: &[u8; 4] = b"PSIN"; const ARRAYINFO: u32 = 0x100; @@ -99,6 +103,11 @@ pub struct Pso { enums: HashMap>, /// Bit where the offset of a pointer starts: 12 (GTA V) or 20 (RDR2). offset_shift: u32, + /// Every section of the file as it was (ident and whole section), in order. + sections: Vec<([u8; 4], Vec)>, + /// Structures that describe the key/item pairs of maps (GTA V), with + /// their names; one per map type, all usually named `0x100`. + pairs: Vec<(u32, StructInfo)>, } pub fn is_pso(data: &[u8]) -> bool { @@ -170,6 +179,7 @@ fn parse_with(file: &[u8], offset_shift: u32) -> Result { let mut data = None; let mut map = None; let mut schema = None; + let mut sections = Vec::new(); let mut pos = 0; while pos + 8 <= file.len() { let ident: [u8; 4] = file[pos..pos + 4].try_into().unwrap_or_default(); @@ -178,6 +188,7 @@ fn parse_with(file: &[u8], offset_shift: u32) -> Result { return Err(err(format!("section {} has bad length {len}", String::from_utf8_lossy(&ident)))); } let section = &file[pos..pos + len]; + sections.push((ident, section.to_vec())); match &ident { b"PSIN" => data = Some(section), b"PMAP" => map = Some(section), @@ -209,6 +220,8 @@ fn parse_with(file: &[u8], offset_shift: u32) -> Result { let mut structs = HashMap::new(); let mut enums = HashMap::new(); + let mut pairs = Vec::new(); + let (key_name, item_name) = (names::parse("Key"), names::parse("Item")); let n = u32_at(schema, 8).map_err(err)? as usize; for i in 0..n.min(0x10000) { let name = u32_at(schema, 12 + i * 8).map_err(err)?; @@ -228,20 +241,26 @@ fn parse_with(file: &[u8], offset_shift: u32) -> Result { key: u32_at(schema, p + 8).map_err(err)?, }); } - structs.entry(name).or_insert(StructInfo { length, entries }); + let info = StructInfo { length, entries }; + if info.find(key_name).is_some() && info.find(item_name).is_some() { + pairs.push((name, info.clone())); + } + structs.entry(name).or_insert(info); } 1 => { + // GTA V: (name, value) pairs; RDR2: name, 8 zero bytes, value. + let (size, value_at) = if offset_shift == 20 { (16, 12) } else { (8, 4) }; let mut values = Vec::new(); for e in 0..(x & 0xFF_FFFF) as usize { - let p = off + 4 + e * 8; - values.push((u32_at(schema, p).map_err(err)?, u32_at(schema, p + 4).map_err(err)? as i32)); + let p = off + 4 + e * size; + values.push((u32_at(schema, p).map_err(err)?, u32_at(schema, p + value_at).map_err(err)? as i32)); } enums.entry(name).or_insert(values); } t => return Err(err(format!("unknown schema element type {t}"))), } } - Ok(Pso { data: data.to_vec(), root_block, blocks, structs, enums, offset_shift }) + Ok(Pso { data: data.to_vec(), root_block, blocks, structs, enums, offset_shift, sections, pairs }) } /// Parses a PSO file and writes it as XML (see [`Pso::to_xml`]). @@ -291,12 +310,12 @@ impl Pso { w.finish() } + /// The name of an enum value; a value the enum does not list as its number. fn enum_name(&self, key: u32, value: i32) -> String { self.enums .get(&key) .and_then(|v| v.iter().find(|(_, x)| *x == value)) - .map(|(n, _)| names::field(*n)) - .unwrap_or_default() + .map_or_else(|| value.to_string(), |(n, _)| names::field(*n)) } #[allow(clippy::too_many_arguments)] @@ -641,7 +660,7 @@ impl Pso { .map(|b| { let (id, off) = self.unpack(ptr_at(b, 0).unwrap_or(0)); let len = (item.sub == 3).then(|| u16::from_be_bytes([b[8], b[9]]) as usize); - xml::escape(&self.string_at(id, off, len).unwrap_or_default()) + self.string_at(id, off, len).unwrap_or_default() }) .collect(); w.item_array(level, ename, &v); diff --git a/crates/rage-formats/src/pso/write.rs b/crates/rage-formats/src/pso/write.rs new file mode 100644 index 0000000..e2fab34 --- /dev/null +++ b/crates/rage-formats/src/pso/write.rs @@ -0,0 +1,831 @@ +//! XML → PSO: builds the data of a PSO file from the XML [`Pso::to_xml`] +//! writes, using the structure and enum infos of the file it came from. +//! +//! The XML does not describe the layout, so the original file is the +//! template: its schema (`PSCH`) and the other sections are written back +//! unchanged, and only the data (`PSIN`) and its block map (`PMAP`) are +//! rebuilt. Like the game's own files, every block holds one type (a +//! structure, or characters, hashes, pointers, …); blocks keep the order the +//! original had, and inside a block the items follow in the order they are +//! met walking the XML depth first. A file read back unchanged therefore +//! comes out byte for byte the same in most cases. +//! +//! The checksum section (`CHKS`) covers the data by an unknown method; it is +//! kept when the data comes out unchanged and left out otherwise, as +//! CodeWalker does for the PSO files it writes. + +use std::collections::HashMap; + +use roxmltree::{Document, Node}; + +use super::{ARRAYINFO, Entry, Pso, PsoError, StructInfo, ty}; +use crate::names; + +type R = Result; + +/// Blocks of characters (strings), named after the data type, as the game's files do. +const CHARS: u32 = ty::SBYTE as u32; +/// Blocks of 8-byte structure pointers. +const POINTERS: u32 = ty::STRUCTURE as u32; +/// Blocks of 32-bit hashes and integers. +const UINTS: u32 = ty::UINT as u32; + +/// Blocks of counted string pointers (16 bytes each); the name is what the game's files use. +const COUNTED_STRINGS: u32 = 0xC8; + +/// Pointer offsets have 20 bits in GTA V's layout. +const MAX_OFFSET: usize = 1 << 20; + +struct Buf { + name: u32, + data: Vec, +} + +/// A pointer to patch once the blocks have their final numbers. +struct Fix { + block: usize, + at: usize, + target: usize, + offset: usize, +} + +struct Builder<'a> { + pso: &'a Pso, + /// Structure names as the XML writes them. + struct_names: HashMap, + /// Enum value names per enum. + enum_values: HashMap>, + blocks: Vec, + by_name: HashMap, + fixes: Vec, +} + +fn element_children<'a, 'i>(node: Node<'a, 'i>) -> impl Iterator> { + node.children().filter(Node::is_element) +} + +fn text(node: Node<'_, '_>) -> String { + node.children().filter(Node::is_text).filter_map(|t| t.text()).collect() +} + +fn attr<'a>(node: Node<'a, '_>, name: &str) -> R<&'a str> { + node.attribute(name).ok_or_else(|| format!("<{}> has no {name}", node.tag_name().name())) +} + +fn value<'a>(node: Node<'a, '_>) -> R<&'a str> { + attr(node, "value") +} + +/// An integer as the XML writes them: decimal (maybe negative) or `0x` hex. +fn int(s: &str) -> R { + let t = s.trim(); + let parsed = match t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) { + Some(hex) => i128::from_str_radix(hex, 16), + None => t.parse::(), + }; + parsed.map_err(|_| format!("\"{s}\" is not a number")) +} + +fn float(s: &str) -> R { + s.trim().parse::().map_err(|_| format!("\"{s}\" is not a number")) +} + +/// The numbers of a raw array (`1 2 3`, or vectors `1, 2, 3` one to a line). +fn tokens(node: Node<'_, '_>) -> Vec { + text(node).split(|c: char| c.is_whitespace() || c == ',').filter(|t| !t.is_empty()).map(str::to_owned).collect() +} + +fn vector(node: Node<'_, '_>, n: usize) -> R> { + ["x", "y", "z", "w"][..n].iter().map(|a| float(attr(node, a)?)).collect() +} + +/// Largest alignment an item of `size` bytes needs (at most 16). +fn align_of(size: usize) -> usize { + if size == 0 { 1 } else { (1 << size.trailing_zeros()).min(16) } +} + +impl<'a> Builder<'a> { + fn new(pso: &'a Pso) -> Self { + Builder { + pso, + struct_names: pso.structs.keys().map(|h| (names::field(*h), *h)).collect(), + enum_values: HashMap::new(), + blocks: Vec::new(), + by_name: HashMap::new(), + fixes: Vec::new(), + } + } + + fn is_rdr2(&self) -> bool { + self.pso.offset_shift == 20 + } + + /// Reserves `size` zero bytes in the block for `name`; returns (block, offset). + fn alloc(&mut self, name: u32, size: usize, align: usize) -> (usize, usize) { + let bi = *self.by_name.entry(name).or_insert_with(|| { + self.blocks.push(Buf { name, data: Vec::new() }); + self.blocks.len() - 1 + }); + let data = &mut self.blocks[bi].data; + let off = data.len().next_multiple_of(align.max(1)); + data.resize(off + size, 0); + (bi, off) + } + + fn put(&mut self, bi: usize, at: usize, bytes: &[u8]) -> R<()> { + let data = &mut self.blocks[bi].data; + let dst = data.get_mut(at..at + bytes.len()).ok_or_else(|| format!("write at {at:#x} beyond its block"))?; + dst.copy_from_slice(bytes); + Ok(()) + } + + fn pointer(&mut self, block: usize, at: usize, target: usize, offset: usize) { + self.fixes.push(Fix { block, at, target, offset }); + } + + fn struct_info(&self, hash: u32) -> R<&'a StructInfo> { + self.pso.structs.get(&hash).ok_or_else(|| format!("structure info {} not found", names::field(hash))) + } + + fn struct_named(&self, name: &str) -> R { + self.struct_names.get(name).copied().ok_or_else(|| format!("unknown structure type \"{name}\"")) + } + + fn enum_value(&mut self, key: u32, name: &str) -> R { + let pso = self.pso; + let values = self.enum_values.entry(key).or_insert_with(|| { + pso.enums.get(&key).map(|v| v.iter().map(|(n, x)| (names::field(*n), *x)).collect()).unwrap_or_default() + }); + match values.get(name.trim()) { + Some(v) => Ok(*v), + None if name.trim().is_empty() => Ok(0), + None => int(name).map(|v| v as i32).map_err(|_| format!("\"{name}\" is not a value of the enum")), + } + } + + /// A string's characters in the character block; returns (block, offset). + fn chars(&mut self, s: &str) -> (usize, usize) { + let (bi, off) = self.alloc(CHARS, s.len() + 1, 1); + self.blocks[bi].data[off..off + s.len()].copy_from_slice(s.as_bytes()); + (bi, off) + } + + /// A structure of type `hash` at `off` in block `bi`, its fields from `node`'s children. + fn structure(&mut self, bi: usize, off: usize, hash: u32, node: Node<'_, '_>, depth: usize) -> R<()> { + if depth > 64 { + return Err("structures nested too deeply".into()); + } + let info = self.struct_info(hash)?; + let mut fields: Vec<(String, Node<'_, '_>)> = + element_children(node).map(|c| (c.tag_name().name().to_owned(), c)).collect(); + if let Some((_, e)) = fields.iter().find(|(n, _)| n == "error") { + return Err(format!("the XML holds an error from reading the original: {}", text(*e))); + } + for entry in &info.entries { + if entry.name == ARRAYINFO { + continue; + } + let name = names::field(entry.name); + let Some(i) = fields.iter().position(|(n, _)| *n == name) else { continue }; + let (_, child) = fields.remove(i); + self.entry(bi, off, entry, info, child, depth).map_err(|e| format!("{name}: {e}"))?; + } + match fields.first() { + Some((n, _)) => Err(format!("{} has no field {n}", names::field(hash))), + None => Ok(()), + } + } + + /// One field of a structure at `base` in block `bi`. + fn entry( + &mut self, + bi: usize, + base: usize, + e: &Entry, + info: &StructInfo, + node: Node<'_, '_>, + depth: usize, + ) -> R<()> { + let at = base + e.offset; + match e.kind { + ty::ARRAY => self.array(bi, base, e, info, node, depth)?, + ty::BOOL => { + let v = match value(node)? { + "true" | "True" | "1" => 1u8, + "false" | "False" | "0" => 0, + other => return Err(format!("\"{other}\" is not true or false")), + }; + self.put(bi, at, &[v])?; + } + ty::SBYTE | ty::UBYTE => self.put(bi, at, &[int(value(node)?)? as u8])?, + ty::SSHORT | ty::USHORT | ty::HFLOAT => self.put(bi, at, &(int(value(node)?)? as u16).to_be_bytes())?, + ty::SINT | ty::UINT => self.put(bi, at, &(int(value(node)?)? as u32).to_be_bytes())?, + ty::LONG | ty::ULONG => self.put(bi, at, &(int(value(node)?)? as u64).to_be_bytes())?, + ty::ENUM => { + let sub = if self.is_rdr2() { e.sub.saturating_sub(1) } else { e.sub }; + let v = self.enum_value(e.key, &text(node))?; + match sub { + 0 => self.put(bi, at, &(v as u32).to_be_bytes())?, + 1 => self.put(bi, at, &(v as u16).to_be_bytes())?, + 2 => self.put(bi, at, &[v as u8])?, + s => return Err(format!("unexpected enum subtype {s}")), + } + } + ty::FLAGS => self.flags(bi, at, e, info, node)?, + ty::FLOAT => self.put(bi, at, &float(value(node)?)?.to_be_bytes())?, + ty::FLOAT2 => self.floats(bi, at, &vector(node, 2)?)?, + ty::FLOAT3 | ty::FLOAT3A | ty::FLOAT4A => self.floats(bi, at, &vector(node, 3)?)?, + ty::FLOAT4 | ty::VEC4V => self.floats(bi, at, &vector(node, 4)?)?, + ty::MATRIX44 => { + let v: Vec = tokens(node).iter().map(|t| float(t)).collect::>()?; + if v.len() != 16 { + return Err(format!("a matrix needs 16 numbers, not {}", v.len())); + } + self.floats(bi, at, &v)?; + } + ty::STRING => self.string(bi, at, e, &text(node))?, + ty::STRUCTURE => match e.sub { + 0 => self.structure(bi, at, e.key, node, depth + 1)?, + 3 | 4 => { + if let Some(t) = node.attribute("type") { + let actual = self.struct_named(t)?; + let len = self.struct_info(actual)?.length; + let (pb, poff) = self.alloc(actual, len, align_of(len)); + self.pointer(bi, at, pb, poff); + self.structure(pb, poff, actual, node, depth + 1)?; + } + } + s => return Err(format!("unexpected structure subtype {s}")), + }, + ty::OPAQUE16 => { + let hex = value(node)?; + let bytes: Vec = (0..16) + .map(|i| hex.get(i * 2..i * 2 + 2).and_then(|b| u8::from_str_radix(b, 16).ok())) + .collect::>() + .ok_or_else(|| format!("\"{hex}\" is not 16 bytes of hex"))?; + self.put(bi, at, &bytes)?; + } + ty::MAP => self.map(bi, at, e, info, node, depth)?, + other => return Err(format!("unexpected data type {other:#04x}")), + } + Ok(()) + } + + /// A map, mirroring [`Pso::map_node`]: a header (`0x01000000`, pointer + /// to the pairs, count, capacity) and the key/item pairs in a block. + fn map(&mut self, bi: usize, at: usize, e: &Entry, info: &StructInfo, node: Node<'_, '_>, depth: usize) -> R<()> { + if e.sub != 1 { + return Err(format!("unexpected map subtype {}", e.sub)); + } + let key_info = *info.entries.get((e.key >> 16) as usize & 0xFFF).ok_or("map Key entry missing")?; + let item_info = *info.entries.get(e.key as usize & 0xFFF).ok_or("map Item entry missing")?; + self.put(bi, at, &[1])?; + let items: Vec<_> = element_children(node).collect(); + let count = + u16::try_from(items.len()).map_err(|_| format!("{} pairs are more than a map holds", items.len()))?; + self.put(bi, at + 16, &count.to_be_bytes())?; + self.put(bi, at + 18, &count.to_be_bytes())?; + if items.is_empty() { + return Ok(()); + } + // GTA V: the pairs are a structure with Key and Item fields, named + // after the block that holds them. RDR2: key at 0 (padded to 8), item at 8. + let same = |a: &Entry, b: &Entry| a.kind == b.kind && a.sub == b.sub && a.key == b.key; + let (key_name, item_name) = (names::parse("Key"), names::parse("Item")); + let pair = self.pso.pairs.iter().find(|(_, st)| { + st.find(key_name).is_some_and(|k| same(k, &key_info)) + && st.find(item_name).is_some_and(|i| same(i, &item_info)) + }); + let (block_name, key_entry, item_entry, pair_len) = match pair { + Some((name, st)) => { + (*name, *st.find(key_name).expect("found"), *st.find(item_name).expect("found"), st.length) + } + None if self.is_rdr2() => { + let item_size = match (item_info.kind, item_info.sub) { + (ty::STRUCTURE, 0) => self.struct_info(item_info.key)?.length, + (ty::STRING, 7 | 8) | (ty::UINT | ty::SINT | ty::ENUM | ty::FLOAT, _) => 4, + _ => 8, + }; + ( + ARRAYINFO, + Entry { offset: 0, ..key_info }, + Entry { offset: 8, ..item_info }, + (8 + item_size).next_multiple_of(8), + ) + } + None => return Err("no structure describes the pairs of this map".into()), + }; + let (pb, poff) = self.alloc(block_name, items.len() * pair_len, align_of(pair_len)); + self.pointer(bi, at + 8, pb, poff); + for (i, child) in items.into_iter().enumerate() { + let base = poff + i * pair_len; + let key = attr(child, "key")?; + let key_at = base + key_entry.offset; + match key_entry.kind { + ty::STRING => self.string(pb, key_at, &key_entry, key)?, + ty::ENUM | ty::UINT | ty::SINT => self.put(pb, key_at, &names::parse_value(key).to_be_bytes())?, + _ => self.put(pb, key_at, &(int(key)? as u32).to_be_bytes())?, + } + match item_entry.kind { + ty::STRING => self.string(pb, base + item_entry.offset, &item_entry, &text(child))?, + ty::STRUCTURE if item_entry.key != 0 && item_entry.sub != 3 => { + self.structure(pb, base + item_entry.offset, item_entry.key, child, depth + 1)?; + } + ty::STRUCTURE => { + let actual = self.struct_named(attr(child, "type")?)?; + let len = self.struct_info(actual)?.length; + let (sb, soff) = self.alloc(actual, len, align_of(len)); + self.pointer(pb, base + item_entry.offset, sb, soff); + self.structure(sb, soff, actual, child, depth + 1)?; + } + _ => { + let v = element_children(child) + .find(|c| c.tag_name().name() == "Value") + .ok_or("map item without Value")?; + self.entry(pb, base, &item_entry, info, v, depth + 1)?; + } + } + } + Ok(()) + } + + fn floats(&mut self, bi: usize, at: usize, v: &[f32]) -> R<()> { + let bytes: Vec = v.iter().flat_map(|f| f.to_be_bytes()).collect(); + self.put(bi, at, &bytes) + } + + fn flags(&mut self, bi: usize, at: usize, e: &Entry, info: &StructInfo, node: Node<'_, '_>) -> R<()> { + let index = (e.key & 0xFFF) as usize; + let flags = (index != 0xFFF) + .then(|| info.entries.get(index)) + .flatten() + .filter(|x| x.name == ARRAYINFO) + .and_then(|x| self.pso.enums.get(&x.key)); + let n_words = match e.sub { + 0..=2 => 1, + 4 => ((e.key >> 16).clamp(1, 4096) as usize).div_ceil(32), + s => return Err(format!("unexpected flags subtype {s}")), + }; + let mut words = vec![0u32; n_words]; + let content = node.attribute("value").map(str::to_owned).unwrap_or_else(|| text(node)); + match flags { + Some(values) => { + // The reader joins the names of the set bits in the enum's + // order with single spaces (unnamed values give empty names): + // matched in that order, whatever it wrote comes back exactly. + // Other text (edited by hand) is taken name by name. + let bit_of = |bit: i32| usize::try_from(bit).ok().filter(|b| b / 32 < n_words); + let mut tokens = content.split(' ').peekable(); + for (n, bit) in values { + if let Some(b) = bit_of(*bit) + && tokens.peek().is_some_and(|t| *t == names::field(*n)) + { + words[b / 32] |= 1 << (b % 32); + tokens.next(); + } + } + if tokens.next().is_some() || content.is_empty() { + words.iter_mut().for_each(|w| *w = 0); + for name in content.split_whitespace() { + let b = values + .iter() + .find(|(n, _)| names::field(*n) == name) + .and_then(|(_, bit)| bit_of(*bit)) + .ok_or_else(|| format!("\"{name}\" is not a flag of this field"))?; + words[b / 32] |= 1 << (b % 32); + } + } + } + None if content.trim().is_empty() => {} + None if n_words == 1 => words[0] = int(&content)? as u32, + None => { + for (w, hex) in words.iter_mut().zip(content.split_whitespace()) { + *w = u32::from_str_radix(hex, 16).map_err(|_| format!("\"{hex}\" is not hex"))?; + } + } + } + match e.sub { + 0 => self.put(bi, at, &words[0].to_be_bytes()), + 1 => self.put(bi, at, &(words[0] as u16).to_be_bytes()), + 2 => self.put(bi, at, &[words[0] as u8]), + _ => { + let bytes: Vec = words.iter().flat_map(|w| w.to_be_bytes()).collect(); + self.put(bi, at, &bytes) + } + } + } + + fn string(&mut self, bi: usize, at: usize, e: &Entry, s: &str) -> R<()> { + match e.sub { + 0 => { + let n = (e.key >> 16) as usize; + if s.len() > n { + return Err(format!("\"{s}\" is longer than the {n} bytes the field holds")); + } + self.put(bi, at, s.as_bytes()) + } + 1 => { + if !s.is_empty() { + let (cb, coff) = self.chars(s); + self.pointer(bi, at, cb, coff); + } + Ok(()) + } + 2 => { + { + // Empty strings point at a terminator, as in the game's files. + let (cb, coff) = self.chars(s); + self.pointer(bi, at, cb, coff); + } + Ok(()) + } + 3 => self.counted_string(bi, at, s), + 7..=15 => self.put(bi, at, &names::parse_value(s.trim()).to_be_bytes()), + s => Err(format!("unexpected string subtype {s}")), + } + } + + /// A string pointer followed by its length and size with the terminator (16 bytes). + fn counted_string(&mut self, bi: usize, at: usize, s: &str) -> R<()> { + if s.is_empty() { + return Ok(()); + } + let n = u16::try_from(s.len()).map_err(|_| "string too long".to_owned())?; + let (cb, coff) = self.chars(s); + self.pointer(bi, at, cb, coff); + // GTA V mostly writes the size first, RDR2 the length. + let (first, second) = if self.is_rdr2() { (n, n + 1) } else { (n + 1, n) }; + self.put(bi, at + 8, &first.to_be_bytes())?; + self.put(bi, at + 10, &second.to_be_bytes()) + } + + /// An array field, mirroring how [`Pso::array_node`] reads it. + fn array( + &mut self, + bi: usize, + base: usize, + e: &Entry, + info: &StructInfo, + node: Node<'_, '_>, + depth: usize, + ) -> R<()> { + let at = base + e.offset; + let mut index = (e.key & 0xFFFF) as usize; + if index >= info.entries.len() { + index = (e.key & 0xFFF) as usize; + } + let item = *info.entries.get(index).ok_or("ARRAYINFO not found")?; + let external = + matches!(e.sub, 0 | 5) || (e.sub == 4 && item.sub == 3) || matches!(item.kind, ty::STRING | ty::ENUM); + if !external && !matches!(e.sub, 1 | 2 | 4 | 129) { + return Err(format!("unsupported array subtype {}", e.sub)); + } + if item.kind == ty::ARRAY { + let n = (e.key >> 16) as usize; + let items: Vec<_> = element_children(node).collect(); + if items.len() > n { + return Err(format!("{} arrays where the structure holds {n}", items.len())); + } + for (i, child) in items.into_iter().enumerate() { + let inner = Entry { offset: 0, ..item }; + self.array(bi, at + i * 16, &inner, info, child, depth + 1)?; + } + return Ok(()); + } + let count = match item.kind { + ty::STRUCTURE | ty::STRING | ty::ENUM => element_children(node).count(), + ty::FLOAT2 => tokens(node).len().div_ceil(2), + ty::FLOAT3 | ty::FLOAT3A => tokens(node).len().div_ceil(3), + ty::FLOAT4 | ty::FLOAT4A | ty::VEC4V => tokens(node).len().div_ceil(4), + _ => tokens(node).len(), + }; + if count == 0 { + // Empty: no storage, and the item type may not even be in the schema. + if external { + self.put(bi, at + 8, &[0; 4])?; + } + return Ok(()); + } + // Item size and the block name of external storage. + let (size, block_name) = match (item.kind, item.sub) { + (ty::STRUCTURE, 3 | 4) => (8, POINTERS), + (ty::STRUCTURE, _) => (self.struct_info(item.key)?.length, item.key), + (ty::STRING, 7..=15) => (4, UINTS), + (ty::STRING, 2) => (8, POINTERS), + (ty::STRING, 3) => (16, COUNTED_STRINGS), + (ty::STRING, s) => return Err(format!("unexpected string array subtype {s}")), + (ty::FLOAT2, _) => (8, ty::FLOAT2 as u32), + (ty::FLOAT3 | ty::FLOAT3A | ty::FLOAT4 | ty::FLOAT4A | ty::VEC4V, _) => (16, item.kind as u32), + (ty::LONG | ty::ULONG, _) => (8, item.kind as u32), + (ty::SBYTE | ty::UBYTE | ty::BOOL, _) => (1, item.kind as u32), + (ty::USHORT, _) => (2, item.kind as u32), + (ty::FLOAT | ty::UINT | ty::SINT, _) => (4, item.kind as u32), + (ty::ENUM, _) => (4, UINTS), + (other, _) => return Err(format!("unsupported array item type {other:#04x}")), + }; + // Where the items go: (block, offset). + let (ab, aoff) = if external { + let n = u16::try_from(count).map_err(|_| format!("{count} items are more than an array holds"))?; + self.put(bi, at + 8, &n.to_be_bytes())?; + self.put(bi, at + 10, &n.to_be_bytes())?; + let (ab, aoff) = self.alloc(block_name, count * size, align_of(size)); + self.pointer(bi, at, ab, aoff); + (ab, aoff) + } else { + let n = (e.key >> 16) as usize; + if count > n { + return Err(format!("{count} items where the structure holds {n}")); + } + (bi, at) + }; + match item.kind { + ty::STRUCTURE if matches!(item.sub, 3 | 4) => { + for (i, child) in element_children(node).enumerate() { + if let Some(t) = child.attribute("type") { + let actual = self.struct_named(t)?; + let len = self.struct_info(actual)?.length; + let (pb, poff) = self.alloc(actual, len, align_of(len)); + self.pointer(ab, aoff + i * 8, pb, poff); + self.structure(pb, poff, actual, child, depth + 1)?; + } + } + } + ty::STRUCTURE => { + for (i, child) in element_children(node).enumerate() { + self.structure(ab, aoff + i * size, item.key, child, depth + 1)?; + } + } + ty::STRING => { + for (i, child) in element_children(node).enumerate() { + let s = text(child); + let p = aoff + i * size; + if item.sub >= 7 { + self.put(ab, p, &names::parse_value(s.trim()).to_be_bytes())?; + } else if item.sub == 3 { + self.counted_string(ab, p, &s)?; + } else if !s.is_empty() { + let (cb, coff) = self.chars(&s); + self.pointer(ab, p, cb, coff); + } + } + } + ty::ENUM => { + for (i, child) in element_children(node).enumerate() { + let v = self.enum_value(item.key, &text(child))?; + self.put(ab, aoff + i * 4, &(v as u32).to_be_bytes())?; + } + } + ty::FLOAT2 | ty::FLOAT3 | ty::FLOAT3A | ty::FLOAT4 | ty::FLOAT4A | ty::VEC4V | ty::FLOAT => { + let per = match item.kind { + ty::FLOAT => 1, + ty::FLOAT2 => 2, + ty::FLOAT3 | ty::FLOAT3A => 3, + _ => 4, + }; + for (i, t) in tokens(node).iter().enumerate() { + let p = aoff + (i / per) * size + (i % per) * 4; + self.put(ab, p, &float(t)?.to_be_bytes())?; + } + } + _ => { + for (i, t) in tokens(node).iter().enumerate() { + let v = int(t)?; + let p = aoff + i * size; + match size { + 1 => self.put(ab, p, &[v as u8])?, + 2 => self.put(ab, p, &(v as u16).to_be_bytes())?, + 4 => self.put(ab, p, &(v as u32).to_be_bytes())?, + _ => self.put(ab, p, &(v as u64).to_be_bytes())?, + } + } + } + } + Ok(()) + } + + fn encode_pointer(&self, id: usize, offset: usize) -> R<[u8; 8]> { + if id > 0xFFF { + return Err(format!("{id} blocks are more than pointers can address")); + } + let mut out = [0u8; 8]; + if self.is_rdr2() { + if offset >= 1 << 28 { + return Err(format!("offset {offset:#x} is beyond what pointers can address")); + } + let word = id as u32 | ((offset as u32 & 0xFFF) << 20); + out[..4].copy_from_slice(&word.to_be_bytes()); + out[4..6].copy_from_slice(&((offset >> 12) as u16).to_le_bytes()); + } else { + if offset >= MAX_OFFSET { + return Err(format!("a block of over {} MB cannot be addressed", MAX_OFFSET >> 20)); + } + out[..4].copy_from_slice(&(id as u32 | (offset as u32) << 12).to_be_bytes()); + } + Ok(out) + } + + /// Puts the blocks in order, resolves pointers and assembles the file. + fn finish(mut self, root: usize) -> R> { + let pso = self.pso; + // Blocks keep the original's order; new types follow. + let rank = |name: u32| pso.blocks.iter().position(|b| b.name == name).unwrap_or(usize::MAX); + let mut order: Vec = (0..self.blocks.len()).collect(); + order.sort_by_key(|&i| (rank(self.blocks[i].name), i)); + let mut id = vec![0usize; self.blocks.len()]; + for (n, &i) in order.iter().enumerate() { + id[i] = n + 1; + } + for f in std::mem::take(&mut self.fixes) { + let p = self.encode_pointer(id[f.target], f.offset)?; + self.put(f.block, f.at, &p)?; + } + if order.len() > 0x7FFF { + return Err(format!("{} blocks are more than a block map holds", order.len())); + } + let mut psin = b"PSIN\0\0\0\0pppppppp".to_vec(); + let mut map = Vec::with_capacity(16 * order.len()); + for &i in &order { + let b = &self.blocks[i]; + psin.resize(psin.len().next_multiple_of(16), b'p'); + map.extend_from_slice(&b.name.to_be_bytes()); + map.extend_from_slice(&(psin.len() as u32).to_be_bytes()); + map.extend_from_slice(&0u32.to_be_bytes()); + map.extend_from_slice(&(b.data.len() as u32).to_be_bytes()); + psin.extend_from_slice(&b.data); + } + let len = u32::try_from(psin.len()).map_err(|_| "the data is over 4 GB".to_owned())?; + psin[4..8].copy_from_slice(&len.to_be_bytes()); + let mut pmap = b"PMAP".to_vec(); + let header = if self.is_rdr2() { 24 } else { 16 }; + pmap.extend_from_slice(&((header + map.len()) as u32).to_be_bytes()); + pmap.extend_from_slice(&(id[root] as u32).to_be_bytes()); + let count = (order.len() as u16).to_be_bytes(); + if self.is_rdr2() { + // RDR2: no count at 12, the count at 16 and the blocks from 24. + pmap.extend_from_slice(&[0; 4]); + pmap.extend_from_slice(&count); + pmap.extend_from_slice(b"pppppp"); + } else { + pmap.extend_from_slice(&count); + pmap.extend_from_slice(b"pp"); + } + pmap.extend_from_slice(&map); + + let same = pso.sections.iter().all(|(ident, s)| match ident { + b"PSIN" => *s == psin, + b"PMAP" => *s == pmap, + _ => true, + }); + let mut out = Vec::with_capacity(psin.len() + pmap.len() + 4096); + for (ident, s) in &pso.sections { + match ident { + b"PSIN" => out.extend_from_slice(&psin), + b"PMAP" => out.extend_from_slice(&pmap), + b"CHKS" if !same => {} + _ => out.extend_from_slice(s), + } + } + Ok(out) + } +} + +/// Builds a PSO file from XML in the form [`Pso::to_xml`] writes, with the +/// schema and the other sections of `template` (the file the XML came from). +pub(super) fn from_xml(template: &Pso, xml: &str) -> Result, PsoError> { + let err = PsoError::Invalid; + let doc = Document::parse(xml).map_err(|e| err(format!("the XML cannot be read: {e}")))?; + let root = doc.root_element(); + let root_block = template.block(template.root_block).ok_or_else(|| err("the original has no root block".into()))?; + let root_name = names::field(root_block.name); + if root.tag_name().name() != root_name { + return Err(err(format!("the root element is <{}>, the file needs <{root_name}>", root.tag_name().name()))); + } + let mut b = Builder::new(template); + let len = b.struct_info(root_block.name).map_err(err)?.length; + let (bi, off) = b.alloc(root_block.name, len, align_of(len)); + b.structure(bi, off, root_block.name, root, 0).map_err(err)?; + b.finish(bi).map_err(err) +} + +impl Pso { + /// Builds a PSO file from XML as [`Pso::to_xml`] writes it, keeping this + /// file's schema: the way to write back an edited copy of this file. + pub fn from_xml(&self, xml: &str) -> Result, PsoError> { + from_xml(self, xml) + } +} + +#[cfg(test)] +mod tests { + use rage_core::hash::{jenkins_bytes, joaat}; + + use super::super::{parse, parse_rdr2}; + + fn h(name: &str) -> u32 { + jenkins_bytes(name.as_bytes()) + } + + /// A PSO file with a list of two items (a hash and a float each), laid + /// out like the game's: items in block 1, the root in block 2. + fn tiny() -> Vec { + let (root, item) = (h("CPedModelInfo__InitDataList"), h("CPedModelInfo__InitData")); + let mut items = Vec::new(); + for (name, radius) in [("adder", 1.5f32), ("banshee", -2.0)] { + items.extend(joaat(name).to_be_bytes()); + items.extend(radius.to_be_bytes()); + } + let mut root_data = 1u32.to_be_bytes().to_vec(); // block 1, offset 0 + root_data.extend([0, 0, 0, 0, 0, 2, 0, 2, 0, 0, 0, 0]); + let mut psin = b"PSIN\0\0\0\0pppppppp".to_vec(); + psin.extend(&items); + psin.extend(&root_data); + let len = psin.len() as u32; + psin[4..8].copy_from_slice(&len.to_be_bytes()); + let mut pmap = b"PMAP".to_vec(); + pmap.extend(48u32.to_be_bytes()); + pmap.extend(2u32.to_be_bytes()); + pmap.extend([0, 2, b'p', b'p']); + for (name, off, len) in [(item, 16u32, 16u32), (root, 32, 16)] { + for v in [name, off, 0, len] { + pmap.extend(v.to_be_bytes()); + } + } + let entry = |name: u32, kind: u8, sub: u8, offset: u16, key: u32| { + let mut e = name.to_be_bytes().to_vec(); + e.extend([kind, sub]); + e.extend(offset.to_be_bytes()); + e.extend(key.to_be_bytes()); + e + }; + let structure = |length: u32, entries: Vec>| { + let mut s = (entries.len() as u32).to_be_bytes().to_vec(); + s.extend(length.to_be_bytes()); + s.extend(0u32.to_be_bytes()); + s.extend(entries.concat()); + s + }; + let root_info = structure(16, vec![entry(0x100, 0x0c, 0, 0, item), entry(h("InitDatas"), 0x0d, 0, 0, 0)]); + let item_info = structure(8, vec![entry(h("Name"), 0x0b, 7, 0, 0), entry(h("Radius"), 0x07, 0, 4, 0)]); + let index_len = 12 + 2 * 8; + let mut psch = b"PSCH".to_vec(); + psch.extend(((index_len + root_info.len() + item_info.len()) as u32).to_be_bytes()); + psch.extend(2u32.to_be_bytes()); + psch.extend(root.to_be_bytes()); + psch.extend((index_len as u32).to_be_bytes()); + psch.extend(item.to_be_bytes()); + psch.extend(((index_len + root_info.len()) as u32).to_be_bytes()); + psch.extend(root_info); + psch.extend(item_info); + [psin, pmap, psch].concat() + } + + #[test] + fn writes_back_the_same_bytes() { + let file = tiny(); + let pso = parse(&file).unwrap(); + let (xml, errors) = pso.to_xml(); + assert!(errors.is_empty(), "{errors:?}"); + assert!(xml.contains("adder") || xml.contains("hash_"), "{xml}"); + assert!(xml.contains(""), "{xml}"); + assert_eq!(pso.from_xml(&xml).unwrap(), file); + } + + #[test] + fn writes_edits() { + let pso = parse(&tiny()).unwrap(); + let (xml, _) = pso.to_xml(); + let edited = xml.replace("", "").replace( + " ", + " \n zentorno\n \n \n ", + ); + assert_ne!(edited, xml); + let written = pso.from_xml(&edited).unwrap(); + let (again, errors) = parse(&written).unwrap().to_xml(); + assert!(errors.is_empty(), "{errors:?}"); + assert_eq!(again, edited.replace("zentorno", &crate::names::value(joaat("zentorno")))); + assert!(again.contains("")); + } + + #[test] + fn refuses_what_does_not_fit() { + let pso = parse(&tiny()).unwrap(); + let (xml, _) = pso.to_xml(); + let unknown = xml.replace("", "\n "); + assert!(pso.from_xml(&unknown).unwrap_err().to_string().contains("no field Speed")); + assert!(pso.from_xml(&xml.replace("value=\"1.5\"", "value=\"fast\"")).is_err()); + assert!(pso.from_xml("").is_err()); + assert!(pso.from_xml("not xml").is_err()); + } + + #[test] + fn rdr2_layout() { + // The same file read as RDR2's reads the same; written back it uses RDR2's block map. + let pso = parse_rdr2(&tiny()).unwrap(); + let (xml, _) = pso.to_xml(); + let written = pso.from_xml(&xml).unwrap(); + let again = parse_rdr2(&written).unwrap(); + assert_eq!(again.to_xml().0, xml); + let pmap = written.windows(4).position(|w| w == b"PMAP").unwrap(); + assert_eq!(&written[pmap + 12..pmap + 18], &[0, 0, 0, 0, 0, 2]); + } +} diff --git a/site/content/_index.md b/site/content/_index.md index 26b4991..99e6500 100644 --- a/site/content/_index.md +++ b/site/content/_index.md @@ -305,7 +305,7 @@ Every format is verified against the complete game (GTA V Enhanced): | Models (`.ydr`, `.yft`, `.ydd`) | 168,779 models | all load (583 million triangles) | | Audio (`.awc`) | 7,758 containers, 252,742 sounds | all decode (279.8 hours) | | Animations (`.ycd`) | 25,961 dictionaries, 332,771 clips | all evaluate | -| Metadata (`.ymap`, `.ytyp`, `.ymt`, `.ymf`, `.cut`, `.pso`) | 30,280 files | all convert to XML | +| Metadata (`.ymap`, `.ytyp`, `.ymt`, `.ymf`, `.cut`, `.pso`) | 30,280 files | all convert to XML; all 4,943 PSO files convert back (3,973 byte-identical, the rest to the same XML) | | Text tables (`.gxt2`, `.nametable`) | 19,858 files, 9.16 million strings | text → binary is byte-identical | | Particles (`.ypt`) | 1,544 dictionaries, 12,987 effects | all read, incl. 1,694 textures and 1,223 models | | Collisions (`.ybn`) | 14,692 files, 70,454 bounds | all read (101 million triangles, 4.7 million shapes) | diff --git a/site/content/cli.md b/site/content/cli.md index 9f61019..32742b3 100644 --- a/site/content/cli.md +++ b/site/content/cli.md @@ -94,6 +94,7 @@ openrage rdr2-names # find RDR2 file names in the gam openrage rpf8 --list /common_0.rpf # RDR2 archive contents openrage rpf8 --text # read every RDR2 text table (.yldb) openrage rpf8 --meta # convert all RDR2 metadata (.ymap, .ytyp, .ymt, .ymf) to XML +openrage rpf8 --meta --rebuild # every RDR2 PSO file → XML → PSO, compared openrage rpf8 --audio /x64/audio # decode every RDR2 sound openrage rpf8 --anims /anim_0.rpf # read every RDR2 clip dictionary openrage --game rdr2-ped # list the RDR2 peds (people and animals) with their base skeletons @@ -175,6 +176,7 @@ openrage verify --models --rebuild # write every Enhanced .ydr anew openrage verify --audio # decode every sound of the game openrage verify --animations # parse every clip dictionary, evaluate all frames openrage verify --meta # convert every metadata file of the game +openrage verify --meta --rebuild # every PSO file → XML → PSO, same bytes or at least the same XML openrage verify --text # every .gxt2/.nametable → text → back, identical openrage verify --particles # parse every particle dictionary openrage verify --collisions # build the meshes of every collision file diff --git a/site/content/modding.md b/site/content/modding.md index 3ee6882..db8357f 100644 --- a/site/content/modding.md +++ b/site/content/modding.md @@ -145,6 +145,15 @@ Packages of format 2.x: | Archives | new archives and DLC packs (`createIfNotExist`) | | Text edits | `add`, `insert`, `replace`, `delete` with Equal, StartWith or Mask | | XML edits | by XPath: `add` (First, Last, Before, After), `replace`, `remove`, keeping the formatting | +| PSO edits | ``: binary metadata (`.ymt`, `.ymf`, `.ytyp`, … in PSO form) is converted to XML, edited with the same commands as ``, and written back as PSO | + +PSO edits work on the XML OpenRAGE shows for the file (**View as XML**, `openrage xml`), the same as CodeWalker's: +hashes appear as their names where the name is known, otherwise as `hash_XXXXXXXX`; names that an XPath compares with +(`Item[modelName = 'adder']`) are always recognised. The file keeps its own structure definitions, so the edit can +change values and add or remove items, but not invent fields the file's structures do not have; the preview says so +before anything is written. Written back unchanged, 80% of GTA V's PSO files come out byte for byte the same and every +one reads back to the same XML (`openrage verify --meta --rebuild`); the rest differ only in bytes the XML does not +carry, such as the unused fourth number of a 3D vector. ### Uninstalling @@ -152,7 +161,8 @@ Every installed package can be **uninstalled** from **History** (or `openrage oi ### Not supported yet -`` edits: such packages are refused with an explanation. `` is skipped, as it only saves disk space. +`` edits of metadata in resource form (`RSC7` `.ymt` files such as ped variations) are refused with an +explanation; only PSO files can be edited that way. `` is skipped, as it only saves disk space. ## ASI mods (GTA V)