def migrateConfigs(self): for path in sorted(glob.iglob(self.configPath + 'skins/*.json'), key=string.lower): new_config = OrderedDict() dir_path, full_name = os.path.split(path) name = os.path.splitext(full_name)[0] old_config = loadJsonOrdered(self.ID, dir_path, name) if not old_config: print self.ID + ': error while reading', full_name + '.' continue for key, data in old_config.iteritems(): if key.endswith('Menu'): new_key = key[:-4] if new_key not in VEHICLE_TYPES_ORDER: new_key = 'default' if new_key == 'Tank' else key new_config[new_key] = data elif key == 'tankSpecific': new_config.update(data) else: new_config[key] = data loadJson(self.ID, name, new_config, dir_path, True, sort_keys=False)
def py_onCreateRemod(self, settings): try: if not settings.name: SystemMessages.pushMessage( 'temp_SM' + g_config.i18n['UI_flash_remodCreate_name_empty'], SystemMessages.SM_TYPE.Warning) return from collections import OrderedDict data = self.newRemodData data['message'] = settings.message for team in g_config.teams: data[team] = getattr(settings, team) data['whitelist'] = settings.whitelist loadJson(g_config.ID, str(settings.name), data, g_config.configPath + 'remods/', True, False, sort_keys=False) g_config.readCurrentSettings() SystemMessages.pushMessage( 'temp_SM' + g_config.i18n['UI_flash_remodCreate_success'], SystemMessages.SM_TYPE.CustomizationForGold) except StandardError: SystemMessages.pushMessage( 'temp_SM' + g_config.i18n['UI_flash_remodCreate_error'], SystemMessages.SM_TYPE.Warning) traceback.print_exc()
def skinLoader(loginView): global skinsChecked if g_config.data['enabled'] and g_config.skinsData[ 'models'] and not skinsChecked: lobbyApp = g_appLoader.getDefLobbyApp() if lobbyApp is not None: lobbyApp.loadView(SFViewLoadParams('SkinnerLoading')) else: return jobStartTime = time.time() try: yield skinCRC32All() yield modelsCheck() yield modelsProcess() except AdispException: traceback.print_exc() loadJson(g_config.ID, 'skinsCache', g_config.skinsCache, g_config.configPath, True) print g_config.ID + ': total models check time:', datetime.timedelta( seconds=round(time.time() - jobStartTime)) BigWorld.callback( 1, partial(SoundGroups.g_instance.playSound2D, 'enemy_sighted_for_team')) BigWorld.callback(2, g_config.loadingProxy.onWindowClose) skinsChecked = True loginView.update()
def py_onSaveSettings(self, settings): settings = objToDict(settings) g_config.settings = settings['skins'] loadJson(g_config.ID, 'settings', g_config.settings, g_config.configPath, True, quiet=not g_config.data['isDebug']) g_config.skinsData['priorities'] = settings['priorities'] loadJson(g_config.ID, 'skinsPriority', g_config.skinsData['priorities'], g_config.configPath, True, quiet=not g_config.data['isDebug']) g_config.readCurrentSettings(not g_config.data['isDebug']) refreshCurrentVehicle()
def load(self): try: webConf_url = 'https://gist.githubusercontent.com/PolyacovYury/220e5da411d78e598687b23ab130e922/raw/' webConf = config.json_reader.JSONLoader.byte_ify( json.loads(urllib2.urlopen(webConf_url).read())) loadJson(self.ID, 'blacklist', webConf, self.configPath, True) except urllib2.URLError as e: if hasattr(e, 'reason'): print self.ID + ': blacklists config download failed:', e.reason elif hasattr(e, 'code'): print self.ID + ': GitHub internal error:', e.code super(ConfigInterface, self).load()
def readCurrentSettings(self, quiet=True): super(ConfigInterface, self).readCurrentSettings(quiet) self.cameraPos = loadJson(self.ID, 'cameraPositions', self.cameraPos, self.configPath, quiet=quiet)
def applyModdedSettings(self): self._cleanSettings() for itemsKey in self._currentSettings: for camoName in self._currentSettings[itemsKey]: g_config.camouflages[itemsKey].setdefault(camoName, {}).update(self._currentSettings[itemsKey][camoName]) if self._currentSettings['remap']: newSettings = {'disable': g_config.disable, 'remap': g_config.camouflages['remap']} loadJson(g_config.ID, 'settings', newSettings, g_config.configPath, True) if self._currentSettings['custom']: for confFolderName in g_config.configFolders: configFolder = g_config.configFolders[confFolderName] loadJson(g_config.ID, 'settings', {key: g_config.camouflages['custom'][key] for key in configFolder}, g_config.configPath + 'camouflages/' + confFolderName + '/', True, False) if any(self._currentSettings.itervalues()): g_config.collectCamouflageData() SystemMessages.pushI18nMessage(g_config.i18n['flashCol_serviceMessage_settings'], type=SM_TYPE.Information)
def migrateConfigs(g_config): settings = loadJson(g_config.ID, 'settings', g_config.settings, g_config.configPath) if settings and 'remods' in settings: for sname, remodData in settings['remods'].items(): if not remodData.pop('enabled', True): print g_config.ID + ': WARNING! Disabled remod detected:', sname + ( '. Remod disabling is not supported anymore, delete unneeded remods. ' 'If game crashed - this is, probably, the reason.') migrateSettings(g_config, remodData, remodData) loadJson(g_config.ID, 'settings', settings['remods'], g_config.configPath, True) selectedData = loadJson(g_config.ID, 'remodsCache', g_config.modelsData['selected'], g_config.configPath) for key in selectedData.keys(): if not key.islower(): selectedData[key.lower()] = selectedData.pop(key) if key.lower() == 'remod': del selectedData[key.lower()] loadJson(g_config.ID, 'remodsCache', selectedData, g_config.configPath, True) for root, _, fNames in os.walk(g_config.configPath + 'remods/'): for fName in fnmatch.filter(fNames, '*.json'): sname = fName.split('.')[0] old_conf = readOrdered(root + '/' + fName) if not old_conf: print g_config.ID + ': error while reading', fName + '.' continue new_conf = OrderedDict() new_conf['message'] = old_conf.get('authorMessage', old_conf.get('message', '')) migrateSettings(g_config, old_conf, new_conf) for key, val in old_conf.items(): if key in ('authorMessage', ) or 'Whitelist' in key or 'swap' in key: continue elif key == 'engine': val = OrderedDict((k, v) for k, v in val.iteritems() if 'wwsound' not in k) elif key == 'gun': val = OrderedDict( (k, v) for k, v in val.iteritems() if 'ffect' not in k) if 'drivenJoints' not in val: val['drivenJoints'] = None elif key == 'hull': if 'exhaust' in val and 'nodes' in val[ 'exhaust'] and isinstance(val['exhaust']['nodes'], basestring): val['exhaust']['nodes'] = val['exhaust'][ 'nodes'].split() elif key == 'chassis': val = migrate_chassis_config(val) new_conf[key] = val loadJson(g_config.ID, sname, new_conf, root, True, sort_keys=False)
def py_onSaveSettings(self, settings, cache): g_config.settings = settings = objToDict(settings) g_config.modelsData['selected'] = cache = objToDict(cache) loadJson(g_config.ID, 'remodsCache', cache, g_config.configPath, True, quiet=not g_config.data['isDebug']) loadJson(g_config.ID, 'settings', settings, g_config.configPath, True, quiet=not g_config.data['isDebug']) g_config.readCurrentSettings(not g_config.data['isDebug']) refreshCurrentVehicle()
def applyOutfitInfo(outfit, seasonName, vDesc, randomCache, vID=None, isPlayerVehicle=True): nationName, vehicleName = vDesc.name.split(':') isTurretCustomisable = isTurretCustom(vDesc) if isPlayerVehicle: vehCache = g_config.outfitCache.get(nationName, {}).get(vehicleName, {}) styleCache = vehCache.get('style', {'intCD': None, 'applied': False}) if styleCache['applied']: styleCD = styleCache['intCD'] if styleCD is not None: itemsCache = dependency.instance(IItemsCache) style = ( itemsCache.items.getItemByCD if itemsCache.items.isSynced() else itemsCache.items.itemsFactory.createCustomization)(styleCD) if not style: print g_config.ID + ': style', styleCD, 'for', vehicleName, 'deleted from game client.' styleCache.update(intCD=None, applied=False) else: outfit = style.getOutfit( SEASON_NAME_TO_TYPE[seasonName]).copy() else: outfit = Outfit() outfit._id = 20000 else: if outfit.modelsSet and any( v for k, v in vehCache.iteritems() if k != 'style'): outfit = Outfit() applyOutfitCache(outfit, vehCache.get(seasonName, {})) deleteEmpty(vehCache, isTurretCustomisable) loadJson(g_config.ID, 'outfitCache', g_config.outfitCache, g_config.configPath, True) if outfit.modelsSet or outfit.id == 20000: randomCache.clear() elif g_config.data['doRandom'] and (g_config.data['fillEmptySlots'] or hasNoCamo(outfit)): processRandomCamouflages(outfit, seasonName, randomCache, isTurretCustomisable, vID) applyOutfitCache(outfit, randomCache) return outfit
def applyModdedItems(self): vDesc = g_currentVehicle.item.descriptor nation, vehName = vDesc.name.split(':') isTurretCustomisable = isTurretCustom(vDesc) vehCache = g_config.outfitCache.setdefault(nation, {}).setdefault(vehName, {}) anything = False for p in (x for x in self.getModdedPurchaseItems() if x.selected): anything = True if p.group == AdditionalPurchaseGroups.STYLES_GROUP_ID: vehCache.setdefault('style', {}).update(intCD=p.item.intCD if not p.isDismantling else None, applied=True) if p.item is not None and not p.isDismantling: g_config.hangarCamoCache.get(nation, {}).get(vehName, {}).clear() break # there will only ever be one, but just to make sure... else: vehCache.get('style', {}).update(applied=False) typeName = GUI_ITEM_TYPE_NAMES[p.slot] seasonName = SEASON_TYPE_TO_NAME[p.group] area = Area.getName(p.areaID) if p.areaID != Area.MISC else 'misc' conf = vehCache.setdefault(seasonName, {}).setdefault(typeName, {}).setdefault(area, {}) origComponent = None origOutfit = self.service.getOutfit(p.group) if origOutfit: origComponent = origOutfit.getContainer(p.areaID).slotFor(p.slot).getComponent(p.regionID) reg = str(p.regionID) if p.slot == GUI_ITEM_TYPE.CAMOUFLAGE: seasonCache = g_config.hangarCamoCache.get(nation, {}).get(vehName, {}).get(seasonName, {}) seasonCache.get(typeName, {}).get(area, {}).pop(reg, None) deleteEmpty(seasonCache, isTurretCustomisable) if not origComponent if p.isDismantling else p.component.weak_eq(origComponent): conf.pop(reg, None) else: conf[reg] = (({f: getattr(p.component, f) for f, fd in p.component.fields.items() if not fd.weakEqualIgnored} if not isinstance(p.component, EmptyComponent) else {'id': p.item.id}) if not p.isDismantling else {'id': None}) if not anything and self._mode != self.__originalMode[self.actualMode]: vehCache.get('style', {}).update(applied=False) # if an "empty" style is applied - 'anything' is already true anything = True if vehCache.get('style', {}) == {'intCD': None, 'applied': False}: vehCache.pop('style', None) if anything: SystemMessages.pushI18nMessage( MESSENGER.SERVICECHANNELMESSAGES_SYSMSG_CONVERTER_CUSTOMIZATIONS, type=SM_TYPE.Information) deleteEmpty(g_config.outfitCache, isTurretCustomisable) loadJson(g_config.ID, 'outfitCache', g_config.outfitCache, g_config.configPath, True)
def py_onCreateRemod(self, settings): try: if not settings.name: SystemMessages.pushMessage('temp_SM' + g_config.i18n['UI_flash_remodCreate_name_empty'], SystemMessages.SM_TYPE.Warning) return from collections import OrderedDict data = self.newRemodData data['authorMessage'] = settings.message for teamIdx, team in enumerate(('player', 'ally', 'enemy')): data[team + 'Whitelist'] = ','.join(settings.whitelists[teamIdx]) loadJson(g_config.ID, str(settings.name), data, g_config.configPath + 'remods/', True, False, sort_keys=False) g_config.readCurrentSettings() SystemMessages.pushMessage( 'temp_SM' + g_config.i18n['UI_flash_remodCreate_success'], SystemMessages.SM_TYPE.CustomizationForGold) except StandardError: SystemMessages.pushMessage( 'temp_SM' + g_config.i18n['UI_flash_remodCreate_error'], SystemMessages.SM_TYPE.Warning) traceback.print_exc()
def readCurrentSettings(self, quiet=True): super(self.__class__, self).readCurrentSettings(quiet) self.configsList = [] self.confMeta.clear() self.sectDict = {} configPath = self.configPath + 'configs/' if os.path.isdir(configPath): if not quiet: print self.ID + ': loading configs from', configPath + ':' for conp in glob.iglob(configPath + '*.json'): fileName = os.path.basename(conp) confdict = loadJson(self.ID, fileName.split('.')[0], {}, os.path.dirname(conp) + '/') if fileName not in self.configsList: self.configsList.append(fileName) self.confMeta[fileName] = metaDict = { 'name': '<b>%s</b>' % fileName, 'desc': self.i18n['UI_setting_NDA'], 'has': False } if 'meta' in confdict: metaDict['name'] = confdict['meta'].get( 'name', metaDict['name']) metaDict['desc'] = confdict['meta'].get( 'desc', metaDict['desc']) metaDict['has'] = True for key, conf in confdict.iteritems(): if key == 'meta': continue section = self.sectDict.setdefault(key, {}) section['mode'] = conf['mode'] if 'bindToKey' in conf: section['bindToKey'] = conf['bindToKey'] textList = section.setdefault('textList', []) text = conf['text'] if section['mode'] == 'single': if isinstance(text, list): text = ''.join(x for x in text if x) textList.append(text.rstrip()) else: if isinstance(text, str): text = text.split(';') textList.extend(x.rstrip() for x in text if x.rstrip()) if not quiet: print '%s: loaded configs: %s' % (self.ID, ', '.join( self.confMeta)) elif not quiet: print '%s: config directory not found: %s' % (self.ID, configPath) for key in self.sectDict: self.sectDict[key]['textList'] = remDups( self.sectDict[key]['textList'])
def loadSkins(self): global skinsChecked jobStartTime = time.time() try: yield skinCRC32All() yield modelsCheck() yield modelsProcess() except AdispException: traceback.print_exc() else: loadJson(g_config.ID, 'skinsCache', g_config.skinsCache, g_config.configPath, True) print g_config.ID + ': total models check time:', datetime.timedelta( seconds=round(time.time() - jobStartTime)) BigWorld.callback( 1, partial(SoundGroups.g_instance.playSound2D, 'enemy_sighted_for_team')) BigWorld.callback(2, self.onWindowClose) skinsChecked = True self.loginView.update()
def readCurrentSettings(self, quiet=True): super(ConfigInterface, self).readCurrentSettings() self.settings = loadJson(self.ID, 'settings', self.settings, self.configPath) self.skinsCache.update(loadJson(self.ID, 'skinsCache', self.skinsCache, self.configPath)) self.skinsData['priorities'] = loadJson(self.ID, 'skinsPriority', self.skinsData['priorities'], self.configPath) if self.data['isDebug']: print self.ID + ': loading skin configs:' skinDirSect = ResMgr.openSection('vehicles/skins/textures/') for sname in () if skinDirSect is None else remDups(skinDirSect.keys()): confDict = self.settings.setdefault(sname, self.defaultSkinConfig) self.skinsData['models'][sname] = pRecord = {'name': sname, 'whitelist': set()} vehiclesDirSect = skinDirSect[sname]['vehicles'] for curNation in [] if vehiclesDirSect is None else remDups(vehiclesDirSect.keys()): nationDirSect = vehiclesDirSect[curNation] for vehicleName in [] if nationDirSect is None else remDups(nationDirSect.keys()): vehDirSect = nationDirSect[vehicleName] sections = {'default': vehDirSect} modelsSetsSect = vehDirSect['_skins'] if modelsSetsSect is not None: for modelsSet, modelsSetSect in modelsSetsSect.items(): sections[modelsSet] = modelsSetSect for modelsSet, modelsSetSect in sections.items(): tracksDirSect = modelsSetSect['tracks'] if not any(texName.endswith('.dds') for texName in ( ([] if modelsSetSect is None else remDups(modelsSetSect.keys())) + ([] if tracksDirSect is None else remDups(tracksDirSect.keys())))): if self.data['isDebug']: print self.ID + ':', vehicleName, 'folder from', sname, 'pack is empty.' else: pRecord['whitelist'].add((vehicleName + '/' + modelsSet).lower()) for skinType in ('static', 'dynamic'): priorities = self.skinsData['priorities'][skinType] for tankType in priorities: if not confDict[skinType][tankType]: if self.data['isDebug']: print self.ID + ':', tankType, 'swapping in', sname, 'disabled.' if sname in priorities[tankType]: priorities[tankType].remove(sname) elif sname not in priorities[tankType]: priorities[tankType].append(sname) if self.data['isDebug']: print self.ID + ': config for', sname, 'loaded.' for sname in self.settings.keys(): if sname not in self.skinsData['models']: del self.settings[sname] if not self.skinsData['models']: if not quiet: print self.ID + ': no skin packs found, skin module standing down.' for skinType in self.skinsData['priorities']: for key in self.skinsData['priorities'][skinType]: for sname in self.skinsData['priorities'][skinType][key]: if sname not in self.skinsData['models']: self.skinsData['priorities'][skinType][key].remove(sname) loadJson(self.ID, 'skinsPriority', self.skinsData['priorities'], self.configPath, True, quiet=quiet) loadJson(self.ID, 'settings', self.settings, self.configPath, True, quiet=quiet)
def migrateConfigs(self): settings = loadJson(self.ID, 'settings', self.settings, self.configPath) if settings.keys() == ['skins', 'skins_dynamic']: new_settings = {} for skinTypeName, skinTypeConf in settings.iteritems(): skinType = skinTypeName.replace('skins', '') if not skinType: skinType = 'static' else: skinType = skinType[1:] for skinName, skinConf in skinTypeConf.iteritems(): skinSettings = new_settings.setdefault(skinName, {}).setdefault(skinType, {}) for setting in skinConf: if 'swap' not in setting: continue new_setting = setting[4:].lower() if new_setting not in self.teams: print new_setting assert False skinSettings[new_setting] = skinConf[setting] loadJson(self.ID, 'settings', new_settings, self.configPath, True) priorities = loadJson(self.ID, 'skinsPriority', self.skinsData['priorities'], self.configPath) for skinType in ('static', 'dynamic'): priority = priorities[skinType] for key in priority.keys(): if not key.islower(): priority[key.lower()] = priority.pop(key) loadJson(self.ID, 'skinsPriority', priorities, self.configPath, True)
def py_onSaveSettings(settings): remodNames = sorted(g_config.modelsData['models']) for idx, setObj in enumerate(settings.remods): modelsSettings = g_config.settings['remods'][remodNames[idx]] for key in ('player', 'ally', 'enemy'): modelsSettings['swap' + key.capitalize()] = getattr(setObj.useFor, key) for teamIdx, team in enumerate(('player', 'ally', 'enemy')): modelsSettings[team + 'Whitelist'] = ','.join(setObj.whitelists[teamIdx]) for idx, settingsArray in enumerate(settings.skins): for nameIdx, setObj in enumerate(settingsArray): for key in ('player', 'ally', 'enemy'): g_config.settings['skins' + ('', '_dynamic')[idx]][ sorted(g_config.skinsData['models'][('static', 'dynamic')[idx]])[nameIdx]][ 'swap' + key.capitalize()] = getattr(setObj.useFor, key) for idx, prioritiesArray in enumerate(settings.priorities): for teamIdx, team in enumerate(('player', 'ally', 'enemy')): g_config.skinsData['priorities'][('static', 'dynamic')[idx]][team] = prioritiesArray[teamIdx] loadJson(g_config.ID, 'skinsPriority', g_config.skinsData['priorities'], g_config.configPath, True, quiet=not g_config.data['isDebug']) loadJson(g_config.ID, 'settings', g_config.settings, g_config.configPath, True, quiet=not g_config.data['isDebug']) g_config.readCurrentSettings(not g_config.data['isDebug']) refreshCurrentVehicle()
def updateCommandData(self): self.configMeta = { 'default': self.i18n['UI_setting_selectedConfig_defaultMeta'] } self.commands.clear() self.commands['default'] = { 'hotkeyOnly': [ CustomMenuCommand({ 'command': 'RELOADINGGUN', 'hotKey': ['KEY_C'] }) ] } for path in sorted(glob.iglob(self.configPath + 'skins/*.json'), key=string.lower): dir_path, full_name = os.path.split(path) name = os.path.splitext(full_name)[0] try: confDict = loadJson(self.ID, name, {}, dir_path) except StandardError: print self.ID + ': config', full_name, 'is invalid.' traceback.print_exc() continue self.configMeta[name] = confDict.get('meta', name) self.commands[name] = commands = {} for key, confSect in confDict.iteritems(): if key == 'meta': continue if isinstance(confSect, basestring): commands[key] = confSect elif key == 'hotkeyOnly': commands[key] = [CustomMenuCommand(x) for x in confSect] else: commands[key] = { menuType: [CustomMenuCommand(x) if x else x for x in menuConf] for menuType, menuConf in confSect.iteritems() } self.data['selectedConfig'] = min(self.data['selectedConfig'], len(self.commands) - 1)
def buyAndExit(self, purchaseItems): self._currentSettings = self._cleanSettings(self._currentSettings) for itemsKey in self._currentSettings: for camoName in self._currentSettings[itemsKey]: g_config.camouflages[itemsKey].setdefault(camoName, {}).update(self._currentSettings[itemsKey][camoName]) if self._currentSettings['remap']: newSettings = {'disable': g_config.disable, 'remap': g_config.camouflages['remap']} loadJson(g_config.ID, 'settings', newSettings, g_config.configPath, True) if self._currentSettings['custom']: for confFolderName in g_config.configFolders: configFolder = g_config.configFolders[confFolderName] loadJson(g_config.ID, 'settings', {key: g_config.camouflages['custom'][key] for key in configFolder}, g_config.configPath + 'camouflages/' + confFolderName + '/', True, False) if any(self._currentSettings.itervalues()): from ..processors import collectCamouflageData collectCamouflageData() self.itemsCache.onSyncCompleted -= self.__onCacheResync boughtOutfits = {season: self.service.getCustomOutfit(season) for season in SeasonType.COMMON_SEASONS} cart = getTotalPurchaseInfo(purchaseItems) nationName, vehicleName = g_currentVehicle.item.descriptor.name.split(':') vehConfig = g_config.outfitCache.get(nationName, {}).get(vehicleName, {}) for pItem in (x for x in purchaseItems if x.selected): seasonName = SEASON_TYPE_TO_NAME[pItem.group] if pItem.slot == GUI_ITEM_TYPE.CAMOUFLAGE: bItem, bComp = boughtOutfits[pItem.group].getContainer(pItem.areaID).slotFor(pItem.slot)._items.get( pItem.regionID, (None, None)) component = self._modifiedOutfits[pItem.group].getContainer(pItem.areaID).slotFor(pItem.slot).getComponent( pItem.regionID) if pItem.isDismantling and (not bItem or not bComp) or not pItem.isDismantling and pItem.item == bItem and \ component.palette == bComp.palette and component.patternSize == bComp.patternSize: vehConfig.get(seasonName, {}).get('camo', {}).pop(TankPartIndexes.getName(pItem.areaID), []) else: g_config.outfitCache.setdefault(nationName, {}).setdefault(vehicleName, {}).setdefault( seasonName, {}).setdefault('camo', {})[TankPartIndexes.getName(pItem.areaID)] = ( [pItem.item.id, component.palette, component.patternSize] if not pItem.isDismantling else []) g_config.hangarCamoCache.get(nationName, {}).get(vehicleName, {}).get(seasonName, {}).pop( TankPartIndexes.getName(pItem.areaID), {}) else: typeName = GUI_ITEM_TYPE_NAMES[pItem.slot] bItem = boughtOutfits[pItem.group].getContainer(pItem.areaID).slotFor(pItem.slot).getItem(pItem.regionID) if pItem.isDismantling and not bItem or not pItem.isDismantling and pItem.item == bItem: vehConfig.get(seasonName, {}).get(typeName, {}).get( TankPartIndexes.getName(pItem.areaID) if pItem.areaID < 4 else 'misc', {}).pop(str(pItem.regionID), None) else: g_config.outfitCache.setdefault(nationName, {}).setdefault(vehicleName, {}).setdefault( seasonName, {}).setdefault(typeName, {}).setdefault( TankPartIndexes.getName(pItem.areaID) if pItem.areaID < 4 else 'misc', {})[ str(pItem.regionID)] = (pItem.item.id if not pItem.isDismantling else None) for nationName in g_config.outfitCache.keys(): for vehicleName in g_config.outfitCache[nationName].keys(): for season in g_config.outfitCache[nationName][vehicleName].keys(): for itemType in g_config.outfitCache[nationName][vehicleName][season].keys(): if itemType == 'camo': if g_currentVehicle.item.turret.isGunCarriage: g_config.outfitCache[nationName][vehicleName][season][itemType].pop('turret', None) else: for areaName in g_config.outfitCache[nationName][vehicleName][season][itemType].keys(): if not g_config.outfitCache[nationName][vehicleName][season][itemType][areaName]: del g_config.outfitCache[nationName][vehicleName][season][itemType][areaName] if not g_config.outfitCache[nationName][vehicleName][season][itemType]: del g_config.outfitCache[nationName][vehicleName][season][itemType] if not g_config.outfitCache[nationName][vehicleName][season]: del g_config.outfitCache[nationName][vehicleName][season] if not g_config.outfitCache[nationName][vehicleName]: del g_config.outfitCache[nationName][vehicleName] if not g_config.outfitCache[nationName]: del g_config.outfitCache[nationName] loadJson(g_config.ID, 'outfitCache', g_config.outfitCache, g_config.configPath, True) if cart.totalPrice != ITEM_PRICE_EMPTY: msgCtx = {'money': formatPrice(cart.totalPrice.price), 'count': cart.numSelected} SystemMessages.pushMessage(g_config.i18n['UI_flashCol_applied_money'] % msgCtx, type=CURRENCY_TO_SM_TYPE.get(cart.totalPrice.getCurrency(byWeight=True), SM_TYPE.PurchaseForGold)) else: SystemMessages.pushI18nMessage(MESSENGER.SERVICECHANNELMESSAGES_SYSMSG_CONVERTER_CUSTOMIZATIONS, type=SM_TYPE.Information) self.__onCacheResync() self.itemsCache.onSyncCompleted += self.__onCacheResync
def readCurrentSettings(self, quiet=True): self.configsDict.clear() self.modes = { 'constant': [], 'stop': [], 'turn_left': [], 'turn_right': [], 'back': [], 'target': [], 'spot': [] } super(ConfigInterface, self).readCurrentSettings(quiet) if self.data['DebugModel']: if self.data['DebugPath']: try: _ = BigWorld.Model(self.data['DebugPath']) except StandardError: LOG_ERROR('Debug model path incorrect: %s' % self.data['DebugPath']) self.data['DebugModel'] = False else: LOG_NOTE('Debug disabled due to absence of DebugPath.') self.data['DebugModel'] = False if self.data['enabled']: configPath = self.configPath + 'configs/' if not os.path.exists(configPath): LOG_ERROR('%s config folder not found: %s' % (self.ID, configPath)) os.makedirs(configPath) for confPath in glob.iglob(configPath + '*.json'): confName = os.path.basename(confPath) try: confdict = loadJson( self.ID, confName.split('.')[0], self.configsDict.get(confName.split('.')[0], {}), os.path.dirname(confPath) + '/') except StandardError: print self.ID + ': config', confName, 'is invalid.' traceback.print_exc() continue if not confdict['enable'] or not any( x for x in (confdict.get(y, True) for y in ('attachToPlayer', 'attachToAlly', 'attachToEnemy'))): if not quiet: print self.ID + ': config', confName, 'is disabled.' continue if self.data['Debug']: print self.ID + ': loading', confName + ':' self.configsDict[confName.split('.')[0]] = configsDict = {} configsDict['meta'] = metaDict = { 'name': '<b>%s</b>' % confName, 'desc': self.i18n['UI_setting_meta_NDA'] } metaDict['name'] = confdict.get('meta', {}).get(self.lang, {}).get( 'name', metaDict['name']) metaDict['desc'] = confdict.get('meta', {}).get(self.lang, {}).get( 'desc', metaDict['desc']) for key in ['attachToPlayer', 'attachToAlly', 'attachToEnemy']: configsDict[key] = confdict.get(key, True) self.readConfDict(quiet, confdict, confPath) if not self.configsDict: print 'LampLights has not loaded any configs. Are you sure you need this .pyc?' if self.data['DebugModel'] and self.configsDict: if self.data['Debug'] and not quiet: print 'LampLights: loading configs for Debug:' for fileName, configsDict in self.configsDict.items(): for confKey in configsDict.keys(): if confKey in ('enable', 'meta', 'attachToPlayer', 'attachToAlly', 'attachToEnemy'): continue if configsDict.get(confKey + 'Debug') is None: if 'model' not in configsDict[confKey]['type']: self.configsDict[fileName][ confKey + 'Debug'] = confDict = {} confDict['type'] = 'model' for key in ('place', 'preRotate', 'postRotate', 'vect', 'mode', 'attachToPlayer', 'attachToAlly', 'attachToEnemy'): confDict[key] = listToTuple( configsDict[confKey][key]) if confDict['mode'] not in self.modes: print 'LampLights: unknown mode at %sDebug detected: %s. This light will be off.' \ % (confKey, confDict['mode']) else: self.modes[confDict['mode']].append( confKey + 'Debug') confDict['path'] = self.data['DebugPath'] if self.data['Debug'] and not quiet: print 'LampLights: config for %sDebug loaded.' % confKey elif self.data['Debug'] and not quiet: print 'LampLights: debug assignment failure: %sDebug' % confKey else: LOG_NOTE('LampLights mod fully disabled via main config.') self.isLampsVisible = False self.isTickRequired = any(self.modes[key] for key in ('stop', 'turn_left', 'turn_right', 'back')) self.updateMod()
def lobbyKeyControl(event): if not event.isKeyDown() or g_config.isMSAWindowOpen: return if (g_config.modelsData['enabled'] or g_config.skinsData['enabled']) and checkKeys(g_config.data['ChangeViewHotkey']): while True: newModeNum = (g_config.possibleModes.index(g_config.currentMode) + 1) % len(g_config.possibleModes) g_config.currentMode = g_config.possibleModes[newModeNum] if g_config.data.get(g_config.currentMode, True): break if g_config.data['isDebug']: print g_config.ID + ': changing display mode to', g_config.currentMode SystemMessages.pushMessage( 'temp_SM%s<b>%s</b>' % (g_config.i18n['UI_mode'], g_config.i18n['UI_mode_' + g_config.currentMode]), SystemMessages.SM_TYPE.Warning) refreshCurrentVehicle() if checkKeys(g_config.data['CollisionHotkey']): if g_config.collisionComparisonEnabled: g_config.collisionComparisonEnabled = False if g_config.data['isDebug']: print g_config.ID + ': disabling collision displaying' SystemMessages.pushMessage('temp_SM' + g_config.i18n['UI_disableCollisionComparison'], SystemMessages.SM_TYPE.CustomizationForGold) elif g_config.collisionEnabled: g_config.collisionEnabled = False g_config.collisionComparisonEnabled = True if g_config.data['isDebug']: print g_config.ID + ': enabling collision display comparison mode' SystemMessages.pushMessage('temp_SM' + g_config.i18n['UI_enableCollisionComparison'], SystemMessages.SM_TYPE.CustomizationForGold) else: g_config.collisionEnabled = True if g_config.data['isDebug']: print g_config.ID + ': enabling collision display' SystemMessages.pushMessage('temp_SM' + g_config.i18n['UI_enableCollision'], SystemMessages.SM_TYPE.CustomizationForGold) refreshCurrentVehicle() if checkKeys(g_config.data['DynamicSkinHotkey']): enabled = g_config.dynamicSkinEnabled g_config.dynamicSkinEnabled = not enabled SystemMessages.pushMessage( 'temp_SM' + g_config.i18n['UI_%sableDynamicSkin' % ('en' if not enabled else 'dis')], SystemMessages.SM_TYPE.CustomizationForGold) refreshCurrentVehicle() if g_config.modelsData['enabled'] and checkKeys(g_config.data['SwitchRemodHotkey']): if g_config.currentMode != 'remod': curTankType = g_config.currentMode snameList = sorted(g_config.modelsData['models'].keys()) + [''] selected = g_config.modelsData['selected'][curTankType] vehName = RemodEnablerUI.py_getCurrentVehicleName() if selected.get(vehName) not in snameList: snameIdx = 0 else: snameIdx = snameList.index(selected[vehName]) + 1 if snameIdx == len(snameList): snameIdx = 0 for Idx in xrange(snameIdx, len(snameList)): curPRecord = g_config.modelsData['models'].get(snameList[Idx]) if snameList[Idx] and vehName not in curPRecord.whitelists[curTankType]: continue if vehName in selected: selected[vehName] = getattr(curPRecord, 'name', '') loadJson(g_config.ID, 'remodsCache', g_config.modelsData['selected'], g_config.configPath, True, quiet=not g_config.data['isDebug']) break else: snameList = sorted(g_config.modelsData['models'].keys()) if g_config.modelsData['selected']['remod'] not in snameList: snameIdx = 0 else: snameIdx = snameList.index(g_config.modelsData['selected']['remod']) + 1 if snameIdx == len(snameList): snameIdx = 0 sname = snameList[snameIdx] g_config.modelsData['selected']['remod'] = sname loadJson(g_config.ID, 'remodsCache', g_config.modelsData['selected'], g_config.configPath, True, quiet=not g_config.data['isDebug']) refreshCurrentVehicle()
def readCurrentSettings(self, quiet=True): super(ConfigInterface, self).readCurrentSettings(quiet) self.blacklists = loadJson(self.ID, 'blacklist', self.blacklists, self.configPath)
def readCurrentSettings(self, quiet=True): super(ConfigInterface, self).readCurrentSettings(quiet) self.settings = loadJson(self.ID, 'settings', self.settings, self.configPath) self.modelsData['models'].clear() self.modelsData['selected'] = selectedData = loadJson( self.ID, 'remodsCache', self.modelsData['selected'], self.configPath) remodTanks = set() for root, _, fNames in os.walk(self.configPath + 'remods/'): for fName in fnmatch.filter(fNames, '*.json'): sName = fName.split('.')[0] confDict = loadJson(self.ID, sName, {}, root, encrypted=True) if not confDict: print self.ID + ': error while reading', fName + '.' continue settingsDict = self.settings.setdefault( sName, {team: confDict[team] for team in self.teams}) self.modelsData['models'][ sName] = pRecord = self.modelDescriptor pRecord['name'] = sName pRecord['message'] = confDict.get('message', '') settingsDict['whitelist'] = pRecord[ 'whitelist'] = whitelist = remDups( x.strip() for x in settingsDict.get( 'whitelist', confDict['whitelist']) if x.strip()) for xmlName in whitelist: remodTanks.add(xmlName) for team in selectedData: if xmlName not in selectedData[ team] or selectedData[team][xmlName] is None: if settingsDict[team]: selectedData[team][xmlName] = sName else: selectedData[team][xmlName] = None if self.data['isDebug']: if not whitelist: print self.ID + ': empty whitelist for', sName + '.' else: print self.ID + ': whitelist for', sName + ':', whitelist for key, data in pRecord.iteritems(): if key in ('name', 'message', 'whitelist'): continue if key == 'common': confSubDict = confDict else: confSubDict = confDict.get(key) if not confSubDict: continue if 'undamaged' in data: data['undamaged'] = confSubDict['undamaged'] if 'AODecals' in data and 'AODecals' in confSubDict and 'hullPosition' in confSubDict: data['AODecals'] = [] for subList in confSubDict['AODecals']: m = Math.Matrix() for strNum, row in enumerate(subList): for colNum, elemNum in enumerate(row): m.setElement(strNum, colNum, elemNum) data['AODecals'].append(m) data['hullPosition'] = confSubDict['hullPosition'] if 'camouflage' in data and 'exclusionMask' in confSubDict.get( 'camouflage', {}): data['camouflage']['exclusionMask'] = confSubDict[ 'camouflage']['exclusionMask'] if 'tiling' in confSubDict['camouflage']: data['camouflage']['tiling'] = confSubDict[ 'camouflage']['tiling'] elif key == 'common' and self.data['isDebug']: print self.ID + ': default camomask not found for', sName if 'emblemSlots' in data: data['emblemSlots'] = slots = [] for subDict in confSubDict.get('emblemSlots', []): if subDict['type'] not in AES: print g_config.ID + ': not supported emblem slot type:', subDict[ 'type'] + ', expected:', AES continue descr = EmblemSlot( Math.Vector3(tuple(subDict['rayStart'])), Math.Vector3(tuple(subDict['rayEnd'])), Math.Vector3(tuple(subDict['rayUp'])), subDict['size'], subDict.get('hideIfDamaged', False), subDict['type'], subDict.get('isMirrored', False), subDict.get('isUVProportional', True), subDict.get('emblemId', None), subDict.get( 'slotId', c11n_constants.customizationSlotIds[key][ subDict['type']][0]), subDict.get('applyToFabric', True)) slots.append(descr) if 'exhaust' in data and 'exhaust' in confSubDict: if 'nodes' in confSubDict['exhaust']: data['exhaust']['nodes'] = confSubDict['exhaust'][ 'nodes'] if 'pixie' in confSubDict['exhaust']: data['exhaust']['pixie'] = confSubDict['exhaust'][ 'pixie'] if key == 'chassis': for k in chassis_params + ('chassisLodDistance', ): data[k] = confSubDict[k] for k in ('soundID', 'drivenJoints'): if k in data and k in confSubDict: data[k] = confSubDict[k] if self.data['isDebug']: print self.ID + ': config for', sName, 'loaded.' for sName in self.settings.keys(): if sName not in self.modelsData['models']: del self.settings[sName] if not self.modelsData['models']: if not quiet: print self.ID + ': no configs found, model module standing down.' for team in self.teams: for xmlName in selectedData[team].keys(): if xmlName not in remodTanks: del selectedData[team][xmlName] continue if selectedData[team][xmlName] is None or ( selectedData[team][xmlName] and selectedData[team][xmlName] not in self.modelsData['models']): selectedData[team][xmlName] = next( (sName for sName in sorted(self.modelsData['models']) if xmlName in self.settings[sName]['whitelist'] and self.settings[sName][team]), None) or '' loadJson(self.ID, 'remodsCache', selectedData, self.configPath, True, quiet=quiet) loadJson(self.ID, 'settings', self.settings, self.configPath, True, quiet=quiet)
def migrateConfigs(g_config): settings = loadJson(g_config.ID, 'settings', g_config.settings, g_config.configPath) if settings and 'remods' in settings: for sname, remodData in settings['remods'].items(): if not remodData.pop('enabled', True): print g_config.ID + ': WARNING! Disabled remod detected:', sname + ( '. Remod disabling is not supported anymore, delete unneeded remods. ' 'If game crashed - this is, probably, the reason.') migrateSettings(g_config, remodData, remodData) loadJson(g_config.ID, 'settings', settings['remods'], g_config.configPath, True) selectedData = loadJson(g_config.ID, 'remodsCache', g_config.modelsData['selected'], g_config.configPath) for key in selectedData.keys(): if not key.islower(): selectedData[key.lower()] = selectedData.pop(key) if key.lower() == 'remod': del selectedData[key.lower()] loadJson(g_config.ID, 'remodsCache', selectedData, g_config.configPath, True) for root, _, fNames in os.walk(g_config.configPath + 'remods/'): for fName in fnmatch.filter(fNames, '*.json'): sname = os.path.splitext(fName)[0] old_conf = loadJsonOrdered(g_config.ID, root, sname) if not old_conf: print g_config.ID + ': error while reading', fName + '.' continue new_conf = OrderedDict() new_conf['message'] = old_conf.get('authorMessage', old_conf.get('message', '')) migrateSettings(g_config, old_conf, new_conf) for key, val in old_conf.items(): if key in ('authorMessage', ) or 'Whitelist' in key or 'swap' in key: continue if key in TankPartNames.ALL and 'emblemSlots' in val: emblemSlots = [] for data in val['emblemSlots']: slotData = OrderedDict() emblemSlots.append(slotData) for k, v in zip(defaultEmblemSlot._fields, defaultEmblemSlot): if k in data: v = data[k] elif k == 'slotId': v = customizationSlotIdRanges[key][ data['type']][0] slotData[k] = v val['emblemSlots'][:] = emblemSlots if key == 'engine': val = OrderedDict((k, v) for k, v in val.iteritems() if 'wwsound' not in k) if key == 'gun': val = OrderedDict( (k, v) for k, v in val.iteritems() if 'ffect' not in k) if 'drivenJoints' not in val: val['drivenJoints'] = None if key == 'hull': if 'exhaust' in val and 'nodes' in val[ 'exhaust'] and isinstance(val['exhaust']['nodes'], basestring): val['exhaust']['nodes'] = val['exhaust'][ 'nodes'].split() if key == 'chassis': val = migrate_chassis_config(val) new_conf[key] = val loadJson(g_config.ID, sname, new_conf, root, True, sort_keys=False)
def readCurrentSettings(self, quiet=True): super(self.__class__, self).readCurrentSettings(quiet) self.blacklists = loadJson(self.ID, 'blacklist', self.blacklists, self.configPath)
def readCurrentSettings(self, quiet=True): configPath = self.configPath + 'configs/' if not os.path.exists(configPath): LOG_ERROR('config folder not found: ' + configPath) os.makedirs(configPath) effectsXmlPath = _VEHICLE_TYPE_XML_PATH + 'common/gun_effects.xml' effectsXml = ResMgr.openSection(effectsXmlPath) for confPath in glob.iglob(configPath + '*.json'): confName = os.path.basename(confPath).split('.')[0] try: confdict = loadJson(self.ID, confName, {}, os.path.dirname(confPath) + '/') except StandardError: print self.ID + ': config', os.path.basename( confPath), 'is invalid.' traceback.print_exc() continue self.confList.add(confName) for itemType, itemsDict in confdict.iteritems(): if itemType not in self.data: if not quiet: print self.ID + ': invalid item type in', confName + ':', itemType continue itemsData = self.data[itemType] if itemType in ('engines', 'guns'): for nationName, nationData in itemsDict.iteritems(): if nationName.split(':')[0] not in nations.NAMES: print self.ID + ': unknown nation in', itemType, 'in', confName + ':', nationName continue for itemName in nationData: itemsData.setdefault(nationName, {}).setdefault( itemName, {}).update(nationData[itemName]) if itemType in ('gun_reload_effects', 'shot_effects', 'sound_notifications'): for itemName in itemsDict: itemsData.setdefault(itemName, {}).update(itemsDict[itemName]) if itemType == 'gun_effects': for itemName, itemData in itemsDict.iteritems(): if 'origin' not in itemData: print self.ID + ':', confName + ':', itemName, 'has no origin' continue origin = itemData['origin'] if origin not in effectsXml.keys(): print self.ID + ':', confName + ':', itemName, 'has unknown origin:', origin continue itemName = intern(itemName) for key in itemData.keys(): if key not in ('origin', 'timeline', 'effects'): print self.ID + ':', confName + ': incorrect key', key, 'in', itemName, 'ignored' itemData.pop(key, None) if 'effects' in itemData: for key in itemData['effects'].keys(): if key != 'shotSound': print self.ID + ':', confName + ': only shotSound effects are supported,', key, 'ignored' itemData['effects'].pop(key) itemsData.setdefault(itemName, {}).update(itemData) print self.ID + ': loaded configs:', ', '.join( x + '.json' for x in sorted(self.confList)) for sname, effData in self.data['gun_effects'].iteritems(): if sname not in g_cache._gunEffects: g_cache._gunEffects[sname] = readEffectsTimeLine( ((None, effectsXmlPath), effData['origin']), effectsXml[effData['origin']]) effectDesc = g_cache._gunEffects[sname] if 'timeline' in effData: for keyPointName, timePoint in effData['timeline'].iteritems(): for keyPoint in effectDesc.keyPoints: if keyPoint.name == keyPointName: effectDesc.keyPoints.remove(keyPoint) effectDesc.keyPoints.append( keyPoint._replace(time=float(timePoint))) break else: effectDesc.keyPoints.append( KeyPoint(keyPointName, timePoint)) effectDesc.keyPoints.sort(key=lambda i: i.time) if 'effects' in effData and 'shotSound' in effData['effects']: data = effData['effects']['shotSound'] for effect in effectDesc.effectsList._EffectsList__effectDescList: if effect.TYPE == '_ShotSoundEffectDesc': effect._soundName = tuple( (tuple(data[key]) if key in data else effectDesc._soundName[idx]) for idx, key in enumerate(('wwsoundPC', 'wwsoundNPC'))) for sname, effData in self.data['gun_reload_effects'].iteritems(): if effData['type'] not in reloadTypes: print self.ID + ': wrong reload effect type:', effData[ 'type'], 'available:', sorted(reloadTypes.keys()) continue reloadType = reloadTypes[effData['type']] orig, desc, sect = g_cache._gunReloadEffects.get( sname, None), None, ResMgr.DataSection() if not isinstance(orig, reloadType): # None is not an instance too if orig is not None: print self.ID + ': changing type of reload effect %s. Might cause problems!' % sname orig, desc = None, reloadType(sect) for slot in reloadType.__slots__: slotName = mismatchSlots.get(slot, slot) if slotName in effData: value = effData[slotName] else: value = getattr(orig or desc, slot) if slot in modifiers: value = modifiers[slot](value) sect.writeString(slotName, str(value)) new_desc = reloadType(sect) if orig is None: g_cache._gunReloadEffects[sname] = new_desc else: # set new attributes to existing descriptors, otherwise they don't update [ setattr(orig, slot, getattr(new_desc, slot)) for slot in reloadType.__slots__ ] for item_type, items_storage in (('engines', g_cache._Cache__engines), ('guns', g_cache._Cache__guns)): for nationID, nation_items in enumerate(items_storage): nationData = self.data[item_type].get(nations.NAMES[nationID]) if not nationData: continue for item in nation_items.itervalues(): itemData = nationData.get(item.name) if not itemData: continue if item_type == 'engines': s = item.sounds.getEvents() item.sounds = SoundConfig( '', itemData.get('wwsoundPC', s[0]), itemData.get('wwsoundNPC', s[1])) elif item_type == 'guns': if 'effects' in itemData: item.effects = g_cache._gunEffects.get( itemData['effects'], item.effects) if 'reloadEffect' in itemData: item.reloadEffect = g_cache._gunReloadEffects.get( itemData['reloadEffect'], item.reloadEffect) for sname, index in g_cache.shotEffectsIndexes.iteritems(): effData = self.data['shot_effects'].get(sname) if effData is None: continue res = g_cache.shotEffects[index] for effType in (x for x in ('projectile', ) if x in effData): typeData = effData[effType] for effectDesc in res[effType][2]._EffectsList__effectDescList: if isinstance(effectDesc, _TracerSoundEffectDesc): effectDesc._soundName = tuple( (typeData.get(key, effectDesc._soundName[idx]), ) for idx, key in enumerate(('wwsoundPC', 'wwsoundNPC'))) for effType in (x for x in ( tuple(x + 'Hit' for x in EFFECT_MATERIALS) + ('armorBasicRicochet', 'armorRicochet', 'armorResisted', 'armorHit', 'armorCriticalHit')) if x in effData): typeData = effData[effType] for effectDesc in res[ effType].effectsList._EffectsList__effectDescList: if isinstance(effectDesc, _SoundEffectDesc): effectDesc._impactNames = ImpactNames( *(typeData.get( key, getattr(effectDesc._impactNames, key)) for key in ('impactNPC_PC', 'impactPC_NPC', 'impactNPC_NPC', 'impactFNPC_PC'))) for vehicleType in g_cache._Cache__vehicles.itervalues(): self.inject_vehicleType(vehicleType)
def readCurrentSettings(self, quiet=True): super(ConfigInterface, self).readCurrentSettings(quiet) self.settings = loadJson(self.ID, 'settings', self.settings, self.configPath) self.modelsData['models'].clear() self.modelsData['selected'] = selectedData = loadJson( self.ID, 'remodsCache', self.modelsData['selected'], self.configPath) changed_xmlNames = set() configs_dir = self.configPath + 'remods/' for directory, _, fNames in os.walk(configs_dir): for fName in fnmatch.filter(fNames, '*.json'): remod_name = os.path.join(directory.replace(configs_dir, ''), fName.split('.')[0]).replace( os.sep, '/') confDict = loadJson(self.ID, remod_name, {}, configs_dir, encrypted=True) if not confDict: print self.ID + ': error while reading', remod_name + '.json.' continue old_settings = None old_setting_names = [ name for name in self.settings if name in remod_name ] if old_setting_names and remod_name not in old_setting_names: if len(old_setting_names) > 1: print self.ID + ': multiple possible settings for remod', remod_name + ':', old_setting_names, print 'skipping settings migration' else: old_settings = self.settings.pop(old_setting_names[0]) settings = self.settings.setdefault( remod_name, old_settings or {team: confDict[team] for team in self.teams}) self.modelsData['models'][ remod_name] = descr = self.modelDescriptor descr['name'] = remod_name descr['message'] = confDict.get('message', '') settings['whitelist'] = descr[ 'whitelist'] = whitelist = remDups( x.strip() for x in settings.get( 'whitelist', confDict['whitelist']) if x.strip()) for xmlName in whitelist: changed_xmlNames.add(xmlName) for team in selectedData: if xmlName not in selectedData[ team] or selectedData[team][xmlName] is None: if settings[team]: selectedData[team][xmlName] = remod_name else: selectedData[team][xmlName] = None if self.data['isDebug']: if not whitelist: print self.ID + ': empty whitelist for', remod_name + '.' else: print self.ID + ': whitelist for', remod_name + ':', whitelist for key, data in descr.iteritems(): if key in ('name', 'message', 'whitelist'): continue if key == 'common': confSubDict = confDict else: confSubDict = confDict.get(key) if not confSubDict: continue if 'undamaged' in data: data['undamaged'] = confSubDict['undamaged'] if 'AODecals' in data and 'AODecals' in confSubDict and 'hullPosition' in confSubDict: data['AODecals'] = [] for subList in confSubDict['AODecals']: m = Math.Matrix() for strNum, row in enumerate(subList): for colNum, elemNum in enumerate(row): m.setElement(strNum, colNum, elemNum) data['AODecals'].append(m) data['hullPosition'] = confSubDict['hullPosition'] if 'camouflage' in data and 'exclusionMask' in confSubDict.get( 'camouflage', {}): data['camouflage']['exclusionMask'] = confSubDict[ 'camouflage']['exclusionMask'] if 'tiling' in confSubDict['camouflage']: data['camouflage']['tiling'] = confSubDict[ 'camouflage']['tiling'] elif key == 'common' and self.data['isDebug']: print self.ID + ': default camomask not found for', remod_name if 'emblemSlots' in data: data['emblemSlots'] = slots = [] for subDict in confSubDict.get('emblemSlots', ()): if subDict['type'] not in AES: print g_config.ID + ': not supported emblem slot type:', subDict[ 'type'] + ', expected:', AES continue subDict.update({ k: Math.Vector3(subDict[k]) for k in ('rayStart', 'rayEnd', 'rayUp') }) slots.append(EmblemSlot(**subDict)) if 'exhaust' in data and 'exhaust' in confSubDict: if 'nodes' in confSubDict['exhaust']: data['exhaust']['nodes'] = confSubDict['exhaust'][ 'nodes'] if 'pixie' in confSubDict['exhaust']: data['exhaust']['pixie'] = confSubDict['exhaust'][ 'pixie'] if key == 'chassis': for k in chassis_params + ('chassisLodDistance', ): data[k] = confSubDict[k] for k in ('soundID', 'drivenJoints'): if k in data and k in confSubDict: data[k] = confSubDict[k] if self.data['isDebug']: print self.ID + ': config for', remod_name, 'loaded.' for remod_name in self.settings.keys(): if remod_name not in self.modelsData['models']: del self.settings[remod_name] if not self.modelsData['models']: if not quiet: print self.ID + ': no configs found, model module standing down.' for team, teamData in selectedData.items(): for xmlName in teamData.keys(): if xmlName not in changed_xmlNames: teamData.pop(xmlName) continue remod_name = teamData[xmlName] if remod_name and remod_name not in self.modelsData['models']: teamData[xmlName] = remod_name = next( (name for name in sorted(self.modelsData['models']) if remod_name in name), None) if remod_name is None or (remod_name and remod_name not in self.modelsData['models']): teamData[xmlName] = next( (name for name in sorted(self.modelsData['models']) if xmlName in self.settings[name]['whitelist'] and self.settings[name][team]), None) or '' loadJson(self.ID, 'remodsCache', selectedData, self.configPath, True, quiet=quiet) loadJson(self.ID, 'settings', self.settings, self.configPath, True, quiet=quiet)
def onHotkeyPressed(self, event): if (not hasattr(BigWorld.player(), 'databaseID') or not self.data['enabled'] or not event.isKeyDown() or self.isMSAOpen): return if self.modelsData['models'] and not self.previewRemod: if checkKeys(self.data['ChangeViewHotkey'], event.key): newModeNum = (self.teams.index(self.currentTeam) + 1) % len( self.teams) self.currentTeam = self.teams[newModeNum] try: from gui.mods.mod_skinner import g_config as _ _.currentTeam = self.currentTeam except ImportError: _ = None if self.data['isDebug']: print self.ID + ': changing display mode to', self.currentTeam SystemMessages.pushMessage( 'temp_SM%s<b>%s</b>' % (self.i18n['UI_mode'], self.i18n['UI_mode_' + self.currentTeam]), SystemMessages.SM_TYPE.Warning) refreshCurrentVehicle() if checkKeys(self.data['SwitchRemodHotkey'], event.key): curTankType = self.currentTeam snameList = sorted(self.modelsData['models'].keys()) + [''] selected = self.modelsData['selected'][curTankType] vehName = RemodEnablerUI.py_getCurrentVehicleName() if vehName not in selected: return snameIdx = (snameList.index(selected[vehName]) + 1) % len(snameList) for Idx in xrange(snameIdx, len(snameList) - 1): curPRecord = self.modelsData['models'][snameList[Idx]] if vehName not in curPRecord['whitelist']: continue selected[vehName] = curPRecord['name'] break else: selected[vehName] = '' loadJson(self.ID, 'remodsCache', self.modelsData['selected'], self.configPath, True, quiet=not self.data['isDebug']) refreshCurrentVehicle() if checkKeys(self.data['CollisionHotkey'], event.key): SystemMessages.pushMessage( 'temp_SM' + self.i18n['UI_collision_unavailable'], SystemMessages.SM_TYPE.CustomizationForGold) return # noinspection PyUnreachableCode self.collisionMode += 1 self.collisionMode %= 3 if self.collisionMode == 0: if self.data['isDebug']: print self.ID + ': disabling collision displaying' SystemMessages.pushMessage( 'temp_SM' + self.i18n['UI_collision_compare_disable'], SystemMessages.SM_TYPE.CustomizationForGold) elif self.collisionMode == 2: if self.data['isDebug']: print self.ID + ': enabling collision display comparison mode' SystemMessages.pushMessage( 'temp_SM' + self.i18n['UI_collision_compare_enable'], SystemMessages.SM_TYPE.CustomizationForGold) else: if self.data['isDebug']: print self.ID + ': enabling collision display' SystemMessages.pushMessage( 'temp_SM' + self.i18n['UI_collision_enable'], SystemMessages.SM_TYPE.CustomizationForGold) refreshCurrentVehicle()
def readCurrentSettings(self, quiet=True): super(ConfigInterface, self).readCurrentSettings() self.settings = loadJson(self.ID, 'settings', self.settings, self.configPath) self.skinsCache.update(loadJson(self.ID, 'skinsCache', self.skinsCache, self.configPath)) configsPath = self.configPath + 'remods/*.json' self.modelsData['enabled'] = bool(glob.glob(configsPath)) if self.modelsData['enabled']: self.modelsData['selected'] = selectedData = loadJson( self.ID, 'remodsCache', self.modelsData['selected'], self.configPath) for key in selectedData.keys(): if not key.islower(): selectedData[key.lower()] = selectedData.pop(key) snameList = set() for configPath in glob.iglob(configsPath): sname = os.path.basename(configPath).split('.')[0] confDict = loadJson(self.ID, sname, {}, os.path.dirname(configPath) + '/', encrypted=True) if not confDict: print self.ID + ': error while reading', os.path.basename(configPath) + '.' continue settingsDict = self.settings['remods'].setdefault(sname, {}) snameList.add(sname) if not settingsDict.setdefault('enabled', self.defaultRemodConfig['enabled']): print self.ID + ':', sname, 'disabled, moving on' if sname in self.modelsData['models']: del self.modelsData['models'][sname] continue self.modelsData['models'][sname] = pRecord = ModelDescriptor() pRecord.name = sname pRecord.authorMessage = confDict.get('authorMessage', '') for tankType in ('player', 'ally', 'enemy'): selected = selectedData[tankType] swapKey = 'swap' + tankType.capitalize() WLKey = tankType + 'Whitelist' whiteStr = settingsDict.setdefault(WLKey, confDict.get(WLKey, '')) templist = [x.strip() for x in whiteStr.split(',') if x] whitelist = pRecord.whitelists[tankType] whitelist.update(templist) if not whitelist: if self.data['isDebug']: print self.ID + ': empty whitelist for', sname + '. Not applied to', tankType, 'tanks.' else: if self.data['isDebug']: print self.ID + ': whitelist for', tankType + ':', list(whitelist) for xmlName in selected: if sname == selected[xmlName] and xmlName not in whitelist: selected[xmlName] = None if not settingsDict.setdefault(swapKey, confDict.get(swapKey, self.defaultRemodConfig[swapKey])): if self.data['isDebug']: print self.ID + ':', tankType, 'swapping in', sname, 'disabled.' whitelist.clear() for xmlName in selected: if sname == selected[xmlName]: selected[xmlName] = None for key, data in pRecord.data.iteritems(): if key == 'common': confSubDict = confDict else: confSubDict = confDict.get(key) if not confSubDict: continue if 'undamaged' in data: data['undamaged'] = confSubDict['undamaged'] if 'AODecals' in data and 'AODecals' in confSubDict and 'hullPosition' in confSubDict: data['AODecals'] = readAODecals(confSubDict['AODecals']) data['hullPosition'] = Math.Vector3(tuple(confSubDict['hullPosition'])) if 'camouflage' in data and 'exclusionMask' in confSubDict.get('camouflage', {}): data['camouflage']['exclusionMask'] = confSubDict['camouflage']['exclusionMask'] if 'tiling' in confSubDict['camouflage']: data['camouflage']['tiling'] = tuple(confDict['camouflage']['tiling']) elif key == 'common' and self.data['isDebug']: print self.ID + ': default camomask not found for', sname if 'emblemSlots' in data: data['emblemSlots'] = readEmblemSlots(confSubDict.get('emblemSlots', [])) if 'exhaust' in data: if 'nodes' in confSubDict.get('exhaust', {}): data['exhaust']['nodes'] = confSubDict['exhaust']['nodes'].split() if 'pixie' in confSubDict.get('exhaust', {}): data['exhaust']['pixie'] = confSubDict['exhaust']['pixie'] if key == 'chassis': for k in ('traces', 'tracks', 'wheels', 'groundNodes', 'trackNodes', 'splineDesc', 'trackParams'): data[k] = confSubDict[k] for subKey in ('effects', 'reloadEffect', 'wwsoundPC', 'wwsoundNPC'): if subKey in data and subKey in confSubDict: data[subKey] = confSubDict[subKey] if self.data['isDebug']: print self.ID + ': config for', sname, 'loaded.' for sname in self.modelsData['models'].keys(): if sname not in snameList: del self.modelsData['models'][sname] for sname in self.settings['remods'].keys(): if sname not in snameList: del self.settings['remods'][sname] if not self.modelsData['models']: if not quiet: print self.ID + ': no configs found, model module standing down.' self.modelsData['enabled'] = False loadJson(self.ID, 'remodsCache', selectedData, self.configPath, True, quiet=quiet) else: remodTanks = {key: set() for key in selectedData} for modelDesc in self.modelsData['models'].values(): for tankType, whitelist in modelDesc.whitelists.iteritems(): for xmlName in whitelist: remodTanks[tankType].add(xmlName) if xmlName not in selectedData[tankType]: selectedData[tankType][xmlName] = None for tankType in ('player', 'ally', 'enemy'): for xmlName in selectedData[tankType].keys(): if (selectedData[tankType][xmlName] and selectedData[tankType][ xmlName] not in self.modelsData['models']): selectedData[tankType][xmlName] = None if xmlName not in remodTanks[tankType]: del selectedData[tankType][xmlName] if selectedData['remod'] and selectedData['remod'] not in self.modelsData['models']: selectedData['remod'] = '' loadJson(self.ID, 'remodsCache', selectedData, self.configPath, True, quiet=quiet) else: if not quiet: print self.ID + ': no remods found, model module standing down.' self.modelsData['enabled'] = False loadJson(self.ID, 'remodsCache', self.modelsData['selected'], self.configPath, True, quiet=quiet) self.skinsData['enabled'] = ResMgr.openSection('vehicles/skins/') is not None and ResMgr.isDir('vehicles/skins/') if self.skinsData['enabled']: self.skinsData['priorities'] = loadJson(self.ID, 'skinsPriority', self.skinsData['priorities'], self.configPath) skinDir = 'vehicles/skins/textures/' for skinTypeSuff in ('', '_dynamic'): skinType = 'static' if not skinTypeSuff else skinTypeSuff[1:] for key in self.skinsData['priorities'][skinType].keys(): if not key.islower(): self.skinsData['priorities'][skinType][key.lower()] = self.skinsData['priorities'][skinType].pop(key) skinsSettings = self.settings['skins' + skinTypeSuff] disabledSkins = [] if self.data['isDebug']: print self.ID + ': loading configs for', skinType, 'skins' skinDirSect = ResMgr.openSection(skinDir) for sname in [] if skinDirSect is None else remDups(skinDirSect.keys()): confDict = skinsSettings.setdefault(sname, self.defaultSkinConfig[skinType]) if not confDict.get('enabled', True): print self.ID + ':', sname, 'disabled, moving on' disabledSkins.append(sname) continue self.skinsData['models'][skinType][sname] = pRecord = {'name': '', 'whitelist': set()} pRecord['name'] = sname priorities = self.skinsData['priorities'][skinType] for tankType in priorities: key = 'swap' + tankType.capitalize() if not confDict.setdefault(key, self.defaultSkinConfig[skinType][key]): if self.data['isDebug']: print self.ID + ':', tankType, 'swapping in', sname, 'disabled.' if sname in priorities[tankType]: priorities[tankType].remove(sname) continue if sname not in priorities[tankType]: priorities[tankType].append(sname) pRecord['whitelist'].clear() vehiclesDirPath = skinDir + sname + '/vehicles/' vehiclesDirSect = ResMgr.openSection(vehiclesDirPath) for curNation in [] if vehiclesDirSect is None else remDups(vehiclesDirSect.keys()): nationDirPath = vehiclesDirPath + curNation + '/' nationDirSect = ResMgr.openSection(nationDirPath) for vehicleName in [] if nationDirSect is None else remDups(nationDirSect.keys()): vehDirPath = nationDirPath + vehicleName + '/' vehDirSect = ResMgr.openSection(vehDirPath) tracksDirPath = vehDirPath + 'tracks/' tracksDirSect = ResMgr.openSection(tracksDirPath) if not any(texName.endswith('.dds') for texName in ( ([] if vehDirSect is None else remDups(vehDirSect.keys())) + ([] if tracksDirSect is None else remDups(tracksDirSect.keys())))): if self.data['isDebug']: print self.ID + ':', vehicleName, 'folder from', sname, 'pack is empty.' else: pRecord['whitelist'].add(vehicleName) if self.data['isDebug']: print self.ID + ': config for', sname, 'loaded.' snameList = self.skinsData['models'][skinType].keys() + disabledSkins for sname in skinsSettings.keys(): if sname not in snameList: del skinsSettings[sname] if not any(self.skinsData['models'].values()): if not quiet: print self.ID + ': no skins configs found, skins module standing down.' self.skinsData['enabled'] = False for skinType in self.skinsData['priorities']: for key in self.skinsData['priorities'][skinType]: self.skinsData['priorities'][skinType][key] = [] else: for skinType in self.skinsData['priorities']: for key in self.skinsData['priorities'][skinType]: for sname in list(self.skinsData['priorities'][skinType][key]): if sname not in self.skinsData['models'][skinType]: self.skinsData['priorities'][skinType][key].remove(sname) else: if not quiet: print self.ID + ': no skins found, skins module standing down.' for skinType in self.skinsData['priorities']: for key in self.skinsData['priorities'][skinType]: self.skinsData['priorities'][skinType][key] = [] loadJson(self.ID, 'skinsPriority', self.skinsData['priorities'], self.configPath, True, quiet=quiet) loadJson(self.ID, 'settings', self.settings, self.configPath, True, quiet=quiet)
def readCurrentSettings(self, quiet=True): configPath = self.configPath + 'configs/' if not os.path.exists(configPath): LOG_ERROR('config folder not found: ' + configPath) os.makedirs(configPath) for confPath in glob.iglob(configPath + '*.json'): confName = os.path.basename(confPath).split('.')[0] try: confdict = loadJson(self.ID, confName, {}, os.path.dirname(confPath) + '/') except StandardError: print self.ID + ': config', os.path.basename( confPath), 'is invalid.' traceback.print_exc() continue self.confList.add(confName) for itemType, itemsDict in confdict.iteritems(): if itemType not in self.data: if not quiet: print self.ID + ': invalid item type in', confName + ':', itemType continue itemsData = self.data[itemType] if itemType in ('engines', 'guns'): for nationName, nationData in itemsDict.iteritems(): if nationName.split(':')[0] not in nations.NAMES: print self.ID + ': unknown nation in', itemType, 'data:', nationName continue itemsData.setdefault(nationName, {}).update(nationData) if itemType in ('gun_reload_effects', 'shot_effects', 'sound_notifications'): for itemName in itemsDict: itemsData.setdefault(itemName, {}).update(itemsDict[itemName]) print self.ID + ': loaded configs:', ', '.join( x + '.json' for x in sorted(self.confList)) newXmlPath = '../' + self.configPath + 'configs/gun_effects.xml' if ResMgr.isFile(newXmlPath): g_cache._gunEffects.update( items.vehicles._readEffectGroups(newXmlPath)) elif self.data['guns']: print self.ID + ': gun effects config not found' for item_type, items_storage in (('engines', g_cache._Cache__engines), ('guns', g_cache._Cache__guns)): for nationID, nation_items in enumerate(items_storage): nationData = self.data[item_type].get(nations.NAMES[nationID]) if not nationData: continue for item in nation_items.itervalues(): itemData = nationData.get(item.name) if not itemData: continue if item_type == 'engines': s = item.sounds.getEvents() item.sounds = SoundConfig( '', itemData.get('wwsoundPC', s[0]), itemData.get('wwsoundNPC', s[1])) elif item_type == 'guns' and 'effects' in itemData: item.effects = items.vehicles.g_cache._gunEffects.get( itemData['effects'], item.effects) for sname, descr in g_cache._gunReloadEffects.iteritems(): effData = self.data['gun_reload_effects'].get(sname) if effData is None: continue descr.duration = float( effData.get('duration', descr.duration * 1000.0)) / 1000.0 descr.soundEvent = effData.get('sound', descr.soundEvent) if effData['type'] == 'BarrelReload' and isinstance( descr, _BarrelReloadDesc): descr.lastShellAlert = effData.get('lastShellAlert', descr.lastShellAlert) descr.shellDuration = effData.get( 'shellDuration', descr.shellDuration * 1000.0) / 1000.0 descr.startLong = effData.get('startLong', descr.startLong) descr.startLoop = effData.get('startLoop', descr.startLoop) descr.stopLoop = effData.get('stopLoop', descr.stopLoop) descr.loopShell = effData.get('loopShell', descr.loopShell) descr.loopShellLast = effData.get('loopShellLast', descr.loopShellLast) descr.ammoLow = effData.get('ammoLow', descr.ammoLow) descr.caliber = effData.get('caliber', descr.caliber) descr.shellDt = effData.get('loopShellDt', descr.shellDt) descr.shellDtLast = effData.get('loopShellLastDt', descr.shellDtLast) for sname, index in g_cache.shotEffectsIndexes.iteritems(): effData = self.data['shot_effects'].get(sname) if effData is None: continue res = g_cache.shotEffects[index] for effType in (x for x in ('projectile', ) if x in effData): typeData = effData[effType] for effectDesc in res[effType][2]._EffectsList__effectDescList: if isinstance(effectDesc, _TracerSoundEffectDesc): effectDesc._soundName = tuple( (typeData.get(key, effectDesc._soundName[idx]), ) for idx, key in enumerate(('wwsoundPC', 'wwsoundNPC'))) for effType in (x for x in ( tuple(x + 'Hit' for x in EFFECT_MATERIALS) + ('armorBasicRicochet', 'armorRicochet', 'armorResisted', 'armorHit', 'armorCriticalHit')) if x in effData): typeData = effData[effType] for effectDesc in res[ effType].effectsList._EffectsList__effectDescList: if isinstance(effectDesc, _SoundEffectDesc): effectDesc._impactNames = tuple( typeData.get(key, effectDesc._impactNames[idx]) for idx, key in enumerate(('impactNPC_PC', 'impactPC_NPC', 'impactNPC_NPC'))) for vehicleType in g_cache._Cache__vehicles.itervalues(): self.inject_vehicleType(vehicleType)