def hasTagInTankmenGroup(nationID, groupID, isPremium, tag):
    nationGroups = getNationGroups(nationID, isPremium)
    if groupID not in nationGroups:
        LOG_WARNING('tankmen.hasTagInTankmenGroup: wrong value of the groupID (unknown groupID)', groupID)
        return False
    return tag in nationGroups[groupID].tags
Exemple #2
0
    def __readXML(self,
                  section,
                  curTime,
                  gStartTime=DEFAULT_QUEST_START_TIME,
                  gFinishTime=DEFAULT_QUEST_FINISH_TIME):
        nodes = {}
        for typeName, questSection in section.items():
            enabled = questSection.readBool('enabled', False)
            if not enabled:
                continue
            eventType = EVENT_TYPE.NAME_TO_TYPE[typeName]
            mainNode = XMLNode('main')
            mainNode.info = info = self.__readHeader(eventType, questSection,
                                                     curTime, gStartTime,
                                                     gFinishTime)
            if not info['announceTime'] <= curTime <= info['finishTime']:
                LOG_WARNING('Skipping outdated quest', info['id'], curTime,
                            info['announceTime'], info['finishTime'])
                continue
            if eventType == EVENT_TYPE.GROUP:
                mainNode.groupContent = tuple(
                    self.__readGroupContent(questSection))
            conditionReaders = self.__getConditionReaders(eventType)
            availableBonuses = self.__getAvailableBonuses(eventType)
            commonNode = XMLNode('common')
            bonusNode = XMLNode('bonus')
            bonusDelayedNode = XMLNode('bonusDelayed')
            prebattleNode = XMLNode('preBattle')
            accountNode = XMLNode('account')
            prebattleNode.addChild(accountNode)
            vehicleNode = XMLNode('vehicle')
            prebattleNode.addChild(vehicleNode)
            battleNode = XMLNode('battle')
            prebattleNode.addChild(battleNode)
            postbattleNode = XMLNode('postBattle')
            mainNode.addChild(prebattleNode)
            mainNode.addChild(postbattleNode)
            mainNode.addChild(commonNode)
            mainNode.addChild(bonusNode)
            mainNode.addChild(bonusDelayedNode)
            info['isIGR'] = accountNode.isExistChildNode('igrType')
            conditions = questSection['conditions']
            if conditions and conditions.has_key('preBattle'):
                condition = conditions['preBattle']
                if condition.has_key('account'):
                    self.__readBattleResultsConditionList(
                        conditionReaders, condition['account'], accountNode)
                if eventType in EVENT_TYPE.LIKE_BATTLE_QUESTS:
                    if condition.has_key('vehicle'):
                        self.__readBattleResultsConditionList(
                            conditionReaders, condition['vehicle'],
                            vehicleNode)
                    if condition.has_key('battle'):
                        self.__readBattleResultsConditionList(
                            conditionReaders, condition['battle'], battleNode)
            if eventType in EVENT_TYPE.LIKE_BATTLE_QUESTS and conditions and conditions.has_key(
                    'postBattle'):
                condition = conditions['postBattle']
                self.__readBattleResultsConditionList(conditionReaders,
                                                      condition,
                                                      postbattleNode)
            if conditions and conditions.has_key('common'):
                condition = conditions['common']
                self.__readBattleResultsConditionList(conditionReaders,
                                                      condition, commonNode)
            daily = commonNode.getChildNode('daily')
            info['isDaily'] = daily is not None
            groupBy = commonNode.getChildNode('groupBy')
            info['groupBy'] = groupBy.getChildNode(
                'groupName').getFirstChildValue() if groupBy else None
            inrow = commonNode.getChildNode('inrow')
            unit = commonNode.getChildNode('unit')
            bonusLimit = commonNode.getChildNode('bonusLimit')
            cumulative = commonNode.getChildNode('cumulative')
            vehicleKills = commonNode.getChildNode('vehicleKills')
            battles = commonNode.getChildNode('battles')
            battleCount = battles.getChildNode(
                'count').getFirstChildValue() if battles else None
            if bonusLimit is None:
                bonusLimitNode = XMLNode('bonusLimit')
                bonusLimitNode.addChild(1 if eventType in EVENT_TYPE.
                                        ONE_BONUS_QUEST else MAX_BONUS_LIMIT)
                commonNode.addChild(bonusLimitNode)
            if eventType in EVENT_TYPE.LIKE_BATTLE_QUESTS:
                if (cumulative or unit or vehicleKills) and inrow:
                    raise SoftException(
                        'battleQuest: Unexpected tags (vehicleKills, cumulative, unit/cumulative) with inrow'
                    )
                if not (cumulative or unit or vehicleKills or bonusLimit
                        or battles) and (daily or groupBy):
                    raise SoftException(
                        'battleQuest: daily and groupBy should be used with cumulative, unit, vehicleKills, bonusLimit or battles tags'
                    )
                if battles and not battleCount:
                    raise SoftException('Invalid battles section')
            elif eventType in EVENT_TYPE.LIKE_TOKEN_QUESTS:
                if cumulative or unit or vehicleKills or groupBy or battles:
                    raise SoftException(
                        'tokenQuest: Unexpected tags (cumulative, unit, vehicleKills, groupBy, battles)'
                    )
                if not bonusLimit and daily:
                    raise SoftException(
                        'tokenQuest: daily should be used with bonusLimit tag')
            mainNode.bonus = walkBonuses(
                readBonusSection(availableBonuses, questSection['bonus'],
                                 eventType), FilterVisitor(eventType))
            mainNode.bonusDelayed = walkBonuses(
                readBonusSection(availableBonuses,
                                 questSection['bonusDelayed'], eventType),
                FilterVisitor(eventType))
            questClientData = dict(info)
            questClientData['bonus'] = deepcopy(mainNode.bonus)
            if mainNode.bonusDelayed is not None:
                questClientData['bonus'].update(mainNode.bonusDelayed)
            questClientData['bonusDelayed'] = deepcopy(mainNode.bonusDelayed)
            questClientData['conditions'] = mainNode.questClientConditions
            if mainNode.groupContent:
                questClientData['groupContent'] = mainNode.groupContent
            self.__stripServerQuestData(questClientData)
            mainNode.info['questClientData'] = questClientData
            nodes.setdefault(eventType, []).append(mainNode)

        return nodes
