LCOV - code coverage report
Current view: top level - source/simulation2/system - ComponentManager.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 538 596 90.3 %
Date: 2026-12-03 01:19:39 Functions: 59 63 93.7 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "ComponentManager.h"
      21             : 
      22             : #include "graphics/HeightMipmap.h"
      23             : #include "lib/utf8.h"
      24             : #include "ps/CLogger.h"
      25             : #include "ps/CStr.h"
      26             : #include "ps/Errors.h"
      27             : #include "ps/Filesystem.h"
      28             : #include "ps/Profiler2.h"
      29             : #include "ps/algorithm.h"
      30             : #include "ps/scripting/JSInterface_VFS.h"
      31             : #include "scriptinterface/FunctionWrapper.h"
      32             : #include "scriptinterface/Object.h"
      33             : #include "scriptinterface/Request.h"
      34             : #include "simulation2/MessageTypes.h"
      35             : #include "simulation2/components/ICmpTemplateManager.h"
      36             : #include "simulation2/helpers/Player.h"
      37             : #include "simulation2/system/DynamicSubscription.h"
      38             : #include "simulation2/system/Message.h"
      39             : 
      40             : #include <algorithm>
      41             : #include <cstdint>
      42             : #include <cstdlib>
      43             : #include <fmt/format.h>
      44             : #include <iterator>
      45             : #include <js/GCAPI.h>
      46             : #include <js/TracingAPI.h>
      47             : #include <js/ValueArray.h>
      48             : #include <stdexcept>
      49             : #include <string_view>
      50             : 
      51             : namespace Script { class Context; }
      52             : 
      53             : /**
      54             :  * Used for script-only message types.
      55             :  */
      56             : class CMessageScripted final : public CMessage
      57             : {
      58             : public:
      59        6309 :     virtual int GetType() const { return mtid; }
      60        2634 :     virtual const char* GetScriptHandlerName() const { return handlerName.c_str(); }
      61        1269 :     virtual const char* GetScriptGlobalHandlerName() const { return globalHandlerName.c_str(); }
      62        2085 :     virtual JS::Value ToJSVal(const Script::Request&) const { return msg.get(); }
      63             : 
      64        2100 :     CMessageScripted(const Script::Request& rq, int mtid, const std::string& name, JS::HandleValue msg) :
      65        2100 :         mtid(mtid), handlerName("On" + name), globalHandlerName("OnGlobal" + name), msg(rq.cx, msg)
      66             :     {
      67        2100 :     }
      68             : 
      69             :     int mtid;
      70             :     std::string handlerName;
      71             :     std::string globalHandlerName;
      72             :     JS::PersistentRootedValue msg;
      73             : };
      74             : 
      75         150 : CComponentManager::CComponentManager(CSimContext& context, Script::Context& cx, bool skipScriptFunctions) :
      76         150 :     m_NextScriptComponentTypeId(CID__LastNative),
      77         150 :     m_ScriptInterface("Engine", "Simulation", cx),
      78         150 :     m_SimContext(context), m_CurrentlyHotloading(false)
      79             : {
      80         150 :     context.SetComponentManager(this);
      81             : 
      82         150 :     m_ScriptInterface.SetCallbackData(static_cast<void*> (this));
      83         150 :     m_ScriptInterface.ReplaceNondeterministicRNG(m_RNG);
      84             : 
      85         150 :     JS_AddExtraGCRootsTracer(m_ScriptInterface.GetGeneralJSContext(), Trace, (void*)this);
      86             : 
      87             :     // For component script tests, the test system sets up its own scripted implementation of
      88             :     // these functions, so we skip registering them here in those cases
      89         150 :     if (!skipScriptFunctions)
      90             :     {
      91          76 :         JSI_VFS::RegisterScriptFunctions_ReadOnlySimulation(m_ScriptInterface);
      92          76 :         Script::Request rq(m_ScriptInterface);
      93          76 :         constexpr Script::Function::ObjectGetter<CComponentManager> Getter = &Script::Interface::ObjectFromCBData<CComponentManager>;
      94         775 :         Script::Function::Register<&CComponentManager::Script_RegisterComponentType, Getter>(rq, "RegisterComponentType");
      95         180 :         Script::Function::Register<&CComponentManager::Script_RegisterSystemComponentType, Getter>(rq, "RegisterSystemComponentType");
      96          78 :         Script::Function::Register<&CComponentManager::Script_ReRegisterComponentType, Getter>(rq, "ReRegisterComponentType");
      97         600 :         Script::Function::Register<&CComponentManager::Script_RegisterInterface, Getter>(rq, "RegisterInterface");
      98         460 :         Script::Function::Register<&CComponentManager::Script_RegisterMessageType, Getter>(rq, "RegisterMessageType");
      99         454 :         Script::Function::Register<&CComponentManager::Script_RegisterGlobal, Getter>(rq, "RegisterGlobal");
     100          76 :         Script::Function::Register<&CComponentManager::Script_GetEntitiesWithInterface, Getter>(rq, "GetEntitiesWithInterface");
     101          76 :         Script::Function::Register<&CComponentManager::Script_GetComponentsWithInterface, Getter>(rq, "GetComponentsWithInterface");
     102        2772 :         Script::Function::Register<&CComponentManager::Script_PostMessage, Getter>(rq, "PostMessage");
     103         320 :         Script::Function::Register<&CComponentManager::Script_BroadcastMessage, Getter>(rq, "BroadcastMessage");
     104         273 :         Script::Function::Register<&CComponentManager::Script_AddEntity, Getter>(rq, "AddEntity");
     105          87 :         Script::Function::Register<&CComponentManager::Script_AddLocalEntity, Getter>(rq, "AddLocalEntity");
     106      110240 :         Script::Function::Register<&CComponentManager::QueryInterface, Getter>(rq, "QueryInterface");
     107          76 :         Script::Function::Register<&CComponentManager::DestroyComponentsSoon, Getter>(rq, "DestroyEntity");
     108          76 :         Script::Function::Register<&CComponentManager::FlushDestroyedComponents, Getter>(rq, "FlushDestroyedEntities");
     109          76 :         Script::Function::Register<&CComponentManager::Script_GetTemplate, Getter>(rq, "GetTemplate");
     110             : 
     111          76 :     }
     112             : 
     113             :     // Globalscripts may use VFS script functions
     114         150 :     m_ScriptInterface.LoadGlobalScripts();
     115             : 
     116             :     // Define MT_*, IID_* as script globals, and store their names
     117             : #define MESSAGE(name) m_ScriptInterface.SetGlobal("MT_" #name, (int)MT_##name);
     118             : #define INTERFACE(name) \
     119             :     m_ScriptInterface.SetGlobal("IID_" #name, (int)IID_##name); \
     120             :     m_InterfaceIdsByName[#name] = IID_##name;
     121             : #define COMPONENT(name)
     122             : #include "simulation2/TypeList.h"
     123             : #undef MESSAGE
     124             : #undef INTERFACE
     125             : #undef COMPONENT
     126             : 
     127         150 :     m_ScriptInterface.SetGlobal("INVALID_ENTITY", (int)INVALID_ENTITY);
     128         150 :     m_ScriptInterface.SetGlobal("INVALID_PLAYER", (int)INVALID_PLAYER);
     129         150 :     m_ScriptInterface.SetGlobal("SYSTEM_ENTITY", (int)SYSTEM_ENTITY);
     130             : 
     131         150 :     m_ComponentsByInterface.resize(IID__LastNative);
     132             : 
     133         150 :     ResetState();
     134         150 : }
     135             : 
     136         150 : CComponentManager::~CComponentManager()
     137             : {
     138         150 :     JS_RemoveExtraGCRootsTracer(m_ScriptInterface.GetGeneralJSContext(), Trace, (void*)this);
     139         150 :     ResetState();
     140         154 : }
     141             : 
     142         137 : void CComponentManager::LoadComponentTypes()
     143             : {
     144             : #define MESSAGE(name) \
     145             :     RegisterMessageType(MT_##name, #name);
     146             : #define INTERFACE(name) \
     147             :     extern void RegisterComponentInterface_##name(Script::Interface&); \
     148             :     RegisterComponentInterface_##name(m_ScriptInterface);
     149             : #define COMPONENT(name) \
     150             :     extern void RegisterComponentType_##name(CComponentManager&); \
     151             :     m_CurrentComponent = CID_##name; \
     152             :     RegisterComponentType_##name(*this);
     153             : 
     154             : #include "simulation2/TypeList.h"
     155             : 
     156         137 :     m_CurrentComponent = CID__Invalid;
     157             : 
     158             : #undef MESSAGE
     159             : #undef INTERFACE
     160             : #undef COMPONENT
     161         137 : }
     162             : 
     163             : 
     164        1257 : bool CComponentManager::LoadScript(const VfsPath& filename, bool hotload)
     165             : {
     166        1257 :     m_CurrentlyHotloading = hotload;
     167        1257 :     CVFSFile file;
     168        1257 :     PSRETURN loadOk = file.Load(g_VFS, filename);
     169        1257 :     if (loadOk != PSRETURN_OK) // VFS will log the failed file and the reason
     170             :         return false;
     171        1257 :     std::string content = file.DecodeUTF8(); // assume it's UTF-8
     172        1257 :     bool ok = m_ScriptInterface.LoadScript(filename, content);
     173             : 
     174        1257 :     m_CurrentlyHotloading = false;
     175        1257 :     return ok;
     176        1257 : }
     177             : 
     178         403 : void CComponentManager::Script_RegisterComponentType_Common(int iid, const std::string& cname, JS::HandleValue ctor, bool reRegister, bool systemComponent)
     179             : {
     180         403 :     Script::Request rq(m_ScriptInterface);
     181             : 
     182             :     // Find the C++ component that wraps the interface
     183         403 :     int cidWrapper = GetScriptWrapper(iid);
     184         403 :     if (cidWrapper == CID__Invalid)
     185           1 :         throw std::invalid_argument{"Invalid interface id"};
     186             : 
     187         402 :     const ComponentType& ctWrapper = m_ComponentTypesById[cidWrapper];
     188             : 
     189         402 :     bool mustReloadComponents = false; // for hotloading
     190             : 
     191         804 :     ComponentTypeId cid = LookupCID(cname);
     192         402 :     if (cid == CID__Invalid)
     193             :     {
     194         395 :         if (reRegister)
     195             :         {
     196           0 :             throw std::logic_error{fmt::format(
     197           0 :                 "ReRegistering component type that was not registered before '{}'", cname.c_str())};
     198             :         }
     199             :         // Allocate a new cid number
     200         395 :         cid = m_NextScriptComponentTypeId++;
     201         395 :         m_ComponentTypeIdsByName[cname] = cid;
     202         395 :         if (systemComponent)
     203          52 :             MarkScriptedComponentForSystemEntity(cid);
     204             :     }
     205             :     else
     206             :     {
     207             :         // Component type is already loaded, so do hotloading:
     208             : 
     209           7 :         if (!m_CurrentlyHotloading && !reRegister)
     210             :         {
     211           0 :             throw std::logic_error{fmt::format(
     212           0 :                 "Registering component type with already-registered name '{}'", cname.c_str())};
     213             :         }
     214             : 
     215           7 :         const ComponentType& ctPrevious = m_ComponentTypesById[cid];
     216             : 
     217             :         // We can only replace scripted component types, not native ones
     218           7 :         if (ctPrevious.type != CT_Script)
     219             :         {
     220           0 :             throw std::logic_error{fmt::format(
     221           0 :                 "Loading script component type with same name '{}' as native component", cname)};
     222             :         }
     223             : 
     224             :         // We don't support changing the IID of a component type (it would require fiddling
     225             :         // around with m_ComponentsByInterface and being careful to guarantee uniqueness per entity)
     226           7 :         if (ctPrevious.iid != iid)
     227             :         {
     228             :             // ...though it only matters if any components exist with this type
     229           0 :             if (!m_ComponentsByTypeId[cid].empty())
     230             :             {
     231           0 :                 throw std::logic_error{
     232           0 :                     "Hotloading script component type mustn't change interface ID"};
     233             :             }
     234             :         }
     235             : 
     236             :         // Remove the old component type's message subscriptions
     237           7 :         std::map<MessageTypeId, std::vector<ComponentTypeId> >::iterator it;
     238         161 :         for (it = m_LocalMessageSubscriptions.begin(); it != m_LocalMessageSubscriptions.end(); ++it)
     239             :         {
     240         154 :             std::vector<ComponentTypeId>& types = it->second;
     241         154 :             std::vector<ComponentTypeId>::iterator ctit = find(types.begin(), types.end(), cid);
     242         154 :             if (ctit != types.end())
     243           0 :                 types.erase(ctit);
     244             :         }
     245          70 :         for (it = m_GlobalMessageSubscriptions.begin(); it != m_GlobalMessageSubscriptions.end(); ++it)
     246             :         {
     247          63 :             std::vector<ComponentTypeId>& types = it->second;
     248          63 :             std::vector<ComponentTypeId>::iterator ctit = find(types.begin(), types.end(), cid);
     249          63 :             if (ctit != types.end())
     250           0 :                 types.erase(ctit);
     251             :         }
     252             : 
     253             :         mustReloadComponents = true;
     254             :     }
     255             : 
     256         402 :     JS::RootedValue protoVal(rq.cx);
     257         402 :     if (!Script::GetProperty(rq, ctor, "prototype", &protoVal))
     258           0 :         throw std::runtime_error("Failed to get property 'prototype'");
     259         402 :     if (!protoVal.isObject())
     260           0 :         throw std::invalid_argument{"Component has no constructor"};
     261             : 
     262         402 :     std::string schema = "<empty/>";
     263             : 
     264         402 :     if (Script::HasProperty(rq, protoVal, "Schema"))
     265         344 :         Script::GetProperty(rq, protoVal, "Schema", schema);
     266             : 
     267             :     // Construct a new ComponentType, using the wrapper's alloc functions
     268         402 :     ComponentType ct{
     269             :         CT_Script,
     270             :         iid,
     271         402 :         ctWrapper.alloc,
     272         402 :         ctWrapper.dealloc,
     273             :         cname,
     274             :         schema,
     275             :         std::make_unique<JS::PersistentRootedValue>(rq.cx, ctor)
     276        1206 :     };
     277         402 :     m_ComponentTypesById[cid] = std::move(ct);
     278             : 
     279         402 :     m_CurrentComponent = cid; // needed by Subscribe
     280             : 
     281             :     // Only now that we have constructed the CT_Script for this CT_ScriptWrapper, we can subscribe the CT_Script
     282         402 :     ctWrapper.classInit(*this);
     283             : 
     284             :     // Find all the ctor prototype's On* methods, and subscribe to the appropriate messages:
     285         402 :     std::vector<std::string> methods;
     286             : 
     287         402 :     if (!Script::EnumeratePropertyNames(rq, protoVal, false, methods))
     288             :     {
     289           0 :         throw std::runtime_error{"Failed to enumerate component properties."};
     290             :         return;
     291             :     }
     292             : 
     293       12004 :     for (const std::string& method : methods)
     294             :     {
     295       11602 :         if (std::string_view{method}.substr(0, 2) != "On")
     296       10821 :             continue;
     297             : 
     298         781 :         std::string_view name{std::string_view{method}.substr(2)}; // strip the "On" prefix
     299             : 
     300             :         // Handle "OnGlobalFoo" functions specially
     301         781 :         bool isGlobal = false;
     302        1377 :         if (std::string_view{name}.substr(0, 6) == "Global")
     303             :         {
     304         185 :             isGlobal = true;
     305         185 :             name.remove_prefix(6);
     306             :         }
     307             : 
     308        1562 :         auto mit = m_MessageTypeIdsByName.find(std::string{name});
     309         781 :         if (mit == m_MessageTypeIdsByName.end())
     310             :         {
     311           0 :             throw std::invalid_argument{fmt::format(
     312             :                 "Registered component has unrecognized '{}' message handler method",
     313           0 :                 method.c_str())};
     314             :         }
     315             : 
     316             :         // If we have already subscribed in classInit, do not subscribe again
     317         781 :         if (isGlobal)
     318             :         {
     319         185 :             if (!IsGloballySubscribed(mit->second))
     320         185 :                 SubscribeGloballyToMessageType(mit->second);
     321             :         }
     322             :         else
     323             :         {
     324         596 :             if (!IsLocallySubscribed(mit->second))
     325         596 :                 SubscribeToMessageType(mit->second);
     326             :         }
     327             :     }
     328             : 
     329         402 :     m_CurrentComponent = CID__Invalid;
     330             : 
     331         402 :     if (mustReloadComponents)
     332             :     {
     333             :         // For every script component with this cid, we need to switch its
     334             :         // prototype from the old constructor's prototype property to the new one's
     335           7 :         const std::map<entity_id_t, IComponent*>& comps = m_ComponentsByTypeId[cid];
     336           7 :         std::map<entity_id_t, IComponent*>::const_iterator eit = comps.begin();
     337          12 :         for (; eit != comps.end(); ++eit)
     338             :         {
     339           5 :             JS::RootedValue instance(rq.cx, eit->second->GetJSInstance());
     340           5 :             if (!instance.isNull())
     341           5 :                 m_ScriptInterface.SetPrototype(instance, protoVal);
     342           5 :         }
     343             :     }
     344         715 : }
     345             : 
     346         350 : void CComponentManager::Script_RegisterComponentType(int iid, const std::string& cname, JS::HandleValue ctor)
     347             : {
     348         350 :     Script_RegisterComponentType_Common(iid, cname, ctor, false, false);
     349         349 :     m_ScriptInterface.SetGlobal(cname.c_str(), ctor, m_CurrentlyHotloading);
     350         349 : }
     351             : 
     352          52 : void CComponentManager::Script_RegisterSystemComponentType(int iid, const std::string& cname, JS::HandleValue ctor)
     353             : {
     354          52 :     Script_RegisterComponentType_Common(iid, cname, ctor, false, true);
     355          52 :     m_ScriptInterface.SetGlobal(cname.c_str(), ctor, m_CurrentlyHotloading);
     356          52 : }
     357             : 
     358           1 : void CComponentManager::Script_ReRegisterComponentType(int iid, const std::string& cname, JS::HandleValue ctor)
     359             : {
     360           1 :     Script_RegisterComponentType_Common(iid, cname, ctor, true, false);
     361           1 : }
     362             : 
     363         262 : void CComponentManager::Script_RegisterInterface(const std::string& name)
     364             : {
     365         262 :     std::map<std::string, InterfaceId>::iterator it = m_InterfaceIdsByName.find(name);
     366         262 :     if (it != m_InterfaceIdsByName.end())
     367             :     {
     368             :         // Redefinitions are fine (and just get ignored) when hotloading; otherwise
     369             :         // they're probably unintentional and should be reported
     370           3 :         if (!m_CurrentlyHotloading)
     371             :         {
     372           0 :             throw std::logic_error{fmt::format(
     373           0 :                 "Registering interface with already-registered name '{}'", name.c_str())};
     374             :         }
     375         262 :         return;
     376             :     }
     377             : 
     378             :     // IIDs start at 1, so size+1 is the next unused one
     379         259 :     size_t id = m_InterfaceIdsByName.size() + 1;
     380         259 :     m_InterfaceIdsByName[name] = (InterfaceId)id;
     381         259 :     m_ComponentsByInterface.resize(id+1); // add one so we can index by InterfaceId
     382         518 :     m_ScriptInterface.SetGlobal(("IID_" + name).c_str(), (int)id);
     383             : }
     384             : 
     385         192 : void CComponentManager::Script_RegisterMessageType(const std::string& name)
     386             : {
     387         192 :     std::map<std::string, MessageTypeId>::iterator it = m_MessageTypeIdsByName.find(name);
     388         192 :     if (it != m_MessageTypeIdsByName.end())
     389             :     {
     390             :         // Redefinitions are fine (and just get ignored) when hotloading; otherwise
     391             :         // they're probably unintentional and should be reported
     392           0 :         if (!m_CurrentlyHotloading)
     393             :         {
     394           0 :             throw std::logic_error{fmt::format(
     395           0 :                 "Registering message type with already-registered name '{}'", name.c_str())};
     396             :         }
     397         192 :         return;
     398             :     }
     399             : 
     400             :     // MTIDs start at 1, so size+1 is the next unused one
     401         192 :     size_t id = m_MessageTypeIdsByName.size() + 1;
     402         192 :     RegisterMessageType((MessageTypeId)id, name.c_str());
     403         384 :     m_ScriptInterface.SetGlobal(("MT_" + name).c_str(), (int)id);
     404             : }
     405             : 
     406         189 : void CComponentManager::Script_RegisterGlobal(const std::string& name, JS::HandleValue value)
     407             : {
     408         189 :     m_ScriptInterface.SetGlobal(name.c_str(), value, m_CurrentlyHotloading);
     409         189 : }
     410             : 
     411           0 : const CParamNode& CComponentManager::Script_GetTemplate(const std::string& templateName)
     412             : {
     413           0 :     static CParamNode nullNode(false);
     414             : 
     415           0 :     ICmpTemplateManager* cmpTemplateManager = static_cast<ICmpTemplateManager*> (QueryInterface(SYSTEM_ENTITY, IID_TemplateManager));
     416           0 :     if (!cmpTemplateManager)
     417             :     {
     418           0 :         LOGERROR("Template manager is not loaded");
     419           0 :         return nullNode;
     420             :     }
     421             : 
     422           0 :     const CParamNode* tmpl = cmpTemplateManager->GetTemplate(templateName);
     423           0 :     if (!tmpl)
     424             :         return nullNode;
     425             :     return *tmpl;
     426             : }
     427             : 
     428           3 : std::vector<int> CComponentManager::Script_GetEntitiesWithInterface(int iid)
     429             : {
     430           3 :     std::vector<int> ret;
     431           6 :     const InterfaceListUnordered& ents = GetEntitiesWithInterfaceUnordered(iid);
     432           3 :     for (InterfaceListUnordered::const_iterator it = ents.begin(); it != ents.end(); ++it)
     433           0 :         if (!ENTITY_IS_LOCAL(it->first))
     434           0 :             ret.push_back(it->first);
     435           3 :     std::sort(ret.begin(), ret.end());
     436           3 :     return ret;
     437           0 : }
     438             : 
     439           0 : std::vector<IComponent*> CComponentManager::Script_GetComponentsWithInterface(int iid)
     440             : {
     441           0 :     std::vector<IComponent*> ret;
     442           0 :     InterfaceList ents = GetEntitiesWithInterface(iid);
     443           0 :     for (InterfaceList::const_iterator it = ents.begin(); it != ents.end(); ++it)
     444           0 :         ret.push_back(it->second); // TODO: maybe we should exclude local entities
     445           0 :     return ret;
     446           0 : }
     447             : 
     448        2940 : CMessage* CComponentManager::ConstructMessage(int mtid, JS::HandleValue data)
     449             : {
     450        2940 :     if (mtid == MT__Invalid || mtid > (int)m_MessageTypeIdsByName.size()) // (IDs start at 1 so use '>' here)
     451           0 :         LOGERROR("PostMessage with invalid message type ID '{}'", mtid);
     452             : 
     453        2940 :     Script::Request rq(m_ScriptInterface);
     454        2940 :     if (mtid < MT__LastNative)
     455             :     {
     456         840 :         return CMessageFromJSVal(mtid, rq, data);
     457             :     }
     458             :     else
     459             :     {
     460        2100 :         return new CMessageScripted(rq, mtid, m_MessageTypeNamesById[mtid], data);
     461             :     }
     462        2940 : }
     463             : 
     464        2696 : void CComponentManager::Script_PostMessage(int ent, int mtid, JS::HandleValue data)
     465             : {
     466        2696 :     CMessage* msg = ConstructMessage(mtid, data);
     467        2696 :     if (!msg)
     468             :         return; // error
     469             : 
     470        2696 :     PostMessage(ent, *msg);
     471             : 
     472        2696 :     delete msg;
     473             : }
     474             : 
     475         244 : void CComponentManager::Script_BroadcastMessage(int mtid, JS::HandleValue data)
     476             : {
     477         244 :     CMessage* msg = ConstructMessage(mtid, data);
     478         244 :     if (!msg)
     479             :         return; // error
     480             : 
     481         244 :     BroadcastMessage(*msg);
     482             : 
     483         244 :     delete msg;
     484             : }
     485             : 
     486         197 : int CComponentManager::Script_AddEntity(const std::wstring& templateName)
     487             : {
     488             :     // TODO: should validate the string to make sure it doesn't contain scary characters
     489             :     // that will let it access non-component-template files
     490         394 :     return AddEntity(templateName, AllocateNewEntity());
     491             : }
     492             : 
     493          11 : int CComponentManager::Script_AddLocalEntity(const std::wstring& templateName)
     494             : {
     495             :     // TODO: should validate the string to make sure it doesn't contain scary characters
     496             :     // that will let it access non-component-template files
     497          22 :     return AddEntity(templateName, AllocateNewLocalEntity());
     498             : }
     499             : 
     500         311 : void CComponentManager::ResetState()
     501             : {
     502             :     // Delete all dynamic message subscriptions
     503         311 :     m_DynamicMessageSubscriptionsNonsync.clear();
     504         311 :     m_DynamicMessageSubscriptionsNonsyncByComponent.clear();
     505             : 
     506             :     // Remove all items we were tracing.
     507         311 :     m_TraceCache.clear();
     508             : 
     509             :     // Delete all IComponents in reverse order of creation.
     510         311 :     std::map<ComponentTypeId, std::map<entity_id_t, IComponent*> >::reverse_iterator iit = m_ComponentsByTypeId.rbegin();
     511         707 :     for (; iit != m_ComponentsByTypeId.rend(); ++iit)
     512             :     {
     513         396 :         std::map<entity_id_t, IComponent*>::iterator eit = iit->second.begin();
     514        5850 :         for (; eit != iit->second.end(); ++eit)
     515             :         {
     516        5454 :             eit->second->Deinit();
     517        5454 :             m_ComponentTypesById[iit->first].dealloc(eit->second);
     518             :         }
     519             :     }
     520             : 
     521         311 :     std::vector<std::unordered_map<entity_id_t, IComponent*> >::iterator ifcit = m_ComponentsByInterface.begin();
     522       16377 :     for (; ifcit != m_ComponentsByInterface.end(); ++ifcit)
     523       16066 :         ifcit->clear();
     524             : 
     525         311 :     m_ComponentsByTypeId.clear();
     526             : 
     527             :     // Delete all SEntityComponentCaches
     528         311 :     std::unordered_map<entity_id_t, SEntityComponentCache*>::iterator ccit = m_ComponentCaches.begin();
     529         608 :     for (; ccit != m_ComponentCaches.end(); ++ccit)
     530         297 :         free(ccit->second);
     531         311 :     m_ComponentCaches.clear();
     532         311 :     m_SystemEntity = CEntityHandle();
     533             : 
     534         311 :     m_DestructionQueue.clear();
     535             : 
     536             :     // Reset IDs
     537         311 :     m_NextEntityId = SYSTEM_ENTITY + 1;
     538         311 :     m_NextLocalEntityId = FIRST_LOCAL_ENTITY;
     539         311 : }
     540             : 
     541           5 : void CComponentManager::SetRNGSeed(std::uint32_t seed)
     542             : {
     543           5 :     m_RNG.seed(seed);
     544           5 : }
     545             : 
     546        4521 : void CComponentManager::RegisterComponentType(InterfaceId iid, ComponentTypeId cid, AllocFunc alloc, DeallocFunc dealloc,
     547             :         const char* name, const std::string& schema)
     548             : {
     549        9042 :     ComponentType c{ CT_Native, iid, alloc, dealloc, name, schema, std::unique_ptr<JS::PersistentRootedValue>() };
     550        4521 :     m_ComponentTypesById.insert(std::make_pair(cid, std::move(c)));
     551        4521 :     m_ComponentTypeIdsByName[name] = cid;
     552        4521 : }
     553             : 
     554        2877 : void CComponentManager::RegisterComponentTypeScriptWrapper(InterfaceId iid, ComponentTypeId cid,
     555             :     AllocFunc alloc, DeallocFunc dealloc, const char* name, const std::string& schema,
     556             :     ClassInitFunc classInit)
     557             : {
     558        2877 :     ComponentType c{ CT_ScriptWrapper, iid, alloc, dealloc, name, schema,
     559        5754 :         std::unique_ptr<JS::PersistentRootedValue>(), classInit };
     560        2877 :     m_ComponentTypesById.insert(std::make_pair(cid, std::move(c)));
     561        2877 :     m_ComponentTypeIdsByName[name] = cid;
     562             :     // TODO: merge with RegisterComponentType
     563        2877 : }
     564             : 
     565          52 : void CComponentManager::MarkScriptedComponentForSystemEntity(CComponentManager::ComponentTypeId cid)
     566             : {
     567          52 :     m_ScriptedSystemComponents.push_back(cid);
     568          52 : }
     569             : 
     570        4713 : void CComponentManager::RegisterMessageType(MessageTypeId mtid, const char* name)
     571             : {
     572        4713 :     m_MessageTypeIdsByName[name] = mtid;
     573        4713 :     m_MessageTypeNamesById[mtid] = name;
     574        4713 : }
     575             : 
     576       11153 : void CComponentManager::SubscribeToMessageType(MessageTypeId mtid)
     577             : {
     578             :     // TODO: verify mtid
     579       11153 :     ENSURE(m_CurrentComponent != CID__Invalid);
     580       11153 :     std::vector<ComponentTypeId>& types = m_LocalMessageSubscriptions[mtid];
     581       11153 :     types.push_back(m_CurrentComponent);
     582       11153 :     std::sort(types.begin(), types.end()); // TODO: just sort once at the end of LoadComponents
     583       11153 : }
     584             : 
     585        1966 : void CComponentManager::SubscribeGloballyToMessageType(MessageTypeId mtid)
     586             : {
     587             :     // TODO: verify mtid
     588        1966 :     ENSURE(m_CurrentComponent != CID__Invalid);
     589        1966 :     std::vector<ComponentTypeId>& types = m_GlobalMessageSubscriptions[mtid];
     590        1966 :     types.push_back(m_CurrentComponent);
     591        1966 :     std::sort(types.begin(), types.end()); // TODO: just sort once at the end of LoadComponents
     592        1966 : }
     593             : 
     594         596 : bool CComponentManager::IsLocallySubscribed(MessageTypeId mtid)
     595             : {
     596         596 :     ENSURE(m_CurrentComponent != CID__Invalid);
     597         596 :     return PS::contains(m_LocalMessageSubscriptions[mtid], m_CurrentComponent);
     598             : }
     599             : 
     600         185 : bool CComponentManager::IsGloballySubscribed(MessageTypeId mtid)
     601             : {
     602         185 :     ENSURE(m_CurrentComponent != CID__Invalid);
     603         185 :     return PS::contains(m_GlobalMessageSubscriptions[mtid], m_CurrentComponent);
     604             : }
     605             : 
     606          34 : void CComponentManager::FlattenDynamicSubscriptions()
     607             : {
     608          34 :     std::map<MessageTypeId, CDynamicSubscription>::iterator it;
     609          65 :     for (it = m_DynamicMessageSubscriptionsNonsync.begin();
     610          65 :          it != m_DynamicMessageSubscriptionsNonsync.end(); ++it)
     611             :     {
     612          31 :         it->second.Flatten();
     613             :     }
     614          34 : }
     615             : 
     616         179 : void CComponentManager::DynamicSubscriptionNonsync(MessageTypeId mtid, IComponent* component, bool enable)
     617             : {
     618         179 :     if (enable)
     619             :     {
     620         170 :         bool newlyInserted = m_DynamicMessageSubscriptionsNonsyncByComponent[component].insert(mtid).second;
     621         170 :         if (newlyInserted)
     622         170 :             m_DynamicMessageSubscriptionsNonsync[mtid].Add(component);
     623             :     }
     624             :     else
     625             :     {
     626           9 :         size_t numRemoved = m_DynamicMessageSubscriptionsNonsyncByComponent[component].erase(mtid);
     627           9 :         if (numRemoved)
     628           7 :             m_DynamicMessageSubscriptionsNonsync[mtid].Remove(component);
     629             :     }
     630         179 : }
     631             : 
     632         949 : void CComponentManager::RemoveComponentDynamicSubscriptions(IComponent* component)
     633             : {
     634         949 :     std::map<IComponent*, std::set<MessageTypeId> >::iterator it = m_DynamicMessageSubscriptionsNonsyncByComponent.find(component);
     635         949 :     if (it == m_DynamicMessageSubscriptionsNonsyncByComponent.end())
     636         949 :         return;
     637             : 
     638          31 :     std::set<MessageTypeId>::iterator mtit;
     639          59 :     for (mtit = it->second.begin(); mtit != it->second.end(); ++mtit)
     640             :     {
     641          28 :         m_DynamicMessageSubscriptionsNonsync[*mtit].Remove(component);
     642             : 
     643             :         // Need to flatten the subscription lists immediately to avoid dangling IComponent* references
     644          28 :         m_DynamicMessageSubscriptionsNonsync[*mtit].Flatten();
     645             :     }
     646             : 
     647          31 :     m_DynamicMessageSubscriptionsNonsyncByComponent.erase(it);
     648             : }
     649             : 
     650        6597 : CComponentManager::ComponentTypeId CComponentManager::LookupCID(const std::string& cname) const
     651             : {
     652        6597 :     std::map<std::string, ComponentTypeId>::const_iterator it = m_ComponentTypeIdsByName.find(cname);
     653        6597 :     if (it == m_ComponentTypeIdsByName.end())
     654             :         return CID__Invalid;
     655        6202 :     return it->second;
     656             : }
     657             : 
     658           8 : std::string CComponentManager::LookupComponentTypeName(ComponentTypeId cid) const
     659             : {
     660           8 :     std::map<ComponentTypeId, ComponentType>::const_iterator it = m_ComponentTypesById.find(cid);
     661           8 :     if (it == m_ComponentTypesById.end())
     662           0 :         return "";
     663           8 :     return it->second.name;
     664             : }
     665             : 
     666         403 : CComponentManager::ComponentTypeId CComponentManager::GetScriptWrapper(InterfaceId iid)
     667             : {
     668         403 :     if (iid >= IID__LastNative && iid <= (int)m_InterfaceIdsByName.size()) // use <= since IDs start at 1
     669             :         return CID_UnknownScript;
     670             : 
     671         141 :     std::map<ComponentTypeId, ComponentType>::const_iterator it = m_ComponentTypesById.begin();
     672        2393 :     for (; it != m_ComponentTypesById.end(); ++it)
     673        2392 :         if (it->second.iid == iid && it->second.type == CT_ScriptWrapper)
     674         140 :             return it->first;
     675             : 
     676           1 :     std::map<std::string, InterfaceId>::const_iterator iiit = m_InterfaceIdsByName.begin();
     677          50 :     for (; iiit != m_InterfaceIdsByName.end(); ++iiit)
     678          49 :         if (iiit->second == iid)
     679             :         {
     680           0 :             LOGERROR("No script wrapper found for interface id {} '{}'", iid, iiit->first);
     681           0 :             return CID__Invalid;
     682             :         }
     683             : 
     684           2 :     LOGERROR("No script wrapper found for interface id {}", iid);
     685           1 :     return CID__Invalid;
     686             : }
     687             : 
     688         210 : entity_id_t CComponentManager::AllocateNewEntity()
     689             : {
     690         210 :     entity_id_t id = m_NextEntityId++;
     691             :     // TODO: check for overflow
     692         197 :     return id;
     693             : }
     694             : 
     695          15 : entity_id_t CComponentManager::AllocateNewLocalEntity()
     696             : {
     697          15 :     entity_id_t id = m_NextLocalEntityId++;
     698             :     // TODO: check for overflow
     699          11 :     return id;
     700             : }
     701             : 
     702           2 : entity_id_t CComponentManager::AllocateNewEntity(entity_id_t preferredId)
     703             : {
     704             :     // TODO: ensure this ID hasn't been allocated before
     705             :     // (this might occur with broken map files)
     706             :     // Trying to actually add two entities with the same id will fail in AddEntitiy
     707           2 :     entity_id_t id = preferredId;
     708             : 
     709             :     // Ensure this ID won't be allocated again
     710           2 :     if (id >= m_NextEntityId)
     711           2 :         m_NextEntityId = id+1;
     712             :     // TODO: check for overflow
     713             : 
     714           2 :     return id;
     715             : }
     716             : 
     717        6391 : bool CComponentManager::AddComponent(CEntityHandle ent, ComponentTypeId cid, const CParamNode& paramNode)
     718             : {
     719        6391 :     IComponent* component = ConstructComponent(ent, cid);
     720        6391 :     if (!component)
     721             :         return false;
     722             : 
     723        6389 :     component->Init(paramNode);
     724        6389 :     return true;
     725             : }
     726             : 
     727           7 : void CComponentManager::AddSystemComponents(bool skipScriptedComponents, bool skipAI)
     728             : {
     729           7 :     CParamNode noParam;
     730           7 :     AddComponent(m_SystemEntity, CID_TemplateManager, noParam);
     731           7 :     AddComponent(m_SystemEntity, CID_CinemaManager, noParam);
     732           7 :     AddComponent(m_SystemEntity, CID_CommandQueue, noParam);
     733           7 :     AddComponent(m_SystemEntity, CID_ObstructionManager, noParam);
     734           7 :     AddComponent(m_SystemEntity, CID_ParticleManager, noParam);
     735           7 :     AddComponent(m_SystemEntity, CID_Pathfinder, noParam);
     736           7 :     AddComponent(m_SystemEntity, CID_ProjectileManager, noParam);
     737           7 :     AddComponent(m_SystemEntity, CID_RangeManager, noParam);
     738           7 :     AddComponent(m_SystemEntity, CID_SoundManager, noParam);
     739           7 :     AddComponent(m_SystemEntity, CID_Terrain, noParam);
     740           7 :     AddComponent(m_SystemEntity, CID_TerritoryManager, noParam);
     741           7 :     AddComponent(m_SystemEntity, CID_UnitMotionManager, noParam);
     742           7 :     AddComponent(m_SystemEntity, CID_UnitRenderer, noParam);
     743           7 :     AddComponent(m_SystemEntity, CID_WaterManager, noParam);
     744             : 
     745             :     // Add scripted system components:
     746           7 :     if (!skipScriptedComponents)
     747             :     {
     748          56 :         for (uint32_t i = 0; i < m_ScriptedSystemComponents.size(); ++i)
     749          52 :             AddComponent(m_SystemEntity, m_ScriptedSystemComponents[i], noParam);
     750           4 :         if (!skipAI)
     751           4 :             AddComponent(m_SystemEntity, CID_AIManager, noParam);
     752             :     }
     753           7 : }
     754             : 
     755        6405 : IComponent* CComponentManager::ConstructComponent(CEntityHandle ent, ComponentTypeId cid)
     756             : {
     757        6405 :     Script::Request rq(m_ScriptInterface);
     758             : 
     759       12810 :     std::map<ComponentTypeId, ComponentType>::const_iterator it = m_ComponentTypesById.find(cid);
     760        6405 :     if (it == m_ComponentTypesById.end())
     761             :     {
     762           1 :         LOGERROR("Invalid component id {}", cid);
     763           1 :         return NULL;
     764             :     }
     765             : 
     766        6404 :     const ComponentType& ct = it->second;
     767             : 
     768        6404 :     ENSURE((size_t)ct.iid < m_ComponentsByInterface.size());
     769             : 
     770        6404 :     std::unordered_map<entity_id_t, IComponent*>& emap1 = m_ComponentsByInterface[ct.iid];
     771        6404 :     if (emap1.find(ent.GetId()) != emap1.end())
     772             :     {
     773           1 :         LOGERROR("Multiple components for interface {}", ct.iid);
     774           1 :         return NULL;
     775             :     }
     776             : 
     777        6403 :     std::map<entity_id_t, IComponent*>& emap2 = m_ComponentsByTypeId[cid];
     778             : 
     779             :     // If this is a scripted component, construct the appropriate JS object first
     780        6403 :     JS::RootedValue obj(rq.cx);
     781        6403 :     if (ct.type == CT_Script)
     782             :     {
     783        3962 :         m_ScriptInterface.CallConstructor(*ct.ctor, JS::HandleValueArray::empty(), &obj);
     784        3962 :         if (obj.isNull())
     785             :         {
     786           0 :             LOGERROR("Script component constructor failed");
     787           0 :             return NULL;
     788             :         }
     789             :     }
     790             : 
     791             :     // Construct the new component
     792             :     // NB: The unit motion manager relies on components not moving in memory once constructed.
     793        6403 :     IComponent* component = ct.alloc(m_ScriptInterface, obj);
     794        6403 :     ENSURE(component);
     795             : 
     796        6403 :     component->SetEntityHandle(ent);
     797        6403 :     component->SetSimContext(m_SimContext);
     798             : 
     799             :     // Store a reference to the new component
     800        6403 :     emap1.insert(std::make_pair(ent.GetId(), component));
     801        6403 :     emap2.insert(std::make_pair(ent.GetId(), component));
     802             :     // TODO: We need to more careful about this - if an entity is constructed by a component
     803             :     // while we're iterating over all components, this will invalidate the iterators and everything
     804             :     // will break.
     805             :     // We probably need some kind of delayed addition, so they get pushed onto a queue and then
     806             :     // inserted into the world later on. (Be careful about immediation deletion in that case, too.)
     807             : 
     808        6403 :     SEntityComponentCache* cache = ent.GetComponentCache();
     809        6403 :     ENSURE(cache != NULL && ct.iid < (int)cache->numInterfaces && cache->interfaces[ct.iid] == NULL);
     810        6403 :     cache->interfaces[ct.iid] = component;
     811             : 
     812        6403 :     return component;
     813        6405 : }
     814             : 
     815          40 : void CComponentManager::AddMockComponent(CEntityHandle ent, InterfaceId iid, IComponent& component)
     816             : {
     817             :     // Just add it into the by-interface map, not the by-component-type map,
     818             :     // so it won't be considered for messages or deletion etc
     819             : 
     820          40 :     std::unordered_map<entity_id_t, IComponent*>& emap1 = m_ComponentsByInterface.at(iid);
     821          40 :     if (emap1.find(ent.GetId()) != emap1.end())
     822           0 :         debug_warn(L"Multiple components for interface");
     823          40 :     emap1.insert(std::make_pair(ent.GetId(), &component));
     824             : 
     825          40 :     SEntityComponentCache* cache = ent.GetComponentCache();
     826          40 :     ENSURE(cache != NULL && iid < (int)cache->numInterfaces && cache->interfaces[iid] == NULL);
     827          40 :     cache->interfaces[iid] = &component;
     828          40 : }
     829             : 
     830           6 : void CComponentManager::Trace(JSTracer* trc, void* data)
     831             : {
     832           6 :     CComponentManager& cmpMgr = *(static_cast<CComponentManager*>(data));
     833          30 :     for (auto& traceByEnt : cmpMgr.m_TraceCache)
     834         300 :         for (JS::Heap<JS::Value>* ptr : traceByEnt.second)
     835         552 :             JS::TraceEdge(trc, ptr, "ComponentManager::Trace");
     836           6 : }
     837             : 
     838        5136 : void CComponentManager::RegisterTrace(entity_id_t ent, const JS::Heap<JS::Value>& instance)
     839             : {
     840        5136 :     m_TraceCache.try_emplace(ent).first->second.push_back(const_cast<JS::Heap<JS::Value>*>(std::addressof(instance)));
     841        5136 : }
     842             : 
     843         331 : CEntityHandle CComponentManager::AllocateEntityHandle(entity_id_t ent)
     844             : {
     845           0 :     ENSURE(!EntityExists(ent));
     846             : 
     847             :     // Interface IDs start at 1, and SEntityComponentCache is defined with a 1-sized array,
     848             :     // so we need space for an extra m_InterfaceIdsByName.size() items
     849         331 :     SEntityComponentCache* cache = (SEntityComponentCache*)calloc(1,
     850         331 :         sizeof(SEntityComponentCache) + sizeof(IComponent*) * m_InterfaceIdsByName.size());
     851         331 :     ENSURE(cache != NULL);
     852         331 :     cache->numInterfaces = m_InterfaceIdsByName.size() + 1;
     853             : 
     854         331 :     m_ComponentCaches[ent] = cache;
     855             : 
     856         331 :     return CEntityHandle(ent, cache);
     857             : }
     858             : 
     859      117348 : CEntityHandle CComponentManager::LookupEntityHandle(entity_id_t ent, bool allowCreate)
     860             : {
     861      117348 :     std::unordered_map<entity_id_t, SEntityComponentCache*>::iterator it;
     862      117348 :     it = m_ComponentCaches.find(ent);
     863      117348 :     if (it == m_ComponentCaches.end())
     864             :     {
     865          93 :         if (allowCreate)
     866          36 :             return AllocateEntityHandle(ent);
     867             :         else
     868          57 :             return CEntityHandle(ent, NULL);
     869             :     }
     870             :     else
     871      117255 :         return CEntityHandle(ent, it->second);
     872             : }
     873             : 
     874          38 : void CComponentManager::InitSystemEntity()
     875             : {
     876          38 :     ENSURE(m_SystemEntity.GetId() == INVALID_ENTITY);
     877          38 :     m_SystemEntity = AllocateEntityHandle(SYSTEM_ENTITY);
     878          38 :     m_SimContext.SetSystemEntity(m_SystemEntity);
     879          38 : }
     880             : 
     881         214 : entity_id_t CComponentManager::AddEntity(const std::wstring& templateName, entity_id_t ent)
     882             : {
     883         214 :     ICmpTemplateManager *cmpTemplateManager = static_cast<ICmpTemplateManager*> (QueryInterface(SYSTEM_ENTITY, IID_TemplateManager));
     884         214 :     if (!cmpTemplateManager)
     885             :     {
     886           0 :         debug_warn(L"No ICmpTemplateManager loaded");
     887           0 :         return INVALID_ENTITY;
     888             :     }
     889             : 
     890         214 :     const CParamNode* tmpl = cmpTemplateManager->LoadTemplate(ent, utf8_from_wstring(templateName));
     891         214 :     if (!tmpl)
     892             :         return INVALID_ENTITY; // LoadTemplate will have reported the error
     893             : 
     894             :     // This also ensures that ent does not exist
     895         212 :     CEntityHandle handle = AllocateEntityHandle(ent);
     896             : 
     897             :     // Construct a component for each child of the root element
     898         212 :     const CParamNode::ChildrenMap& tmplChilds = tmpl->GetChildren();
     899        6546 :     for (CParamNode::ChildrenMap::const_iterator it = tmplChilds.begin(); it != tmplChilds.end(); ++it)
     900             :     {
     901             :         // Ignore attributes on the root element
     902        6334 :         if (it->first.length() && it->first[0] == '@')
     903         187 :             continue;
     904             : 
     905        6147 :         CComponentManager::ComponentTypeId cid = LookupCID(it->first);
     906        6147 :         if (cid == CID__Invalid)
     907             :         {
     908           0 :             LOGERROR("Unrecognized component type name '{}' in entity template '{}'", it->first,
     909             :                 utf8_from_wstring(templateName));
     910           0 :             return INVALID_ENTITY;
     911             :         }
     912             : 
     913        6147 :         if (!AddComponent(handle, cid, it->second))
     914             :         {
     915           0 :             LOGERROR("Failed to construct component type name '{}' in entity template '{}'",
     916             :                 it->first, utf8_from_wstring(templateName));
     917           0 :             return INVALID_ENTITY;
     918             :         }
     919             :         // TODO: maybe we should delete already-constructed components if one of them fails?
     920             :     }
     921             : 
     922         426 :     CMessageCreate msg(ent);
     923         212 :     PostMessage(ent, msg);
     924             : 
     925         212 :     return ent;
     926             : }
     927             : 
     928         413 : bool CComponentManager::EntityExists(entity_id_t ent) const
     929             : {
     930         331 :     return m_ComponentCaches.find(ent) != m_ComponentCaches.end();
     931             : }
     932             : 
     933             : 
     934          82 : void CComponentManager::DestroyComponentsSoon(entity_id_t ent)
     935             : {
     936          82 :     m_DestructionQueue.push_back(ent);
     937          82 : }
     938             : 
     939         374 : void CComponentManager::FlushDestroyedComponents()
     940             : {
     941         374 :     PROFILE2("Flush Destroyed Components");
     942         407 :     while (!m_DestructionQueue.empty())
     943             :     {
     944             :         // Make a copy of the destruction queue, so that the iterators won't be invalidated if the
     945             :         // CMessageDestroy handlers try to destroy more entities themselves
     946          33 :         std::vector<entity_id_t> queue;
     947          33 :         queue.swap(m_DestructionQueue);
     948             : 
     949         115 :         for (std::vector<entity_id_t>::iterator it = queue.begin(); it != queue.end(); ++it)
     950             :         {
     951          82 :             entity_id_t ent = *it;
     952             : 
     953             :             // Do nothing if invalid, destroyed, etc.
     954          82 :             if (!EntityExists(ent))
     955          48 :                 continue;
     956             : 
     957          34 :             CEntityHandle handle = LookupEntityHandle(ent);
     958             : 
     959          34 :             CMessageDestroy msg(ent);
     960          34 :             PostMessage(ent, msg);
     961             : 
     962             :             // Flatten all the dynamic subscriptions to ensure there are no dangling
     963             :             // references in the 'removed' lists to components we're going to delete
     964             :             // Some components may have dynamically unsubscribed following the Destroy message
     965          34 :             FlattenDynamicSubscriptions();
     966             : 
     967             :             // Destroy the components, and remove from m_ComponentsByTypeId:
     968          34 :             std::map<ComponentTypeId, std::map<entity_id_t, IComponent*> >::iterator iit = m_ComponentsByTypeId.begin();
     969        2349 :             for (; iit != m_ComponentsByTypeId.end(); ++iit)
     970             :             {
     971        2315 :                 std::map<entity_id_t, IComponent*>::iterator eit = iit->second.find(ent);
     972        2315 :                 if (eit != iit->second.end())
     973             :                 {
     974         949 :                     eit->second->Deinit();
     975         949 :                     RemoveComponentDynamicSubscriptions(eit->second);
     976         949 :                     m_ComponentTypesById[iit->first].dealloc(eit->second);
     977         949 :                     iit->second.erase(ent);
     978         949 :                     handle.GetComponentCache()->interfaces[m_ComponentTypesById[iit->first].iid] = NULL;
     979             :                 }
     980             :             }
     981             : 
     982          34 :             free(handle.GetComponentCache());
     983          34 :             m_ComponentCaches.erase(ent);
     984             : 
     985          34 :             auto hit = m_TraceCache.find(ent);
     986          34 :             if (hit != m_TraceCache.end())
     987          33 :                 m_TraceCache.erase(hit);
     988             : 
     989             :             // Remove from m_ComponentsByInterface
     990          34 :             std::vector<std::unordered_map<entity_id_t, IComponent*> >::iterator ifcit = m_ComponentsByInterface.begin();
     991        3654 :             for (; ifcit != m_ComponentsByInterface.end(); ++ifcit)
     992             :             {
     993        3620 :                 ifcit->erase(ent);
     994             :             }
     995          34 :         }
     996          33 :     }
     997         374 : }
     998             : 
     999      214002 : IComponent* CComponentManager::QueryInterface(entity_id_t ent, InterfaceId iid) const
    1000             : {
    1001      214002 :     if ((size_t)iid >= m_ComponentsByInterface.size())
    1002             :     {
    1003             :         // Invalid iid
    1004             :         return NULL;
    1005             :     }
    1006             : 
    1007      214002 :     std::unordered_map<entity_id_t, IComponent*>::const_iterator eit = m_ComponentsByInterface[iid].find(ent);
    1008      214002 :     if (eit == m_ComponentsByInterface[iid].end())
    1009             :     {
    1010             :         // This entity doesn't implement this interface
    1011             :         return NULL;
    1012             :     }
    1013             : 
    1014      186650 :     return eit->second;
    1015             : }
    1016             : 
    1017          11 : CComponentManager::InterfaceList CComponentManager::GetEntitiesWithInterface(InterfaceId iid) const
    1018             : {
    1019          11 :     std::vector<std::pair<entity_id_t, IComponent*> > ret;
    1020             : 
    1021          11 :     if ((size_t)iid >= m_ComponentsByInterface.size())
    1022             :     {
    1023             :         // Invalid iid
    1024             :         return ret;
    1025             :     }
    1026             : 
    1027          11 :     ret.reserve(m_ComponentsByInterface[iid].size());
    1028             : 
    1029          11 :     std::unordered_map<entity_id_t, IComponent*>::const_iterator it = m_ComponentsByInterface[iid].begin();
    1030         193 :     for (; it != m_ComponentsByInterface[iid].end(); ++it)
    1031         182 :         ret.push_back(*it);
    1032             : 
    1033          11 :     std::sort(ret.begin(), ret.end()); // lexicographic pair comparison means this'll sort by entity ID
    1034             : 
    1035             :     return ret;
    1036           0 : }
    1037             : 
    1038             : static CComponentManager::InterfaceListUnordered g_EmptyEntityMap;
    1039           4 : const CComponentManager::InterfaceListUnordered& CComponentManager::GetEntitiesWithInterfaceUnordered(InterfaceId iid) const
    1040             : {
    1041           4 :     if ((size_t)iid >= m_ComponentsByInterface.size())
    1042             :     {
    1043             :         // Invalid iid
    1044             :         return g_EmptyEntityMap;
    1045             :     }
    1046             : 
    1047           4 :     return m_ComponentsByInterface[iid];
    1048             : }
    1049             : 
    1050       25171 : void CComponentManager::PostMessage(entity_id_t ent, const CMessage& msg)
    1051             : {
    1052             :     // Send the message to components of ent, that subscribed locally to this message
    1053       25171 :     std::map<MessageTypeId, std::vector<ComponentTypeId> >::const_iterator it;
    1054       50342 :     it = m_LocalMessageSubscriptions.find(msg.GetType());
    1055       25171 :     if (it != m_LocalMessageSubscriptions.end())
    1056             :     {
    1057       25149 :         std::vector<ComponentTypeId>::const_iterator ctit = it->second.begin();
    1058      115054 :         for (; ctit != it->second.end(); ++ctit)
    1059             :         {
    1060             :             // Find the component instances of this type (if any)
    1061      179810 :             std::map<ComponentTypeId, std::map<entity_id_t, IComponent*> >::const_iterator emap = m_ComponentsByTypeId.find(*ctit);
    1062       89905 :             if (emap == m_ComponentsByTypeId.end())
    1063       33463 :                 continue;
    1064             : 
    1065             :             // Send the message to all of them
    1066       56442 :             std::map<entity_id_t, IComponent*>::const_iterator eit = emap->second.find(ent);
    1067       56442 :             if (eit != emap->second.end())
    1068       54410 :                 eit->second->HandleMessage(msg, false);
    1069             :         }
    1070             :     }
    1071             : 
    1072       25171 :     SendGlobalMessage(ent, msg);
    1073       25171 : }
    1074             : 
    1075        1172 : void CComponentManager::BroadcastMessage(const CMessage& msg)
    1076             : {
    1077             :     // Send the message to components of all entities that subscribed locally to this message
    1078        1172 :     std::map<MessageTypeId, std::vector<ComponentTypeId> >::const_iterator it;
    1079        2344 :     it = m_LocalMessageSubscriptions.find(msg.GetType());
    1080        1172 :     if (it != m_LocalMessageSubscriptions.end())
    1081             :     {
    1082        1157 :         std::vector<ComponentTypeId>::const_iterator ctit = it->second.begin();
    1083        9933 :         for (; ctit != it->second.end(); ++ctit)
    1084             :         {
    1085             :             // Find the component instances of this type (if any)
    1086       17552 :             std::map<ComponentTypeId, std::map<entity_id_t, IComponent*> >::const_iterator emap = m_ComponentsByTypeId.find(*ctit);
    1087        8776 :             if (emap == m_ComponentsByTypeId.end())
    1088        6143 :                 continue;
    1089             : 
    1090             :             // Send the message to all of them
    1091        2633 :             std::map<entity_id_t, IComponent*>::const_iterator eit = emap->second.begin();
    1092       13998 :             for (; eit != emap->second.end(); ++eit)
    1093       11365 :                 eit->second->HandleMessage(msg, false);
    1094             :         }
    1095             :     }
    1096             : 
    1097        1172 :     SendGlobalMessage(INVALID_ENTITY, msg);
    1098        1172 : }
    1099             : 
    1100       26343 : void CComponentManager::SendGlobalMessage(entity_id_t ent, const CMessage& msg)
    1101             : {
    1102             :     // (Common functionality for PostMessage and BroadcastMessage)
    1103             : 
    1104             :     // Send the message to components of all entities that subscribed globally to this message
    1105       26343 :     std::map<MessageTypeId, std::vector<ComponentTypeId> >::const_iterator it;
    1106       52686 :     it = m_GlobalMessageSubscriptions.find(msg.GetType());
    1107       26343 :     if (it != m_GlobalMessageSubscriptions.end())
    1108             :     {
    1109        9130 :         std::vector<ComponentTypeId>::const_iterator ctit = it->second.begin();
    1110       28765 :         for (; ctit != it->second.end(); ++ctit)
    1111             :         {
    1112             :             // Special case: Messages for local entities shouldn't be sent to script
    1113             :             // components that subscribed globally, so that we don't have to worry about
    1114             :             // them accidentally picking up non-network-synchronised data.
    1115       19635 :             if (ENTITY_IS_LOCAL(ent))
    1116             :             {
    1117         254 :                 std::map<ComponentTypeId, ComponentType>::const_iterator cit = m_ComponentTypesById.find(*ctit);
    1118         127 :                 if (cit != m_ComponentTypesById.end() && cit->second.type == CT_Script)
    1119          63 :                     continue;
    1120             :             }
    1121             : 
    1122             :             // Find the component instances of this type (if any)
    1123       39144 :             std::map<ComponentTypeId, std::map<entity_id_t, IComponent*> >::const_iterator emap = m_ComponentsByTypeId.find(*ctit);
    1124       19572 :             if (emap == m_ComponentsByTypeId.end())
    1125         381 :                 continue;
    1126             : 
    1127             :             // Send the message to all of them
    1128       19191 :             std::map<entity_id_t, IComponent*>::const_iterator eit = emap->second.begin();
    1129       40092 :             for (; eit != emap->second.end(); ++eit)
    1130       20901 :                 eit->second->HandleMessage(msg, true);
    1131             :         }
    1132             :     }
    1133             : 
    1134             :     // Send the message to component instances that dynamically subscribed to this message
    1135       26343 :     std::map<MessageTypeId, CDynamicSubscription>::iterator dit = m_DynamicMessageSubscriptionsNonsync.find(msg.GetType());
    1136       26343 :     if (dit != m_DynamicMessageSubscriptionsNonsync.end())
    1137             :     {
    1138           0 :         dit->second.Flatten();
    1139           0 :         const std::vector<IComponent*>& dynamic = dit->second.GetComponents();
    1140           0 :         for (size_t i = 0; i < dynamic.size(); i++)
    1141           0 :             dynamic[i]->HandleMessage(msg, false);
    1142             :     }
    1143       26343 : }
    1144             : 
    1145          15 : std::string CComponentManager::GenerateSchema() const
    1146             : {
    1147          15 :     std::string schema =
    1148             :         "<grammar xmlns='http://relaxng.org/ns/structure/1.0' xmlns:a='http://ns.wildfiregames.com/entity' datatypeLibrary='http://www.w3.org/2001/XMLSchema-datatypes'>"
    1149             :             "<define name='decimal'>"
    1150             :                 "<data type='decimal'/>"
    1151             :             "</define>"
    1152             :             "<define name='nonNegativeDecimal'>"
    1153             :                 "<data type='decimal'><param name='minInclusive'>0</param></data>"
    1154             :             "</define>"
    1155             :             "<define name='positiveDecimal'>"
    1156             :                 "<data type='decimal'><param name='minExclusive'>0</param></data>"
    1157             :             "</define>"
    1158             :             "<define name='anything'>"
    1159             :                 "<zeroOrMore>"
    1160             :                       "<choice>"
    1161             :                             "<attribute><anyName/></attribute>"
    1162             :                             "<text/>"
    1163             :                             "<element>"
    1164             :                                 "<anyName/>"
    1165             :                                 "<ref name='anything'/>"
    1166             :                             "</element>"
    1167             :                       "</choice>"
    1168             :                 "</zeroOrMore>"
    1169          15 :             "</define>";
    1170             : 
    1171          15 :     std::map<InterfaceId, std::vector<std::string> > interfaceComponentTypes;
    1172             : 
    1173          15 :     std::vector<std::string> componentTypes;
    1174             : 
    1175        1180 :     for (std::map<ComponentTypeId, ComponentType>::const_iterator it = m_ComponentTypesById.begin(); it != m_ComponentTypesById.end(); ++it)
    1176             :     {
    1177        1165 :         schema +=
    1178        2330 :             "<define name='component." + it->second.name + "'>"
    1179        3495 :                 "<element name='" + it->second.name + "'>"
    1180        4660 :                     "<interleave>" + it->second.schema + "</interleave>"
    1181             :                 "</element>"
    1182        1165 :             "</define>";
    1183             : 
    1184        1165 :         interfaceComponentTypes[it->second.iid].push_back(it->second.name);
    1185        1165 :         componentTypes.push_back(it->second.name);
    1186             :     }
    1187             : 
    1188             :     // Declare the implementation of each interface, for documentation
    1189        1007 :     for (std::map<std::string, InterfaceId>::const_iterator it = m_InterfaceIdsByName.begin(); it != m_InterfaceIdsByName.end(); ++it)
    1190             :     {
    1191        3968 :         schema += "<define name='interface." + it->first + "'><choice>";
    1192         992 :         std::vector<std::string>& cts = interfaceComponentTypes[it->second];
    1193        2157 :         for (size_t i = 0; i < cts.size(); ++i)
    1194        4660 :             schema += "<ref name='component." + cts[i] + "'/>";
    1195         992 :         schema += "</choice></define>";
    1196             :     }
    1197             : 
    1198             :     // List all the component types, in alphabetical order (to match the reordering performed by CParamNode).
    1199             :     // (We do it this way, rather than <interleave>ing all the interface definitions (which would additionally perform
    1200             :     // a check that we don't use multiple component types of the same interface in one file), because libxml2 gives
    1201             :     // useless error messages in the latter case; this way lets it report the real error.)
    1202          15 :     std::sort(componentTypes.begin(), componentTypes.end());
    1203          15 :     schema +=
    1204             :         "<start>"
    1205             :             "<element>"
    1206             :                 "<anyName/>"
    1207          15 :                 "<optional><attribute name='parent'/></optional>";
    1208        1180 :     for (std::vector<std::string>::const_iterator it = componentTypes.begin(); it != componentTypes.end(); ++it)
    1209        4660 :         schema += "<optional><ref name='component." + *it + "'/></optional>";
    1210          15 :     schema +=
    1211             :         "</element>"
    1212          15 :     "</start>";
    1213             : 
    1214          15 :     schema += "</grammar>";
    1215             : 
    1216          30 :     return schema;
    1217          15 : }

Generated by: LCOV version 1.16