Пример #1
0
def init():
    global g_gameplayNames
    global g_cache
    global g_geometryNamesToIDs
    global g_gameplaysMask
    rootSection = ResMgr.openSection(ARENA_TYPE_XML_PATH + '_list_.xml')
    if rootSection is None:
        raise Exception("Can't open '%s'" % (ARENA_TYPE_XML_PATH + '_list_.xml'))
    defaultXml = ResMgr.openSection(_DEFAULT_XML)
    if defaultXml is None:
        raise Exception("Can't open '%s'" % _DEFAULT_XML)
    defaultGameplayTypesXml = defaultXml['gameplayTypes']
    if defaultGameplayTypesXml is None or not defaultGameplayTypesXml:
        raise Exception("No defaults for 'gameplayTypes'")
    geometriesSet = set()
    for key, value in rootSection.items():
        geometryID = value.readInt('id')
        if geometryID in geometriesSet:
            raise Exception('Geometry ID=%d is not unique' % geometryID)
        geometriesSet.add(geometryID)
        __buildCache(geometryID, value.readString('name'), defaultXml)

    g_gameplaysMask = getGameplaysMask(g_gameplayNames)
    g_geometryNamesToIDs = dict([ (arenaType.geometryName, arenaType.geometryID) for arenaType in g_cache.itervalues() ])
    return
Пример #2
0
    def __init__(self):
        global _HANGAR_CFGS
        global _DEFAULT_CFG
        global _CFG
        self.__spaceId = None
        self.__cam = None
        self.__waitCallback = None
        self.__loadingStatus = 0.0
        self.__destroyFunc = None
        self.__spaceMappingId = None
        self.__onLoadedCallback = None
        self.__boundingRadius = None
        self.__vAppearance = None
        self.__vEntityId = None
        self.__savedInputHandler = None
        self.__selectedEmblemInfo = None
        hangarsXml = ResMgr.openSection('gui/hangars.xml')
        for isPremium in (False, True):
            spacePath = _DEFAULT_HANGAR_SPACE_PATH_PREM if isPremium else _DEFAULT_HANGAR_SPACE_PATH_BASIC
            settingsXml = ResMgr.openSection(spacePath + '/space.settings/hangarSettings')
            cfg = {'path': spacePath}
            self.__loadConfig(cfg, settingsXml)
            self.__loadConfigValue('fakeShadowMapModelName', hangarsXml, hangarsXml.readString, cfg)
            self.__loadConfigValue('fakeShadowMapDefaultTexName', hangarsXml, hangarsXml.readString, cfg)
            self.__loadConfigValue('fakeShadowMapEmptyTexName', hangarsXml, hangarsXml.readString, cfg)
            _DEFAULT_CFG[self.getSpaceType(isPremium)] = cfg
            _HANGAR_CFGS[spacePath.lower()] = settingsXml

        for folderName, folderDS in ResMgr.openSection('spaces').items():
            settingsXml = ResMgr.openSection('spaces/' + folderName + '/space.settings/hangarSettings')
            if settingsXml is not None:
                _HANGAR_CFGS[('spaces/' + folderName).lower()] = settingsXml

        _CFG = copy.copy(_DEFAULT_CFG[self.getSpaceType(False)])
        return
Пример #3
0
 def typeShell(self, effectsIndex):
     self.data['costShell'] = 'unknown'
     self.data['shellKind'] = 'not_shell'
     if (self.data['attackerID'] == 0) or (self.data['attackReasonID'] != 0):
         return
     player = BigWorld.player()
     attacker = player.arena.vehicles.get(self.data['attackerID'])
     if (attacker is None) or not attacker['vehicleType']:
         self.data['shellKind'] = None
         self.data['caliber'] = None
         self.data['costShell'] = None
         return
     for shell in attacker['vehicleType'].gun['shots']:
         if effectsIndex == shell['shell']['effectsIndex']:
             self.data['shellKind'] = str(shell['shell']['kind']).lower()
             self.data['caliber'] = shell['shell']['caliber']
             xmlPath = ITEM_DEFS_PATH + 'vehicles/' + nations.NAMES[shell['shell']['id'][0]] + '/components/shells.xml'
             for name, subsection in ResMgr.openSection(xmlPath).items():
                 if name != 'icons':
                     xmlCtx = (None, xmlPath + '/' + name)
                     if _xml.readInt(xmlCtx, subsection, 'id', 0, 65535) == shell['shell']['id'][1]:
                         price = _xml.readPrice(xmlCtx, subsection, 'price')
                         self.data['costShell'] = 'gold-shell' if price[1] else 'silver-shell'
                         break
             ResMgr.purge(xmlPath, True)
             break
Пример #4
0
def _init():
    res = [_UNKNOWN_VEHICLE_DATA]
    try:
        for nation in nations.NAMES:
            nationID = nations.INDICES[nation]
            for (id, descr) in vehicles.g_list.getList(nationID).iteritems():
                if descr['name'].endswith('training'):
                    continue

                item = vehicles.g_cache.vehicle(nationID, id)
                #log('%i	%i	%s	%s' % (descr['level'], descr['compactDescr'], descr['name'], descr['shortUserString']))

                data = dict()
                data['vehCD'] = descr['compactDescr']
                data['key'] = descr['name']
                data['nation'] = nation
                data['level'] = descr['level']
                data['vclass'] = tuple(vehicles.VEHICLE_CLASS_TAGS & descr['tags'])[0]
                data['localizedName'] = descr['shortUserString']
                data['localizedShortName'] = descr['shortUserString']
                data['localizedFullName'] = descr['userString']
                data['premium'] = 'premium' in descr['tags']

                stockTurret = item.turrets[0][0]
                topTurret = item.turrets[0][-1]
                topGun = topTurret['guns'][-1]

                if len(item.hulls) != 1:
                    log('WARNING: TODO: len(hulls) != 1 for vehicle ' + descr['name'])
                data['hpStock'] = item.hulls[0]['maxHealth'] + stockTurret['maxHealth']
                data['hpTop'] = item.hulls[0]['maxHealth'] + topTurret['maxHealth']
                data['turret'] = _getTurretType(item, nation)
                (data['visRadius'], data['firingRadius'], data['artyRadius']) = \
                    _getRanges(topTurret, topGun, data['nation'], data['vclass'])

                (data['tierLo'], data['tierHi']) = getTiers(data['level'], data['vclass'], data['key'])

                data['shortName'] = vehinfo_short.getShortName(data['key'], data['level'], data['vclass'])

                wn8data = vehinfo_wn8.getWN8ExpectedData(data['vehCD'])
                if wn8data is not None:
                    data['wn8expDamage'] = float(wn8data['expDamage'])
                    data['wn8expSpot'] = float(wn8data['expSpot'])
                    data['wn8expWinRate'] = float(wn8data['expWinRate'])
                    data['wn8expDef'] = float(wn8data['expDef'])
                    data['wn8expFrag'] = float(wn8data['expFrag'])

                # is reserved?
                import xvm_tankcarousel.python.reserve as reserve
                data['isReserved'] = reserve.is_reserved(data['vehCD'])
                #log(data)

                res.append(data)

            ResMgr.purge(_VEHICLE_TYPE_XML_PATH + nation + '/components/guns.xml', True)

        vehinfo_short.checkNames(res)

    except Exception, ex:
        err(traceback.format_exc())