Exemple #3
0
 def _makeResponse(self, code=0, errMsg='', data=None, ctx=None):
     response = self._Response(code, errMsg, data)
     if not response.isSuccess():
         LOG_WARNING('Avatar request error', ctx, response)
     return response
Exemple #4
0
 def _errorHandler(self, code, errStr='', ctx=None):
     LOG_WARNING('Error on server request to get battle results ',
                 self.__arenaUniqueID, code, errStr, ctx)
     return makeError()
Exemple #5
0
 def validate(self, actionsHolder):
     for idx, button in enumerate(self._buttons[:]):
         if not actionsHolder.hasAllActions(button.action):
             self._buttons[idx] = self._buttons[idx]._replace(visible=False)
             LOG_WARNING('Some actions are not defined for button', button)
Exemple #6
0
    def _updateTeamData(self, isEnemy, team, arenaDP, isFragsUpdate=True):
        pNamesList, fragsList, vNamesList, additionalDataList, pNamesListPanels = (
            [], [], [], [], [])
        valuesHashes = []
        ctx = makeTeamCtx(team, isEnemy, arenaDP,
                          int(self._battleUI.getPlayerNameLength(isEnemy)),
                          int(self._battleUI.getVehicleNameLength(isEnemy)),
                          self._battleUI.getCameraVehicleID())
        if isFragsUpdate:
            fragCorrelation = self._battleUI.fragCorrelation
            fragCorrelation.clear(team)
            collection = vos_collections.TeamVehiclesInfoCollection(team)
            for vInfoVO in collection.iterator(arenaDP):
                if not vInfoVO.isObserver():
                    fragCorrelation.addVehicle(
                        team, vInfoVO.vehicleID,
                        vInfoVO.vehicleType.getClassName(), vInfoVO.isAlive())
                    if not vInfoVO.isAlive():
                        fragCorrelation.addKilled(team)

        playerAccountID = getAvatarDatabaseID()
        inviteSendingProhibited = isEnemy or self.prbInvites.getSentInviteCount(
        ) >= 100
        if not inviteSendingProhibited:
            inviteSendingProhibited = not self._isSquadAllowToInvite(arenaDP)
        invitesReceivingProhibited = arenaDP.getVehicleInfo(
            playerAccountID).player.forbidInBattleInvitations
        isPlayerObserver = self._battleCtx.isPlayerObserver()
        if self._arenaVisitor.hasRespawns():
            sortKey = vos_collections.RespawnSortKey
        else:
            sortKey = vos_collections.VehicleInfoSortKey
        if isEnemy:
            collection = vos_collections.EnemyItemsCollection(sortKey=sortKey)
        else:
            collection = vos_collections.AllyItemsCollection(sortKey=sortKey)
        for index, (vInfoVO,
                    vStatsVO) in enumerate(collection.iterator(arenaDP)):
            if index >= PLAYERS_PANEL_LENGTH:
                LOG_WARNING('Max players in panel are', PLAYERS_PANEL_LENGTH)
                break
            if vInfoVO.isObserver() and isPlayerObserver:
                continue
            playerFullName = self._battleCtx.getPlayerFullName(
                vID=vInfoVO.vehicleID, showVehShortName=False)
            if not playerFullName:
                playerFullName = vInfoVO.player.getPlayerLabel()
            valuesHash = self._makeHash(index, playerFullName, vInfoVO,
                                        vStatsVO, ctx, playerAccountID,
                                        inviteSendingProhibited,
                                        invitesReceivingProhibited, isEnemy)
            pName, frags, vName, additionalData, pNamePanels = self._battleUI.statsForm.getFormattedStrings(
                vInfoVO, vStatsVO, ctx, playerFullName)
            pNamesList.append(pName)
            fragsList.append(frags)
            vNamesList.append(vName)
            additionalDataList.append(additionalData)
            valuesHashes.append(valuesHash)
            pNamesListPanels.append(pNamePanels)

        self._battleUI.setTeamValuesData(
            self._makeTeamValues(isEnemy, ctx, pNamesList, fragsList,
                                 vNamesList, additionalDataList, valuesHashes,
                                 pNamesListPanels))
 def onOptionSelect(self, optionId):
     if optionId in self.__handlers:
         return getattr(self, self.__handlers[optionId])()
     LOG_WARNING('Unknown context menu option', self, self.__cmProxy,
                 optionId)
    def readScriptConfig(self, dataSection, userDataSection=None):
        if self._isDataLoaded or dataSection is None:
            return
        else:

            def _readSvrList(section, nodeName):
                if section is not None and section.has_key(nodeName):
                    return section[nodeName].items()
                else:
                    return []

            self.__csisUrl = dataSection.readString('csisUrl')
            self._hosts = []
            self._urlMap.clear()
            self._nameMap.clear()
            self._peripheryMap.clear()
            svrList = _readSvrList(dataSection, 'login') + _readSvrList(
                userDataSection, 'development/login')
            for name, subSec in svrList:
                name = subSec.readString('name')
                shortName = subSec.readString('short_name')
                urls = _LoginAppUrlIterator(subSec.readStrings('url'))
                host = urls.primary
                if host is not None:
                    if not name:
                        name = host
                    keyPath = subSec.readString('public_key_path')
                    if not keyPath:
                        keyPath = None
                    areaID = subSec.readString('game_area_id')
                    if not areaID:
                        areaID = None
                    app = self._makeHostItem(
                        name,
                        shortName,
                        host,
                        urlToken=subSec.readString('url_token'),
                        urlIterator=urls if len(urls) > 1 else None,
                        keyPath=keyPath,
                        areaID=areaID,
                        peripheryID=subSec.readInt('periphery_id', 0))
                    idx = len(self._hosts)
                    url = app.url
                    if url in self._urlMap:
                        LOG_WARNING(
                            'Host url is already added. This host is ignored',
                            url)
                        continue
                    self._urlMap[url] = idx
                    urlToken = app.urlToken
                    if urlToken:
                        if urlToken in self._urlMap:
                            LOG_WARNING(
                                'Alternative host url is already added. This url is ignored',
                                app.url)
                        else:
                            self._urlMap[urlToken] = idx
                    self._nameMap[app.name] = idx
                    self._peripheryMap[app.peripheryID] = idx
                    self._hosts.append(app)

            self._isDataLoaded = True
            return
 def revoke(self, callback=None):
     LOG_WARNING('Old-style invite can not be revoked')
 def select(self):
     LOG_WARNING('That routine can not be invoked')
 def setOnlineMode(self, onlineMode):
     if onlineMode is None:
         return super(TemporaryIgnoredFindCriteria, self).setOnlineMode(onlineMode)
     else:
         LOG_WARNING('Online mode for temporary ignored list will be skipped')
         return
    def __makeProgresData(self):
        refSystem = game_control.g_instance.refSystem
        totalXP = refSystem.getTotalXP()
        currentXP = refSystem.getReferralsXPPool()
        progressText = '%(currentXP)s / %(totalXP)s %(icon)s' % {
            'currentXP':
            text_styles.credits(BigWorld.wg_getIntegralFormat(currentXP)),
            'totalXP':
            BigWorld.wg_getIntegralFormat(totalXP),
            'icon':
            icons.makeImageTag(RES_ICONS.MAPS_ICONS_LIBRARY_NORMALXPICON, 16,
                               16, -3, 0)
        }
        text = i18n.makeString(
            MENU.REFERRALMANAGEMENTWINDOW_PROGRESSINDICATOR_PROGRESS,
            progress=progressText)
        awardData = {}
        progresData = {'text': text_styles.main(text)}
        progressAlertText = ''
        if refSystem.isTotallyCompleted():
            completedText = i18n.makeString(
                MENU.REFERRALMANAGEMENTWINDOW_PROGRESSINDICATOR_COMPLETE)
            completedText = text_styles.middleTitle(completedText)
            awardData['completedText'] = completedText
            _, lastStepQuests = refSystem.getQuests()[-1]
            vehicleBonus = findFirst(lambda q: q.getBonuses('vehicles'),
                                     reversed(lastStepQuests))
            vehicleBonusIcon = ''
            if vehicleBonus is not None:
                vehicleBonusIcon = vehicleBonus.getBonuses(
                    'vehicles')[0].getTooltipIcon()
            awardData['completedImage'] = vehicleBonusIcon
        else:
            stepsData = []
            progress = 0.0
            quests = refSystem.getQuests()
            totalQuestsCount = len(
                tuple(itertools.chain(*dict(quests).values())))
            if quests and totalQuestsCount == self.TOTAL_QUESTS:
                currentCompletedStep = -1
                totalSteps = len(quests)
                lastStep = totalSteps - 1
                for i, (xp, events) in enumerate(quests):
                    notCompleted = filter(lambda q: not q.isCompleted(),
                                          reversed(events))
                    lastNotCompleted = findFirst(None, notCompleted)
                    if lastNotCompleted is not None:
                        questIDs = map(methodcaller('getID'), notCompleted)
                        icon = self.__getBonusIcon(lastNotCompleted)
                    else:
                        questIDs = map(methodcaller('getID'), events)
                        icon = RES_ICONS.MAPS_ICONS_LIBRARY_COMPLETE
                        currentCompletedStep = i
                    stepsData.append({
                        'id': pickle.dumps((xp, questIDs)),
                        'icon': icon
                    })

                nextStep = min(currentCompletedStep + 1, lastStep)
                nextStepXP, _ = quests[nextStep]
                if currentXP:
                    totalProgress = 0.0
                    currentCompletedStepXP = 0
                    oneStepWeight = 1.0 / totalSteps
                    if currentCompletedStep != -1:
                        currentCompletedStepXP, _ = quests[
                            currentCompletedStep]
                        totalProgress = (currentCompletedStep +
                                         1) * oneStepWeight
                    xpForNextStep = nextStepXP - currentCompletedStepXP
                    xpFromPrevStep = currentXP - currentCompletedStepXP
                    stepProgress = float(xpFromPrevStep) / xpForNextStep
                    totalStepProgress = stepProgress * oneStepWeight
                    progress = totalProgress + totalStepProgress
            else:
                LOG_WARNING('Referral quests is in invalid state: ', quests)
                progressAlertIcon = icons.alert()
                progressAlertText = text_styles.alert(
                    i18n.makeString(
                        MENU.REFERRALMANAGEMENTWINDOW_PROGRESSNOTAVAILABLE))
                progressAlertText = i18n.makeString(progressAlertIcon + ' ' +
                                                    progressAlertText)
            progresData.update({'steps': stepsData, 'progress': progress})
        if progressAlertText != '':
            self.as_showAlertS(progressAlertText)
        elif refSystem.isTotallyCompleted():
            self.as_setAwardDataDataS(awardData)
        else:
            self.as_setProgressDataS(progresData)
