forked from mcedit/pymclevel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mce.py
1501 lines (1173 loc) · 46.2 KB
/
mce.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
#!/usr/bin/env python
import mclevel
import infiniteworld
import sys
import os
from box import BoundingBox
import numpy
from numpy import zeros, bincount
import logging
import itertools
import traceback
import shlex
import operator
import codecs
from math import floor
try:
import readline # if available, used by raw_input()
except:
pass
class UsageError(RuntimeError):
pass
class BlockMatchError(RuntimeError):
pass
class PlayerNotFound(RuntimeError):
pass
class mce(object):
"""
Block commands:
{commandPrefix}clone <sourceBox> <destPoint> [noair] [nowater]
{commandPrefix}fill <blockType> [ <box> ]
{commandPrefix}replace <blockType> [with] <newBlockType> [ <box> ]
{commandPrefix}export <filename> <sourceBox>
{commandPrefix}import <filename> <destPoint> [noair] [nowater]
{commandPrefix}createChest <point> <item> [ <count> ]
{commandPrefix}analyze
Player commands:
{commandPrefix}player [ <player> [ <point> ] ]
{commandPrefix}spawn [ <point> ]
Entity commands:
{commandPrefix}removeEntities [ <EntityID> ]
{commandPrefix}dumpSigns [ <filename> ]
{commandPrefix}dumpChests [ <filename> ]
Chunk commands:
{commandPrefix}createChunks <box>
{commandPrefix}deleteChunks <box>
{commandPrefix}prune <box>
{commandPrefix}relight [ <box> ]
World commands:
{commandPrefix}create <filename>
{commandPrefix}dimension [ <dim> ]
{commandPrefix}degrief
{commandPrefix}time [ <time> ]
{commandPrefix}worldsize
{commandPrefix}heightmap <filename>
{commandPrefix}randomseed [ <seed> ]
{commandPrefix}gametype [ <player> [ <gametype> ] ]
Editor commands:
{commandPrefix}save
{commandPrefix}reload
{commandPrefix}load <filename> | <world number>
{commandPrefix}execute <filename>
{commandPrefix}quit
Informational:
{commandPrefix}blocks [ <block name> | <block ID> ]
{commandPrefix}help [ <command> ]
**IMPORTANT**
{commandPrefix}box
Type 'box' to learn how to specify points and areas.
"""
random_seed = os.getenv('MCE_RANDOM_SEED', None)
last_played = os.getenv("MCE_LAST_PLAYED", None)
def commandUsage(self, command):
" returns usage info for the named command - just give the docstring for the handler func "
func = getattr(self, "_" + command)
return func.__doc__
commands = [
"clone",
"fill",
"replace",
"export",
"execute",
"import",
"createchest",
"player",
"spawn",
"removeentities",
"dumpsigns",
"dumpchests",
"createchunks",
"deletechunks",
"prune",
"relight",
"create",
"degrief",
"time",
"worldsize",
"heightmap",
"randomseed",
"gametype",
"save",
"load",
"reload",
"dimension",
"repair",
"quit",
"exit",
"help",
"blocks",
"analyze",
"region",
"debug",
"log",
"box",
]
debug = False
needsSave = False
def readInt(self, command):
try:
val = int(command.pop(0))
except ValueError:
raise UsageError("Cannot understand numeric input")
return val
def prettySplit(self, command):
cmdstring = " ".join(command)
lex = shlex.shlex(cmdstring)
lex.whitespace_split = True
lex.whitespace += "(),"
command[:] = list(lex)
def readBox(self, command):
self.prettySplit(command)
sourcePoint = self.readIntPoint(command)
if command[0].lower() == "to":
command.pop(0)
sourcePoint2 = self.readIntPoint(command)
sourceSize = map(operator.sub, sourcePoint2, sourcePoint)
else:
sourceSize = self.readIntPoint(command, isPoint=False)
if len([p for p in sourceSize if p <= 0]):
raise UsageError("Box size cannot be zero or negative")
box = BoundingBox(sourcePoint, sourceSize)
return box
def readIntPoint(self, command, isPoint=True):
point = self.readPoint(command, isPoint)
point = map(int, map(floor, point))
return point
def readPoint(self, command, isPoint=True):
self.prettySplit(command)
try:
word = command.pop(0)
if isPoint and (word in self.level.players):
x, y, z = self.level.getPlayerPosition(word)
if len(command) and command[0].lower() == "delta":
command.pop(0)
try:
x += int(command.pop(0))
y += int(command.pop(0))
z += int(command.pop(0))
except ValueError:
raise UsageError("Error decoding point input (expected a number).")
return x, y, z
except IndexError:
raise UsageError("Error decoding point input (expected more values).")
try:
try:
x = float(word)
except ValueError:
if isPoint:
raise PlayerNotFound(word)
raise
y = float(command.pop(0))
z = float(command.pop(0))
except ValueError:
raise UsageError("Error decoding point input (expected a number).")
except IndexError:
raise UsageError("Error decoding point input (expected more values).")
return x, y, z
def readBlockInfo(self, command):
keyword = command.pop(0)
matches = self.level.materials.blocksMatching(keyword)
blockInfo = None
if len(matches):
if len(matches) == 1:
blockInfo = matches[0]
# eat up more words that possibly specify a block. stop eating when 0 matching blocks.
while len(command):
newMatches = self.level.materials.blocksMatching(keyword + " " + command[0])
if len(newMatches) == 1:
blockInfo = newMatches[0]
if len(newMatches) > 0:
matches = newMatches
keyword = keyword + " " + command.pop(0)
else:
break
else:
try:
data = 0
if ":" in keyword:
blockID, data = map(int, keyword.split(":"))
else:
blockID = int(keyword)
blockInfo = self.level.materials.blockWithID(blockID, data)
except ValueError:
blockInfo = None
if blockInfo is None:
print "Ambiguous block specifier: ", keyword
if len(matches):
print "Matches: "
for m in matches:
if m == self.level.materials.defaultName:
continue
print "{0:3}:{1:<2} : {2}".format(m.ID, m.blockData, m.name)
else:
print "No blocks matched."
raise BlockMatchError
return blockInfo
def readBlocksToCopy(self, command):
blocksToCopy = range(256)
while len(command):
word = command.pop()
if word == "noair":
blocksToCopy.remove(0)
if word == "nowater":
blocksToCopy.remove(8)
blocksToCopy.remove(9)
return blocksToCopy
def _box(self, command):
"""
Boxes:
Many commands require a <box> as arguments. A box can be specified with
a point and a size:
(12, 5, 15), (5, 5, 5)
or with two points, making sure to put the keyword "to" between them:
(12, 5, 15) to (17, 10, 20)
The commas and parentheses are not important.
You may add them for improved readability.
Points:
Points and sizes are triplets of numbers ordered X Y Z.
X is position north-south, increasing southward.
Y is position up-down, increasing upward.
Z is position east-west, increasing westward.
Players:
A player's name can be used as a point - it will use the
position of the player's head. Use the keyword 'delta' after
the name to specify a point near the player.
Example:
codewarrior delta 0 5 0
This refers to a point 5 blocks above codewarrior's head.
"""
raise UsageError
def _debug(self, command):
self.debug = not self.debug
print "Debug", ("disabled", "enabled")[self.debug]
def _log(self, command):
"""
log [ <number> ]
Get or set the log threshold. 0 logs everything; 50 only logs major errors.
"""
if len(command):
try:
logging.getLogger().level = int(command[0])
except ValueError:
raise UsageError("Cannot understand numeric input.")
else:
print "Log level: {0}".format(logging.getLogger().level)
def _clone(self, command):
"""
clone <sourceBox> <destPoint> [noair] [nowater]
Clone blocks in a cuboid starting at sourcePoint and extending for
sourceSize blocks in each direction. Blocks and entities in the area
are cloned at destPoint.
"""
if len(command) == 0:
self.printUsage("clone")
return
box = self.readBox(command)
destPoint = self.readPoint(command)
destPoint = map(int, map(floor, destPoint))
blocksToCopy = self.readBlocksToCopy(command)
tempSchematic = self.level.extractSchematic(box)
self.level.copyBlocksFrom(tempSchematic, BoundingBox((0, 0, 0), box.origin), destPoint, blocksToCopy)
self.needsSave = True
print "Cloned 0 blocks."
def _fill(self, command):
"""
fill <blockType> [ <box> ]
Fill blocks with blockType in a cuboid starting at point and
extending for size blocks in each direction. Without a
destination, fills the whole world. blockType and may be a
number from 0-255 or a name listed by the 'blocks' command.
"""
if len(command) == 0:
self.printUsage("fill")
return
blockInfo = self.readBlockInfo(command)
if len(command):
box = self.readBox(command)
else:
box = None
print "Filling with {0}".format(blockInfo.name)
self.level.fillBlocks(box, blockInfo)
self.needsSave = True
print "Filled {0} blocks.".format("all" if box is None else box.volume)
def _replace(self, command):
"""
replace <blockType> [with] <newBlockType> [ <box> ]
Replace all blockType blocks with newBlockType in a cuboid
starting at point and extending for size blocks in
each direction. Without a destination, replaces blocks over
the whole world. blockType and newBlockType may be numbers
from 0-255 or names listed by the 'blocks' command.
"""
if len(command) == 0:
self.printUsage("replace")
return
blockInfo = self.readBlockInfo(command)
if command[0].lower() == "with":
command.pop(0)
newBlockInfo = self.readBlockInfo(command)
if len(command):
box = self.readBox(command)
else:
box = None
print "Replacing {0} with {1}".format(blockInfo.name, newBlockInfo.name)
self.level.fillBlocks(box, newBlockInfo, blocksToReplace=[blockInfo])
self.needsSave = True
print "Done."
def _createchest(self, command):
"""
createChest <point> <item> [ <count> ]
Create a chest filled with the specified item.
Stacks are 64 if count is not given.
"""
point = map(lambda x: int(floor(float(x))), self.readPoint(command))
itemID = self.readInt(command)
count = 64
if len(command):
count = self.readInt(command)
chest = mclevel.MCSchematic.chestWithItemID(itemID, count)
self.level.copyBlocksFrom(chest, chest.bounds, point)
self.needsSave = True
def _analyze(self, command):
"""
analyze
Counts all of the block types in every chunk of the world.
Also updates the level's 'SizeOnDisk' field, correcting its size in the
world select menu.
"""
blockCounts = zeros((4096,), 'uint64')
sizeOnDisk = 0
print "Analyzing {0} chunks...".format(self.level.chunkCount)
# for input to bincount, create an array of uint16s by
# shifting the data left and adding the blocks
for i, cPos in enumerate(self.level.allChunks, 1):
ch = self.level.getChunk(*cPos)
btypes = numpy.array(ch.Data.ravel(), dtype='uint16')
btypes <<= 8
btypes += ch.Blocks.ravel()
counts = bincount(btypes)
blockCounts[:counts.shape[0]] += counts
sizeOnDisk += ch.compressedSize()
ch.unload()
if i % 100 == 0:
logging.info("Chunk {0}...".format(i))
for blockID in range(256):
block = self.level.materials.blockWithID(blockID, 0)
if block.hasVariants:
for data in range(16):
i = (data << 8) + blockID
if blockCounts[i]:
idstring = "({id}:{data})".format(id=blockID, data=data)
print "{idstring:9} {name:30}: {count:<10}".format(
idstring=idstring, name=self.level.materials.blockWithID(blockID, data).name, count=blockCounts[i])
else:
count = int(sum(blockCounts[(d << 8) + blockID] for d in range(16)))
if count:
idstring = "({id})".format(id=blockID)
print "{idstring:9} {name:30}: {count:<10}".format(
idstring=idstring, name=self.level.materials.blockWithID(blockID, 0).name, count=count)
print "Size on disk: {0:.3}MB".format(sizeOnDisk / 1048576.0)
self.level.SizeOnDisk = sizeOnDisk
self.needsSave = True
def _export(self, command):
"""
export <filename> <sourceBox>
Exports blocks in the specified region to a file in schematic format.
This file can be imported with mce or MCEdit.
"""
if len(command) == 0:
self.printUsage("export")
return
filename = command.pop(0)
box = self.readBox(command)
tempSchematic = self.level.extractSchematic(box)
tempSchematic.saveToFile(filename)
print "Exported {0} blocks.".format(tempSchematic.bounds.volume)
def _import(self, command):
"""
import <filename> <destPoint> [noair] [nowater]
Imports a level or schematic into this world, beginning at destPoint.
Supported formats include
- Alpha single or multiplayer world folder containing level.dat,
- Zipfile containing Alpha world folder,
- Classic single-player .mine,
- Classic multiplayer server_level.dat,
- Indev .mclevel
- Schematic from RedstoneSim, MCEdit, mce
- .inv from INVEdit (appears as a chest)
"""
if len(command) == 0:
self.printUsage("import")
return
filename = command.pop(0)
destPoint = self.readPoint(command)
blocksToCopy = self.readBlocksToCopy(command)
importLevel = mclevel.fromFile(filename)
self.level.copyBlocksFrom(importLevel, importLevel.bounds, destPoint, blocksToCopy, create=True)
self.needsSave = True
print "Imported {0} blocks.".format(importLevel.bounds.volume)
def _player(self, command):
"""
player [ <player> [ <point> ] ]
Move the named player to the specified point.
Without a point, prints the named player's position.
Without a player, prints all players and positions.
In a single-player world, the player is named Player.
"""
if len(command) == 0:
print "Players: "
for player in self.level.players:
print " {0}: {1}".format(player, self.level.getPlayerPosition(player))
return
player = command.pop(0)
if len(command) == 0:
print "Player {0}: {1}".format(player, self.level.getPlayerPosition(player))
return
point = self.readPoint(command)
self.level.setPlayerPosition(point, player)
self.needsSave = True
print "Moved player {0} to {1}".format(player, point)
def _spawn(self, command):
"""
spawn [ <point> ]
Move the world's spawn point.
Without a point, prints the world's spawn point.
"""
if len(command):
point = self.readPoint(command)
point = map(int, map(floor, point))
self.level.setPlayerSpawnPosition(point)
self.needsSave = True
print "Moved spawn point to ", point
else:
print "Spawn point: ", self.level.playerSpawnPosition()
def _dumpsigns(self, command):
"""
dumpSigns [ <filename> ]
Saves the text and location of every sign in the world to a text file.
With no filename, saves signs to <worldname>.signs
Output is newline-delimited. 5 lines per sign. Coordinates are
on the first line, followed by four lines of sign text. For example:
[229, 118, -15]
"To boldy go
where no man
has gone
before."
Coordinates are ordered the same as point inputs:
[North/South, Down/Up, East/West]
"""
if len(command):
filename = command[0]
else:
filename = self.level.displayName + ".signs"
outFile = codecs.open(filename, "w", encoding='utf-8')
print "Dumping signs..."
signCount = 0
for i, cPos in enumerate(self.level.allChunks):
try:
chunk = self.level.getChunk(*cPos)
except mclevel.ChunkMalformed:
continue
for tileEntity in chunk.TileEntities:
if tileEntity["id"].value == "Sign":
signCount += 1
outFile.write(str(map(lambda x: tileEntity[x].value, "xyz")) + "\n")
for i in range(4):
outFile.write(tileEntity["Text{0}".format(i + 1)].value + u"\n")
if i % 100 == 0:
print "Chunk {0}...".format(i)
chunk.unload()
print "Dumped {0} signs to {1}".format(signCount, filename)
outFile.close()
def _region(self, command):
"""
region [rx rz]
List region files in this world.
"""
level = self.level
assert(isinstance(level, mclevel.MCInfdevOldLevel))
assert level.version
def getFreeSectors(rf):
runs = []
start = None
count = 0
for i, free in enumerate(rf.freeSectors):
if free:
if start is None:
start = i
count = 1
else:
count += 1
else:
if start is None:
pass
else:
runs.append((start, count))
start = None
count = 0
return runs
def printFreeSectors(runs):
for i, (start, count) in enumerate(runs):
if i % 4 == 3:
print ""
print "{start:>6}+{count:<4}".format(**locals()),
print ""
if len(command):
if len(command) > 1:
rx, rz = map(int, command[:2])
level.allChunks
rf = level.regionFiles.get((rx, rz))
if rf is None:
print "Region {rx},{rz} not found.".format(**locals())
return
print "Region {rx:6}, {rz:6}: {used}/{sectors} sectors".format(used=rf.usedSectors, sectors=rf.sectorCount)
print "Offset Table:"
for cx in range(32):
for cz in range(32):
if cz % 4 == 0:
print ""
print "{0:3}, {1:3}: ".format(cx, cz),
off = rf.getOffset(cx, cz)
sector, length = off >> 8, off & 0xff
print "{sector:>6}+{length:<2} ".format(**locals()),
print ""
runs = getFreeSectors(rf)
if len(runs):
print "Free sectors:",
printFreeSectors(runs)
else:
if command[0] == "free":
level.allChunks
for (rx, rz), rf in level.regionFiles.iteritems():
runs = getFreeSectors(rf)
if len(runs):
print "R {0:3}, {1:3}:".format(rx, rz),
printFreeSectors(runs)
else:
level.allChunks
coords = (r for r in level.regionFiles)
for i, (rx, rz) in enumerate(coords):
print "({rx:6}, {rz:6}): {count}, ".format(count=level.regionFiles[rx, rz].chunkCount),
if i % 5 == 4:
print ""
def _repair(self, command):
"""
repair
Attempt to repair inconsistent region files.
MAKE A BACKUP. WILL DELETE YOUR DATA.
Scans for and repairs errors in region files:
Deletes chunks whose sectors overlap with another chunk
Rearranges chunks that are in the wrong slot in the offset table
Deletes completely unreadable chunks
Only usable with region-format saves.
"""
if self.level.version:
self.level.preloadRegions()
for rf in self.level.regionFiles.itervalues():
rf.repair()
def _dumpchests(self, command):
"""
dumpChests [ <filename> ]
Saves the content and location of every chest in the world to a text file.
With no filename, saves signs to <worldname>.chests
Output is delimited by brackets and newlines. A set of coordinates in
brackets begins a chest, followed by a line for each inventory slot.
For example:
[222, 51, 22]
2 String
3 String
3 Iron bar
Coordinates are ordered the same as point inputs:
[North/South, Down/Up, East/West]
"""
from items import items
if len(command):
filename = command[0]
else:
filename = self.level.displayName + ".chests"
outFile = file(filename, "w")
print "Dumping chests..."
chestCount = 0
for i, cPos in enumerate(self.level.allChunks):
try:
chunk = self.level.getChunk(*cPos)
except mclevel.ChunkMalformed:
continue
for tileEntity in chunk.TileEntities:
if tileEntity["id"].value == "Chest":
chestCount += 1
outFile.write(str(map(lambda x: tileEntity[x].value, "xyz")) + "\n")
itemsTag = tileEntity["Items"]
if len(itemsTag):
for itemTag in itemsTag:
try:
id = itemTag["id"].value
damage = itemTag["Damage"].value
item = items.findItem(id, damage)
itemname = item.name
except KeyError:
itemname = "Unknown Item {0}".format(itemTag)
except Exception, e:
itemname = repr(e)
outFile.write("{0} {1}\n".format(itemTag["Count"].value, itemname))
else:
outFile.write("Empty Chest\n")
if i % 100 == 0:
print "Chunk {0}...".format(i)
chunk.unload()
print "Dumped {0} chests to {1}".format(chestCount, filename)
outFile.close()
def _removeentities(self, command):
"""
removeEntities [ [except] [ <EntityID> [ <EntityID> ... ] ] ]
Remove all entities matching one or more entity IDs.
With the except keyword, removes all entities not
matching one or more entity IDs.
Without any IDs, removes all entities in the world,
except for Paintings.
Known Mob Entity IDs:
Mob Monster Creeper Skeleton Spider Giant
Zombie Slime Pig Sheep Cow Chicken
Known Item Entity IDs: Item Arrow Snowball Painting
Known Vehicle Entity IDs: Minecart Boat
Known Dynamic Tile Entity IDs: PrimedTnt FallingSand
"""
ENT_MATCHTYPE_ANY = 0
ENT_MATCHTYPE_EXCEPT = 1
ENT_MATCHTYPE_NONPAINTING = 2
def match(entityID, matchType, matchWords):
if(ENT_MATCHTYPE_ANY == matchType):
return entityID.lower() in matchWords
elif(ENT_MATCHTYPE_EXCEPT == matchType):
return not (entityID.lower() in matchWords)
else:
# ENT_MATCHTYPE_EXCEPT == matchType
return entityID != "Painting"
removedEntities = {}
match_words = []
if len(command):
if command[0].lower() == "except":
command.pop(0)
print "Removing all entities except ", command
match_type = ENT_MATCHTYPE_EXCEPT
else:
print "Removing {0}...".format(", ".join(command))
match_type = ENT_MATCHTYPE_ANY
match_words = map(lambda x: x.lower(), command)
else:
print "Removing all entities except Painting..."
match_type = ENT_MATCHTYPE_NONPAINTING
for cx, cz in self.level.allChunks:
chunk = self.level.getChunk(cx, cz)
entitiesRemoved = 0
for entity in list(chunk.Entities):
entityID = entity["id"].value
if match(entityID, match_type, match_words):
removedEntities[entityID] = removedEntities.get(entityID, 0) + 1
chunk.Entities.remove(entity)
entitiesRemoved += 1
if entitiesRemoved:
chunk.chunkChanged(False)
chunk.compress()
chunk.save()
chunk.unload()
if len(removedEntities) == 0:
print "No entities to remove."
else:
print "Removed entities:"
for entityID in sorted(removedEntities.keys()):
print " {0}: {1:6}".format(entityID, removedEntities[entityID])
self.needsSave = True
def _createchunks(self, command):
"""
createChunks <box>
Creates any chunks not present in the specified region.
New chunks are filled with only air. New chunks are written
to disk immediately.
"""
if len(command) == 0:
self.printUsage("createchunks")
return
box = self.readBox(command)
chunksCreated = self.level.createChunksInBox(box)
print "Created {0} chunks." .format(len(chunksCreated))
self.needsSave = True
def _deletechunks(self, command):
"""
deleteChunks <box>
Removes all chunks contained in the specified region.
Chunks are deleted from disk immediately.
"""
if len(command) == 0:
self.printUsage("deletechunks")
return
box = self.readBox(command)
deletedChunks = self.level.deleteChunksInBox(box)
print "Deleted {0} chunks." .format(len(deletedChunks))
def _prune(self, command):
"""
prune <box>
Removes all chunks not contained in the specified region. Useful for enforcing a finite map size.
Chunks are deleted from disk immediately.
"""
if len(command) == 0:
self.printUsage("prune")
return
box = self.readBox(command)
i = 0
for cx, cz in list(self.level.allChunks):
if cx < box.mincx or cx >= box.maxcx or cz < box.mincz or cz >= box.maxcz:
self.level.deleteChunk(cx, cz)
i += 1
print "Pruned {0} chunks." .format(i)
def _relight(self, command):
"""
relight [ <box> ]
Recalculates lights in the region specified. If omitted,
recalculates the entire world.
"""
if len(command):
box = self.readBox(command)
chunks = itertools.product(range(box.mincx, box.maxcx), range(box.mincz, box.maxcz))
else:
chunks = self.level.allChunks
self.level.generateLights(chunks)
print "Relit 0 chunks."
self.needsSave = True
def _create(self, command):
"""
create [ <filename> ]
Create and load a new Minecraft Alpha world. This world will have no
chunks and a random terrain seed. If run from the shell, filename is not
needed because you already specified a filename earlier in the command.
For example:
mce.py MyWorld create
"""
if len(command) < 1:
raise UsageError("Expected a filename")
filename = command[0]
if not os.path.exists(filename):
os.mkdir(filename)
if not os.path.isdir(filename):
raise IOError("{0} already exists".format(filename))
if mclevel.MCInfdevOldLevel.isLevel(filename):
raise IOError("{0} is already a Minecraft Alpha world".format(filename))
level = mclevel.MCInfdevOldLevel(filename, create=True)
self.level = level
def _degrief(self, command):
"""
degrief [ <height> ]
Reverse a few forms of griefing by removing
Adminium, Obsidian, Fire, and Lava wherever
they occur above the specified height.
Without a height, uses height level 32.