Пример #5
0
 def reload(self):
     if not constants.IS_DEVELOPMENT:
         return
     import ResMgr
     ResMgr.purge('gui/avatar_input_handler.xml')
     cameraSec = ResMgr.openSection('gui/avatar_input_handler.xml/arcadeMode/camera/')
     self.__readCfg(cameraSec)
Пример #6
0
def _parameterCheck(pos, modelPath, nodes, parameter, tank, comp):
    modelSec = ResMgr.openSection(modelPath)
    if modelSec is None:
        print 'Error loading ',
        print modelPath
        return 
    visualFile = modelSec.readString('nodefullVisual') + '.visual'
    sec = ResMgr.openSection(visualFile)
    if sec is None:
        print "Error: can't find visual %s" % visualFile
        return 
    translation = Math.Vector3()
    for node in nodes:
        sec = _findNodeSec(sec, node)
        if sec is None:
            print "Error: cant't find node %s in visual %s" % (node, visualFile)
            return 
        translation += sec.readVector3('transform/row3')

    if (translation - pos).length > EPSILON:
        print 'Error: %s parameter is incorrect\n   Model:\t %s\n   Tank:\t  %s\n   Component: %s\n   Note: it must be <%s>' % (parameter,
         modelPath,
         tank,
         comp,
         translation)
Пример #7
0
def _readNationConfig(xmlPath):
    section = ResMgr.openSection(xmlPath)
    if section is None:
        _xml.raiseWrongXml(None, xmlPath, 'can not open or read')
    res = _readNationConfigSection((None, xmlPath), section)
    section = None
    ResMgr.purge(xmlPath, True)
    return res
Пример #8
0
 def shell(self):                
     xmlPath = ''
     for nation in nations.NAMES:
         xmlPath = '%s%s%s%s' % (ITEM_DEFS_PATH, 'vehicles/', nation, '/components/shells.xml')
         xmlCtx_s = (((None, '{}/{}'.format(xmlPath, n)), s) for n, s in ResMgr.openSection(xmlPath).items() if (n != 'icons') and (n != 'xmlns:xmlref'))
         id_xmlCtx_s = ((_xml.readInt(xmlCtx, s, 'id', 0, 65535), xmlCtx, s) for xmlCtx, s in xmlCtx_s)
         self.shells[nation] = [i for i, xmlCtx, s in id_xmlCtx_s if s.readBool('improved', False)]
     ResMgr.purge(xmlPath, True)
Пример #9
0
 def readFromExternalFile(self, path, gStartTime, gFinishTime, curTime):
     ResMgr.purge(path)
     section = ResMgr.openSection(path)
     if section is None:
         raise Exception("Can not open '%s'" % path)
     if not section.has_key('quests'):
         return {}
     else:
         return self.__readXML(section['quests'], gStartTime, gFinishTime, curTime)
Пример #10
0
 def reload(self):
     if constants.IS_DEVELOPMENT:
         import ResMgr
         ResMgr.purge('gui/avatar_input_handler.xml')
         cameraSec = ResMgr.openSection('gui/avatar_input_handler.xml/strategicMode/camera/')
         self._StrategicCamera__readCfg(cameraSec)
         return
     else:
         return
Пример #11
0
 def reloadDynamicSettings(self):
     if not constants.IS_DEVELOPMENT:
         return
     ResMgr.purge(_INPUT_HANDLER_CFG)
     sec = ResMgr.openSection(_INPUT_HANDLER_CFG)
     self.__dynamicCameraSettings = DynamicCameraSettings(sec['dynamicCameraCommon'])
     try:
         self.__ctrls['sniper'].camera.aimingSystem.reloadConfig(sec['sniperMode']['camera'])
     except:
         pass
Пример #12
0
    def getAvailableIntroVideoFiles():
        ds = ResMgr.openSection(GuiDirReader.SCALEFORM_STARTUP_VIDEO_PATH)
        movieFiles = []
        for filename in ds.keys():
            basename, extension = filename.split('.')
            if extension == GuiDirReader.VIDEO_EXTENSION and basename[0:1] != '_':
                movieFiles.append(GuiDirReader.SCALEFORM_STARTUP_VIDEO_MASK % filename)

        ResMgr.purge(GuiDirReader.SCALEFORM_STARTUP_VIDEO_PATH, True)
        return movieFiles
Пример #13
0
def loadDescriptorData(filePath, exParsers = None, clearCache = False):
    try:
        if exParsers is not None:
            imported = __import__(exParsers, globals(), locals(), ['init'])
            getattr(imported, 'init')()
        if clearCache:
            ResMgr.purge(filePath)
        return DescriptorParser().parse(filePath)
    except Exception:
        LOG_CURRENT_EXCEPTION()
        return
Пример #14
0
def root_generator(filePath):
    try:
        ctx, section = getRoot(filePath)
    except ResourceError as error:
        raise error
    else:
        try:
            yield (ctx, section)
        except:
            LOG_CURRENT_EXCEPTION()
        finally:
            ResMgr.purge(filePath, True)
Пример #15
0
def list_directory(vfs_directory):
    """
    Returns list of elements in a directory within a wotmod package.

    :param vfs_directory: directory path within a package
    :return: list of elements
    """
    result = []
    folder = ResMgr.openSection(vfs_directory)
    if folder is not None and ResMgr.isDir(vfs_directory):
        for name in folder.keys():
            if name not in result:
                result.append(name)
    return sorted(result)
Пример #16
0
def _dataSectionFromFilename(filename, createIfMissing = False):
    """
    This method returns a data section, given a data section
    or a filename
    """
    ds = None
    if isinstance(filename, ResMgr.DataSection):
        ds = filename
    else:
        ds = ResMgr.openSection(filename, createIfMissing)
        if ds == None:
            basePath = 'system/post_processing/chains/'
            ds = ResMgr.openSection(basePath + filename, createIfMissing)
    return ds
Пример #17
0
def loadDescriptorData(setting, exParsers = None, clearCache = False):
    try:
        if exParsers is not None:
            imported = __import__(exParsers, globals(), locals(), ['init'])
            getattr(imported, 'init')()
        if clearCache:
            ResMgr.purge(setting.descriptorPath)
        classPath = setting.descriptorParser
        parser = settings.createTutorialElement(classPath)
        return parser.parse(setting.descriptorPath)
    except Exception:
        LOG_CURRENT_EXCEPTION()
        return

    return
Пример #18
0
def read_file(vfs_path, read_as_binary=True):
    """
    Reads a file from a wotmod package.

    :param vfs_path:       path within a package
    :param read_as_binary: read file in binary or text mode
    :return: file contents a string
    """
    vfs_file = ResMgr.openSection(vfs_path)
    if vfs_file is not None and ResMgr.isFile(vfs_path):
        if read_as_binary:
            return str(vfs_file.asBinary)
        else:
            return str(vfs_file.asString)
    return None
