Exemplo n.º 1
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
Exemplo n.º 2
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)
Exemplo n.º 3
0
    def __init__(self):
        if IS_CLIENT:
            sec = ResMgr.openSection(DESTRUCTIBLES_EFFECTS_FILE)
            if not sec:
                raise Exception, "Fail to read '%s'" % DESTRUCTIBLES_EFFECTS_FILE
            self.__effects = _readDestructiblesEffects(sec)
            ResMgr.purge(DESTRUCTIBLES_EFFECTS_FILE, True)
        sec = ResMgr.openSection(DESTRUCTIBLES_CONFIG_FILE)
        if not sec:
            raise Exception, "Fail to read '%s'" % DESTRUCTIBLES_CONFIG_FILE
        self.__defaultLifetimeEffectChance = sec.readFloat('defaultLifetimeEffectChance')
        self.__unitVehicleMass = sec.readFloat('unitVehicleMass')
        if not IS_CLIENT or IS_DEVELOPMENT:
            self.__maxHpForShootingThrough = sec.readFloat('maxHpForShootingThrough')
            self.__projectilePiercingPowerReduction = _readProjectilePiercingPowerReduction(sec['projectilePiercingPowerReduction'])
        descs = []
        for fragileSec in sec['fragiles'].values():
            desc = self.__readFragile(fragileSec)
            descs.append(desc)

        for fallingSec in sec['fallingAtoms'].values():
            desc = self.__readFallingAtom(fallingSec)
            descs.append(desc)

        for treeSec in sec['trees'].values():
            desc = self.__readTree(treeSec)
            descs.append(desc)

        for structSec in sec['structures'].values():
            desc = self.__readStructure(structSec)
            descs.append(desc)

        self.__descs = descs
        self.__descIDs = dict(((desc['filename'], i) for i, desc in enumerate(descs)))
        ResMgr.purge(DESTRUCTIBLES_CONFIG_FILE, True)
Exemplo n.º 4
0
def readHangarSettings(igrKey):
    global _HANGAR_CFGS
    global _DEFAULT_CFG
    global _CFG
    hangarsXml = ResMgr.openSection('gui/hangars.xml')
    for isPremium in (False, True):
        spacePath = _getDefaultHangarPath(isPremium)
        settingsXmlPath = spacePath + '/space.settings'
        ResMgr.purge(settingsXmlPath, True)
        settingsXml = ResMgr.openSection(settingsXmlPath)
        settingsXml = settingsXml['hangarSettings']
        cfg = {'path': spacePath,
         'cam_yaw_constr': Math.Vector2(-180, 180),
         'cam_pitch_constr': Math.Vector2(-70, -5)}
        loadConfig(cfg, settingsXml)
        loadConfigValue('shadow_model_name', hangarsXml, hangarsXml.readString, cfg)
        loadConfigValue('shadow_default_texture_name', hangarsXml, hangarsXml.readString, cfg)
        loadConfigValue('shadow_empty_texture_name', hangarsXml, hangarsXml.readString, cfg)
        loadConfigValue(igrKey, hangarsXml, hangarsXml.readString, cfg)
        _DEFAULT_CFG[getSpaceType(isPremium)] = cfg
        _HANGAR_CFGS[spacePath.lower()] = settingsXml

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

    _CFG = copy.copy(_DEFAULT_CFG[getSpaceType(False)])
    return
Exemplo n.º 5
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
Exemplo n.º 6
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
Exemplo n.º 7
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
Exemplo n.º 8
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
Exemplo n.º 9
0
    def load_json(self, name, config, save=False):
        res = ResMgr.openSection('../paths.xml')
        sb = res['Paths']
        vals = sb.values()[0:2]
        config_new = config
        for vl in vals:
            path = '%s/scripts/client/gui/mods/' % vl.asString
            if os.path.isdir(path):
                new_path = '%s%s.json' % (path, name)
                if save:
                    with codecs.open(new_path, 'w', encoding='utf-8-sig') as json_file:
                        data = json.dumps(config, sort_keys=True, indent=4, ensure_ascii=False, encoding='utf-8-sig') #encoding='utf-8-sig'
                        json_file.write('%s' % self.byteify(data))
                        json_file.close()
                        config_new = config
                else:
                    if os.path.isfile(new_path):
                        try:
                            with codecs.open(new_path, 'r', encoding='utf-8-sig') as json_file:
                                data = json_file.read().decode('utf-8-sig')
                                config_new = self.byteify(json.loads(data)) #.decode('utf-8-sig')
                                json_file.close()
                        except Exception as e:
                            print 'ERROR: %s' % e

                    else:
                        #with open(new_path, 'w') as json_file:
                        with codecs.open(new_path, 'w', encoding='utf-8-sig') as json_file:
                            data = json.dumps(config, sort_keys=True, indent=4, ensure_ascii=False, encoding='utf-8-sig') #encoding='utf-8-sig'
                            json_file.write('%s' % self.byteify(data))
                            json_file.close()
                            config_new = config
        return config_new
