use std::sync::Arc;
use crate::bundle::{self, Asset, FileRef, Kind, Manifest};
use crate::folder::Source;
use crate::toc::{Toc, TocChunk};
use crate::{Error, Result, depot, hex, lookup};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Listed {
pub toc: String,
pub bundle: String,
pub kind: Kind,
pub index: usize,
pub name: String,
pub resource_type: Option<u32>,
pub resource_id: Option<u64>,
pub size: u32,
pub file: FileRef,
}
#[derive(Clone, Debug)]
pub struct Bundle {
pub toc_path: String,
pub name: String,
pub(super) toc: Arc<Toc>,
pub(super) files: Vec<FileRef>,
pub(super) first: usize,
pub manifest: Manifest,
}
#[derive(Clone, Debug, Default)]
pub struct Listing {
pub bundles: Vec<Bundle>,
pub unread: Vec<(String, String)>,
}
impl Listing {
pub fn entries(&self) -> impl Iterator<Item = Listed> + '_ {
self.bundles.iter().flat_map(Bundle::entries)
}
}
impl Bundle {
fn file_index(&self, kind: Kind, index: usize) -> usize {
let m = &self.manifest;
let before = match kind {
Kind::Ebx => 0,
Kind::Res => m.ebx.len(),
Kind::Chunk => m.ebx.len().saturating_add(m.res.len()),
};
self.first.saturating_add(before).saturating_add(index)
}
fn listed(&self, kind: Kind, index: usize, a: &Asset) -> Option<Listed> {
let res = kind == Kind::Res;
Some(Listed {
toc: self.toc_path.clone(),
bundle: self.name.clone(),
kind,
index,
name: match kind {
Kind::Chunk => hex(&a.guid),
_ => a.name.clone(),
},
resource_type: res.then_some(a.rtype),
resource_id: res.then_some(a.rid),
size: if kind == Kind::Chunk { a.lsize } else { a.size },
file: *self.files.get(self.file_index(kind, index))?,
})
}
pub fn entries(&self) -> impl Iterator<Item = Listed> + '_ {
let m = &self.manifest;
let ebx = (m.ebx.iter().enumerate()).filter_map(move |(i, a)| self.listed(Kind::Ebx, i, a));
let res = (m.res.iter().enumerate()).filter_map(move |(i, a)| self.listed(Kind::Res, i, a));
let chunks = (m.chunks.iter().enumerate()).filter_map(move |(i, a)| self.listed(Kind::Chunk, i, a));
ebx.chain(res).chain(chunks)
}
pub fn ebx(&self, i: usize) -> Option<Listed> {
self.listed(Kind::Ebx, i, self.manifest.ebx.get(i)?)
}
pub fn resource(&self, i: usize) -> Option<Listed> {
self.listed(Kind::Res, i, self.manifest.res.get(i)?)
}
pub fn toc_chunk(&self, src: &Source<'_>, guid: &[u8; 16]) -> Result<Option<(FileRef, usize)>> {
let Some(TocChunk { file, .. }) = self.toc.chunks.iter().find(|c| &c.guid == guid) else {
return Ok(None);
};
let file =
file.ok_or_else(|| Error::Missing(format!("{}: chunk {} is removed", self.name, hex(guid))))?;
let raw = src.raw(file)?;
let blocks = crate::cas::blocks(&raw)?;
Ok(Some((
file,
blocks
.iter()
.map(|b| b.decoded_size)
.fold(0usize, usize::saturating_add),
)))
}
pub fn chunk(&self, src: &Source<'_>, guid: &[u8; 16]) -> Result<(FileRef, usize)> {
let m = &self.manifest;
if let Some((i, c)) = m.chunks.iter().enumerate().find(|(_, c)| &c.guid == guid) {
let file = self.files.get(self.file_index(Kind::Chunk, i)).ok_or_else(|| {
Error::Missing(format!(
"{}: chunk {} has no file in the bundle's file table",
self.name,
hex(guid)
))
})?;
return Ok((*file, c.lsize as usize));
}
let TocChunk { file, .. } = self.toc.chunks.iter().find(|c| &c.guid == guid).ok_or_else(|| {
Error::Missing(format!(
"{}: chunk {} is in neither the bundle nor its TOC",
self.name,
hex(guid)
))
})?;
let file =
file.ok_or_else(|| Error::Missing(format!("{}: chunk {} is removed", self.name, hex(guid))))?;
let raw = src.raw(file)?;
let blocks = crate::cas::blocks(&raw)?;
Ok((
file,
blocks
.iter()
.map(|b| b.decoded_size)
.fold(0usize, usize::saturating_add),
))
}
}
pub fn resource_type_name(rtype: u32) -> Option<&'static str> {
TYPE_NAMES
.iter()
.find(|(id, _)| *id == rtype)
.map(|(_, name)| *name)
}
pub const TYPE_NAMES: &[(u32, &str)] = &[
(crate::TEXTURE, "Texture"),
(crate::MESHSET, "MeshSet"),
(depot::RTYPE, "ShaderBlockDepotResource"),
(crate::bytecode::RTYPE, "CompiledBytecode"),
(lookup::PROGRAM_LOOKUP, "ExpressionShaderDatabase"),
(
lookup::TEXTURE_LOOKUP,
"ExpressionShaderStreamableTextureSetLookupTable",
),
(0x2FEC_6526, "ShaderStateAssetId"),
(0xD489_FACB, "ExpressionShaderRasterPermutation"),
(0x95CE_62DD, "ExpressionShaderComputePermutation"),
(0xA19B_025D, "ExpressionShaderBindingSet"),
(0x7D98_F632, "ExpressionShaderInputLayout"),
(0x2500_47B2, "ExpressionShaderRasterPermutationSharedData"),
(0x879B_A711, "ExpressionShaderPermutationSharedData"),
(0x7A63_0735, "ExpressionShaderStreamableTextureSet"),
(0xA895_7ED6, "ExpressionShaderRootSlotInitData"),
(0x589B_B36E, "ExpressionShaderPassBinding"),
(0x6A5B_E5DB, "ExpressionShaderBindingSignature"),
(0xF434_940D, "ShaderParameterCollectionTable"),
(0x4175_9364, "PhysicsResource"),
(0x30B4_A553, "OccluderMesh"),
(0x1CA3_8E06, "VisualTerrain"),
(0x957C_32B1, "AtlasTexture"),
(0xDE54_0C59, "LayerGraphs"),
(0x428E_C9D4, "BundleRefTableResource"),
(0x22FE_8AC8, "TerrainStreamingTree"),
(0x15E1_F32E, "TerrainDecals"),
];
pub fn type_id(name: &str) -> u32 {
crate::djb2(&name.to_ascii_lowercase())
}
impl Source<'_> {
pub fn bundle_names(&self, toc: &str) -> Result<Vec<String>> {
Ok(self
.folder
.toc(toc)?
.bundles
.into_iter()
.map(|(n, _)| n)
.collect())
}
fn open_bundle(&self, toc_path: &str, toc: &Arc<Toc>, name: &str, region: &[u8]) -> Result<Bundle> {
let (files, inline) = bundle::read_region(region)?;
let (manifest, first, _) = self
.manifest(&files, &inline)?
.ok_or_else(|| Error::Missing(format!("{name} has no manifest")))?;
Ok(Bundle {
toc_path: toc_path.to_owned(),
name: name.to_owned(),
toc: Arc::clone(toc),
files,
first,
manifest,
})
}
pub fn bundle(&self, toc: &str, name: &str) -> Result<Bundle> {
let t = Arc::new(self.folder.toc(toc)?);
let (n, region) = t
.bundles
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(name))
.ok_or_else(|| Error::Missing(format!("{toc} has no bundle {name}")))?;
self.open_bundle(toc, &t, n, region)
}
pub fn listing(&self, toc: &str) -> Result<Listing> {
let t = Arc::new(self.folder.toc(toc)?);
let mut out = Listing::default();
for (name, region) in &t.bundles {
match self.open_bundle(toc, &t, name, region) {
Ok(b) => out.bundles.push(b),
Err(e) => out.unread.push((name.clone(), e.to_string())),
}
}
Ok(out)
}
pub fn ebx_type(&self, entry: &Listed) -> Result<String> {
if entry.kind != Kind::Ebx {
return Err(Error::Unsupported(format!("{}: not an EBX document", entry.name)));
}
let bytes = self.payload(entry.file, entry.size as usize)?;
Ok(crate::ebx::read(&bytes)?.root_type)
}
}