Пример #19
0
    def __init__(self, initialModeName):
        if SoundModes.MEDIA_PATH is None:
            engineConfig = ResMgr.openSection('engine_config.xml')
            if engineConfig is not None:
                SoundModes.MEDIA_PATH = engineConfig.readString('soundMgr/mediaPath', 'audio')
            else:
                SoundModes.MEDIA_PATH = 'audio'
        self.__modes = {}
        self.__currentMode = SoundModes.DEFAULT_MODE_NAME
        self.__nationalPresets = {}
        self.__nationToSoundModeMapping = {'default': SoundModes.DEFAULT_MODE_NAME}
        self.__currentNationalPreset = (SoundModes.DEFAULT_MODE_NAME, False)
        self.modifiedSoundGroups = []
        modesSettingsSection = ResMgr.openSection(SoundModes.__MODES_FOLDER + SoundModes.__MODES_FILENAME)
        if modesSettingsSection is None:
            LOG_ERROR('%s is not found' % SoundModes.__MODES_FILENAME)
            return
        else:
            soundModes, nationalPresets = self.__readSoundModesConfig(modesSettingsSection, self.__nationalPresets)
            self.__modes = dict(((soundMode.name, soundMode) for soundMode in soundModes))
            self.__nationalPresets = dict(((preset.name, preset) for preset in nationalPresets))
            if SoundModes.DEFAULT_MODE_NAME not in self.__modes:
                LOG_ERROR('Default sound mode is not found!')
            modifiedSoundGroupsSection = modesSettingsSection['modified_sound_groups']
            if modifiedSoundGroupsSection is not None:
                self.modifiedSoundGroups = modifiedSoundGroupsSection.readStrings('sound_group')
            folderSection = ResMgr.openSection(SoundModes.__MODES_FOLDER)
            if folderSection is None:
                LOG_ERROR("Folder for SoundModes: '%s' is not found!" % SoundModes.__MODES_FOLDER)
            else:
                defaultNationalPresets = dict(self.__nationalPresets)
                for modesConfigSection in folderSection.values():
                    if modesConfigSection.name != SoundModes.__MODES_FILENAME:
                        soundModes, nationalPresets = self.__readSoundModesConfig(modesConfigSection, defaultNationalPresets)
                        for mode in soundModes:
                            if self.__modes.has_key(mode.name):
                                LOG_WARNING("%s config tries to redefine soundMode '%s', ignored" % (modesConfigSection.name, mode.name))
                            else:
                                self.__modes[mode.name] = mode

                        for preset in nationalPresets:
                            if self.__nationalPresets.has_key(preset.name):
                                LOG_WARNING("%s config tries to redefine nationalPreset '%s', ignored" % (preset.name, preset.name))
                            else:
                                self.__nationalPresets[preset.name] = preset

            self.setMode(initialModeName)
            return
Пример #20
0
    def __init__(self):
        global _HANGAR_CFGS
        global _DEFAULT_CFG
        global _CFG
        self.__spaceId = None
        self.__cam = None
        self.__waitCallback = None
        self.__loadingStatus = 0.0
        self.__destroyFunc = None
        self.__spaceMappingId = None
        self.__onLoadedCallback = None
        self.__boundingRadius = None
        self.__vAppearance = None
        self.__vEntityId = None
        self.__isMouseDown = False
        self.__igrHangarPathKey = 'igrPremHangarPath' + ('CN' if constants.IS_CHINA else '')
        self.__selectedEmblemInfo = None
        self.__showMarksOnGun = False
        self.__fakeShadowId = None
        self.__fakeShadowAsset = None
        self.__fakeShadowScale = 1.0
        self.__prevDirection = 0.0
        self.__camDistConstr = ((0.0, 0.0), (0.0, 0.0))
        self.__locatedOnEmbelem = False
        hangarsXml = ResMgr.openSection('gui/hangars.xml')
        for isPremium in (False, True):
            spacePath = _DEFAULT_HANGAR_SPACE_PATH_PREM if isPremium else _DEFAULT_HANGAR_SPACE_PATH_BASIC
            settingsXml = ResMgr.openSection(spacePath + '/space.settings')
            settingsXml = settingsXml['hangarSettings']
            cfg = {'path': spacePath,
             'cam_yaw_constr': Math.Vector2(-180, 180),
             'cam_pitch_constr': Math.Vector2(-70, -5)}
            self.__loadConfig(cfg, settingsXml)
            self.__loadConfigValue('shadow_model_name', hangarsXml, hangarsXml.readString, cfg)
            self.__loadConfigValue('shadow_default_texture_name', hangarsXml, hangarsXml.readString, cfg)
            self.__loadConfigValue('shadow_empty_texture_name', hangarsXml, hangarsXml.readString, cfg)
            self.__loadConfigValue(self.__igrHangarPathKey, hangarsXml, hangarsXml.readString, cfg)
            _DEFAULT_CFG[self.getSpaceType(isPremium)] = cfg
            _HANGAR_CFGS[spacePath.lower()] = settingsXml

        for folderName, folderDS in ResMgr.openSection('spaces').items():
            settingsXml = ResMgr.openSection('spaces/' + folderName + '/space.settings/hangarSettings')
            if settingsXml is not None:
                _HANGAR_CFGS[('spaces/' + folderName).lower()] = settingsXml

        _CFG = copy.copy(_DEFAULT_CFG[self.getSpaceType(False)])
        self.__yawCameraFilter = HangarCameraYawFilter(math.radians(_CFG['cam_yaw_constr'][0]), math.radians(_CFG['cam_yaw_constr'][1]), _CFG['cam_sens'])
        return
Пример #21
0
def loadDescriptorData(setting, exParsers = None, clearCache = False):
    try:
        if exParsers is not None:
            imported = __import__(exParsers, globals(), locals(), ['init'])
            getattr(imported, 'init')()
        if clearCache:
            ResMgr.purge(setting.descriptorPath)
        classPath = setting.descriptorParser
        imported = __import__(classPath.module, globals(), locals(), [classPath.clazz])
        if not imported:
            raise ValueError('Can not find class {0.module} in {0.clazz}'.format(classPath))
        clazz = getattr(imported, classPath.clazz)
        return clazz().parse(setting.descriptorPath)
    except Exception:
        LOG_CURRENT_EXCEPTION()
        return
Пример #22
0
 def __loadConfig(self):
     xmlPath = 'gui/gui_sounds.xml'
     section = ResMgr.openSection(xmlPath)
     if section is None:
         _xml.raiseWrongXml(None, xmlPath, 'can not open or read')
     for (groupName, types,) in section.items():
         self.__soundEvents[groupName] = SoundSettings.populateSettings(types)