Exemplo n.º 10
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)
Exemplo n.º 11
0
    def _create(self, prereqs = None):
        try:
            pSection = prereqs[self.fileName]
        except KeyError:
            pSection = ResMgr.openSection(self.fileName)
        except TypeError:
            pSection = ResMgr.openSection(self.fileName)

        if pSection != None:
            self._createFromSection(pSection, prereqs)
        else:
            ERROR_MSG('Could not open file', self.fileName)
            return
        if Effect._debugTimings == 1:
            self.events.append(('', timedEvents.DebugEventTiming()))
        return
Exemplo n.º 12
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
Exemplo n.º 13
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
Exemplo n.º 14
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)
Exemplo n.º 15
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)
Exemplo n.º 16
0
 def config(self):
     self.active = True
     self.allies = False
     self.alliesAtStart = False
     self.unvisible = True
     self.bonusBrotherhood = True
     self.bonusStimulator = False
     self.bonusAuto = True
     self.timeoutAutoReload = True
     self.timeoutReloadDelay = 3.0
     self.timeReloadCorrect = 0.0
     self.SWF_FILE_NAME_ENEMIES = 'marker_red.swf'
     self.SWF_FILE_NAME_ALLIES = 'marker_green.swf'
     self.marker_timeUpdate = 0.3
     self.marker_timeCorrect = 0.3
     self.config = ResMgr.openSection('scripts/client/gui/mods/mod_reload.xml')
     if self.config:
         self.allies = self.config.readBool('allies', False)
         self.alliesAtStart = self.config.readBool('alliesAtStart', self.allies)
         self.unvisible = self.config.readBool('unvisible', True)
         self.bonusBrotherhood = self.config.readBool('bonusBrotherhood', True)
         self.bonusStimulator = self.config.readBool('bonusStimulator', False)
         self.bonusAuto = self.config.readBool('bonusAuto', True)
         self.timeoutAutoReload = self.config.readBool('timeoutAutoReload', True)
         self.timeoutReloadDelay = self.config.readFloat('timeoutReloadDelay', 3.0)
         self.timeReloadCorrect = self.config.readFloat('timeReloadCorrect', 0.0)
         self.SWF_FILE_NAME_ENEMIES = self.config.readString('enemiesMarker', 'marker_red.swf')
         self.SWF_FILE_NAME_ALLIES = self.config.readString('alliesMarker', 'marker_green.swf')
         self.marker_timeUpdate = self.config.readFloat('marker_timeUpdate', 0.3)
         self.marker_timeCorrect = self.config.readFloat('marker_timeCorrect', 0.3)
     return
Exemplo n.º 17
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)
Exemplo n.º 18
0
 def isShowLicense(self):
     dSection = ResMgr.openSection(VERSION_FILE_PATH)
     if dSection is None:
         LOG_ERROR('Can not open file:', VERSION_FILE_PATH)
         return False
     else:
         return bool(dSection.readInt(SHOW_LICENCE_TAG, 0))
Exemplo n.º 19
0
 def readXml(path, defset, filename = ''):
     cfg = ResMgr.openSection(path)
     if cfg is None:
         LOG_WARNING('no config found')
         return defset
     else:
         return FileUtils.readElement(cfg, defset, filename, 'root')
	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()
Exemplo n.º 21
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
Exemplo n.º 22
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)
Exemplo n.º 23
0
def isSupported(dataSection):
    """
    This method checks an dataSection to see if all the Effects contained
    therein are supported by the current graphics setting.
    
    Currently the only issue is that cases are depth-based effects are not
    available if the MRTDepth setting is not turned on.
    """
    optionIdx = BigWorld.getGraphicsSetting("MRT_DEPTH")
    if optionIdx == 0:
        return True
    else:
        ds = ResMgr.openSection(dataSection)
        if ds is None:
            raise exceptions.AttributeError(dataSection)
        effects = ds.readStrings("Effect")
        for name in effects:
            if name in (
                "Depth of Field (variable filter)",
                "Depth of Field (bokeh control)",
                "Depth of Field (multi-blur)",
                "Rainbow",
                "God Rays",
                "Volume Light",
            ):
                return False

        return True
