def createschematic():
    a = (128 * 129 * (maxup + abs(maxdown) + 1))
    schematic = nbt.NBTFile()
    schematic["Height"] = nbt.TAG_Short(value=(abs(maxdown) + maxup + 1))
    schematic["Length"] = nbt.TAG_Short(value=129)
    schematic["Width"] = nbt.TAG_Short(value=128)
    tempblocks = array.array('B', [0] * a)
    tempdata = array.array('B', [0] * a)
    for x in xrange(128):
        for y in xrange(128):
            tempblocks[s(x, y)] = blockid[tempcolors[m(x, y)]]
            tempdata[s(x, y)] = blockdata[tempcolors[m(x, y)]]
        tempblocks[s(x, 128)] = 3
        tempdata[s(x, 128)] = 0
    schematic["Blocks"] = nbt.TAG_Byte_Array()
    schematic["Data"] = nbt.TAG_Byte_Array()
    schematic["Blocks"].value = bytearray(tempblocks)
    schematic["Data"].value = bytearray(tempdata)
    schematic["Materials"] = nbt.TAG_String(value="Alpha")
    print "Writing file..."
    schematic.write_file(schematicpath)
    print "Schematic successfully created!"
    print "max height up: " + repr(maxup)
    print "max height down: " + repr(abs(maxdown))
    print "Minimum height you should build at: " + repr(maxup + 64)
Esempio n. 2
0
def render_topographic_chunk((chunk_file, map_size, render_options)):
    chunk = nbt.NBTFile(chunk_file, 'rb')
    array_offset_X = (abs(map_size['x_min']) +
                      chunk['Level']['xPos'].value) * Level.chunk_size_X
    array_offset_Z = (abs(map_size['z_min']) +
                      chunk['Level']['zPos'].value) * Level.chunk_size_Z

    try:
        blocks = numpy.fromstring(chunk['Level']['Blocks'].value,
                                  dtype=numpy.uint8).reshape(
                                      Level.chunk_size_X, Level.chunk_size_Z,
                                      Level.chunk_size_Y)
        for y in xrange(Level.chunk_size_Y):
            profile = Level.topographic_translator[blocks[..., y]]
            water = (profile == -1) * 1
            colors = Level.topographic_colors[((profile + water) * (y + 2)) +
                                              water].reshape(
                                                  Level.chunk_size_X,
                                                  Level.chunk_size_Z,
                                                  Level.color_depth)

            image_array[array_offset_Z:array_offset_Z + Level.chunk_size_Z,
                        array_offset_X:array_offset_X +
                        Level.chunk_size_X] = overlay_chunk(
                            colors.swapaxes(0, 1),
                            image_array[array_offset_Z:array_offset_Z +
                                        Level.chunk_size_Z,
                                        array_offset_X:array_offset_X +
                                        Level.chunk_size_X])
        print 'Finished chunk %s' % str((array_offset_X, array_offset_Z))
    except IndexError, err:
        print 'Failed chunk: %s' % err
Esempio n. 3
0
def filterEntities(value, args):
    buff = io.BytesIO(value)
    outBuff = io.BytesIO()
    removed = False
    while True:
        try:
            tree = nbt.NBTFile(buffer=buff)
            try:
                name = tree['CustomName']
                tree.write_file(buffer=outBuff)
            except KeyError:
                try:
                    if tree['IsTamed']:
                        tree.write_file(buffer=outBuff)
                    elif "+minecraft:charged_creeper" in tree["definitions"]:
                        tree.write_file(buffer=outBuff)
                    elif not tree["NaturalSpawn"]:
                        found = False
                        for definition in tree['definitions']:
                            if definition in entitiesFiler:
                                removed = True
                                found = True
                                break
                        if not found:
                            tree.write_file(buffer=outBuff)
                    else:
                        removed = True
                except KeyError as e:
                    tree.write_file(buffer=outBuff)
        except nbt.MalformedFileError:
            break
    if removed:
        return outBuff
    else:
        return None
Esempio n. 4
0
 def __init__(self, level_file):
     self.level_file = level_file
     try:
         self.level_file = nbt.NBTFile(self.level_file, 'rb')
         #do something here to checkout the level file?
     except IOError, err:
         #should probably do something more worthwhile here
         raise err