Пример #23
0
def _preloadBufferedOneShotEffect(fileName, maxDuration = 10.0, prereqs = None):
    """This method preloads the whole effect buffer given by fileName.
    If no prerequisites are passed in, then the entire buffer is synchronously
    created.  This may create a pause in the rendering thread.
    If prerequisites are provided, it immediately queues up one effect, and
    then asnychronously loads the rest.
    """
    pSection = None
    if prereqs != None:
        pSection = prereqs[fileName]
    else:
        pSection = ResMgr.openSection(fileName)
    if not pSection:
        ERROR_MSG('Could not open file', fileName)
        return False
    else:
        _effectBuffer[fileName] = Queue()
        queue = _effectBuffer[fileName]
        bufferSize = pSection.readInt('bufferSize', 5)
        if prereqs != None:
            resourceIDs = tuple(prereqs.keys())
            queue.put(_BufferedOneShot(fileName, maxDuration, queue, prereqs))
            for i in xrange(0, bufferSize - 1):
                BigWorld.loadResourceListBG(resourceIDs, partial(_onAsyncLoadBufferedEffect, fileName, maxDuration))

        else:
            for i in xrange(0, bufferSize):
                queue.put(_BufferedOneShot(fileName, maxDuration, queue))

        return True
Пример #24
0
 def _readVersion(cls):
     dSection = ResMgr.openSection(VERSION_FILE_PATH)
     if dSection is None:
         LOG_ERROR('Can not open file:', VERSION_FILE_PATH)
         IngameHelp.__version = -1
         return 
     IngameHelp.__version = dSection.readInt('ingameHelpVersion', -1)
Пример #25
0
            def getShellPrice(nationID, shellID):
                import ResMgr, nations
                from items import _xml, vehicles
                from constants import ITEM_DEFS_PATH

                price = {}
                xmlPath = ITEM_DEFS_PATH + 'vehicles/' + nations.NAMES[nationID] + '/components/shells.xml'
                for name, subsection in ResMgr.openSection(xmlPath).items():
                    if name != 'icons':
                        xmlCtx = (None, xmlPath + '/' + name)
                        if _xml.readInt(xmlCtx, subsection, 'id', 0, 65535) == shellID:
                            price = _xml.readPrice(xmlCtx, subsection, 'price')
                            break
                ResMgr.purge(xmlPath, True)

                return price
	def __init__(self):
		sect = ResMgr.openSection( graphicsPresetsResource )
		
		# Entries is a dictionary of dictionaries of graphics presets
		self.entries = {}
		# Entry names is a list of the names of the entries in the
		# order they appear in the presets file
		self.entryNames = []
		# The currently selected option as an index into entry names
		# -1 means no preselected option selected (i.e. advanced settings)
		self.selectedOption = -1

		# load up the preset groups
		for group in sect.values():
			# only allow named groups
			if group.asString != "":
				# init the map for the current entry
				entry = {}
				# create the entries for this group
				for setting in group.values():
					if setting.name == 'entry':
						entry[setting.readString('label')] = setting.readInt('activeOption')
				
				# add the entry to the dictionary and add the name to the entry list
				self.entries[group.asString] = entry
				self.entryNames.append(group.asString)
		
		self.setSelectedOption()
Пример #27
0
 def getStatistics(self, andStop = True):
     proceed = self.__state == _STATISTICS_STATE.IN_PROGRESS
     ret = {}
     if proceed:
         ret = BigWorld.wg_getClientStatistics()
         proceed = ret is not None
         if proceed:
             ret['cpuScore'] = BigWorld.getAutoDetectGraphicsSettingsScore(_HARDWARE_SCORE_PARAMS.PARAM_CPU_SCORE)
             ret['gpuScore'] = BigWorld.getAutoDetectGraphicsSettingsScore(_HARDWARE_SCORE_PARAMS.PARAM_GPU_SCORE)
             ret['ping'] = int(math.ceil(self.avrPing))
             ret['lag'] = self.lagPercentage
             ret['graphicsEngine'] = SettingsCore.g_settingsCore.getSetting(GRAPHICS.RENDER_PIPELINE)
             if not self.__hangarLoaded:
                 self.__invalidStats |= INVALID_CLIENT_STATS.CLIENT_STRAIGHT_INTO_BATTLE
             ret['graphicsPreset'] = SettingsCore.g_settingsCore.getSetting(GRAPHICS.PRESETS)
             windowMode = SettingsCore.g_settingsCore.getSetting(GRAPHICS.FULLSCREEN)
             ret['windowMode'] = 1 if windowMode else 0
             resolutionContainer = graphics.g_monitorSettings.currentVideoMode if windowMode else graphics.g_monitorSettings.currentWindowSize
             ret['screenResWidth'] = resolutionContainer.width
             ret['screenResHeight'] = resolutionContainer.height
             ret['drrScale'] = int(round(BigWorld.getDRRScale() * 100))
             ret['dynamicDRR'] = BigWorld.isDRRAutoscalingEnabled()
             ret['invalidStats'] |= self.__invalidStats
             ret['contentType'] = ResMgr.activeContentType()
     if andStop is True or not proceed:
         self.stop()
     return ret
Пример #28
0
def merge(dataSection, addEffectIfMissing = False):
    """
    This method loads a chain from XML and merges it with the
    existing chain.  Effects with the same name as any of those
    loaded via XML will be replaced.
    """
    dataSection = _dataSectionFromFilename(dataSection)
    from Effects import Properties
    ds = ResMgr.openSection(dataSection)
    oldEffects = chain()
    newEffects = load(ds)
    ch = []
    for old in oldEffects:
        found = False
        for nw in newEffects:
            if old.name == nw.name:
                ch.append(nw)
                found = True
                break

        if not found:
            ch.append(old)

    if addEffectIfMissing == True:
        for nw in newEffects:
            found = False
            for old in ch:
                if old.name == nw.name:
                    found = True
                    break

            if not found:
                pass

    chain(*ch)
Пример #29
0
def _getRanges(turret, gun, nation, vclass):
    visionRadius = firingRadius = artyRadius = 0
    gunsInfoPath = _VEHICLE_TYPE_XML_PATH + nation + '/components/guns.xml/shared/'

    # Turret-dependent
    visionRadius = int(turret['circularVisionRadius'])  # 240..420

    # Gun-dependent
    shots = gun['shots']
    for shot in shots:
        radius = int(shot['maxDistance'])
        if firingRadius < radius:
            firingRadius = radius  # 10000, 720, 395, 360, 350

        if vclass == 'SPG' and shot['shell']['kind'] == 'HIGH_EXPLOSIVE':
            try:    # faster way
                pitchLimit_rad = min(CONST_45_IN_RADIANS, -calcPitchLimitsFromDesc(0, gun['pitchLimits']))
            except Exception: # old way
                gunsInfoPath = _VEHICLE_TYPE_XML_PATH + nation + '/components/guns.xml/shared/'
                pitchLimit = ResMgr.openSection(gunsInfoPath + gun['name']).readInt('pitchLimits')
                pitchLimit = min(45, -pitchLimit)  # -35..-65
                pitchLimit_rad = radians(pitchLimit)

            radius = int(pow(shot['speed'], 2) * sin(2 * pitchLimit_rad) / shot['gravity'])
            if artyRadius < radius:
                artyRadius = radius  # 485..1469

    return (visionRadius, firingRadius, artyRadius)
Пример #30
0
 def __loadCustomSounds(self, spacePath):
     xmlName = spacePath.split('/')[-1]
     settings = ResMgr.openSection('scripts/arena_defs/' + xmlName + '.xml')
     if settings is None:
         return
     else:
         musicName = settings.readString('music')
         if FMOD.enabled:
             ambientName = settings.readString('ambientSound')
         combatVictory = settings.readString('combatVictory')
         combatLose = settings.readString('combatLose')
         combatDraw = settings.readString('combatDraw')
         if musicName:
             self.__updateOverridden(MUSIC_EVENT_LOBBY, _CLIENT_OVERRIDDEN, (musicName, musicName))
         if combatVictory:
             self.__updateOverridden(MUSIC_EVENT_COMBAT_VICTORY, _CLIENT_OVERRIDDEN, combatVictory)
         if combatLose:
             self.__updateOverridden(MUSIC_EVENT_COMBAT_LOSE, _CLIENT_OVERRIDDEN, combatLose)
         if combatDraw:
             self.__updateOverridden(MUSIC_EVENT_COMBAT_DRAW, _CLIENT_OVERRIDDEN, combatDraw)
         if ambientName:
             self.__updateOverridden(AMBIENT_EVENT_LOBBY, _CLIENT_OVERRIDDEN, (ambientName, ambientName))
             self.__updateOverridden(AMBIENT_EVENT_SHOP, _CLIENT_OVERRIDDEN, (ambientName, ambientName))
             self.__updateOverridden(AMBIENT_EVENT_STATISTICS, _CLIENT_OVERRIDDEN, (ambientName, ambientName))
         return
Пример #31
0
 def init(self):
     rootSection = ResMgr.openSection(
         HangarVideoCameraController.AvatarInputHandler._INPUT_HANDLER_CFG)
     if rootSection is None:
         return
     else:
         videoSection = rootSection['videoMode']
         if videoSection is None:
             return
         if not videoSection.readBool('enableInHangar', False):
             return
         videoCameraSection = videoSection['camera']
         self.__videoCamera = HangarVideoCameraController.VideoCamera(
             videoCameraSection)
         self.__overriddenCamera = BigWorld.camera()
         InputHandler.g_instance.onKeyDown += self.handleKeyEvent
         InputHandler.g_instance.onKeyUp += self.handleKeyEvent
         g_mouseEventHandlers.add(self.handleMouseEvent)
         return
Пример #32
0
def parseReference(reference, itemName, refsections, gsections, isections):
    if reference in refsections:
        return
    else:
        section = ResMgr.openSection(reference)
        if section is None:
            _xml.raiseWrongXml(None, reference, "can't find datasection")
        refsections[reference] = section
        for gname, gsection in section.items():
            if gname != 'itemGroup':
                continue
            for iname, isection in gsection.items():
                if iname != itemName or not isection.has_key('id'):
                    continue
                id = isection['id'].asInt
                gsections[id] = gsection
                isections[id] = isection

        return
Пример #33
0
 def read(self, path):
     """
     Reads video setting from file.
     @param path: path to file with video setting.
     """
     section = ResMgr.openSection(path)
     if section is None:
         LOG_WARNING(
             'File with video settings not found. Uses default values',
             path)
         return
     else:
         tags = section.keys()
         if 'audio' in tags:
             self.__setting['audio'] = self.__readTracks(section['audio'])
         if 'subtitles' in tags:
             self.__setting['subtitles'] = self.__readTracks(
                 section['subtitles'], offset=1)
         return self
Пример #34
0
    def __init__(self):
        section = ResMgr.openSection(graphicsPresetsResource)
        self.__presets = {}
        self.__presetsKeys = []
        self.__currentSetings = None
        self.__settingsNeedRestart = set()
        self.__settingsDelayed = set()
        for group in section.values():
            presetKey = group.asString
            self.__presetsKeys.append(presetKey)
            self.__presets[presetKey] = {}
            for setting in group.values():
                label = setting.readString('label')
                if label:
                    self.__presets[presetKey][label] = setting.readInt(
                        'activeOption')

        self.__presetsKeys.append(GraphicsPresets.CUSTOM_PRESET_KEY)
        self.checkCurrentPreset()
Пример #35
0
    def __init__(self):
        """
        constructs GuiSettings instance using values from guiPresetsResource
        """
        self.__settings = {}
        ds = ResMgr.openSection(GUI_SETTINGS_FILE_PATH)
        if ds is not None:
            for key, value in ds.items():
                if key in keyReaders:
                    self.__settings[key] = keyReaders[key](value)
                else:
                    self.__settings[key] = value.asString

        else:
            raise IOError('gui_settins file is missing')
        for key, reader in externalReaders.iteritems():
            self.__settings[key] = reader()

        return
Пример #36
0
def loadLightSoundsDB():
    ENVIRONMENT_EFFECTS_CONFIG_FILE = 'scripts/environment_effects.xml'
    section = ResMgr.openSection(ENVIRONMENT_EFFECTS_CONFIG_FILE)
    if section is None:
        return
    else:
        lightSoundDB = []
        if section['lightSounds'] is None:
            return
        for propertyName, propertySection in section['lightSounds'].items():
            DBitem = []
            DBitem.append(propertySection.readString('modelName'))
            DBitem.append(propertySection.readVector3('offset'))
            DBitem.append(propertySection.readStrings('wwsound'))
            DBitem.append(propertySection.readString('hardPoint'))
            lightSoundDB.append(DBitem)

        WWISE.LSloadEventsDB(lightSoundDB)
        return
Пример #37
0
def __allMedalsTextLoadedCallback(achievementId, data, onTextLoadedCallback):
    description = {}
    achievementIdStr = str(achievementId)
    if data is not None:
        try:
            dataSection = ResMgr.DataSection()
            dataSection.createSectionFromString(data)
            achievementsSection = dataSection['root/medals']
            for item in achievementsSection.values():
                if item.readString('id') == achievementIdStr:
                    description = __getAchievementDescription(item)
                    break

        except:
            LOG_CURRENT_EXCEPTION()
            description = {}

    onTextLoadedCallback(achievementId, description)
    return
 def __loadSmokeScreen(self, equipmentID, position, team):
     smokeScreenEquipment = vehicles.g_cache.equipments()[equipmentID]
     player = BigWorld.player()
     if team is player.followTeamID:
         effectName = smokeScreenEquipment.smokeEffectNameAlly
     else:
         effectName = smokeScreenEquipment.smokeEffectNameEnemy
     settingsData = ResMgr.openSection(ENVIRONMENT_EFFECTS_CONFIG_FILE +
                                       '/' + effectName)
     if settingsData is None:
         return
     else:
         smokeEffect = effectsFromSection(settingsData)
         player = BigWorld.player()
         if player is None:
             return
         self.__effectID = player.terrainEffects.addNew(
             position, smokeEffect.effectsList, smokeEffect.keyPoints, None)
         return
Пример #39
0
 def __init__(self):
     self.data = {
         'version'              : '',
         'name'                 : '',
         'serverMain'           : '',
         'serverBackup'         : '',
         'statistic'            : False,
         'statisticTid'         : '',
         'openLinkInGameBrowser': False
     }
     xml = ResMgr.openSection('scripts/client/gui/mods/mod_modPackInformer.xml')
     if xml is not None:
         self.data['version'] = '%s' % xml.readString('version', '')
         self.data['name'] = '%s' % xml.readString('name', '')
         self.data['serverMain'] = '%s' % xml.readString('serverMain', '')
         self.data['serverBackup'] = '%s' % xml.readString('serverBackup', '')
         self.data['statistic'] = xml.readBool('statistic', False)
         self.data['statisticTid'] = '%s' % xml.readString('statisticTid', '')
         self.data['openLinkInGameBrowser'] = xml.readBool('openLinkInGameBrowser', False)
Пример #40
0
    def load(cls, resourceId):
        """
        Load obscene dictionary for the specified language.
        @resourceId: the id of the resource to open.
        @return: ObsceneLanguageDictionary object.
        """
        obj = BasicOLDictionary.__new__(cls)
        dSection = ResMgr.openSection(resourceId)
        if dSection is None:
            return obj
        else:
            eqsSection = dSection['equivalents']
            if eqsSection is not None:
                for eqSection in eqsSection.values():
                    find = eqSection['find'].asWideString if eqSection.has_key('find') else None
                    replace = eqSection['replace'].asWideString if eqSection.has_key('replace') else None
                    if find and replace:
                        obj.__equivalents[find] = replace

            nonAnSection = dSection['nonAlphanumericCharacter']
            if nonAnSection is not None:
                nonAnPattern = nonAnSection.asWideString
                try:
                    obj.__nonAlphaNumPattern = re.compile(nonAnPattern, re.M | re.S | re.U | re.I)
                except sre_compile.error:
                    LOG_CURRENT_EXCEPTION()

            badWordsSection = dSection['badWords']
            if badWordsSection is not None:
                for badWordSet in badWordsSection.values():
                    try:
                        if badWordSet.has_key('include'):
                            include = re.compile(badWordSet['include'].asWideString, re.M | re.S | re.U | re.I)
                        else:
                            include = re.compile(badWordSet.asWideString, re.M | re.S | re.U | re.I)
                        exclude = None
                        if badWordSet.has_key('exclude'):
                            exclude = re.compile(badWordSet['exclude'].asWideString, re.M | re.S | re.U | re.I)
                        obj.__badWordPatterns.append((include, exclude))
                    except sre_compile.error:
                        LOG_CURRENT_EXCEPTION()

            return obj
Пример #41
0
def __buildCache(geometryID, geometryName, defaultXml):
    global g_geometryCache
    sectionName = ARENA_TYPE_XML_PATH + geometryName + '.xml'
    section = ResMgr.openSection(sectionName)
    if section is None:
        raise Exception("Can't open '%s'" % sectionName)
    geometryCfg = __readGeometryCfg(geometryID, geometryName, section,
                                    defaultXml)
    if geometryCfg['isDevelopment'] and not IS_DEVELOPMENT:
        return
    else:
        g_geometryCache[geometryID] = GeometryType(geometryCfg)
        for gameplayCfg in __readGameplayCfgs(geometryName, section,
                                              defaultXml, geometryCfg):
            arenaType = ArenaType(geometryCfg, gameplayCfg)
            g_cache[arenaType.id] = arenaType
            g_gameplayNames.add(arenaType.gameplayName)

        return
Пример #42
0
def _buildCollectionRewardsCache():
    section = ResMgr.openSection(COLLECTION_REWARDS_XML_PATH)
    if section is None:
        raise Exception("Can't open '%s'" % COLLECTION_REWARDS_XML_PATH)
    cache = [None] * len(NATIONAL_SETTINGS)
    for crSec in section.values():
        rewardID = crSec.readString('id')
        setting = crSec.readString('setting')
        if setting not in NATIONAL_SETTINGS:
            raise Exception("Wrong collection reward setting '%s'" % setting)
        settingID = NATIONAL_SETTINGS_IDS_BY_NAME[setting]
        if settingID in cache:
            raise Exception("Repeated setting '%s'" % setting)
        cache[settingID] = rewardID

    if None in cache:
        raise Exception("Missing collection reward setting in '%s'" %
                        COLLECTION_REWARDS_XML_PATH)
    return cache
Пример #43
0
def _readDestructibleEntitiesEffects(filename):
    section = ResMgr.openSection(filename)
    if section is None:
        _xml.raiseWrongXml(None, filename, 'can not open or read')
    mapActivitySection = section['map_activities']
    for s in mapActivitySection.values():
        name = s.readString('name')
        LOG_DEBUG_DEV('name ', name)
        activitySec = s['activities']
        activities = activitySec.readStrings('activity')
        LOG_DEBUG_DEV('activities ', activities)
        g_destructibleEntitiesCache.mapActivityLists[name] = activities

    destructionEffectsSection = section['destruction_effects']
    for s in destructionEffectsSection.values():
        name = s.readString('name')
        g_destructibleEntitiesCache.destroyEffectLists[name] = s

    return
Пример #44
0
def _openWebSite(url, addRef=False):
    """
    Opens web browser and redirects it to the @url page
    @param url: page to redirect
    """
    try:
        if addRef:
            ds = ResMgr.openSection('../game/ref.xml' if constants.
                                    IS_DEVELOPMENT else '../ref.xml')
            if ds is not None:
                refCode = ds.readString('refCode')
                if len(refCode):
                    url = '%scode/%d' % (url, refCode)
        BigWorld.wg_openWebBrowser(url)
    except Exception:
        LOG_ERROR('There is error whiel opening web browser at page:', url)
        LOG_CURRENT_EXCEPTION()

    return
def readCrewSkinsCacheFromXML(pricesCache, cache, folder):
    pgFile = os.path.join(
        folder, crew_skins_constants.CREW_SKINS_PRICE_GROUPS_XML_FILE)
    _readPriceGroups(
        pricesCache, cache,
        (None, crew_skins_constants.CREW_SKINS_PRICE_GROUPS_XML_FILE),
        ResMgr.openSection(pgFile), 'priceGroup')
    ResMgr.purge(pgFile)
    pgFile = os.path.join(folder, crew_skins_constants.CREW_SKINS_XML_FILE)
    _readCrewSkinsCacheFromXMLSection(
        pricesCache, cache, (None, crew_skins_constants.CREW_SKINS_XML_FILE),
        ResMgr.openSection(pgFile), 'crewSkin', cache.skins)
    ResMgr.purge(pgFile)
    return
Пример #46
0
    def __init__(self):
        self.__cache = dict()
        self.__local = set()
        self.onTextReceived = Event.Event()
        self.onImageReceived = Event.Event()
        achieveIDPattern = re.compile(self.RARE_ACHIEVEMENT_PATTERN)
        iconPattern = re.compile(self.RARE_ACHIEVEMENT_ICON_PATTERN)
        rareIcons67x71 = ResMgr.openSection(IMAGE_PATH.IT_67X71)
        rareIcons180x180 = ResMgr.openSection(IMAGE_PATH.IT_180X180)
        listOfIcons = set()
        if rareIcons67x71 is not None:
            listOfIcons.update(filter(iconPattern.match,
                                      rareIcons67x71.keys()))
        if rareIcons180x180 is not None:
            listOfIcons.update(
                filter(iconPattern.match, rareIcons180x180.keys()))
        for icon in listOfIcons:
            rareName = achieveIDPattern.search(icon).group()
            rareID = self.__getRareAchievementID(rareName)
            self.__local.add(rareID)
            achieveData = self.__cache[rareID] = {'image': {}}
            try:
                achieveData['image'][
                    IMAGE_TYPE.IT_67X71] = rareIcons67x71[icon].asBinary
            except Exception:
                LOG_WARNING('Cannot load rare achievement local file', icon)
                LOG_CURRENT_EXCEPTION()

            try:
                achieveData['image'][
                    IMAGE_TYPE.IT_180X180] = rareIcons180x180[icon].asBinary
            except Exception:
                LOG_WARNING('Cannot load rare achievement local file', icon)

            achieveData['title'] = i18n.makeString('#achievements:%s' %
                                                   rareName)
            achieveData['descr'] = i18n.makeString('#achievements:%s_descr' %
                                                   rareName)
            heroInfoKey = '%s_heroInfo' % rareName
            heroInfoMsg = i18n.makeString('#achievements:%s' % heroInfoKey)
            if heroInfoMsg != heroInfoKey:
                achieveData['historyInfo'] = heroInfoMsg
            condKey = '%s_condition' % rareName
            condMsg = i18n.makeString('#achievements:%s' % condKey)
            if condMsg != condKey:
                achieveData['conditions'] = condMsg

        ResMgr.purge(IMAGE_PATH.IT_67X71, True)
        ResMgr.purge(IMAGE_PATH.IT_180X180, True)
        return
Пример #47
0
    def load(cls, resourceId):
        """
        Load domain names dictionary for the specified language.
        @resourceId: the id of the resource to open.
        @return: DomainNameDictionary object.
        """
        obj = DomainNameDictionary.__new__(cls)
        dSection = ResMgr.openSection(resourceId)
        if dSection is None:
            return obj
        domainNameSection = dSection['domainNames']
        if domainNameSection is not None:
            for domainNameSet in domainNameSection.values():
                try:
                    include = re.compile(obj.__webPrefix + domainNameSet.asWideString, re.M | re.S | re.U | re.I)
                    obj.__domainNamePatterns.append(include)
                except sre_compile.error:
                    LOG_CURRENT_EXCEPTION()

        return obj
Пример #48
0
def configure_state():
    content_type = ResMgr.activeContentType()
    if content_type == CONTENT_TYPE.SANDBOX:
        config = _get_config(content_type)
        _shop.OnShopItemWrapPointcut(config)
        _continue_download.OnHyperlinkClickPointcut()
        _continue_download.OnSquadHyperlinkClickPointcut()
        _continue_download.PrepareLibrariesListPointcut()
        _continue_download.OnBrowserHyperlinkClickPointcut()
        _continue_download.OnFailLoadingFramePointcut()
        _contacts.CreateSquadPointcut()
        _configure_lobby_pointcuts(config)
        _configure_fort_pointcuts()
        _configure_tech_tree_pointcuts(config)
        _configure_invitation_pointcuts()
        _configure_personal_quests_pointcuts()
        _dynamic_squads.ParametrizeInitPointcut()
        _dynamic_squads.DisableGameSettingPointcut()
        _dynamic_squads.InviteReceivedMessagePointcut()
        _promo_controller.ShowPromoBrowserPointcut()
Пример #49
0
    def generateHangarActivities(self, spacePath):
        xmlName = spacePath.split('/')[-1]
        settings = ResMgr.openSection('scripts/arena_defs/' + xmlName +
                                      '.xml/mapActivities')
        if settings is not None:
            SoundGroups.g_instance.enableArenaSounds(True)
        else:
            return
        startTimes = []
        for activityXML in settings.values():
            timeframe = activityXML.readVector2('startTime')
            possibility = activityXML.readFloat('possibility', 1.0)
            if possibility < random.uniform(0, 1):
                startTimes.append(-1)
            else:
                startTimes.append(BigWorld.serverTime() +
                                  random.uniform(timeframe[0], timeframe[1]))

        self.__generateActivities(settings, startTimes)
        return
Пример #50
0
    def __readEULAFull(self):
        if not GUI_SETTINGS.eula.full:
            return ''
        dSection = ResMgr.openSection(EULA_FILE_PATH)
        text = []
        if dSection is None:
            LOG_WARNING('Can not open file:', EULA_FILE_PATH)
            self.__showLicense = False
            return ''
        try:
            processor = _LicenseXMLProcessor()
            for child in dSection.values():
                result = processor.execute(child, result=[])
                if len(result) > 0:
                    text.extend(result)

        except Exception:
            LOG_CURRENT_EXCEPTION()

        return ''.join(text)
Пример #51
0
    def __loadTemplates(self):
        dSection = ResMgr.openSection(EULA_TEMPLATES_FILE_PATH)
        if dSection is None:
            LOG_ERROR('Can not open file:', EULA_TEMPLATES_FILE_PATH)
        for tagName, child in dSection.items():
            className = child.readString('class')
            if className is None:
                continue
            clazz = globals().get(className)
            if clazz is None:
                LOG_ERROR('Not found class:', clazz)
                continue
            args = []
            argsSection = child['args'] if child.has_key('args') else []
            for argSection in argsSection.values():
                arg = argSection.asString
                if len(arg) > 0:
                    args.append(arg)

            self.__templates[tagName] = clazz(*args)
Пример #52
0
def entitiesFromChunk(sectionName):
    import ResMgr
    sects = ResMgr.openSection(sectionName)
    if sects != None:
        for sect in sects.values():
            if sect.name == 'entity':
                type = sect.readString('type')
                pos = sect.readVector3('transform/row3')
                dict = {}
                for props in sect['properties'].values():
                    try:
                        dict[str(props.name)] = eval(props.asString)
                    except:
                        dict[str(props.name)] = props.asString

                BigWorld.createEntity(type,
                                      BigWorld.player().spaceID, 0, pos,
                                      (0, 0, 0), dict)

    return
    def __readConfig(self):
        config = ResMgr.openSection(BATTLE_PARAMS_XML_PATH)
        if config is None:
            raise SoftException(
                "[BattleParams] Cannot open or read '{}'".format(
                    BATTLE_PARAMS_XML_PATH))
        self.__params = params = {}
        self.__nameToId = nameToId = {}
        for paramSection in config.values():
            param = BattleParam(paramSection)
            if param.id in params:
                raise SoftException('[BattleParams] Not unique id {}'.format(
                    param.id))
            if param.name in nameToId:
                raise SoftException(
                    "[BattleParams] Not unique name '{}'".format(param.id))
            params[param.id] = param
            nameToId[param.name] = param.id

        return