Exemplo n.º 24
0
def launch(spaceName):
    global g_offlineModeEnabled
    global g_spaceID
    global g_videoCamera
    print 'Entering offline space', spaceName
    BigWorld.clearAllSpaces()
    BigWorld.worldDrawEnabled(False)
    _displayGUI(spaceName)
    g_spaceID = BigWorld.createSpace()
    BigWorld.addSpaceGeometryMapping(g_spaceID, None, spaceName)
    BigWorld.setCursor(GUI.mcursor())
    GUI.mcursor().visible = False
    GUI.mcursor().clipped = True
    g_offlineModeEnabled = True
    BigWorld.callback(1.0, _offlineLoadCheck)
    rootSection = ResMgr.openSection(AvatarInputHandler._INPUT_HANDLER_CFG)
    videoSection = rootSection['videoMode']
    videoCameraSection = videoSection['camera']
    g_videoCamera = VideoCamera(videoCameraSection)
    g_videoCamera.enable(camMatrix=mathUtils.createTranslationMatrix((0.0, 0.0, 0.0)))
    BigWorld.camera().spaceID = g_spaceID
    import game
    game.handleKeyEvent = handleKeyEvent
    game.handleMouseEvent = handleMouseEvent
    BigWorld.player = lambda : g_fakeAvatar
    return
Exemplo n.º 25
0
Arquivo: model.py Projeto: konlil/mypy
	def load(self, res):
		import resmgrdll
		import ResMgr
		super(NodefullModel, self).load(res)
		self.fileSection = ResMgr.openSection(res)
		self.visualName = self.fileSection.readString('nodefullVisual')
		self.visual = visual.Visual()
		self.visual.load('%s.visual' % self.visualName)
Exemplo n.º 26
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)
Exemplo n.º 27
0
 def getAvailableNations(self):
     if self.__availableNations is None:
         section = ResMgr.openSection(TREE_SHARED_REL_FILE_PATH)
         if section is None:
             _xml.raiseWrongXml(None, TREE_SHARED_REL_FILE_PATH, 'can not open or read')
         xmlCtx = (None, TREE_SHARED_REL_FILE_PATH)
         self.__availableNations = self.__readAvailableNations(xmlCtx, section)
     return self.__availableNations[:]
Exemplo n.º 28
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
Exemplo n.º 29
0
def getAllFontNames():
    l = []
    all = ResMgr.openSection("system/fonts")
    for name, ds in all.items():
        if name.endswith(".font"):
            l.append(name)

    return l
Exemplo n.º 30
0
    def __getWallpapersList():
        result = []
        ds = ResMgr.openSection(SCALEFORM_WALLPAPER_PATH)
        for filename in ds.keys():
            if filename[-4:] == '.png' and filename[0:2] != '__':
                result.append(filename[0:-4])

        return result
Exemplo n.º 31
0
 def readXML():
     settingsFileName = 'scripts/client/development/replay_override/config.xml'
     settings = ResMgr.openSection(settingsFileName)
     if settings is not None:
         overridables = settings['ReplayOverridables']
         if overridables is not None:
             vehicle = overridables['Vehicle']
             if vehicle is not None:
                 BattleReplayPatch.vehicleName = vehicle.asString
             location = overridables['Location']
             if location is not None:
                 BattleReplayPatch.locationName = location.asString
     return
Exemplo n.º 32
0
 def __init__(self):
     self.loginSection = None
     if GAME_REGION not in URLS.WG_API_SERVERS:
         warn('xvm_online: no API available for this server')
         return
     self.lock = threading.RLock()
     self.thread = None
     self.resp = None
     self.done_config = False
     self.loginSection = ResMgr.openSection('scripts_config.xml')['login']
     self.region = GAME_REGION.lower()
     if 'CT' in URLS.WG_API_SERVERS and self.region == 'ct':  # CT is uncommented in xfw.constants to check on test server
         self.region = 'ru'
Exemplo n.º 33
0
    def getDefaults(self):
        section = ResMgr.openSection(CommandMapping.__DEFAULT_CONFIG_FILE_NAME)
        result = {}
        for commandName in section.keys():
            subsec = section[commandName]
            fireKeyName = subsec.readString('fireKey')
            satelliteKeyNames = []
            if subsec.has_key('satelliteKeys'):
                satelliteKeyNames = subsec.readString('satelliteKeys').split()
            if len(satelliteKeyNames) == 0:
                result[self.getCommand(commandName)] = int(Keys.__dict__.get(fireKeyName, 0))

        return result
Exemplo n.º 34
0
    def fromXmlFile(cls, xmlPath):
        root = ResMgr.openSection(xmlPath)
        if root is None:
            raise Exception(
                'Wrong xml with item qualifiers={0}'.format(xmlPath))
        res = []
        for name, section in root.items():
            if name != 'qualifier':
                LOG_ERROR('Unexpected tag in qualifiers', name)
                continue
            res.append(parseQualifier(section))

        return cls(res)
Exemplo n.º 35
0
    def __init__(self):
        if FlockLike.__SoundNames is None:
            FlockLike.__SoundNames = {}
            flockDataSect = ResMgr.openSection(
                ENVIRONMENT_EFFECTS_CONFIG_FILE + '/birds')
            for value in flockDataSect.values():
                modelName = value.readString('modelName', '')
                soundName = value.readString('wwsound', '')
                if modelName != '' and soundName != '':
                    FlockLike.__SoundNames[modelName] = soundName

        self.__sound = None
        return
Exemplo n.º 36
0
    def parse(self):
        section = ResMgr.openSection(BONUSES_REFS_FILE_PATH)
        if section is None:
            _xml.raiseWrongXml(None, BONUSES_REFS_FILE_PATH, 'can not open or read')
        xmlCtx = (None, BONUSES_REFS_FILE_PATH)
        result = {}
        for _, subSec in _xml.getChildren(xmlCtx, section, 'bonuses'):
            bonusID = sub_parsers.parseID(xmlCtx, subSec, 'Specify a bonus ID')
            bonus = sub_parsers.parseBonus(xmlCtx, subSec)
            result[bonusID] = bonus

        _xml.clearCaches()
        return result
Exemplo n.º 37
0
def _loadCameraTransforms():
    rootDS = ResMgr.openSection(PROFILE_CAMERA_TRANSFORMS_XML_NAME)
    if rootDS is not None and rootDS['cameras'] is not None:
        for c in rootDS['cameras'].values():
            c = CameraTransform(c.readMatrix('transform'))
            g_cameraTransforms.append(c)

    else:
        m = Math.Matrix()
        m.lookAt((41, 14, -337), (-0.2, -0.05, 0.97), (0, 1, 0))
        g_cameraTransforms.append(CameraTransform(m))
    rootDs = None
    return
Exemplo n.º 38
0
 def _readCfg(self):
     sec = ResMgr.openSection(_INPUT_HANDLER_CFG)
     if sec is None:
         LOG_ERROR('can not open <%s>.' % _INPUT_HANDLER_CFG)
         return
     else:
         self.__checkSections(sec)
         keySec = sec['keys']
         if keySec is not None:
             self.__showMarkersKey = getattr(Keys, keySec.readString('showMarkersKey', ''), None)
             self.__alwaysShowAimKey = getattr(Keys, keySec.readString('alwaysShowAimKey', ''), None)
         self.__dynamicCameraSettings = DynamicCameraSettings(sec['dynamicCameraCommon'])
         return sec
Exemplo n.º 39
0
 def _onLoading(self, *args, **kwargs):
     super(OfferBannerWindowView, self)._onLoading(*args, **kwargs)
     offer = self._offersProvider.getOffer(self._offerID)
     if offer is None:
         return
     else:
         localization = ResMgr.openSection(self._offersProvider.getCdnResourcePath(offer.cdnLocFilePath, relative=False))
         with self.viewModel.transaction() as model:
             model.setTitle(R.strings.offers.banner.title())
             model.setDescription(localization.readString('bannerDescription', default=''))
             model.setName(localization.readString('nameInBanner', default=''))
             model.setIcon(getGfImagePath(self._offersProvider.getCdnResourcePath(offer.cdnBannerLogoPath, relative=True)))
         return
Exemplo n.º 40
0
 def collectBankFiles(self, mediaPath):
     bankFiles = {'mods': set(), 'pkg': set(), 'ignore': set(), 'audio_mods_allowed': ('protanki.bnk',),
                  'res': {os.path.basename(path) for path in glob.iglob('./res/' + mediaPath + '/*')
                          if os.path.splitext(path)[1] in ('.bnk', '.pck')}}
     for pkgPath in glob.iglob('./res/packages/audioww*.pkg'):
         with zipfile.ZipFile(pkgPath) as pkg:
             bankFiles['pkg'].update({os.path.basename(name) for name in pkg.namelist()})
     bankFiles['orig'] = bankFiles['res'] | bankFiles['pkg']
     bankFiles['mods'] = set(
         x for x in ResMgr.openSection(mediaPath).keys()
         if os.path.splitext(x)[1] in ('.bnk', '.pck') and not any(y in bankFiles['orig'] for y in (x, x.lower())))
     bankFiles['all'] = bankFiles['orig'] | bankFiles['mods']
     return bankFiles
Exemplo n.º 41
0
    def parse(filePath, excludedHints):
        hints = HintsData()
        section = ResMgr.openSection(filePath)
        if section is None:
            _xml.raiseWrongXml(None, filePath, 'can not open or read')
        xmlCtx = (None, filePath)
        hints.setGuiFilePath(_xml.readString(xmlCtx, section, 'gui'))
        for _, subSec in _xml.getChildren(xmlCtx, section, 'hints'):
            hint = sub_parsers.parseHint(xmlCtx, subSec)
            if hint['hintID'] not in excludedHints:
                hints.addHint(hint)

        return hints
Exemplo n.º 42
0
def _buildToysCache():
    section = ResMgr.openSection(TOYS_XML_PATH)
    if section is None:
        raise Exception("Can't open '%s'" % TOYS_XML_PATH)
    cache = {}
    for toySec in section.values():
        cfg = _readToy(toySec)
        toyID = cfg['id']
        if cache.has_key(toyID):
            raise Exception("Repeated toyID '%d'" % toyID)
        cache[toyID] = ToyDescriptor(cfg)

    return cache
Exemplo n.º 43
0
 def __init__(self):
     self.config = {}
     res = ResMgr.openSection('../paths.xml')
     sb = res['Paths']
     vals = sb.values()[0:2]
     for vl in vals:
         path = vl.asString + '/scripts/client/gui/mods/'
         if os.path.isdir(path):
             conf_file = path + 'mod_wotxp.json'
             if os.path.isfile(conf_file):
                 with open(conf_file) as data_file:
                     self.config = json.load(data_file)
                     break
Exemplo n.º 44
0
def _buildChestsCache():
    section = ResMgr.openSection(CHESTS_XML_PATH)
    if section is None:
        raise Exception("Can't open '%s'" % CHESTS_XML_PATH)
    cache = {}
    for chestSec in section.values():
        cfg = _readChest(chestSec)
        chestID = cfg['id']
        if cache.has_key(chestID):
            raise Exception("Repeated chestID '%s'" % chestID)
        cache[chestID] = ChestDescriptor(cfg)

    return cache
Exemplo n.º 45
0
def _buildBoxesCache():
    section = ResMgr.openSection(BOXES_XML_PATH)
    if section is None:
        raise Exception("Can't open '%s'" % BOXES_XML_PATH)
    cache = {}
    for boxSec in section.values():
        cfg = _readBox(boxSec)
        boxID = cfg['id']
        if cache.has_key(boxID):
            raise Exception("Repeated boxID '%s'" % boxID)
        cache[boxID] = BoxDescriptor(cfg)

    return cache
Exemplo n.º 46
0
def _buildVariadicTankmenCache():
    section = ResMgr.openSection(VARIADIC_TANKMEN_XML_PATH)
    if section is None:
        raise Exception("Can't open '%s'" % VARIADIC_TANKMEN_XML_PATH)
    cache = {}
    for vdSec in section.values():
        cfg = _readVariadicTankman(vdSec)
        vtID = cfg['id']
        if cache.has_key(vtID):
            raise Exception("Repeated variadic tankman ID '%s'" % vtID)
        cache[vtID] = VariadicTankman(cfg)

    return cache
Exemplo n.º 47
0
    def __init__(self):
        self.listeners = []
        self.lock = threading.RLock()
        self.thread = None
        self.resp = None

        self.hosts = list()
        loginSection = ResMgr.openSection('scripts_config.xml')['login']
        if loginSection is not None:
            for (name, subSec) in loginSection.items():
                self.hosts.append({
                    'name':subSec.readStrings('name')[0],
                    'url':subSec.readStrings('url')[0]})
Exemplo n.º 48
0
def _buildVariadicDiscountsCache():
    section = ResMgr.openSection(VARIADIC_DISCOUNTS_XML_PATH)
    if section is None:
        raise Exception("Can't open '%s'" % VARIADIC_DISCOUNTS_XML_PATH)
    cache = {}
    for vdSec in section.values():
        cfg = _readVariadicDiscount(vdSec)
        vdID = cfg['id']
        if cache.has_key(vdID):
            raise Exception("Repeated variadic discount ID '%s'" % vdID)
        cache[vdID] = VariadicDiscount(cfg)

    return cache
Exemplo n.º 49
0
    def __loadConfig(self):
        eventNames = {}
        xmlPath = 'gui/music_events.xml'
        section = ResMgr.openSection(xmlPath)
        if section is None:
            _xml.raiseWrongXml(None, xmlPath, 'can not open or read')
        for i in section.items():
            s = i[1]
            if i[0] == 'music':
                eventNames[MUSIC_EVENT_LOGIN] = s.readString('login')
                eventNames[MUSIC_EVENT_LOBBY] = (s.readString('lobby'), s.readString('lobby'))
                eventNames[MUSIC_EVENT_COMBAT_VICTORY] = s.readString('combat_victory')
                eventNames[MUSIC_EVENT_COMBAT_LOSE] = s.readString('combat_lose')
                eventNames[MUSIC_EVENT_COMBAT_DRAW] = s.readString('combat_draw')
            elif i[0] == 'ambient':
                eventNames[AMBIENT_EVENT_LOBBY] = (s.readString('lobby'), s.readString('lobby'))
                eventNames[AMBIENT_EVENT_SHOP] = (s.readString('shop'), s.readString('lobby'))
                eventNames[AMBIENT_EVENT_STATISTICS] = (s.readString('rating'), s.readString('lobby'))
                for key, const in FORT_MAPPING.iteritems():
                    eventNames[const] = (s.readString(key), s.readString(key))

        fallbackEventNames = eventNames.copy()
        self.__overrideEvents(eventNames)
        soundsByName = {}
        for eventId, names in eventNames.items():
            lstEvents = []
            if not isinstance(names, tuple):
                names = (names,)
            fallbackNames = fallbackEventNames[eventId]
            if not isinstance(fallbackNames, tuple):
                fallbackNames = (fallbackNames,)
            for i in xrange(len(names)):
                eventName = names[i]
                fallbackEventName = fallbackNames[i]
                sound = soundsByName.get(eventName)
                if sound is None:
                    sound = SoundGroups.g_instance.getSound2D(eventName) if eventName != '' else None
                    if sound is None:
                        sound = SoundGroups.g_instance.getSound2D(fallbackEventName) if fallbackEventName != '' else None
                soundsByName[eventName] = sound
                lstEvents.append(sound)
                if sound is not None:
                    sound.stop()

            prevList = self.__soundEvents.get(eventId, None)
            if prevList is not None:
                for event in prevList:
                    if event is not None:
                        event.stop()

            self.__soundEvents[eventId] = lstEvents
Exemplo n.º 50
0
 def onClientReady(self):
     if not self.isPlaying:
         if not self.isRecording:
             return
         if self.isRecording and BigWorld.player(
         ).arena.guiType == constants.ARENA_GUI_TYPE.TUTORIAL:
             self.stop()
             return
         self.__replayCtrl.playerVehicleID = BigWorld.player(
         ).playerVehicleID
         self.__replayCtrl.onClientReady()
         if self.isRecording:
             player = BigWorld.player()
             arena = player.arena
             arenaName = arena.arenaType.geometry
             i = arenaName.find('/')
             arenaName = i != -1 and arenaName[i + 1:]
         now = datetime.datetime.now()
         now = '%02d.%02d.%04d %02d:%02d:%02d' % (
             now.day, now.month, now.year, now.hour, now.minute, now.second)
         vehicleName = BigWorld.entities[
             player.playerVehicleID].typeDescriptor.name
         vehicleName = vehicleName.replace(':', '-')
         vehicles = self.__getArenaVehiclesInfo()
         gameplayID = player.arenaTypeID >> 16
         sec = ResMgr.openSection(VERSION_FILE_PATH)
         clientVersionFromXml = i18n.makeString(
             sec.readString('appname')) + ' ' + sec.readString('version')
         clientVersionFromExe = BigWorld.wg_getProductVersion()
         arenaInfo = {
             'dateTime': now,
             'playerName': player.name,
             'playerID': self.__playerDatabaseID,
             'playerVehicle': vehicleName,
             'mapName': arenaName,
             'mapDisplayName': arena.arenaType.name,
             'gameplayID': ArenaType.getGameplayName(gameplayID)
             or gameplayID,
             'vehicles': vehicles,
             'battleType': arena.bonusType,
             'clientVersionFromExe': clientVersionFromExe,
             'clientVersionFromXml': clientVersionFromXml
         }
         self.__replayCtrl.recMapName = arenaName
         self.__replayCtrl.recPlayerVehicleName = vehicleName
         self.__replayCtrl.setArenaInfoStr(json.dumps(arenaInfo))
     else:
         self.__showInfoMessage('replayControlsHelp1')
         self.__showInfoMessage('replayControlsHelp2')
         self.__showInfoMessage('replayControlsHelp3')
         self.__disableSidePanelContextMenu()
Exemplo n.º 51
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()
        listOfIcons.update(filter(iconPattern.match, rareIcons67x71.keys()))
        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:
                LOG_WARNING('Cannot load rare achievement local file', icon)
                LOG_CURRENT_EXCEPTION()

            try:
                achieveData['image'][IMAGE_TYPE.IT_180X180] = rareIcons180x180[icon].asBinary
            except:
                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
def _readHangarSettings():
    hangarsXml = ResMgr.openSection('gui/hangars.xml')
    paths = [ path for path, _ in ResMgr.openSection(_DEFAULT_SPACES_PATH).items() ]
    defaultSpace = 'hangar_v3'
    if hangarsXml.has_key('hangar_space_switch_items'):
        switchItems = hangarsXml['hangar_space_switch_items']
        for item in switchItems.values():
            if item.readString('name') == _DEFAULT_HANGAR_PATH_KEY:
                defaultSpace = item.readString('space')
                break

    configset = {_DEFAULT_HANGAR_PATH_KEY: '{}/{}'.format(_DEFAULT_SPACES_PATH, defaultSpace)}
    for folderName in paths:
        spacePath = '{prefix}/{node}'.format(prefix=_DEFAULT_SPACES_PATH, node=folderName)
        spaceKey = _getHangarKey(spacePath)
        settingsXmlPath = '{path}/{file}/{sec}'.format(path=spacePath, file='space.settings', sec='hangarSettings')
        ResMgr.purge(settingsXmlPath, True)
        settingsXml = ResMgr.openSection(settingsXmlPath)
        if settingsXml is None:
            continue
        cfg = HangarConfig()
        cfg.loadDefaultHangarConfig(hangarsXml, _IGR_HANGAR_PATH_KEY)
        cfg.loadConfig(settingsXml)
        _loadVisualScript(cfg, settingsXml)
        if settingsXml.has_key(_CUSTOMIZATION_HANGAR_SETTINGS_SEC):
            customizationXmlSection = settingsXml[_CUSTOMIZATION_HANGAR_SETTINGS_SEC]
            customizationCfg = HangarConfig()
            customizationCfg.loadCustomizationConfig(customizationXmlSection)
            cfg[_CUSTOMIZATION_HANGAR_SETTINGS_SEC] = customizationCfg
        if settingsXml.has_key(_SECONDARY_HANGAR_SETTINGS_SEC):
            secondarySettingsXmlSection = settingsXml[_SECONDARY_HANGAR_SETTINGS_SEC]
            secondaryCfg = HangarConfig()
            secondaryCfg.loadSecondaryConfig(secondarySettingsXmlSection)
            cfg[_SECONDARY_HANGAR_SETTINGS_SEC] = secondaryCfg
        configset[spaceKey] = cfg
        _validateConfigValues(cfg)

    return configset
Exemplo n.º 53
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)
Exemplo n.º 54
0
def init():
    global g_gameplayNames
    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)
    return
