def saveFile(fName, data, savePolicy): if fName is None: return if os.path.exists(fName): r = ask("File already exists.\nClick 'OK' to choose one.") if r == 'OK': folder, name = os.path.split(fName) suffix = os.path.splitext(name)[-1][1:] fName = mcplatform.askSaveFile(folder, "Choose a NBT file...", name, 'Folder\0*.dat\0*.*\0\0', suffix) else: return if savePolicy == -1: if hasattr(data, 'name'): data.name = "" if not os.path.isdir(fName): if savePolicy <= 0: data.save(fName) elif savePolicy == 1: with littleEndianNBT(): toSave = data.save(compressed=False) toSave = struct.Struct('<i').pack(4) + struct.Struct( '<i').pack(len(toSave)) + toSave with open(fName, 'w') as f: f.write(toSave) else: alert("The selected object is not a file.\nCan't save it.")
def saveFile(fName, data, savePolicy): if fName is None: return if os.path.exists(fName): r = ask("File already exists.\nClick 'OK' to choose one.") if r == 'OK': folder, name = os.path.split(fName) suffix = os.path.splitext(name)[-1][1:] fName = mcplatform.askSaveFile(folder, "Choose a NBT file...", name, 'Folder\0*.dat\0*.*\0\0', suffix) else: return if savePolicy == -1: if hasattr(data, 'name'): data.name = "" if not os.path.isdir(fName): if savePolicy <= 0: data.save(fName) elif savePolicy == 1: with littleEndianNBT(): toSave = data.save(compressed=False) toSave = struct.Struct('<i').pack(4) + struct.Struct('<i').pack(len(toSave)) + toSave with open(fName, 'w') as f: f.write(toSave) else: alert("The selected object is not a file.\nCan't save it.")
def generateArrows(level, box, options): arrows = options["Arrow Format"] fineX = float(options["Fine Tune X"]) fineY = float(options["Fine Tune Y"]) fineZ = float(options["Fine Tune Z"]) leftArrow = str(str(arrows.split("::")[0]).replace("%", colorCode)) rightArrow = str(str(arrows.split("::")[1]).replace("%", colorCode)) for x in xrange(box.minx, box.maxx): for y in xrange(box.miny, box.maxy): for z in xrange(box.minz, box.maxz): if level.blockAt(x, y, z) == ARROWBLOCK: if level.blockAt(x, y+1, z) == SIGNBLOCK: tileEntity = level.tileEntityAt(x, y+1, z) if tileEntity["id"].value == "Sign": identifier = tileEntity["Text1"].value arrowType = tileEntity["Text2"].value value = str(float(x) + fineX) + ":" + str(float(y) + fineY) + ":" + str(float(z) + fineZ) + ":" + arrowType signIdentifierDICT[identifier] = value for identify in signIdentifierDICT.keys(): value = signIdentifierDICT[identify] data = value.split(":") x = data[0] y = data[1] z = data[2] arrowType = data[3] arrowName = "" if arrowType == "LEFT": arrowName = leftArrow elif arrowType == "RIGHT": arrowName = rightArrow testforCommand = "/testfor @e[x={},y={},z={},r=0,type=Slime]".format(str(round(float(x))), str(round(float(y))), str(round(float(z)))) summonCommand = "/summon Slime "+x+" "+y+" "+z+" {ActiveEffects:[{Id:14,Amplifier:-1,Duration:1000000000}],Riding:{id:WitherSkull,direction:[0.0,0.0,0.0],CustomName:"+arrowName+",CustomNameVisible:1b},PersistenceRequired:1b}" teleportCommand = "/tp @e[x={},y={},z={},r=0,type=WitherSkull] ~ ~-1000000 ~".format(str(round(float(x))), str(round(float(y))), str(round(float(z)))) schematic = arrowSchematic() TEL = schematic.root_tag["TileEntities"] TEL.append(CommandBlock(4,2,1,testforCommand)) TEL.append(CommandBlock(0,1,2,summonCommand)) TEL.append(CommandBlock(2,1,2,teleportCommand)) TEL.append(CommandBlock(4,1,0,"/setblock ~ ~ ~1 air")) TEL.append(CommandBlock(4,0,1,"/setblock ~ ~1 ~ redstone_block 0 destroy")) TEL.append(CommandBlock(4,1,2,"/testforblock ~ ~1 ~-1 command_block 0 {SuccessCount:0}")) schematicFile = mcplatform.askSaveFile(mcplatform.lastSchematicsDir or mcplatform.schematicsDir, "Save Schematic As...", "", "Schematic\0*.schematic\0\0", ".schematic") if schematicFile == None: print "ERROR: No schematic filename provided!" return schematic.saveToFile(schematicFile)
def perform(level, box, options): fname = askSaveFile(getDocumentsFolder(), 'Save to file...', 'biomes.txt', '*', '.txt') fout = open(fname, "w+") fout.write('x\ty\tbiomeID\n') for x in xrange(box.minx, box.maxx): chunkx = x // 16 for z in xrange(box.minz, box.maxz): chunkz = z // 16 biome = level.getChunk(chunkx, chunkz).Biomes[x % 15, z % 15] fout.write(str(x) + '\t' + str(z) + '\t' + str(biome) + '\n')
def perform(level, box, options): #level.markDirtyBox(box) Not needed method = "KingSupernova's ArmorStands" print '%s: Started at %s' % (method, time.ctime()) tags = ("Marker:1b,Invisible:1,Invulnerable:1,NoGravity:1," if options["Include Marker:1b,Invisible:1,Invulnerable:1,NoGravity:1"] else "") tags += options["Additional tags"] command_list = [] for (chunk, slices, point) in level.getChunkSlices(box): for e in chunk.TileEntities: x = e["x"].value y = e["y"].value z = e["z"].value if (x, y, z) in box: if e["id"].value == "Sign": if level.blockAt(x,y,z) == 68: data = level.blockDataAt(x,y,z) if data == 2: z += 1 elif data == 3: z += -1 elif data == 4: x += 1 elif data == 5: x += -1 try: name = json.loads(e["Text1"].value)["text"] + json.loads(e["Text2"].value)["text"] command = "/summon ArmorStand %s %s %s {CustomName:\"%s\",%s}" % (x,y,z, name, tags) print(command) for i in xrange(int(json.loads(e["Text4"].value)["text"])): command_list.append(command) except TypeError as error: print("Skipping sign at %s %s %s due to TypeError: %s" % (x,y,z, error)) schematic = MCSchematic((1,1,len(command_list)), mats = level.materials) for x_coord, command in enumerate(command_list): schematic.setBlockAt(0,0,x_coord,211) #211 is chain command block schematic.setBlockDataAt(0,0,x_coord,3) #3 = facing south schematic.TileEntities.append(cmdBlockTe(0,0,x_coord,command, not(options["Require redstone"]))) schematic_file = mcplatform.askSaveFile(mcplatform.lastSchematicsDir or mcplatform.schematicsDir, "Save Schematic As...", "", "Schematic\0*.schematic\0\0", ".schematic") if schematic_file == None: print "ERROR: No schematic filename provided!" return schematic.saveToFile(schematic_file) print '%s: Ended at %s' % (method, time.ctime())
def extractChunks(self): folder = mcplatform.askSaveFile(mcplatform.docsFolder, title='Export chunks to...', defaultName=self.editor.level.displayName + "_chunks", filetype='Folder\0*.*\0\0', suffix="", ) if not folder: return # TODO: We need a third dimension, Scotty! for cx, cz in self.selectedChunks(): if self.editor.level.containsChunk(cx, cz): self.editor.level.extractChunk(cx, cz, folder)
def extractChunks(self): folder = mcplatform.askSaveFile(directories.docsFolder, title='Export chunks to...', defaultName=self.editor.level.displayName + "_chunks", filetype='Folder\0*.*\0\0', suffix="", ) if not folder: return # TODO: We need a third dimension, Scotty! for cx, cz in self.selectedChunks(): if self.editor.level.containsChunk(cx, cz): self.editor.level.extractChunk(cx, cz, folder)
def _save_file(self): file_types = 'Custom File\0{}\0'.format(';'.join(self.file_types)) if not self.file_types[0].startswith("*"): name = self.file_types[0] else: name = self.file_types[0][1:] file_path = mcplatform.askSaveFile(".", "Save as...", name, file_types, self.file_types[0][1:]) if file_path: self._button.set_text(os.path.basename(file_path), True) self.file_path = file_path else: self._button.set_text('Save a file') self.file_path = None self._button.shrink_wrap() self.shrink_wrap()
def saveFile(fName, data, dontSaveRootTag): if os.path.exists(fName): r = ask("File already exists.\nClick 'OK' to choose one.") if r == 'OK': folder, name = os.path.split(fName) suffix = os.path.splitext(name)[-1][1:] fName = mcplatform.askSaveFile(folder, "Choose a NBT file...", name, 'Folder\0*.dat\0*.*\0\0', suffix) else: return if dontSaveRootTag: if hasattr(data, 'name'): data.name = "" if not os.path.isdir(fName): data.save(fName) else: alert("The selected object is not a file.\nCan't save it.")
def perform(level, box, options): op = options["Operation:"] cleartrack = options["Clear and prevent output tracking on import:"] reset = options["Reset Success Count on import:"] filterstr = options[ "Dump only commands containing: (\"None\" to dump all)"] filepath = options["File path:"] order = sorts[options["Sort command blocks by:"]] if op == "Dump Command Blocks": if filterstr == "None": filtercoms = False else: filtercoms = True commands = [] for (chunk, _, _) in level.getChunkSlices(box): for e in chunk.TileEntities: x = e["x"].value y = e["y"].value z = e["z"].value if (x, y, z) in box: if "CommandBlock" in e["id"].value: if "CustomName" in e: name = e["CustomName"].value.encode( "unicode-escape") else: name = "@" type = level.blockAt(x, y, z) direction = level.blockDataAt(x, y, z) if "powered" in e: powered = e["powered"].value else: powered = 0 if "auto" in e: auto = e["auto"].value else: auto = 0 if "conditionMet" in e: conditionMet = e["conditionMet"].value else: conditionMet = 0 if filtercoms: if e["Command"].value.find(filterstr) != -1: commands.append( ((x, y, z), type, direction, powered, auto, conditionMet, name, e["Command"].value.encode( "unicode-escape"))) else: commands.append( ((x, y, z), type, direction, powered, auto, conditionMet, name, e["Command"].value.encode("unicode-escape"))) if not commands: raise Exception( "ERROR: No command blocks exist within the selection!") commands.sort( key=lambda s: (s[0][order[0]], s[0][order[1]], s[0][order[2]])) outputlines = [] for (coords, type, direction, powered, auto, conditionMet, comname, command) in commands: outputlines.append( u"#%d,%d,%d|%d|%d|%d|%d|%d:%s\n" % (coords[0], coords[1], coords[2], type, direction, powered, auto, conditionMet, comname)) if "{" in command: mdatapos = command.find("{") outputlines.append(command[:mdatapos] + "\n") outputlines += strexplode(command[mdatapos:]) else: outputlines.append(str(command) + "\n") outputlines.append("\n") if filepath == "None": text_file = mcplatform.askSaveFile( mcplatform.lastSchematicsDir or mcplatform.schematicsDir, "Save Dumped Text File...", "", "Text File\0*.txt\0\0", ".txt") if text_file == None: print "ERROR: No filename provided!" return else: text_file = filepath file = open(text_file, "w") file.writelines(outputlines) file.close() else: if filepath == "None": text_file = mcplatform.askOpenFile( title="Select a Dumped Text File...", schematics=False) if text_file == None: print "ERROR: No filename provided!" return else: text_file = filepath file = open(text_file, 'rb') filearray = file.readlines() file.close() blocks = strcollapse(filearray) for idstr, command in blocks: precoordstr, name = idstr.split(":", 1) if "|" in precoordstr: coordstr, bdata = precoordstr.split("|", 1) else: coordstr = precoordstr bdata = None cx, cy, cz = coordstr.split(",") if bdata: parts = bdata.split("|") if len(parts) != 5: type = 137 direction = 0 powered = 0 auto = 0 conditionMet = 0 else: type = int(parts[0]) direction = int(parts[1]) powered = int(parts[2]) auto = int(parts[3]) conditionMet = int(parts[4]) else: type = 137 direction = 0 powered = 0 auto = 0 conditionMet = 0 cx = int(cx) cy = int(cy) cz = int(cz) level.setBlockAt(cx, cy, cz, type) level.setBlockDataAt(cx, cy, cz, direction) chunk = level.getChunk(cx >> 4, cz >> 4) ent = level.tileEntityAt(cx, cy, cz) if ent != None: if cleartrack: ent["TrackOutput"] = TAG_Byte(0) if "LastOutput" in ent: del ent["LastOutput"] if reset: ent["SuccessCount"] = TAG_Int(0) ent["powered"] = TAG_Byte(powered) ent["auto"] = TAG_Byte(auto) ent["conditionMet"] = TAG_Byte(conditionMet) ent["CustomName"] = TAG_String(name) ent["Command"] = TAG_String(command) chunk.dirty = True else: cmd = TAG_Compound() cmd["id"] = TAG_String("CommandBlock") cmd["x"] = TAG_Int(cx) cmd["y"] = TAG_Int(cy) cmd["z"] = TAG_Int(cz) if cleartrack: cmd["TrackOutput"] = TAG_Byte(0) cmd["powered"] = TAG_Byte(powered) cmd["auto"] = TAG_Byte(auto) cmd["conditionMet"] = TAG_Byte(conditionMet) cmd["CustomName"] = TAG_String(name) cmd["Command"] = TAG_String(command) chunk.TileEntities.remove(cmd) chunk.TileEntities.append(cmd) chunk.dirty = True
def perform(level, box, options): global search # Don't forget to 'globalize' these... global chunks global bbox global by bbox = box by = options["Match by:"] matchtype = options["Match block type (for TileEntity searches):"] matchblock = options["Match block:"] matchdata = options["Match block data:"] matchtile = options["Match tile entities (for Block searches):"] matchname = "" if options["Match Tag Name:"] == "None" else str( options["Match Tag Name:"]) matchval = "" if options["Match Tag Value:"] == "None" else str( options["Match Tag Value:"]) caseSensitive = not options["Case insensitive:"] matchtagtype = tagtypes.get(options["Match Tag Type:"], "Any") op = options["Operation:"] datas = [] if not caseSensitive: matchname = matchname.upper() matchval = matchval.upper() if matchtile and matchname == "" and matchval == "": alert( "\nInvalid Tag Name and Value; the present values will match every tag of the specified type." ) if search is None or op == trn._("Start New Search") or op == trn._( "Dump Found Coordinates"): search = [] if not search: if by == trn._("Block"): for x in range(box.minx, box.maxx): for z in range(box.minz, box.maxz): for y in range(box.miny, box.maxy): block = level.blockAt(x, y, z) data = level.blockDataAt(x, y, z) if block == matchblock.ID and ( not matchdata or data == matchblock.blockData): pass else: continue if matchtile: tile = level.tileEntityAt(x, y, z) if tile is not None: if not FindTag(tile, matchname, matchval, tagses[matchtagtype], caseSensitive): continue else: continue search.append((x, y, z)) datas.append(data) elif by == trn._("TileEntity"): chunks = [] for (chunk, slices, point) in level.getChunkSlices(box): for e in chunk.TileEntities: x = e["x"].value y = e["y"].value z = e["z"].value if (x, y, z) in box: if matchtype: block = level.blockAt(x, y, z) data = level.blockDataAt(x, y, z) if block == matchblock.ID and ( not matchdata or data == matchblock.blockData): pass else: continue if not FindTag(e, matchname, matchval, tagses[matchtagtype], caseSensitive): continue search.append((x, y, z)) datas.append(e) chunks.append([chunk, slices, point]) else: chunks = [] for (chunk, slices, point) in level.getChunkSlices(box): for e in chunk.Entities: x = e["Pos"][0].value y = e["Pos"][1].value z = e["Pos"][2].value if (x, y, z) in box: if FindTag(e, matchname, matchval, tagses[matchtagtype], caseSensitive): search.append((x, y, z)) datas.append(e) chunks.append([chunk, slices, point]) if not search: alert("\nNo matching blocks/tile entities found") else: search.sort() if op == trn._("Dump Found Coordinates"): result = "\n".join("%d, %d, %d" % pos for pos in search) answer = ask(result, height=editor.height, colLabel="Matching Coordinates", responses=["Save", "OK"]) if answer == "Save": fName = askSaveFile(getDocumentsFolder(), "Save to file...", "find.txt", 'TXT\0*.txt\0\0', 'txt') if fName: fData = "# MCEdit find output\n# Search options:\n# Match by: %s\n# Match block type: %s\n# Match block: %s\n# Match block data: %s\n# Match tile entities: %s\n# Match Tag Name:%s\n# Match Tag Value: %s\n# Case insensitive: %s\n# Match Tag Type: %s\n\n%s" % ( by, matchtype, matchblock, matchdata, matchtile, matchname, matchval, caseSensitive, matchtagtype, result) open(fName, 'w').write(fData) else: treeData = {} # To set tooltip text to the items the need it, use a dict: {"value": <item to be added to the tree>, "tooltipText": "Some text"} for i in range(len(search)): if by == trn._('Block'): treeData["%s" % (search[i], )] = { "value": datas[i], "tooltipText": "Double-click to go to this item." } elif by == trn._('Entity'): treeData["%s" % ( (datas[i]['Pos'][0].value, datas[i]['Pos'][1].value, datas[i]['Pos'][2].value), )] = { "value": datas[i], "tooltipText": "Double-click to go to this item." } else: treeData["%s" % ((datas[i]['x'].value, datas[i]['y'].value, datas[i]['z'].value), )] = { "value": datas[i], "tooltipText": "Double-click to go to this item." } inputs[1][1][1][1] = {'Data': treeData} options[""](inputs[1])
def perform(level, box, options): global search # Don't forget to 'globalize' these... global chunks global bbox global by bbox = box by = options["Match by:"] matchtype = options["Match block type (for TileEntity searches):"] matchblock = options["Match block:"] matchdata = options["Match block data:"] matchtile = options["Match tile entities (for Block searches):"] matchname = u"" if options["Match Tag Name:"] == "None" else unicode(options["Match Tag Name:"]) matchval = u"" if options["Match Tag Value:"] == "None" else unicode(options["Match Tag Value:"]) caseSensitive = not options["Case insensitive:"] matchtagtype = tagtypes.get(options["Match Tag Type:"], "Any") op = options["Operation:"] datas = [] if not caseSensitive: matchname = matchname.upper() matchval = matchval.upper() if matchtile and matchname == "" and matchval == "": alert("\nInvalid Tag Name and Value; the present values will match every tag of the specified type.") if search is None or op == trn._("Start New Search") or op == trn._("Dump Found Coordinates"): search = [] if not search: if by == trn._("Block"): for x in xrange(box.minx, box.maxx): for z in xrange(box.minz, box.maxz): for y in xrange(box.miny, box.maxy): block = level.blockAt(x, y, z) data = level.blockDataAt(x, y, z) if block == matchblock.ID and (not matchdata or data == matchblock.blockData): pass else: continue if matchtile: tile = level.tileEntityAt(x, y, z) if tile is not None: if not FindTag(tile, matchname, matchval, tagses[matchtagtype], caseSensitive): continue else: continue search.append((x, y, z)) datas.append(data) elif by == trn._("TileEntity"): chunks = [] for (chunk, slices, point) in level.getChunkSlices(box): for e in chunk.TileEntities: x = e["x"].value y = e["y"].value z = e["z"].value if (x, y, z) in box: if matchtype: block = level.blockAt(x, y, z) data = level.blockDataAt(x, y, z) if block == matchblock.ID and (not matchdata or data == matchblock.blockData): pass else: continue if not FindTag(e, matchname, matchval, tagses[matchtagtype], caseSensitive): continue search.append((x, y, z)) datas.append(e) chunks.append([chunk, slices, point]) else: chunks = [] for (chunk, slices, point) in level.getChunkSlices(box): for e in chunk.Entities: x = e["Pos"][0].value y = e["Pos"][1].value z = e["Pos"][2].value if (x, y, z) in box: if FindTag(e, matchname, matchval, tagses[matchtagtype], caseSensitive): search.append((x, y, z)) datas.append(e) chunks.append([chunk, slices, point]) if not search: alert("\nNo matching blocks/tile entities found") else: search.sort() if op == trn._("Dump Found Coordinates"): result = "\n".join("%d, %d, %d" % pos for pos in search) answer = ask(result, height=editor.height, colLabel="Matching Coordinates", responses=["Save", "OK"]) if answer == "Save": fName = askSaveFile(getDocumentsFolder(), "Save to file...", "find.txt", 'Folder\0*.dat\0*.*\0\0', 'txt') if fName: fData = "# MCEdit find output\n# Search options:\n# Match by: %s\n# Match block type: %s\n# Match block: %s\n# Match block data: %s\n# Match tile entities: %s\n# Match Tag Name:%s\n# Match Tag Value: %s\n# Case insensitive: %s\n# Match Tag Type: %s\n\n%s"%(by, matchtype, matchblock, matchdata, matchtile, matchname, matchval, caseSensitive, matchtagtype, result) open(fName, 'w').write(fData) else: treeData = {} # To set tooltip text to the items the need it, use a dict: {"value": <item to be added to the tree>, "tooltipText": "Some text"} for i in range(len(search)): if by == trn._('Block'): treeData[u"%s"%(search[i],)] = {"value": datas[i], "tooltipText": "Double-click to go to this item."} elif by == trn._('Entity'): treeData[u"%s"%((datas[i]['Pos'][0].value, datas[i]['Pos'][1].value, datas[i]['Pos'][2].value),)] = {"value": datas[i], "tooltipText": "Double-click to go to this item."} else: treeData[u"%s"%((datas[i]['x'].value, datas[i]['y'].value, datas[i]['z'].value),)] = {"value": datas[i], "tooltipText": "Double-click to go to this item."} inputs[1][1][1][1] = {'Data': treeData} options[""](inputs[1])
def perform(level, box, options): global tag tag = options["Area effect cloud tag"] or "cond" # the aec spawns pre = [] # the amount of conditionals conditional_count = 0 prefix = "" # the main commands cmds = [] if box.volume != 1: raise Exception("The box must only be 1x1x1!") # code below is based from MrGarretto # since the box is 1x1x1, this is all we need x, y, z = box.origin if level.blockAt(x, y, z) == 210 or level.blockAt(x, y, z) == 137: doneChain = 0 chX = x chY = y chZ = z whileIndex = 0 while (doneChain == 0): if (level.blockAt(chX, chY, chZ) == 210 and whileIndex == 0) or (level.blockAt(chX, chY, chZ) == 137 and whileIndex == 0) or level.blockAt(chX, chY, chZ) == 211: bX = chX bY = chY bZ = chZ if level.blockDataAt(chX, chY, chZ) == 0 or level.blockDataAt(chX, chY, chZ) == 8: chY -= 1 elif level.blockDataAt(chX, chY, chZ) == 1 or level.blockDataAt(chX, chY, chZ) == 9: chY += 1 elif level.blockDataAt(chX, chY, chZ) == 2 or level.blockDataAt(chX, chY, chZ) == 10: chZ -= 1 elif level.blockDataAt(chX, chY, chZ) == 3 or level.blockDataAt(chX, chY, chZ) == 11: chZ += 1 elif level.blockDataAt(chX, chY, chZ) == 4 or level.blockDataAt(chX, chY, chZ) == 12: chX -= 1 elif level.blockDataAt(chX, chY, chZ) == 5 or level.blockDataAt(chX, chY, chZ) == 13: chX += 1 # ignore impulse command blocks from conditional checks if level.blockDataAt(bX, bY, bZ) > 7 and level.blockAt(chX, chY, chZ) != 137: # check if there are is not an aec there, otherwise add it if len(pre) < 3: pre += addPre() conditional_count += 1 prefix = "" if conditional_count == 1: # add init command to the last command init_command = "execute @e[type=area_effect_cloud,tag=%s] ~ ~ ~ " % tag cmds[-1] = init_command + cmds[-1] prefix = "execute @e[type=area_effect_cloud,tag=%s,score_SuccessCount_min=1] ~ ~ ~ " % tag else: # reset the prefix and count of conditionals if more than one conditional_count = 0 prefix = "" command = level.tileEntityAt(bX, bY, bZ)["Command"].value # remove preceding slash if the command is non-blank if command: if command[0] == "/": command = command[1:] cmds.append(prefix + command) whileIndex += 1 else: doneChain = 1 # end code from MrGarretto # join the two lists together cmds = pre + cmds # convert to line by line commands = "\n".join(cmds) if options["Ask for file save"]: # Now save the file file_path = mcplatform.askSaveFile(".", "Save as...", tag, "*.mcfunction", "mcfunction") if file_path: with codecs.open(file_path, "w", "utf-8") as file: file.write(commands) # raise Exception to not save the world raise Exception("Saved file.\nPlease ensure that there is a SuccessCount dummy objective in the world if you're using conditional command blocks.\n\nThis is not an error.") else: print "#" * 74 print commands print "#" * 74 # raise Exception to not save the world raise Exception("Commands have been outputted to the console.\n\nThis is not an error.")
def perform(level, box, options): forward_offset = options['Forward offset'] right_offset = options['Right offset'] up_offset = options['Up offset'] relative_position = options['Relative position'] generate_surrounding_box = options['Generate surrounding box'] if generate_surrounding_box: forward_offset += 1 up_offset += 1 if relative_position == 'North': execution_center = ((box.minx + box.maxx) // 2 - right_offset, box.miny - up_offset + 2, box.maxz + forward_offset - 1) elif relative_position == 'East': execution_center = (box.minx - forward_offset, box.miny - up_offset + 2, (box.minz + box.maxz) // 2 - right_offset) elif relative_position == 'South': execution_center = ((box.minx + box.maxx) // 2 + right_offset, box.miny - up_offset + 2, box.minz - forward_offset) elif relative_position == 'West': execution_center = (box.maxx + forward_offset - 1, box.miny - up_offset + 2, (box.minz + box.maxz) // 2 + right_offset) include_air = options['Include air'] include_blocks = options['Include blocks'] include_null_block_data = options['Include null block data'] include_entities = options['Include entities'] include_commandblockoutput_command = options['Include "gamerule commandBlockOutput false" command'] include_logadmincommands_command = options['Include "gamerule logAdminCommands false" command'] add_initialization_commands = options['Add initialization commands'] add_finalization_commands = options['Add finalization commands'] block_to_enqueue_input = re.split(r'\s*,\s*', options['Blocks to enqueue'].strip()) blocks_to_enqueue = [] for block_id in xrange(0, len(materials.block_map) - 1): if materials.block_map[block_id] in block_to_enqueue_input: blocks_to_enqueue.append(block_id) nbt_tags_to_ignore = re.split(r'\s*,\s*', options['NBT tags to ignore']) + ['x', 'y', 'z'] save_command_to_file = options['Save the command to a file instead of to a Command Block'] ignore_maximum_command_block_command_length = options['Ignore maximum Command Block command length'] box_wall_material_block = options['Box wall material block'] box_wall_material_data = options['Box wall material data value'] box_floor_material_block = options['Box floor material block'] box_floor_material_data = options['Box floor material data value'] box_ceiling_material_block = options['Box ceiling material block'] box_ceiling_material_data = options['Box ceiling material data value'] add_box_signs = options['Add box signs'] add_credits = True command = 'summon minecraft:falling_block ~ ~1 ~ {id:"minecraft:falling_block",Block:"minecraft:redstone_block",Time:1,Passengers:[{id:"minecraft:falling_block",Block:"minecraft:activator_rail",Time:1,Passengers:[' unformatted_command = command first_element = True if include_commandblockoutput_command: command_part = '{id:"minecraft:commandblock_minecart",Command:"gamerule commandBlockOutput false"}' command += '\n\t' + command_part unformatted_command += command_part first_element = False if include_logadmincommands_command: if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"gamerule logAdminCommands false"}' command += '\n\t' + command_part unformatted_command += command_part if add_initialization_commands: file = mcplatform.askOpenFile('Select the text file containing the initialization commands...', False, ['txt']) if file is not None: input = open(file) if input is not None: for line in input.read().splitlines(): if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"' + escape_string(line) + '"}' command += '\n\t' + command_part unformatted_command += command_part input.close() if include_blocks: if include_air: air_blocks = [] for x in xrange(box.minx, box.maxx): air_blocks.append([]) for y in xrange(box.miny, box.maxy): air_blocks[x - box.minx].append([]) for z in xrange(box.minz, box.maxz): air_blocks[x - box.minx][y - box.miny].append(True) for cuboid in subdivide_in_cuboids(air_blocks, 32768, False, True, False): if not first_element: command += ',' unformatted_command += ',' first_element = False if volume(cuboid[0][0], cuboid[0][1], cuboid[0][2], cuboid[1][0], cuboid[1][1], cuboid[1][2]) == 1: command_part = '{id:"minecraft:commandblock_minecart",Command:"setblock ~' + str(cuboid[0][0] + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[0][2] + box.minz - execution_center[2]) + ' minecraft:air' else: command_part = '{id:"minecraft:commandblock_minecart",Command:"fill ~' + str(cuboid[0][0] + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[0][2] + box.minz - execution_center[2]) + ' ~' + str(cuboid[1][0] + box.minx - execution_center[0]) + ' ~' + str(cuboid[1][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[1][2] + box.minz - execution_center[2]) + ' minecraft:air' if include_null_block_data: command_part += ' 0' command_part += '"}' command += '\n\t' + command_part unformatted_command += command_part blocks = [] for x in xrange(box.minx, box.maxx): blocks.append([]) for y in xrange(box.miny, box.maxy): blocks[x - box.minx].append([]) for z in xrange(box.minz, box.maxz): blocks[x - box.minx][y - box.miny].append((level.blockAt(x, y, z), level.blockDataAt(x, y, z), level.tileEntityAt(x, y, z))) enqueued = [] for x in xrange(0, len(blocks)): for y in xrange(0, len(blocks[x])): for z in xrange(0, len(blocks[x][y])): block = blocks[x][y][z] if block[0] >= 1: for cuboid in subdivide_in_cuboids(blocks, 32768, False, block, (-1, 0, None)): if volume(cuboid[0][0], cuboid[0][1], cuboid[0][2], cuboid[1][0], cuboid[1][1], cuboid[1][2]) == 1: command_part = '{id:"minecraft:commandblock_minecart",Command:"setblock ~' + str(cuboid[0][0] + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[0][2] + box.minz - execution_center[2]) + ' ' + materials.block_map[block[0]] else: command_part = '{id:"minecraft:commandblock_minecart",Command:"fill ~' + str(cuboid[0][0] + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[0][2] + box.minz - execution_center[2]) + ' ~' + str(cuboid[1][0] + box.minx - execution_center[0]) + ' ~' + str(cuboid[1][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[1][2] + box.minz - execution_center[2]) + ' ' + materials.block_map[block[0]] if include_null_block_data or block[1] != 0 or (block[1] == 0 and block[2] is not None): command_part += ' ' + str(block[1]) if block[2] is not None: command_part += ' replace ' + escape_string(nbt_to_string(block[2], nbt_tags_to_ignore)) command_part += '"}' if block[0] not in blocks_to_enqueue: if not first_element: command += ',' unformatted_command += ',' first_element = False command += '\n\t' + command_part unformatted_command += command_part else: enqueued.append(command_part) for enqueued_command in enqueued: if not first_element: command += ',' unformatted_command += ',' first_element = False command += '\n\t' + enqueued_command unformatted_command += enqueued_command if include_entities: for (chunk, slices, point) in level.getChunkSlices(box): for entity in chunk.Entities: entity_x = entity['Pos'][0].value entity_y = entity['Pos'][1].value entity_z = entity['Pos'][2].value if (entity_x, entity_y, entity_z) in box: if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"summon ' + str(entity['id'].value) + ' ~' + str((Decimal(entity_x - execution_center[0]) - Decimal('0.5')).normalize()) + ' ~' + str((Decimal(entity_y - execution_center[1]) - Decimal('0.0625')).normalize()) + ' ~' + str((Decimal(entity_z - execution_center[2]) - Decimal('0.5')).normalize()) + ' ' + escape_string(nbt_to_string(entity, nbt_tags_to_ignore)) + '"}' command += '\n\t' + command_part unformatted_command += command_part if generate_surrounding_box: if volume(box.minx - 1, box.miny - 1, box.minz - 1, box.maxx, box.maxy, box.maxz) <= 32768: if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"fill ~' + str(box.minx - 1 - execution_center[0]) + ' ~' + str(box.miny - 1 - execution_center[1]) + ' ~' + str(box.minz - 1 - execution_center[2]) + ' ~' + str(box.maxx - execution_center[0]) + ' ~' + str(box.maxy - execution_center[1]) + ' ~' + str(box.maxz - execution_center[2]) + ' ' + escape_string(box_wall_material_block) + ' ' + str(box_wall_material_data) + ' outline"}' command += '\n\t' + command_part unformatted_command += command_part else: wall_blocks = [] for x in xrange(0, box.maxx - box.minx + 2): wall_blocks.append([]) for y in xrange(0, box.maxy - box.miny): wall_blocks[x].append([]) for z in xrange(0, box.maxz - box.minz + 2): if x == 0 or x == box.maxx - box.minx + 1 or z == 0 or z == box.maxz - box.minz + 1: wall_blocks[x][y].append(True) else: wall_blocks[x][y].append(False) for cuboid in subdivide_in_cuboids(wall_blocks, 32768, False, True, False): if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"fill ~' + str(cuboid[0][0] - 1 + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[0][2] - 1 + box.minz - execution_center[2]) + ' ~' + str(cuboid[1][0] - 1 + box.minx - execution_center[0]) + ' ~' + str(cuboid[1][1] + box.miny - execution_center[1]) + ' ~' + str(cuboid[1][2] - 1 + box.minz - execution_center[2]) + ' ' + escape_string(box_wall_material_block) if include_null_block_data or box_wall_material_data != 0: command_part += ' ' + str(box_wall_material_data) command_part += '"}' command += '\n\t' + command_part unformatted_command += command_part if add_box_signs: file = mcplatform.askOpenFile('Select the text file containing the signs to put on front of the box...', False, ['txt']) if file is not None: input = open(file) if input is not None: signs = OrderedDict() signs_line = 0 coordinate = (0, 0) for line in input.read().splitlines(): if signs_line == 0: if line != '': coordinates = re.split(r'\s*,\s*', line.strip()) coordinate = (int(coordinates[0]), int(coordinates[1])) signs[coordinate] = [] signs_line += 1 else: signs[coordinate].append(line) signs_line += 1 if signs_line == 9: signs_line = 0 for coordinate, sign in signs.items(): if relative_position == 'North': world_coordinate = (box.minx - 1 + coordinate[0] - execution_center[0], box.miny - 1 + coordinate[1] - execution_center[1], box.maxz + 1 - execution_center[2]) sign_data = 3 elif relative_position == 'East': world_coordinate = (box.minx - 2 - execution_center[0], box.miny - 1 + coordinate[1] - execution_center[1], box.minz - 1 + coordinate[0] - execution_center[2]) sign_data = 4 elif relative_position == 'South': world_coordinate = (box.maxx - coordinate[0] - execution_center[0], box.miny - 1 + coordinate[1] - execution_center[1], box.minz - 2 - execution_center[2]) sign_data = 2 else: world_coordinate = (box.maxx + 1 - execution_center[0], box.miny - 1 + coordinate[1] - execution_center[1], box.maxz - coordinate[0] - execution_center[2]) sign_data = 5 if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"setblock ~' + str(world_coordinate[0]) + ' ~' + str(world_coordinate[1]) + ' ~' + str(world_coordinate[2]) + ' minecraft:wall_sign ' + str(sign_data) + ' replace {' for i in xrange(0, min(4, len(sign))): sign_text = sign[i] sign_command = sign[i + 4] if len(sign) > i + 4 and len(sign[i + 4]) > 0 else '' if i > 0: command_part += ',' command_part += 'Text' + str(i + 1) + r':\"' if sign_text.startswith('{'): if sign_command != '': command_part += escape_string(escape_string('{"text":"","extra":[' + sign_text + ']')) else: command_part += escape_string(escape_string(sign_text)) elif sign_text.startswith('['): if sign_command != '': command_part += escape_string(escape_string('{"text":"","extra":' + sign_text)) else: command_part += escape_string(escape_string(sign_text)) elif sign_text.startswith('"'): if sign_command != '': command_part += escape_string(escape_string('{"text":' + sign_text)) else: command_part += escape_string(escape_string(sign_text)) else: if sign_command != '': command_part += escape_string(escape_string('{"text":"' + escape_string(sign_text) + '"')) else: command_part += escape_string(escape_string('"' + sign_text + '"')) if sign_command != '': command_part += escape_string(escape_string(',"clickEvent":{"action":"run_command","value":"' + escape_string(sign_command) + '"}}')) command_part += r'\"' command_part += '}"}' command += '\n\t' + command_part unformatted_command += command_part floor_ceiling_blocks = [] for x in xrange(0, box.maxx - box.minx + 2): floor_ceiling_blocks.append([]) floor_ceiling_blocks[x].append([]) for z in xrange(0, box.maxz - box.minz + 2): floor_ceiling_blocks[x][0].append(True) for cuboid in subdivide_in_cuboids(floor_ceiling_blocks, 32768, False, True, False): if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"fill ~' + str(cuboid[0][0] - 1 + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] - 1 + box.miny - execution_center[1]) + ' ~' + str(cuboid[0][2] - 1 + box.minz - execution_center[2]) + ' ~' + str(cuboid[1][0] - 1 + box.minx - execution_center[0]) + ' ~' + str(cuboid[1][1] - 1 + box.miny - execution_center[1]) + ' ~' + str(cuboid[1][2] - 1 + box.minz - execution_center[2]) + ' ' + escape_string(box_floor_material_block) if include_null_block_data or box_floor_material_data != 0: command_part += ' ' + str(box_floor_material_data) command_part += '"}' command += '\n\t' + command_part unformatted_command += command_part command_part = '{id:"minecraft:commandblock_minecart",Command:"fill ~' + str(cuboid[0][0] - 1 + box.minx - execution_center[0]) + ' ~' + str(cuboid[0][1] + box.maxy - execution_center[1]) + ' ~' + str(cuboid[0][2] - 1 + box.minz - execution_center[2]) + ' ~' + str(cuboid[1][0] - 1 + box.minx - execution_center[0]) + ' ~' + str(cuboid[1][1] + box.maxy - execution_center[1]) + ' ~' + str(cuboid[1][2] - 1 + box.minz - execution_center[2]) + ' ' + escape_string(box_ceiling_material_block) if include_null_block_data or box_ceiling_material_data != 0: command_part += ' ' + str(box_ceiling_material_data) command_part += '"}' command += ',\n\t' + command_part unformatted_command += ',' + command_part if add_finalization_commands: file = mcplatform.askOpenFile('Select the text file containing the finalization commands...', False, ['txt']) if file is not None: input = open(file) if input is not None: for line in input.read().splitlines(): if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"' + escape_string(line) + '"}' command += '\n\t' + command_part unformatted_command += command_part input.close() if add_credits: if not first_element: command += ',' unformatted_command += ',' first_element = False command_part = '{id:"minecraft:commandblock_minecart",Command:"' + escape_string('tellraw @p {"color":"yellow","text":"Generated with Mamo\'s ","extra":[{"color":"blue","underlined":true,"text":"Structure spawner generator","clickEvent":{"action":"open_url","value":"https://github.com/xMamo/Structure-spawner-generator"},"hoverEvent":{"action":"show_text","value":"Click here if you want this filter too!"}},"."]}') + '"}' command += '\n\t' + command_part unformatted_command += command_part if not first_element: command += ',' unformatted_command += ',' command_part = r'{id:"minecraft:commandblock_minecart",Command:"setblock ~ ~1 ~ minecraft:command_block 0 replace {auto:1b,Command:\"fill ~ ~-3 ~ ~ ~ ~ minecraft:air' if include_null_block_data: command_part += ' 0' command_part += r'\"}"}' command += '\n\t' + command_part unformatted_command += command_part command_part = '{id:"minecraft:commandblock_minecart",Command:"kill @e[type=minecraft:commandblock_minecart,r=0]"}' command += ",\n\t" + command_part + '\n]}]}' unformatted_command += "," + command_part + ']}]}' if not ignore_maximum_command_block_command_length and len(unformatted_command) > 32500: editor.Notify('Unfortunately no command could be generated, as it would be longer than the Command Block command length limit of 32500 characters.') return command_output = None if save_command_to_file: output_file = mcplatform.askSaveFile(None, 'Select the text file to which you want to save the command...', 'command.txt', 'Text file (*.txt)\0*.txt\0\0', None) if output_file is not None: command_output = open(output_file, mode = 'w') if save_command_to_file and command_output is not None: command_output.write((command + '\n').encode('UTF-8')) command_output.flush() command_output.close() else: schematic = MCSchematic((1, 1, 1), None, None, level.materials) schematic.setBlockAt(0, 0, 0, 137) command_block = TAG_Compound() command_block['id'] = TAG_String('minecraft:command_block') command_block['x'] = TAG_Int(0) command_block['y'] = TAG_Int(0) command_block['z'] = TAG_Int(0) command_block['Command'] = TAG_String(unformatted_command) schematic.addTileEntity(command_block) editor.addCopiedSchematic(schematic)