use crate::{Rd, Result, bad};
const W: &str = "shader permutation";
pub const RASTER: u32 = 0xD489_FACB;
pub const COMPUTE: u32 = 0x95CE_62DD;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Raster,
Compute,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Permutation {
pub kind: Kind,
pub id: u64,
pub shared_data: u64,
pub input_layout: Option<u64>,
pub unknown_18: u64,
pub bytecode: Vec<[u8; 16]>,
}
pub fn resource_id(meta: &[u8; 16]) -> u64 {
meta.last_chunk::<8>().map_or(0, |id| u64::from_le_bytes(*id))
}
pub fn bytecode_name(g: &[u8; 16]) -> String {
format!("shaders/bytecode/{}", crate::guid_text(g))
}
pub fn read(rtype: u32, d: &[u8], meta: &[u8; 16]) -> Result<Permutation> {
let kind = match rtype {
RASTER => Kind::Raster,
COMPUTE => Kind::Compute,
t => return Err(bad(W, 0, format!("type {t:#010x} is not a permutation"))),
};
let m = Rd::new(meta, W);
let (size, reloc) = (m.size32le(0)?, m.size32le(4)?);
if size.checked_add(reloc) != Some(d.len()) {
return Err(bad(
W,
0,
format!("size {size} + relocations {reloc} != {}", d.len()),
));
}
let r = Rd::new(d, W);
if reloc != 4 || r.u32le(size)? != 8 {
return Err(bad(W, size, "relocations are not the pointer at 8 alone"));
}
let start = match kind {
Kind::Raster => 0x20,
Kind::Compute => 0x10,
};
let guids_len = size.checked_sub(start).filter(|&n| n > 0 && n.is_multiple_of(16));
let Some(guids_len) = guids_len.filter(|_| r.u64le(8).is_ok_and(|p| usize::try_from(p) == Ok(start)))
else {
return Err(bad(
W,
8,
format!(
"GUIDs at {:#x} in a payload of {size}, not at {start:#x} to its end",
r.u64le(8)?
),
));
};
let count = guids_len / 16;
if count > 2 || (kind == Kind::Compute && count != 1) {
return Err(bad(
W,
start,
format!("{count} programs in a {kind:?} permutation"),
));
}
Ok(Permutation {
kind,
id: resource_id(meta),
shared_data: r.u64le(0)?,
input_layout: (kind == Kind::Raster).then(|| r.u64le(0x10)).transpose()?,
unknown_18: if kind == Kind::Raster { r.u64le(0x18)? } else { 0 },
bytecode: (0..count)
.map(|i| r.arr::<16>(crate::at(start, i, 16)))
.collect::<Result<_>>()?,
})
}
pub const SHARED_RASTER: u32 = 0x2500_47B2;
pub const SHARED_COMPUTE: u32 = 0x879B_A711;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SharedData {
pub id: u64,
pub pass_binding: Option<u64>,
pub signature: u64,
pub sets: [Option<u64>; 3],
pub root_slots: u64,
pub words: [u64; 2],
pub rest: Vec<u8>,
}
pub fn read_shared(rtype: u32, d: &[u8], meta: &[u8; 16]) -> Result<SharedData> {
if rtype != SHARED_RASTER && rtype != SHARED_COMPUTE {
return Err(bad(
"shared data",
0,
format!("type {rtype:#010x} is not shared data"),
));
}
let m = Rd::new(meta, "shared data");
let (size, reloc) = (m.size32le(0)?, m.size32le(4)?);
if size.checked_add(reloc) != Some(d.len()) {
return Err(bad(
"shared data",
0,
format!("size {size} + relocations {reloc} != {}", d.len()),
));
}
let r = Rd::new(d, "shared data");
let some = |at: usize| -> Result<Option<u64>> { Ok(Some(r.u64le(at)?).filter(|&v| v != 0)) };
let signature = r.u64le(8)?;
let root_slots = r.u64le(0x38)?;
if signature == 0 || root_slots == 0 {
return Err(bad(
"shared data",
8,
"a shared data without a signature or root slots",
));
}
Ok(SharedData {
id: resource_id(meta),
pass_binding: some(0)?,
signature,
sets: [some(0x18)?, some(0x20)?, some(0x28)?],
root_slots,
words: [r.u64le(0x10)?, r.u64le(0x30)?],
rest: r.bytes(0x40, d.len().saturating_sub(0x40))?.to_vec(),
})
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Compare {
Never,
Less,
Equal,
LessEqual,
Greater,
NotEqual,
GreaterEqual,
Always,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum StencilOp {
Keep,
Zero,
Replace,
IncrementSaturate,
DecrementSaturate,
Invert,
Increment,
Decrement,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BlendOp {
Add,
Subtract,
ReverseSubtract,
Min,
Max,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Cull {
None,
Front,
Back,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Fill {
Solid,
Wireframe,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct StencilFace {
pub fail: StencilOp,
pub depth_fail: StencilOp,
pub pass: StencilOp,
pub compare: Compare,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FixedState {
pub slope_scaled_depth_bias: f32,
pub depth_bias: i16,
pub forced_sample_count: u8,
pub fill: Fill,
pub cull: Cull,
pub front_counter_clockwise: bool,
pub depth_clip: bool,
pub multisample: bool,
pub antialiased_line: bool,
pub conservative: bool,
pub depth_test: bool,
pub depth_write: bool,
pub stencil_test: bool,
pub depth_compare: Compare,
pub stencil_read_mask: u8,
pub stencil_write_mask: u8,
pub front: StencilFace,
pub back: StencilFace,
pub logic_op: u8,
pub logic_op_enable: bool,
pub alpha_to_coverage: bool,
pub independent_blend: bool,
pub targets: [TargetRecord; 8],
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TargetRecord {
pub blend: bool,
pub source: u8,
pub destination: u8,
pub source_alpha: u8,
pub destination_alpha: u8,
pub alpha_op: BlendOp,
pub write_mask: u8,
}
const COMPARES: [Compare; 8] = [
Compare::Never,
Compare::Less,
Compare::Equal,
Compare::LessEqual,
Compare::Greater,
Compare::NotEqual,
Compare::GreaterEqual,
Compare::Always,
];
const STENCIL_OPS: [StencilOp; 8] = [
StencilOp::Keep,
StencilOp::Zero,
StencilOp::Replace,
StencilOp::IncrementSaturate,
StencilOp::DecrementSaturate,
StencilOp::Invert,
StencilOp::Increment,
StencilOp::Decrement,
];
const BLEND_OPS: [BlendOp; 5] = [
BlendOp::Add,
BlendOp::Subtract,
BlendOp::ReverseSubtract,
BlendOp::Min,
BlendOp::Max,
];
const STATE_AT: usize = 0x78;
const STATE_END: usize = 0x8c + 8 * 5;
impl SharedData {
pub fn fixed_state(&self) -> Result<FixedState> {
const W: &str = "shared data state";
let s = self.rest.get(STATE_AT - 0x40..STATE_END - 0x40).ok_or_else(|| {
bad(
W,
STATE_AT,
format!("{} bytes hold no state", self.rest.len().saturating_add(0x40)),
)
})?;
let b = |o: usize| s.get(o.wrapping_sub(STATE_AT)).copied().unwrap_or(0);
fn pick<T: Copy>(table: &[T; 8], v: u8, at: usize) -> Result<T> {
table
.get(usize::from(v & 7))
.copied()
.ok_or_else(|| bad("shared data state", at, format!("table index {v}")))
}
let face = |o: usize| -> Result<StencilFace> {
Ok(StencilFace {
fail: pick(&STENCIL_OPS, b(o), o)?,
depth_fail: pick(&STENCIL_OPS, b(o) >> 3, o)?,
pass: pick(&STENCIL_OPS, b(o.saturating_add(1)), o)?,
compare: pick(&COMPARES, b(o.saturating_add(1)) >> 3, o)?,
})
};
let mode = |o: usize| -> Result<u8> {
let v = b(o) & 0x1f;
if v > 16 {
return Err(bad(W, o, format!("blend mode {v} is past the game's 17")));
}
Ok(v)
};
let mut targets = [TargetRecord {
blend: false,
source: 0,
destination: 0,
source_alpha: 0,
destination_alpha: 0,
alpha_op: BlendOp::Add,
write_mask: 0,
}; 8];
for (i, t) in targets.iter_mut().enumerate() {
let o = crate::at(0x8c, i, 5);
let at = |k: usize| o.saturating_add(k);
if b(at(1)) >> 5 != 0 {
return Err(bad(
W,
at(1),
"colour blend operation bits are set, expected the top 3 bits clear",
));
}
let source = b(o) >> 1 & 0x1f;
if source > 16 {
return Err(bad(W, o, format!("blend mode {source} is past the game's 17")));
}
*t = TargetRecord {
blend: b(o) & 1 != 0,
source,
destination: mode(at(1))?,
source_alpha: mode(at(2))?,
destination_alpha: mode(at(3))?,
alpha_op: *BLEND_OPS.get(usize::from(b(at(3)) >> 5)).ok_or_else(|| {
bad(
W,
at(3),
format!("blend op {} is past the game's 5", b(at(3)) >> 5),
)
})?,
write_mask: b(at(4)),
};
}
let (raster, depth, blend) = (b(0x7f), b(0x80), b(0x87));
Ok(FixedState {
slope_scaled_depth_bias: f32::from_le_bytes([b(0x78), b(0x79), b(0x7a), b(0x7b)]),
depth_bias: i16::from_le_bytes([b(0x7c), b(0x7d)]),
forced_sample_count: b(0x7e),
fill: if raster & 1 == 0 {
Fill::Solid
} else {
Fill::Wireframe
},
cull: match raster >> 1 & 3 {
0 => Cull::None,
1 => Cull::Front,
2 => Cull::Back,
_ => return Err(bad(W, 0x7f, "cull mode 3")),
},
front_counter_clockwise: raster >> 3 & 1 != 0,
depth_clip: raster >> 4 & 1 != 0,
multisample: raster >> 5 & 1 != 0,
antialiased_line: raster >> 6 & 1 != 0,
conservative: raster >> 7 != 0,
depth_test: depth & 1 != 0,
depth_write: depth >> 1 & 1 != 0,
stencil_test: depth >> 2 & 1 != 0,
depth_compare: pick(&COMPARES, depth >> 3, 0x80)?,
stencil_read_mask: b(0x81),
stencil_write_mask: b(0x82),
front: face(0x83)?,
back: face(0x85)?,
logic_op: blend & 0xf,
logic_op_enable: blend >> 4 & 1 != 0,
alpha_to_coverage: blend >> 5 & 1 != 0,
independent_blend: blend >> 6 & 1 != 0,
targets,
})
}
}