Exemplo n.º 55
0
def __buildCache(geometryID, geometryName, defaultXml):
    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)
    for gameplayCfg in __readGameplayCfgs(geometryName, section, defaultXml,
                                          geometryCfg):
        arenaType = ArenaType(geometryCfg, gameplayCfg)
        g_cache[arenaType.id] = arenaType
        g_gameplayNames.add(arenaType.gameplayName)

    return
    def create(self, isPremium, onSpaceLoadedCallback=None):
        global _CFG
        BigWorld.worldDrawEnabled(False)
        BigWorld.wg_setSpecialFPSMode()
        self.__onLoadedCallback = onSpaceLoadedCallback
        self.__spaceId = BigWorld.createSpace()
        isIGR = self.igrCtrl.getRoomType() == constants.IGR_TYPE.PREMIUM
        spacePath = _getHangarPath(isPremium, isIGR)
        spaceType = _getHangarType(isPremium)
        LOG_DEBUG(
            'load hangar: hangar type = <{0:>s}>, space = <{1:>s}>'.format(
                spaceType, spacePath))
        safeSpacePath = _getDefaultHangarPath(False)
        if ResMgr.openSection(spacePath) is None:
            LOG_ERROR(
                'Failed to load hangar from path: %s; default hangar will be loaded instead'
                % spacePath)
            spacePath = safeSpacePath
        try:
            self.__spaceMappingId = BigWorld.addSpaceGeometryMapping(
                self.__spaceId, None, spacePath)
        except Exception:
            try:
                LOG_CURRENT_EXCEPTION()
                spacePath = safeSpacePath
                self.__spaceMappingId = BigWorld.addSpaceGeometryMapping(
                    self.__spaceId, None, spacePath)
            except Exception:
                BigWorld.releaseSpace(self.__spaceId)
                self.__spaceMappingId = None
                self.__spaceId = None
                LOG_CURRENT_EXCEPTION()
                return

        spaceKey = _getHangarKey(spacePath)
        _CFG = copy.deepcopy(_HANGAR_CFGS[spaceKey])
        self.__vEntityId = BigWorld.createEntity(
            'HangarVehicle', self.__spaceId, 0, _CFG['v_start_pos'],
            (_CFG['v_start_angles'][2], _CFG['v_start_angles'][1],
             _CFG['v_start_angles'][0]), dict())
        self.__cameraManager = HangarCameraManager(self.__spaceId)
        self.__cameraManager.init()
        self.__waitCallback = BigWorld.callback(0.1, self.__waitLoadingSpace)
        self.__gfxOptimizerMgr = GraphicsOptimizationManager()
        size = BigWorld.screenSize()
        self.__optimizerID = self.__gfxOptimizerMgr.registerOptimizationArea(
            0, 0, size[0], size[1])
        MapActivities.g_mapActivities.generateOfflineActivities(spacePath)
        BigWorld.pauseDRRAutoscaling(True)
        return
Exemplo n.º 57
0
    def __init__(self):
        self.xfwping = None
        self.lock = threading.RLock()
        self.thread = None
        self.resp = None
        self.done_config = False
        self.loginSection = ResMgr.openSection('scripts_config.xml')['login']

        #import XFW.Ping
        self.xfwping = loader.get_mod_module('com.modxvm.xfw.ping')
        if not self.xfwping:
            logging.warning(
                "[XVM/Ping] [pinger/init]: failed to import XFW.Ping. Ping results will be unavailable."
            )
Exemplo n.º 58
0
def load(messengerSettings):
    section = ResMgr.openSection(MESSENGER_XML_FILE_PATH)
    xmlCtx = XMLCtx(MESSENGER_XML_FILE_PATH)
    if section is None:
        raise XMLError(xmlCtx, 'Messenger settings file is not found')
    tags = section.keys()
    for tag, isRequired, loader in _LOADERS:
        if tag in tags:
            subSec = section[tag]
            loader(xmlCtx.next(subSec), subSec, messengerSettings)
        elif isRequired:
            raise XMLError(xmlCtx, 'Tag "{0:>s}" not found'.format(tag))

    return
Exemplo n.º 59
0
    def __init__(self):
        self._profiles = {}
        destructionProfilesRaw = ResMgr.openSection(
            consts.SHAKING_PROFILES_PATH)
        if destructionProfilesRaw:
            rawProfiles = destructionProfilesRaw['profiles']
            for rawProfile in rawProfiles.values():
                profileId = rawProfile['id'].asString
                self._profiles[profileId] = Profile(rawProfile)

            ResMgr.purge(consts.SHAKING_PROFILES_PATH)
        else:
            CRITICAL_ERROR("Can't load or corrupted data file.",
                           consts.SHAKING_PROFILES_PATH)
Exemplo n.º 60
0
    def __readXML(self):
        rootSection = ResMgr.openSection(self.COLOR_SCHEMES_FILE)
        if rootSection is None:
            LOG_ERROR('Color schemes file loading failed: %s' % self.COLOR_SCHEMES_FILE)
            return
        else:
            xmlHash = self.__readHash(rootSection)
            xmlHash = self.__overrideTags(xmlHash, xmlHash)
            for scheme_name in xmlHash.keys():
                scheme = xmlHash[scheme_name]
                color_scheme = self.__readColorScheme(scheme)
                self.__colors[scheme_name] = color_scheme

            return