Exemple #13
0
def getStyle(currency):
    if currency in _CURRENCY_TO_TEXT_STYLE:
        return _CURRENCY_TO_TEXT_STYLE[currency]
    LOG_WARNING('Text style is not set for the following currency: ', currency)
    return lambda txt: str(txt)
Exemple #14
0
def getBWFormatter(currency):
    if currency in _CURRENCY_TO_BW_FORMATTER:
        return _CURRENCY_TO_BW_FORMATTER[currency]
    LOG_WARNING('BW formatter is not set for the following currency: ',
                currency)
    return BigWorld.wg_getIntegralFormat
Exemple #15
0
 def getItemFormat(cls, itemType, itemValue):
     if itemType not in cls._formats:
         LOG_WARNING('Type of item is not found', itemType, itemValue)
         return str(itemValue)
     method = cls._formats[itemType]
     return getattr(cls, method)(itemValue)
 def revoke(self, callback=None):
     LOG_WARNING('Need to call valid Account method')
Exemple #17
0
 def setOnlineMode(self, onlineMode):
     if onlineMode is None:
         return super(IgnoredFindCriteria, self).setOnlineMode(onlineMode)
     LOG_WARNING('Online mode for ignored list will be skipped')
Exemple #18
0
 def load(self, loadParams, *args, **kwargs):
     viewKey = loadParams.viewKey
     viewLoadingItem = self.__loader.getViewLoadingItem(viewKey)
     if viewLoadingItem is not None:
         LOG_DEBUG('View with key {} is already loading. item=[{}]'.format(
             viewKey, viewLoadingItem))
         view = viewLoadingItem.pyEntity
         if loadParams.loadMode == ViewLoadMode.DEFAULT:
             loadingViewLoadMode = viewLoadingItem.loadParams.loadMode
             if loadingViewLoadMode == ViewLoadMode.PRELOAD:
                 viewLoadingItem.loadParams = loadParams
                 self.__addLoadingView(view)
         elif loadParams.loadMode == ViewLoadMode.PRELOAD:
             pass
         else:
             LOG_WARNING(
                 'Unsupported load mode {}. View loading will be skipped.'.
                 format(loadParams))
             view = None
     else:
         view = self.__globalContainer.findView(viewKey)
         if view is None:
             view = self.__viewCache.getView(viewKey)
             if view is None:
                 chain = self.__chainMng.getChainByViewKey(viewKey)
                 if chain is not None:
                     LOG_WARNING(
                         'View with loadParams={} is in the loading chain {}. The request will be skipped.'
                         .format(loadParams, chain))
                 else:
                     LOG_DEBUG(
                         'Load view with loadParams={}. Loader=[{}]'.format(
                             loadParams, self.__loader))
                     if loadParams.loadMode == ViewLoadMode.DEFAULT:
                         view = self.__loader.loadView(
                             loadParams, *args, **kwargs)
                         self.__addLoadingView(view)
                     elif loadParams.loadMode == ViewLoadMode.PRELOAD:
                         view = self.__loader.loadView(
                             loadParams, *args, **kwargs)
                     else:
                         LOG_WARNING(
                             'Unsupported load mode {}. View loading will be skipped.'
                             .format(loadParams))
             elif loadParams.loadMode == ViewLoadMode.PRELOAD:
                 LOG_DEBUG(
                     'View with key {} ({}) is already pre-loaded.'.format(
                         viewKey, view))
             elif loadParams.loadMode == ViewLoadMode.DEFAULT:
                 LOG_DEBUG(
                     'Load view with loadParams={} from the cache. Cache=[{}]'
                     .format(loadParams, self.__viewCache))
                 self.__viewCache.removeView(viewKey)
                 self.__showAndInitializeView(view)
                 view.validate(*args, **kwargs)
             else:
                 LOG_WARNING(
                     'Unsupported load mode {}. View loading will be skipped.'
                     .format(loadParams))
                 view = None
         else:
             LOG_DEBUG('View with key {} ({}) is already loaded.'.format(
                 viewKey, view))
             viewType = view.settings.type
             viewContainer = self.__globalContainer.findContainer(viewType)
             viewContainer.addView(view)
             view.validate(*args, **kwargs)
     return view
