Skip to content

Instantly share code, notes, and snippets.

@barncastle
Created August 12, 2022 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barncastle/02eb58226ae5cc7cb699806ddde85793 to your computer and use it in GitHub Desktop.
Save barncastle/02eb58226ae5cc7cb699806ddde85793 to your computer and use it in GitHub Desktop.
Sample code for decompressing the header of Dragon Mania Legends PAK files
// iterate each sample file
foreach (var sample in Directory.GetFiles(@"C:\Users\temp\Downloads\sample"))
{
// open the file stream and create a reader
using var stream = File.OpenRead(sample);
using var reader = new BinaryReader(stream);
// read the header
var magic = reader.ReadString(4);
var fileTableCompressedSize = reader.ReadInt32();
var fileTableDecompressedSize = reader.ReadInt32();
// create our zstd decompressor
var decompressor = new ZstdSharp.Decompressor();
// read and decompress the compressed file table bytes
var compressedFileTableBytes = reader.ReadBytes(fileTableCompressedSize);
var decompressedFileTableBytes = decompressor.Unwrap(compressedFileTableBytes);
// check it decompressed correctly
Debug.Assert(decompressedFileTableBytes.Length == fileTableDecompressedSize);
// convert our decompressed bytes to a stream
// and create a new reader to simplify things
using var tblStream = new MemoryStream(decompressedFileTableBytes.ToArray());
using var tblReader = new BinaryReader(tblStream);
// create a filetable collection
var fileTable = new List<FileTableEntry>();
// iterate to end of
while (tblReader.BaseStream.Position != tblReader.BaseStream.Length)
{
// read the entry and add to collection
var nameLen = tblReader.ReadInt32();
var name = tblReader.ReadString(nameLen);
var compressedSize = tblReader.ReadInt32();
var decompressedSize = tblReader.ReadInt32();
fileTable.Add(new FileTableEntry()
{
NameLen = nameLen,
Name = name,
CompressedSize = compressedSize,
DecompressedSize = decompressedSize
});
}
}
@barncastle
Copy link
Author

This example uses oleg-st's ZstdSharp for ZStandard decompression.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment