TConnectionPtr CAudioSystemEditor_wwise::CreateConnectionFromXMLNode(XmlNodeRef pNode, EACEControlType eATLControlType) { if (pNode) { const string sTag = pNode->getTag(); TImplControlType type = TagToType(sTag); if (type != AUDIO_IMPL_INVALID_TYPE) { string sName = pNode->getAttr("wwise_name"); string sLocalised = pNode->getAttr("wwise_localised"); bool bLocalised = (sLocalised.compareNoCase("true") == 0); // If control not found, create a placeholder. // We want to keep that connection even if it's not in the middleware. // The user could be using the engine without the wwise project IAudioSystemControl* pControl = GetControlByName(sName, bLocalised); if (pControl == nullptr) { pControl = CreateControl(SControlDef(sName, type)); if (pControl) { pControl->SetPlaceholder(true); pControl->SetLocalised(bLocalised); } } // If it's a switch we actually connect to one of the states within the switch if (type == eWCT_WWISE_SWITCH_GROUP || type == eWCT_WWISE_GAME_STATE_GROUP) { if (pNode->getChildCount() == 1) { pNode = pNode->getChild(0); if (pNode) { string sChildName = pNode->getAttr("wwise_name"); IAudioSystemControl* pChildControl = GetControlByName(sChildName, false, pControl); if (pChildControl == nullptr) { pChildControl = CreateControl(SControlDef(sChildName, type == eWCT_WWISE_SWITCH_GROUP ? eWCT_WWISE_SWITCH : eWCT_WWISE_GAME_STATE, false, pControl)); } pControl = pChildControl; } } else { CryWarning(VALIDATOR_MODULE_EDITOR, VALIDATOR_ERROR, "Audio Controls Editor (Wwise): Error reading connection to Wwise control %s", sName); } } if (pControl) { pControl->SetConnected(true); ++m_connectionsByID[pControl->GetId()]; if (type == eWCT_WWISE_RTPC) { switch (eATLControlType) { case EACEControlType::eACET_RTPC: { TRtpcConnectionPtr pConnection = std::make_shared<CRtpcConnection>(pControl->GetId()); float mult = 1.0f; float shift = 0.0f; if (pNode->haveAttr("atl_mult")) { const string sProperty = pNode->getAttr("atl_mult"); mult = (float)std::atof(sProperty.c_str()); } if (pNode->haveAttr("atl_shift")) { const string sProperty = pNode->getAttr("atl_shift"); shift = (float)std::atof(sProperty.c_str()); } pConnection->fMult = mult; pConnection->fShift = shift; return pConnection; } case EACEControlType::eACET_SWITCH_STATE: { TStateConnectionPtr pConnection = std::make_shared<CStateToRtpcConnection>(pControl->GetId()); float value = 0.0f; if (pNode->haveAttr("atl_mult")) { const string sProperty = pNode->getAttr("wwise_value"); value = (float)std::atof(sProperty.c_str()); } pConnection->fValue = value; return pConnection; } } } else { return std::make_shared<IAudioConnection>(pControl->GetId()); } } } } return nullptr; }
void CHUDMissionObjectiveSystem::LoadLevelObjectivesInternal(const char* levelpath) { CryFixedStringT<128> filename; if (levelpath==NULL) { // there is no Objectives_global.xml, but there is a file with the previous standard naming // load the file with old name for backwards compatibility if (!gEnv->pCryPak->IsFileExist("Libs/UI/Objectives_global.xml") && gEnv->pCryPak->IsFileExist("Libs/UI/Objectives_new.xml")) { CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "File 'Objectives_new.xml' is deprecated and should be renamed to 'Objectives_global.xml'"); filename = "Libs/UI/Objectives_new.xml"; } else { filename = "Libs/UI/Objectives_global.xml"; } } else { filename.Format("%s/leveldata/Objectives.xml", levelpath); } /*if(gEnv->bMultiplayer) { CGameRules *pGameRules = g_pGame->GetGameRules(); if(stricmp (pGameRules->GetEntity()->GetClass()->GetName(), "Coop")) filename = "Libs/UI/MP_Objectives.xml"; }*/ XmlNodeRef missionObjectives = GetISystem()->LoadXmlFromFile(filename.c_str()); if (missionObjectives == 0) return; for(int tag = 0; tag < missionObjectives->getChildCount(); ++tag) { XmlNodeRef mission = missionObjectives->getChild(tag); const char* attrib; const char* objective; const char* text; const char* optional; const char* levelName; if (!mission->getAttr("name", &levelName)) { levelName = mission->getTag(); } for(int obj = 0; obj < mission->getChildCount(); ++obj) { XmlNodeRef objectiveNode = mission->getChild(obj); string id(levelName); id.append("."); id.append(objectiveNode->getTag()); if(objectiveNode->getAttributeByIndex(0, &attrib, &objective) && objectiveNode->getAttributeByIndex(1, &attrib, &text)) { bool secondaryObjective = false; int attribs = objectiveNode->getNumAttributes(); for(int attribIndex = 2; attribIndex < attribs; ++attribIndex) { if(objectiveNode->getAttributeByIndex(attribIndex, &attrib, &optional)) { if(attrib) { if(!stricmp(attrib, "Secondary")) { if(!stricmp(optional, "true")) secondaryObjective = true; } } } } m_currentMissionObjectives.push_back(CHUDMissionObjective(this, id.c_str(), objective, text, secondaryObjective)); } else GameWarning("Error reading mission objectives."); } } }
void COptionsManager::ResetDefaults(const char* option) { if(!m_pPlayerProfileManager) return; const char* user = m_pPlayerProfileManager->GetCurrentUser(); IPlayerProfile *pProfile = m_pPlayerProfileManager->GetCurrentProfile(user); if(!pProfile) return; XmlNodeRef root = GetISystem()->LoadXmlFile("libs/config/profiles/default/attributes.xml"); bool resetAll = (option==NULL); bool detectHardware = false; for (int i = 0; i < root->getChildCount(); ++i) { XmlNodeRef enumNameNode = root->getChild(i); const char *name = enumNameNode->getAttr("name"); const char *value = enumNameNode->getAttr("value"); if(name && value) { const char* attribCVar = ""; bool bWriteToCfg = false; const bool bIsOption = IsOption(name, attribCVar, bWriteToCfg); if(bIsOption) { if(!resetAll && strcmp(attribCVar,option)) continue; if(!strcmp(attribCVar, "sys_spec_Shadows")) { detectHardware = true; } if(!strcmp(attribCVar, "hud_colorLine")) { CryFixedStringT<32> color; color.Format("%d", g_pGameCVars->hud_colorLine); SetCrysisProfileColor(color.c_str()); } if(!strcmp(attribCVar,"pb_client")) { if(atoi(value)==0) { m_pbEnabled = false; gEnv->pConsole->ExecuteString("net_pb_cl_enable false"); } else { m_pbEnabled = true; gEnv->pConsole->ExecuteString("net_pb_cl_enable true"); } } else if(!strcmp(attribCVar, "g_difficultyLevel")) { SetDifficulty(value); } else { ICVar *pCVar = gEnv->pConsole->GetCVar(attribCVar); if(pCVar) { pCVar->Set(value); } } if(!resetAll) break; } } } if(detectHardware) AutoDetectHardware(""); }
void CForceFeedBackSystem::LoadEffects( XmlNodeRef& effectsNode ) { CGameXmlParamReader paramReader(effectsNode); const int effectsCount = paramReader.GetUnfilteredChildCount(); m_effectToIndexMap.reserve(effectsCount); m_effects.reserve(effectsCount); m_effectNames.reserve(effectsCount); for (int i = 0; i < effectsCount; ++i) { XmlNodeRef childEffectNode = paramReader.GetFilteredChildAt(i); if( childEffectNode ) { SEffect newEffect; const int effectDataCount = childEffectNode->getChildCount(); const char* effectName = childEffectNode->getAttr("name"); //Check for invalid name if ((effectName == NULL) || (effectName[0] == '\0')) { FORCEFEEDBACK_LOG("Could not load effect without name (at line %d)", childEffectNode->getLine()); continue; } //Check for duplicates if (m_effectToIndexMap.find(FFBInternalId::GetIdForName(effectName)) != m_effectToIndexMap.end()) { FORCEFEEDBACK_LOG("Effect '%s' does already exists, skipping", effectName); continue; } childEffectNode->getAttr("time", newEffect.time); for (int j = 0; j < effectDataCount; ++j) { XmlNodeRef motorNode = childEffectNode->getChild(j); const char* motorTag = motorNode->getTag(); if (strcmp(motorTag, "MotorAB") == 0) { newEffect.patternA.Set( motorNode->haveAttr("pattern") ? motorNode->getAttr("pattern") : "" ); newEffect.patternB = newEffect.patternA; newEffect.envelopeA.Set( motorNode->haveAttr("envelope") ? motorNode->getAttr("envelope") : "" ); newEffect.envelopeB = newEffect.envelopeA; motorNode->getAttr("frequency", newEffect.frequencyA); newEffect.frequencyB = newEffect.frequencyA; } else if (strcmp(motorTag, "MotorA") == 0) { newEffect.patternA.Set( motorNode->haveAttr("pattern") ? motorNode->getAttr("pattern") : "" ); newEffect.envelopeA.Set( motorNode->haveAttr("envelope") ? motorNode->getAttr("envelope") : "" ); motorNode->getAttr("frequency", newEffect.frequencyA); } else if (strcmp(motorTag, "MotorB") == 0) { newEffect.patternB.Set( motorNode->haveAttr("pattern") ? motorNode->getAttr("pattern") : "" ); newEffect.envelopeB.Set( motorNode->haveAttr("envelope") ? motorNode->getAttr("envelope") : "" ); motorNode->getAttr("frequency", newEffect.frequencyB); } } newEffect.frequencyA = (float)__fsel(-newEffect.frequencyA, 1.0f, newEffect.frequencyA); newEffect.frequencyB = (float)__fsel(-newEffect.frequencyB, 1.0f, newEffect.frequencyB); m_effects.push_back(newEffect); m_effectNames.push_back(effectName); FFBInternalId internalId; internalId.Set(effectName); m_effectToIndexMap.insert(TEffectToIndexMap::value_type(internalId, ((int)m_effects.size() - 1))); } } }
void CDLCManager::PopulateDLCContents(const XmlNodeRef &rootNode, int dlcId, const char* name ) { mbstowcs( m_dlcContents[dlcId].name, name, MAX_DLC_NAME ); XmlNodeRef levelsNode = rootNode->findChild("levels"); if (levelsNode) { XmlString levelName; int numLevels = levelsNode->getChildCount(); CryLog( "Found %d levels in the DLC", numLevels ); m_dlcContents[dlcId].levels.reserve(numLevels); for (int i=0; i<numLevels; ++i) { XmlNodeRef levelNode = levelsNode->getChild(i); if (levelNode->getAttr("name", levelName)) { CryLog( "Found level %s and added to the DLC manager", levelName.c_str() ); m_dlcContents[dlcId].levels.push_back(levelName); } } } XmlNodeRef bonusNode = rootNode->findChild("bonus"); if( bonusNode ) { CryLog( "DLC pak includes a pre-sale bonus" ); uint32 bonusID = 0; bonusNode->getAttr("id", bonusID ); m_dlcContents[dlcId].bonusID = bonusID; } XmlNodeRef uniqueIdNode = rootNode->findChild("uniqueId"); if( uniqueIdNode ) { uint32 uniqueID = 0; uniqueIdNode->getAttr("id", uniqueID ); m_dlcContents[dlcId].uniqueID = uniqueID; } XmlNodeRef uniqueTagNode = rootNode->findChild("uniqueTag"); if( uniqueTagNode ) { const char* str = uniqueTagNode->getAttr( "tag" ); m_dlcContents[dlcId].uniqueTag.Format( str ); } }
////////////////////////////////////////////////////////////////////////// //this respawns the active AI at their spawn locations void CCheckpointSystem::RespawnAI(XmlNodeRef data) { if(!data) return; XmlNodeRef actorData = data->findChild(ACTOR_FLAGS_SECTION); if(!actorData) { CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_ERROR, "Failed reading actor data from checkpoint, actors won't be respawned"); return; } IActorSystem *pActorSystem = CCryAction::GetCryAction()->GetIActorSystem(); //first run through all actors and hide/deactivate them IActorIteratorPtr it = pActorSystem->CreateActorIterator(); while (IActor *pActor = it->Next()) { IEntity *pEntity = pActor->GetEntity(); //deactivate all actors pEntity->Hide(true); pEntity->Activate(false); } //load actorflags for active actors XmlNodeRef activatedActors = actorData->findChild(ACTIVATED_ACTORS_SECTION); if(activatedActors) { int actorFlags = activatedActors->getNumAttributes(); const char *key; const char *value; for(int i = 0; i < actorFlags; ++i) { activatedActors->getAttributeByIndex(i, &key, &value); //format is "idXXX" CRY_ASSERT(strlen(key)>2); EntityId id = (EntityId)(atoi(&key[2])); bool foundEntity = RepairEntityId(id, value); if(foundEntity) { IActor* pActor = pActorSystem->GetActor(id); if(pActor) { pActor->GetEntity()->Hide(false); pActor->GetEntity()->Activate(true); } else CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_ERROR, "Failed finding actor %i from checkpoint.", (int)id); } else CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_ERROR, "Failed finding actor %s from checkpoint, actor is not setup correctly.", value); } } else CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_ERROR, "Deactivated actors section was missing in checkpoint."); it = pActorSystem->CreateActorIterator(); //iterate all actors and respawn if active while (IActor *pActor = it->Next()) { IEntity *pEntity = pActor->GetEntity(); if(pEntity->GetId() == LOCAL_PLAYER_ENTITY_ID) //don't respawn player continue; //we don't respawn deactivated actors if(!pEntity->IsHidden() && pEntity->IsActive()) { pActor->SetHealth(0); pActor->Respawn(); } else //but we still reset their position { pActor->ResetToSpawnLocation(); } } }
// TODO parameterise and refactor this now its mainly duplicated between the two runs void CAutoTester::UpdateTestNumClients() { if(gEnv->bServer) { IGameFramework *pFramework = gEnv->pGame->GetIGameFramework(); int numChannels = 1; //local channel if(pFramework) { INetNub *pNub = pFramework->GetServerNetNub(); if(pNub) { numChannels = pNub->GetNumChannels(); } } if (numChannels > m_stateData.testNumClients.m_maxNumClientsConnected) { m_stateData.testNumClients.m_maxNumClientsConnected=numChannels; } float timeSeconds=gEnv->pTimer->GetFrameStartTime().GetSeconds(); CryWatch("time=%f; numClients=%d; maxNumClients=%d; numClientsExpected=%d", timeSeconds, numChannels, m_stateData.testNumClients.m_maxNumClientsConnected, m_stateData.testNumClients.m_numClientsExpected); if (timeSeconds > m_stateData.testNumClients.m_debugTimer) { m_stateData.testNumClients.m_debugTimer = timeSeconds+2.0f; CryLogAlways("CAutoTester::UpdateTestNumClients() updating time=%f; numClients=%d; maxNumClients=%d; numClientsExpected=%d", timeSeconds, numChannels, m_stateData.testNumClients.m_maxNumClientsConnected, m_stateData.testNumClients.m_numClientsExpected); } if (timeSeconds > m_stateData.testNumClients.m_timeOut) { CryLogAlways("CAutoTester::UpdateTestNumClients() testing num clients and time has expired. numClients=%d; maxNumClients=%d; numClientsExpected=%d", numChannels, m_stateData.testNumClients.m_maxNumClientsConnected, m_stateData.testNumClients.m_numClientsExpected); bool passed=false; string mapName = g_pGame->GetIGameFramework()->GetILevelSystem()->GetCurrentLevel()->GetLevelInfo()->GetName(); string gameRulesName; gameRulesName = g_pGame->GetGameRules()->GetEntity()->GetClass()->GetName(); XmlNodeRef testCase = GetISystem()->CreateXmlNode(); string nameStr; nameStr.Format("Level: %s; gameRules: %s; numClients=%d; timeTested=%.1f seconds", mapName.c_str(), gameRulesName.c_str(), numChannels, m_stateData.testNumClients.m_timeOut); testCase->setTag("testcase"); testCase->setAttr("name", nameStr.c_str()); testCase->setAttr("time", 0); testCase->setAttr("numClients", numChannels); testCase->setAttr("maxNumClientsConnected",m_stateData.testNumClients.m_maxNumClientsConnected); testCase->setAttr("numClientsExpected", m_stateData.testNumClients.m_numClientsExpected); if (numChannels == m_stateData.testNumClients.m_maxNumClientsConnected) { CryLogAlways("CAutoTester::UpdateTestNumClients() testing num clients and time has expired. We have the same number of clients are our maxNumClients %d", numChannels); if (numChannels == m_stateData.testNumClients.m_numClientsExpected) // may want to remove this check as keeping the number that joined should be sufficient { CryLogAlways("CAutoTester::UpdateTestNumClients() testing num clients and time has expired. We have the same number of clients as we expected to have %d", numChannels); testCase->setAttr("status", "run"); passed=true; } else { CryLogAlways("CAutoTester::UpdateTestNumClients() testing num clients and time has expired. We DON'T have the same number of clients %d as we expected to have %d", numChannels, m_stateData.testNumClients.m_numClientsExpected); //testCase->setAttr("status", "failed"); XmlNodeRef failedCase = GetISystem()->CreateXmlNode(); failedCase->setTag("failure"); failedCase->setAttr("type", "NotEnoughClients"); failedCase->setAttr("message", string().Format("testing num clients and time has expired. We DON'T have the same number of clients %d as we expected to have %d", numChannels, m_stateData.testNumClients.m_numClientsExpected)); testCase->addChild(failedCase); } } else { //testCase->setAttr("status", "failed"); XmlNodeRef failedCase = GetISystem()->CreateXmlNode(); failedCase->setTag("failure"); failedCase->setAttr("type", "NotEnoughClients"); failedCase->setAttr("message", string().Format("testing num clients and time has expired. We DON'T have the same number of clients %d as we peaked at %d", numChannels, m_stateData.testNumClients.m_maxNumClientsConnected)); testCase->addChild(failedCase); } AddTestCaseResult("Test Clients In Levels", testCase, passed); Stop(); } } }
//------------------------------------------------------------------------ bool CPlayerProfileImplFSDir::LoginUser(SUserEntry* pEntry) { // lookup stored profiles of the user (pEntry->userId) and fill in the pEntry->profileDesc // vector pEntry->profileDesc.clear(); // scan directory for profiles string path; InternalMakeFSPath(pEntry, "", path); // no profile name -> only path std::multimap<time_t, SLocalProfileInfo> profiles; ICryPak * pCryPak = gEnv->pCryPak; _finddata_t fd; path.TrimRight("/\\"); string search = path + "/*.*"; IPlatformOS* pOS = GetISystem()->GetPlatformOS(); IPlatformOS::IFileFinderPtr fileFinder = pOS->GetFileFinder(IPlatformOS::Unknown_User); intptr_t handle = fileFinder->FindFirst(search.c_str(), &fd); if (handle != -1) { do { if (strcmp(fd.name, ".") == 0 || strcmp(fd.name, "..") == 0) continue; if (fd.attrib & _A_SUBDIR) { // profile name = folder name // but make sure there is a profile.xml in it string filename = path + "/" + fd.name; filename += "/" ; filename += "profile.xml"; XmlNodeRef rootNode = LoadXMLFile(filename.c_str()); // see if the root tag is o.k. if (rootNode && stricmp(rootNode->getTag(), PROFILE_ROOT_TAG) == 0) { string profileName = fd.name; if (rootNode->haveAttr(PROFILE_NAME_TAG)) { const char* profileHumanName = rootNode->getAttr(PROFILE_NAME_TAG); if (profileHumanName!=0 && stricmp(profileHumanName, profileName) == 0) { profileName = profileHumanName; } } time_t time = NULL; if (rootNode->haveAttr(PROFILE_LAST_PLAYED)) { rootNode->getAttr(PROFILE_LAST_PLAYED, time); } SLocalProfileInfo info(profileName); info.SetLastLoginTime(time); profiles.insert(std::make_pair(time, info)); } else { GameWarning("CPlayerProfileImplFSDir::LoginUser: Profile '%s' of User '%s' seems to exists but is invalid (File '%s). Skipped", fd.name, pEntry->userId.c_str(), filename.c_str()); } } } while ( fileFinder->FindNext( handle, &fd ) >= 0 ); fileFinder->FindClose( handle ); } // Insert in most recently played order std::multimap<time_t, SLocalProfileInfo>::const_reverse_iterator itend = profiles.rend(); for(std::multimap<time_t, SLocalProfileInfo>::const_reverse_iterator it = profiles.rbegin(); it != itend; ++it) pEntry->profileDesc.push_back(it->second); return true; }
bool CCommonSaveGameHelper::GetSaveGames(CPlayerProfileManager::SUserEntry* pEntry, CPlayerProfileManager::TSaveGameInfoVec& outVec, const char* altProfileName="") { // Scan savegames directory for XML files // we scan only for save game meta information string path; string profileName = (altProfileName && *altProfileName) ? altProfileName : pEntry->pCurrentProfile->GetName(); m_pImpl->InternalMakeFSSaveGamePath(pEntry, profileName, path, true); const bool bNeedProfilePrefix = m_pImpl->GetManager()->IsSaveGameFolderShared(); string profilePrefix = profileName; profilePrefix+='_'; size_t profilePrefixLen = profilePrefix.length(); path.TrimRight("/\\"); string search; search.Format("%s/*%s", path.c_str(), CRY_SAVEGAME_FILE_EXT); IPlatformOS* os = GetISystem()->GetPlatformOS(); IPlatformOS::IFileFinderPtr fileFinder = os->GetFileFinder(IPlatformOS::Unknown_User); _finddata_t fd; intptr_t handle = fileFinder->FindFirst(search.c_str(), &fd); if (handle != -1) { CPlayerProfileManager::SSaveGameInfo sgInfo; do { if (strcmp(fd.name, ".") == 0 || strcmp(fd.name, "..") == 0) continue; if (bNeedProfilePrefix) { if (strnicmp(profilePrefix, fd.name, profilePrefixLen) != 0) continue; } sgInfo.name = fd.name; if (bNeedProfilePrefix) // skip profile_ prefix (we made sure this is valid by comparism above) sgInfo.humanName = fd.name+profilePrefixLen; else sgInfo.humanName = fd.name; PathUtil::RemoveExtension(sgInfo.humanName); sgInfo.description = "no description"; bool ok = false; // filename construction #if defined(PS3) || defined(XENON) //don't use meta files on PS3 or 360 sgInfo.metaData.saveTime = static_cast<time_t>(fd.time_write); // the time gets used to find the most recent save sgInfo.metaData.loadTime = sgInfo.metaData.saveTime; ok = true; #else string metaFilename = path; metaFilename.append("/"); metaFilename.append(fd.name); metaFilename = PathUtil::ReplaceExtension(metaFilename, ".meta"); XmlNodeRef rootNode = LoadXMLFile(metaFilename.c_str()); // see if the root tag is o.k. if (rootNode && stricmp(rootNode->getTag(), "Metadata") == 0) { // get meta data ok = FetchMetaData(rootNode, sgInfo.metaData); } else { // when there is no meta information, we currently reject the savegame //ok = true; // un-comment this, if you want to accept savegames without meta } // Use the file modified time for the load time as we touch the saves when they are used to keep most recent checkpoint sgInfo.metaData.loadTime = static_cast<time_t>(fd.time_write); #endif if (ok) { outVec.push_back(sgInfo); } else { GameWarning("CPlayerProfileImplFS::GetSaveGames: SaveGame '%s' of user '%s' is invalid", fd.name, pEntry->userId.c_str()); } } while ( fileFinder->FindNext(handle, &fd) >= 0 ); fileFinder->FindClose( handle ); } return true; }
bool CGameTokenSystem::_InternalLoadLibrary( const char *filename, const char* tag ) { XmlNodeRef root = GetISystem()->LoadXmlFromFile( filename ); if (!root) { GameWarning( _HELP("Unable to load game token database: %s"), filename ); return false; } if (0 != strcmp( tag, root->getTag() )) { GameWarning( _HELP("Not a game tokens library : %s"), filename ); return false; } // GameTokens are (currently) not saved with their full path // we expand it here to LibName.TokenName string libName; { const char *sLibName = root->getAttr("Name"); if (sLibName == 0) { GameWarning( "GameTokensLibrary::LoadLibrary: Unable to find LibName in file '%s'", filename); return false; } libName = sLibName; } // we dont skip already loaded libraries anymore. We need to reload them to be sure that all necessary gametokens are present even if some level has not up-to-date libraries. if (!stl::find(m_libraries, libName)) //return true; m_libraries.push_back(libName); libName+= "."; int numChildren = root->getChildCount(); for (int i=0; i<numChildren; i++) { XmlNodeRef node = root->getChild(i); const char *sName = node->getAttr("Name"); const char *sType = node->getAttr("Type"); const char *sValue = node->getAttr("Value"); const char *sLocalOnly = node->getAttr("LocalOnly"); int localOnly=atoi(sLocalOnly); EFlowDataTypes tokenType = eFDT_Any; if (0 == strcmp(sType,"Int")) tokenType = eFDT_Int; else if (0 == strcmp(sType,"Float")) tokenType = eFDT_Float; else if (0 == strcmp(sType,"EntityId")) tokenType = eFDT_EntityId; else if (0 == strcmp(sType,"Vec3")) tokenType = eFDT_Vec3; else if (0 == strcmp(sType,"String")) tokenType = eFDT_String; else if (0 == strcmp(sType,"Bool")) tokenType = eFDT_Bool; if (tokenType == eFDT_Any) { GameWarning(_HELP("Unknown game token type %s in token %s (%s:%d)"),sType,sName,node->getTag(),node->getLine()); continue; } TFlowInputData initialValue = TFlowInputData(string(sValue)); string fullName (libName); fullName+=sName; IGameToken *pToken = stl::find_in_map(*m_pGameTokensMap,fullName,NULL); if (!pToken) { pToken = SetOrCreateToken( fullName,initialValue ); if (pToken && localOnly) pToken->SetFlags(pToken->GetFlags()|EGAME_TOKEN_LOCALONLY); } } return true; }
////////////////////////////////////////////////////////////////////////// // Set event targets from the XmlNode exported by Editor. void CScriptProxy::SetEventTargets( XmlNodeRef &eventTargetsNode ) { std::set<string> sourceEvents; std::vector<SEntityEventTarget> eventTargets; IScriptSystem* pSS = GetIScriptSystem(); for (int i = 0; i < eventTargetsNode->getChildCount(); i++) { XmlNodeRef eventNode = eventTargetsNode->getChild(i); SEntityEventTarget et; et.event = eventNode->getAttr("Event"); if (!eventNode->getAttr("Target", et.target)) et.target = 0; // failed reading... et.sourceEvent = eventNode->getAttr("SourceEvent"); if (et.event.empty() || !et.target || et.sourceEvent.empty()) continue; eventTargets.push_back(et); sourceEvents.insert(et.sourceEvent); } if (eventTargets.empty()) return; SmartScriptTable pEventsTable; if (!m_pThis->GetValue( "Events",pEventsTable )) { pEventsTable = pSS->CreateTable(); // assign events table to the entity self script table. m_pThis->SetValue( "Events",pEventsTable ); } for (std::set<string>::iterator it = sourceEvents.begin(); it != sourceEvents.end(); ++it) { SmartScriptTable pTrgEvents(pSS); string sourceEvent = *it; pEventsTable->SetValue( sourceEvent.c_str(),pTrgEvents ); // Put target events to table. int trgEventIndex = 1; for (size_t i = 0; i < eventTargets.size(); i++) { SEntityEventTarget &et = eventTargets[i]; if (et.sourceEvent == sourceEvent) { SmartScriptTable pTrgEvent(pSS); pTrgEvents->SetAt( trgEventIndex,pTrgEvent ); trgEventIndex++; ScriptHandle hdl; hdl.n = et.target; pTrgEvent->SetAt( 1, hdl); pTrgEvent->SetAt( 2,et.event.c_str()); } } } }
void CAnimationProxyDualCharacterBase::Generate1P3PPairFile() { const int MAX_MODELS = 128; ICharacterModel *pCharacterModels[MAX_MODELS]; int numModels; gEnv->pCharacterManager->GetLoadedModels(NULL, numModels); numModels = min(numModels, MAX_MODELS); gEnv->pCharacterManager->GetLoadedModels(pCharacterModels, numModels); s_animCrCHashMap.clear(); for (uint32 i=0; i<numModels; ++i) { if (pCharacterModels[i]->GetNumInstances() > 0) { IAnimationSet *animSet = pCharacterModels[i]->GetICharInstanceFromModel(0)->GetIAnimationSet(); uint32 numAnims = animSet->GetAnimationCount(); for (uint32 anm = 0; anm < numAnims; anm++) { uint32 animCRC = animSet->GetCRCByAnimID(anm); if (s_animCrCHashMap.find(animCRC) == s_animCrCHashMap.end()) { int animID3P = -1; const char *name = animSet->GetNameByAnimID(anm); if (strlen(name) >= 255) { CRY_ASSERT_MESSAGE(0, string().Format("[CAnimationProxyDualCharacterBase::Generate1P3PPairFiles] Animname %s overruns buffer", name)); CryLogAlways("[CAnimationProxyDualCharacterBase::Generate1P3PPairFiles] Animname %s overruns buffer", name); continue; } const char *pos = CryStringUtils::stristr(name, "_1p"); if (pos) { char name3P[256]; strcpy(name3P, name); name3P[(int)(TRUNCATE_PTR)pos + 1 - (int)(TRUNCATE_PTR)name] = '3'; animID3P = animSet->GetAnimIDByName(name3P); if (animID3P >= 0) { uint32 animCRCTP = animSet->GetCRCByAnimID(animID3P); s_animCrCHashMap[animCRC] = animCRCTP; } } } } } } //--- Save the file CryFixedStringT<256> animCrC; XmlNodeRef nodePairList = gEnv->pSystem->CreateXmlNode( "Pairs" ); for (NameHashMap::iterator iter = s_animCrCHashMap.begin(); iter != s_animCrCHashMap.end(); ++iter) { XmlNodeRef nodePair = nodePairList->newChild( "Pair" ); animCrC.Format("%u", iter->first); nodePair->setAttr( "FP", animCrC.c_str()); animCrC.Format("%u", iter->second); nodePair->setAttr( "TP", animCrC.c_str()); } nodePairList->saveToFile(ANIMPAIR_PATHNAME); s_animCrCHashMap.clear(); Load1P3PPairFile(); }
void CClientHitEffectsMP::ProcessEffectInfo(SHitEffectInfoSet& hitEffectSet, XmlNodeRef xmlNode, const char* libraryName) { bool foundDefault = false; bool foundMelee = false; const uint numEffects = xmlNode->getChildCount(); IMaterialEffects* pMaterialEffects = gEnv->pMaterialEffects; IEntityClassRegistry* pClassRegistry = gEnv->pEntitySystem->GetClassRegistry(); hitEffectSet.m_effectInfos.reserve(numEffects); for (uint i = 0; i < numEffects; i++) { if(XmlNodeRef childNode = xmlNode->getChild(i)) { if(const char* nameTag = childNode->getTag()) { if(!foundDefault && !strcmp("default", nameTag)) { const char* effectName = childNode->getAttr("effect"); if(effectName) { hitEffectSet.m_default = pMaterialEffects->GetEffectIdByName(libraryName, effectName); } foundDefault = true; } else if(!foundMelee && !strcmp("melee", nameTag)) { const char* effectName = childNode->getAttr("effect"); if(effectName) { hitEffectSet.m_melee = pMaterialEffects->GetEffectIdByName(libraryName, effectName); } foundMelee = true; } else { SHitEffectInfo newInfo; newInfo.pAmmoClass = pClassRegistry->FindClass(nameTag); const char* effectName = childNode->getAttr("effect"); if(effectName) { newInfo.effectId = pMaterialEffects->GetEffectIdByName(libraryName, effectName); } if(newInfo.pAmmoClass && newInfo.effectId) { hitEffectSet.m_effectInfos.push_back(newInfo); } else { if(!newInfo.pAmmoClass) { GameWarning("Class type %s does not exist", nameTag); } if(!newInfo.effectId) { GameWarning("Material Effect %s does not exist", effectName ? effectName : ""); } } } } } } if(!hitEffectSet.m_melee) { hitEffectSet.m_melee = hitEffectSet.m_default; } }
XmlNodeRef CAudioSystemEditor_wwise::CreateXMLNodeFromConnection(const TConnectionPtr pConnection, const EACEControlType eATLControlType) { const IAudioSystemControl* pControl = GetControl(pConnection->GetID()); if (pControl) { switch (pControl->GetType()) { case AudioControls::eWCT_WWISE_SWITCH: case AudioControls::eWCT_WWISE_SWITCH_GROUP: case AudioControls::eWCT_WWISE_GAME_STATE: case AudioControls::eWCT_WWISE_GAME_STATE_GROUP: { const IAudioSystemControl* pParent = pControl->GetParent(); if (pParent) { XmlNodeRef pSwitchNode = GetISystem()->CreateXmlNode(TypeToTag(pParent->GetType())); pSwitchNode->setAttr("wwise_name", pParent->GetName()); XmlNodeRef pStateNode = pSwitchNode->createNode("WwiseValue"); pStateNode->setAttr("wwise_name", pControl->GetName()); pSwitchNode->addChild(pStateNode); return pSwitchNode; } } break; case AudioControls::eWCT_WWISE_RTPC: { XmlNodeRef pConnectionNode; pConnectionNode = GetISystem()->CreateXmlNode(TypeToTag(pControl->GetType())); pConnectionNode->setAttr("wwise_name", pControl->GetName()); if (eATLControlType == eACET_RTPC) { std::shared_ptr<const CRtpcConnection> pRtpcConnection = std::static_pointer_cast<const CRtpcConnection>(pConnection); if (pRtpcConnection->fMult != 1.0f) { pConnectionNode->setAttr("atl_mult", pRtpcConnection->fMult); } if (pRtpcConnection->fShift != 0.0f) { pConnectionNode->setAttr("atl_shift", pRtpcConnection->fShift); } } else if (eATLControlType == eACET_SWITCH_STATE) { std::shared_ptr<const CStateToRtpcConnection> pStateConnection = std::static_pointer_cast<const CStateToRtpcConnection>(pConnection); pConnectionNode->setAttr("wwise_value", pStateConnection->fValue); } return pConnectionNode; } break; case AudioControls::eWCT_WWISE_EVENT: { XmlNodeRef pConnectionNode; pConnectionNode = GetISystem()->CreateXmlNode(TypeToTag(pControl->GetType())); pConnectionNode->setAttr("wwise_name", pControl->GetName()); return pConnectionNode; } break; case AudioControls::eWCT_WWISE_AUX_BUS: { XmlNodeRef pConnectionNode; pConnectionNode = GetISystem()->CreateXmlNode(TypeToTag(pControl->GetType())); pConnectionNode->setAttr("wwise_name", pControl->GetName()); return pConnectionNode; } break; case AudioControls::eWCT_WWISE_SOUND_BANK: { XmlNodeRef pConnectionNode = GetISystem()->CreateXmlNode(TypeToTag(pControl->GetType())); pConnectionNode->setAttr("wwise_name", pControl->GetName()); if (pControl->IsLocalised()) { pConnectionNode->setAttr("wwise_localised", "true"); } return pConnectionNode; } break; } } return nullptr; }
//------------------------------------------------------------------------ bool CWeaponSystem::ScanXML(XmlNodeRef &root, const char *xmlFile) { if (strcmpi(root->getTag(), "ammo")) return false; const char *name = root->getAttr("name"); if (!name) { GameWarning("Missing ammo name in XML '%s'! Skipping...", xmlFile); return false; } const char *className = root->getAttr("class"); if (!className) { GameWarning("Missing ammo class in XML '%s'! Skipping...", xmlFile); return false; } TProjectileRegistry::iterator it = m_projectileregistry.find(CONST_TEMP_STRING(className)); if (it == m_projectileregistry.end()) { GameWarning("Unknown ammo class '%s' specified in XML '%s'! Skipping...", className, xmlFile); return false; } const char *scriptName = root->getAttr("script"); IEntityClassRegistry::SEntityClassDesc classDesc; classDesc.sName = name; classDesc.sScriptFile = scriptName?scriptName:""; //classDesc.pUserProxyData = (void *)it->second; //classDesc.pUserProxyCreateFunc = &CreateProxy<CProjectile>; classDesc.flags |= ECLF_INVISIBLE; IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name); if (!m_reloading && !pClass) { m_pGame->GetIGameFramework()->GetIGameObjectSystem()->RegisterExtension(name, it->second, &classDesc); pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name); assert(pClass); } TAmmoTypeParams::iterator ait=m_ammoparams.find(pClass); if (ait==m_ammoparams.end()) { std::pair<TAmmoTypeParams::iterator, bool> result = m_ammoparams.insert(TAmmoTypeParams::value_type(pClass, SAmmoTypeDesc())); ait=result.first; } const char *configName = root->getAttr("configuration"); IItemParamsNode *params = m_pItemSystem->CreateParams(); params->ConvertFromXML(root); SAmmoParams *pAmmoParams=new SAmmoParams(params, pClass); SAmmoTypeDesc &desc=ait->second; if (!configName || !configName[0]) { if (desc.params) delete desc.params; desc.params=pAmmoParams; } else desc.configurations.insert(std::make_pair<string, const SAmmoParams*>(configName, pAmmoParams)); return true; }
//------------------------------------------------------------------------ void CGameRulesCommonDamageHandling::Init( XmlNodeRef xml ) { m_pGameRules = g_pGame->GetGameRules(); // Reserved hit types - in sync with RESERVED_HIT_TYPES /*00*/ //m_pGameRules->RegisterHitType("invalid", CGameRules::EHitTypeFlag::None); /*01*/ m_pGameRules->RegisterHitType("melee", CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::IgnoreHeadshots); /*02*/ m_pGameRules->RegisterHitType("collision", CGameRules::EHitTypeFlag::Server); /*03*/ m_pGameRules->RegisterHitType("frag", CGameRules::EHitTypeFlag::Server | CGameRules::EHitTypeFlag::AllowPostDeathDamage); /*04*/ m_pGameRules->RegisterHitType("explosion", CGameRules::EHitTypeFlag::Server | CGameRules::EHitTypeFlag::AllowPostDeathDamage); /*05*/ m_pGameRules->RegisterHitType("stealthKill", CGameRules::EHitTypeFlag::Server | CGameRules::EHitTypeFlag::AllowPostDeathDamage); /*06*/ m_pGameRules->RegisterHitType("silentMelee", CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::SinglePlayerOnly | CGameRules::EHitTypeFlag::IgnoreHeadshots); /*07*/ m_pGameRules->RegisterHitType("punish", CGameRules::EHitTypeFlag::ClientSelfHarm); /*08*/ m_pGameRules->RegisterHitType("punishFall", CGameRules::EHitTypeFlag::ClientSelfHarm); /*09*/ m_pGameRules->RegisterHitType("mike_burn", CGameRules::EHitTypeFlag::ValidationRequired); /*10*/ m_pGameRules->RegisterHitType("fall", CGameRules::EHitTypeFlag::ClientSelfHarm); /*11*/ m_pGameRules->RegisterHitType("normal", CGameRules::EHitTypeFlag::Server); //Used for killing players so they can switch teams /*12*/ m_pGameRules->RegisterHitType("fire", CGameRules::EHitTypeFlag::Server); // used by PressurizedObject.lua /*13*/ m_pGameRules->RegisterHitType("bullet", CGameRules::EHitTypeFlag::ValidationRequired); /*14*/ m_pGameRules->RegisterHitType("stamp", CGameRules::EHitTypeFlag::Server | CGameRules::EHitTypeFlag::CustomValidationRequired); /*15*/ m_pGameRules->RegisterHitType("environmentalThrow", CGameRules::EHitTypeFlag::CustomValidationRequired | CGameRules::EHitTypeFlag::AllowPostDeathDamage | CGameRules::EHitTypeFlag::IgnoreHeadshots); /*16*/ m_pGameRules->RegisterHitType("meleeLeft", CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::SinglePlayerOnly | CGameRules::EHitTypeFlag::IgnoreHeadshots); /*17*/ m_pGameRules->RegisterHitType("meleeRight", CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::SinglePlayerOnly | CGameRules::EHitTypeFlag::IgnoreHeadshots); /*18*/ m_pGameRules->RegisterHitType("meleeKick", CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::SinglePlayerOnly | CGameRules::EHitTypeFlag::IgnoreHeadshots); /*19*/ m_pGameRules->RegisterHitType("meleeUppercut", CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::SinglePlayerOnly | CGameRules::EHitTypeFlag::IgnoreHeadshots); /*20*/ m_pGameRules->RegisterHitType("vehicleDestruction", CGameRules::EHitTypeFlag::Server | CGameRules::EHitTypeFlag::AllowPostDeathDamage); /*21*/ m_pGameRules->RegisterHitType("electricity", CGameRules::EHitTypeFlag::SinglePlayerOnly); /*22*/ m_pGameRules->RegisterHitType("stealthKill_Maximum", CGameRules::EHitTypeFlag::SinglePlayerOnly); /*23*/ m_pGameRules->RegisterHitType("eventDamage", CGameRules::EHitTypeFlag::ClientSelfHarm); /*24*/ m_pGameRules->RegisterHitType("VTOLExplosion", CGameRules::EHitTypeFlag::Server); /*25*/ m_pGameRules->RegisterHitType("environmentalMelee", CGameRules::EHitTypeFlag::IsMeleeAttack | CGameRules::EHitTypeFlag::CustomValidationRequired | CGameRules::EHitTypeFlag::AllowPostDeathDamage | CGameRules::EHitTypeFlag::IgnoreHeadshots); CRY_ASSERT(m_pGameRules->GetHitTypesCount() == CGameRules::EHitType::Unreserved); // Read any non-native hit_types from the HitTypes.xml file! XmlNodeRef xmlNode = gEnv->pSystem->LoadXmlFromFile( "Scripts/Entities/Items/HitTypes.xml" ); if( xmlNode ) { const int numEntries = xmlNode->getChildCount(); for (int i = 0; i < numEntries; ++i) { XmlNodeRef hitTypeXML = xmlNode->getChild(i); if (strcmp(hitTypeXML->getTag(), "hit_type") != 0) continue; if( const char* pHitType = hitTypeXML->getAttr("name") ) { TBitfield flags = CGameRules::EHitTypeFlag::None; if( const char * pHitTypeFlags = hitTypeXML->getAttr("flags")) { flags = AutoEnum_GetBitfieldFromString(pHitTypeFlags, CGameRules::s_hitTypeFlags, CGameRules::EHitTypeFlag::HIT_TYPES_FLAGS_numBits); } m_pGameRules->RegisterHitType( pHitType, flags ); } } } m_scriptHitInfo.Create(gEnv->pScriptSystem); }
//------------------------------------------------------------------------ void CGameRulesManager::Init() { XmlNodeRef root = gEnv->pSystem->LoadXmlFromFile( GAMERULES_DEFINITIONS_XML_PATH ); if (root) { if (!stricmp(root->getTag(), "Modes")) { IGameRulesSystem *pGameRulesSystem = g_pGame->GetIGameFramework()->GetIGameRulesSystem(); int numModes = root->getChildCount(); for (int i = 0; i < numModes; ++ i) { XmlNodeRef modeXml = root->getChild(i); if (!stricmp(modeXml->getTag(), "GameMode")) { const char *modeName; if (modeXml->getAttr("name", &modeName)) { pGameRulesSystem->RegisterGameRules(modeName, "GameRules"); SGameRulesData gameRulesData; int numModeChildren = modeXml->getChildCount(); for (int j = 0; j < numModeChildren; ++ j) { XmlNodeRef modeChildXml = modeXml->getChild(j); const char *nodeTag = modeChildXml->getTag(); if (!stricmp(nodeTag, "Alias")) { const char *alias; if (modeChildXml->getAttr("name", &alias)) { pGameRulesSystem->AddGameRulesAlias(modeName, alias); } } else if (!stricmp(nodeTag, "LevelLocation")) { const char *path; if (modeChildXml->getAttr("path", &path)) { pGameRulesSystem->AddGameRulesLevelLocation(modeName, path); } } else if (!stricmp(nodeTag, "Rules")) { const char *path; if (modeChildXml->getAttr("path", &path)) { gameRulesData.m_rulesXMLPath = path; } } else if( !stricmp(nodeTag, "DefaultHudState")) { const char *name; if (modeChildXml->getAttr("name", &name)) { gameRulesData.m_defaultHud = name; } } } // Check if we're a team game if (!gameRulesData.m_rulesXMLPath.empty()) { XmlNodeRef rulesXml = gEnv->pSystem->LoadXmlFromFile( gameRulesData.m_rulesXMLPath.c_str() ); if (rulesXml) { XmlNodeRef teamXml = rulesXml->findChild("Teams"); gameRulesData.m_bIsTeamGame = (teamXml != (IXmlNode *)NULL); } } // Insert gamerule specific data m_rulesData.insert(TDataMap::value_type(modeName, gameRulesData)); } else { CryLogAlways("CGameRulesModulesManager::Init(), invalid 'GameMode' node, requires 'name' attribute"); } } else { CryLogAlways("CGameRulesModulesManager::Init(), invalid xml, expected 'GameMode' node, got '%s'", modeXml->getTag()); } } } else { CryLogAlways("CGameRulesModulesManager::Init(), invalid xml, expected 'Modes' node, got '%s'", root->getTag()); } } }
void CWorldState::SetBool(const char * entityName, char * valueName , bool value) { // CryLog("CWorldState::SetBool()"); if(worldStateXml) { XmlNodeRef entityNode = worldStateXml->findChild(entityName); if(!entityNode) { CreateChild(entityName); entityNode = worldStateXml->findChild(entityName); } const uint32 Count = entityNode->getChildCount(); for (uint32 Index = 0; Index < Count; ++Index) { XmlNodeRef child = entityNode->getChild(Index); if(strcmp(child->getTag(),valueName)==0) { if(value) child->setAttr("value","true"); else child->setAttr("value","false"); worldStateXml->saveToFile(szSaveFile); return; } } //CryLog("CWorldState::CreateBool()"); XmlNodeRef child = entityNode->newChild(valueName); if(value) child->setAttr("value","true"); else child->setAttr("value","false"); worldStateXml->saveToFile(szSaveFile); } else return; }
void CAutoTester::WriteResults(TBitfield flags, const string * additionalTestSuiteName, const XmlNodeRef * additionalTestCase) { const int& autotest_enabled = g_pGameCVars->autotest_enabled; if (!autotest_enabled) { return; } //If result generation is skipped, exit early if (autotest_enabled == 2) { if (m_quitWhenDone) { gEnv->pConsole->ExecuteString("quit"); } return; } // test workaround //DesignerWarning(0, "test warning"); // test workaround const char * mapName; string gameRulesName; const char * serverText = ""; const char * dedicatedText = gEnv->IsDedicated() ? "_Dedicated" : ""; CGameRules * rules = g_pGame ? g_pGame->GetGameRules() : NULL; if (rules) { gameRulesName = rules->GetEntity()->GetClass()->GetName(); serverText = gEnv->bServer ? "_Server" : "_Client"; } else { gameRulesName = "FrontEnd"; } if (g_pGame && g_pGame->GetIGameFramework()->GetILevelSystem()->GetCurrentLevel()) { mapName = g_pGame->GetIGameFramework()->GetILevelSystem()->GetCurrentLevel()->GetLevelInfo()->GetName(); } else { mapName = "NoMapLoaded"; } #ifndef _RELEASE CryLogAlways ("CAutoTester::WriteResults(%s): map is '%s', game mode is '%s'", AutoEnum_GetStringFromBitfield(flags, s_writeResultsFlagNames, WriteResultsFlagList_numBits).c_str(), mapName, gameRulesName.c_str()); #endif XmlNodeRef testSuites = GetISystem()->CreateXmlNode("testSuites"); testSuites->setTag("testsuites"); for (TTestSuites::const_iterator it=m_testSuites.begin(); it!=m_testSuites.end(); ++it) { const STestSuite &testSuiteStruct = it->second; int numTests = testSuiteStruct.m_testCases.size(); int numFails = testSuiteStruct.m_numTestCasesFailed; XmlNodeRef testSuite = GetISystem()->CreateXmlNode("AutoTest"); testSuite->setTag("testsuite"); testSuite->setAttr("name", it->first); testSuite->setAttr("LevelName", mapName); testSuite->setAttr("GameRulesName", gameRulesName); if (additionalTestSuiteName && it->first == *additionalTestSuiteName) { CryLog ("Writing additional test case to existing '%s' suite", additionalTestSuiteName->c_str()); ++ numFails; // Assumption here that any additional test data provided is a failure... [TF] ++ numTests; testSuite->addChild(*additionalTestCase); additionalTestSuiteName = NULL; } testSuite->setAttr("tests", numTests); testSuite->setAttr("failures", numFails); testSuite->setAttr("errors", 0); testSuite->setAttr("time", 0); for (size_t i = 0; i < testSuiteStruct.m_testCases.size(); i++) { testSuite->addChild(testSuiteStruct.m_testCases[i]); } testSuites->addChild(testSuite); } if (additionalTestSuiteName) // Still haven't written our additional test case because the suite name didn't match any existing suite... { CryLog ("CAutoTester writing additional test case to unique '%s' suite", additionalTestSuiteName->c_str()); XmlNodeRef testSuite = GetISystem()->CreateXmlNode("AutoTest"); testSuite->setTag("testsuite"); testSuite->setAttr("name", *additionalTestSuiteName); testSuite->setAttr("LevelName", mapName); testSuite->setAttr("GameRulesName", gameRulesName); testSuite->setAttr("tests", 1); testSuite->setAttr("failures", 1); testSuite->setAttr("errors", 0); testSuite->setAttr("time", 0); testSuite->addChild(*additionalTestCase); testSuites->addChild(testSuite); } char mapNameChrs[256]; char gameRulesNameChrs[256]; cry_strncpy(mapNameChrs, mapName, sizeof(mapNameChrs)); cry_strncpy(gameRulesNameChrs, gameRulesName, sizeof(gameRulesNameChrs)); for (int i=0; mapNameChrs[i]; i++) { if (mapNameChrs[i] == '/' || mapNameChrs[i] == ' ') { mapNameChrs[i] = '_'; } } for (int i=0; gameRulesNameChrs[i]; i++) { if (gameRulesNameChrs[i] == '/' || gameRulesNameChrs[i] == ' ') { gameRulesNameChrs[i] = '_'; } } const char * resultsCompleteFailMessage = NULL; if (flags & kWriteResultsFlag_unfinished) { resultsCompleteFailMessage = "Didn't finish all tests!"; } else if (m_testSuites.size() == 0) { resultsCompleteFailMessage = "Ran zero tests!"; } if (resultsCompleteFailMessage || m_writeResultsCompleteTestCasePass) { int numFailures = 0; XmlNodeRef testSuite = GetISystem()->CreateXmlNode("testsuite"); testSuite->setAttr("name", "Are results complete?"); XmlNodeRef unfinishedFailure = GetISystem()->CreateXmlNode("testcase"); if (m_createVerboseFilename) { unfinishedFailure->setAttr("name", string().Format("%s_%s_%s%s%s", m_includeThisInFileName, mapNameChrs, gameRulesNameChrs, dedicatedText, serverText)); } else { unfinishedFailure->setAttr("name", string().Format("%s%s", m_includeThisInFileName, dedicatedText)); } if (resultsCompleteFailMessage) { XmlNodeRef failedCase = GetISystem()->CreateXmlNode("failure"); failedCase->setAttr("type", "Unfinished"); failedCase->setAttr("message", resultsCompleteFailMessage); unfinishedFailure->addChild(failedCase); ++ numFailures; } else { unfinishedFailure->setAttr("status", "run"); } testSuite->setAttr("tests", 1); testSuite->setAttr("errors", 0); testSuite->setAttr("time", 0); testSuite->setAttr("failures", numFailures); testSuite->addChild(unfinishedFailure); testSuites->addChild(testSuite); } string justTheFilename; if (m_createVerboseFilename) { justTheFilename.Format("autotest_%s_%s_%s%s%s.xml", m_includeThisInFileName, mapNameChrs, gameRulesNameChrs, dedicatedText, serverText); // TODO add datestamp if needed } else { // If m_createVerboseFilename is false, then only include things in the filename which WON'T CHANGE between the test starting and ending [TF] justTheFilename.Format("autotest_%s%s.xml", m_includeThisInFileName, dedicatedText); } m_outputPath.Format("../Xml-Reports/%s", justTheFilename.c_str()); #ifndef _RELEASE CryLogAlways ("Outputting test to %s", m_outputPath.c_str()); #endif SaveToValidXmlFile(testSuites, m_outputPath.c_str()); if (flags & kWriteResultsFlag_writeDoneMarkerFile) { XmlNodeRef finished = GetISystem()->CreateXmlNode("Finished"); SaveToValidXmlFile(finished, m_outputPath + ".done"); if (m_quitWhenDone) { gEnv->pConsole->ExecuteString("unload"); gEnv->pConsole->ExecuteString("quit"); } } }
int CDialogLoader::LoadFromTable(XmlNodeRef tableNode, const string& groupName, TDialogScriptMap& outScriptMap) { unsigned char nCellIndexToType[MAX_CELL_COUNT]; memset(nCellIndexToType, ATTR_SKIP, sizeof(nCellIndexToType) ); IMScript theScript; int nNumGoodScripts = 0; int nRowIndex = 0; int nChilds = tableNode->getChildCount(); for (int i=0; i<nChilds; ++i) { XmlNodeRef rowNode = tableNode->getChild(i); if (!rowNode || !rowNode->isTag("Row")) continue; ++nRowIndex; // skip first row as it should only contain column description if (nRowIndex == 1) { FillMapping(rowNode, nCellIndexToType); continue; } IMScriptLine scriptLine; bool bLineValid = false; int nColCount = rowNode->getChildCount(); int nCellIndex = 0; for (int j=0; j<nColCount; ++j) { XmlNodeRef cellNode = rowNode->getChild(j); if (!cellNode || !cellNode->isTag("Cell")) continue; int tmpIndex = 0; if (cellNode->getAttr("ss:Index", tmpIndex)) { nCellIndex = tmpIndex-1; } if (nCellIndex < 0 || nCellIndex >= MAX_CELL_COUNT) break; XmlNodeRef cellDataNode = cellNode->findChild("Data"); if (!cellDataNode) { ++nCellIndex; continue; } unsigned char nCellType = nCellIndexToType[nCellIndex]; const char* content = cellDataNode->getContent(); // nRowIndex and nCellIndex should be correct now [1-based, not 0-based!] switch (nCellType) { case ATTR_SKIP: break; case ATTR_DIALOG: if (theScript.IsValid()) { const bool ok = ProcessScript(theScript, groupName, outScriptMap); if (ok) ++nNumGoodScripts; theScript.Reset(); } theScript.name = content; break; case ATTR_ACTOR: scriptLine.actor = content; bLineValid = true; break; case ATTR_AUDIO: if (bLineValid) { if(content == 0) scriptLine.audioID = INVALID_AUDIO_CONTROL_ID; else gEnv->pAudioSystem->GetAudioTriggerID(content, scriptLine.audioID); } break; case ATTR_ANIM: if (bLineValid) scriptLine.anim = content; break; case ATTR_FACIAL: if (bLineValid) { size_t n = strcspn(content, ":; "); if (n == strlen(content)) { scriptLine.facial = content; scriptLine.facialWeight = 0.5f; scriptLine.facialFadeTime = 0.5f; } else { scriptLine.facial.assign ( content, n ); float w = 0.5f; float t = 0.5f; int nGood = sscanf(content+n+1, "%f%*[:; ]%f",&w,&t); if (nGood != 1 && nGood != 2) { GameWarning("[DIALOG] CDialogLoader::LoadFromTable: DialogScript '%s' has invalid Facial Expression Content '%s'. Using weight=%f fadetime=%f.", groupName.c_str(), content,w,t); } scriptLine.facialWeight = w; scriptLine.facialFadeTime = t; } } break; case ATTR_LOOKAT: if (bLineValid) scriptLine.lookat = content; break; case ATTR_DELAY: if (bLineValid) { float val = 0.0f; int n = sscanf(content,"%f", &val); if (n == 1) { scriptLine.delay = val; } } break; default: break; } ++nCellIndex; } if (scriptLine.IsValid()) { theScript.lines.push_back(scriptLine); } } if (theScript.IsValid()) { const bool ok = ProcessScript(theScript, groupName, outScriptMap); if (ok) ++nNumGoodScripts; } return nNumGoodScripts; }
void CAutoTester::UpdateTestNumClientsLevelRotate() { if(gEnv->bServer) { IGameFramework *pFramework = gEnv->pGame->GetIGameFramework(); int numChannels = 1; //local channel if(pFramework) { INetNub *pNub = pFramework->GetServerNetNub(); if(pNub) { numChannels = pNub->GetNumChannels(); } } if (numChannels > m_stateData.testNumClientsRotate.m_maxNumClientsConnected) { m_stateData.testNumClientsRotate.m_maxNumClientsConnected=numChannels; } float timeSeconds=gEnv->pTimer->GetFrameStartTime().GetSeconds(); CryWatch("time=%f; nextTimeOut=%f; numClients=%d; maxNumClients=%d; numClientsExpected=%d", timeSeconds, m_stateData.testNumClientsRotate.m_nextTimeOut, numChannels, m_stateData.testNumClientsRotate.m_maxNumClientsConnected, m_stateData.testNumClientsRotate.m_numClientsExpected); if (timeSeconds > m_stateData.testNumClientsRotate.m_debugTimer) { m_stateData.testNumClientsRotate.m_debugTimer = timeSeconds+2.0f; CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() updating time=%f; nextTimeOut=%f; numClients=%d; maxNumClients=%d; numClientsExpected=%d", timeSeconds, m_stateData.testNumClientsRotate.m_nextTimeOut, numChannels, m_stateData.testNumClientsRotate.m_maxNumClientsConnected, m_stateData.testNumClientsRotate.m_numClientsExpected); } if (timeSeconds > m_stateData.testNumClientsRotate.m_nextTimeOut) { CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() testing num clients and time has expired. numClients=%d; maxNumClients=%d; numClientsExpected=%d", numChannels, m_stateData.testNumClientsRotate.m_maxNumClientsConnected, m_stateData.testNumClientsRotate.m_numClientsExpected); bool passed=false; ILevelRotation *pLevelRotation = g_pGame->GetIGameFramework()->GetILevelSystem()->GetLevelRotation(); string mapName = g_pGame->GetIGameFramework()->GetILevelSystem()->GetCurrentLevel()->GetLevelInfo()->GetName(); string gameRulesName; gameRulesName = g_pGame->GetGameRules()->GetEntity()->GetClass()->GetName(); XmlNodeRef testCase = GetISystem()->CreateXmlNode(); string nameStr; if (m_stateData.testNumClientsRotate.m_levelIndex == 0) { nameStr.Format("%02d/%d) Level: %s; gameRules: %s; numClients=%d; timeTested=%.1f seconds", m_stateData.testNumClientsRotate.m_levelIndex+1, pLevelRotation->GetLength(), mapName.c_str(), gameRulesName.c_str(), numChannels, m_stateData.testNumClientsRotate.m_firstLevelTimeOut); } else { nameStr.Format("%02d/%d) Level: %s; gameRules: %s; numClients=%d; timeTested=%.1f seconds", m_stateData.testNumClientsRotate.m_levelIndex+1, pLevelRotation->GetLength(), mapName.c_str(), gameRulesName.c_str(), numChannels, m_stateData.testNumClientsRotate.m_levelTimeOut); } CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() outputting a test result with these details [%s]", nameStr.c_str()); testCase->setTag("testcase"); testCase->setAttr("name", nameStr.c_str()); testCase->setAttr("time", 0); testCase->setAttr("numClients", numChannels); testCase->setAttr("maxNumClientsConnected",m_stateData.testNumClientsRotate.m_maxNumClientsConnected); testCase->setAttr("numClientsExpected", m_stateData.testNumClientsRotate.m_numClientsExpected); if (numChannels == m_stateData.testNumClientsRotate.m_maxNumClientsConnected) { CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() testing num clients and time has expired. We have the same number of clients are our maxNumClients %d", numChannels); if (numChannels == m_stateData.testNumClientsRotate.m_numClientsExpected) // may want to remove this check as keeping the number that joined should be sufficient { CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() testing num clients and time has expired. We have the same number of clients as we expected to have %d", numChannels); testCase->setAttr("status", "run"); passed=true; } else { CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() testing num clients and time has expired. We DON'T have the same number of clients %d as we expected to have %d", numChannels, m_stateData.testNumClientsRotate.m_numClientsExpected); //testCase->setAttr("status", "failed"); XmlNodeRef failedCase = GetISystem()->CreateXmlNode(); failedCase->setTag("failure"); failedCase->setAttr("type", "NotEnoughClients"); failedCase->setAttr("message", string().Format("testing num clients and time has expired. We DON'T have the same number of clients %d as we expected to have %d", numChannels, m_stateData.testNumClientsRotate.m_numClientsExpected)); testCase->addChild(failedCase); } } else { //testCase->setAttr("status", "failed"); XmlNodeRef failedCase = GetISystem()->CreateXmlNode(); failedCase->setTag("failure"); failedCase->setAttr("type", "NotEnoughClients"); failedCase->setAttr("message", string().Format("testing num clients and time has expired. We DON'T have the same number of clients %d as we peaked at %d", numChannels, m_stateData.testNumClientsRotate.m_maxNumClientsConnected)); testCase->addChild(failedCase); } AddTestCaseResult("Test Clients In Level Rotation", testCase, passed); Stop(); if (pLevelRotation->GetNext() != 0) { CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() has found we're not at the end of the level rotation moving on to the next level - levelIndex=%d; rotation->GetNext()=%d\n", m_stateData.testNumClientsRotate.m_levelIndex+1, pLevelRotation->GetNext()); Restart(); gEnv->pConsole->ExecuteString("g_nextlevel"); // has to be a better way of doing this m_stateData.testNumClientsRotate.m_nextTimeOut = timeSeconds + m_stateData.testNumClientsRotate.m_levelTimeOut; m_stateData.testNumClientsRotate.m_levelIndex++; } else { CryLogAlways("CAutoTester::UpdateTestNumClientsLevelRotate() has found we ARE at the end of the level rotation. Not doing anymore tests\n"); } } } }
//////////////////////////////////////////////////////////////////////////// // private functions //////////////////////////////////////////////////////////////////////////// void CUIObjectives::UpdateObjectiveInfo() { m_ObjectiveMap.clear(); string path = "Libs/UI/Objectives_new.xml"; XmlNodeRef missionObjectives = GetISystem()->LoadXmlFromFile( path.c_str() ); if (missionObjectives == 0) { gEnv->pLog->LogError("Error while loading MissionObjective file '%s'", path.c_str() ); return; } for(int tag = 0; tag < missionObjectives->getChildCount(); ++tag) { XmlNodeRef mission = missionObjectives->getChild(tag); const char* attrib; const char* objective; const char* text; for(int obj = 0; obj < mission->getChildCount(); ++obj) { XmlNodeRef objectiveNode = mission->getChild(obj); string id(mission->getTag()); id += "."; id += objectiveNode->getTag(); if(objectiveNode->getAttributeByIndex(0, &attrib, &objective) && objectiveNode->getAttributeByIndex(1, &attrib, &text)) { m_ObjectiveMap[ id ].Name = objective; m_ObjectiveMap[ id ].Desc = text; } else { gEnv->pLog->LogError("Error while loading MissionObjective file '%s'", path.c_str() ); return; } } } }
void CDLCManager::OnDLCMounted(const XmlNodeRef &rootNode, const char* sDLCRootFolder) { CryLog( "OnDLCMounted: '%s'", sDLCRootFolder); XmlString minVersion; XmlString sName; int dlcId; if (rootNode->getAttr("minversion", minVersion) && rootNode->getAttr("name", sName) && rootNode->getAttr("id", dlcId)) { CryLog( "DLC Name = %s, ID = %d", sName.c_str(), dlcId ); if (dlcId >= 0 && dlcId < MAX_DLC_COUNT) { #if (! ENTITLEMENTS_AUTHORATIVE) || defined (DEDICATED_SERVER) //whenever we load a dlc, it is automatically allowed m_allowedDLCs |= BIT(dlcId); #endif if (!IsDLCReallyLoaded(dlcId)) { SFileVersion currentVersion = gEnv->pSystem->GetProductVersion(); SFileVersion minimumVersion = SFileVersion(minVersion.c_str()); if (currentVersion < minimumVersion) { char currentVersionString[MAX_VERSION_STRING]; currentVersion.ToString(currentVersionString); CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "Unable to load DLC \"%s\" because it requires version %s and current version is %s", sName.c_str(), minVersion.c_str(), currentVersionString); RequestDLCWarning("DLCVersionMismatch",2, true); } else { XmlNodeRef crcNode = rootNode->findChild("crcs"); PopulateDLCContents(rootNode, dlcId, sName.c_str() ); //insist that CRCs are present and level folders match listed contents if ( !crcNode || !VerifyCRCs(crcNode, sDLCRootFolder) || !CheckLevels( dlcId, sDLCRootFolder ) ) { ClearDLCContents( dlcId ); RequestDLCWarning("DLCFileCorrupt",4, true); CryLog("DLC \"%s\" not loaded successfully", sName.c_str()); } else { CryLog("DLC \"%s\" loaded successfully", sName.c_str()); m_loadedDLCs |= BIT(dlcId); m_dlcContents[ dlcId ].root.Format( "%s", sDLCRootFolder ); XmlNodeRef unlocksXml = rootNode->findChild("Unlocks"); if(unlocksXml) { DoDLCUnlocks( unlocksXml, dlcId); } CryFixedStringT<ICryPak::g_nMaxPath> path; //Level Extras pak contains things which need to be accessed relative to the Level Path //eg. Level meta data, icons and mini maps //also contains Level Names and Rich Presence mappings path.Format("%s/dlcLevelExtras.pak", sDLCRootFolder); CryLog( "DLC: Opening %s as %s", path.c_str(), sDLCRootFolder ); bool success = gEnv->pCryPak->OpenPack( sDLCRootFolder, path ); //Data pak contains things which need to be accessed relative to the Game Root //eg. Objects and Textures for new entities path.Format("%s/dlcData.pak", sDLCRootFolder); string gamePath = PathUtil::GetGameFolder(); CryLog( "DLC: Opening %s as %s", path.c_str(), gamePath.c_str() ); success &= gEnv->pCryPak->OpenPack( gamePath.c_str(), path ); if (success == false) { CRY_ASSERT_MESSAGE(success, "Failed to open DLC packs"); CryLog("Failed to open DLC packs '%s'",path.c_str()); } else { //Only DLCs with data paks can have strings or levels path.Format("%s/", sDLCRootFolder); CryLog( "DLCManager: Adding %s to Mod paths", path.c_str() ); gEnv->pCryPak->AddMod(path.c_str()); //load string mappings for level names in this DLC path.Format( "%s/scripts/dlc%dnames.xml", sDLCRootFolder, dlcId ); g_pGame->LoadMappedLevelNames( path.c_str() ); //and load the actual localized strings ILocalizationManager *pLocMan = GetISystem()->GetLocalizationManager(); path.Format( "%s/scripts/dlc%d%s.xml", sDLCRootFolder, dlcId, pLocMan->GetLanguage() ); pLocMan->LoadExcelXmlSpreadsheet( path ); //see if the pack has a description CryFixedStringT<32> descriptionKey; descriptionKey.Format( "dlc%d_pack_description", dlcId ); SLocalizedInfoGame tempInfo; if( pLocMan->GetLocalizedInfoByKey( descriptionKey.c_str(), tempInfo ) ) { m_dlcContents[ dlcId ].descriptionStr.Format( "@%s", descriptionKey.c_str() ); } //and load the Rich Presence mappings path.Format( "%s/scripts/dlc%dpresence.xml", sDLCRootFolder, dlcId ); g_pGame->AddRichPresence( path.c_str() ); //and get the Score Rewards Path m_dlcContents[ dlcId ].scoreRewardsPath.Format( "%s/scripts/dlc%drewards.xml", sDLCRootFolder, dlcId ); //and the Playlists Path m_dlcContents[ dlcId ].playlistsPath.Format( "%s/scripts/dlc%dplaylists", sDLCRootFolder, dlcId ); ILevelSystem *pLevelSystem = g_pGame->GetIGameFramework()->GetILevelSystem(); path.Format("%s/levels", sDLCRootFolder); CryLog("DLC Levelsystem rescan '%s'", path.c_str()); const uint32 dlcTag = 'DLC0'; pLevelSystem->Rescan(path.c_str(), dlcTag); } } } } else { CryLog("DLC %d already loaded, OK if from re-sign in", dlcId ); } } else { CRY_ASSERT_MESSAGE(false, "DLC id is not within range"); } } else { RequestDLCWarning("DLCXmlError",4, true); } }
void SAIDescriptor::Reset(const XmlNodeRef& paramsNode, bool defaultInit) { FUNCTION_PROFILER(GetISystem(), PROFILE_GAME); if (paramsNode) { paramsNode->getAttr("speed", descriptor.fSpeed); paramsNode->getAttr("damage_radius", descriptor.fDamageRadius); paramsNode->getAttr("charge_time", descriptor.fChargeTime); paramsNode->getAttr("burstBulletCountMin", descriptor.burstBulletCountMin); paramsNode->getAttr("burstBulletCountMax", descriptor.burstBulletCountMax); paramsNode->getAttr("burstPauseTimeMin", descriptor.burstPauseTimeMin); paramsNode->getAttr("burstPauseTimeMax", descriptor.burstPauseTimeMax); paramsNode->getAttr("singleFireTriggerTime", descriptor.singleFireTriggerTime); paramsNode->getAttr("spreadRadius", descriptor.spreadRadius); paramsNode->getAttr("coverFireTime", descriptor.coverFireTime); paramsNode->getAttr("sweep_width", descriptor.sweepWidth); paramsNode->getAttr("sweep_frequency", descriptor.sweepFrequency); paramsNode->getAttr("draw_time", descriptor.drawTime); paramsNode->getAttr("projectileGravity", descriptor.projectileGravity); paramsNode->getAttr("pressureMultiplier", descriptor.pressureMultiplier); paramsNode->getAttr("lobCriticalDistance", descriptor.lobCriticalDistance); paramsNode->getAttr("preferredHeight", descriptor.preferredHeight); paramsNode->getAttr("closeDistance", descriptor.closeDistance); descriptor.preferredHeightForCloseDistance = descriptor.preferredHeight; paramsNode->getAttr("preferredHeightForCloseDistance", descriptor.preferredHeightForCloseDistance); paramsNode->getAttr("maxAcceptableDistanceFromTarget", descriptor.maxAcceptableDistanceFromTarget); paramsNode->getAttr("minimumDistanceFromFriends", descriptor.minimumDistanceFromFriends); descriptor.smartObjectClass = paramsNode->getAttr("smartobject_class"); descriptor.firecmdHandler = paramsNode->getAttr("handler"); int signalOnShoot(0); paramsNode->getAttr("signal_on_shoot", signalOnShoot); descriptor.bSignalOnShoot = signalOnShoot != 0; } }
//====================================================================== void CWeaponAttachmentManager::CreatePlayerBoneAttachments() { if (ICharacterInstance *pCharInstance = m_pOwner->GetEntity()->GetCharacter(0)) { IAttachmentManager *pAttachmentManager = pCharInstance->GetIAttachmentManager(); if(pAttachmentManager == NULL) { return; } const XmlNodeRef rootNode = gEnv->pSystem->LoadXmlFromFile( WEAPON_ATTACHMENTS_FILE ); if (!rootNode || strcmpi(rootNode->getTag(), "WeaponAttachments")) { CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "Could not load Weapon Attachments data. Invalid XML file '%s'! ", WEAPON_ATTACHMENTS_FILE); return; } IAttachment *pAttachment = NULL; const int childCount = rootNode->getChildCount(); for (int i = 0; i < childCount; ++i) { XmlNodeRef weaponAttachmentNode = rootNode->getChild(i); if(weaponAttachmentNode == (IXmlNode *)NULL) { continue; } const char *attachmentName = ""; weaponAttachmentNode->getAttr("name", &attachmentName); if(!strcmp(attachmentName, "")) { CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "Empty Weapon Attachment name in file: %s! Skipping Weapon Attachment.", WEAPON_ATTACHMENTS_FILE); continue; } pAttachment = pAttachmentManager->GetInterfaceByName(attachmentName); if(pAttachment) { continue; } //Attachment doesn't exist, create it const int weaponAttachmentCount = weaponAttachmentNode->getChildCount(); const char *boneName = ""; Vec3 attachmentOffset(ZERO); Ang3 attachmentRotation(ZERO); for (int a = 0; a < weaponAttachmentCount; ++a) { const XmlNodeRef childNode = weaponAttachmentNode->getChild(a); if(childNode == (IXmlNode *)NULL) { continue; } if(!strcmp(childNode->getTag(), "Bone")) { childNode->getAttr("name", &boneName); } else if(!strcmp(childNode->getTag(), "Offset")) { childNode->getAttr("x", attachmentOffset.x); childNode->getAttr("y", attachmentOffset.y); childNode->getAttr("z", attachmentOffset.z); } else if(!strcmp(childNode->getTag(), "Rotation")) { float value = 0.0f; childNode->getAttr("x", value); attachmentRotation.x = DEG2RAD(value); childNode->getAttr("y", value); attachmentRotation.y = DEG2RAD(value); childNode->getAttr("z", value); attachmentRotation.z = DEG2RAD(value); } } const char *attachmentType = ""; weaponAttachmentNode->getAttr("type", &attachmentType); if(!strcmp(attachmentType, "")) { CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "No Weapon Attachment type assigned! Skipping Weapon Attachment: %s", attachmentName); continue; } const bool isBoneAttachment = !strcmp(attachmentType, "Bone"); const bool isFaceAttachment = !strcmp(attachmentType, "Face"); //Bone attachment needs the bone name if (!strcmp(boneName, "") && isBoneAttachment) { CryWarning(VALIDATOR_MODULE_GAME, VALIDATOR_WARNING, "Bone Attachment with no bone name assigned! Skipping Weapon Attachment: %s", attachmentName); continue; } if(isBoneAttachment) { pAttachment = pAttachmentManager->CreateAttachment(attachmentName, CA_BONE, boneName); } else if(isFaceAttachment) { pAttachment = pAttachmentManager->CreateAttachment(attachmentName, CA_FACE, 0); } if(pAttachment) { if(isBoneAttachment) { m_boneAttachmentMap.insert(TBoneAttachmentMap::value_type(attachmentName, 0)); } if(pAttachment && !attachmentOffset.IsZero()) { QuatT attachmentQuat(IDENTITY); attachmentQuat.SetRotationXYZ(attachmentRotation, attachmentOffset); pAttachment->SetAttAbsoluteDefault( attachmentQuat ); pAttachment->ProjectAttachment(); } } } } }
void SFireParams::Reset(const XmlNodeRef& paramsNode, bool defaultInit/*=true*/) { CryFixedStringT<32> ammo_type = ""; CryFixedStringT<32> ammo_spawn_type = ""; if (defaultInit) { suffix = ""; suffixAG = ""; tag = ""; rate = 400; fake_fire_rate = 0; minimum_ammo_count = 0; clip_size = 30; max_clips = 20; hit_type = "bullet"; hitTypeId = 0; changeFMFireDelayFraction = 0.0f; endReloadFraction = 1.0f; fillAmmoReloadFraction = 1.0f; autoReload = true; autoSwitch = true; stabilization = 0.2f; speed_override = 0.0f; bullet_chamber = 0; damage = 32; damage_drop_per_meter = 0.0f; damage_drop_min_distance = 0.0f; damage_drop_min_damage = 0.0f; point_blank_amount = 1.0f; point_blank_distance = 0.0f; point_blank_falloff_distance = 0.0f; ai_infiniteAmmo = false; npc_additional_damage = 0; ai_reload_time = 2.5f; crosshair = eHCH_Normal; no_cock = true; helper[0] = ""; helper[1] = ""; barrel_count = 1; spin_up_time = 0.0f; fire_anim_damp = 1.0f; ironsight_fire_anim_damp = 1.0f; holdbreath_fire_anim_damp = 0.5f; holdbreath_ffeedback_damp = 0.5f; knocks_target = false; min_damage_for_knockDown = 0; knockdown_chance_leg = 0; min_damage_for_knockDown_leg = 0; bullet_pierceability_modifier = 0; is_silenced = false; ignore_damage_falloff = false; laser_beam_uses_spread = false; muzzleFromFiringLocator = false; } if (paramsNode) { CGameXmlParamReader reader(paramsNode); suffix = reader.ReadParamValue("suffix", suffix.c_str()); suffixAG = reader.ReadParamValue("suffixAG", suffixAG.c_str()); tag = reader.ReadParamValue("tag", tag.c_str()); reader.ReadParamValue<short>("rate", rate); reader.ReadParamValue<short>("fake_fire_rate", fake_fire_rate); reader.ReadParamValue<short>("minimum_ammo_count", minimum_ammo_count); reader.ReadParamValue<short>("clip_size", clip_size); reader.ReadParamValue<short>("max_clips", max_clips); hit_type = reader.ReadParamValue("hit_type", hit_type.c_str()); ammo_type = reader.ReadParamValue("ammo_type", ammo_type.c_str()); ammo_spawn_type = reader.ReadParamValue("ammo_spawn_type", ammo_spawn_type.c_str()); reader.ReadParamValue<float>("changeFMFireDelayFraction", changeFMFireDelayFraction); reader.ReadParamValue<float>("endReloadFraction", endReloadFraction); reader.ReadParamValue<float>("fillAmmoReloadFraction", fillAmmoReloadFraction); reader.ReadParamValue<bool>("autoReload", autoReload); reader.ReadParamValue<bool>("autoSwitch", autoSwitch); reader.ReadParamValue<float>("stabilization", stabilization); reader.ReadParamValue<float>("speed_override", speed_override); #ifndef _RELEASE if (!defaultInit && endReloadFraction < fillAmmoReloadFraction) { const char* weaponName = ""; for (XmlNodeRef currentNode = paramsNode;;currentNode=currentNode->getParent()) { if (currentNode->getParent()) continue; weaponName = currentNode->getAttr("name"); break; } XmlNodeRef fireModeNode = paramsNode->getParent(); const char* fireModeName = fireModeNode->getAttr("name"); gEnv->pLog->LogWarning( "endReloadFraction is smaller than fillAmmoReloadFraction on '%s' at '%s'", weaponName, fireModeName); } #endif endReloadFraction = max(endReloadFraction, fillAmmoReloadFraction); int bulletChamber = 0; if (reader.ReadParamValue<int>("bullet_chamber", bulletChamber)) { bullet_chamber = (uint8)bulletChamber; } reader.ReadParamValue<int>("damage", damage); reader.ReadParamValue<float>("damage_drop_per_meter", damage_drop_per_meter); reader.ReadParamValue<float>("damage_drop_min_distance", damage_drop_min_distance); reader.ReadParamValue<float>("damage_drop_min_damage", damage_drop_min_damage); reader.ReadParamValue<float>("point_blank_amount", point_blank_amount); reader.ReadParamValue<float>("point_blank_distance", point_blank_distance); reader.ReadParamValue<float>("point_blank_falloff_distance", point_blank_falloff_distance); reader.ReadParamValue<bool>("ai_infiniteAmmo", ai_infiniteAmmo); reader.ReadParamValue<int>("npc_additional_damage", npc_additional_damage); reader.ReadParamValue<float>("ai_reload_time", ai_reload_time); int crosshairType = (ECrosshairTypes)eHCH_Normal; if (reader.ReadParamValue<int>("crosshair", crosshairType)) { crosshair = (ECrosshairTypes)crosshairType; } reader.ReadParamValue<bool>("no_cock", no_cock); helper[0] = reader.ReadParamValue("helper_fp", helper[0].c_str()); helper[1] = reader.ReadParamValue("helper_tp", helper[1].c_str()); reader.ReadParamValue<short>("barrel_count", barrel_count); reader.ReadParamValue<float>("spin_up_time", spin_up_time); reader.ReadParamValue<float>("fire_anim_damp", fire_anim_damp); reader.ReadParamValue<float>("ironsight_fire_anim_damp", ironsight_fire_anim_damp); reader.ReadParamValue<float>("holdbreath_fire_anim_damp", holdbreath_fire_anim_damp); reader.ReadParamValue<float>("holdbreath_ffeedback_damp", holdbreath_ffeedback_damp); reader.ReadParamValue<bool>("knocks_target", knocks_target); reader.ReadParamValue<float>("min_damage_for_knockDown", min_damage_for_knockDown); reader.ReadParamValue<int>("knockdown_chance_leg", knockdown_chance_leg); reader.ReadParamValue<float>("min_damage_for_knockDown_leg", min_damage_for_knockDown_leg); int pierceabilityMod = 0; reader.ReadParamValue<int>("bullet_pierceability_modifier", pierceabilityMod); bullet_pierceability_modifier = (int8)pierceabilityMod; reader.ReadParamValue<bool>("is_silenced", is_silenced); reader.ReadParamValue<bool>("muzzleFromFiringLocator", muzzleFromFiringLocator); reader.ReadParamValue<bool>("ignore_damage_falloff", ignore_damage_falloff); reader.ReadParamValue<bool>("laser_beam_uses_spread", laser_beam_uses_spread); } if (defaultInit || !ammo_type.empty()) { ammo_type_class = gEnv->pEntitySystem->GetClassRegistry()->FindClass(ammo_type.c_str()); } spawn_ammo_class = 0; if (defaultInit || !ammo_spawn_type.empty()) { spawn_ammo_class = gEnv->pEntitySystem->GetClassRegistry()->FindClass(ammo_spawn_type.c_str()); } if (spawn_ammo_class == 0) { spawn_ammo_class = ammo_type_class; } }
void CHUDMissionObjectiveSystem::LoadObjectiveAnalysisData(const char* levelpath) { CryFixedStringT<128> filename; if(levelpath==NULL) { filename = "Libs/UI/ObjectivesAnalysis.xml"; } else { filename.Format("%s/leveldata/ObjectivesAnalysis.xml", levelpath); } XmlNodeRef root = GetISystem()->LoadXmlFromFile(filename.c_str()); if (root == 0) return; XmlNodeRef analysisDataContainerNode = root->findChild("AnalysisData"); SObjectiveAnalysisData analysisData; SSingleObjectiveAnalysisData singleAnalysisData; if (analysisDataContainerNode != 0) { for(int i = 0; i < analysisDataContainerNode->getChildCount(); ++i) { XmlNodeRef analysisDataNode = analysisDataContainerNode->getChild(i); const char* szOuterId = analysisDataNode->getAttr("Id"); if (szOuterId == NULL || szOuterId[0] == '\0') { GameWarning("CHUDMissionObjectiveSystem::LoadObjectiveAnalysisData: Failed to load analysisdata, invalid id"); continue; } analysisData.m_singleObjectiveData.clear(); const int iNumSingleAnalysis = analysisDataNode->getChildCount(); bool bFailedAddedSingleAnalysis = false; for (int j = 0; j < iNumSingleAnalysis; j++) { XmlNodeRef singleAnalysisDataNode = analysisDataNode->getChild(j); const char* szSingleId; int iUseOuterId; // UseOuterId saves needing to duplicate text to the outer Id bool bResult = singleAnalysisDataNode->getAttr("UseOuterId", iUseOuterId); if (bResult && (iUseOuterId == 1)) { szSingleId = szOuterId; } else { szSingleId = analysisDataNode->getAttr("Id"); } if (szSingleId == NULL || szSingleId[0] == '\0') { GameWarning("CHUDMissionObjectiveSystem::LoadObjectiveAnalysisData: Failed to load single analysisdata section for analysis: %s, invalid id", szOuterId); bFailedAddedSingleAnalysis = true; break; } singleAnalysisData.m_id = szSingleId; singleAnalysisDataNode->getAttr("Percent", singleAnalysisData.m_fPercent); analysisData.m_singleObjectiveData.push_back(singleAnalysisData); } if (bFailedAddedSingleAnalysis || analysisData.m_singleObjectiveData.size() < 1) { GameWarning("CHUDMissionObjectiveSystem::LoadObjectiveAnalysisData: Failed to load analysisdata: %s, problem with section data", szOuterId); continue; } analysisDataNode->getAttr("OverrideSectionID",analysisData.m_iOverrideIndex); analysisDataNode->getAttr("AttachInWorld", analysisData.m_bAttachInWorld); m_objectiveAnalysisData[szOuterId] = analysisData; } } }
void CUIHUD3D::SpawnHudEntities() { RemoveHudEntities(); if(gEnv->IsEditor() && gEnv->IsEditing()) return; XmlNodeRef node = gEnv->pSystem->LoadXmlFromFile(HUD3D_PREFAB_LIB); if(node) { // get the prefab with the name defined in HUD3D_PREFAB_NAME XmlNodeRef prefab = NULL; for(int i = 0; i < node->getChildCount(); ++i) { const char *name = node->getChild(i)->getAttr("Name"); if(name && strcmp(name, HUD3D_PREFAB_NAME) == 0) { prefab = node->getChild(i); prefab = prefab ? prefab->findChild("Objects") : XmlNodeRef(); break; } } if(prefab) { // get the PIVOT entity and collect childs XmlNodeRef pivotNode = NULL; std::vector<XmlNodeRef> childs; const int count = prefab->getChildCount(); childs.reserve(count-1); for(int i = 0; i < count; ++i) { const char *name = prefab->getChild(i)->getAttr("Name"); if(strcmp("PIVOT", name) == 0) { assert(pivotNode == NULL); pivotNode = prefab->getChild(i); } else { childs.push_back(prefab->getChild(i)); } } if(pivotNode) { // spawn pivot entity IEntityClass *pEntClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(pivotNode->getAttr("EntityClass")); if(pEntClass) { SEntitySpawnParams params; params.nFlags = ENTITY_FLAG_CLIENT_ONLY; params.pClass = pEntClass; m_pHUDRootEntity = gEnv->pEntitySystem->SpawnEntity(params); } if(!m_pHUDRootEntity) return; m_HUDRootEntityId = m_pHUDRootEntity->GetId(); // spawn the childs and link to the pivot enity for(std::vector<XmlNodeRef>::iterator it = childs.begin(); it != childs.end(); ++it) { XmlNodeRef child = *it; pEntClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(child->getAttr("EntityClass")); if(pEntClass) { const char *material = child->getAttr("Material"); Vec3 pos; Vec3 scale; Quat rot; child->getAttr("Pos", pos); child->getAttr("Rotate", rot); child->getAttr("Scale", scale); SEntitySpawnParams params; params.nFlags = ENTITY_FLAG_CLIENT_ONLY; params.pClass = pEntClass; params.vPosition = pos; params.qRotation = rot; params.vScale = scale; IEntity *pEntity = gEnv->pEntitySystem->SpawnEntity(params); if(pEntity) { IScriptTable *pScriptTable = pEntity->GetScriptTable(); if(pScriptTable) { SmartScriptTable probs; pScriptTable->GetValue("Properties", probs); XmlNodeRef properties = child->findChild("Properties"); if(probs && properties) { for(int k = 0; k < properties->getNumAttributes(); ++k) { const char *sKey; const char *sVal; properties->getAttributeByIndex(k, &sKey, &sVal); probs->SetValue(sKey, sVal); } } Script::CallMethod(pScriptTable,"OnPropertyChange"); } if(material) { IMaterial *pMat = gEnv->p3DEngine->GetMaterialManager()->LoadMaterial(material); if(pMat) pEntity->SetMaterial(pMat); } m_pHUDRootEntity->AttachChild(pEntity); m_HUDEnties.push_back(pEntity->GetId()); } } } } } } OnVisCVarChange(NULL); }
void CBattleDust::ReloadXml() { // first empty out the previous stuff m_weaponPower.clear(); m_explosionPower.clear(); m_vehicleExplosionPower.clear(); m_bulletImpactPower.clear(); IXmlParser* pxml = g_pGame->GetIGameFramework()->GetISystem()->GetXmlUtils()->CreateXmlParser(); if(!pxml) return; XmlNodeRef node = GetISystem()->LoadXmlFromFile(PathUtil::GetGameFolder() + "/Scripts/GameRules/BattleDust.xml"); if(!node) return; XmlNodeRef paramsNode = node->findChild("params"); if(paramsNode) { paramsNode->getAttr("fogspawnpower", m_entitySpawnPower); paramsNode->getAttr("defaultlifetime", m_defaultLifetime); paramsNode->getAttr("maxlifetime", m_maxLifetime); paramsNode->getAttr("maxeventpower", m_maxEventPower); paramsNode->getAttr("minparticlecount", m_minParticleCount); paramsNode->getAttr("maxparticlecount", m_maxParticleCount); paramsNode->getAttr("distancebetweenevents", m_distanceBetweenEvents); } XmlNodeRef eventsNode = node->findChild("events"); if(eventsNode) { // corresponds to the eBDET_ShotFired event XmlNodeRef shotNode = eventsNode->findChild("shotfired"); if(shotNode) { for (int i = 0; i < shotNode->getChildCount(); ++i) { XmlNodeRef weaponNode = shotNode->getChild(i); if(weaponNode) { XmlString name; float power = 1.0f; float lifetime = 1.0f; weaponNode->getAttr("name", name); weaponNode->getAttr("power", power); weaponNode->getAttr("lifetime", lifetime); if(!strcmp(name, "default")) { m_defaultWeapon.m_power = power; m_defaultWeapon.m_lifetime = lifetime; } else { SBattleEventParameter param; param.m_name = name; param.m_pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name); param.m_power = power; param.m_lifetime = lifetime; m_weaponPower.push_back(param); } } } } XmlNodeRef explodeNode = eventsNode->findChild("explosion"); if(explodeNode) { for(int i=0; i < explodeNode->getChildCount(); ++i) { XmlNodeRef explosiveNode = explodeNode->getChild(i); if(explosiveNode) { XmlString name; float power = 1.0f; float lifetime = 1.0f; explosiveNode->getAttr("name", name); explosiveNode->getAttr("power", power); explosiveNode->getAttr("lifetime", lifetime); if(!strcmp(name, "default")) { m_defaultExplosion.m_power = power; m_defaultExplosion.m_lifetime = lifetime; } else { SBattleEventParameter param; param.m_name = name; param.m_pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name); param.m_power = power; param.m_lifetime = lifetime; m_explosionPower.push_back(param); } } } } XmlNodeRef vehicleExplodeNode = eventsNode->findChild("vehicleexplosion"); if(vehicleExplodeNode) { for(int i=0; i < vehicleExplodeNode->getChildCount(); ++i) { XmlNodeRef vehicleNode = vehicleExplodeNode->getChild(i); if(vehicleNode) { XmlString name; float power = 1.0f; float lifetime = 1.0f; vehicleNode->getAttr("name", name); vehicleNode->getAttr("power", power); vehicleNode->getAttr("lifetime", lifetime); if(!strcmp(name, "default")) { m_defaultVehicleExplosion.m_power = power; m_defaultVehicleExplosion.m_lifetime = lifetime; } else { SBattleEventParameter param; param.m_name = name; param.m_pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name); param.m_power = power; param.m_lifetime = lifetime; m_vehicleExplosionPower.push_back(param); } } } } XmlNodeRef impactNode = eventsNode->findChild("bulletimpact"); if(impactNode) { for(int i=0; i < impactNode->getChildCount(); ++i) { XmlNodeRef impact = impactNode->getChild(i); if(impact) { XmlString name; float power = 1.0f; float lifetime = 1.0f; impact->getAttr("name", name); impact->getAttr("power", power); impact->getAttr("lifetime", lifetime); if(!strcmp(name, "default")) { m_defaultBulletImpact.m_power = power; m_defaultBulletImpact.m_lifetime = lifetime; } else { SBattleEventParameter param; param.m_name = name; param.m_pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name); param.m_lifetime = lifetime; param.m_power = power; m_bulletImpactPower.push_back(param); } } } } } }
void CAntiCheatManager::ProcessFlagActivity(TCheatType type, uint16 channelId, const float *params, int numParams, const char * pDescription, XmlNodeRef additionalXmlData) { SCheatType &cheat = m_cheats[type]; XmlNodeRef incidentXML; float fInfractionsSeverity = 0.0f; int nMaxConfidence = 0, nMaxInfractionConfidence = 0; typedef std::vector<const SCheatAction*> TCheatActionPtrList; TCheatActionPtrList actionsToTake; EDisconnectionCause kickReason = eDC_Kicked; for (std::vector<SCheatAction>::iterator itAction = cheat.actions.begin(); itAction != cheat.actions.end(); ++itAction) { bool meetsConditions = true; for (std::vector<SCheatCondition>::const_iterator itCondition = itAction->conditions.begin(); itCondition != itAction->conditions.end(); ++itCondition) { assert(itCondition->paramNum <= numParams); float paramValue = params[itCondition->paramNum-1]; meetsConditions = MeetsCondition(itCondition->op, paramValue, itCondition->value); if (!meetsConditions) { break; } } if (meetsConditions) { actionsToTake.push_back(&(*itAction)); if(incidentXML == NULL) { incidentXML = CreateIncidentXML(channelId, type, params, numParams, pDescription); if(additionalXmlData != NULL && incidentXML != NULL) incidentXML->addChild(additionalXmlData); } } if(itAction->action == eCA_Global_Ban) { kickReason = GetBanKickType(channelId); } } bool bDoRemoteLog = false; for(TCheatActionPtrList::const_iterator itActionPtr = actionsToTake.begin(); itActionPtr != actionsToTake.end(); ++itActionPtr) { const SCheatAction * actionPtr = *itActionPtr; nMaxConfidence = max(actionPtr->confidence, nMaxConfidence); switch (actionPtr->action) { case eCA_Log: //The presence of this action will cause the incident to be logged, we don't want to add // any more output as it won't provide any more data break; case eCA_Log_Remote: bDoRemoteLog = true; break; case eCA_Infraction: { fInfractionsSeverity += actionPtr->severity; nMaxInfractionConfidence = max(actionPtr->confidence, nMaxInfractionConfidence); } break; case eCA_Kick: CheatLogAction(incidentXML, eCA_Kick, actionPtr->confidence); KickPlayer(channelId, kickReason, actionPtr->confidence); break; case eCA_Kick_Delayed: CheatLogAction(incidentXML, eCA_Kick_Delayed, actionPtr->confidence); KickPlayerDelayed(channelId, kickReason, actionPtr->confidence); break; case eCA_Ban: CheatLogAction(incidentXML, eCA_Ban, actionPtr->confidence); BanPlayer_Internal(channelId, actionPtr->banTimeout, actionPtr->confidence); break; case eCA_Global_Ban: break; case eCA_Dev_CheatDetected: { #if defined(DEV_CHEAT_HANDLING) CheatLogAction(incidentXML, eCA_Dev_CheatDetected, actionPtr->confidence); stack_string paramsString; CAntiCheatManager::GenerateMessageString(paramsString, params, numParams, pDescription); paramsString.append(" "); paramsString.append(s_cheatTypeNames[type]); HandleDevCheat(channelId, paramsString); #endif break; } } } //If multiple infractions have been triggered by the parameters, we want to log if(fInfractionsSeverity > 0.0f) { XmlNodeRef actionXml = CheatLogAction(incidentXML, eCA_Infraction, nMaxInfractionConfidence); RegisterInfraction(actionXml, channelId, type, fInfractionsSeverity); } if(incidentXML) { CheatLogInternalXml(incidentXML); } }