forked from mcedit/pymclevel
-
Notifications
You must be signed in to change notification settings - Fork 1
/
infiniteworld.py
2461 lines (1843 loc) · 82.4 KB
/
infiniteworld.py
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Created on Jul 22, 2011
@author: Rio
'''
from mclevelbase import *
from collections import deque;
import time
import zlib
import struct
import shutil
#infinite
Level = 'Level'
BlockData = 'BlockData'
BlockLight = 'BlockLight'
SkyLight = 'SkyLight'
HeightMap = 'HeightMap'
TerrainPopulated = 'TerrainPopulated'
LastUpdate = 'LastUpdate'
xPos = 'xPos'
zPos = 'zPos'
Data = 'Data'
SpawnX = 'SpawnX'
SpawnY = 'SpawnY'
SpawnZ = 'SpawnZ'
LastPlayed = 'LastPlayed'
RandomSeed = 'RandomSeed'
SizeOnDisk = 'SizeOnDisk' #maybe update this?
Time = 'Time'
Player = 'Player'
__all__ = ["ZeroChunk", "InfdevChunk", "MCInfdevOldLevel", "MCAlphaDimension", "ZipSchematic"]
class ZeroChunk(object):
" a placebo for neighboring-chunk routines "
def compress(self): pass
def load(self): pass
def __init__(self, height=512):
zeroChunk = zeros((16, 16, height), uint8)
whiteLight = zeroChunk + 15;
self.Blocks = zeroChunk
self.BlockLight = whiteLight
self.SkyLight = whiteLight
self.Data = zeroChunk
class InfdevChunk(EntityLevel):
""" This is a 16x16xH chunk in an (infinite) world.
The properties Blocks, Data, SkyLight, BlockLight, and Heightmap
are ndarrays containing the respective blocks in the chunk file.
Each array is indexed [x,z,y]. The Data, Skylight, and BlockLight
arrays are automatically unpacked from nibble arrays into byte arrays
for better handling.
"""
@property
def filename(self):
if self.world.version:
cx, cz = self.chunkPosition
rx, rz = cx >> 5, cz >> 5
rf = self.world.regionFiles[rx, rz]
offset = rf.getOffset(cx & 0x1f, cz & 0x1f)
return u"{region} index {index} sector {sector} format {format}".format(
region=os.path.basename(self.world.regionFilename(rx, rz)),
sector=offset >> 8,
index=4 * ((cx & 0x1f) + ((cz & 0x1f) * 32)),
format=["???", "gzip", "deflate"][self.compressMode])
else:
return self.chunkFilename
def __init__(self, world, chunkPosition, create=False):
self.world = world;
#self.materials = self.world.materials
self.chunkPosition = chunkPosition;
self.chunkFilename = world.chunkFilename(*chunkPosition)
#self.filename = "UNUSED" + world.chunkFilename(*chunkPosition);
#self.filename = "REGION FILE (chunk {0})".format(chunkPosition)
self.compressedTag = None
self.root_tag = None
self.dirty = False;
self.needsLighting = False
if self.world.version:
self.compressMode = MCRegionFile.VERSION_DEFLATE
else:
self.compressMode = MCRegionFile.VERSION_GZIP
if create:
self.create();
else:
if not world.containsChunk(*chunkPosition):
raise ChunkNotPresent("Chunk {0} not found", self.chunkPosition)
@property
def materials(self):
return self.world.materials
@classmethod
def compressTagGzip(cls, root_tag):
buf = StringIO()
with closing(gzip.GzipFile(fileobj=buf, mode='wb', compresslevel=2)) as gzipper:
root_tag.save(buf=gzipper)
return buf.getvalue()
@classmethod
def compressTagDeflate(cls, root_tag):
buf = StringIO()
root_tag.save(buf=buf)
return deflate(buf.getvalue())
def _compressChunk(self):
root_tag = self.root_tag
if root_tag is None: return
if self.compressMode == MCRegionFile.VERSION_GZIP:
self.compressedTag = self.compressTagGzip(root_tag)
if self.compressMode == MCRegionFile.VERSION_DEFLATE:
self.compressedTag = self.compressTagDeflate(root_tag)
self.root_tag = None
def decompressTagGzip(self, data):
return nbt.load(buf=gunzip(data))
def decompressTagDeflate(self, data):
return nbt.load(buf=inflate(data))
def _decompressChunk(self):
data = self.compressedTag
if self.compressMode == MCRegionFile.VERSION_GZIP:
self.root_tag = self.decompressTagGzip(data)
if self.compressMode == MCRegionFile.VERSION_DEFLATE:
self.root_tag = self.decompressTagDeflate(data)
def compressedSize(self):
"return the size of the compressed data for this level, in bytes."
self.compress();
if self.compressedTag is None: return 0
return len(self.compressedTag)
def sanitizeBlocks(self):
#change grass to dirt where needed so Minecraft doesn't flip out and die
grass = self.Blocks == self.materials.Grass.ID
grass |= self.Blocks == self.materials.Dirt.ID
badgrass = grass[:, :, 1:] & grass[:, :, :-1]
self.Blocks[:, :, :-1][badgrass] = self.materials.Dirt.ID
#remove any thin snow layers immediately above other thin snow layers.
#minecraft doesn't flip out, but it's almost never intended
if hasattr(self.materials, "SnowLayer"):
snowlayer = self.Blocks == self.materials.SnowLayer.ID
badsnow = snowlayer[:, :, 1:] & snowlayer[:, :, :-1]
self.Blocks[:, :, 1:][badsnow] = self.materials.Air.ID
def compress(self):
if not self.dirty:
#if we are not dirty, just throw the
#uncompressed tag structure away. rely on the OS disk cache.
self.root_tag = None
else:
if self.root_tag is not None:
self.sanitizeBlocks() #xxx
self.packChunkData()
self._compressChunk()
self.world.chunkDidCompress(self);
def decompress(self):
"""called when accessing attributes decorated with @decompress_first"""
if not self in self.world.decompressedChunkQueue:
if self.root_tag != None: return
if self.compressedTag is None:
if self.root_tag is None:
self.load();
else:
return;
try:
self._decompressChunk()
except Exception, e:
error(u"Malformed NBT data in file: {0} ({1})".format(self.filename, e))
if self.world: self.world.malformedChunk(*self.chunkPosition);
raise ChunkMalformed, self.filename
try:
self.shapeChunkData()
except KeyError, e:
error(u"Incorrect chunk format in file: {0} ({1})".format(self.filename, e))
if self.world: self.world.malformedChunk(*self.chunkPosition);
raise ChunkMalformed, self.filename
self.dataIsPacked = True;
self.world.chunkDidDecompress(self);
def __str__(self):
return u"InfdevChunk, coords:{0}, world: {1}, D:{2}, L:{3}".format(self.chunkPosition, self.world.displayName, self.dirty, self.needsLighting)
def create(self):
(cx, cz) = self.chunkPosition;
chunkTag = nbt.TAG_Compound()
chunkTag.name = ""
levelTag = nbt.TAG_Compound()
chunkTag[Level] = levelTag
levelTag[TerrainPopulated] = TAG_Byte(1)
levelTag[xPos] = TAG_Int(cx)
levelTag[zPos] = TAG_Int(cz)
levelTag[LastUpdate] = TAG_Long(0);
levelTag[BlockLight] = TAG_Byte_Array()
levelTag[BlockLight].value = zeros(16 * 16 * self.world.ChunkHeight / 2, uint8)
levelTag[Blocks] = TAG_Byte_Array()
levelTag[Blocks].value = zeros(16 * 16 * self.world.ChunkHeight, uint8)
levelTag[Data] = TAG_Byte_Array()
levelTag[Data].value = zeros(16 * 16 * self.world.ChunkHeight / 2, uint8)
levelTag[SkyLight] = TAG_Byte_Array()
levelTag[SkyLight].value = zeros(16 * 16 * self.world.ChunkHeight / 2, uint8)
levelTag[SkyLight].value[:] = 255
if self.world.ChunkHeight <= 128:
levelTag[HeightMap] = TAG_Byte_Array()
levelTag[HeightMap].value = zeros(16 * 16, uint8)
else:
levelTag[HeightMap] = TAG_Int_Array()
levelTag[HeightMap].value = zeros(16 * 16, uint32).newbyteorder()
levelTag[Entities] = TAG_List()
levelTag[TileEntities] = TAG_List()
#levelTag["Creator"] = TAG_String("MCEdit-" + release.release);
#empty lists are seen in the wild with a list.TAG_type for a list of single bytes,
#even though these contain TAG_Compounds
self.root_tag = chunkTag
self.shapeChunkData();
self.dataIsPacked = True;
self.dirty = True;
self.save();
def save(self):
""" does not recalculate any data or light """
self.compress()
if self.dirty:
debug(u"Saving chunk: {0}".format(self))
self.world._saveChunk(self)
debug(u"Saved chunk {0}".format(self))
self.dirty = False;
def load(self):
""" If the chunk is unloaded, calls world._loadChunk to set root_tag and
compressedTag, then unpacks the chunk fully"""
if self.root_tag is None and self.compressedTag is None:
try:
self.world._loadChunk(self)
self.dataIsPacked = True;
self.shapeChunkData()
self.unpackChunkData()
except Exception, e:
error(u"Incorrect chunk format in file: {0} ({1})".format(self.filename, e))
if self.world: self.world.malformedChunk(*self.chunkPosition);
raise ChunkMalformed, self.filename
self.world.chunkDidLoad(self)
self.world.chunkDidDecompress(self);
def unload(self):
""" Frees the chunk's memory. Will not save to disk. Unloads completely
if the chunk does not need to be saved."""
self.compress();
if not self.dirty:
self.compressedTag = None;
self.world.chunkDidUnload(self)
def isLoaded(self):
#we're loaded if we have our tag data in ram
#and we don't have to go back to the disk for it.
return not (self.compressedTag is None and self.root_tag is None)
def isCompressed(self):
return self.isLoaded() and self.root_tag == None
def chunkChanged(self, calcLighting=True):
""" You are required to call this function after you are done modifying
the chunk. Pass False for calcLighting if you know your changes will
not change any lights."""
if self.compressedTag == None and self.root_tag == None:
#unloaded chunk
return;
self.dirty = True;
self.needsLighting = calcLighting or self.needsLighting;
generateHeightMap(self);
if calcLighting:
self.genFastLights()
def genFastLights(self):
self.SkyLight[:] = 0;
if self.world.dimNo == -1:
return #no light in nether
blocks = self.Blocks;
la = self.world.materials.lightAbsorption
skylight = self.SkyLight;
heightmap = self.HeightMap;
for x, z in itertools.product(xrange(16), xrange(16)):
skylight[x, z, heightmap[z, x]:] = 15
lv = 15;
for y in reversed(range(heightmap[z, x])):
lv -= (la[blocks[x, z, y]] or 1)
if lv <= 0:
break;
skylight[x, z, y] = lv;
def unpackChunkData(self):
if not self.dataIsPacked: return
""" for internal use. call getChunk and compressChunk to load, compress, and unpack chunks automatically """
for key in (SkyLight, BlockLight, Data):
dataArray = self.root_tag[Level][key].value
s = dataArray.shape
assert s[2] == self.world.ChunkHeight / 2;
#unpackedData = insert(dataArray[...,newaxis], 0, 0, 3)
unpackedData = zeros((s[0], s[1], s[2] * 2), dtype='uint8')
unpackedData[:, :, ::2] = dataArray
unpackedData[:, :, ::2] &= 0xf
unpackedData[:, :, 1::2] = dataArray
unpackedData[:, :, 1::2] >>= 4
self.root_tag[Level][key].value = unpackedData
self.dataIsPacked = False;
def packChunkData(self):
if self.dataIsPacked: return
if self.root_tag is None:
warn(u"packChunkData called on unloaded chunk: {0}".format(self.chunkPosition))
return;
for key in (SkyLight, BlockLight, Data):
dataArray = self.root_tag[Level][key].value
assert dataArray.shape[2] == self.world.ChunkHeight;
unpackedData = self.root_tag[Level][key].value.reshape(16, 16, self.world.ChunkHeight / 2, 2)
unpackedData[..., 1] <<= 4
unpackedData[..., 1] |= unpackedData[..., 0]
self.root_tag[Level][key].value = array(unpackedData[:, :, :, 1])
self.dataIsPacked = True;
def shapeChunkData(self):
"""Applies the chunk shape to all of the data arrays
in the chunk tag. used by chunk creation and loading"""
chunkTag = self.root_tag
chunkSize = 16
chunkTag[Level][Blocks].value.shape = (chunkSize, chunkSize, self.world.ChunkHeight)
chunkTag[Level][HeightMap].value.shape = (chunkSize, chunkSize);
chunkTag[Level][SkyLight].value.shape = (chunkSize, chunkSize, self.world.ChunkHeight / 2)
chunkTag[Level][BlockLight].value.shape = (chunkSize, chunkSize, self.world.ChunkHeight / 2)
chunkTag[Level]["Data"].value.shape = (chunkSize, chunkSize, self.world.ChunkHeight / 2)
if TileEntities not in chunkTag[Level]:
chunkTag[Level][TileEntities] = TAG_List();
if Entities not in chunkTag[Level]:
chunkTag[Level][Entities] = TAG_List();
def removeEntitiesInBox(self, box):
self.dirty = True;
return super(InfdevChunk, self).removeEntitiesInBox(box)
def removeTileEntitiesInBox(self, box):
self.dirty = True;
return super(InfdevChunk, self).removeTileEntitiesInBox(box)
@property
@decompress_first
def Blocks(self):
return self.root_tag[Level][Blocks].value
@property
@decompress_first
@unpack_first
def Data(self):
return self.root_tag[Level][Data].value
@property
@decompress_first
def HeightMap(self):
return self.root_tag[Level][HeightMap].value
@property
@decompress_first
@unpack_first
def SkyLight(self):
return self.root_tag[Level][SkyLight].value
@property
@decompress_first
@unpack_first
def BlockLight(self):
return self.root_tag[Level][BlockLight].value
@property
@decompress_first
def Entities(self):
return self.root_tag[Level][Entities]
@property
@decompress_first
def TileEntities(self):
return self.root_tag[Level][TileEntities]
@property
@decompress_first
def TerrainPopulated(self):
return self.root_tag[Level]["TerrainPopulated"].value;
@TerrainPopulated.setter
@decompress_first
def TerrainPopulated(self, val):
"""True or False. If False, the game will populate the chunk with
ores and vegetation on next load"""
self.root_tag[Level]["TerrainPopulated"].value = val;
def generateHeightMap(self):
self.load();
blocks = self.Blocks
heightMap = self.HeightMap
heightMap[:] = 0;
lightAbsorption = self.world.materials.lightAbsorption[blocks]
axes = lightAbsorption.nonzero()
heightMap[axes[1], axes[0]] = axes[2]; #assumes the y-indices come out in increasing order
heightMap += 1;
class dequeset(object):
def __init__(self):
self.deque = deque();
self.set = set();
def __contains__(self, obj):
return obj in self.set;
def __len__(self):
return len(self.set);
def append(self, obj):
self.deque.append(obj);
self.set.add(obj);
def discard(self, obj):
if obj in self.set:
self.deque.remove(obj);
self.set.discard(obj);
def __getitem__(self, idx):
return self.deque[idx];
from contextlib import contextmanager
@contextmanager
def notclosing(f):
yield f;
class MCRegionFile(object):
holdFileOpen = False #if False, reopens and recloses the file on each access
@property
def file(self):
openfile = lambda:file(self.path, "rb+")
if MCRegionFile.holdFileOpen:
if self._file is None:
self._file = openfile()
return notclosing(self._file)
else:
return openfile()
def close(self):
if MCRegionFile.holdFileOpen:
self._file.close()
self._file = None
def __init__(self, path, regionCoords):
self.path = path
self.regionCoords = regionCoords
self._file = None
if not os.path.exists(path):
file(path, "w").close()
with self.file as f:
filesize = os.path.getsize(path)
if filesize & 0xfff:
filesize = (filesize | 0xfff) + 1
f.truncate(filesize)
if filesize == 0:
filesize = self.SECTOR_BYTES * 2
f.truncate(filesize)
f.seek(0)
offsetsData = f.read(self.SECTOR_BYTES)
modTimesData = f.read(self.SECTOR_BYTES)
self.freeSectors = [True] * (filesize / self.SECTOR_BYTES)
self.freeSectors[0:2] = False, False
self.offsets = fromstring(offsetsData, dtype='>u4')
self.modTimes = fromstring(modTimesData, dtype='>u4')
needsRepair = False
for offset in self.offsets:
sector = offset >> 8
count = offset & 0xff
for i in xrange(sector, sector + count):
if i >= len(self.freeSectors):
#raise RegionMalformed, "Region file offset table points to sector {0} (past the end of the file)".format(i)
print "Region file offset table points to sector {0} (past the end of the file)".format(i)
needsRepair = True
break
if self.freeSectors[i] is False:
needsRepair = True
self.freeSectors[i] = False
if needsRepair:
self.repair()
info("Found region file {file} with {used}/{total} sectors used and {chunks} chunks present".format(
file=os.path.basename(path), used=len(self.freeSectors) - sum(self.freeSectors), total=len(self.freeSectors), chunks=sum(self.offsets > 0)))
def repair(self):
lostAndFound = {}
_freeSectors = [True] * len(self.freeSectors)
_freeSectors[0] = _freeSectors[1] = False
deleted = 0
recovered = 0
info("Beginning repairs on {file} ({chunks} chunks)".format(file=os.path.basename(self.path), chunks=sum(self.offsets > 0)))
rx, rz = self.regionCoords
for index, offset in enumerate(self.offsets):
if offset:
cx = index & 0x1f
cz = index >> 5
cx += rx << 5
cz += rz << 5
sectorStart = offset >> 8
sectorCount = offset & 0xff
try:
if sectorStart + sectorCount > len(self.freeSectors):
raise RegionMalformed, "Offset {start}:{end} ({offset}) at index {index} pointed outside of the file".format(
start=sectorStart, end=sectorStart + sectorCount, index=index, offset=offset)
compressedData = self._readChunk(cx, cz)
if compressedData is None:
raise RegionMalformed, "Failed to read chunk data for {0}".format((cx, cz))
format, data = self.decompressSectors(compressedData)
chunkTag = nbt.load(buf=data)
lev = chunkTag["Level"]
xPos = lev["xPos"].value
zPos = lev["zPos"].value
overlaps = False
for i in xrange(sectorStart, sectorStart + sectorCount):
if _freeSectors[i] is False:
overlaps = True
_freeSectors[i] = False
if xPos != cx or zPos != cz or overlaps:
lostAndFound[xPos, zPos] = (format, compressedData)
if (xPos, zPos) != (cx, cz):
raise RegionMalformed, "Chunk {found} was found in the slot reserved for {expected}".format(found=(xPos, zPos), expected=(cx, cz))
else:
raise RegionMalformed, "Chunk {found} (in slot {expected}) has overlapping sectors with another chunk!".format(found=(xPos, zPos), expected=(cx, cz))
except Exception, e:
info("Unexpected chunk data at sector {sector} ({exc})".format(sector=sectorStart, exc=e))
self.setOffset(cx, cz, 0)
deleted += 1
for cPos, (format, foundData) in lostAndFound.iteritems():
cx, cz = cPos
if self.getOffset(cx, cz) == 0:
info("Found chunk {found} and its slot is empty, recovering it".format(found=cPos))
self._saveChunk(cx, cz, foundData[5:], format)
recovered += 1
info("Repair complete. Removed {0} chunks, recovered {1} chunks, net {2}".format(deleted, recovered, recovered - deleted))
def extractAllChunks(self, folder):
if not os.path.exists(folder):
os.mkdir(folder)
for cx, cz in itertools.product(range(32), range(32)):
sectors = self._readChunk(cx, cz)
if sectors is not None:
format, compressedData = self.unpackSectors(sectors)
data = self._decompressSectors(format, compressedData)
chunkTag = nbt.load(buf=data)
lev = chunkTag["Level"]
xPos = lev["xPos"].value
zPos = lev["zPos"].value
gzdata = InfdevChunk.compressTagGzip(chunkTag)
#print chunkTag.pretty_string()
with file(os.path.join(folder, "c.{0}.{1}.dat".format(base36(xPos), base36(zPos))), "wb") as f:
f.write(gzdata)
def _readChunk(self, cx, cz):
cx &= 0x1f
cz &= 0x1f
offset = self.getOffset(cx, cz)
if offset == 0: return None
sectorStart = offset >> 8
numSectors = offset & 0xff
if numSectors == 0: return None
if sectorStart + numSectors > len(self.freeSectors):
return None
with self.file as f:
f.seek(sectorStart * self.SECTOR_BYTES)
data = f.read(numSectors * self.SECTOR_BYTES)
assert(len(data) > 0)
#debug("REGION LOAD {0},{1} sector {2}".format(cx, cz, sectorStart))
return data
def loadChunk(self, chunk):
cx, cz = chunk.chunkPosition
data = self._readChunk(cx, cz)
if data is None: raise ChunkNotPresent, (cx, cz, self)
chunk.compressedTag = data[5:]
format, data = self.decompressSectors(data)
chunk.root_tag = nbt.load(buf=data)
chunk.compressMode = format
def unpackSectors(self, data):
length = struct.unpack_from(">I", data)[0]
format = struct.unpack_from("B", data, 4)[0]
data = data[5:length + 5]
return (format, data)
def _decompressSectors(self, format, data):
if format == self.VERSION_GZIP:
return gunzip(data)
if format == self.VERSION_DEFLATE:
return inflate(data)
raise IOError, "Unknown compress format: {0}".format(format)
def decompressSectors(self, data):
format, data = self.unpackSectors(data)
return format, self._decompressSectors(format, data)
def saveChunk(self, chunk):
cx, cz = chunk.chunkPosition
data = chunk.compressedTag
format = chunk.compressMode
self._saveChunk(cx, cz, data, format)
def _saveChunk(self, cx, cz, data, format):
cx &= 0x1f
cz &= 0x1f
offset = self.getOffset(cx, cz)
sectorNumber = offset >> 8
sectorsAllocated = offset & 0xff
sectorsNeeded = (len(data) + self.CHUNK_HEADER_SIZE) / self.SECTOR_BYTES + 1;
if sectorsNeeded >= 256: return
if (sectorNumber != 0 and sectorsAllocated >= sectorsNeeded):
debug("REGION SAVE {0},{1} rewriting {2}b".format(cx, cz, len(data)))
self.writeSector(sectorNumber, data, format)
else:
# we need to allocate new sectors
# mark the sectors previously used for this chunk as free
for i in xrange(sectorNumber, sectorNumber + sectorsAllocated):
self.freeSectors[i] = True
runLength = 0
try:
runStart = self.freeSectors.index(True)
for i in range(runStart, len(self.freeSectors)):
if runLength:
if self.freeSectors[i]:
runLength += 1
else:
runLength = 0
elif self.freeSectors[i]:
runStart = i
runLength = 1
if runLength >= sectorsNeeded:
break
except ValueError:
pass
# we found a free space large enough
if runLength >= sectorsNeeded:
debug("REGION SAVE {0},{1}, reusing {2}b".format(cx, cz, len(data)))
sectorNumber = runStart
self.setOffset(cx, cz, sectorNumber << 8 | sectorsNeeded)
self.writeSector(sectorNumber, data, format)
self.freeSectors[sectorNumber:sectorNumber + sectorsNeeded] = [False] * sectorsNeeded
else:
# no free space large enough found -- we need to grow the
# file
debug("REGION SAVE {0},{1}, growing by {2}b".format(cx, cz, len(data)))
with self.file as f:
f.seek(0, 2)
filesize = f.tell()
sectorNumber = len(self.freeSectors)
assert sectorNumber * self.SECTOR_BYTES == filesize
filesize += sectorsNeeded * self.SECTOR_BYTES
f.truncate(filesize)
self.freeSectors += [False] * sectorsNeeded
self.setOffset(cx, cz, sectorNumber << 8 | sectorsNeeded)
self.writeSector(sectorNumber, data, format)
def writeSector(self, sectorNumber, data, format):
with self.file as f:
debug("REGION: Writing sector {0}".format(sectorNumber))
f.seek(sectorNumber * self.SECTOR_BYTES)
f.write(struct.pack(">I", len(data) + 1));# // chunk length
f.write(struct.pack("B", format));# // chunk version number
f.write(data);# // chunk data
#f.flush()
def getOffset(self, cx, cz):
cx &= 0x1f;
cz &= 0x1f
return self.offsets[cx + cz * 32]
def setOffset(self, cx, cz, offset):
cx &= 0x1f;
cz &= 0x1f
self.offsets[cx + cz * 32] = offset
with self.file as f:
f.seek(0)
f.write(self.offsets.tostring())
SECTOR_BYTES = 4096
SECTOR_INTS = SECTOR_BYTES / 4
CHUNK_HEADER_SIZE = 5;
VERSION_GZIP = 1
VERSION_DEFLATE = 2
compressMode = VERSION_DEFLATE
base36alphabet = "0123456789abcdefghijklmnopqrstuvwxyz"
def decbase36(s):
return int(s, 36)
def base36(n):
global base36alphabet
n = int(n);
if 0 == n: return '0'
neg = "";
if n < 0:
neg = "-"
n = -n;
work = []
while(n):
n, digit = divmod(n, 36)
work.append(base36alphabet[digit])
return neg + ''.join(reversed(work))
def deflate(data):
#zobj = zlib.compressobj(6,zlib.DEFLATED,-zlib.MAX_WBITS,zlib.DEF_MEM_LEVEL,0)
#zdata = zobj.compress(data)
#zdata += zobj.flush()
#return zdata
return zlib.compress(data)
def inflate(data):
return zlib.decompress(data)
class MCInfdevOldLevel(EntityLevel):
materials = alphaMaterials;
isInfinite = True
parentWorld = None;
dimNo = 0;
ChunkHeight = 128
@property
def displayName(self):
#shortname = os.path.basename(self.filename);
#if shortname == "level.dat":
shortname = os.path.basename(os.path.dirname(self.filename))
return shortname
@classmethod
def _isLevel(cls, filename):
if os.path.isdir(filename):
files = os.listdir(filename);
if "level.dat" in files or "level.dat_old" in files:
return True;
elif os.path.basename(filename) in ("level.dat", "level.dat_old"):
return True;
return False
def getWorldBounds(self):
if self.chunkCount == 0:
return BoundingBox((0, 0, 0), (0, 0, 0))
allChunksArray = array(list(self.allChunks), dtype='int32')
mincx = min(allChunksArray[:, 0])
maxcx = max(allChunksArray[:, 0])
mincz = min(allChunksArray[:, 1])
maxcz = max(allChunksArray[:, 1])
origin = (mincx << 4, 0, mincz << 4)
size = ((maxcx - mincx + 1) << 4, self.Height, (maxcz - mincz + 1) << 4)
return BoundingBox(origin, size)
def __str__(self):
return "MCInfdevOldLevel(" + os.path.split(self.worldDir)[1] + ")"
def TagProperty(tagName, tagType, defaultValueFunc=lambda self:None):
def getter(self):
if tagName not in self.root_tag[Data]:
self.root_tag[Data][tagName] = tagType(defaultValueFunc(self))
return self.root_tag[Data][tagName].value
def setter(self, val):
self.root_tag[Data][tagName] = tagType(value=val)
return property(getter, setter)
SizeOnDisk = TagProperty('SizeOnDisk', TAG_Long)
RandomSeed = TagProperty('RandomSeed', TAG_Long)
Time = TagProperty('Time', TAG_Long); """ Age of the world in ticks. 20 ticks per second; 24000 ticks per day."""
LastPlayed = TagProperty('LastPlayed', TAG_Long, lambda self:long(time.time()*1000))
LevelName = TagProperty('LevelName', TAG_String, lambda self:self.displayName)
_bounds = None
@property
def bounds(self):
if self._bounds is None: self._bounds = self.getWorldBounds();
return self._bounds
@property
def size(self):
return self.bounds.size
def close(self):
for rf in (self.regionFiles or {}).values():
rf.close();
self.regionFiles = {}
def create(self, filename, random_seed, last_played):
if filename == None:
raise ValueError, "Can't create an Infinite level without a filename!"
#create a new level
root_tag = TAG_Compound();
root_tag[Data] = TAG_Compound();
root_tag[Data][SpawnX] = TAG_Int(0)
root_tag[Data][SpawnY] = TAG_Int(2)
root_tag[Data][SpawnZ] = TAG_Int(0)
if last_played is None:
last_played = long(time.time()*1000)
if random_seed is None:
random_seed = long(random.random() * 0xffffffffffffffffL) - 0x8000000000000000L
self.root_tag = root_tag;
root_tag[Data]['version'] = TAG_Int(19132)
self.LastPlayed = long(last_played)
self.RandomSeed = long(random_seed)
self.SizeOnDisk = 0
self.Time = 1
self.LevelName = os.path.basename(self.worldDir)
### if singleplayer:
self.createPlayer("Player")
if not os.path.exists(self.worldDir):
os.mkdir(self.worldDir)
def createPlayer(self, playerName):
if playerName == "Player":
playerTag = self.root_tag[Data].setdefault(playerName, TAG_Compound())
else:
playerTag = TAG_Compound()
playerTag['Air'] = TAG_Short(300);
playerTag['AttackTime'] = TAG_Short(0)
playerTag['DeathTime'] = TAG_Short(0);
playerTag['Fire'] = TAG_Short(-20);
playerTag['Health'] = TAG_Short(20);
playerTag['HurtTime'] = TAG_Short(0);
playerTag['Score'] = TAG_Int(0);
playerTag['FallDistance'] = TAG_Float(0)
playerTag['OnGround'] = TAG_Byte(0)
playerTag['Inventory'] = TAG_List()
playerTag['Motion'] = TAG_List([TAG_Double(0) for i in range(3)])
playerTag['Pos'] = TAG_List([TAG_Double([0.5, 2.8, 0.5][i]) for i in range(3)])
playerTag['Rotation'] = TAG_List([TAG_Float(0), TAG_Float(0)])
if playerName != "Player":
self.playerTagCache.save(self.getPlayerPath(playerName))
def __init__(self, filename=None, create=False, random_seed=None, last_played=None):
"""
Load an Alpha level from the given filename. It can point to either
a level.dat or a folder containing one. If create is True, it will
also create the world using the random_seed and last_played arguments.
If they are none, a random 64-bit seed will be selected for RandomSeed
and long(time.time()*1000) will be used for LastPlayed.
If you try to create an existing world, its level.dat will be replaced.
"""
self.Length = 0
self.Width = 0