def tryImport_new(_root, name, org_lang, stock=False, subFolderString="", unicode_name=False, notify=True): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec (source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, 'displayName')): module.displayName = module_name # Python is awesome if not stock: # This work fine with custom filters, but the choice buttons are broken for the stock ones... if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, subFolderString[1:-1], module_name) if os.path.exists(trn_path): albow.translate.buildTranslation(config.settings.langCode.get(), extend=True, langPath=trn_path) # module.trn = albow.translate module.displayName = _(module.displayName) module.trn = albow.translate return module except Exception as e: traceback.print_exc() if notify: alert(_(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format(name, e)) return None
def tryImport_old(_root, name, org_lang, stock=False, subFolderString="", unicode_name=False): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec(source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, 'displayName')): module.displayName = module_name # Python is awesome if not stock: if "trn" in sys.modules.keys(): del sys.modules["trn"] if "albow.translate" in sys.modules.keys(): del sys.modules["albow.translate"] from albow import translate as trn if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, subFolderString[1:-1], module_name) module.trn = trn if os.path.exists(trn_path): module.trn.setLangPath(trn_path) module.trn.buildTranslation(config.settings.langCode.get()) n = module.displayName if hasattr(module, "trn"): n = module.trn._(module.displayName) if n == module.displayName: n = _(module.displayName) module.displayName = n import albow.translate albow.translate.lang = org_lang return module except Exception as e: traceback.print_exc() alert( _(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format(name, e)) return None
def tryImport(_root, name, stock=False, subFolderString="", unicode_name=False): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec(source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, 'displayName')): module.displayName = module_name # Python is awesome if not stock: # -- Note by Rubisk 20-06-2015: # I have no idea what this does, and left it as much alone as I could. # If anyone wants to explain it and/or modify this to work w/o modifying sys stuff, # that would be great. if "trn" in sys.modules.keys(): del sys.modules["trn"] if "albow.translate" in sys.modules.keys(): del sys.modules["albow.translate"] if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, module_name) module.trn = translate if os.path.exists(trn_path): module.trn.setLangPath(trn_path) module.trn.buildTranslation(config.settings.langCode.get()) n = module.displayName if hasattr(module, "trn"): n = module.trn._(module.displayName) if n == module.displayName: n = _(module.displayName) module.displayName = n return module except Exception as e: traceback.print_exc() alert( _(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format(name, e)) return None
def tryImport_old(_root, name, org_lang, stock=False, subFolderString="", unicode_name=False, notify=True): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec (source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, "displayName")): module.displayName = module_name # Python is awesome if not stock: if "trn" in sys.modules.keys(): del sys.modules["trn"] if "albow.translate" in sys.modules.keys(): del sys.modules["albow.translate"] from albow import translate as trn if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, subFolderString[1:-1], module_name) module.trn = trn if os.path.exists(trn_path): module.trn.setLangPath(trn_path) module.trn.buildTranslation(config.settings.langCode.get()) n = module.displayName if hasattr(module, "trn"): n = module.trn._(module.displayName) if n == module.displayName: n = _(module.displayName) module.displayName = n import albow.translate albow.translate.lang = org_lang return module except Exception as e: traceback.print_exc() if notify: alert( _(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format( name, e ) ) return None
def tryImport(_root, name, org_lang, stock=False, subFolderString="", unicode_name=False): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec (source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, 'displayName')): module.displayName = module_name # Python is awesome if not stock: #-# WIP. Following commented lines can be removed once we're sure we don't need them any more. # if "trn" in sys.modules.keys(): # del sys.modules["trn"] # if "albow.translate" in sys.modules.keys(): # del sys.modules["albow.translate"] # from albow import translate as trn if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, subFolderString[1:-1], module_name) # module.trn = trn if os.path.exists(trn_path): # module.trn.setLangPath(trn_path) # module.trn.buildTranslation(config.settings.langCode.get()) albow.translate.buildTranslation(config.settings.langCode.get(), extend=True, langPath=trn_path) # n = module.displayName # if hasattr(module, "trn"): # n = module.trn._(module.displayName) # if n == module.displayName: # n = _(module.displayName) # module.displayName = n module.displayName = _(module.displayName) # import albow.translate # albow.translate.lang = org_lang return module except Exception as e: traceback.print_exc() alert(_(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format(name, e)) return None
def updateFilters(self): totalFilters = 0 updatedFilters = 0 filtersDir = directories.getFiltersDir() try: os.mkdir(os.path.join(filtersDir, "updates")) except OSError: pass for module in self.filterModules.values(): totalFilters += 1 if hasattr(module, "UPDATE_URL") and hasattr(module, "VERSION"): if isinstance(module.UPDATE_URL, (str, unicode)) and isinstance(module.VERSION, (str, unicode)): # Pass on URL or network errors. # This is a basic error hadling, need more refinement to sort errors... update = True try: versionJSON = json.loads(urllib2.urlopen(module.UPDATE_URL).read()) except Exception, e: update = False log.warn(" Could not fetch source for %s. System said: %s" % (module.displayName, e)) if update and module.VERSION != versionJSON["Version"]: urllib.urlretrieve( versionJSON["Download-URL"], os.path.join(filtersDir, "updates", versionJSON["Name"]) ) updatedFilters += 1
def __init__(self, tool): Panel.__init__(self, name="Panel.FilterToolPanel") self.macro_steps = [] self.current_step = 0 self._filter_json = None self.keys_panel = None self.filterOptionsPanel = None self.filterSelect = ChoiceButton([], choose=self.filterChanged, doNotTranslate=True) self.binding_button = Button("", action=self.bind_key, tooltipText="Click to bind this filter to a key") self.filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255)) self.filterLabel.mouse_down = lambda x: mcplatform.platform_open(directories.getFiltersDir()) self.filterLabel.tooltipText = "Click to open filters folder" self.macro_button = Button("Record Macro", action=self.start_record_macro) self.filterSelectRow = Row((self.filterLabel, self.filterSelect, self.macro_button, self.binding_button)) self.confirmButton = Button("Filter", action=self.confirm) self._recording = False self._save_macro = False self.tool = tool self.selectedName = self.filter_json.get("Last Filter Opened", "") utils = FilterUtils( editor=tool.editor, materials=self.tool.editor.level.materials, custom_widget=tool.editor.addExternalWidget, resize_selection_box=tool.editor._resize_selection_box, ) utils_module = imp.new_module("filter_utils") utils_module = utils sys.modules["filter_utils"] = utils_module
def updateFilters(self): totalFilters = 0 updatedFilters = 0 filtersDir = directories.getFiltersDir() try: os.mkdir(os.path.join(filtersDir, "updates")) except OSError: pass for module in self.filterModules.values(): totalFilters += 1 if hasattr(module, "UPDATE_URL") and hasattr(module, "VERSION"): if isinstance(module.UPDATE_URL, (str, unicode)) and isinstance( module.VERSION, (str, unicode)): versionJSON = json.loads( urllib2.urlopen(module.UPDATE_URL).read()) if module.VERSION != versionJSON["Version"]: urllib.urlretrieve( versionJSON["Download-URL"], os.path.join(filtersDir, "updates", versionJSON["Name"])) updatedFilters += 1 for f in os.listdir(os.path.join(filtersDir, "updates")): shutil.copy(os.path.join(filtersDir, "updates", f), filtersDir) shutil.rmtree(os.path.join(filtersDir, "updates")) finishedUpdatingWidget = Widget() lbl = Label("Updated %s filter(s) out of %s" % (updatedFilters, totalFilters)) closeBTN = Button("Close this message", action=finishedUpdatingWidget.dismiss) col = Column((lbl, closeBTN)) finishedUpdatingWidget.bg_color = (0.0, 0.0, 0.6) finishedUpdatingWidget.add(col) finishedUpdatingWidget.shrink_wrap() finishedUpdatingWidget.present()
def __init__(self, tool): Panel.__init__(self) self.macro_steps = [] self.current_step = 0 self._filter_json = None self.keys_panel = None self.filterOptionsPanel = None self.filterSelect = ChoiceButton([], choose=self.filterChanged, doNotTranslate=True) self.binding_button = Button("", action=self.bind_key, tooltipText="Click to bind this filter to a key") self.filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255)) self.filterLabel.mouse_down = lambda x: mcplatform.platform_open(directories.getFiltersDir()) self.filterLabel.tooltipText = "Click to open filters folder" self.macro_button = Button("Record Macro", action=self.start_record_macro) self.filterSelectRow = Row((self.filterLabel, self.filterSelect, self.macro_button, self.binding_button)) self.confirmButton = Button("Filter", action=self.confirm) self._recording = False self._save_macro = False self.tool = tool self.selectedName = self.filter_json.get("Last Filter Opened", "")
def __init__(self, tool): Panel.__init__(self) self.macro_steps = [] self.current_step = 0 self._filter_json = None self.keys_panel = None self.filterOptionsPanel = None self.filterSelect = ChoiceButton([], choose=self.filterChanged, doNotTranslate=True) self.binding_button = Button( "", action=self.bind_key, tooltipText="Click to bind this filter to a key") self.filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255)) self.filterLabel.mouse_down = lambda x: mcplatform.platform_open( directories.getFiltersDir()) self.filterLabel.tooltipText = "Click to open filters folder" self.macro_button = Button("Record Macro", action=self.start_record_macro) self.filterSelectRow = Row((self.filterLabel, self.filterSelect, self.macro_button, self.binding_button)) self.confirmButton = Button("Filter", action=self.confirm) self._recording = False self._save_macro = False self.tool = tool self.selectedName = self.filter_json.get("Last Filter Opened", "")
def updateFilters(self): totalFilters = 0 updatedFilters = 0 filtersDir = directories.getFiltersDir() try: os.mkdir(os.path.join(filtersDir, "updates")) except OSError: pass for module in self.filterModules.values(): totalFilters = totalFilters + 1 if hasattr(module, "UPDATE_URL") and hasattr(module, "VERSION"): if isinstance(module.UPDATE_URL, (str, unicode)) and isinstance(module.VERSION, (str, unicode)): versionJSON = json.loads(urllib2.urlopen(module.UPDATE_URL).read()) if module.VERSION != versionJSON["Version"]: urllib.urlretrieve(versionJSON["Download-URL"], os.path.join(filtersDir, "updates", versionJSON["Name"])) updatedFilters = updatedFilters + 1 for f in os.listdir(os.path.join(filtersDir ,"updates")): shutil.copy(os.path.join(filtersDir, "updates", f), filtersDir) shutil.rmtree(os.path.join(filtersDir, "updates")) self.finishedUpdatingWidget = Widget() lbl = Label("Updated " + str(updatedFilters) + " filter(s) out of " + str(totalFilters)) closeBTN = Button("Close this message", action=self.closeFinishedUpdatingWidget) col = Column((lbl, closeBTN)) self.finishedUpdatingWidget.bg_color = (0.0, 0.0, 0.6) self.finishedUpdatingWidget.add(col) self.finishedUpdatingWidget.shrink_wrap() self.finishedUpdatingWidget.present()
def reloadFilters(self): filterFiles = [] unicode_module_names = [] def searchForFiltersInDir(searchFolder, stock=False): for root, folders, files in os.walk(os.path.join(searchFolder), True): filter_dir = os.path.basename(root) if filter_dir.startswith('demo') or filter_dir.startswith('lib'): continue subFolderString = root.replace(searchFolder, "") if subFolderString.endswith(os.sep): subFolderString = subFolderString[:len(os.sep)] if subFolderString.startswith(os.sep): subFolderString = subFolderString[len(os.sep):] if len(subFolderString) > 0: subFolderString = "[" + subFolderString + "]" try: root = str(root) if root not in sys.path: sys.path.append(root) except UnicodeEncodeError: unicode_module_names.extend([filter_name for filter_name in files]) for possible_filter in files: if possible_filter.endswith(".py"): filterFiles.append((root, possible_filter, stock, subFolderString)) searchForFiltersInDir(directories.getFiltersDir(), False) searchForFiltersInDir(os.path.join(directories.getDataDir(), "stock-filters"), True) filterModules = [] # If the path has unicode chars, there's no way of knowing what order to add the # files to the sys.modules. To fix this, we keep trying to import until we import # fail to import all leftover files. shouldContinue = True while shouldContinue: shouldContinue = False for f in filterFiles: module = tryImport(f[0], f[1], f[2], f[3], f[1] in unicode_module_names) if module is None: continue filterModules.append(module) filterFiles.remove(f) shouldContinue |= True displayNames = [] for m in filterModules: while m.displayName in displayNames: m.displayName += "_" displayNames.append(m) filterModules = filter(lambda mod: hasattr(mod, "perform"), filterModules) self.filterModules = collections.OrderedDict(sorted( [(FilterTool.moduleDisplayName(x), x) for x in filterModules], key=lambda module_name: (module_name[0].lower(), module_name[1])))
def tryImport(_root, name, stock=False, subFolderString="", unicode_name=False): with open(os.path.join(_root, name)) as module_file: module_name = name.split(os.path.sep)[-1].replace(".py", "") try: if unicode_name: source_code = module_file.read() module = imp.new_module(module_name) exec (source_code, module.__dict__) if module_name not in sys.modules.keys(): sys.modules[module_name] = module else: module = imp.load_source(module_name, os.path.join(_root, name), module_file) module.foldersForDisplayName = subFolderString if not (hasattr(module, 'displayName')): module.displayName = module_name # Python is awesome if not stock: # -- Note by Rubisk 20-06-2015: # I have no idea what this does, and left it as much alone as I could. # If anyone wants to explain it and/or modify this to work w/o modifying sys stuff, # that would be great. if "trn" in sys.modules.keys(): del sys.modules["trn"] if "albow.translate" in sys.modules.keys(): del sys.modules["albow.translate"] if directories.getFiltersDir() in name: trn_path = os.path.split(name)[0] else: trn_path = directories.getFiltersDir() trn_path = os.path.join(trn_path, module_name) module.trn = translate if os.path.exists(trn_path): module.trn.setLangPath(trn_path) module.trn.buildTranslation(config.settings.langCode.get()) n = module.displayName if hasattr(module, "trn"): n = module.trn._(module.displayName) if n == module.displayName: n = _(module.displayName) module.displayName = n return module except Exception as e: traceback.print_exc() alert(_(u"Exception while importing filter module {}. " + u"See console for details.\n\n{}").format(name, e)) return None
def reload(self): for i in list(self.subwidgets): self.remove(i) tool = self.tool if len(tool.filterModules) is 0: self.add(Label("No filter modules found!")) self.shrink_wrap() return if self.selectedFilterName is None or self.selectedFilterName not in tool.filterNames: self.selectedFilterName = tool.filterNames[0] self.filterSelect = ChoiceButton(tool.filterNames, choose=self.filterChanged) self.filterSelect.selectedChoice = self.selectedFilterName filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255)) filterLabel.mouse_down = lambda x: mcplatform.platform_open(directories.getFiltersDir()) filterLabel.tooltipText = "Click to open filters folder" self.filterSelectRow = filterSelectRow = Row((filterLabel, self.filterSelect)) self.confirmButton = Button("Filter", action=self.tool.confirm) self.filterOptionsPanel = None while self.filterOptionsPanel is None: module = self.tool.filterModules[self.selectedFilterName] try: self.filterOptionsPanel = FilterModuleOptions(self.tool, module, _parent=self) except Exception, e: alert(_("Error creating filter inputs for {0}: {1}").format(module, e)) traceback.print_exc() self.tool.filterModules.pop(self.selectedFilterName) self.selectedFilterName = tool.filterNames[0] if len(tool.filterNames) == 0: raise ValueError("No filters loaded!")
def updateFilters(self): totalFilters = 0 updatedFilters = 0 filtersDir = directories.getFiltersDir() try: os.mkdir(os.path.join(filtersDir, "updates")) except OSError: pass for module in self.filterModules.values(): totalFilters += 1 if hasattr(module, "UPDATE_URL") and hasattr(module, "VERSION"): if isinstance(module.UPDATE_URL, (str, unicode)) and isinstance(module.VERSION, (str, unicode)): # Pass on URL or network errors. # This is a basic error hadling, need more refinement to sort errors... update = True try: versionJSON = json.loads(urllib2.urlopen(module.UPDATE_URL).read()) except Exception, e: update = False log.warn(" Could not fetch source for %s. System said: %s"%(module.displayName, e)) if update and module.VERSION != versionJSON["Version"]: urllib.urlretrieve(versionJSON["Download-URL"], os.path.join(filtersDir, "updates", versionJSON["Name"])) updatedFilters += 1
def __init__(self, tool): Panel.__init__(self, name='Panel.FilterToolPanel') self.macro_steps = [] self.current_step = 0 self._filter_json = None self.keys_panel = None self.filterOptionsPanel = None self.filterSelect = ChoiceButton([], choose=self.filterChanged, doNotTranslate=True) self.binding_button = Button("", action=self.bind_key, tooltipText="Click to bind this filter to a key") self.filterLabel = Label("Filter:", fg_color=(177, 177, 255, 255)) self.filterLabel.mouse_down = lambda x: mcplatform.platform_open(directories.getFiltersDir()) self.filterLabel.tooltipText = "Click to open filters folder" self.macro_button = Button("Record Macro", action=self.start_record_macro) self.filterSelectRow = Row((self.filterLabel, self.filterSelect, self.macro_button, self.binding_button)) self.confirmButton = Button("Filter", action=self.confirm) self._recording = False self._save_macro = False self.tool = tool self.selectedName = self.filter_json.get("Last Filter Opened", "") utils = FilterUtils( editor=tool.editor, materials=self.tool.editor.level.materials, custom_widget=tool.editor.addExternalWidget, resize_selection_box=tool.editor._resize_selection_box ) utils_module = imp.new_module("filter_utils") utils_module = utils sys.modules["filter_utils"] = utils_module
def reloadFilters(self): filterFiles = [] unicode_module_names = [] # Tracking stock and custom filters names in order to load correctly the translations. stock_filters = [] cust_filters = [] def searchForFiltersInDir(searchFolder, stock=False): for root, folders, files in os.walk(os.path.join(searchFolder), True): filter_dir = os.path.basename(root) if filter_dir.startswith('demo') or filter_dir.startswith('lib'): continue subFolderString = root.replace(searchFolder, "") if subFolderString.endswith(os.sep): subFolderString = subFolderString[:len(os.sep)] if subFolderString.startswith(os.sep): subFolderString = subFolderString[len(os.sep):] if len(subFolderString) > 0: subFolderString = "[" + subFolderString + "]" try: root = str(root) if root not in sys.path: sys.path.append(root) except UnicodeEncodeError: unicode_module_names.extend([filter_name for filter_name in files]) for possible_filter in files: if possible_filter.endswith(".py"): if stock: stock_filters.append(possible_filter) _stock = True else: cust_filters.append(possible_filter) _stock = False # Force the 'stock' parameter if the filter was found in the stock-filters directory if possible_filter in stock_filters: _stock = True filterFiles.append((root, possible_filter, _stock, subFolderString)) # Search first for the stock filters. searchForFiltersInDir(os.path.join(directories.getDataDir(), "stock-filters"), True) searchForFiltersInDir(directories.getFiltersDir(), False) filterModules = [] org_lang = albow.translate.lang # If the path has unicode chars, there's no way of knowing what order to add the # files to the sys.modules. To fix this, we keep trying to import until we import # fail to import all leftover files. shouldContinue = True while shouldContinue: shouldContinue = False for f in filterFiles: if f[1] in self.not_imported_filters: continue module = tryImport(f[0], f[1], org_lang, f[2], f[3], f[1] in unicode_module_names, notify=(not self.optionsPanel.notifications_disabled)) if module is None: self.not_imported_filters.append(f[1]) continue filterModules.append(module) filterFiles.remove(f) shouldContinue |= True displayNames = [] for m in filterModules: while m.displayName in displayNames: m.displayName += "_" displayNames.append(m) filterModules = filter(lambda mod: hasattr(mod, "perform"), filterModules) self.filterModules = collections.OrderedDict(sorted( [(FilterTool.moduleDisplayName(x), x) for x in filterModules], key=lambda module_name: (module_name[0].lower(), module_name[1])))
def perform(level, box, options): filterVersion = '#V1.2' breakForUpdate = False try: newFilter = urllib2.urlopen( 'https://raw.githubusercontent.com/gentlegiantJGC/MCEdit-Filters/master/Bedrock%20Edition%20Filters/bedrockFix.py' ).read() newVersion = newFilter.replace('\r', '').split('\n')[0] if filterVersion != newVersion: f = open('{}/bedrockFix.py'.format(directories.getFiltersDir()), 'w') f.write(newFilter) f.close() breakForUpdate = True except Exception as e: print 'error checking or updating filter : "{}"'.format(e) if breakForUpdate: raise Exception( 'Updated Filter To Version {}\nRestart Filter Tool To See Changes'. format(newVersion[1:])) logFile = '' def logFileFun(logFile, msg): print msg if logFile == '': return msg else: return '{}\n{}'.format(logFile, msg) if level.gamePlatform != 'PE': raise Exception('Must be a PE/Win10... world') try: f = open('{}/ggjgc.json'.format(directories.getFiltersDir()), 'r') licenses = json.load(f) f.close() except: licenses = {} if type(licenses) != dict: licenses = {} if 'bedrockFix' not in licenses: licenses['bedrockFix'] = False if not licenses['bedrockFix']: answer = None print lic answer = albow.ask( 'Please agree to the user agreement to use this filter (written at the start of the filter and printed in the console)', ['I Accept', 'Cancel'], default=0, cancel=1) if answer == 'I Accept': licenses['bedrockFix'] = True else: raise Exception( 'You need to agree to the user agreement to use this filter') f = open('{}/ggjgc.json'.format(directories.getFiltersDir()), 'w') f.write(json.dumps(licenses)) f.close() chestProb = [True] * options["Percentage of chests to populate"] + [ False ] * (100 - options["Percentage of chests to populate"]) blocksSupported = { 23: "Dispenser", 25: "Music", 26: "Bed", 29: "PistonArm", 33: "PistonArm", 52: "MobSpawner", 54: "Chest", 61: "Furnace", 62: "Furnace", 63: "Sign", 68: "Sign", 84: "Jukebox", 116: "EnchantTable", 117: "BrewingStand", 118: "Cauldron", 125: "Dropper", 137: "CommandBlock", 130: "EnderChest", 138: "Beacon", 140: "FlowerPot", 144: "Skull", 146: "Chest", 149: "Comparator", 150: "Comparator", 151: "DaylightDetector", 154: "Hopper", 176: "Banner", 177: "Banner", 178: "DaylightDetector", 188: "CommandBlock", 189: "CommandBlock", 199: "ItemFrame", 205: "ShulkerBox", 218: "ShulkerBox", 247: "NetherReactor", 252: "StructureBlock" } transparrent = [ 244, 199, 177, 176, 175, 148, 147, 143, 142, 141, 132, 131, 126, 115, 106, 105, 104, 83, 77, 76, 75, 72, 70, 69, 68, 66, 63, 59, 55, 51, 50, 40, 39, 38, 37, 32, 31, 30, 28, 27, 11, 10, 9, 8, 6, 0 ] for cx, cz in box.chunkPositions: try: chunk = level.getChunk(cx, cz) except: continue chunkBlockList = np.unique(chunk.Blocks) for block in chunkBlockList: if block not in blocksSupported: continue for coord in np.argwhere(chunk.Blocks == block): x, z, y = coord x += cx * 16 z += cz * 16 if (x, y, z) not in box: continue # get the tile entity te = level.tileEntityAt(x, y, z) createTileEntity = False if te is None: createTileEntity = True #create tile entitiy te = TAG_Compound() te['x'] = TAG_Int(x) te['y'] = TAG_Int(y) te['z'] = TAG_Int(z) if options["Log Errors"]: if 'id' in te: if te['id'].value != blocksSupported[block]: logFile = logFileFun( logFile, 'Block at {} is type "{}" but set as type "{}"' .format((x, y, z), blocksSupported[block], te['id'].value)) else: if createTileEntity: logFile = logFileFun( logFile, 'Block at {} is type "{}" but has no tile entity' .format((x, y, z), blocksSupported[block])) else: logFile = logFileFun( logFile, 'Block at {} is type "{}" but has no "id" key'. format((x, y, z), blocksSupported[block])) if blocksSupported[block] == 'Bed': if level.blockDataAt(x, y, z) == 0 and level.blockAt( x, y, z + 1) == 26 and level.blockDataAt( x, y, z + 1) == 8: pass elif level.blockDataAt(x, y, z) == 8 and level.blockAt( x, y, z - 1) == 26 and level.blockDataAt( x, y, z - 1) == 0: pass elif level.blockDataAt( x, y, z) == 10 and level.blockAt( x, y, z + 1) == 26 and level.blockDataAt( x, y, z + 1) == 2: pass elif level.blockDataAt(x, y, z) == 2 and level.blockAt( x, y, z - 1) == 26 and level.blockDataAt( x, y, z - 1) == 10: pass elif level.blockDataAt(x, y, z) == 3 and level.blockAt( x + 1, y, z) == 26 and level.blockDataAt( x + 1, y, z) == 11: pass elif level.blockDataAt( x, y, z) == 11 and level.blockAt( x - 1, y, z) == 26 and level.blockDataAt( x - 1, y, z) == 3: pass elif level.blockDataAt(x, y, z) == 9 and level.blockAt( x + 1, y, z) == 26 and level.blockDataAt( x + 1, y, z) == 1: pass elif level.blockDataAt(x, y, z) == 1 and level.blockAt( x - 1, y, z) == 26 and level.blockDataAt( x - 1, y, z) == 9: pass else: logFile = logFileFun( logFile, 'Block at {} is an invalid bed'.format( (x, y, z))) if options["Fix Errors"]: te['id'] = TAG_String(blocksSupported[block]) if blocksSupported[block] == "MobSpawner" and options[ "Spawner Entity"]: if 'EntityId' not in te or ('EntityId' in te and te['EntityId'].value == 1): te['EntityId'] = TAG_Int( random.choice([32, 33, 34, 35])) elif blocksSupported[block] == 'Chest': if 'Items' in te and len(te['Items']) > 0: pass elif 'LootTable' not in te and options[ "Chest Contents"] and random.choice(chestProb): te['LootTable'] = TAG_String( options["Chest Loot Table"]) elif blocksSupported[block] == 'ShulkerBox' and options[ "Fix undefined Shulker box rotation"]: if "facing" not in te: if level.blockAt(x, y + 1, z) in transparrent: te["facing"] = TAG_Byte(1) else: directions = [] if level.blockAt(x, y - 1, z) in transparrent: directions.append(0) if level.blockAt(x - 1, y, z) in transparrent: directions.append(4) if level.blockAt(x + 1, y, z) in transparrent: directions.append(5) if level.blockAt(x, y, z - 1) in transparrent: directions.append(2) if level.blockAt(x, y, z + 1) in transparrent: directions.append(3) if directions == []: te["facing"] = TAG_Byte(1) else: te["facing"] = TAG_Byte( random.choice(directions)) if createTileEntity: chunk.TileEntities.append(te) if options["Fix Errors"]: chunk.chunkChanged() if options["Log Errors"] and options["Log File"] is not None: f = open(options["Log File"], 'w') f.write(logFile) f.close() os.startfile(options["Log File"])
def perform(level, box, options): global colourpalletscan try: colourpalletscan except: colourpalletscan = [] if options["Mode"] == "3d Model to Schematic": filterDir = directories.getFiltersDir() kv6Path = '{}/poly2vox.exe'.format(filterDir) #checking all the required files exist and errors if they don't if not os.path.isdir(filterDir): print 'Filter Folder' print filterDir raise Exception( 'Hmm I expected a filter directory here: {}.\nIt seems you do not have a directory in that location' .format(filterDir)) if not os.path.isfile(kv6Path): print 'ploy2vox.exe Path' print kv6Path print 'The filters folder has been found but poly2vox cannot be found' raise Exception( 'poly2vox.exe should be found here: {}.'.format(kv6Path)) fileName = mcplatform.askOpenFile(title="Select the 3D Model", schematics=False) if fileName == None: raise Exception('No Model File Specified') model = fileName.split(os.sep)[-1] meshDir = os.sep.join(fileName.split(os.sep)[0:-1]) if model[-4:].lower() in [ '.obj', '.asc', '.3ds', '.md2', '.md3', '.stl' ]: shutil.copyfile(kv6Path, '{}/poly2vox.exe'.format(meshDir)) else: raise Exception('file format selected not supported') if options["3d import limits"] == "Default": argument = '{} kv6.kv6'.format(model) elif options["3d import limits"] == "Max dimension": argument = '{} kv6.kv6 /v{}'.format(model, int(options["Limit Value"])) elif options["3d import limits"] == "Scale Factor": argument = '{} kv6.kv6 /s{}'.format(model, options["Limit Value"]) defaultDir = os.getcwd() os.chdir(meshDir) #being super cautious here because I have changed the working directory which is probably a dirty thing #to do but textures won't get noticed if poly2vox is run from a different folder. It was either change the #working directory to keep everything together or put everything in the main mcedit directory which would #make a mess and be very difficult to clean up. If any step in the conversion process fails the working #directory needs to be changed back to default otherwise it will mess up MCedit and a restart of the program #would be required. print 'poly2vox {}'.format(argument) try: os.system('poly2vox {}'.format(argument)) except: os.chdir(defaultDir) raise Exception("Failure at Voxelization.") os.chdir(defaultDir) try: kv6 = binascii.hexlify( open('{}/kv6.kv6'.format(meshDir), "rb").read()) except: raise Exception("Failure to read kv6 file.") try: kv62sch(level, kv6, colourpalletscan) except: raise Exception("Failure to convert to schematic.") try: os.remove('{}/poly2vox.exe'.format(meshDir)) except: print 'Unable to remove poly2vox.exe in {}. You will have to have a look why it could not be removed'.format( meshDir) if not options["Leave kv6 (for debugging)"]: try: os.remove('{}/kv6.kv6'.format(meshDir)) except: print 'Unable to remove kv6.kv6 in {}. You will have to have a look why it could not be removed'.format( meshDir) raise Exception('Conversion Finished') if options["Mode"] == "kv6 To Schematic": fileName = mcplatform.askOpenFile(title="Select the kv6 file", schematics=False, suffixes=['kv6']) if fileName == None: raise Exception('No File Selected') kv6 = binascii.hexlify(open(fileName, "rb").read()) kv62sch(level, kv6, colourpalletscan) raise Exception('Conversion Finished') elif options["Mode"] == "Get Colour Pallet": from PIL import Image colourpalletscan = [] fileName = mcplatform.askOpenFile( title="Select an image within the folder", schematics=False) if fileName == None: raise Exception('No File Specified') filepath = os.sep.join(fileName.split(os.sep)[0:-1]) imgno = 0 imgcomp = Image.new('RGBA', (32, 16 * len(Name2ID))) for blockname in Name2ID: if os.path.isfile(filepath + os.sep + blockname + '.png'): img = Image.open(filepath + os.sep + blockname + '.png') (width, height) = img.size rtot = 0 gtot = 0 btot = 0 pixelcount = 0 for y in range(height): for x in range(width): if len(img.getpixel((x, y))) == 3: (r, g, b) = img.getpixel((x, y)) a = 255 elif len(img.getpixel((x, y))) == 4: (r, g, b, a) = img.getpixel((x, y)) else: raise exception( "soooo ... erm ... I don't quite know what this texture is" ) if a > 128: rtot += r gtot += g btot += b pixelcount += 1 ravg = rtot / pixelcount gavg = gtot / pixelcount bavg = btot / pixelcount idmg = Name2ID[blockname] imgcomp.paste(img, (0, 16 * imgno)) imgcomp.paste((ravg, gavg, bavg, 255), (16, 16 * imgno, 32, 16 * imgno + 16)) imgno += 1 print[ravg, gavg, bavg, idmg[0], idmg[1]] colourpalletscan.append([ravg, gavg, bavg, idmg[0], idmg[1]]) imgcomp.save(filepath + os.sep + 'imgcomp.png', 'PNG')
import json import directories blockToIntermediate = {} blockToIntermediate['PC'] = json.load(open(directories.getFiltersDir()+'/WorldConverter/blockMapping/java_intermediate.json')) blockToIntermediate['PE'] = {} # add json mappings here for the other versions blockFromIntermediate = {} blockFromIntermediate['PC'] = {} blockFromIntermediate['PE'] = json.load(open(directories.getFiltersDir()+'/WorldConverter/blockMapping/intermediate_bedrock.json')) # add json mappings here for the other versions def convertBlock(convertFrom, convertTo, blockID, blockData, nbtIn=None, fallBack = False): # check the conversion options are valid if convertFrom not in ['PC','PE'] or convertTo not in ['PC','PE']: raise Exception('{} to {} is not a valid conversion method'.format(convertFrom, convertTo)) try: nbtOut = None # if the block mapping requires nbt if 'nbt' in blockToIntermediate[convertFrom][str(blockID)][str(blockData)] and not fallBack: # if fallBack is false and the tile entity has not been defined return -1 # this happens when doing the whole chunk if nbtIn is None: return -1,-1, nbtOut else: # if nbt has been defined then use it to find the intermediate id intermediateID = blockToIntermediate[convertFrom][str(blockID)][str(blockData)] # multiple keys can be checked. They are stored recursively while 'nbt' in intermediateID: intermediateID = intermediateID['value'][nbtIn[intermediateID['key']].value] intermediateID = intermediateID['intermediateID']
def reloadFilters(self): filterFiles = [] unicode_module_names = [] def searchForFiltersInDir(searchFolder, stock=False): for root, folders, files in os.walk(os.path.join(searchFolder), True): filter_dir = os.path.basename(root) if filter_dir.startswith('demo') or filter_dir.startswith( 'lib'): continue subFolderString = root.replace(searchFolder, "") if subFolderString.endswith(os.sep): subFolderString = subFolderString[:len(os.sep)] if subFolderString.startswith(os.sep): subFolderString = subFolderString[len(os.sep):] if len(subFolderString) > 0: subFolderString = "[" + subFolderString + "]" try: root = str(root) if root not in sys.path: sys.path.append(root) except UnicodeEncodeError: unicode_module_names.extend( [filter_name for filter_name in files]) for possible_filter in files: if possible_filter.endswith(".py"): filterFiles.append( (root, possible_filter, stock, subFolderString)) searchForFiltersInDir(directories.getFiltersDir(), False) searchForFiltersInDir( os.path.join(directories.getDataDir(), "stock-filters"), True) filterModules = [] # If the path has unicode chars, there's no way of knowing what order to add the # files to the sys.modules. To fix this, we keep trying to import until we import # fail to import all leftover files. shouldContinue = True while shouldContinue: shouldContinue = False for f in filterFiles: module = tryImport(f[0], f[1], f[2], f[3], f[1] in unicode_module_names) if module is None: continue filterModules.append(module) filterFiles.remove(f) shouldContinue |= True displayNames = [] for m in filterModules: while m.displayName in displayNames: m.displayName += "_" displayNames.append(m) filterModules = filter(lambda mod: hasattr(mod, "perform"), filterModules) self.filterModules = collections.OrderedDict( sorted([(FilterTool.moduleDisplayName(x), x) for x in filterModules], key=lambda module_name: (module_name[0].lower(), module_name[1])))
def reloadFilters(self): filterFiles = [] unicode_module_names = [] # Tracking stock and custom filters names in order to load correctly the translations. stock_filters = [] cust_filters = [] def searchForFiltersInDir(searchFolder, stock=False): for root, folders, files in os.walk(os.path.join(searchFolder), True): filter_dir = os.path.basename(root) if filter_dir.startswith("demo") or filter_dir.startswith("lib"): continue subFolderString = root.replace(searchFolder, "") if subFolderString.endswith(os.sep): subFolderString = subFolderString[: len(os.sep)] if subFolderString.startswith(os.sep): subFolderString = subFolderString[len(os.sep) :] if len(subFolderString) > 0: subFolderString = "[" + subFolderString + "]" try: root = str(root) if root not in sys.path: sys.path.append(root) except UnicodeEncodeError: unicode_module_names.extend([filter_name for filter_name in files]) for possible_filter in files: if possible_filter.endswith(".py"): if stock: stock_filters.append(possible_filter) _stock = True else: cust_filters.append(possible_filter) _stock = False # Force the 'stock' parameter if the filter was found in the stock-filters directory if possible_filter in stock_filters: _stock = True filterFiles.append((root, possible_filter, _stock, subFolderString)) # Search first for the stock filters. searchForFiltersInDir(os.path.join(directories.getDataDir(), "stock-filters"), True) searchForFiltersInDir(directories.getFiltersDir(), False) filterModules = [] org_lang = albow.translate.lang # If the path has unicode chars, there's no way of knowing what order to add the # files to the sys.modules. To fix this, we keep trying to import until we import # fail to import all leftover files. shouldContinue = True while shouldContinue: shouldContinue = False for f in filterFiles: module = tryImport( f[0], f[1], org_lang, f[2], f[3], f[1] in unicode_module_names, notify=(not self.optionsPanel.notifications_disabled), ) if module is None: continue filterModules.append(module) filterFiles.remove(f) shouldContinue |= True displayNames = [] for m in filterModules: while m.displayName in displayNames: m.displayName += "_" displayNames.append(m) filterModules = filter(lambda mod: hasattr(mod, "perform"), filterModules) self.filterModules = collections.OrderedDict( sorted( [(FilterTool.moduleDisplayName(x), x) for x in filterModules], key=lambda module_name: (module_name[0].lower(), module_name[1]), ) )
import json import directories itemToIntermediate = {} itemToIntermediate['PC'] = json.load( open(directories.getFiltersDir() + '/WorldConverter/itemMapping/java_intermediate.json')) itemToIntermediate['PE'] = {} itemFromIntermediate = {} itemFromIntermediate['PC'] = {} itemFromIntermediate['PE'] = json.load( open(directories.getFiltersDir() + '/WorldConverter/itemMapping/intermediate_bedrock.json')) def convertItem(convertFrom, convertTo, itemID, itemData): #, nbtIn=None, fallBack = False): if convertFrom == convertTo: return itemID, itemData try: intermediateID = itemToIntermediate[convertFrom][str(itemID)][str( itemData)]['intermediateID'] itemIDNew = itemFromIntermediate[convertTo][intermediateID]['id'] itemDataNew = itemFromIntermediate[convertTo][intermediateID]['data'] return itemIDNew, itemDataNew except: pass #put except code here
import json import directories from WorldConverter.itemMapping.convert import convertItem blockEntityToIntermediate = json.load(open(directories.getFiltersDir()+'/WorldConverter/tileEntityMapping/_intermediate.json')) blockEntityFromIntermediate = {} blockEntityFromIntermediate['PC'] = json.load(open(directories.getFiltersDir()+'/WorldConverter/tileEntityMapping/intermediate_java.json')) blockEntityFromIntermediate['PE'] = json.load(open(directories.getFiltersDir()+'/WorldConverter/tileEntityMapping/intermediate_bedrock.json')) from pymclevel import TAG_List, TAG_Byte, TAG_Int, TAG_Compound, TAG_Short, TAG_Double, TAG_String, TAG_Float def convertBlockEntity(convertFrom, convertTo, te): if convertFrom == convertTo: return if 'id' not in te: del te if te['id'].value not in blockEntityToIntermediate: raise Exception('{} is not a known block entity name'.format(te['id'].value)) intermediateID = blockEntityToIntermediate[te['id'].value] # conversion code here # something recursive would probably be required in the long term if intermediateID == 'minecraft:flower_pot': if convertFrom == 'PC': if 'Item' in te: itemID = te['Item'].value del te['Item'] else: itemID = 'minecraft:air' # raise Exception('Item definition not in te:{}'.format(te))