Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions NOTICE.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,27 @@ Vorbis audio (Red Dead Redemption 2) is decoded with lewton
(https://github.com/RustAudio/lewton), licensed under the MIT or Apache-2.0
license.

## opus-rs

Opus audio (GTA VI) is decoded with opus-rs
(https://github.com/restsend/opus-rs), a port of libopus, licensed under the
BSD 3-Clause licence.

## Leonida

What is known about GTA VI's formats (RPF9 archives, audio containers, PSIN
and RBF0 metadata, texture pools) comes from the documentation of Leonida
(https://github.com/ItsNotRexed/Leonida, GPL-3.0). The PSIN reader in
`crates/rage-formats/src/psin.rs` follows its `tools/psin_data.py`, the
texture pool reader in `crates/rage-formats/src/ttpf.rs` its
`tools/ttpf_mips.py` and `tools/tex_headers.py`.

## rpf9-explorer

The layout of GTA VI's models (`crates/rage-formats/src/drawable6.rs`) is the
one found by rpf9-explorer (https://github.com/breadbbbb/rpf9-explorer). Its
decoder was read to learn the layout; no code was taken from it.

## RDR2-RPF-Tool

The TFIT2-CBC cipher and the strided file encryption of Red Dead Redemption 2
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ OpenIV's last release was in January 2022. OpenRAGE picks up where it left off a
- **Mods, safely:** changes go to OpenIV's `mods` folder, never into your game files; every change and every `.oiv` package can be undone.
- **Models in:** replace props and vehicle bodies of GTA V Enhanced with your own OBJ models; doors and bonnets keep moving (preview).
- **ASI mods:** see and switch GTA V's ASI mods, and on Linux let Proton load the ASI loader with one click.
- **Ready for GTA VI:** support follows as fast as possible once GTA VI comes to PC.
- **Experimental GTA VI Scarlett support:** RPF9 TOC browsing, named lookup, streaming extraction, model previews and standalone TTPF textures for the analysed 1.0.2.1 build. See [scope and setup](crates/rage-rpf/RPF9.md).
- **Tested on the whole game:** every format is checked against every file of GTA V ([details](https://two-play.github.io/openrage/#status)).

<table>
Expand All @@ -62,7 +62,7 @@ More screenshots and all features: **[two-play.github.io/openrage](https://two-p
|---|---|---|
| **GTA V** (Legacy & Enhanced) | ✅ read and edit (mods folder, with undo) | ✅ textures (also inside models) · models · audio · animations · metadata · text · collisions · paths · cutscenes · scripts · ASI mods (manager, Proton fix on Linux) · ◐ model import from OBJ with compressed textures and detail levels (Enhanced `.ydr` and vehicle bodies `.yft`, preview; explorer via the OBJ tools plugin) |
| **Red Dead Redemption 2** | ✅ read, with keys from your own game · ◐ edit (Lenny's Mod Loader `lml/replace` folder, with undo; nested archives rewritten; not yet tried in the game) | ◐ textures (replace same-shape) · models with moving parts and cloth · texts · metadata · audio · animations on fitting models · ped outfits (read-only) |
| **GTA VI** | 🔜 next: as fast as possible once it comes to PC | – |
| **GTA VI Scarlett 1.0.2.1** | Experimental RPF9 reader, GUI and selected model/texture formats | Read-only; requires the user's reference executable |
| **GTA IV** (Complete Edition) | ✅ read (IMG3, RPF2, RPF3), key from your own `GTAIV.exe` | ◐ textures · models · collisions · animations · text · scripts · maps in 3D · cutscenes (played with their cast, camera, subtitles and particle effects) · particle effect lists (`.wpfl`) · editing `.img`, `.rpf`, placement files, loose files and textures (`.wtd`, inside `.wdr`) (update folder, or the game files with originals kept) |

**Plugins** (API 0.3, preview): sandboxed WebAssembly plugins add file types, previews (text, tree, table, image, 3D model), tool windows of their own (Tools menu), export and batch actions with access to the game's models and textures, and changes to game files through the `mods` folder (with undo), for every game. ✅ explorer (file list, preview, context menu, Settings → Plugins) and command line (`openrage plugin`), four example plugins included (OBJ export and import, a number and hash converter among them) · plugin packages (`.orp`) with install/uninstall in the explorer and the CLI · models into game formats (`build-model`) · ✅ openFormats: OpenIV's text formats (`.odr`, `.oft`, `.odd`, `.otd` with `.mesh`, `.skel`, DDS) exported and imported back (preview). [Writing plugins](https://two-play.github.io/openrage/plugins/)
Expand Down
1 change: 1 addition & 0 deletions crates/openrage-app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@ png = "0.18"
zip.workspace = true

[dev-dependencies]
flate2.workspace = true
zip = { version = "9", default-features = false, features = ["deflate-flate2"] }
140 changes: 140 additions & 0 deletions crates/openrage-app/examples/rpf9_model_probe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
//! Bounded local-corpus probe, with no recovery scan or archive extraction.
//! Run with the game directory as the sole argument. The reference executable
//! is discovered by Rpf9 in that directory's ancestors.

use std::io::Write;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, ensure};
use rage_formats::drawable6;
use rage_rpf::{Rpf9, rpf9::Kind};

const MAX_RESOURCE: u64 = 32 << 20;
const MAX_SAMPLES: usize = 16;

fn main() -> Result<()> {
let root = PathBuf::from(std::env::args_os().nth(1).context("usage: rpf9_model_probe <game-directory>")?);
let rpf = Rpf9::open(&root.join("data.rpf"))?;
ensure!(rpf.has_toc(), "no usable TOC: refusing to scan archive payloads");
let mut totals = (0, 0);
probe_models(&rpf, "data.rpf", &mut totals)?;
let entries = rpf.entries()?;
for (index, _) in entries
.iter()
.enumerate()
.filter(|(_, e)| matches!(e.kind, Kind::Toc { file_type: 0, resource: false, .. }))
.take(10)
{
if totals.0 + totals.1 >= MAX_SAMPLES {
break;
}
match rpf.open_child(index) {
Ok(child) => probe_models(&child, &format!("data.rpf/{index}"), &mut totals)?,
Err(error) => println!("CHILD_FAIL index={index} error={error}"),
}
}
println!("MODEL_SUMMARY parsed={} failed={}", totals.0, totals.1);
let textures = probe_textures(&root)?;
ensure!(totals.0 > 0 || textures > 0, "neither sampled models nor textures decoded successfully");
Ok(())
}

fn probe_models(rpf: &Rpf9, archive: &str, totals: &mut (usize, usize)) -> Result<()> {
ensure!(rpf.has_toc(), "refusing recovery scan");
let entries = rpf.entries()?;
let candidates: Vec<_> = entries
.iter()
.enumerate()
.filter(|(_, e)| matches!(e.kind, Kind::Toc { resource: true, file_type: 2..=4, .. }) && e.size <= MAX_RESOURCE)
.take(MAX_SAMPLES.saturating_sub(totals.0 + totals.1))
.collect();
println!(
"archive={archive} entries={} samples={} max_resource_bytes={MAX_RESOURCE}",
entries.len(),
candidates.len()
);
for (index, entry) in candidates {
let name = rpf.entry_name(entry);
let result = (|| -> Result<(usize, usize, usize, usize, usize)> {
let (system, graphics) = rpf.resource_parts(index)?.context("TOC entry has no resource parts")?;
ensure!(system.len() as u64 + graphics.len() as u64 <= MAX_RESOURCE, "decoded resource exceeds limit");
let drawables = drawable6::parse(&system, &graphics)?;
let meshes: usize = drawables.iter().map(|d| d.meshes.len()).sum();
let vertices: usize = drawables.iter().flat_map(|d| &d.meshes).map(|m| m.positions.len()).sum();
ensure!(meshes > 0 && vertices > 0, "parser returned no renderable geometry");
Ok((system.len(), graphics.len(), drawables.len(), meshes, vertices))
})();
match result {
Ok((sys, gfx, drawables, meshes, vertices)) => {
totals.0 += 1;
println!(
"OK archive={archive} index={index} name={name:?} sys={sys} gfx={gfx} drawables={drawables} meshes={meshes} vertices={vertices}"
);
}
Err(error) => {
totals.1 += 1;
println!(
"FAIL archive={archive} index={index} name={name:?} logical_bytes={} error={error:#}",
entry.size
);
}
}
}
Ok(())
}

fn probe_textures(root: &Path) -> Result<usize> {
let mut files = Vec::new();
openrage_app::detect::collect_archives(&root.join("data/ttdb"), &["ttpf"], &mut files);
files.sort_by_key(|p| std::fs::metadata(p).map_or(u64::MAX, |m| m.len()));
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_nanos();
let output = std::env::temp_dir().join(format!("openrage-rpf9-textures-{}-{stamp}", std::process::id()));
let (mut attempted, mut decoded, mut pools) = (0, 0, 0);
for file in files.into_iter().take(64) {
if attempted >= MAX_SAMPLES {
break;
}
pools += 1;
let pool = match rage_formats::ttpf::Pool::open(&file) {
Ok(pool) => pool,
Err(error) => {
println!("POOL_FAIL path={file:?} error={error}");
continue;
}
};
for index in 0..pool.len() {
if attempted >= MAX_SAMPLES {
break;
}
let Some(d) = pool.descriptor(index) else {
continue;
};
if d.base.is_none() || d.dimension != 1 || d.depth != 1 || d.width > 512 || d.height > 512 {
continue;
}
attempted += 1;
let result = (|| -> Result<_> {
let texture = pool.texture_with_limit(index, Some(512), MAX_RESOURCE as usize)?;
ensure!(texture.width <= 512 && texture.height <= 512, "mip fallback exceeds preview dimensions");
let rgba = texture.to_rgba().context("pixel decoder does not support this format")?;
let png = rage_formats::png(texture.width, texture.height, &rgba)?;
std::fs::create_dir_all(&output)?;
let path = output.join(format!("pool{pools}-texture{index}.png"));
std::fs::File::create_new(&path)?.write_all(&png)?;
Ok((texture.width, texture.height, texture.format.name(), path))
})();
match result {
Ok((width, height, format, path)) => {
decoded += 1;
println!(
"TEXTURE_OK pool={file:?} index={index} key={:016x} width={width} height={height} format={format} png={path:?}",
pool.keys()[index]
);
}
Err(error) => println!("TEXTURE_FAIL pool={file:?} index={index} error={error:#}"),
}
}
}
println!("TEXTURE_SUMMARY pools={pools} attempted={attempted} decoded={decoded} failed={}", attempted - decoded);
Ok(decoded)
}
1 change: 1 addition & 0 deletions crates/openrage-app/src/audio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub fn load(game_dir: &Path, keys: Option<Arc<GtaVKeys>>, vpath: &str) -> Result
let data = match node {
Node::ArchiveFile(rpf, id) => rpf.read(id)?,
Node::PlainFile(p) => std::fs::read(p)?,
Node::Rpf9File(rpf, i) => rpf.read_at(i)?,
_ => bail!("{vpath} is not a file"),
};
parse(data, keys.as_deref())
Expand Down
52 changes: 48 additions & 4 deletions crates/openrage-app/src/detect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,19 +63,40 @@ pub fn find_installs() -> Vec<PathBuf> {
}

pub fn is_gta5_dir(dir: &Path) -> bool {
EXECUTABLES.iter().any(|exe| dir.join(exe).is_file())
!is_gta6_dir(dir) && EXECUTABLES.iter().any(|exe| dir.join(exe).is_file())
}

/// The program that marks a Red Dead Redemption 2 installation.
pub const RDR2_EXE: &str = "RDR2.exe";

/// Whether a folder is a Red Dead Redemption 2 installation.
pub fn is_rdr2_dir(dir: &Path) -> bool {
dir.join(RDR2_EXE).is_file()
!is_gta6_dir(dir) && dir.join(RDR2_EXE).is_file()
}

/// Whether a folder holds RPF9 archives. Archive signatures take precedence
/// over executable names, since a reference executable may have been copied here.
pub fn is_gta6_dir(dir: &Path) -> bool {
if rage_rpf::Rpf9::file_is_rpf9(&dir.join("common.rpf")) {
return true;
}
let Ok(rd) = fs::read_dir(dir) else { return false };
rd.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("rpf")))
.any(|p| rage_rpf::Rpf9::file_is_rpf9(&p))
}

/// Whether a folder holds a game OpenRAGE can open.
pub fn is_game_dir(dir: &Path) -> bool {
is_gta5_dir(dir) || is_rdr2_dir(dir) || crate::gta4::is_gta4_dir(dir) || is_gta6_dir(dir)
}

/// The icon of the game in `dir`, from its own program: (width, height, RGBA).
pub fn game_icon(dir: &Path) -> Option<(u32, u32, Vec<u8>)> {
if is_gta6_dir(dir) {
return None;
}
let programs: &[&str] = if is_rdr2_dir(dir) {
&[RDR2_EXE]
} else if crate::gta4::is_gta4_dir(dir) {
Expand All @@ -87,9 +108,11 @@ pub fn game_icon(dir: &Path) -> Option<(u32, u32, Vec<u8>)> {
}

/// Short name of the game installed in `dir`: "GTA V Enhanced", "GTA V",
/// "GTA IV", "RDR2", or `None` when no known executable is there.
/// "GTA IV", "RDR2", "GTA VI", or `None` when the folder holds no known game.
pub fn game_name(dir: &Path) -> Option<&'static str> {
if is_rdr2_dir(dir) {
if is_gta6_dir(dir) {
Some("GTA VI")
} else if is_rdr2_dir(dir) {
Some("RDR2")
} else if dir.join("GTA5_Enhanced.exe").is_file() {
Some("GTA V Enhanced")
Expand Down Expand Up @@ -130,6 +153,27 @@ pub fn collect_rpfs(dir: &Path, out: &mut Vec<PathBuf>) {
mod tests {
use super::*;

#[test]
fn archive_signature_overrides_copied_executables() {
let dir = std::env::temp_dir().join(format!("openrage-detect-rpf9-{}", std::process::id()));
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join("GTA5_Enhanced.exe"), []).unwrap();
fs::write(dir.join("RDR2.exe"), []).unwrap();
fs::write(dir.join("GTAIV.exe"), []).unwrap();
// Detection reads only the signature, never the archive's payload.
fs::write(dir.join("common.rpf"), b"9FPR").unwrap();
assert!(is_gta6_dir(&dir));
assert!(!is_gta5_dir(&dir));
assert!(!is_rdr2_dir(&dir));
assert_eq!(game_name(&dir), Some("GTA VI"));
assert!(game_icon(&dir).is_none());
// Other RPF9 archives still identify the game if common is another format.
fs::write(dir.join("common.rpf"), b"RPF7").unwrap();
fs::write(dir.join("data.rpf"), b"9FPR").unwrap();
assert_eq!(game_name(&dir), Some("GTA VI"));
fs::remove_dir_all(dir).unwrap();
}

#[test]
fn parses_library_folders() {
let vdf = r#"
Expand Down
79 changes: 79 additions & 0 deletions crates/openrage-app/src/gta6_models.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//! GTA VI models using the TOC resource boundaries when available.
//! The stream-boundary heuristic below is only used for the recovery view.
//!
//! A model is stored as its system part and then its graphics part, each
//! cut into zlib streams of 64 KiB. Without the table of contents nothing
//! says where one part ends: the recovery view lists a resource as its first
//! entry (which starts the system part) and what follows it. So the parts
//! are found by trying: every cut between two streams is a possible end of
//! the system part, and the reader says whether the graphics part reaches
//! far enough.

use anyhow::{Context, Result, bail};
use rage_formats::drawable::Drawable;
use rage_formats::drawable6::{self, ModelError};
use rage_rpf::Rpf9;

/// Streams unpack to this many bytes, the last one of a part to fewer.
const STREAM: usize = 0x10000;
/// A system part is at most this long.
const MAX_SYSTEM: usize = 32 << 20;
/// A resource is at most this long, and spread over at most this many entries.
const MAX_RESOURCE: usize = 256 << 20;
const MAX_ENTRIES: usize = 4096;

/// Reads the model that starts at entry `index`: its drawables with their names.
pub fn load(rpf: &Rpf9, index: usize) -> Result<Vec<(String, Drawable)>> {
let entries = rpf.entries()?;
let first = entries.get(index).context("no such entry")?;
if first.size > MAX_RESOURCE as u64 {
bail!("model exceeds the preview size limit");
}
if let Some((system, graphics)) = rpf.resource_parts(index)? {
return Ok(named(drawable6::parse(&system, &graphics)?));
}
if rpf.has_toc() {
bail!("this TOC entry is not a model resource");
}
let mut data = rpf.read(first)?;
if drawable6::root(&data).is_none() {
bail!("this resource is not a model");
}
// Where streams end: the possible ends of the system part.
let mut cuts: Vec<usize> = (1..=data.len().div_ceil(STREAM)).map(|i| (i * STREAM).min(data.len())).collect();
let mut last = index;
loop {
let mut needs_more = false;
let mut failure = None;
for cut in cuts.iter().copied().take_while(|c| *c <= MAX_SYSTEM) {
match drawable6::parse(&data[..cut], &data[cut..]) {
Ok(drawables) => return Ok(named(drawables)),
Err(ModelError::Graphics(_)) => needs_more = true,
Err(e) => failure = failure.or(Some(e)),
}
}
// The graphics part goes on in the next entry.
if !needs_more || !Rpf9::follows(&entries, last) || last - index >= MAX_ENTRIES || data.len() >= MAX_RESOURCE {
match failure {
Some(e) if !needs_more => bail!(e),
_ => bail!("the model's vertex and index data was not found after it"),
}
}
last += 1;
if entries[last].size > MAX_RESOURCE.saturating_sub(data.len()) as u64 {
bail!("model exceeds the preview size limit");
}
let more = rpf.read(&entries[last])?;
let start = data.len();
data.extend_from_slice(&more);
cuts.extend((1..=more.len().div_ceil(STREAM)).map(|i| start + (i * STREAM).min(more.len())));
}
}

fn named(drawables: Vec<Drawable>) -> Vec<(String, Drawable)> {
drawables
.into_iter()
.enumerate()
.map(|(i, d)| (if d.name.is_empty() { format!("drawable {i}") } else { d.name.clone() }, d))
.collect()
}
Loading