summaryrefslogtreecommitdiff
path: root/include/file/world.hpp
blob: c204c763d6782f0e45f81427ad56e63e9dce93ef (plain)
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
#pragma once

#include <cstdint>
#include <cstdio>
#include <fcntl.h>
#include <filesystem>
#include <stdexcept>
#include <string>
#include <vector>

#include "file/metadata.hpp"
#include "util/bitset.hpp"
#include "util/io.hpp"
#include "version.hpp"

namespace file {

class world {
	// TODO: World, Player and Map files probably share similar(or the same) header format.
	// If so, move this into file/header.hpp, and defile `struct header : file::header` here
	struct header {
		int32_t version;
		metadata meta;
		std::vector<int32_t> positions;
		bitset<0> importance;
		

		ssize_t read(io::serialized_file f)
		{
			auto bytes = f.read(version);

			if (version < 88 || version > terraria_version) {
				throw std::runtime_error("unsupported world version");
			}

			if (version >= 135) {
				bytes += f.read(meta);
				if (meta.ftype != metadata::filetype::World) {
					throw std::runtime_error("unexpected relogic file format");
				}
			} else {
				throw std::runtime_error("unimplemented");
			}

			int16_t positions_size;
			bytes += f.read(positions_size);
			positions.resize(positions_size);
			bytes += f.read(positions);
			
			int16_t importance_size;
			bytes += f.read(importance_size);
			importance.resize(bits_ceil(importance_size));
			bytes += f.read(importance);
			return bytes;
		}
	};
	
	enum file_positions {
		FileHeaderEnd,
		HeaderEnd,
		WorldTilesEnd,
		ChestsEnd,
		SignsEnd,
		NPCsEnd,
		DummiesEnd, // Terraria[116;122)
		TileEntitiesEnd = DummiesEnd,
		WeightedPressurePlatesEnd,
		TownManagerEnd,
		BestiaryEnd,
		CreativePowersEnd,
	};

	header hdr;

public:
	world(std::string filename)
	{
		if (!std::filesystem::exists(filename)) {
			throw std::runtime_error("file not found");
		}
		auto rw = io::serialized_io(io::file_io { filename });

		auto offset = rw.read(hdr);
		if (offset != hdr.positions[file_positions::FileHeaderEnd]) {
			throw std::runtime_error("currupted file!");
		}
	}
};

}