def _getHandlerClass(handlerType):
    if handlerType in _handlers:
        return _handlers[handlerType]
    else:
        LOG_WARNING('Unknown context menu handler type', handlerType)
        return None
Exemple #20
0
 def _onEmblemReceived(_, emblem):
     imgSize = getImageSize(emblem)
     if imgSize != size:
         LOG_WARNING('Received emblem has invalid size, use default instead', imgSize, size, url, type(emblem))
         emblem = defaultEmblemGetter(size)
     callback(emblem)
 def __setData(self):
     seasonID, cohort, _ = ranked_helpers.getRankedDataFromTokenQuestID(
         self._quest.getID())
     season = self.rankedController.getSeason(int(seasonID))
     if season is not None:
         leagueData = yield self.rankedController.getLeagueData()
         if leagueData is not None:
             position = BigWorld.wg_getNiceNumberFormat(
                 leagueData['position'])
             league = leagueData.get('league', 0)
         else:
             position = '0'
             league = 0
         itemsCache = dependency.instance(IItemsCache)
         dossier = itemsCache.items.getAccountDossier(
         ).getPreviousSeasonRankedStats()
         seasonPoints = season.getPoints()
         efficiency = dossier.getStepsEfficiency()
         if efficiency is not None:
             efficiencyValue = efficiency * 100
         else:
             efficiencyValue = 0
         avgExp = dossier.getAvgXP()
         if avgExp is None:
             avgExp = 0
         self.as_setDataS({
             'leagueImage':
             RES_ICONS.getRankedWebLeagueIcon('big', league),
             'scoresValue':
             BigWorld.wg_getNiceNumberFormat(seasonPoints),
             'scoresLabel':
             _ms(RANKED_BATTLES.SEASONCOMPLETE_TOTALSCORES),
             'effectValue':
             BigWorld.wg_getIntegralFormat(efficiencyValue),
             'effectLabel':
             _ms(RANKED_BATTLES.SEASONCOMPLETE_EFFECTLABEL),
             'placeValue':
             position,
             'placeLabel':
             _ms(RANKED_BATTLES.SEASONCOMPLETE_PLACEINRATING),
             'expValue':
             BigWorld.wg_getIntegralFormat(avgExp),
             'expLabel':
             _ms(RANKED_BATTLES.SEASONCOMPLETE_EXPLABEL),
             'congratulationTitle':
             _ms(RANKED_BATTLES.SEASONCOMPLETE_BIGTITLE,
                 season=str(season.getNumber())),
             'typeTitle':
             _ms(RANKED_BATTLES.SEASONCOMPLETE_SMALLTITLE),
             'typeIcon':
             RES_ICONS.MAPS_ICONS_BATTLETYPES_40X40_RANKED,
             'nextButtonLabel':
             _ms(RANKED_BATTLES.SEASONCOMPLETE_LEADERSBUTTON),
             'bgSource':
             RES_ICONS.MAPS_ICONS_RANKEDBATTLES_BG_RANK_BLUR,
             'leagueLabel':
             _ms(RANKED_BATTLES.SEASONCOMPLETE_UNDERLABEL)
         })
         self.as_setRewardsDataS({
             'ribbonType': 'ribbon2',
             'rendererLinkage': 'RibbonAwardAnimUI',
             'gap': 20,
             'rendererWidth': 80,
             'rendererHeight': 80,
             'awards': self._packAwards()
         })
     else:
         LOG_WARNING(
             'Try to show RankedBattlesSeasonCompleteView, but season is None. Params: ',
             seasonID, cohort)
     return
 def __logModuleWarning():
     LOG_WARNING(
         'Unable to apply the following modules type: {}'.format(
             self.__currentModulesType))
