1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// SPDX-FileCopyrightText: 2023 Joshua Goins <josh@redstrate.com>
// SPDX-License-Identifier: GPL-3.0-or-later

#![allow(clippy::needless_range_loop)]

use std::io::{Cursor, Read, Seek, SeekFrom};

use crate::ByteSpan;
use binrw::binrw;
use binrw::BinRead;
use bitflags::bitflags;
use texture2ddecoder::{decode_bc1, decode_bc3, decode_bc5};

// Attributes and Format are adapted from Lumina (https://github.com/NotAdam/Lumina/blob/master/src/Lumina/Data/Files/TexFile.cs)
bitflags! {
    #[binrw]
    struct TextureAttribute : u32 {
        const DISCARD_PER_FRAME = 0x1;
        const DISCARD_PER_MAP = 0x2;

        const MANAGED = 0x4;
        const USER_MANAGED = 0x8;
        const CPU_READ = 0x10;
        const LOCATION_MAIN = 0x20;
        const NO_GPU_READ = 0x40;
        const ALIGNED_SIZE = 0x80;
        const EDGE_CULLING = 0x100;
        const LOCATION_ONION = 0x200;
        const READ_WRITE = 0x400;
        const IMMUTABLE = 0x800;

        const TEXTURE_RENDER_TARGET = 0x100000;
        const TEXTURE_DEPTH_STENCIL = 0x200000;
        const TEXTURE_TYPE1_D = 0x400000;
        const TEXTURE_TYPE2_D = 0x800000;
        const TEXTURE_TYPE3_D = 0x1000000;
        const TEXTURE_TYPE_CUBE = 0x2000000;
        const TEXTURE_TYPE_MASK = 0x3C00000;
        const TEXTURE_SWIZZLE = 0x4000000;
        const TEXTURE_NO_TILED = 0x8000000;
        const TEXTURE_NO_SWIZZLE = 0x80000000;
    }
}

#[binrw]
#[brw(repr = u32)]
#[derive(Debug)]
enum TextureFormat {
    B4G4R4A4 = 0x1440,
    B8G8R8A8 = 0x1450,
    BC1 = 0x3420,
    BC3 = 0x3431,
    BC5 = 0x6230,
}

#[binrw]
#[derive(Debug)]
#[allow(dead_code)]
#[brw(little)]
struct TexHeader {
    attribute: TextureAttribute,
    format: TextureFormat,

    width: u16,
    height: u16,
    depth: u16,
    mip_levels: u16,

    lod_offsets: [u32; 3],
    offset_to_surface: [u32; 13],
}

pub struct Texture {
    /// Width of the texture in pixels
    pub width: u32,
    /// Height of the texture in pixels
    pub height: u32,
    /// Raw RGBA data
    pub rgba: Vec<u8>,
}

type DecodeFunction = fn(&[u8], usize, usize, &mut [u32]) -> Result<(), &'static str>;

impl Texture {
    /// Reads an existing TEX file
    pub fn from_existing(buffer: ByteSpan) -> Option<Texture> {
        let mut cursor = Cursor::new(buffer);
        let header = TexHeader::read(&mut cursor).ok()?;

        cursor
            .seek(SeekFrom::Start(std::mem::size_of::<TexHeader>() as u64))
            .ok()?;

        let mut src = vec![0u8; buffer.len() - std::mem::size_of::<TexHeader>()];
        cursor.read_exact(src.as_mut_slice()).ok()?;

        let mut dst: Vec<u8>;

        match header.format {
            TextureFormat::B4G4R4A4 => {
                dst = vec![0u8; header.width as usize * header.height as usize * 4];

                let mut offset = 0;
                let mut dst_offset = 0;

                for _ in 0..header.width * header.height {
                    let short: u16 = ((src[offset] as u16) << 8) | src[offset + 1] as u16;

                    let src_b = short & 0xF;
                    let src_g = (short >> 4) & 0xF;
                    let src_r = (short >> 8) & 0xF;
                    let src_a = (short >> 12) & 0xF;

                    dst[dst_offset] = (17 * src_r) as u8;
                    dst[dst_offset + 1] = (17 * src_g) as u8;
                    dst[dst_offset + 2] = (17 * src_b) as u8;
                    dst[dst_offset + 3] = (17 * src_a) as u8;

                    offset += 2;
                    dst_offset += 4;
                }
            }
            TextureFormat::B8G8R8A8 => {
                dst = src; // TODO: not correct, of course
            }
            TextureFormat::BC1 => {
                dst = Texture::decode(
                    &src,
                    header.width as usize,
                    header.height as usize,
                    decode_bc1,
                );
            }
            TextureFormat::BC3 => {
                dst = Texture::decode(
                    &src,
                    header.width as usize,
                    header.height as usize,
                    decode_bc3,
                );
            }
            TextureFormat::BC5 => {
                dst = Texture::decode(
                    &src,
                    header.width as usize,
                    header.height as usize,
                    decode_bc5,
                );
            }
        }

        Some(Texture {
            width: header.width as u32,
            height: header.height as u32,
            rgba: dst,
        })
    }

    fn decode(src: &[u8], width: usize, height: usize, decode_func: DecodeFunction) -> Vec<u8> {
        let mut image: Vec<u32> = vec![0; width * height];
        decode_func(src, width, height, &mut image).unwrap();

        image
            .iter()
            .flat_map(|x| {
                let v = x.to_le_bytes();
                [v[2], v[1], v[0], v[3]]
            })
            .collect::<Vec<u8>>()
    }
}

#[cfg(test)]
mod tests {
    use std::fs::read;
    use std::path::PathBuf;

    use super::*;

    #[test]
    fn test_invalid() {
        let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        d.push("resources/tests");
        d.push("random");

        // Feeding it invalid data should not panic
        Texture::from_existing(&read(d).unwrap());
    }
}