TombEngine/TR5Main/Specific/IO/ChunkReader.h

143 lines
2.7 KiB
C
Raw Normal View History

#pragma once
#include <stdlib.h>
#include <memory>
#include "ChunkId.h"
#include "LEB128.h"
#include "Streams.h"
class ChunkReader
{
private:
bool m_isValid;
ChunkId* m_emptyChunk;
BaseStream* m_stream;
2019-12-02 09:11:21 +01:00
int readInt32()
{
2019-12-02 09:11:21 +01:00
int value = 0;
m_stream->Read(reinterpret_cast<char *>(&value), 4);
return value;
}
2019-12-02 09:11:21 +01:00
short readInt16()
{
2019-12-02 09:11:21 +01:00
short value = 0;
m_stream->Read(reinterpret_cast<char *>(&value), 2);
return value;
}
public:
2019-12-02 09:11:21 +01:00
ChunkReader(int expectedMagicNumber, BaseStream* stream)
{
m_isValid = false;
if (stream == NULL)
return;
m_stream = stream;
// Check the magic number
2019-12-02 09:11:21 +01:00
int magicNumber = readInt32();
if (magicNumber != expectedMagicNumber)
return;
// TODO: future use for compression
m_stream->Seek(4, SEEK_ORIGIN::CURRENT);
m_emptyChunk = new ChunkId(NULL, 0);
m_isValid = true;
}
~ChunkReader()
{
delete m_emptyChunk;
}
bool IsValid()
{
return m_isValid;
}
bool ReadChunks(bool(*func)(ChunkId* parentChunkId, int maxSize, int arg), int arg)
{
do
{
ChunkId* chunkId = ChunkId::FromStream(m_stream);
if (chunkId->EqualsTo(m_emptyChunk)) // End reached
break;
// Read up to a 64 bit number for the chunk size
__int64 chunkSize = LEB128::ReadLong(m_stream);
// Try loading chunk content
bool chunkRecognized = false;
2019-12-02 09:11:21 +01:00
int startPos = m_stream->GetCurrentPosition();
2018-10-24 23:32:22 +02:00
chunkRecognized = func(chunkId, chunkSize, arg);
2019-12-02 09:11:21 +01:00
int readDataCount = m_stream->GetCurrentPosition() - startPos;
// Adjust _stream position if necessary
if (readDataCount != chunkSize)
2018-10-24 23:32:22 +02:00
m_stream->Seek(chunkSize - readDataCount, SEEK_ORIGIN::CURRENT);
} while (true);
return true;
}
char* ReadChunkArrayOfBytes(__int64 length)
{
char* value = (char*)malloc(length);
m_stream->Read(value, length);
return value;
}
bool ReadChunkBool(__int64 length)
{
return (LEB128::ReadByte(m_stream) != 0);
}
__int64 ReadChunkLong(__int64 length)
{
return LEB128::ReadLong(m_stream);
}
2019-12-02 09:11:21 +01:00
int ReadChunkInt32(__int64 length)
{
return LEB128::ReadInt32(m_stream);
}
2019-12-02 09:11:21 +01:00
unsigned int ReadChunkUInt32(__int64 length)
{
return LEB128::ReadUInt32(m_stream);
}
2019-12-02 09:11:21 +01:00
short ReadChunkInt16(__int64 length)
{
return LEB128::ReadInt16(m_stream);
}
2019-12-02 09:11:21 +01:00
unsigned short ReadChunkUInt16(__int64 length)
{
return LEB128::ReadUInt16(m_stream);
}
byte ReadChunkByte(__int64 length)
{
return LEB128::ReadByte(m_stream);
}
char* ReadChunkString(long length)
{
char* value = (char*)malloc(length);
memcpy(value, LevelDataPtr, length);
return value;
}
BaseStream* GetRawStream()
{
return m_stream;
}
};