Exemple #23
0
 def warning(self, area, message, *args):
     if area != CLIENT_LOG_AREA.GLOOX_XML:
         LOG_WARNING(self.__makeHeader(area, message), *args)
Exemple #24
0
def fireCoolDownEvent(scopeID, rqTypeID, coolDown = DEFAULT_COOLDOWN_TO_REQUEST):
    if scopeID not in _REQUEST_SCOPE_TO_EVENT:
        LOG_WARNING('Type of event is not found, it is ignored', scopeID)
        return
    g_eventBus.handleEvent(events.CoolDownEvent(_REQUEST_SCOPE_TO_EVENT[scopeID], rqTypeID, coolDown), scope=EVENT_BUS_SCOPE.LOBBY)
Exemple #25
0
 def __readCfg(self, dataSec):
     if not dataSec:
         LOG_WARNING(
             'Invalid section <sniperMode/camera> in avatar_input_handler.xml'
         )
     self.__baseCfg = dict()
     bcfg = self.__baseCfg
     bcfg['keySensitivity'] = readFloat(dataSec, 'keySensitivity', 0, 10,
                                        0.005)
     bcfg['sensitivity'] = readFloat(dataSec, 'sensitivity', 0, 10, 0.005)
     bcfg['scrollSensitivity'] = readFloat(dataSec, 'scrollSensitivity', 0,
                                           10, 0.005)
     zooms = readVec3(dataSec, 'zooms', (0, 0, 0), (10, 10, 10), (2, 4, 8))
     bcfg['zooms'] = [zooms.x, zooms.y, zooms.z]
     ds = Settings.g_instance.userPrefs[Settings.KEY_CONTROL_MODE]
     if ds is not None:
         ds = ds['sniperMode/camera']
     self.__userCfg = dict()
     ucfg = self.__userCfg
     from account_helpers.settings_core.SettingsCore import g_settingsCore
     ucfg['horzInvert'] = g_settingsCore.getSetting('mouseHorzInvert')
     ucfg['vertInvert'] = g_settingsCore.getSetting('mouseVertInvert')
     ucfg['keySensitivity'] = readFloat(ds, 'keySensitivity', 0.0, 10.0,
                                        1.0)
     ucfg['sensitivity'] = readFloat(ds, 'sensitivity', 0.0, 10.0, 1.0)
     ucfg['scrollSensitivity'] = readFloat(ds, 'scrollSensitivity', 0.0,
                                           10.0, 1.0)
     ucfg['zoom'] = readFloat(ds, 'zoom', 0.0, 10.0, bcfg['zooms'][0])
     self.__cfg = dict()
     cfg = self.__cfg
     cfg['keySensitivity'] = bcfg['keySensitivity']
     cfg['sensitivity'] = bcfg['sensitivity']
     cfg['scrollSensitivity'] = bcfg['scrollSensitivity']
     cfg['zooms'] = bcfg['zooms']
     cfg['keySensitivity'] *= ucfg['keySensitivity']
     cfg['sensitivity'] *= ucfg['sensitivity']
     cfg['scrollSensitivity'] *= ucfg['scrollSensitivity']
     cfg['horzInvert'] = ucfg['horzInvert']
     cfg['vertInvert'] = ucfg['vertInvert']
     cfg['zoom'] = ucfg['zoom']
     dynamicsSection = dataSec['dynamics']
     self.__impulseOscillator = createOscillatorFromSection(
         dynamicsSection['impulseOscillator'])
     self.__movementOscillator = createOscillatorFromSection(
         dynamicsSection['movementOscillator'])
     self.__noiseOscillator = createOscillatorFromSection(
         dynamicsSection['randomNoiseOscillatorSpherical'])
     self.__dynamicCfg.readImpulsesConfig(dynamicsSection)
     self.__dynamicCfg['accelerationSensitivity'] = readVec3(
         dynamicsSection, 'accelerationSensitivity', (-1000, -1000, -1000),
         (1000, 1000, 1000), (0.5, 0.5, 0.5))
     accelerationThreshold = readFloat(dynamicsSection,
                                       'accelerationThreshold', 0.0, 1000.0,
                                       0.1)
     self.__dynamicCfg['accelerationThreshold'] = accelerationThreshold
     self.__dynamicCfg['accelerationMax'] = readFloat(
         dynamicsSection, 'accelerationMax', 0.0, 1000.0, 0.1)
     self.__dynamicCfg['maxShotImpulseDistance'] = readFloat(
         dynamicsSection, 'maxShotImpulseDistance', 0.0, 1000.0, 10.0)
     self.__dynamicCfg['maxExplosionImpulseDistance'] = readFloat(
         dynamicsSection, 'maxExplosionImpulseDistance', 0.0, 1000.0, 10.0)
     self.__dynamicCfg['impulsePartToRoll'] = readFloat(
         dynamicsSection, 'impulsePartToRoll', 0.0, 1000.0, 0.3)
     self.__dynamicCfg['pivotShift'] = Vector3(
         0, readFloat(dynamicsSection, 'pivotShift', -1000, 1000, -0.5), 0)
     self.__dynamicCfg['aimMarkerDistance'] = readFloat(
         dynamicsSection, 'aimMarkerDistance', -1000, 1000, 1.0)
     self.__dynamicCfg['zoomExposure'] = readVec3(dynamicsSection,
                                                  'zoomExposure',
                                                  (0.1, 0.1, 0.1),
                                                  (10, 10, 10),
                                                  (0.5, 0.5, 0.5))
     accelerationFilter = mathUtils.RangeFilter(
         self.__dynamicCfg['accelerationThreshold'],
         self.__dynamicCfg['accelerationMax'], 100,
         mathUtils.SMAFilter(SniperCamera._FILTER_LENGTH))
     maxAccelerationDuration = readFloat(
         dynamicsSection, 'maxAccelerationDuration', 0.0, 10000.0,
         SniperCamera._DEFAULT_MAX_ACCELERATION_DURATION)
     self.__accelerationSmoother = AccelerationSmoother(
         accelerationFilter, maxAccelerationDuration)
