upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tools/rpf9dump/Program.cs
diff options
context:
space:
mode:
authorNotRexed <therealnothingfn@gmail.com>2026-11-20 15:22:16 -0500
committerNotRexed <therealnothingfn@gmail.com>2026-11-20 15:22:16 -0500
commitdb0dc8bd5ebce6e2bc27d47085f7f104eb3037d3 (patch)
tree4fb3edca45f8b4dd3368c6ac2a0e4fdc8ed7065c /tools/rpf9dump/Program.cs
Initial commit: Leonida, build-it-yourself PC port groundwork
Shader pipeline (carve, FSSM unpack, gfx1013 disassembly, RDNA2 to SPIR-V), asset export via rpf9-explorer's Core (submodule), PE loader and shim skeleton, and make_game.py, which builds from the user's own copy of the game. No game data, keys or executables are included. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools/rpf9dump/Program.cs')
-rw-r--r--tools/rpf9dump/Program.cs154
1 files changed, 154 insertions, 0 deletions
diff --git a/tools/rpf9dump/Program.cs b/tools/rpf9dump/Program.cs
new file mode 100644
index 000000000..8b6c93f50
--- /dev/null
+++ b/tools/rpf9dump/Program.cs
@@ -0,0 +1,154 @@
1// Bulk exporter around rpf9-explorer's Core (github.com/breadbbbb/rpf9-explorer).
2// Local use only: writes OBJ/DDS/JSON from the user's own package. No keys, no TOC decryption.
3using System.Diagnostics;
4using System.Text.Json;
5using RpfPreview.Core;
6
7if (args.Length < 3) { Console.WriteLine("usage: rpf9dump ttpf|models|textures <source> <outdir>"); return 2; }
8string mode = args[0], src = Path.GetFullPath(args[1]), outRoot = Path.GetFullPath(args[2]);
9var json = new JsonSerializerOptions { WriteIndented = true };
10var sw = Stopwatch.StartNew();
11string baseName = Path.GetFileNameWithoutExtension(src);
12string outDir = Path.Combine(outRoot, baseName); Directory.CreateDirectory(outDir);
13long length = new FileInfo(src).Length;
14int ok = 0, fail = 0, skip = 0;
15
16if (mode == "ttpf")
17{
18 var info = TtpfReader.Inspect(src);
19 var rows = new List<object>();
20 foreach (var t in info.Textures)
21 {
22 string name = $"{t.Index:D6}_{Util.Safe(Path.GetFileNameWithoutExtension(t.Name))}.dds";
23 rows.Add(new { t.Index, t.Name, t.Id, AssetKey = t.AssetKey.ToString("X16"), t.Width, t.Height, t.DxgiFormat, t.Mips, t.SourceMips, t.BaseMipLevel, t.Limitation, File = t.CanExtract ? name : null });
24 if (!t.CanExtract) { skip++; continue; }
25 string path = Path.Combine(outDir, name);
26 if (File.Exists(path)) { ok++; continue; }
27 try { File.WriteAllBytes(path, TtpfReader.CreateDds(src, t.Index)); ok++; }
28 catch (Exception e) { fail++; if (fail <= 5) Console.WriteLine($" fail {t.Index}: {e.GetType().Name} {e.Message}"); }
29 if ((ok + fail) % 5000 == 0) Console.WriteLine($" {ok + fail}/{info.Textures.Count}");
30 }
31 File.WriteAllText(Path.Combine(outDir, "manifest.json"), JsonSerializer.Serialize(new { src, info.Version, Count = info.Textures.Count, info.Metadata, Textures = rows }, json));
32}
33else if (mode == "audio")
34{
35 if (!AwcRecovery.HasCompleteCache(src))
36 {
37 long last = -1;
38 var prog = new Progress<long>(p => { long s = p / (4L << 30); if (s != last) { last = s; Console.WriteLine($" awc scan {100.0 * p / length:0.0}%"); } });
39 var found = AwcRecovery.RecoverFull(src, prog);
40 AwcRecovery.WriteCache(src, found);
41 Console.WriteLine($" {found.Count:N0} AWC banks ({sw.Elapsed.TotalSeconds:0}s)");
42 }
43 var doc = ArchiveReader.Open(src);
44 var banks = doc.Entries.Where(e => e.Extension == ".awc" && e.CanExtract).ToList();
45 string sub = Path.Combine(outDir, "awc");
46 var todo = banks.Where(e => !File.Exists(ArchiveReader.SafeDestination(sub, e.Path))).ToList();
47 Console.WriteLine($" {banks.Count:N0} banks, {todo.Count:N0} to write");
48 for (int i = 0; i < todo.Count; i += 500)
49 doc.ExtractAsync(todo.Skip(i).Take(500), sub).GetAwaiter().GetResult();
50 ok = banks.Count;
51 var rows = banks.Select(e => { var info = AwcInfo.Inspect(src, e.Offset, e.Size);
52 return new { e.Path, e.Offset, e.Size, Streams = info?.Streams.Select(s => new { s.Index, Id = s.Id.ToString("X8"), s.Codec, s.Channels, s.SampleRate, s.DurationSeconds, s.IsStreamed }) }; }).ToList();
53 File.WriteAllText(Path.Combine(outDir, "audio_manifest.json"), JsonSerializer.Serialize(new { src, Count = banks.Count, Banks = rows }, json));
54}
55else if (mode is "models" or "textures")
56{
57 byte[] header; using (var f = File.OpenRead(src)) { header = new byte[64]; f.ReadExactly(header); }
58 var cached = RecoveryIndexCache.Load(mode, src, length, header);
59 if (cached == null)
60 {
61 long last = -1;
62 var prog = new Progress<long>(p => { long s = p / (4L << 30); if (s != last) { last = s; Console.WriteLine($" scan {100.0 * p / length:0.0}%"); } });
63 var cands = mode == "models" ? Rpf9ModelRecovery.FindCandidateOffsets(src, progress: prog) : Rpf9TextureRecovery.FindCandidateOffsets(src, progress: prog);
64 Console.WriteLine($" candidates {cands.Count:N0} ({sw.Elapsed.TotalSeconds:0}s)");
65 var entries = new List<ArchiveEntry>();
66 for (int i = 0; i < cands.Count; i += 32)
67 {
68 var chunk = cands.Skip(i).Take(32).ToArray();
69 var got = mode == "models" ? Rpf9ModelRecovery.RecoverAtOffsets(src, length, chunk, entries.Count) : Rpf9TextureRecovery.RecoverAtOffsets(src, length, chunk, entries.Count);
70 entries.AddRange(got);
71 if ((i / 32) % 200 == 0) Console.WriteLine($" validated {i + chunk.Length:N0}/{cands.Count:N0} -> {entries.Count:N0} ({sw.Elapsed.TotalSeconds:0}s)");
72 }
73 entries = entries.OrderBy(e => e.Offset).Select((e, k) => e with { Index = k }).ToList();
74 RecoveryIndexCache.Save(mode, src, entries, $"rpf9dump full scan, {cands.Count:N0} candidates, {entries.Count:N0} recovered");
75 }
76 var doc = ArchiveReader.Open(src);
77 string want = mode == "models" ? "Recovered model" : "Recovered texture dictionary";
78 var list = doc.Entries.Where(e => e.Compression == want).ToList();
79 Console.WriteLine($" {list.Count:N0} {mode} entries ({sw.Elapsed.TotalSeconds:0}s)");
80 string sub = Path.Combine(outDir, mode); Directory.CreateDirectory(sub);
81 var rows = new List<object>();
82 int embedded = 0;
83 foreach (var e in list)
84 {
85 string stem = Util.Safe(Path.GetFileNameWithoutExtension(e.Name));
86 try
87 {
88 var data = ArchiveReader.ReadResourceData(doc, e);
89 int split = e.ResourceSystemBytes ?? checked((int)e.Segments![0].Size);
90 var sys = data.AsSpan(0, split); var gfx = data.AsSpan(split);
91 if (mode == "models")
92 {
93 var m = RageModelDecoder.Decode(sys, gfx);
94 if (m == null) { fail++; continue; }
95 string obj = Path.Combine(sub, stem + ".obj");
96 if (!File.Exists(obj)) File.WriteAllText(obj, RageModelDecoder.CreateObj(m));
97 if (m.EmbeddedTextures != null && m.EmbeddedTextureDictionaryOffset is int dOff)
98 {
99 string td = Path.Combine(sub, stem + "_tex"); Directory.CreateDirectory(td);
100 foreach (var t in m.EmbeddedTextures)
101 {
102 string p = Path.Combine(td, $"{t.Index:D3}_{Util.Safe(t.Name)}.dds");
103 if (File.Exists(p)) { embedded++; continue; }
104 try { File.WriteAllBytes(p, Util.BgraDds(RageTextureDecoder.DecodeEmbeddedTexturePixels(sys, gfx, dOff, t.Index))); embedded++; } catch { }
105 }
106 }
107 rows.Add(new { e.Offset, File = stem + ".obj", m.Name, Meshes = m.Meshes.Count, Verts = m.Meshes.Sum(x => x.Positions.Count), Tris = m.Meshes.Sum(x => x.Indices.Count) / 3, m.IsFragment, m.HasBoneBindings,
108 Min = new[] { m.BoundsMin.X, m.BoundsMin.Y, m.BoundsMin.Z }, Max = new[] { m.BoundsMax.X, m.BoundsMax.Y, m.BoundsMax.Z },
109 MeshShaders = m.Meshes.Select(x => x.ShaderIndex),
110 Embedded = m.EmbeddedTextures?.Select(t => new { t.Index, t.Name, t.Width, t.Height, t.Format, Hash = t.NameHash.ToString("X8"), Key = t.AssetKey?.ToString("X16") }),
111 Materials = m.Materials?.Select(x => new { x.ShaderIndex, Shader = x.ShaderHash.ToString("X8"), Preset = x.PresetHash.ToString("X8"), x.RenderBucket,
112 Textures = x.Textures.Select(r => new { Param = r.ParameterHash.ToString("X8"), r.TextureIndex, Name = r.NameHash.ToString("X8"), Id64 = r.OpaqueId64.ToString("X16"), Tag = r.Tag.ToString("X8") }) }) });
113 ok++;
114 }
115 else
116 {
117 var dict = RageTextureDecoder.Inspect(sys, gfx);
118 if (dict == null) { fail++; continue; }
119 string td = Path.Combine(sub, stem); Directory.CreateDirectory(td);
120 foreach (var t in dict.Textures)
121 {
122 string p = Path.Combine(td, $"{t.Index:D3}_{Util.Safe(t.Name)}.dds");
123 try { if (!File.Exists(p)) File.WriteAllBytes(p, RageTextureDecoder.CreateDds(sys, gfx, t.Index)); ok++; } catch { fail++; }
124 }
125 rows.Add(new { e.Offset, Dir = stem, Textures = dict.Textures.Select(t => new { t.Index, t.Name, t.Width, t.Height, t.Format, t.MipCount, Hash = t.NameHash.ToString("X8"), Key = t.AssetKey?.ToString("X16") }) });
126 }
127 }
128 catch (Exception ex) { fail++; if (fail <= 5) Console.WriteLine($" fail {e.Name}: {ex.GetType().Name} {ex.Message}"); }
129 if ((ok + fail) % 1000 == 0) Console.WriteLine($" exported {ok + fail:N0}/{list.Count:N0}");
130 }
131 if (mode == "models") Console.WriteLine($" embedded textures {embedded:N0}");
132 File.WriteAllText(Path.Combine(sub, "manifest.json"), JsonSerializer.Serialize(new { src, Count = list.Count, Items = rows }, json));
133}
134Console.WriteLine($"{mode} {baseName}: ok={ok} fail={fail} skip={skip} in {sw.Elapsed.TotalSeconds:0}s");
135return 0;
136
137static class Util
138{
139 public static string Safe(string s)
140 {
141 var bad = Path.GetInvalidFileNameChars();
142 var c = s.Select(ch => bad.Contains(ch) || char.IsControl(ch) ? '_' : ch).ToArray();
143 var v = new string(c).Trim(' ', '.'); return v.Length == 0 ? "x" : v[..Math.Min(120, v.Length)];
144 }
145 // Uncompressed 32-bit BGRA DDS (legacy header, A8R8G8B8 masks).
146 public static byte[] BgraDds(RageTexturePixels px)
147 {
148 var o = new byte[128 + px.Bgra32.Length];
149 void U(int at, uint v) => BitConverter.TryWriteBytes(o.AsSpan(at), v);
150 U(0, 0x20534444); U(4, 124); U(8, 0x100F); U(12, (uint)px.Height); U(16, (uint)px.Width); U(20, (uint)(px.Width * 4));
151 U(76, 32); U(80, 0x41); U(88, 32); U(92, 0x00FF0000); U(96, 0x0000FF00); U(100, 0x000000FF); U(104, 0xFF000000); U(108, 0x1000);
152 px.Bgra32.CopyTo(o, 128); return o;
153 }
154}