Esempio n. 5
0
def render_chunk((map_size, chunk_file)):
    chunk_setup = time.time()

    map_chunk_offset_X = abs(map_size['x_min'])
    map_chunk_offset_Z = abs(map_size['z_min'])
    map_image_size = (
        (abs(map_size['x_max']) + map_chunk_offset_X) * Mapper.chunk_size_X +
        16,
        (abs(map_size['z_max']) + map_chunk_offset_Z) * Mapper.chunk_size_Z +
        16)

    block_colors = numpy.array([
        Mapper.block_colors.get(color, (255, 255, 255))
        for color in xrange(255)
    ],
                               dtype=numpy.uint8)
    chunk = nbt.NBTFile(chunk_file, 'rb')

    chunk_pos_X = chunk['Level']['xPos'].value
    chunk_pos_Z = chunk['Level']['zPos'].value
    chunk_pixel_offset_X = (chunk_pos_X +
                            map_chunk_offset_X) * Mapper.chunk_size_X
    chunk_pixel_offset_Z = (chunk_pos_Z +
                            map_chunk_offset_Z) * Mapper.chunk_size_Z

    end_chunk_setup = time.time()

    chunk_render = time.time()
    try:
        blocks = numpy.fromstring(chunk['Level']['Blocks'].value,
                                  dtype=numpy.uint8).reshape(16, 16, 128)
        tops = [z[z.nonzero()][-1] for x in blocks for z in x]
        colors = block_colors[tops].reshape(16, 16, 3)

        image_array = numpy.memmap(mmap_filen,
                                   dtype=numpy.uint8,
                                   mode='r+',
                                   shape=(map_image_size[1], map_image_size[0],
                                          3))
        image_array[(map_chunk_offset_Z + chunk_pos_Z) *
                    16:(map_chunk_offset_Z + chunk_pos_Z) * 16 + 16,
                    (map_chunk_offset_X + chunk_pos_X) *
                    16:(map_chunk_offset_X + chunk_pos_X) * 16 +
                    16] = colors.swapaxes(0, 1)
        del image_array
    except:
        pass

    end_chunk_render = time.time()

    return (end_chunk_setup - chunk_setup, end_chunk_render - chunk_render)
Esempio n. 6
0
def getPosition(world):
    name, path = world

    nbtfile = nbt.NBTFile(os.path.join(path, "level.dat"), "rb")
    data = nbtfile["Data"]
    player = data["Player"]
    if player:
        nbtpos = player["Pos"]
        pos = (int(nbtpos[0].value), int(nbtpos[1].value),
               int(nbtpos[2].value))
    else:
        pos = (data["SpawnX"].value, data["SpawnY"].value,
               data["SpawnZ"].value)
    return pos
Esempio n. 7
0
def region_chunks(chunk_region_file):
    chunk_region = file(chunk_region_file, 'rb')

    # Read where each chunk is
    locations_and_sizes = _1024_UINT32_STRUCT.unpack(chunk_region.read(_1024_UINT32_STRUCT.size))

    # Now convert them to (location, size) tuples
    locations_and_sizes = map(bytes_to_location_and_size, locations_and_sizes)

    for location, size_ in locations_and_sizes:
        if location and size_:
            chunk_region.seek(location)
            size = UINT32_STRUCT.unpack(chunk_region.read(UINT32_STRUCT.size))[0] - 1
            compression_type = ord(chunk_region.read(1))
            data = chunk_region.read(size).decode('zlib') + '\0'
            nbt_ = nbt.NBTFile()
            nbt_.parse_file(file=StringIO.StringIO(data))
            yield nbt_
Esempio n. 8
0
def render_oblique_chunk((chunk_file, map_size, render_options)):
    chunk = nbt.NBTFile(chunk_file, 'rb')
    array_offset_X = (abs(map_size['x_min']) +
                      chunk['Level']['xPos'].value) * Level.chunk_size_X
    array_offset_Z = (abs(map_size['z_min']) +
                      chunk['Level']['zPos'].value) * Level.chunk_size_Z

    try:
        blocks = numpy.fromstring(chunk['Level']['Blocks'].value,
                                  dtype=numpy.uint8).reshape(
                                      Level.chunk_size_X, Level.chunk_size_Z,
                                      Level.chunk_size_Y)
        new_chunk_pixels = image_array[array_offset_Z:array_offset_Z +
                                       Level.chunk_size_Z * 2 +
                                       Level.chunk_size_Y,
                                       array_offset_X:array_offset_X +
                                       Level.chunk_size_X]

        for y in range(Level.chunk_size_Y):
            colors = Level.base_block_colors[blocks[..., y]].reshape(
                Level.chunk_size_X, Level.chunk_size_Z, Level.color_depth)
            shaded_colors = Level.base_block_colors[blocks[..., y]].reshape(
                Level.chunk_size_X, Level.chunk_size_Z, Level.color_depth)
            for z, x in itertools.product(
                    *map(xrange, [Level.chunk_size_X, Level.chunk_size_Z])):
                try:
                    new_chunk_pixels[(Level.chunk_size_Y - y) + z,
                                     x] = overlay_pixel(
                                         colors[x, z],
                                         new_chunk_pixels[(Level.chunk_size_Y -
                                                           y) + z, x])
                    new_chunk_pixels[(Level.chunk_size_Y - y) + z + 1,
                                     x] = overlay_pixel(
                                         shaded_colors[x, z],
                                         new_chunk_pixels[(Level.chunk_size_Y -
                                                           y) + z + 1, x])
                except IndexError:
                    pass
        image_array[array_offset_Z:array_offset_Z + Level.chunk_size_Z * 2 +
                    Level.chunk_size_Y, array_offset_X:array_offset_X +
                    Level.chunk_size_X] = new_chunk_pixels
    except IndexError, err:
        print 'Failed chunk: %s' % err