Exemple #26
0
    def __readCfg(self, dataSec):
        if dataSec is None:
            LOG_WARNING(
                'Invalid section <arcadeMode/camera> in avatar_input_handler.xml'
            )
        self.__baseCfg = dict()
        bcfg = self.__baseCfg
        bcfg['keySensitivity'] = readFloat(dataSec, 'keySensitivity', 0, 10,
                                           0.01)
        bcfg['sensitivity'] = readFloat(dataSec, 'sensitivity', 0, 10, 0.01)
        bcfg['scrollSensitivity'] = readFloat(dataSec, 'scrollSensitivity', 0,
                                              10, 0.01)
        bcfg['angleRange'] = readVec2(dataSec, 'angleRange', (0, 0),
                                      (180, 180), (10, 110))
        distRangeVec = readVec2(dataSec, 'distRange', (1, 1), (100, 100),
                                (2, 20))
        bcfg['distRange'] = MinMax(distRangeVec.x, distRangeVec.y)
        bcfg['minStartDist'] = readFloat(dataSec, 'minStartDist',
                                         bcfg['distRange'][0],
                                         bcfg['distRange'][1],
                                         bcfg['distRange'][0])
        bcfg['optimalStartDist'] = readFloat(dataSec, 'optimalStartDist',
                                             bcfg['distRange'][0],
                                             bcfg['distRange'][1],
                                             bcfg['distRange'][0])
        bcfg['angleRange'][0] = math.radians(
            bcfg['angleRange'][0]) - math.pi * 0.5
        bcfg['angleRange'][1] = math.radians(
            bcfg['angleRange'][1]) - math.pi * 0.5
        bcfg['fovMultMinMaxDist'] = MinMax(
            readFloat(dataSec, 'fovMultMinDist', 0.1, 100, 1.0),
            readFloat(dataSec, 'fovMultMaxDist', 0.1, 100, 1.0))
        ds = Settings.g_instance.userPrefs[Settings.KEY_CONTROL_MODE]
        if ds is not None:
            ds = ds['arcadeMode/camera']
        self.__userCfg = dict()
        ucfg = self.__userCfg
        ucfg['horzInvert'] = self.settingsCore.getSetting('mouseHorzInvert')
        ucfg['vertInvert'] = self.settingsCore.getSetting('mouseVertInvert')
        ucfg['sniperModeByShift'] = self.settingsCore.getSetting(
            'sniperModeByShift')
        ucfg['keySensitivity'] = readFloat(ds, 'keySensitivity', 0.0, 10.0,
                                           1.0)
        ucfg['sensitivity'] = readFloat(ds, 'sensitivity', 0.0, 10.0, 1.0)
        ucfg['scrollSensitivity'] = readFloat(ds, 'scrollSensitivity', 0.0,
                                              10.0, 1.0)
        ucfg['startDist'] = readFloat(ds, 'startDist', bcfg['distRange'][0],
                                      500, bcfg['optimalStartDist'])
        if ucfg['startDist'] < bcfg['minStartDist']:
            ucfg['startDist'] = bcfg['optimalStartDist']
        ucfg['startAngle'] = readFloat(ds, 'startAngle', 5, 180, 60)
        ucfg['startAngle'] = math.radians(ucfg['startAngle']) - math.pi * 0.5
        ucfg['fovMultMinMaxDist'] = MinMax(
            readFloat(ds, 'fovMultMinDist', 0.1, 100,
                      bcfg['fovMultMinMaxDist'].min),
            readFloat(ds, 'fovMultMaxDist', 0.1, 100,
                      bcfg['fovMultMinMaxDist'].max))
        self.__cfg = dict()
        cfg = self.__cfg
        cfg['keySensitivity'] = bcfg['keySensitivity']
        cfg['sensitivity'] = bcfg['sensitivity']
        cfg['scrollSensitivity'] = bcfg['scrollSensitivity']
        cfg['angleRange'] = bcfg['angleRange']
        cfg['distRange'] = bcfg['distRange']
        cfg['minStartDist'] = bcfg['minStartDist']
        cfg['horzInvert'] = ucfg['horzInvert']
        cfg['vertInvert'] = ucfg['vertInvert']
        cfg['keySensitivity'] *= ucfg['keySensitivity']
        cfg['sensitivity'] *= ucfg['sensitivity']
        cfg['scrollSensitivity'] *= ucfg['scrollSensitivity']
        cfg['startDist'] = ucfg['startDist']
        cfg['startAngle'] = ucfg['startAngle']
        cfg['fovMultMinMaxDist'] = ucfg['fovMultMinMaxDist']
        cfg['sniperModeByShift'] = ucfg['sniperModeByShift']
        enableShift = dataSec.readBool('shift', False)
        if enableShift:
            movementMappings = dict()
            movementMappings[Keys.KEY_A] = Math.Vector3(-1, 0, 0)
            movementMappings[Keys.KEY_D] = Math.Vector3(1, 0, 0)
            movementMappings[Keys.KEY_Q] = Math.Vector3(0, 1, 0)
            movementMappings[Keys.KEY_E] = Math.Vector3(0, -1, 0)
            movementMappings[Keys.KEY_W] = Math.Vector3(0, 0, 1)
            movementMappings[Keys.KEY_S] = Math.Vector3(0, 0, -1)
            shiftSensitivity = dataSec.readFloat('shiftSensitivity', 0.5)
            self.__shiftKeySensor = KeySensor(movementMappings,
                                              shiftSensitivity)
            self.__shiftKeySensor.reset(Math.Vector3())
        dynamicsSection = dataSec['dynamics']
        self.__impulseOscillator = createOscillatorFromSection(
            dynamicsSection['impulseOscillator'], False)
        self.__movementOscillator = createOscillatorFromSection(
            dynamicsSection['movementOscillator'], False)
        self.__movementOscillator = Math.PyCompoundOscillator(
            self.__movementOscillator,
            Math.PyOscillator(1.0, Vector3(50), Vector3(20),
                              Vector3(0.01, 0.0, 0.01)))
        self.__noiseOscillator = createOscillatorFromSection(
            dynamicsSection['randomNoiseOscillatorSpherical'])
        self.__dynamicCfg.readImpulsesConfig(dynamicsSection)
        self.__dynamicCfg['accelerationSensitivity'] = readFloat(
            dynamicsSection, 'accelerationSensitivity', -1000, 1000, 0.1)
        self.__dynamicCfg['frontImpulseToPitchRatio'] = math.radians(
            readFloat(dynamicsSection, 'frontImpulseToPitchRatio', -1000, 1000,
                      0.1))
        self.__dynamicCfg['sideImpulseToRollRatio'] = math.radians(
            readFloat(dynamicsSection, 'sideImpulseToRollRatio', -1000, 1000,
                      0.1))
        self.__dynamicCfg['sideImpulseToYawRatio'] = math.radians(
            readFloat(dynamicsSection, 'sideImpulseToYawRatio', -1000, 1000,
                      0.1))
        accelerationThreshold = readFloat(dynamicsSection,
                                          'accelerationThreshold', 0.0, 1000.0,
                                          0.1)
        self.__dynamicCfg['accelerationThreshold'] = accelerationThreshold
        self.__dynamicCfg['accelerationMax'] = readFloat(
            dynamicsSection, 'accelerationMax', 0.0, 1000.0, 0.1)
        self.__dynamicCfg['maxShotImpulseDistance'] = readFloat(
            dynamicsSection, 'maxShotImpulseDistance', 0.0, 1000.0, 10.0)
        self.__dynamicCfg['maxExplosionImpulseDistance'] = readFloat(
            dynamicsSection, 'maxExplosionImpulseDistance', 0.0, 1000.0, 10.0)
        self.__dynamicCfg['zoomExposure'] = readFloat(dynamicsSection,
                                                      'zoomExposure', 0.0,
                                                      1000.0, 0.25)
        accelerationFilter = mathUtils.RangeFilter(
            self.__dynamicCfg['accelerationThreshold'],
            self.__dynamicCfg['accelerationMax'], 100,
            mathUtils.SMAFilter(ArcadeCamera._FILTER_LENGTH))
        maxAccelerationDuration = readFloat(
            dynamicsSection, 'maxAccelerationDuration', 0.0, 10000.0,
            ArcadeCamera._DEFAULT_MAX_ACCELERATION_DURATION)
        self.__accelerationSmoother = AccelerationSmoother(
            accelerationFilter, maxAccelerationDuration)
        self.__inputInertia = _InputInertia(self.__cfg['fovMultMinMaxDist'],
                                            0.0)
        advancedCollider = dataSec['advancedCollider']
        self.__adCfg = dict()
        cfg = self.__adCfg
        if advancedCollider is None:
            LOG_ERROR('<advancedCollider> dataSection is not found!')
            cfg['enable'] = False
        else:
            cfg['enable'] = advancedCollider.readBool('enable', False)
            cfg['fovRatio'] = advancedCollider.readFloat('fovRatio', 2.0)
            cfg['rollbackSpeed'] = advancedCollider.readFloat(
                'rollbackSpeed', 1.0)
            cfg['minimalCameraDistance'] = self.__cfg['distRange'][0]
            cfg['speedThreshold'] = advancedCollider.readFloat(
                'speedThreshold', 0.1)
            cfg['minimalVolume'] = advancedCollider.readFloat(
                'minimalVolume', 200.0)
            cfg['volumeGroups'] = dict()
            for group in VOLUME_GROUPS_NAMES:
                groups = advancedCollider['volumeGroups']
                cfg['volumeGroups'][group] = CollisionVolumeGroup.fromSection(
                    groups[group])

        return
