summaryrefslogtreecommitdiff
path: root/src/save.py
blob: 0e8e3d21fb509b967be0df674af39a5333e3141f (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
import os
import zlib
import json

import constants

def save_world(path, regions):
    checksums = {}
    region_list = []

    if not os.path.exists(path):
        os.mkdir(path)

    if not os.path.exists(path + "/region"):
        os.mkdir(path + "/region")

    if not os.path.exists(path + "/playerdata"):
        os.mkdir(path + "/playerdata")

    for i in range(len(regions)):
        with open(path + "/region/" + str(i) + ".bcr", "wb") as f:
            checksums[str(i) + ".bcr"] = hex(zlib.crc32(str.encode(json.dumps(regions[i]))))
            region_list.append(str(i) + ".bcr")
            f.write(zlib.compress(str.encode(json.dumps(regions[i]))))

    with open(path + "/level.dat", "wb") as f:
        f.write(zlib.compress(str.encode(json.dumps({
            "version": constants.VERSION,
            "checksums": checksums,
            "regions": region_list
        }))))

def load_world(path):
    blocks = []

    with open(path + "/level.dat", "rb") as f:
        data = json.loads(zlib.decompress(f.read()))

    print(data)

    for region in data['regions']:
        with open(path + "/region/" + region, "rb") as f:
            raw = zlib.decompress(f.read())

            if hex(zlib.crc32(raw)) != data['checksums'][region]:
                raise Exception("Region file " + region + " is corrupted.")

            blocks.append(json.loads(raw))


    return {
        "version": data['version'],
        "blocks": blocks
    }