forked from mrkite/minutor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chunkloader.cpp
105 lines (83 loc) · 2.5 KB
/
chunkloader.cpp
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
/** Copyright (c) 2013, Sean Kasun */
#include "chunkloader.h"
#include "chunkcache.h"
#include "chunk.h"
ChunkLoader::ChunkLoader(QString path, int cx, int cz)
: path(path)
, cx(cx), cz(cz)
, cache(ChunkCache::Instance())
{}
ChunkLoader::~ChunkLoader()
{}
void ChunkLoader::run() {
// get existing Chunk entry from Cache
QSharedPointer<Chunk> chunk(cache.fetchCached(cx, cz));
// load & parse NBT data
loadNbt(path, cx, cz, chunk);
emit loaded(cx, cz);
}
bool ChunkLoader::loadNbt(QString path, int cx, int cz, QSharedPointer<Chunk> chunk)
{
// check if chunk is a valid storage
if (!chunk) {
return false;
}
// get coordinates of region file
int rx = cx >> 5;
int rz = cz >> 5;
QString filename;
filename = path + "/region/r." + QString::number(rx) + "." + QString::number(rz) + ".mca";
bool result = loadNbtHelper(filename, cx, cz, chunk, ChunkLoader::MAIN_MAP_DATA);
filename = path + "/entities/r." + QString::number(rx) + "." + QString::number(rz) + ".mca";
loadNbtHelper(filename, cx, cz, chunk, ChunkLoader::SEPARATED_ENTITIES);
return result;
}
bool ChunkLoader::loadNbtHelper(QString filename, int cx, int cz, QSharedPointer<Chunk> chunk, int loadtype)
{
QFile f(filename);
if (!f.open(QIODevice::ReadOnly)) {
// no chunks in this region (region file not present at all)
return false;
}
const int headerSize = 4096;
if (f.size() < headerSize) {
// file header not yet fully written by minecraft
return false;
}
// map header into memory
uchar *header = f.map(0, headerSize);
int offset = 4 * ((cx & 31) + (cz & 31) * 32);
int coffset = (header[offset] << 16) | (header[offset + 1] << 8) | header[offset + 2];
int numSectors = header[offset+3];
f.unmap(header);
if (coffset == 0) {
// no Chunk information stored in region file
f.close();
return false;
}
const int chunkStart = coffset * 4096;
const int chunkSize = numSectors * 4096;
if (f.size() < (chunkStart + chunkSize)) {
// Chunk not yet fully written by Minecraft
return false;
}
uchar *raw = f.map(chunkStart, chunkSize);
if (raw == NULL) {
f.close();
return false;
}
// parse Chunk data
// Chunk will be flagged "loaded" in a thread save way
NBT nbt(raw);
switch (loadtype) {
case ChunkLoader::MAIN_MAP_DATA:
chunk->load(nbt);
Q_FALLTHROUGH();
case ChunkLoader::SEPARATED_ENTITIES:
chunk->loadEntities(nbt);
}
f.unmap(raw);
f.close();
// if we reach this point, everything went well
return true;
}