LCOV - code coverage report
Current view: top level - source/simulation2/components - CCmpAIManager.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 161 545 29.5 %
Date: 2026-12-02 01:21:50 Functions: 22 45 48.9 %

          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 "ICmpAIManager.h"
      21             : 
      22             : #include "graphics/HeightMipmap.h"
      23             : #include "lib/alignment.h"
      24             : #include "lib/allocators/shared_ptr.h"
      25             : #include "lib/code_annotation.h"
      26             : #include "lib/debug.h"
      27             : #include "lib/file/vfs/vfs_path.h"
      28             : #include "lib/file/vfs/vfs_util.h"
      29             : #include "lib/os_path.h"
      30             : #include "lib/path.h"
      31             : #include "lib/tex/tex.h"
      32             : #include "lib/utf8.h"
      33             : #include "maths/FixedVector2D.h"
      34             : #include "ps/CLogger.h"
      35             : #include "ps/Filesystem.h"
      36             : #include "ps/Profile.h"
      37             : #include "ps/Profiler2.h"
      38             : #include "ps/TemplateLoader.h"
      39             : #include "ps/Util.h"
      40             : #include "ps/scripting/JSInterface_VFS.h"
      41             : #include "scriptinterface/FunctionWrapper.h"
      42             : #include "scriptinterface/JSON.h"
      43             : #include "scriptinterface/ModuleLoader.h"
      44             : #include "scriptinterface/Object.h"
      45             : #include "scriptinterface/Context.h"
      46             : #include "scriptinterface/Conversions.h"
      47             : #include "scriptinterface/Interface.h"
      48             : #include "scriptinterface/Request.h"
      49             : #include "scriptinterface/StructuredClone.h"
      50             : #include "simulation2/components/ICmpAIInterface.h"
      51             : #include "simulation2/components/ICmpCommandQueue.h"
      52             : #include "simulation2/components/ICmpPathfinder.h"
      53             : #include "simulation2/components/ICmpRangeManager.h"
      54             : #include "simulation2/components/ICmpTemplateManager.h"
      55             : #include "simulation2/components/ICmpTerritoryManager.h"
      56             : #include "simulation2/helpers/Grid.h"
      57             : #include "simulation2/helpers/HierarchicalPathfinder.h"
      58             : #include "simulation2/helpers/LongPathfinder.h"
      59             : #include "simulation2/helpers/PathGoal.h"
      60             : #include "simulation2/helpers/Pathfinding.h"
      61             : #include "simulation2/helpers/Player.h"
      62             : #include "simulation2/serialization/DebugSerializer.h"
      63             : #include "simulation2/serialization/SerializeTemplates.h"
      64             : #include "simulation2/serialization/SerializedTypes.h"
      65             : #include "simulation2/serialization/StdDeserializer.h"
      66             : #include "simulation2/serialization/StdSerializer.h"
      67             : #include "simulation2/system/Component.h"
      68             : 
      69             : #include <boost/random/linear_congruential.hpp>
      70             : #include <cstring>
      71             : #include <js/Array.h>
      72             : #include <js/GCAPI.h>
      73             : #include <js/GCVector.h>
      74             : #include <js/PropertyAndElement.h>
      75             : #include <js/RootingAPI.h>
      76             : #include <js/TracingAPI.h>
      77             : #include <js/TypeDecls.h>
      78             : #include <js/Value.h>
      79             : #include <js/experimental/TypedData.h>
      80             : #include <map>
      81             : #include <memory>
      82             : #include <set>
      83             : #include <sstream>
      84             : #include <string>
      85             : #include <tuple>
      86             : #include <utility>
      87             : #include <vector>
      88             : 
      89             : extern void QuitEngine(int exitStatus);
      90             : 
      91             : /**
      92             :  * @file
      93             :  * Player AI interface.
      94             :  * AI is primarily scripted, and the CCmpAIManager component defined here
      95             :  * takes care of managing all the scripts.
      96             :  *
      97             :  * The original idea was to run CAIWorker in a separate thread to prevent
      98             :  * slow AIs from impacting framerate. However, copying the game-state every turn
      99             :  * proved difficult and rather slow itself (and isn't threadable, obviously).
     100             :  * For these reasons, the design was changed to a single-thread, same-compartment, different-realm design.
     101             :  * The AI can therefore directly use the simulation data via the 'Sim' & 'SimEngine' globals.
     102             :  * As a result, a lof of the code is still designed to be "thread-ready", but this no longer matters.
     103             :  *
     104             :  * TODO: despite the above, it would still be useful to allow the AI to run tasks asynchronously (and off-thread).
     105             :  * This could be implemented by having a separate JS runtime in a different thread,
     106             :  * that runs tasks and returns after a distinct # of simulation turns (to maintain determinism).
     107             :  *
     108             :  * Note also that the RL Interface, by default, uses the 'AI representation'.
     109             :  * This representation, alimented by the JS AIInterface/AIProxy tandem, is likely to grow smaller over time
     110             :  * as the AI uses more sim data directly.
     111             :  */
     112             : 
     113             : /**
     114             :  * AI computation orchestator for CCmpAIManager.
     115             :  */
     116             : class CAIWorker
     117             : {
     118             : private:
     119             :     class CAIPlayer
     120             :     {
     121             :         NONCOPYABLE(CAIPlayer);
     122             :     public:
     123           0 :         CAIPlayer(CAIWorker& worker, const std::wstring& aiName, player_id_t player,
     124             :             std::uint8_t difficulty, const std::wstring& behavior,
     125           0 :             std::shared_ptr<Script::Interface> scriptInterface) :
     126           0 :             m_Worker(worker), m_AIName(aiName), m_Player(player), m_Difficulty(difficulty), m_Behavior(behavior),
     127           0 :             m_ScriptInterface(scriptInterface), m_Obj(scriptInterface->GetGeneralJSContext())
     128             :         {
     129           0 :         }
     130             : 
     131           0 :         bool Initialise()
     132             :         {
     133           0 :             Script::Request rq(m_ScriptInterface);
     134             : 
     135           0 :             OsPath path = L"simulation/ai/" + m_AIName + L"/data.json";
     136           0 :             JS::RootedValue metadata(rq.cx);
     137           0 :             m_Worker.LoadMetadata(path, &metadata);
     138           0 :             if (metadata.isUndefined())
     139             :             {
     140           0 :                 LOGERROR("Failed to create AI player: can't find {}", path.string8());
     141           0 :                 return false;
     142             :             }
     143             : 
     144             :             // Get the constructor name from the metadata
     145           0 :             std::string filename;
     146           0 :             std::string constructor;
     147           0 :             JS::RootedValue ctor(rq.cx);
     148           0 :             if (!Script::HasProperty(rq, metadata, "filename"))
     149             :             {
     150           0 :                 LOGERROR("Failed to create AI player: {}: missing 'filename'", path.string8());
     151           0 :                 return false;
     152             :             }
     153             : 
     154           0 :             Script::GetProperty(rq, metadata, "filename", filename);
     155             : 
     156             : 
     157           0 :             auto result = m_ScriptInterface->GetModuleLoader().LoadModule(rq,
     158           0 :                 "simulation/ai/" + utf8_from_wstring(m_AIName) + "/" + filename);
     159             : 
     160           0 :             g_ScriptContext->RunJobs();
     161           0 :             JS::RootedValue objectWithConstructor(rq.cx, JS::ObjectValue(*result.begin()->Get()));
     162             : 
     163           0 :             if (!Script::GetProperty(rq, metadata, "constructor", constructor))
     164             :             {
     165           0 :                 LOGERROR("Failed to create AI player: {}: missing 'constructor'", path.string8());
     166           0 :                 return false;
     167             :             }
     168             : 
     169             :             // Get the constructor function from the loaded scripts
     170           0 :             if (!Script::GetProperty(rq, objectWithConstructor, constructor.c_str(), &ctor)
     171           0 :                 || ctor.isNull())
     172             :             {
     173           0 :                 LOGERROR("Failed to create AI player: {}: can't find constructor '{}'",
     174             :                     path.string8(), constructor);
     175           0 :                 return false;
     176             :             }
     177             : 
     178           0 :             Script::GetProperty(rq, metadata, "useShared", m_UseSharedComponent);
     179             : 
     180             :             // Set up the data to pass as the constructor argument
     181           0 :             JS::RootedValue settings(rq.cx);
     182           0 :             Script::CreateObject(
     183             :                 rq,
     184             :                 &settings,
     185           0 :                 "player", m_Player,
     186           0 :                 "difficulty", m_Difficulty,
     187           0 :                 "behavior", m_Behavior);
     188             : 
     189           0 :             if (!m_UseSharedComponent)
     190             :             {
     191           0 :                 ENSURE(m_Worker.m_HasLoadedEntityTemplates);
     192           0 :                 Script::SetProperty(rq, settings, "templates", m_Worker.m_EntityTemplates, false);
     193             :             }
     194             : 
     195           0 :             JS::RootedValueVector argv(rq.cx);
     196           0 :             std::ignore = argv.append(settings.get());
     197           0 :             m_ScriptInterface->CallConstructor(ctor, argv, &m_Obj);
     198             : 
     199           0 :             if (m_Obj.get().isNull())
     200             :             {
     201           0 :                 LOGERROR("Failed to create AI player: {}: error calling constructor '{}'",
     202             :                     path.string8(), constructor);
     203           0 :                 return false;
     204             :             }
     205             :             return true;
     206           0 :         }
     207             : 
     208           0 :         void Run(JS::HandleValue state, int playerID)
     209             :         {
     210           0 :             m_Commands.clear();
     211           0 :             Script::Request rq(m_ScriptInterface);
     212           0 :             Script::Function::CallVoid(rq, m_Obj, "HandleMessage", state, playerID);
     213           0 :         }
     214             :         // overloaded with a sharedAI part.
     215             :         // javascript can handle both natively on the same function.
     216           0 :         void Run(JS::HandleValue state, int playerID, JS::HandleValue SharedAI)
     217             :         {
     218           0 :             m_Commands.clear();
     219           0 :             Script::Request rq(m_ScriptInterface);
     220           0 :             Script::Function::CallVoid(rq, m_Obj, "HandleMessage", state, playerID, SharedAI);
     221           0 :         }
     222           0 :         void InitAI(JS::HandleValue SharedAI)
     223             :         {
     224           0 :             m_Commands.clear();
     225           0 :             Script::Request rq(m_ScriptInterface);
     226           0 :             Script::Function::CallVoid(rq, m_Obj, "Init", m_Player, SharedAI);
     227           0 :         }
     228             : 
     229             :         CAIWorker& m_Worker;
     230             :         std::wstring m_AIName;
     231             :         player_id_t m_Player;
     232             :         std::uint8_t m_Difficulty;
     233             :         std::wstring m_Behavior;
     234             :         bool m_UseSharedComponent;
     235             : 
     236             :         // Take care to keep this declaration before heap rooted members. Destructors of heap rooted
     237             :         // members have to be called before the context destructor.
     238             :         std::shared_ptr<Script::Interface> m_ScriptInterface;
     239             : 
     240             :         JS::PersistentRootedValue m_Obj;
     241             :         std::vector<Script::StructuredClone> m_Commands;
     242             :     };
     243             : 
     244             : public:
     245           0 :     struct SCommandSets
     246             :     {
     247             :         player_id_t player;
     248             :         std::vector<Script::StructuredClone> commands;
     249             :     };
     250             : 
     251           4 :     CAIWorker() :
     252           4 :         m_TurnNum(0),
     253           4 :         m_CommandsComputed(true),
     254           4 :         m_HasLoadedEntityTemplates(false),
     255           4 :         m_HasSharedComponent(false)
     256             :     {
     257           4 :     }
     258             : 
     259           4 :     ~CAIWorker()
     260             :     {
     261             :         // Init will always be called.
     262           4 :         JS_RemoveExtraGCRootsTracer(m_ScriptInterface->GetGeneralJSContext(), Trace, this);
     263          27 :     }
     264             : 
     265           4 :     void Init(const Script::Interface& simInterface)
     266             :     {
     267             :         // Create the script interface in the same compartment as the simulation interface.
     268             :         // This will allow us to directly share data from the sim to the AI (and vice versa, should the need arise).
     269           4 :         m_ScriptInterface = std::make_shared<Script::Interface>("Engine", "AI", simInterface,
     270           4 :             [](const VfsPath& path)
     271             :             {
     272           0 :                 return path.string().find(L"simulation/ai/") == 0;
     273           4 :             });
     274             : 
     275           4 :         Script::Request rq(m_ScriptInterface);
     276             : 
     277           4 :         m_EntityTemplates.init(rq.cx);
     278           4 :         m_SharedAIObj.init(rq.cx);
     279           4 :         m_PassabilityMapVal.init(rq.cx);
     280           4 :         m_TerritoryMapVal.init(rq.cx);
     281             : 
     282             : 
     283           4 :         m_ScriptInterface->ReplaceNondeterministicRNG(m_RNG);
     284             : 
     285           4 :         m_ScriptInterface->SetCallbackData(static_cast<void*> (this));
     286             : 
     287           4 :         JS_AddExtraGCRootsTracer(m_ScriptInterface->GetGeneralJSContext(), Trace, this);
     288             : 
     289           4 :         {
     290           4 :             Script::Request simrq(simInterface);
     291             :             // Register the sim globals for easy & explicit access. Mark it replaceable for hotloading.
     292           4 :             JS::RootedValue global(rq.cx, simrq.globalValue());
     293           4 :             m_ScriptInterface->SetGlobal("Sim", global, true);
     294           4 :             JS::RootedValue scope(rq.cx, JS::ObjectValue(*simrq.nativeScope.get()));
     295           4 :             m_ScriptInterface->SetGlobal("SimEngine", scope, true);
     296           4 :         }
     297             : 
     298             : #define REGISTER_FUNC_NAME(func, name) \
     299             :     Script::Function::Register<&CAIWorker::func, Script::Interface::ObjectFromCBData<CAIWorker>>(rq, name);
     300             : 
     301           4 :         REGISTER_FUNC_NAME(PostCommand, "PostCommand");
     302           4 :         Script::Function::Register<QuitEngine>(rq, "Exit");
     303             : 
     304           4 :         REGISTER_FUNC_NAME(ComputePathScript, "ComputePath");
     305             : 
     306           4 :         REGISTER_FUNC_NAME(DumpImage, "DumpImage");
     307           4 :         REGISTER_FUNC_NAME(GetTemplate, "GetTemplate");
     308             : 
     309             : #undef REGISTER_FUNC_NAME
     310             : 
     311           4 :         JSI_VFS::RegisterScriptFunctions_ReadOnlySimulation(rq);
     312             : 
     313             :         // Globalscripts may use VFS script functions
     314           4 :         m_ScriptInterface->LoadGlobalScripts();
     315             : 
     316           4 :     }
     317             : 
     318           0 :     bool HasLoadedEntityTemplates() const { return m_HasLoadedEntityTemplates; }
     319             : 
     320           0 :     void PostCommand(int playerid, JS::HandleValue cmd)
     321             :     {
     322           0 :         Script::Request rq(m_ScriptInterface);
     323           0 :         for (size_t i=0; i<m_Players.size(); i++)
     324             :         {
     325           0 :             if (m_Players[i]->m_Player == playerid)
     326             :             {
     327           0 :                 m_Players[i]->m_Commands.push_back(Script::WriteStructuredClone(rq, cmd));
     328           0 :                 return;
     329             :             }
     330             :         }
     331             : 
     332           0 :         LOGERROR("Invalid playerid in PostCommand!");
     333           0 :     }
     334             : 
     335           0 :     JS::Value ComputePathScript(JS::HandleValue position, JS::HandleValue goal, pass_class_t passClass)
     336             :     {
     337           0 :         Script::Request rq(m_ScriptInterface);
     338             : 
     339           0 :         CFixedVector2D pos, goalPos;
     340           0 :         std::vector<CFixedVector2D> waypoints;
     341           0 :         JS::RootedValue retVal(rq.cx);
     342             : 
     343           0 :         Script::FromJSVal(rq, position, pos);
     344           0 :         Script::FromJSVal(rq, goal, goalPos);
     345             : 
     346           0 :         ComputePath(pos, goalPos, passClass, waypoints);
     347           0 :         Script::ToJSVal(rq, &retVal, waypoints);
     348             : 
     349           0 :         return retVal;
     350           0 :     }
     351             : 
     352           0 :     void ComputePath(const CFixedVector2D& pos, const CFixedVector2D& goal, pass_class_t passClass, std::vector<CFixedVector2D>& waypoints)
     353             :     {
     354           0 :         WaypointPath ret;
     355           0 :         PathGoal pathGoal = { PathGoal::POINT, goal.X, goal.Y };
     356           0 :         m_LongPathfinder.ComputePath(m_HierarchicalPathfinder, pos.X, pos.Y, pathGoal, passClass, ret);
     357             : 
     358           0 :         for (Waypoint& wp : ret.m_Waypoints)
     359           0 :             waypoints.emplace_back(wp.x, wp.z);
     360           0 :     }
     361             : 
     362           0 :     CParamNode GetTemplate(const std::string& name)
     363             :     {
     364           0 :         if (!m_TemplateLoader.TemplateExists(name))
     365           0 :             return CParamNode(false);
     366           0 :         return m_TemplateLoader.GetTemplateFileData(name).GetOnlyChild();
     367             :     }
     368             : 
     369             :     /**
     370             :      * Debug function for AI scripts to dump 2D array data (e.g. terrain tile weights).
     371             :      */
     372           0 :     void DumpImage(const std::wstring& name, const std::vector<std::uint32_t>& data, std::uint32_t w,
     373             :         std::uint32_t h, std::uint32_t max)
     374             :     {
     375             :         // TODO: this is totally not threadsafe.
     376           0 :         VfsPath filename = L"screenshots/aidump/" + name;
     377             : 
     378           0 :         if (data.size() != w*h)
     379             :         {
     380           0 :             debug_warn(L"DumpImage: data size doesn't match w*h");
     381           0 :             return;
     382             :         }
     383             : 
     384           0 :         if (max == 0)
     385             :         {
     386           0 :             debug_warn(L"DumpImage: max must not be 0");
     387           0 :             return;
     388             :         }
     389             : 
     390           0 :         const size_t bpp = 8;
     391           0 :         int flags = TEX_BOTTOM_UP|TEX_GREY;
     392             : 
     393           0 :         const size_t img_size = w * h * bpp/8;
     394           0 :         const size_t hdr_size = tex_hdr_size(filename);
     395           0 :         std::shared_ptr<std::uint8_t> buf;
     396           0 :         AllocateAligned(buf, hdr_size+img_size, maxSectorSize);
     397           0 :         Tex t;
     398           0 :         if (t.wrap(w, h, bpp, flags, buf, hdr_size) < 0)
     399           0 :             return;
     400             : 
     401           0 :         std::uint8_t* img = buf.get() + hdr_size;
     402           0 :         for (size_t i = 0; i < data.size(); ++i)
     403           0 :             img[i] = static_cast<std::uint8_t>((data[i] * 255) / max);
     404             : 
     405           0 :         tex_write(&t, filename);
     406           0 :     }
     407             : 
     408           3 :     void SetRNGSeed(std::uint32_t seed)
     409             :     {
     410           3 :         m_RNG.seed(seed);
     411             :     }
     412             : 
     413           3 :     bool TryLoadSharedComponent()
     414             :     {
     415           3 :         Script::Request rq(m_ScriptInterface);
     416             : 
     417             :         // we don't need to load it.
     418           3 :         if (!std::exchange(m_HasSharedComponent, true))
     419             :             return false;
     420             : 
     421           0 :         auto result = m_ScriptInterface->GetModuleLoader().LoadModule(rq,
     422           0 :             "simulation/ai/common-api/shared.js");
     423             : 
     424           0 :         g_ScriptContext->RunJobs();
     425             : 
     426             :         // mainly here for the error messages
     427           0 :         OsPath path = L"simulation/ai/common-api/";
     428             : 
     429             :         // Constructor name is SharedScript, it's in the module API3
     430             :         // TODO: Hardcoding this is bad, we need a smarter way.
     431           0 :         JS::RootedValue AIModule(rq.cx, JS::ObjectValue(*result.begin()->Get()));
     432           0 :         JS::RootedValue ctor(rq.cx);
     433             : 
     434           0 :         if (!Script::GetProperty(rq, AIModule, "SharedScript", &ctor)
     435           0 :             || ctor.isUndefined())
     436             :         {
     437           0 :             LOGERROR("Failed to create shared AI component: {}: can't find constructor '{}'",
     438             :                 path.string8(), "SharedScript");
     439           0 :             return false;
     440             :         }
     441             : 
     442             :         // Set up the data to pass as the constructor argument
     443           0 :         JS::RootedValue playersID(rq.cx);
     444           0 :         Script::CreateObject(rq, &playersID);
     445             : 
     446           0 :         for (size_t i = 0; i < m_Players.size(); ++i)
     447             :         {
     448           0 :             JS::RootedValue val(rq.cx);
     449           0 :             Script::ToJSVal(rq, &val, m_Players[i]->m_Player);
     450           0 :             Script::SetPropertyInt(rq, playersID, i, val, true);
     451           0 :         }
     452             : 
     453           0 :         ENSURE(m_HasLoadedEntityTemplates);
     454             : 
     455           0 :         JS::RootedValue settings(rq.cx);
     456           0 :         Script::CreateObject(
     457             :             rq,
     458             :             &settings,
     459             :             "players", playersID,
     460           0 :             "templates", m_EntityTemplates);
     461             : 
     462           0 :         JS::RootedValueVector argv(rq.cx);
     463           0 :         std::ignore = argv.append(settings);
     464           0 :         m_ScriptInterface->CallConstructor(ctor, argv, &m_SharedAIObj);
     465             : 
     466           0 :         if (m_SharedAIObj.get().isNull())
     467             :         {
     468           0 :             LOGERROR("Failed to create shared AI component: {}: error calling constructor '{}'",
     469             :                 path.string8(), "SharedScript");
     470           0 :             return false;
     471             :         }
     472             : 
     473             :         return true;
     474           3 :     }
     475             : 
     476           0 :     bool AddPlayer(const std::wstring& aiName, player_id_t player, std::uint8_t difficulty,
     477             :         const std::wstring& behavior)
     478             :     {
     479           0 :         std::shared_ptr<CAIPlayer> ai = std::make_shared<CAIPlayer>(*this, aiName, player, difficulty, behavior, m_ScriptInterface);
     480           0 :         if (!ai->Initialise())
     481             :             return false;
     482             : 
     483             :         // this will be set to true if we need to load the shared Component.
     484           0 :         if (!m_HasSharedComponent)
     485           0 :             m_HasSharedComponent = ai->m_UseSharedComponent;
     486             : 
     487           0 :         m_Players.push_back(ai);
     488             : 
     489             :         return true;
     490           0 :     }
     491             : 
     492           3 :     bool RunGamestateInit(const Script::StructuredClone& gameState,
     493             :         const Grid<NavcellData>& passabilityMap, const Grid<std::uint8_t>& territoryMap,
     494             :         const std::map<std::string, pass_class_t>& nonPathfindingPassClassMasks,
     495             :         const std::map<std::string, pass_class_t>& pathfindingPassClassMasks)
     496             :     {
     497             :         // this will be run last by InitGame.js, passing the full game representation.
     498             :         // For now it will run for the shared Component.
     499             :         // This is NOT run during deserialization.
     500           3 :         Script::Request rq(m_ScriptInterface);
     501             : 
     502           3 :         JS::RootedValue state(rq.cx);
     503           3 :         Script::ReadStructuredClone(rq, gameState, &state);
     504           3 :         Script::ToJSVal(rq, &m_PassabilityMapVal, passabilityMap);
     505           3 :         Script::ToJSVal(rq, &m_TerritoryMapVal, territoryMap);
     506             : 
     507           3 :         m_PassabilityMap = passabilityMap;
     508           3 :         m_NonPathfindingPassClasses = nonPathfindingPassClassMasks;
     509           3 :         m_PathfindingPassClasses = pathfindingPassClassMasks;
     510             : 
     511           3 :         m_LongPathfinder.Reload(&m_PassabilityMap);
     512           3 :         m_HierarchicalPathfinder.Recompute(&m_PassabilityMap, nonPathfindingPassClassMasks, pathfindingPassClassMasks);
     513             : 
     514           3 :         if (m_HasSharedComponent)
     515             :         {
     516           3 :             Script::SetProperty(rq, state, "passabilityMap", m_PassabilityMapVal, true);
     517           3 :             Script::SetProperty(rq, state, "territoryMap", m_TerritoryMapVal, true);
     518           3 :             Script::Function::CallVoid(rq, m_SharedAIObj, "init", state);
     519             : 
     520           3 :             for (size_t i = 0; i < m_Players.size(); ++i)
     521             :             {
     522           0 :                 if (m_HasSharedComponent && m_Players[i]->m_UseSharedComponent)
     523           0 :                     m_Players[i]->InitAI(m_SharedAIObj);
     524             :             }
     525             :         }
     526             : 
     527           3 :         return true;
     528           3 :     }
     529             : 
     530           0 :     void UpdateGameState(JS::HandleValue gameState)
     531             :     {
     532           0 :         ENSURE(m_CommandsComputed);
     533           0 :         m_GameState.reset();
     534           0 :         m_GameState.init(Script::Request(m_ScriptInterface).cx, gameState);
     535           0 :     }
     536             : 
     537           0 :     void UpdatePathfinder(const Grid<NavcellData>& passabilityMap, bool globallyDirty,
     538             :         const Grid<std::uint8_t>& dirtinessGrid, bool justDeserialized,
     539             :         const std::map<std::string, pass_class_t>& nonPathfindingPassClassMasks,
     540             :         const std::map<std::string, pass_class_t>& pathfindingPassClassMasks)
     541             :     {
     542           0 :         ENSURE(m_CommandsComputed);
     543           0 :         bool dimensionChange = m_PassabilityMap.m_W != passabilityMap.m_W || m_PassabilityMap.m_H != passabilityMap.m_H;
     544             : 
     545           0 :         m_PassabilityMap = passabilityMap;
     546           0 :         if (globallyDirty)
     547             :         {
     548           0 :             m_LongPathfinder.Reload(&m_PassabilityMap);
     549           0 :             m_HierarchicalPathfinder.Recompute(&m_PassabilityMap, nonPathfindingPassClassMasks, pathfindingPassClassMasks);
     550             :         }
     551             :         else
     552             :         {
     553           0 :             m_LongPathfinder.Update(&m_PassabilityMap);
     554           0 :             m_HierarchicalPathfinder.Update(&m_PassabilityMap, dirtinessGrid);
     555             :         }
     556             : 
     557           0 :         Script::Request rq(m_ScriptInterface);
     558           0 :         if (dimensionChange || justDeserialized)
     559           0 :             Script::ToJSVal(rq, &m_PassabilityMapVal, m_PassabilityMap);
     560             :         else
     561             :         {
     562             :             // Avoid a useless memory reallocation followed by a garbage collection.
     563           0 :             JS::RootedObject mapObj(rq.cx, &m_PassabilityMapVal.toObject());
     564           0 :             JS::RootedValue mapData(rq.cx);
     565           0 :             ENSURE(JS_GetProperty(rq.cx, mapObj, "data", &mapData));
     566           0 :             JS::RootedObject dataObj(rq.cx, &mapData.toObject());
     567             : 
     568           0 :             std::uint32_t length = 0;
     569           0 :             ENSURE(JS::GetArrayLength(rq.cx, dataObj, &length));
     570           0 :             std::uint32_t nbytes = static_cast<std::uint32_t>(length * sizeof(NavcellData));
     571             : 
     572           0 :             bool sharedMemory;
     573           0 :             JS::AutoCheckCannotGC nogc;
     574           0 :             memcpy((void*)JS_GetUint16ArrayData(dataObj, &sharedMemory, nogc), m_PassabilityMap.m_Data, nbytes);
     575           0 :         }
     576           0 :     }
     577             : 
     578           0 :     void UpdateTerritoryMap(const Grid<std::uint8_t>& territoryMap)
     579             :     {
     580           0 :         ENSURE(m_CommandsComputed);
     581           0 :         bool dimensionChange = m_TerritoryMap.m_W != territoryMap.m_W || m_TerritoryMap.m_H != territoryMap.m_H;
     582             : 
     583           0 :         m_TerritoryMap = territoryMap;
     584             : 
     585           0 :         Script::Request rq(m_ScriptInterface);
     586           0 :         if (dimensionChange)
     587           0 :             Script::ToJSVal(rq, &m_TerritoryMapVal, m_TerritoryMap);
     588             :         else
     589             :         {
     590             :             // Avoid a useless memory reallocation followed by a garbage collection.
     591           0 :             JS::RootedObject mapObj(rq.cx, &m_TerritoryMapVal.toObject());
     592           0 :             JS::RootedValue mapData(rq.cx);
     593           0 :             ENSURE(JS_GetProperty(rq.cx, mapObj, "data", &mapData));
     594           0 :             JS::RootedObject dataObj(rq.cx, &mapData.toObject());
     595             : 
     596           0 :             std::uint32_t length = 0;
     597           0 :             ENSURE(JS::GetArrayLength(rq.cx, dataObj, &length));
     598           0 :             std::uint32_t nbytes = static_cast<std::uint32_t>(length * sizeof(std::uint8_t));
     599             : 
     600           0 :             bool sharedMemory;
     601           0 :             JS::AutoCheckCannotGC nogc;
     602           0 :             memcpy((void*)JS_GetUint8ArrayData(dataObj, &sharedMemory, nogc), m_TerritoryMap.m_Data, nbytes);
     603           0 :         }
     604           0 :     }
     605             : 
     606           0 :     void StartComputation()
     607             :     {
     608           0 :         m_CommandsComputed = false;
     609             :     }
     610             : 
     611         198 :     void WaitToFinishComputation()
     612             :     {
     613         198 :         if (!m_CommandsComputed)
     614             :         {
     615           0 :             PerformComputation();
     616           0 :             m_CommandsComputed = true;
     617             :         }
     618             :     }
     619             : 
     620         180 :     void GetCommands(std::vector<SCommandSets>& commands)
     621             :     {
     622         180 :         WaitToFinishComputation();
     623             : 
     624         180 :         commands.clear();
     625         180 :         commands.resize(m_Players.size());
     626         180 :         for (size_t i = 0; i < m_Players.size(); ++i)
     627             :         {
     628           0 :             commands[i].player = m_Players[i]->m_Player;
     629           0 :             commands[i].commands = m_Players[i]->m_Commands;
     630             :         }
     631         180 :     }
     632             : 
     633           0 :     void LoadEntityTemplates(const std::vector<std::pair<std::string, const CParamNode*> >& templates)
     634             :     {
     635           0 :         Script::Request rq(m_ScriptInterface);
     636             : 
     637           0 :         m_HasLoadedEntityTemplates = true;
     638             : 
     639           0 :         Script::CreateObject(rq, &m_EntityTemplates);
     640             : 
     641           0 :         JS::RootedValue val(rq.cx);
     642           0 :         for (size_t i = 0; i < templates.size(); ++i)
     643             :         {
     644           0 :             templates[i].second->ToJSVal(rq, false, &val);
     645           0 :             Script::SetProperty(rq, m_EntityTemplates, templates[i].first.c_str(), val, true);
     646             :         }
     647           0 :     }
     648             : 
     649          18 :     void Serialize(std::ostream& stream, bool isDebug)
     650             :     {
     651          18 :         WaitToFinishComputation();
     652             : 
     653          18 :         if (isDebug)
     654             :         {
     655           0 :             CDebugSerializer serializer(*m_ScriptInterface, stream);
     656           0 :             serializer.Indent(4);
     657           0 :             SerializeState(serializer);
     658           0 :         }
     659             :         else
     660             :         {
     661          18 :             CStdSerializer serializer(*m_ScriptInterface, stream);
     662          18 :             SerializeState(serializer);
     663          18 :         }
     664          18 :     }
     665             : 
     666          18 :     void SerializeState(ISerializer& serializer)
     667             :     {
     668          18 :         if (m_Players.empty())
     669          18 :             return;
     670             : 
     671           0 :         Script::Request rq(m_ScriptInterface);
     672             : 
     673           0 :         std::stringstream rngStream;
     674           0 :         rngStream << m_RNG;
     675           0 :         serializer.StringASCII("rng", rngStream.str(), 0, 32);
     676             : 
     677           0 :         serializer.NumberU32_Unbounded("turn", m_TurnNum);
     678             : 
     679           0 :         serializer.Bool("useSharedScript", m_HasSharedComponent);
     680           0 :         if (m_HasSharedComponent)
     681           0 :             serializer.ScriptVal("sharedData", &m_SharedAIObj);
     682           0 :         for (size_t i = 0; i < m_Players.size(); ++i)
     683             :         {
     684           0 :             serializer.String("name", m_Players[i]->m_AIName, 1, 256);
     685           0 :             serializer.NumberI32_Unbounded("player", m_Players[i]->m_Player);
     686           0 :             serializer.NumberU8_Unbounded("difficulty", m_Players[i]->m_Difficulty);
     687           0 :             serializer.String("behavior", m_Players[i]->m_Behavior, 1, 256);
     688             : 
     689           0 :             serializer.NumberU32_Unbounded("num commands", static_cast<std::uint32_t>(m_Players[i]->m_Commands.size()));
     690           0 :             for (size_t j = 0; j < m_Players[i]->m_Commands.size(); ++j)
     691             :             {
     692           0 :                 JS::RootedValue val(rq.cx);
     693           0 :                 Script::ReadStructuredClone(rq, m_Players[i]->m_Commands[j], &val);
     694           0 :                 serializer.ScriptVal("command", &val);
     695           0 :             }
     696             : 
     697           0 :             serializer.ScriptVal("data", &m_Players[i]->m_Obj);
     698             :         }
     699             : 
     700             :         // AI pathfinder
     701           0 :         Serializer(serializer, "non pathfinding pass classes", m_NonPathfindingPassClasses);
     702           0 :         Serializer(serializer, "pathfinding pass classes", m_PathfindingPassClasses);
     703           0 :         serializer.NumberU16_Unbounded("pathfinder grid w", m_PassabilityMap.m_W);
     704           0 :         serializer.NumberU16_Unbounded("pathfinder grid h", m_PassabilityMap.m_H);
     705           0 :         serializer.RawBytes("pathfinder grid data",
     706           0 :             reinterpret_cast<const std::uint8_t*>(m_PassabilityMap.m_Data),
     707           0 :             m_PassabilityMap.m_W*m_PassabilityMap.m_H*sizeof(NavcellData));
     708           0 :     }
     709             : 
     710           0 :     void Deserialize(std::istream& stream, std::uint32_t numAis)
     711             :     {
     712           0 :         m_PlayerMetadata.clear();
     713           0 :         m_Players.clear();
     714             : 
     715           0 :         if (numAis == 0)
     716           0 :             return;
     717             : 
     718           0 :         Script::Request rq(m_ScriptInterface);
     719             : 
     720           0 :         ENSURE(m_CommandsComputed); // deserializing while we're still actively computing would be bad
     721             : 
     722           0 :         CStdDeserializer deserializer(*m_ScriptInterface, stream);
     723             : 
     724           0 :         std::string rngString;
     725           0 :         std::stringstream rngStream;
     726           0 :         deserializer.StringASCII("rng", rngString, 0, 32);
     727           0 :         rngStream << rngString;
     728           0 :         rngStream >> m_RNG;
     729             : 
     730           0 :         deserializer.NumberU32_Unbounded("turn", m_TurnNum);
     731             : 
     732           0 :         deserializer.Bool("useSharedScript", m_HasSharedComponent);
     733           0 :         if (m_HasSharedComponent)
     734             :         {
     735           0 :             TryLoadSharedComponent();
     736           0 :             deserializer.ScriptObjectAssign("sharedData", m_SharedAIObj);
     737             :         }
     738             : 
     739           0 :         for (size_t i = 0; i < numAis; ++i)
     740             :         {
     741           0 :             std::wstring name;
     742           0 :             player_id_t player;
     743           0 :             std::uint8_t difficulty;
     744           0 :             std::wstring behavior;
     745           0 :             deserializer.String("name", name, 1, 256);
     746           0 :             deserializer.NumberI32_Unbounded("player", player);
     747           0 :             deserializer.NumberU8_Unbounded("difficulty",difficulty);
     748           0 :             deserializer.String("behavior", behavior, 1, 256);
     749           0 :             if (!AddPlayer(name, player, difficulty, behavior))
     750           0 :                 throw PSERROR_Deserialize_ScriptError();
     751             : 
     752           0 :             std::uint32_t numCommands;
     753           0 :             deserializer.NumberU32_Unbounded("num commands", numCommands);
     754           0 :             m_Players.back()->m_Commands.reserve(numCommands);
     755           0 :             for (size_t j = 0; j < numCommands; ++j)
     756             :             {
     757           0 :                 JS::RootedValue val(rq.cx);
     758           0 :                 deserializer.ScriptVal("command", &val);
     759           0 :                 m_Players.back()->m_Commands.push_back(Script::WriteStructuredClone(rq, val));
     760           0 :             }
     761             : 
     762           0 :             deserializer.ScriptObjectAssign("data", m_Players.back()->m_Obj);
     763           0 :         }
     764             : 
     765             :         // AI pathfinder
     766           0 :         Serializer(deserializer, "non pathfinding pass classes", m_NonPathfindingPassClasses);
     767           0 :         Serializer(deserializer, "pathfinding pass classes", m_PathfindingPassClasses);
     768           0 :         std::uint16_t mapW, mapH;
     769           0 :         deserializer.NumberU16_Unbounded("pathfinder grid w", mapW);
     770           0 :         deserializer.NumberU16_Unbounded("pathfinder grid h", mapH);
     771           0 :         m_PassabilityMap = Grid<NavcellData>(mapW, mapH);
     772           0 :         deserializer.RawBytes("pathfinder grid data",
     773           0 :             reinterpret_cast<std::uint8_t*>(m_PassabilityMap.m_Data), mapW * mapH * sizeof(NavcellData));
     774           0 :         m_LongPathfinder.Reload(&m_PassabilityMap);
     775           0 :         m_HierarchicalPathfinder.Recompute(&m_PassabilityMap, m_NonPathfindingPassClasses, m_PathfindingPassClasses);
     776           0 :     }
     777             : 
     778         198 :     int getPlayerSize()
     779             :     {
     780         198 :         return m_Players.size();
     781             :     }
     782             : 
     783             : private:
     784           6 :     static void Trace(JSTracer *trc, void *data)
     785             :     {
     786           6 :         reinterpret_cast<CAIWorker*>(data)->TraceMember(trc);
     787           6 :     }
     788             : 
     789           6 :     void TraceMember(JSTracer *trc)
     790             :     {
     791           6 :         for (std::pair<const VfsPath, JS::Heap<JS::Value>>& metadata : m_PlayerMetadata)
     792           0 :             JS::TraceEdge(trc, &metadata.second, "CAIWorker::m_PlayerMetadata");
     793           6 :     }
     794             : 
     795           0 :     void LoadMetadata(const VfsPath& path, JS::MutableHandleValue out)
     796             :     {
     797           0 :         if (m_PlayerMetadata.find(path) == m_PlayerMetadata.end())
     798             :         {
     799             :             // Load and cache the AI player metadata
     800           0 :             Script::ReadJSONFile(Script::Request(m_ScriptInterface), path, out);
     801           0 :             m_PlayerMetadata[path] = JS::Heap<JS::Value>(out);
     802           0 :             return;
     803             :         }
     804           0 :         out.set(m_PlayerMetadata[path].get());
     805             :     }
     806             : 
     807           0 :     void PerformComputation()
     808             :     {
     809             :         // Deserialize the game state, to pass to the AI's HandleMessage
     810           0 :         Script::Request rq(m_ScriptInterface);
     811           0 :         {
     812           0 :             PROFILE3("AI compute read state");
     813           0 :             Script::SetProperty(rq, m_GameState, "passabilityMap", m_PassabilityMapVal, true);
     814           0 :             Script::SetProperty(rq, m_GameState, "territoryMap", m_TerritoryMapVal, true);
     815           0 :         }
     816             : 
     817             :         // It would be nice to do
     818             :         //   Script::FreezeObject(rq, state.get(), true);
     819             :         // to prevent AI scripts accidentally modifying the state and
     820             :         // affecting other AI scripts they share it with. But the performance
     821             :         // cost is far too high, so we won't do that.
     822             :         // If there is a shared component, run it
     823             : 
     824           0 :         if (m_HasSharedComponent)
     825             :         {
     826           0 :             PROFILE3("AI run shared component");
     827           0 :             Script::Function::CallVoid(rq, m_SharedAIObj, "onUpdate", m_GameState);
     828           0 :         }
     829             : 
     830           0 :         for (size_t i = 0; i < m_Players.size(); ++i)
     831             :         {
     832           0 :             PROFILE3("AI script");
     833           0 :             PROFILE2_ATTR("player: %d", m_Players[i]->m_Player);
     834           0 :             PROFILE2_ATTR("script: %ls", m_Players[i]->m_AIName.c_str());
     835             : 
     836           0 :             if (m_HasSharedComponent && m_Players[i]->m_UseSharedComponent)
     837           0 :                 m_Players[i]->Run(m_GameState, m_Players[i]->m_Player, m_SharedAIObj);
     838             :             else
     839           0 :                 m_Players[i]->Run(m_GameState, m_Players[i]->m_Player);
     840           0 :         }
     841           0 :     }
     842             : 
     843             :     std::shared_ptr<Script::Interface> m_ScriptInterface;
     844             :     boost::rand48 m_RNG;
     845             :     std::uint32_t m_TurnNum;
     846             : 
     847             :     JS::PersistentRootedValue m_EntityTemplates;
     848             :     bool m_HasLoadedEntityTemplates;
     849             : 
     850             :     std::map<VfsPath, JS::Heap<JS::Value>> m_PlayerMetadata;
     851             :     std::vector<std::shared_ptr<CAIPlayer>> m_Players; // use shared_ptr just to avoid copying
     852             : 
     853             :     bool m_HasSharedComponent;
     854             :     JS::PersistentRootedValue m_SharedAIObj;
     855             :     std::vector<SCommandSets> m_Commands;
     856             : 
     857             :     std::set<std::wstring> m_LoadedModules;
     858             : 
     859             :     JS::PersistentRootedValue m_GameState;
     860             :     Grid<NavcellData> m_PassabilityMap;
     861             :     JS::PersistentRootedValue m_PassabilityMapVal;
     862             :     Grid<std::uint8_t> m_TerritoryMap;
     863             :     JS::PersistentRootedValue m_TerritoryMapVal;
     864             : 
     865             :     std::map<std::string, pass_class_t> m_NonPathfindingPassClasses;
     866             :     std::map<std::string, pass_class_t> m_PathfindingPassClasses;
     867             :     HierarchicalPathfinder m_HierarchicalPathfinder;
     868             :     LongPathfinder m_LongPathfinder;
     869             : 
     870             :     bool m_CommandsComputed;
     871             : 
     872             :     CTemplateLoader m_TemplateLoader;
     873             : };
     874             : 
     875             : 
     876             : /**
     877             :  * Implementation of ICmpAIManager.
     878             :  */
     879             : class CCmpAIManager final : public ICmpAIManager
     880             : {
     881             : public:
     882             :     static void ClassInit(CComponentManager&)
     883             :     {
     884             :     }
     885             : 
     886           8 :     DEFAULT_COMPONENT_ALLOCATOR(AIManager)
     887             : 
     888         137 :     static std::string GetSchema()
     889             :     {
     890         274 :         return "<a:component type='system'/><empty/>";
     891             :     }
     892             : 
     893           4 :     void Init(const CParamNode&) override
     894             :     {
     895           4 :         m_Worker.Init(GetSimContext().GetScriptInterface());
     896             : 
     897           4 :         m_TerritoriesDirtyID = 0;
     898           4 :         m_TerritoriesDirtyBlinkingID = 0;
     899           4 :         m_JustDeserialized = false;
     900           4 :     }
     901             : 
     902           4 :     void Deinit() override
     903             :     {
     904           4 :     }
     905             : 
     906          18 :     void Serialize(ISerializer& serialize) override
     907             :     {
     908          18 :         serialize.NumberU32_Unbounded("num ais", m_Worker.getPlayerSize());
     909             : 
     910             :         // Because the AI worker uses its own Script::Interface, we can't use the
     911             :         // ISerializer (which was initialised with the simulation Script::Interface)
     912             :         // directly. So we'll just grab the ISerializer's stream and write to it
     913             :         // with an independent serializer.
     914             : 
     915          18 :         m_Worker.Serialize(serialize.GetStream(), serialize.IsDebug());
     916          18 :     }
     917             : 
     918           0 :     void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) override
     919             :     {
     920           0 :         Init(paramNode);
     921             : 
     922           0 :         std::uint32_t numAis;
     923           0 :         deserialize.NumberU32_Unbounded("num ais", numAis);
     924           0 :         if (numAis > 0)
     925           0 :             LoadUsedEntityTemplates();
     926             : 
     927           0 :         m_Worker.Deserialize(deserialize.GetStream(), numAis);
     928             : 
     929           0 :         m_JustDeserialized = true;
     930           0 :     }
     931             : 
     932           0 :     void AddPlayer(const std::wstring& id, player_id_t player, std::uint8_t difficulty,
     933             :         const std::wstring& behavior) override
     934             :     {
     935           0 :         LoadUsedEntityTemplates();
     936             : 
     937           0 :         m_Worker.AddPlayer(id, player, difficulty, behavior);
     938             : 
     939             :         // AI players can cheat and see through FoW/SoD, since that greatly simplifies
     940             :         // their implementation.
     941             :         // (TODO: maybe cleverer AIs should be able to optionally retain FoW/SoD)
     942           0 :         CmpPtr<ICmpRangeManager> cmpRangeManager(GetSystemEntity());
     943           0 :         if (cmpRangeManager)
     944           0 :             cmpRangeManager->SetLosRevealWholeMap(player, true);
     945           0 :     }
     946             : 
     947           3 :     void SetRNGSeed(std::uint32_t seed) override
     948             :     {
     949           3 :         m_Worker.SetRNGSeed(seed);
     950           3 :     }
     951             : 
     952           3 :     void TryLoadSharedComponent() override
     953             :     {
     954           3 :         m_Worker.TryLoadSharedComponent();
     955           3 :     }
     956             : 
     957           3 :     void RunGamestateInit() override
     958             :     {
     959           3 :         const Script::Interface& scriptInterface = GetSimContext().GetScriptInterface();
     960           3 :         Script::Request rq(scriptInterface);
     961             : 
     962           3 :         CmpPtr<ICmpAIInterface> cmpAIInterface(GetSystemEntity());
     963           3 :         ENSURE(cmpAIInterface);
     964             : 
     965             :         // Get the game state from AIInterface
     966             :         // We flush events from the initialization so we get a clean state now.
     967           3 :         JS::RootedValue state(rq.cx);
     968           3 :         cmpAIInterface->GetFullRepresentation(&state, true);
     969             : 
     970             :         // Get the passability data
     971           6 :         Grid<NavcellData> dummyGrid;
     972           3 :         const Grid<NavcellData>* passabilityMap = &dummyGrid;
     973           3 :         CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
     974           3 :         if (cmpPathfinder)
     975           3 :             passabilityMap = &cmpPathfinder->GetPassabilityGrid();
     976             : 
     977             :         // Get the territory data
     978             :         // Since getting the territory grid can trigger a recalculation, we check NeedUpdateAI first
     979           6 :         Grid<std::uint8_t> dummyGrid2;
     980           3 :         const Grid<std::uint8_t>* territoryMap = &dummyGrid2;
     981           3 :         CmpPtr<ICmpTerritoryManager> cmpTerritoryManager(GetSystemEntity());
     982           3 :         if (cmpTerritoryManager && cmpTerritoryManager->NeedUpdateAI(&m_TerritoriesDirtyID, &m_TerritoriesDirtyBlinkingID))
     983           3 :             territoryMap = &cmpTerritoryManager->GetTerritoryGrid();
     984             : 
     985           3 :         LoadPathfinderClasses(state);
     986           6 :         std::map<std::string, pass_class_t> nonPathfindingPassClassMasks, pathfindingPassClassMasks;
     987           3 :         if (cmpPathfinder)
     988           3 :             cmpPathfinder->GetPassabilityClasses(nonPathfindingPassClassMasks, pathfindingPassClassMasks);
     989             : 
     990           6 :         m_Worker.RunGamestateInit(Script::WriteStructuredClone(rq, state),
     991             :             *passabilityMap, *territoryMap, nonPathfindingPassClassMasks, pathfindingPassClassMasks);
     992           3 :     }
     993             : 
     994         180 :     void StartComputation() override
     995             :     {
     996         180 :         PROFILE("AI setup");
     997             : 
     998         180 :         const Script::Interface& scriptInterface = GetSimContext().GetScriptInterface();
     999         180 :         Script::Request rq(scriptInterface);
    1000             : 
    1001         180 :         if (m_Worker.getPlayerSize() == 0)
    1002         180 :             return;
    1003             : 
    1004           0 :         CmpPtr<ICmpAIInterface> cmpAIInterface(GetSystemEntity());
    1005           0 :         ENSURE(cmpAIInterface);
    1006             : 
    1007             :         // Get the game state from AIInterface
    1008           0 :         JS::RootedValue state(rq.cx);
    1009           0 :         if (m_JustDeserialized)
    1010           0 :             cmpAIInterface->GetFullRepresentation(&state, false);
    1011             :         else
    1012           0 :             cmpAIInterface->GetRepresentation(&state);
    1013           0 :         LoadPathfinderClasses(state); // add the pathfinding classes to it
    1014             : 
    1015             :         // Update the game state
    1016           0 :         m_Worker.UpdateGameState(state);
    1017             : 
    1018             :         // Update the pathfinding data
    1019           0 :         CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
    1020           0 :         if (cmpPathfinder)
    1021             :         {
    1022           0 :             const GridUpdateInformation& dirtinessInformations = cmpPathfinder->GetAIPathfinderDirtinessInformation();
    1023             : 
    1024           0 :             if (dirtinessInformations.dirty || m_JustDeserialized)
    1025             :             {
    1026           0 :                 const Grid<NavcellData>& passabilityMap = cmpPathfinder->GetPassabilityGrid();
    1027             : 
    1028           0 :                 std::map<std::string, pass_class_t> nonPathfindingPassClassMasks, pathfindingPassClassMasks;
    1029           0 :                 cmpPathfinder->GetPassabilityClasses(nonPathfindingPassClassMasks, pathfindingPassClassMasks);
    1030             : 
    1031           0 :                 m_Worker.UpdatePathfinder(passabilityMap,
    1032           0 :                     dirtinessInformations.globallyDirty, dirtinessInformations.dirtinessGrid, m_JustDeserialized,
    1033             :                     nonPathfindingPassClassMasks, pathfindingPassClassMasks);
    1034           0 :             }
    1035             : 
    1036           0 :             cmpPathfinder->FlushAIPathfinderDirtinessInformation();
    1037             :         }
    1038             : 
    1039             :         // Update the territory data
    1040             :         // Since getting the territory grid can trigger a recalculation, we check NeedUpdateAI first
    1041           0 :         CmpPtr<ICmpTerritoryManager> cmpTerritoryManager(GetSystemEntity());
    1042           0 :         if (cmpTerritoryManager && (cmpTerritoryManager->NeedUpdateAI(&m_TerritoriesDirtyID, &m_TerritoriesDirtyBlinkingID) || m_JustDeserialized))
    1043             :         {
    1044           0 :             const Grid<std::uint8_t>& territoryMap = cmpTerritoryManager->GetTerritoryGrid();
    1045           0 :             m_Worker.UpdateTerritoryMap(territoryMap);
    1046             :         }
    1047             : 
    1048           0 :         m_Worker.StartComputation();
    1049             : 
    1050           0 :         m_JustDeserialized = false;
    1051         180 :     }
    1052             : 
    1053         180 :     void PushCommands() override
    1054             :     {
    1055         180 :         std::vector<CAIWorker::SCommandSets> commands;
    1056         180 :         m_Worker.GetCommands(commands);
    1057             : 
    1058         180 :         CmpPtr<ICmpCommandQueue> cmpCommandQueue(GetSystemEntity());
    1059         180 :         if (!cmpCommandQueue)
    1060           0 :             return;
    1061             : 
    1062         180 :         const Script::Interface& scriptInterface = GetSimContext().GetScriptInterface();
    1063         180 :         Script::Request rq(scriptInterface);
    1064         180 :         JS::RootedValue clonedCommandVal(rq.cx);
    1065             : 
    1066         180 :         for (size_t i = 0; i < commands.size(); ++i)
    1067             :         {
    1068           0 :             for (size_t j = 0; j < commands[i].commands.size(); ++j)
    1069             :             {
    1070           0 :                 Script::ReadStructuredClone(rq, commands[i].commands[j], &clonedCommandVal);
    1071           0 :                 cmpCommandQueue->PushLocalCommand(commands[i].player, clonedCommandVal);
    1072             :             }
    1073             :         }
    1074         180 :     }
    1075             : 
    1076             : private:
    1077             :     size_t m_TerritoriesDirtyID;
    1078             :     size_t m_TerritoriesDirtyBlinkingID;
    1079             : 
    1080             :     bool m_JustDeserialized;
    1081             : 
    1082             :     /**
    1083             :      * Load the templates of all entities on the map (called when adding a new AI player for a new game
    1084             :      * or when deserializing)
    1085             :      */
    1086           0 :     void LoadUsedEntityTemplates()
    1087             :     {
    1088           0 :         if (m_Worker.HasLoadedEntityTemplates())
    1089           0 :             return;
    1090             : 
    1091           0 :         CmpPtr<ICmpTemplateManager> cmpTemplateManager(GetSystemEntity());
    1092           0 :         ENSURE(cmpTemplateManager);
    1093             : 
    1094           0 :         std::vector<std::string> templateNames = cmpTemplateManager->FindUsedTemplates();
    1095           0 :         std::vector<std::pair<std::string, const CParamNode*> > usedTemplates;
    1096           0 :         usedTemplates.reserve(templateNames.size());
    1097           0 :         for (const std::string& name : templateNames)
    1098             :         {
    1099           0 :             const CParamNode* node = cmpTemplateManager->GetTemplateWithoutValidation(name);
    1100           0 :             if (node)
    1101           0 :                 usedTemplates.emplace_back(name, node);
    1102             :         }
    1103             :         // Send the data to the worker
    1104           0 :         m_Worker.LoadEntityTemplates(usedTemplates);
    1105             :     }
    1106             : 
    1107           3 :     void LoadPathfinderClasses(JS::HandleValue state)
    1108             :     {
    1109           3 :         CmpPtr<ICmpPathfinder> cmpPathfinder(GetSystemEntity());
    1110           3 :         if (!cmpPathfinder)
    1111           0 :             return;
    1112             : 
    1113           3 :         const Script::Interface& scriptInterface = GetSimContext().GetScriptInterface();
    1114           3 :         Script::Request rq(scriptInterface);
    1115             : 
    1116           3 :         JS::RootedValue classesVal(rq.cx);
    1117           3 :         Script::CreateObject(rq, &classesVal);
    1118             : 
    1119           3 :         std::map<std::string, pass_class_t> classes;
    1120           3 :         cmpPathfinder->GetPassabilityClasses(classes);
    1121          30 :         for (std::map<std::string, pass_class_t>::iterator it = classes.begin(); it != classes.end(); ++it)
    1122          27 :             Script::SetProperty(rq, classesVal, it->first.c_str(), it->second, true);
    1123             : 
    1124           3 :         Script::SetProperty(rq, state, "passabilityClasses", classesVal, true);
    1125           3 :     }
    1126             : 
    1127             :     CAIWorker m_Worker;
    1128             : };
    1129             : 
    1130         274 : REGISTER_COMPONENT_TYPE(AIManager)

Generated by: LCOV version 1.16