mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 12:20:42 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5df1f9146f | ||
|
|
48e42d6d4b | ||
|
|
951189c61b | ||
|
|
7c89ed62a2 | ||
|
|
f19d57967d | ||
|
|
ef1a94ce71 |
No files matched your search
@@ -1,6 +1,8 @@
|
||||
## Summary
|
||||
|
||||
<!-- What changes, and why? Link an issue if relevant. -->
|
||||
<!-- What changes, and why? -->
|
||||
|
||||
Closes #<!-- the issue you claimed -->
|
||||
|
||||
## Implementation and evidence
|
||||
|
||||
@@ -23,6 +25,7 @@
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] I claimed the linked issue before starting, and the claim was still mine when I opened this pull request.
|
||||
- [ ] I reviewed the changes and disclosed material AI assistance below, if applicable.
|
||||
- [ ] The change preserves native ARM64 and Metal-first requirements.
|
||||
- [ ] I added relevant tests or explained why they are not applicable.
|
||||
|
||||
@@ -45,6 +45,19 @@ No AI slop (section 29).
|
||||
|
||||
Read docs/interfaces.md and docs/progress.md before implementation.
|
||||
|
||||
## Claiming work before you start
|
||||
|
||||
Several people and coding agents work on this repository at the same time. An issue with no visible claim is the only signal that a task is free, so claim before you edit anything.
|
||||
|
||||
1. **Check.** Read the issue's comments, assignees and labels, its linked pull requests, and open pull requests that touch the same files. If someone holds a live claim, pick another task. Do not start parallel work on a claimed task.
|
||||
2. **Claim.** Comment `/claim` on the issue (or run `scripts/agent-queue.sh claim <n>`). Where the claim workflow is enabled, wait for its grant comment and the `claimed-by:<login>` label; a refusal names the reason. Where it is not enabled yet, your comment is the claim and the earliest valid claim comment wins. One issue per claim; claim follow-up tasks separately.
|
||||
3. **Respect file ownership.** Two claimed tasks never edit the same files at the same time. If the issue lists files, edit only those; ask the maintainer before widening the list.
|
||||
4. **Keep it alive.** A claim lapses 24 hours after the latest grant, `/progress <what changed>` comment, or push to the linked pull request. Post `/progress` at least once a day while you work. Lapsed tasks return to the queue and may be claimed by anyone.
|
||||
5. **Release.** If you stop, comment `/release` so the task returns to the queue. Use `/blocked <reason>` instead if you are waiting on another task.
|
||||
6. **Link.** Open the pull request from a branch named `task/<n>-<slug>` with `Closes #<n>` in its description.
|
||||
|
||||
An agent acting for a contributor claims in that contributor's name and must not claim work for areas that contributor may not claim (`.github/agent-queue.json`). Never remove, overwrite or ignore another person's claim; ask the maintainer to `/reassign` instead. See `docs/coordination/agent-tasks.md` when present.
|
||||
|
||||
## Changelog maintenance
|
||||
|
||||
- At the start of every engineering task, read `CHANGELOG.md` alongside the relevant project documentation. Review the existing `[Unreleased]` entries before implementation to avoid duplicating completed work.
|
||||
|
||||
@@ -11,6 +11,8 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- Added explicit claim-before-work rules for contributors and coding agents to `AGENTS.md`, `CONTRIBUTING.md` and the pull request template: check for existing claims, claim with `/claim`, keep a 24-hour lease alive with `/progress`, `/release` when stopping, and link the claimed issue. Without the claim workflow, the earliest valid claim comment wins.
|
||||
- Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet.
|
||||
- Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution
|
||||
test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and
|
||||
verifies the value lands in guest memory.
|
||||
|
||||
@@ -6,6 +6,7 @@ Xenora is an experimental Xbox Series X|S recompilation framework for Apple Sili
|
||||
|
||||
- Read `README.md` and, when present, `AGENTS.md`, `docs/interfaces.md`, `docs/status.toml` and the relevant architecture decisions.
|
||||
- Discuss substantial changes in an issue before implementing them; small fixes do not require prior approval.
|
||||
- Claim an issue before working on it by commenting `/claim`, and check that nobody else holds a live claim first. Claims lapse after 24 hours without a `/progress` comment or a push; comment `/release` if you stop. Coding agents follow the same rules; see "Claiming work before you start" in `AGENTS.md`.
|
||||
- Use a native ARM64 macOS environment with Rust and the appropriate Xcode/Metal tools. LLVM AMDGPU tools are needed for ISA fixture generation; extra tooling depends on the subsystem.
|
||||
- Keep changes focused and preserve existing public interfaces unless a change is justified and documented.
|
||||
|
||||
|
||||
@@ -276,21 +276,16 @@ impl<'a> Interpreter<'a> {
|
||||
// HLT: Halt execution
|
||||
0xF4 => Ok(Some(ExitReason::Halt)),
|
||||
|
||||
0x0F => match self.fetch_u8()? {
|
||||
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
|
||||
op @ 0xC8..=0xCF => {
|
||||
let reg = Register::from_index((op & 7) | (u8::from(rex_b) << 3));
|
||||
let value = self.cpu.get(reg);
|
||||
let reversed = if rex_w {
|
||||
value.swap_bytes()
|
||||
} else {
|
||||
u64::from((value as u32).swap_bytes())
|
||||
};
|
||||
self.cpu.set(reg, reversed);
|
||||
Ok(None)
|
||||
// SYSCALL: 0x0F 0x05
|
||||
0x0F => {
|
||||
let second = self.fetch_u8()?;
|
||||
if second == 0x05 {
|
||||
let syscall_num = self.cpu.get(Register::Rax);
|
||||
Ok(Some(ExitReason::Syscall(syscall_num)))
|
||||
} else {
|
||||
Err(ExitReason::IllegalInstruction(second))
|
||||
}
|
||||
op => Err(ExitReason::IllegalInstruction(op)),
|
||||
},
|
||||
}
|
||||
|
||||
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
|
||||
0xB8..=0xBF => {
|
||||
|
||||
@@ -1077,16 +1077,6 @@ impl DbtEngine {
|
||||
cur_rip += 1;
|
||||
|
||||
match op2 {
|
||||
// BSWAP r32/r64: the register is encoded in the opcode.
|
||||
0xC8..=0xCF => {
|
||||
insn_count += 1;
|
||||
let reg = (op2 & 7) | (u8::from(rex_b) << 3);
|
||||
let offset = u32::from(reg) * 8;
|
||||
asm.ldr_uoff_64(X9, X19, offset);
|
||||
// REV X9, X9 or REV W9, W9. A W write clears the upper half.
|
||||
asm.emit(if rex_w { 0xdac0_0d29 } else { 0x5ac0_0929 });
|
||||
asm.str_uoff_64(X9, X19, offset);
|
||||
}
|
||||
// Jcc rel32 (0x0F 0x80..=0x8F)
|
||||
0x80..=0x8F => {
|
||||
insn_count += 1;
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
|
||||
fn check_bswap(native: bool) {
|
||||
const ENTRY: u64 = 0x1000;
|
||||
const INPUT: u64 = 0x1122_3344_5566_7788;
|
||||
for reg in 0_u8..16 {
|
||||
for width in [16, 32, 64] {
|
||||
let wide = width == 64;
|
||||
let mut code = Vec::new();
|
||||
if width == 16 {
|
||||
code.push(0x66);
|
||||
}
|
||||
let rex = 0x40 | (u8::from(wide) << 3) | (reg >> 3);
|
||||
if rex != 0x40 {
|
||||
code.push(rex);
|
||||
}
|
||||
code.extend([0x0f, 0xc8 + (reg & 7)]);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr.fill(0xdead_beef);
|
||||
cpu.gpr[reg as usize] = INPUT;
|
||||
cpu.flags = RFlags {
|
||||
cf: wide,
|
||||
zf: !wide,
|
||||
sf: wide,
|
||||
of: !wide,
|
||||
};
|
||||
let flags = cpu.flags;
|
||||
let mut expected = cpu.gpr;
|
||||
let result = if native {
|
||||
DbtEngine::new(16 * 1024)
|
||||
.unwrap()
|
||||
.run(&mut cpu, &mut memory, 1)
|
||||
} else {
|
||||
Interpreter::new(cpu, &mut memory, 1).run()
|
||||
};
|
||||
if width == 16 {
|
||||
assert!(matches!(
|
||||
result.exit_reason,
|
||||
ExitReason::IllegalInstruction(_)
|
||||
));
|
||||
assert_eq!(result.instructions_executed, 0);
|
||||
} else {
|
||||
assert_eq!(
|
||||
result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{code:02x?}"
|
||||
);
|
||||
assert_eq!(result.instructions_executed, 1);
|
||||
assert_eq!(result.final_state.rip, ENTRY + code.len() as u64);
|
||||
expected[reg as usize] = if wide {
|
||||
0x8877_6655_4433_2211
|
||||
} else {
|
||||
0x8877_6655
|
||||
};
|
||||
}
|
||||
assert_eq!(result.final_state.gpr, expected);
|
||||
assert_eq!(result.final_state.flags, flags);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpreter_bswap() {
|
||||
check_bswap(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_bswap() {
|
||||
check_bswap(true);
|
||||
}
|
||||
@@ -259,106 +259,3 @@ fn probe_consumes_complete_c7_operands_even_when_native_support_is_missing() {
|
||||
assert!(!records[1].is_supported_dbt);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exported_reports_agree_across_fixtures_and_blocker_locations() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("xenora-report-consistency-{}", std::process::id()));
|
||||
// (file offset, RVA) for a reachable instruction immediately after a MOV.
|
||||
for (fixture, file_offset, rva, sections, imports) in [
|
||||
(create_synthetic_probe_pe(), 0x209, 0x1009_u32, 1, 0),
|
||||
(
|
||||
include_bytes!("../../../fixtures/pe/trusted-runner.exe").to_vec(),
|
||||
0x44e,
|
||||
0x104e,
|
||||
4,
|
||||
1,
|
||||
),
|
||||
] {
|
||||
assert_eq!(fixture[file_offset], 0xc3);
|
||||
for padding in [None, Some(0), Some(1), Some(7)] {
|
||||
let mut pe = fixture.clone();
|
||||
let blocker = padding.map(|n| {
|
||||
pe[file_offset..file_offset + n].fill(0x90);
|
||||
pe[file_offset + n] = 0xcc;
|
||||
rva + n as u32
|
||||
});
|
||||
run_probe_and_export(&pe, &dir, &ProbeConfig::default()).unwrap();
|
||||
let read = |name| std::fs::read_to_string(dir.join(name)).unwrap();
|
||||
let md = read("candidate_static_report.md");
|
||||
let json = read("candidate_static_report.json");
|
||||
let cpu = read("cpu_coverage.csv");
|
||||
let import_csv = read("imports.csv");
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
|
||||
let json_field = |name: &str| {
|
||||
let prefix = format!("\"{name}\": ");
|
||||
json.lines()
|
||||
.find_map(|line| line.trim().strip_prefix(&prefix))
|
||||
.unwrap()
|
||||
.trim_end_matches(',')
|
||||
.trim_matches('"')
|
||||
};
|
||||
assert_eq!(json_field("sections_count"), sections.to_string());
|
||||
assert!(
|
||||
md.lines()
|
||||
.any(|line| line == format!("## Sections Census ({sections})"))
|
||||
);
|
||||
assert_eq!(
|
||||
md.lines()
|
||||
.filter(|line| line.contains(" VirtualSize: "))
|
||||
.count(),
|
||||
sections
|
||||
);
|
||||
|
||||
assert_eq!(json_field("total_imports"), imports.to_string());
|
||||
assert!(
|
||||
md.lines()
|
||||
.any(|line| line == format!("- **Total Imported Thunks**: `{imports}`"))
|
||||
);
|
||||
assert_eq!(import_csv.lines().skip(1).count(), imports);
|
||||
|
||||
let expected = blocker.map(|addr| format!("0x{addr:08x}"));
|
||||
assert_eq!(
|
||||
json_field("first_unsupported_dbt_rva"),
|
||||
expected.as_deref().unwrap_or("none")
|
||||
);
|
||||
let md_rvas: Vec<_> = md
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
line.strip_prefix("- **RVA**: `")?
|
||||
.split_once('`')
|
||||
.map(|(addr, _)| addr)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(md_rvas, expected.iter().collect::<Vec<_>>());
|
||||
|
||||
// The first columns precede quoted fields. Read the support flags from
|
||||
// the closing quote of the mnemonic, which can itself contain commas.
|
||||
let mut unsupported = Vec::new();
|
||||
let mut tail = Vec::new();
|
||||
for row in cpu.lines().skip(1) {
|
||||
let (addr, rest) = row.split_once(',').unwrap();
|
||||
let (_, fields) = rest.split_once(",\"").unwrap();
|
||||
let (bytes, mnemonic) = fields.split_once("\",\"").unwrap();
|
||||
let (_, flags) = mnemonic.split_once("\",").unwrap();
|
||||
if flags.split(',').next() == Some("false") {
|
||||
unsupported.push(addr);
|
||||
}
|
||||
let address = u32::from_str_radix(addr.strip_prefix("0x").unwrap(), 16).unwrap();
|
||||
if address >= rva {
|
||||
tail.push((address, bytes));
|
||||
}
|
||||
}
|
||||
assert_eq!(unsupported, expected.iter().collect::<Vec<_>>());
|
||||
let mut expected_tail = Vec::new();
|
||||
if let Some(end) = blocker {
|
||||
expected_tail.extend((rva..end).map(|addr| (addr, "90")));
|
||||
expected_tail.push((end, "cc"));
|
||||
} else {
|
||||
expected_tail.push((rva, "c3"));
|
||||
}
|
||||
assert_eq!(tail, expected_tail);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//! CPU block decoders for BC2, BC3, BC4 and BC5.
|
||||
//!
|
||||
//! Sources (public): Microsoft, "Texture Block Compression in Direct3D 11"
|
||||
//! (sections BC2, BC3, BC4, BC5) and "Block Compression (Direct3D 10)"; Khronos
|
||||
//! Data Format Specification 1.3, sections "S3TC compressed texture image
|
||||
//! formats" and "RGTC compressed texture image formats".
|
||||
//!
|
||||
//! Colour blocks of BC2 and BC3 always use the four-colour interpolation,
|
||||
//! whatever the order of their endpoints (Khronos, "S3TC compressed texture
|
||||
//! image formats", DXT3/DXT5 subsections; the BC1 three-colour/alpha mode does
|
||||
//! not apply). Texels are row-major, texel 0 at the top-left.
|
||||
//!
|
||||
//! Rounding: every interpolated value uses integer division that truncates
|
||||
//! toward zero (the same rule `decode_bc1` uses). For unsigned values that is
|
||||
//! floor. BC2 alpha nibbles expand as `v * 17`. The specifications define the
|
||||
//! interpolation in real numbers; truncation is this crate's integer choice.
|
||||
//!
|
||||
//! SNORM: the specification maps both -128 and -127 to -1.0. Endpoints are
|
||||
//! compared as the stored signed bytes; for interpolation -128 is treated as
|
||||
//! -127. Output bytes are the stored endpoint bytes for indices 0 and 1 (so
|
||||
//! -128 is preserved, not rewritten) and -127 / 127 for the fixed values.
|
||||
|
||||
use super::rgb565;
|
||||
|
||||
/// Reads texel `n` of a packed little-endian 48-bit array of 3-bit indices.
|
||||
fn index3(bytes: &[u8; 6], n: usize) -> usize {
|
||||
let mut bits = 0u64;
|
||||
for (i, b) in bytes.iter().enumerate() {
|
||||
bits |= u64::from(*b) << (8 * i);
|
||||
}
|
||||
((bits >> (3 * n)) & 7) as usize
|
||||
}
|
||||
|
||||
fn unorm_palette(a0: u8, a1: u8) -> [u8; 8] {
|
||||
let (x, y) = (u16::from(a0), u16::from(a1));
|
||||
let mut p = [a0, a1, 0, 0, 0, 0, 0, 255];
|
||||
if a0 > a1 {
|
||||
for k in 1..=6u16 {
|
||||
p[(k + 1) as usize] = (((7 - k) * x + k * y) / 7) as u8;
|
||||
}
|
||||
} else {
|
||||
for k in 1..=4u16 {
|
||||
p[(k + 1) as usize] = (((5 - k) * x + k * y) / 5) as u8;
|
||||
}
|
||||
p[6] = 0;
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
fn snorm_palette(a0: i8, a1: i8) -> [i8; 8] {
|
||||
let x = i16::from(a0).max(-127);
|
||||
let y = i16::from(a1).max(-127);
|
||||
let mut p = [a0, a1, 0, 0, 0, 0, 0, 0];
|
||||
if a0 > a1 {
|
||||
for k in 1..=6i16 {
|
||||
p[(k + 1) as usize] = (((7 - k) * x + k * y) / 7) as i8;
|
||||
}
|
||||
} else {
|
||||
for k in 1..=4i16 {
|
||||
p[(k + 1) as usize] = (((5 - k) * x + k * y) / 5) as i8;
|
||||
}
|
||||
p[6] = -127;
|
||||
p[7] = 127;
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
fn unorm_block(block: &[u8]) -> [u8; 16] {
|
||||
let p = unorm_palette(block[0], block[1]);
|
||||
let idx: [u8; 6] = block[2..8].try_into().unwrap();
|
||||
std::array::from_fn(|t| p[index3(&idx, t)])
|
||||
}
|
||||
|
||||
fn snorm_block(block: &[u8]) -> [i8; 16] {
|
||||
let p = snorm_palette(block[0] as i8, block[1] as i8);
|
||||
let idx: [u8; 6] = block[2..8].try_into().unwrap();
|
||||
std::array::from_fn(|t| p[index3(&idx, t)])
|
||||
}
|
||||
|
||||
/// Decodes a BC4 UNORM block to 16 row-major red values.
|
||||
pub fn decode_bc4_unorm(block: [u8; 8]) -> [u8; 16] {
|
||||
unorm_block(&block)
|
||||
}
|
||||
|
||||
/// Decodes a BC4 SNORM block to 16 row-major signed red values.
|
||||
pub fn decode_bc4_snorm(block: [u8; 8]) -> [i8; 16] {
|
||||
snorm_block(&block)
|
||||
}
|
||||
|
||||
/// Decodes a BC5 UNORM block; each texel is `[red, green]` (first 8 bytes red).
|
||||
pub fn decode_bc5_unorm(block: [u8; 16]) -> [[u8; 2]; 16] {
|
||||
let r = unorm_block(&block[..8]);
|
||||
let g = unorm_block(&block[8..]);
|
||||
std::array::from_fn(|t| [r[t], g[t]])
|
||||
}
|
||||
|
||||
/// Decodes a BC5 SNORM block; each texel is `[red, green]`.
|
||||
pub fn decode_bc5_snorm(block: [u8; 16]) -> [[i8; 2]; 16] {
|
||||
let r = snorm_block(&block[..8]);
|
||||
let g = snorm_block(&block[8..]);
|
||||
std::array::from_fn(|t| [r[t], g[t]])
|
||||
}
|
||||
|
||||
/// Four-colour BC1-style palette, forced regardless of endpoint order.
|
||||
fn colour_block(block: &[u8]) -> [[u8; 4]; 16] {
|
||||
let first = u16::from_le_bytes([block[0], block[1]]);
|
||||
let second = u16::from_le_bytes([block[2], block[3]]);
|
||||
let mut p = [rgb565(first), rgb565(second), [255; 4], [255; 4]];
|
||||
for c in 0..3 {
|
||||
let a = u16::from(p[0][c]);
|
||||
let b = u16::from(p[1][c]);
|
||||
p[2][c] = ((2 * a + b) / 3) as u8;
|
||||
p[3][c] = ((a + 2 * b) / 3) as u8;
|
||||
}
|
||||
let bits = u32::from_le_bytes([block[4], block[5], block[6], block[7]]);
|
||||
std::array::from_fn(|t| p[((bits >> (2 * t)) & 3) as usize])
|
||||
}
|
||||
|
||||
/// Decodes a BC2 block to 16 row-major RGBA8 texels (explicit 4-bit alpha).
|
||||
pub fn decode_bc2(block: [u8; 16]) -> [[u8; 4]; 16] {
|
||||
let mut out = colour_block(&block[8..]);
|
||||
for (t, px) in out.iter_mut().enumerate() {
|
||||
// Two texels per byte, low nibble first.
|
||||
px[3] = ((block[t / 2] >> (4 * (t % 2))) & 15) * 17;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Decodes a BC3 block to 16 row-major RGBA8 texels (interpolated alpha).
|
||||
pub fn decode_bc3(block: [u8; 16]) -> [[u8; 4]; 16] {
|
||||
let mut out = colour_block(&block[8..]);
|
||||
let alpha = unorm_block(&block[..8]);
|
||||
for (px, a) in out.iter_mut().zip(alpha) {
|
||||
px[3] = a;
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -7,8 +7,12 @@
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod bc;
|
||||
pub mod sampler;
|
||||
mod upload;
|
||||
pub use bc::{
|
||||
decode_bc2, decode_bc3, decode_bc4_snorm, decode_bc4_unorm, decode_bc5_snorm, decode_bc5_unorm,
|
||||
};
|
||||
pub use sampler::{AddressMode, FilterMode, SamplerDesc, SamplerError, TextureMetadata};
|
||||
pub use upload::{Bc1Subresource, Bc1Upload, Bc1UploadDesc};
|
||||
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//! Expected values are worked by hand from the Microsoft BC2-BC5 and Khronos
|
||||
//! S3TC/RGTC formulas (truncating integer division); the production decoder is
|
||||
//! never used to produce them.
|
||||
|
||||
use xenora_texture::{
|
||||
decode_bc2, decode_bc3, decode_bc4_snorm, decode_bc4_unorm, decode_bc5_snorm, decode_bc5_unorm,
|
||||
};
|
||||
|
||||
/// Packs sixteen 3-bit indices bit by bit, texel 0 in the lowest bit.
|
||||
fn pack3(indices: [u8; 16]) -> [u8; 6] {
|
||||
let mut out = [0u8; 6];
|
||||
for (t, idx) in indices.iter().enumerate() {
|
||||
for bit in 0..3 {
|
||||
if (idx >> bit) & 1 == 1 {
|
||||
let pos = 3 * t + bit;
|
||||
out[pos / 8] |= 1 << (pos % 8);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn bc4(a0: u8, a1: u8, indices: [u8; 16]) -> [u8; 8] {
|
||||
let i = pack3(indices);
|
||||
[a0, a1, i[0], i[1], i[2], i[3], i[4], i[5]]
|
||||
}
|
||||
|
||||
const SEQ: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7];
|
||||
|
||||
fn expect(palette: [u8; 8]) -> [u8; 16] {
|
||||
std::array::from_fn(|t| palette[t % 8])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packing_helper_matches_hand_bytes() {
|
||||
// 111 110 101 100 011 010 001 000 = 0xFAC688, twice.
|
||||
assert_eq!(pack3(SEQ), [0x88, 0xC6, 0xFA, 0x88, 0xC6, 0xFA]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bc4_unorm_eight_value_mode() {
|
||||
// a0 > a1: p[k+1] = ((7-k)*200 + k*100) / 7 for k = 1..6.
|
||||
// 1300/7=185, 1200/7=171, 1100/7=157, 1000/7=142, 900/7=128, 800/7=114.
|
||||
let out = decode_bc4_unorm(bc4(200, 100, SEQ));
|
||||
assert_eq!(out, expect([200, 100, 185, 171, 157, 142, 128, 114]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bc4_unorm_six_value_mode_with_zero_and_255() {
|
||||
// a0 <= a1: ((5-k)*100 + k*200) / 5: 600/5=120, 700/5=140, 800/5=160,
|
||||
// 900/5=180, then 0 and 255.
|
||||
let out = decode_bc4_unorm(bc4(100, 200, SEQ));
|
||||
assert_eq!(out, expect([100, 200, 120, 140, 160, 180, 0, 255]));
|
||||
// Equal endpoints also take the six-value mode.
|
||||
let out = decode_bc4_unorm(bc4(50, 50, SEQ));
|
||||
assert_eq!(out, expect([50, 50, 50, 50, 50, 50, 0, 255]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bc4_snorm_eight_value_mode_truncates_toward_zero() {
|
||||
// a0=100 > a1=-100: 500/7=71, 300/7=42, 100/7=14, -100/7=-14,
|
||||
// -300/7=-42, -500/7=-71.
|
||||
let b = bc4(100, 0x9C, SEQ); // 0x9C = -100
|
||||
let out = decode_bc4_snorm(b);
|
||||
let e: [i8; 8] = [100, -100, 71, 42, 14, -14, -42, -71];
|
||||
assert_eq!(out, std::array::from_fn(|t| e[t % 8]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bc4_snorm_six_value_mode_with_fixed_extremes() {
|
||||
// a0=-100 <= a1=100: (-400+100)/5=-60, (-300+200)/5=-20, 20, 60, -127, 127.
|
||||
let out = decode_bc4_snorm(bc4(0x9C, 100, SEQ));
|
||||
let e: [i8; 8] = [-100, 100, -60, -20, 20, 60, -127, 127];
|
||||
assert_eq!(out, std::array::from_fn(|t| e[t % 8]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bc4_snorm_minus_128_is_kept_for_endpoints_and_acts_as_minus_127() {
|
||||
// a0=-128 < a1=127: six-value mode, x=-127: p2=(4*-127+127)/5=-381/5=-76.
|
||||
let out = decode_bc4_snorm(bc4(0x80, 127, SEQ));
|
||||
assert_eq!(out[0], -128);
|
||||
assert_eq!(out[1], 127);
|
||||
assert_eq!(out[2], -76);
|
||||
// a0=127 > a1=-128: eight-value mode, y=-127: p2=(6*127-127)/7=635/7=90.
|
||||
let out = decode_bc4_snorm(bc4(127, 0x80, SEQ));
|
||||
assert_eq!(out[1], -128);
|
||||
assert_eq!(out[2], 90);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_index_position_is_read_from_its_own_bits() {
|
||||
// Texel n alone uses index 1 (value 100); all others index 0 (value 200).
|
||||
// Texels 2, 5, 10 and 13 span byte boundaries.
|
||||
for n in 0..16 {
|
||||
let mut idx = [0u8; 16];
|
||||
idx[n] = 1;
|
||||
let out = decode_bc4_unorm(bc4(200, 100, idx));
|
||||
for (t, v) in out.iter().enumerate() {
|
||||
assert_eq!(*v, if t == n { 100 } else { 200 }, "texel {t}, set {n}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_index_bit_order_would_fail() {
|
||||
// Texel 5 occupies bits 15..17 (byte 1 bit 7, byte 2 bits 0-1); texel 10
|
||||
// occupies bits 30..32 (byte 3 bits 6-7, byte 4 bit 0).
|
||||
let mut idx = [0u8; 16];
|
||||
idx[5] = 1;
|
||||
idx[10] = 2;
|
||||
let b = bc4(200, 100, idx);
|
||||
// Hand-checked bytes: bit 15 set; bit 31 set.
|
||||
assert_eq!(&b[2..], &[0x00, 0x80, 0x00, 0x80, 0x00, 0x00]);
|
||||
let out = decode_bc4_unorm(b);
|
||||
assert_eq!(out[5], 100);
|
||||
assert_eq!(out[10], 185);
|
||||
assert_ne!(out[5], out[10]);
|
||||
// A decoder reading the 48 bits most-significant first (wrong order)
|
||||
// lands on different texels; show that this block tells them apart.
|
||||
let bits = b[2..8]
|
||||
.iter()
|
||||
.rev()
|
||||
.fold(0u64, |a, x| (a << 8) | u64::from(*x));
|
||||
let wrong = |t: usize| ((bits >> (45 - 3 * t)) & 7) as u8;
|
||||
assert_ne!(wrong(5), 1);
|
||||
assert_ne!(wrong(10), 2);
|
||||
}
|
||||
|
||||
fn colour_bytes(c0: u16, c1: u16, indices: u32) -> [u8; 8] {
|
||||
let (a, b, i) = (c0.to_le_bytes(), c1.to_le_bytes(), indices.to_le_bytes());
|
||||
[a[0], a[1], b[0], b[1], i[0], i[1], i[2], i[3]]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bc2_expands_four_bit_alpha_and_always_uses_four_colours() {
|
||||
// Red 0xF800 = (255,0,0), blue 0x001F = (0,0,255).
|
||||
// p2 = (170,0,85), p3 = (85,0,170). Texels 0..3 use indices 0..3.
|
||||
let alpha = [0x10, 0x32, 0x54, 0x76, 0x98, 0xBA, 0xDC, 0xFE];
|
||||
for (c0, c1, mid) in [
|
||||
(0xF800, 0x001F, [[170, 0, 85], [85, 0, 170]]),
|
||||
// Endpoints swapped: still four-colour mode, no transparent index.
|
||||
(0x001F, 0xF800, [[85, 0, 170], [170, 0, 85]]),
|
||||
] {
|
||||
let mut block = [0u8; 16];
|
||||
block[..8].copy_from_slice(&alpha);
|
||||
block[8..].copy_from_slice(&colour_bytes(c0, c1, 0b11_10_01_00));
|
||||
let out = decode_bc2(block);
|
||||
let first = if c0 == 0xF800 {
|
||||
[255, 0, 0]
|
||||
} else {
|
||||
[0, 0, 255]
|
||||
};
|
||||
let second = if c0 == 0xF800 {
|
||||
[0, 0, 255]
|
||||
} else {
|
||||
[255, 0, 0]
|
||||
};
|
||||
let rgb = [first, second, mid[0], mid[1]];
|
||||
for t in 0..16 {
|
||||
assert_eq!(out[t][3], t as u8 * 17, "alpha texel {t}");
|
||||
if t < 4 {
|
||||
assert_eq!(out[t][..3], rgb[t], "colour texel {t}");
|
||||
} else {
|
||||
assert_eq!(out[t][..3], first, "colour texel {t}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bc3_uses_bc4_style_alpha_and_four_colour_block() {
|
||||
let mut block = [0u8; 16];
|
||||
block[..8].copy_from_slice(&bc4(200, 100, SEQ));
|
||||
// c0 < c1 would be 3-colour in BC1; index 3 must stay interpolated.
|
||||
block[8..].copy_from_slice(&colour_bytes(0x001F, 0xF800, 0xFFFF_FFFF));
|
||||
let out = decode_bc3(block);
|
||||
let alpha = expect([200, 100, 185, 171, 157, 142, 128, 114]);
|
||||
for t in 0..16 {
|
||||
assert_eq!(out[t][3], alpha[t]);
|
||||
assert_eq!(out[t][..3], [170, 0, 85]);
|
||||
}
|
||||
// Six-value alpha mode.
|
||||
block[..8].copy_from_slice(&bc4(100, 200, SEQ));
|
||||
let alpha = expect([100, 200, 120, 140, 160, 180, 0, 255]);
|
||||
let out = decode_bc3(block);
|
||||
for t in 0..16 {
|
||||
assert_eq!(out[t][3], alpha[t]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bc5_channel_order_is_red_then_green() {
|
||||
// All texels index 1 = 0b001 repeated: bytes 0x49 0x92 0x24 twice.
|
||||
let ones = [0x49, 0x92, 0x24, 0x49, 0x92, 0x24];
|
||||
let mut block = [0u8; 16];
|
||||
block[..2].copy_from_slice(&[200, 100]);
|
||||
block[2..8].copy_from_slice(&ones);
|
||||
block[8..10].copy_from_slice(&[100, 200]);
|
||||
block[10..].copy_from_slice(&ones);
|
||||
for texel in decode_bc5_unorm(block) {
|
||||
assert_eq!(texel, [100, 200]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bc5_snorm_channels_and_fixed_values() {
|
||||
// Index 6 = 0b110 repeated: bytes 0xB6 0x6D 0xDB twice.
|
||||
let sixes = [0xB6, 0x6D, 0xDB, 0xB6, 0x6D, 0xDB];
|
||||
let mut block = [0u8; 16];
|
||||
// Red: a0=100 > a1=-100, index 6 = -42. Green: a0=-100 <= a1=100, index 6 = -127.
|
||||
block[..2].copy_from_slice(&[100, 0x9C]);
|
||||
block[2..8].copy_from_slice(&sixes);
|
||||
block[8..10].copy_from_slice(&[0x9C, 100]);
|
||||
block[10..].copy_from_slice(&sixes);
|
||||
for texel in decode_bc5_snorm(block) {
|
||||
assert_eq!(texel, [-42, -127]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user