Esempio n. 9
0
def fixPendingTicks(key, value, args):
	buff = io.BytesIO(value)
	outBuff = io.BytesIO()
	modified = 0
	while True :
		try :
			tree = nbt.NBTFile(buffer=buff)
			try :
				if tree['tickList']:
					print(key.x*16, key.z*16, len(tree['tickList']))
					print(tree.pretty_tree())
#					modified += 1
#					newList = nbt.TAG_List(type=nbt.TAG_Compound, name='tickList')
#					tree['tickList'] = newList
#					tree.write_file(buffer=outBuff)
			except KeyError:
				pass
		except nbt.MalformedFileError:
			break
	return modified, outBuff
Esempio n. 10
0
    def notify_save(self):
        global names
        data = nbt.NBTFile(level_file)["Data"]

        time = data["DayTime"].value % 24000
        rain = data["raining"].value
        thunder = data["thundering"].value

        index = bisect.bisect(names, (time, ))
        name = random.choice(names[index - 1][1])
        text = "[*] 'Tis " + name + " in Loafyland with "

        if rain:
            if thunder:
                text += "a severe thunderstorm warning."
            else:
                text += "a chance of showers."
        else:
            text += "partly cloudy skies."

        self.reply.say(text)
Esempio n. 11
0
def main(args):
	date = datetime.datetime.now()
	worldBorders = []
	if args.worldBorders :
		worldBorders = getWorldBordersFromFile(args.worldBorders)
	world = ""
	if args.world.endswith('db'):
		world = args.world
	else :
		world = os.path.join(args.world, 'db')
	
	spawners = {}
	ships = {}
	with leveldb.DB(world) as db :
		if args.worldBorders or args.removeEntities or args.pendingTicks or args.dumpHSA or args.findSpawners or args.compact:
			print("Reading database")
			for entry in db:
				if not  isinstance(entry, Row):
					print(entry)
					continue
				key = Key.fromBytes(entry.key)
				if not key :
					continue
				if args.worldBorders and (key.dimension, key.x, key.z) not in worldBorders:
					print("Removing d:%s x:%s z:%s"%( key.dimension, key.x, key.z))
					db.delete(entry.key)
					continue
				if key.tag == 50 and args.removeEntities :
					outBuff = filterEntities(entry.value, args)
					if outBuff :
						db.put(entry.key, outBuff.getvalue())
				elif key.tag == 51 and args.pendingTicks:
					db.delete(entry.key)
#					removed, outBuff = fixPendingTicks(key, entry.value, args)
#					if removed:
#						print("Removed %d pendingTicks in d:%s, x:%s, z:%s"%( removed, key.dimension, key.x, key.z))
#						db.put(entry.key, outBuff.getvalue())
				elif key.tag == 49 and args.findSpawners:
					buff = io.BytesIO(entry.value)
					if entry.value :
						tree = nbt.NBTFile(buffer=buff)
						if tree['id'] == "MobSpawner":
							spawners[Position(tree['x'].value, tree['y'].value, tree['z'].value, key.dimension)] = tree
				elif key.tag == 57 and args.dumpHSA:
					amount = int.from_bytes(entry.value[0:4],"little")
#					newAmount = 0
#					newData = b""
					for x in range(amount):
						hsa = HSA.fromBytes(entry.value[x*25+4:(x+1)*25+4], key.dimension)
						print(hsa)
