def export_raids_dat() -> None: raidsJson: dict = {} nbt = nbtlib.load(os.path.join(Config.WORLD_DATA_DIR, 'raids.dat')) raidsJson['overworld'] = nbt[""] nbt = nbtlib.load(os.path.join(Config.NETHER_DATA_DIR, 'raids_nether.dat')) raidsJson['nether'] = nbt[""] nbt = nbtlib.load(os.path.join(Config.END_DATA_DIR, 'raids_end.dat')) raidsJson['end'] = nbt[""] with open(os.path.join(Config.OUTPUT_DIR, 'raids.json'), 'w') as f: f.write(json.dumps(raidsJson))
def export_villages_dat() -> None: villagesJson: dict = {} nbt = nbtlib.load(os.path.join(Config.WORLD_DATA_DIR, 'villages.dat')) villagesJson['overworld'] = nbt[""] nbt = nbtlib.load( os.path.join(Config.WORLD_DATA_DIR, 'villages_nether.dat')) villagesJson['nether'] = nbt[""] nbt = nbtlib.load(os.path.join(Config.WORLD_DATA_DIR, 'villages_end.dat')) villagesJson['end'] = nbt[""] with open(os.path.join(Config.OUTPUT_DIR, 'villages.json'), 'w') as f: f.write(json.dumps(villagesJson))
async def resetspawn(self, ctx: commands.Context, node: str, server: str, username: str): await ctx.send("Resetting player " + username + " to spawn...") if node == "london": serverid = utils.londonids[server] elif node == "canada": serverid = utils.canadaids[server] elif node == "germany": serverid = utils.germanyids[server] uuid = utils.getUUID(username) if uuid: if not os.path.exists(uuid + ".dat"): url = serverid + "/world/playerdata/" + uuid + ".dat" print(("Downloading " + url + "...")) utils.download(url, uuid + ".dat", node) dir_path = os.getcwd() nbtfile = nbtlib.load(dir_path + "/" + uuid + ".dat") url = serverid + "/world/level.dat" print(("Downloading " + url + "...")) utils.download(url, "level.dat", node) worldfile = nbtlib.load(dir_path + "/" + "level.dat") xCoord = worldfile.root["Data"]["SpawnX"] yCoord = worldfile.root["Data"]["SpawnY"] zCoord = worldfile.root["Data"]["SpawnZ"] print( ("Resetting " + username + "\'s coordinates to " + str(xCoord) + "," + str(yCoord) + "," + str(zCoord) + "...")) await ctx.send("Original coords: " + str(nbtfile.root["Pos"][0]) + ", " + str(nbtfile.root["Pos"][1]) + ", " + str(nbtfile.root["Pos"][2]) + " in dim " + str(nbtfile.root["Dimension"])) nbtfile.root["Pos"][0] = Double(xCoord) nbtfile.root["Pos"][1] = Double(yCoord) nbtfile.root["Pos"][2] = Double(zCoord) nbtfile.root["Dimension"] = Int(0) nbtfile.save() await ctx.send("New coords: " + str(nbtfile.root["Pos"][0]) + ", " + str(nbtfile.root["Pos"][1]) + ", " + str(nbtfile.root["Pos"][2]) + " in dim " + str(nbtfile.root["Dimension"])) print("Uploading to server...") utils.upload(dir_path + "/" + uuid + ".dat", serverid + "/world/playerdata/" + uuid + ".dat", node) print("Uploaded!") os.unlink(dir_path + "/" + uuid + ".dat") os.unlink(dir_path + "/" + "level.dat") await ctx.send("Done!")
def save_chunk(self, chunk_position): x, y, z = chunk_position # try to load the chunk file # if it doesn't exist, create a new one chunk_path = self.chunk_position_to_path(chunk_position) try: chunk_data = nbt.load(chunk_path) except FileNotFoundError: chunk_data = nbt.File({"": nbt.Compound({"Level": nbt.Compound()})}) chunk_data["Level"]["xPos"] = x chunk_data["Level"]["zPos"] = z # fill the chunk file with the blocks from our chunk chunk_blocks = nbt.ByteArray([0] * (chunk.CHUNK_WIDTH * chunk.CHUNK_HEIGHT * chunk.CHUNK_LENGTH)) for x in range(chunk.CHUNK_WIDTH): for y in range(chunk.CHUNK_HEIGHT): for z in range(chunk.CHUNK_LENGTH): chunk_blocks[ x * chunk.CHUNK_LENGTH * chunk.CHUNK_HEIGHT + z * chunk.CHUNK_HEIGHT + y] = self.world.chunks[chunk_position].blocks[x][y][z] # save the chunk file chunk_data["Level"]["Blocks"] = chunk_blocks chunk_data.save(chunk_path, gzipped = True)
def load_structure_blocks(structurePaths, sizes, palette): schemX, schemY, schemZ = sizes structPaths = os.listdir(structurePaths) structures = [] for path in structPaths: structures.append(nbtlib.load(structurePaths + '/' + path)) outputArr = np.zeros((len(structures), schemX, schemY, schemZ)) for i in range(len(structures)): nbt_file = structures[i] nbt_data = nbt_file.root['blocks'] nbt_palette = nbt_file.root['palette'] converted_blocks = np.zeros((schemX, schemY, schemZ)) for block in nbt_data: converted_blocks[block['pos'][0], block['pos'][1], block['pos'][2]] = convert_palette( block['state'], nbt_palette, palette) f = open('palettes/globalPalette.txt', 'w+') print(palette) for element in palette: try: element['Properties'] except KeyError: prop = 'no properties' else: prop = str(element['Properties']) f.writelines(element['Name'] + ' ' + prop + '\n') outputArr[i] = converted_blocks return outputArr
def __init__(self, file): self.NBTfile = nbtlib.load(file, byteorder='little') self.blocks = list( map(int, self.NBTfile[""]["structure"]["block_indices"][0])) self.size = list(map(int, self.NBTfile[""]["size"])) self.palette = self.NBTfile[""]["structure"]["palette"]["default"][ "block_palette"] self.get_blockmap()
def save_temp_playerdata_json(uuid): filepath = os.path.join(Config.PLAYERDATA_DIR, "{}.dat".format(uuid)) nbt = nbtlib.load(filepath) jsnbt = json.dumps(nbt.root) with open( os.path.join(Config.TEMP_PLAYERDATA_JSON_DIR, "{}.json".format(uuid)), 'w') as f: f.write(jsnbt)
def set_item_ids(ldat_files, b, c): # Loop over all .dat files for datfile in ldat_files: # If it starts with "level" if datfile.startswith("level", 0, 5): # Load it and set the drive item IDs level_dat = nbtlib.load(datfile) set_cell_ids(level_dat, c) set_backpack_ids(level_dat, b)
def clearWorldPlayerData(serverName): serverWorld = serversPath + '\\' + serverName + '\\' + 'world' shutil.rmtree(serverWorld + '\\advancements') shutil.rmtree(serverWorld + '\\playerdata') shutil.rmtree(serverWorld + '\\stats') with nbtlib.load(serverWorld + '\\level.dat') as leveldat: try: del leveldat.root['Data']['Player'] except KeyError: pass
def player(self, uuid: str) -> nbtlib.Compound: """Load a player from `level.dat` or `playerdata` folder.""" dat = self.level_dat() sp_uuid = None if "Player" in dat.root["Data"]: sp_data = dat.root["Data"]["Player"] sp_uuid = parse_uuid(sp_data, "UUID") if uuid == str(sp_uuid): return dat.root["Data"]["Player"] return nbtlib.load(self._folder / "playerdata" / "{}.dat".format(uuid))
def load(filepath: str): """ Load a Minecraft schematic file. :param filepath: Path of the schematic. :return: None. """ file = nbtlib.load(filepath) for i in file['Schematic']['Blocks']: print(i, end=' ')
def get_score(objective): nbt_file = nbtlib.load(scoreboard_path) # load the nbt data root = nbt_file.root['data']['PlayerScores'] # get to the correct branch: data -> playerscores scoreboard = [] # create empty list to store data for i in root: if i['Objective'] == objective: # filter on a certain objective name = i['Name'] # get player name scoreboard.append([name, i['Score']]) # add list containing name & score to scoreboard return scoreboard
def get_single_score(objective, player): nbt_file = nbtlib.load(scoreboard_path) # load the nbt data root = nbt_file.root['data']['PlayerScores'] # get to the correct branch: data -> playerscores white_players = player_data.players('whitelist.json') # load a list of all whitelisted playes from uuid if player not in white_players: # check if player is whitelisted, if not break the operation return for i in root: # print(i) if i['Objective'] == objective: # filter on a certain objective name = i['Name'] if name == player: # search for the required player return i['Score'] # return the score
def datToPng(datfile, pngfile): nbt_file = nbtlib.load(datfile) im = Image.new("RGBA", (128, 128), "white") pix = im.load() for h in range(128): for w in range(128): color_id = nbt_file.get("", nbt_file)["data"]["colors"][w + h * 128] pix[(w, h)] = getColor(color_id) im.save(pngfile, "PNG")
def getday() -> int: """Get how many days the server has been running since its establishment. Returns: `int`: Integer number of days, or `-1` if an error occurs """ try: if config.nbt_mode: return int(nbtlib.load(config.nbt_file)['Data']['Time'] / 1728000) return (datetime.now() - datetime.strptime(config.start_date, '%Y-%m-%d')).days except: print_exc() return -1
def send_nbt_to_server( self, load_coord: (int, int, int), load_file: str, block_priority=[], place_block_priority_first=True, ): """ blocks json has the following format: [{"type": int, "position": {"x": int, "y": int, "z": int}, "orientation": int}, ...] """ nbt_struct = nbtlib.load(load_file) nbt_blocks = nbt_struct.root["blocks"] nbt_palette = nbt_struct.root["palette"] blockname_to_blockid(nbt_palette[int(nbt_blocks[0]["state"])]["Name"]) sx, sy, sz = load_coord block_list = [ Block( position=Point( x=int(b["pos"][0]) + sx, y=int(b["pos"][1]) + sy, z=int(b["pos"][2]) + sz, ), type=blockname_to_blockid(nbt_palette[int( b["state"])]["Name"]), orientation=dig_direction_from_facing_entry(nbt_palette[int( b["state"])]), ) for b in nbt_blocks ] if len(block_priority) > 0: unique_block_types = set([b.type for b in block_list]) block_priority = [ b for b in block_priority if b in unique_block_types ] for b in block_priority: unique_block_types.remove(b) unique_block_types = list(unique_block_types) if place_block_priority_first: for b in block_priority: unique_block_types.insert(0, b) else: for b in block_priority: unique_block_types.append(b) block_list = sorted(block_list, key=lambda x: unique_block_types.index(x.type)) response = self._client.spawnBlocks(Blocks(blocks=block_list)) return response
def extract_nbt_blocks(load_file): nbt_struct = nbtlib.load(load_file) nbt_blocks = nbt_struct.root["blocks"] nbt_palette = nbt_struct.root["palette"] block_data = dict() for b in nbt_blocks: type_name = nbt_palette[b['state']]['Name'].replace('minecraft:', "") if type_name != 'air': if type_name not in block_data: block_data[type_name] = [b['pos']] else: block_data[type_name].append(b['pos']) ordered_points.append(tuple(b['pos'])) return block_data, nbt_struct
def fill_palette(structurePaths): structPaths = os.listdir(structurePaths) structures = [] localPalette = [] for path in structPaths: structures.append(nbtlib.load(structurePaths + '/' + path)) for structure in range(len(structures)): nbt_file = structures[structure] nbt_palette = nbt_file.root['palette'] #print(nbt_file) for key in nbt_palette: if key not in localPalette: localPalette.append(key) return localPalette
def generate(path): commands = { "start": "scoreboard players set @s bb.success 1", "block": "execute as @s[scores={bb.success=1}] store success score @s bb.success if block ~<x> ~<y> ~<z> <block>", "end": "execute as @s[scores={bb.success=1}] run tag @s add <tag>" } file_list = [ join(directory, file) for (directory, _, files) in walk(path) if (len(files) > 0) for file in files if (file.endswith(".nbt") and isfile(join(directory, file))) ] for file in file_list: out = open( check_path( file.replace(path, "./output").replace(".nbt", ".mcfunction")), "w") f = nbtlib.load(file) data = convert(f) palette = [x["Name"] + block_state(x) for x in data[""]["palette"]] blocks = data[""]["blocks"] out.write(commands['start'] + "\n") for block in blocks: nbt_state = nbt(block) line = commands['block'] + "\n" line = line.replace("<x>", str(block["pos"][0])).replace( "<y>", str(block["pos"][1])).replace("<z>", str( block["pos"][2])).replace( "<block>", str(palette[block["state"]]) + nbt_state) out.write(line) out.write(commands['end'].replace( "<tag>", file.replace(path, "").replace(".nbt", "").replace( "\\", ".").replace("/", ".")[1:]) + "\n") out.close() print("Generated: " + file)
def load(file): world = nbtlib.load( f'{os.path.dirname(os.path.abspath(__file__))}//maps/{file}') root = world.get("ClassicWorld") data = bytearray(root.get("BlockArray")) #size x = root.get('X') y = root.get('Y') z = root.get('Z') #spawn spawn = root.get("Spawn") spawnx = spawn.get("X") spawny = spawn.get("Y") spawnz = spawn.get("Z") spawnh = spawn.get("H") spawnp = spawn.get("P") volume = x * y * z return data, x, y, z, spawnx * 32, spawny * 32, spawnz * 32, spawnh, spawnp, volume
async def resetcoords(self, ctx: commands.Context, node: str, server: str, player: str, x: int, y: int, z: int, dim: int): """Reset a player's coords""" await ctx.send("Resetting player " + player + " to coords: " + str(x) + ", " + str(y) + ", " + str(z) + " " + "in dimension " + str(dim) + "...") if node == "london": serverid = utils.londonids[server] elif node == "canada": serverid = utils.canadaids[server] elif node == "germany": serverid = utils.germanyids[server] uuid = utils.getUUID(player) if uuid: url = serverid + "/world/playerdata/" + uuid + ".dat" print("Downloading " + url + "...") utils.download(url, uuid + ".dat", node) dir_path = cwd = os.getcwd() nbtfile = nbtlib.load(dir_path + "/" + uuid + ".dat") print("Resetting " + player + "\'s coordinates to " + str(x) + "," + str(y) + "," + str(z) + "...") await ctx.send("Original coords: " + str(nbtfile.root["Pos"][0]) + ", " + str(nbtfile.root["Pos"][1]) + ", " + str(nbtfile.root["Pos"][2]) + " in dim " + str(nbtfile.root["Dimension"])) nbtfile.root["Pos"][0] = x nbtfile.root["Pos"][1] = y nbtfile.root["Pos"][2] = z nbtfile.root["Dimension"] = Int(dim) nbtfile.save() await ctx.send("New coords: " + str(nbtfile.root["Pos"][0]) + ", " + str(nbtfile.root["Pos"][1]) + ", " + str(nbtfile.root["Pos"][2]) + " in dim " + str(nbtfile.root["Dimension"])) print("Uploading to server...") utils.upload(dir_path + "/" + uuid + ".dat", serverid + "/world/playerdata/" + uuid + ".dat", node) print("Uploaded!") os.unlink(dir_path + "/" + uuid + ".dat") await ctx.send("Done!")
async def getschematic(self, ctx, schematicfile): await download_file(schematicfile.url, 'resources/test.schematic') nbt_file = nbtlib.load('resources/test.schematic') blocks = nbt_file['Schematic']['Blocks'] async with aiohttp.ClientSession() as session: async with session.get( 'https://minecraft-ids.grahamedgecombe.com/items.json' ) as r: if r.status == 200: sch = await r.json(content_type='text/plain') # really makes you think block_ids = [] block_counts = [] for x in set(blocks): block_ids.append(str(x).upper()) block_counts.append( str(blocks).replace("B; ", "").split(", ").count(str(x).upper())) block_counts, block_ids = zip( *sorted(zip(block_counts, block_ids), reverse=True)) output = "```\n" for i in range(0, len(block_ids)): b_name = "None" b_id_clean = int(re.sub("[^0-9]", "", block_ids[i])) item = next((item for item in sch if item['type'] == b_id_clean), None) if item is not None: b_name = item['name'] if b_name.lower() == "air": continue if '-' in block_ids[i]: b_name = "???" output += b_name.rjust(30, " ") + " " + str( block_counts[i]).ljust(2, " ") + "\n" await ctx.channel.send(output + "```")
def load_chunk(self, chunk_position): # load the chunk file chunk_path = self.chunk_position_to_path(chunk_position) try: chunk_blocks = nbt.load(chunk_path)["Level"]["Blocks"] except FileNotFoundError: return # create chunk and fill it with the blocks from our chunk file self.world.chunks[chunk_position] = chunk.Chunk(self.world, chunk_position) for x in range(chunk.CHUNK_WIDTH): for y in range(chunk.CHUNK_HEIGHT): for z in range(chunk.CHUNK_LENGTH): self.world.chunks[chunk_position].blocks[x][y][z] = chunk_blocks[ x * chunk.CHUNK_LENGTH * chunk.CHUNK_HEIGHT + z * chunk.CHUNK_HEIGHT + y]
def loadData(self): entries = os.listdir(PDATA_ROOT) for entry in entries: nbt_file = nbtlib.load(os.path.join(PDATA_ROOT, entry)).root["bukkit"] stats = dict() try: with open( os.path.join(STATS_ROOT, entry.split(".")[0] + ".json"), "r") as f: data = json.load(f) if "stats" in data.keys(): stats = data["stats"] except: print("file not exist") self.players.append({ "uuid": entry.split(".")[0], "firstPlayed": nbt_file["firstPlayed"] / 1000, "lastKnownName": nbt_file["lastKnownName"], "lastPlayed": nbt_file["lastPlayed"] / 1000, "stats": stats, })
import sys import nbtlib import json import numpy as np class NumpyEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() return json.JSONEncoder.default(self, obj) nbt_file = nbtlib.load(sys.argv[1]) dump = json.dumps(nbt_file, cls=NumpyEncoder) print(dump)
# data # |- nodes # |- ghost # | \ 'n78': { 'UUID': Int(-1), # 'elemCoordd': Int(0), # 'elemCoordx': Int(-107), # 'elemCoordy': Int(73), # 'elemCoordz': Int(233), # 'obserCoordd': Int(0), # 'obserCoordx': Int(-108), # 'obserCoordy': Int(73), # 'obserCoordz': Int(232)}, # \- dim: Int(0) # nbt_file = nbtlib.load('examples/electricalAgeWorld0.dat') #nbt_file = nbtlib.load('examples/eln.worldStorage0.dat') #print("loaded") #pprint(nbt_file.root["nodes"]) totalSixPop = 0 def parseRegSix(node): global totalSixPop # Each side has a EID<N>: short which is the code for the element type # If it is 0, the node is unpopulated. # If it exists, there is also an ED<N> that has the properties for it.
def bigtest(): return load('tests/nbt_files/bigtest.nbt')
(81, 81, 81), (54, 90, 108), (66, 110, 132), (76, 127, 153), (40, 67, 81), (90, 44, 126), (110, 54, 154), (127, 63, 178), (67, 33, 94), (36, 54, 126), (44, 66, 154), (51, 76, 178), (27, 40, 94), (72, 54, 36), (88, 66, 44), (102, 76, 51), (54, 40, 27), (72, 90, 36), (88, 110, 44), (102, 127, 51), (54, 67, 27), (108, 36, 36), (132, 44, 44), (153, 51, 51), (81, 27, 27), (18, 18, 18), (22, 22, 22), (25, 25, 25), (13, 13, 13), (176, 168, 54), (216, 205, 66), (250, 238, 77), (132, 126, 41), (65, 155, 150), (79, 189, 184), (92, 219, 213), (49, 116, 113), (52, 90, 180), (64, 110, 220), (74, 128, 255), (39, 68, 135), (0, 153, 41), (0, 187, 50), (0, 217, 58), (0, 115, 31), (91, 61, 35), (111, 74, 42), (129, 86, 49), (68, 46, 26), (79, 1, 0), (97, 2, 0), (112, 2, 0), (59, 1, 0)] pixels_arr = np.zeros((128, 128, 3), dtype=np.uint8) pixels = [] with nbtlib.load(input_file) as map: blocks = map.root['data']['colors'] for block in blocks: rgb = allcolors[int(block)] pixels.append(rgb) for i in range(128 * 128): pixels_arr[int(i / 128)][i % 128] = pixels[i] img = Image.fromarray(pixels_arr) img = img.resize((1280, 1280), Image.NEAREST) img.save(output_file)
import nbtlib from collections import namedtuple face = namedtuple("face", "A B C D") point = namedtuple("v", "X Y Z") nbtfile = nbtlib.load("skull_4.nbt").root palettes = nbtfile["palette"] blocks = nbtfile["blocks"] def create_palette(palette): #现在只是判断是不是空气。将要改掉。 if palette["Name"] == "minecraft:air": return [] else: return [ face(point(0, 0, 0), point(16, 0, 0), point(16, 16, 0), point(0, 16, 0)), face(point(0, 0, 16), point(16, 0, 16), point(16, 16, 16), point(0, 16, 16)), face(point(0, 0, 0), point(0, 16, 0), point(0, 16, 16), point(0, 0, 16)), face(point(16, 0, 0), point(16, 16, 0), point(16, 16, 16), point(16, 0, 16)), face(point(0, 0, 0), point(16, 0, 0), point(16, 0, 16), point(0, 0, 16)), face(point(0, 16, 0), point(16, 16, 0), point(16, 16, 16), point(0, 16, 16)) ] #一个立方体
def bigtest(): return load("tests/nbt_files/bigtest.nbt")