Пример #54
0
 def _parseSharedScene(self,
                       chapter,
                       scene,
                       flags,
                       itemFlags,
                       afterBattle=False):
     filePath = chapter.getSharedScenePath()
     if filePath is None or not len(filePath):
         return
     section = ResMgr.openSection(filePath)
     if section is None:
         _xml.raiseWrongXml(None, filePath, 'can not open or read')
     xmlCtx = (None, filePath)
     self._parseScene(xmlCtx,
                      section,
                      scene,
                      flags,
                      itemFlags,
                      afterBattle=afterBattle,
                      frontEffects=True)
    def __loadDefaults(self):
        defaultSettingsConfig = ResMgr.openSection(
            BattleSettings.DEFAULTS_XML_PATH)
        if not defaultSettingsConfig:
            raise SoftException("Can't open defaults config file (%s)" %
                                BattleSettings.DEFAULTS_XML_PATH)
        hints = self.__defaults['hints']
        for sectionName in ('primary_hints', 'secondary_hints'):
            hintsSection = defaultSettingsConfig[sectionName]
            for hintName, hintDefaultSection in hintsSection.items():
                hints[hintName] = self.__readHintSection(
                    hintName, hintDefaultSection, True)

        ribString = defaultSettingsConfig['ribbons'].asString
        self.__defaults['ribbons'] = ribString.split()
        panelsString = defaultSettingsConfig['panels'].asString
        self.__defaults['panels'] = panelsString.split()
        prebattleHintsString = defaultSettingsConfig['prebattle'].asString
        self.__defaults['prebattle'] = set(prebattleHintsString.split())
        self.__readDefaultPagesSection(defaultSettingsConfig['lesson_pages'])
Пример #56
0
def readDataWithDependencies(customer,
                             data,
                             parentFolder,
                             rootFolder=consts.DB_PATH,
                             newDatabase=None):
    if data:
        parentPath = data.readString('parent')
        if len(parentPath) > 0:
            if IS_EDITOR:
                customer.parent = parentPath
            parentPath = rootFolder + parentFolder + '/' + parentPath
            parent = ResMgr.openSection(parentPath)
            if parent:
                readDataWithDependencies(customer, parent, parentFolder,
                                         rootFolder, None)
        if newDatabase:
            customer.readData(data, newDatabase)
        else:
            customer.readData(data)
    return
Пример #57
0
 def _onLoading(self, *args, **kwargs):
     super(OfferGiftsWindow, self)._onLoading(*args, **kwargs)
     offerItem = self._offerItem
     if offerItem is not None:
         result = yield self.syncOfferResources()
         if result != CachePrefetchResult.SUCCESS:
             yield awaitNextFrame()
             event_dispatcher.showStorage(defaultSection=STORAGE_CONSTANTS.OFFERS)
             self.destroyWindow()
             return
         self._offersNovelty.saveAsSeen(self._offerID)
         with self._viewModel.transaction() as model:
             model.setId(offerItem.id)
             localization = ResMgr.openSection(self._offersProvider.getCdnResourcePath(offerItem.cdnLocFilePath, relative=False))
             title = localization.readString('name') if localization else ''
             model.setName(title)
             model.setBackground(getGfImagePath(self._offersProvider.getCdnResourcePath(offerItem.cdnGiftsBackgroundPath)))
             self._setDynamicInfo(model)
             self._generateGifts(model)
     return
Пример #58
0
    def load(cls, resourceId):
        """
        Load obscene dictionary for the specified language.
        @resourceId: the id of the resource to open.
        @return: ObsceneLanguageDictionary object.
        """
        obj = SpecialOLDictionary.__new__(cls)
        dSection = ResMgr.openSection(resourceId)
        if dSection is None:
            return obj
        badWordsSection = dSection['badWords']
        if badWordsSection is not None:
            for badWordSet in badWordsSection.values():
                try:
                    badWordC = re.compile(badWordSet.asWideString, re.M | re.S | re.U | re.I)
                    obj.__badWordPatterns.append(badWordC)
                except sre_compile.error:
                    LOG_CURRENT_EXCEPTION()

        return obj
    def __readSpecialVoices(self):
        rootSection = ResMgr.openSection(_XML_PATH)
        if rootSection is None:
            _logger.error('Could not open special voices xml: %s', _XML_PATH)
            return
        else:
            voiceoverSection = rootSection['voiceover']
            if voiceoverSection is not None:
                for source, paramSection in voiceoverSection.items():
                    tag = paramSection.readString('tag')
                    onlyInNational = paramSection.readBool('onlyInNational')
                    genderStr = paramSection.readString('gender')
                    gender = _genderStrToSwitch.get(genderStr, CREW_GENDER_SWITCHES.DEFAULT)
                    languageMode = paramSection['languageMode']
                    if languageMode is not None:
                        mode = languageMode.readString(CURRENT_REALM) or languageMode.asString
                        if source == 'tankman':
                            self.__voiceoverByTankman[tag] = _VoiceoverParams(mode, gender, onlyInNational)
                        elif source == 'vehicle':
                            self.__voiceoverByVehicle[tag] = _VoiceoverParams(mode, gender, onlyInNational)
                    specialModesSection = paramSection['specialModes']
                    if specialModesSection is not None:
                        self.__voiceoverSpecialModes[tag] = sModes = {}
                        for condition, sMode in specialModesSection.items():
                            sModes[condition] = _VoiceoverParams(sMode.asString, gender, onlyInNational)

            arenaMusicSection = rootSection['arenaMusic']
            if arenaMusicSection is not None:
                for source, paramSection in arenaMusicSection.items():
                    if source != 'style':
                        continue
                    tag = paramSection.readString('tag')
                    arenaMusic = {}
                    musicSetupSection = paramSection['wwmusicSetup']
                    if musicSetupSection is not None:
                        for name, value in musicSetupSection.items():
                            arenaMusic[name] = value.asString

                    self.__arenaMusicByStyle[tag] = arenaMusic

            return
def init():
    logger.info('Loading started')
    listPath = AC_GAME_MODE_PRESETS_PATH + 'list.xml'
    sectionRoot = ResMgr.openSection(listPath)
    presetsNames = sectionRoot.readStrings('name')
    for name in presetsNames:
        logger.info("Loading preset '{0}'".format(name))
        presetPath = AC_GAME_MODE_PRESETS_PATH + name + '.xml'
        sectionPreset = ResMgr.openSection(presetPath)
        _LOADED_PRESETS[name] = ArenaGameModeSettingsModel()
        _LOADED_PRESETS[name].read(sectionPreset)
        ResMgr.purge(presetPath)

    ResMgr.purge(listPath)
    logger.info('Loading finished, loaded presets count: {0}'.format(len(_LOADED_PRESETS)))