#				elif key.tag == 47 and args.compact :
#						palette = { 0x2 : (32,1,False) , 0x4 : (16,2,False), 0x6 : (10,3,True) , 0x8 : (8,4,False) , 0xa : (6,5,True) , 0xc: (5,6,True) , 0x10: (4,8,False) , 0x20 : (2,16,False) }
#						pal = int(entry.value[2])
#						chunkPalFormat = palette[pal]
#						size = len(entry.value)
#						end = (4096//chunkPalFormat[0])*4 + int(chunkPalFormat[2])*4
#				#                   print(key, len(entry.value), pal, chunkPalFormat, end+7)
#						buff = io.BytesIO(entry.value[end+7:])
#						chunkPalette = []
#						while True :
#							try :
#								tree = nbt.NBTFile(buffer=buff)
#				#                           print(tree.pretty_tree())
#								chunkPalette.append(tree)
#							except nbt.MalformedFileError:
#								break
#						data = entry.value[3:end]
#						usedId = set()
#						for index in range(0,end,4):
#							value = int.from_bytes(data[index:index+3], byteorder="big")
#							for blockId in range(0,32, chunkPalFormat[1]):
#								blockVal = (value >> blockId) & ((1<<chunkPalFormat[1])-1)
#				#                           print(blockId, blockVal, chunkPalette[blockVal]["name"])
#						usedId.add(blockVal)
#						if len(usedId) > len(chunkPalette):
#							print(key, len(entry.value), pal, chunkPalFormat, end+7)
#							print(usedId, len(chunkPalette), int.from_bytes(entry.value[end+3:end+7], "little"))
		if args.compact:
			db.compactRange(None,0,None,0)
	if args.findSpawners:
		findSpawners(spawners, args.nbProcess)
Esempio n. 12
0
def render_topographic_chunk_file((chunk_file, map_size, render_options)):
    _render_topographic_chunk(nbt.NBTFile(chunk_file, 'rb'), map_size, render_options)
Esempio n. 13
0
def render_oblique_chunk((chunk_file, map_size, render_options)):
    _render_oblique_chunk(nbt.NBTFile(chunk_file, 'rb'), map_size, render_options)
Esempio n. 14
0
def render_overhead_chunk_file((chunk_file, map_size, render_options)):
    _render_overhead_chunk(nbt.NBTFile(chunk_file, 'rb'), map_size, render_options)
Esempio n. 15
0
#!/usr/bin/python
import numpy
import nbt

blocks = numpy.fromstring(nbt.NBTFile('/home/aheadley/.minecraft/saves/World1/0/0/c.0.0.dat','rb')['Level']['Blocks'].value, dtype=numpy.uint8).reshape(16,16,128)

print blocks
Esempio n. 16
0
import nbt
import sys

if __name__ == '__main__':

    with open(sys.argv[1], 'rb') as fd:
        tree = nbt.NBTFile(buffer=fd)
        print(tree.pretty_tree())
        x, y, z = tree['size']
        blocks, logged = tree['structure']['block_indices']

        i = 0
        blockPalette = tree['structure']['palette']['default']['block_palette']
        for xx in range(int(x)):
            for yy in range(int(y)):
                for zz in range(int(z)):
                    print("x : %d, y:%s, z:%s -> %s" %
                          (xx, yy, zz, blockPalette[int(blocks[i])]))
                    i += 1
Esempio n. 17
0
import nbt
import array

#Loads the map.dat file, which must be numbered 777 and in the python main directory
mappath = raw_input(
    "Please type the full filename path of the map.dat file you wish to convert\n"
)
mapfile = nbt.NBTFile(mappath, 'rb')
schematicpath = raw_input(
    "\nPlease type the full filename path of the schematic file you wish to create\nThe file name must end in \".schematic\"\nSaving directly to the C drive requires administrator privileges\n"
)
print

blocksBytes = mapfile['data']['colors'].value
tempcolors = [0] * 16384
tempcolors = [i for i in blocksBytes]

#maximum amount the schematic will vertically rise from the starting level
maxup = 0
#max amount the schematic will vertically decline from the starting level
maxdown = 0
#maps the relative height of each (x, y) position, but takes m(x, y) as an input
height = [0] * (128 * 128)
edgeheight = [0] * 128

#blockid[map color index number] = block id number
blockid = [
    7, 7, 7, 7, 2, 2, 2, 2, 88, 88, 88, 88, 13, 13, 13, 13, 46, 46, 46, 46,
    174, 174, 174, 174, 101, 101, 101, 101, 116, 116, 116, 116, 80, 80, 80, 80,
    82, 82, 82, 82, 3, 3, 3, 3, 4, 4, 4, 4, 9, 9, 9, 9, 5, 5, 5, 5, 35, 35, 35,
    35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35,
Esempio n. 18
0
 def getLevelInfo(self, worldName=False):
     """ Return an NBT object of the world's level.dat. """
     if not worldName: worldName = self.wrapper.server.worldName
     if not worldName: raise Exception("Server Uninitiated")
     f = nbt.NBTFile("%s/level.dat" % worldName, "rb")
     return f["Data"]