Exemple #27
0
    def addFilter(self, name, filterObj, order=-1, removed=None):
        inFilter = isinstance(filterObj, IIncomingMessageFilter)
        outFilter = isinstance(filterObj, IOutgoingMessageFilter)
        if removed is None:
            removed = []
        if not inFilter and not outFilter or inFilter and outFilter:
            LOG_WARNING(
                'Invalid filter (name = {0:>s}, object = {1!r:s}))'.format(
                    name, filterObj))
            return
        else:
            if inFilter and name not in self.__inFilterNames:
                if name in self.__outFilterNames:
                    LOG_WARNING(
                        'Invalid filter (name = {0:>s}, object = {1!r:s})).Filter name must be unique.'
                        .format(name, filterObj))
                    return
                self.__inFilters.append({
                    'name':
                    name,
                    'filter':
                    filterObj,
                    'order':
                    order if order > 0 else len(self.__inFilters) + 1,
                    'lock':
                    False
                })
                LOG_DEBUG('Incoming filter added', name)
                for removedName in removed:
                    self.__doRemoveInFilter(removedName)

                self.__prepareInFilters()
            elif inFilter:
                LOG_DEBUG(
                    'Filter (name = {0:>s}, object = {1!r:s})) is already added to chain of incoming filters'
                    .format(name, filterObj))
            if outFilter and name not in self.__outFilterNames:
                if name in self.__inFilterNames:
                    LOG_WARNING(
                        'Invalid filter (name = {0:>s}, object = {1!r:s})).Filter name must be unique.'
                        .format(name, filterObj))
                    return
                self.__outFilters.append({
                    'name':
                    name,
                    'filter':
                    filterObj,
                    'order':
                    order if order > 0 else len(self.__outFilters) + 1,
                    'lock':
                    False
                })
                LOG_DEBUG('Outgoing filter added', name)
                for removedName in removed:
                    self.__doRemoveOutFilter(removedName)

                self.__prepareOutFilters()
            elif outFilter:
                LOG_DEBUG(
                    'Filter (name = {0:>s}, object = {1!r:s})) is already added to chain of outgoing filters'
                    .format(name, filterObj))
            return
Exemple #28
0
 def onTileClick(self, tileID):
     try:
         self.__proxy.showTileChainsView(tileID)
     except:
         LOG_WARNING('Error while getting event window for showing quests list window')
         LOG_CURRENT_EXCEPTION()
 def __checkDynLogDir(self):
     if not os.path.exists(VehicleTelemetry.DYNAMICS_LOG_DIR):
         LOG_WARNING('DYNAMICS_LOG_DIR not found, creating ...', VehicleTelemetry.DYNAMICS_LOG_DIR)
         os.mkdir(VehicleTelemetry.DYNAMICS_LOG_DIR)
 def addHandler(self, handler):
     if handler not in self.__handlers:
         self.__handlers.append(handler)
     else:
         LOG_WARNING('Handler %s already added to WebCommandHandler!' %
                     str(handler))