LCOV - code coverage report
Current view: top level - source/tools/atlas/GameInterface/Handlers - MapHandlers.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 0 335 0.0 %
Date: 2026-12-03 01:19:39 Functions: 0 60 0.0 %

          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 "MessageHandler.h"
      21             : 
      22             : #include "graphics/GameView.h"
      23             : #include "graphics/LOSTexture.h"
      24             : #include "graphics/MapIO.h"
      25             : #include "graphics/MapWriter.h"
      26             : #include "graphics/MiniMapTexture.h"
      27             : #include "graphics/MiniPatch.h"
      28             : #include "graphics/Patch.h"
      29             : #include "graphics/Terrain.h"
      30             : #include "graphics/TerrainTextureEntry.h"
      31             : #include "lib/debug.h"
      32             : #include "lib/file/vfs/vfs.h"
      33             : #include "lib/file/vfs/vfs_path.h"
      34             : #include "lib/file/vfs/vfs_util.h"
      35             : #include "lib/os_path.h"
      36             : #include "lib/path.h"
      37             : #include "lib/posix/posix_types.h"
      38             : #include "lib/status.h"
      39             : #include "maths/Fixed.h"
      40             : #include "maths/FixedVector3D.h"
      41             : #include "maths/MathUtil.h"
      42             : #include "ps/CLogger.h"
      43             : #include "ps/CStr.h"
      44             : #include "ps/Errors.h"
      45             : #include "ps/Filesystem.h"
      46             : #include "ps/Game.h"
      47             : #include "ps/Loader.h"
      48             : #include "ps/World.h"
      49             : #include "renderer/Renderer.h"
      50             : #include "renderer/SceneRenderer.h"
      51             : #include "renderer/WaterManager.h"
      52             : #include "scriptinterface/JSON.h"
      53             : #include "scriptinterface/Object.h"
      54             : #include "scriptinterface/Interface.h"
      55             : #include "scriptinterface/Request.h"
      56             : #include "simulation2/Simulation2.h"
      57             : #include "simulation2/components/ICmpOwnership.h"
      58             : #include "simulation2/components/ICmpPosition.h"
      59             : #include "simulation2/components/ICmpRangeManager.h"
      60             : #include "simulation2/components/ICmpTemplateManager.h"
      61             : #include "simulation2/components/ICmpTerrain.h"
      62             : #include "simulation2/components/ICmpVisual.h"
      63             : #include "simulation2/helpers/Player.h"
      64             : #include "simulation2/system/Component.h"
      65             : #include "simulation2/system/Entity.h"
      66             : #include "tools/atlas/GameInterface/CommandProc.h"
      67             : #include "tools/atlas/GameInterface/Messages.h"
      68             : #include "tools/atlas/GameInterface/Shareable.h"
      69             : 
      70             : #include <algorithm>
      71             : #include <cmath>
      72             : #include <cstddef>
      73             : #include <cstdint>
      74             : #include <exception>
      75             : #include <iterator>
      76             : #include <js/Array.h>
      77             : #include <js/RootingAPI.h>
      78             : #include <js/TypeDecls.h>
      79             : #include <js/Value.h>
      80             : #include <limits>
      81             : #include <string>
      82             : #include <utility>
      83             : #include <vector>
      84             : 
      85             : class CFileInfo;
      86             : 
      87             : #ifdef _MSC_VER
      88             : # pragma warning(disable: 4458) // Declaration hides class member.
      89             : #endif
      90             : 
      91             : namespace
      92             : {
      93           0 :     void InitGame()
      94             :     {
      95           0 :         if (g_Game)
      96             :         {
      97           0 :             delete g_Game;
      98           0 :             g_Game = NULL;
      99             :         }
     100             : 
     101           0 :         g_Game = new CGame(false);
     102             : 
     103             :         // Default to player 1 for playtesting
     104           0 :         g_Game->SetPlayerID(1);
     105           0 :     }
     106             : 
     107           0 :     void StartGame(JS::MutableHandleValue attrs)
     108             :     {
     109           0 :         g_Game->StartGame(attrs, "");
     110             : 
     111             :         // TODO: Non progressive load can fail - need a decent way to handle this
     112           0 :         PS::Loader::NonprogressiveLoad();
     113             : 
     114             :         // Disable fog-of-war - this must be done before starting the game,
     115             :         // as visual actors cache their visibility state on first render.
     116           0 :         CmpPtr<ICmpRangeManager> cmpRangeManager(*g_Game->GetSimulation2(), SYSTEM_ENTITY);
     117           0 :         if (cmpRangeManager)
     118           0 :             cmpRangeManager->SetLosRevealWholeMapForAll(true);
     119             : 
     120           0 :         PSRETURN ret = g_Game->ReallyStartGame();
     121           0 :         ENSURE(ret == PSRETURN_OK);
     122           0 :     }
     123             : }
     124             : 
     125             : namespace AtlasMessage {
     126             : 
     127           0 : QUERYHANDLER(GenerateMap)
     128             : {
     129           0 :     try
     130             :     {
     131           0 :         InitGame();
     132             : 
     133             :         // Random map
     134           0 :         const Script::Interface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface();
     135           0 :         Script::Request rq(scriptInterface);
     136             : 
     137           0 :         JS::RootedValue settings(rq.cx);
     138           0 :         Script::ParseJSON(rq, *msg->settings, &settings);
     139           0 :         Script::SetProperty(rq, settings, "mapType", "random");
     140             : 
     141           0 :         JS::RootedValue attrs(rq.cx);
     142           0 :         Script::CreateObject(
     143             :             rq,
     144             :             &attrs,
     145             :             "mapType", "random",
     146           0 :             "script", *msg->filename,
     147             :             "settings", settings);
     148             : 
     149           0 :         StartGame(&attrs);
     150             : 
     151           0 :         msg->status = 0;
     152           0 :     }
     153           0 :     catch (std::exception&)
     154             :     {
     155             :         // Cancel loading
     156           0 :         PS::Loader::Cancel();
     157             : 
     158             :         // Since map generation failed and we don't know why, use the blank map as a fallback
     159             : 
     160           0 :         InitGame();
     161             : 
     162           0 :         const Script::Interface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface();
     163           0 :         Script::Request rq(scriptInterface);
     164             : 
     165             :         // Set up 8-element array of empty objects to satisfy init
     166           0 :         JS::RootedValueArray<8> playerData{rq.cx};
     167             : 
     168           0 :         for (JS::Value& p : playerData.get().elements)
     169             :         {
     170           0 :             JS::RootedValue player(rq.cx);
     171           0 :             Script::CreateObject(rq, &player);
     172           0 :             p = player;
     173           0 :         }
     174             : 
     175           0 :         JS::RootedValue settings(rq.cx);
     176           0 :         Script::CreateObject(
     177             :             rq,
     178             :             &settings,
     179             :             "mapType", "scenario",
     180             :             "PlayerData",
     181           0 :             JS::RootedValue{rq.cx, JS::ObjectValue(*JS::NewArrayObject(rq.cx, playerData))});
     182             : 
     183           0 :         JS::RootedValue attrs(rq.cx);
     184           0 :         Script::CreateObject(
     185             :             rq,
     186             :             &attrs,
     187             :             "mapType", "scenario",
     188             :             "map", "maps/scenarios/_default",
     189             :             "settings", settings);
     190             : 
     191           0 :         StartGame(&attrs);
     192             : 
     193           0 :         msg->status = -1;
     194           0 :     }
     195           0 : }
     196             : 
     197           0 : MESSAGEHANDLER(LoadMap)
     198             : {
     199           0 :     InitGame();
     200             : 
     201           0 :     const Script::Interface& scriptInterface = g_Game->GetSimulation2()->GetScriptInterface();
     202           0 :     Script::Request rq(scriptInterface);
     203             : 
     204             :     // Scenario
     205           0 :     CStrW map = *msg->filename;
     206           0 :     CStrW mapBase = map.BeforeLast(L".pmp"); // strip the file extension, if any
     207             : 
     208           0 :     JS::RootedValue attrs(rq.cx);
     209             : 
     210           0 :     Script::CreateObject(
     211             :         rq,
     212             :         &attrs,
     213             :         "mapType", "scenario",
     214             :         "map", mapBase);
     215             : 
     216           0 :     StartGame(&attrs);
     217           0 : }
     218             : 
     219           0 : MESSAGEHANDLER(ImportHeightmap)
     220             : {
     221           0 :     std::vector<std::uint16_t> heightmap_source;
     222           0 :     if (LoadHeightmapImageOs(*msg->filename, heightmap_source) != INFO::OK)
     223             :     {
     224           0 :         LOGERROR("Failed to decode heightmap.");
     225           0 :         return;
     226             :     }
     227             : 
     228             :     // resize terrain to heightmap size
     229             :     // Notice that the number of tiles/pixels per side of the heightmap image is
     230             :     // one less than the number of vertices per side of the heightmap.
     231           0 :     CTerrain& terrain = g_Game->GetWorld()->GetTerrain();
     232           0 :     const ssize_t newSize = (sqrt(heightmap_source.size()) - 1) / PATCH_SIZE;
     233           0 :     const ssize_t offset = (newSize - terrain.GetPatchesPerSide()) / 2;
     234           0 :     terrain.ResizeAndOffset(newSize, offset, offset);
     235             : 
     236             :     // copy heightmap data into map
     237           0 :     std::uint16_t* const heightmap = g_Game->GetWorld()->GetTerrain().GetHeightMap();
     238           0 :     ENSURE(heightmap_source.size() == (std::size_t) SQR(g_Game->GetWorld()->GetTerrain().GetVerticesPerSide()));
     239           0 :     std::copy(heightmap_source.begin(), heightmap_source.end(), heightmap);
     240             : 
     241             :     // update simulation
     242           0 :     CmpPtr<ICmpTerrain> cmpTerrain(*g_Game->GetSimulation2(), SYSTEM_ENTITY);
     243           0 :     if (cmpTerrain)
     244           0 :         cmpTerrain->ReloadTerrain();
     245             : 
     246           0 :     g_Game->GetView()->GetLOSTexture().MakeDirty();
     247           0 : }
     248             : 
     249           0 : MESSAGEHANDLER(SaveMap)
     250             : {
     251           0 :     CMapWriter writer;
     252           0 :     VfsPath pathname = VfsPath(*msg->filename).ChangeExtension(L".pmp");
     253           0 :     writer.SaveMap(pathname,
     254           0 :         &g_Game->GetWorld()->GetTerrain(),
     255           0 :         &g_Renderer.GetSceneRenderer().GetWaterManager(), &g_Renderer.GetSceneRenderer().GetSkyManager(),
     256             :         &g_LightEnv, g_Game->GetView()->GetCamera(), g_Game->GetView()->GetCinema(),
     257           0 :         &g_Renderer.GetPostprocManager(),
     258             :         g_Game->GetSimulation2());
     259           0 : }
     260             : 
     261           0 : QUERYHANDLER(GetMapSettings)
     262             : {
     263           0 :     msg->settings = g_Game->GetSimulation2()->GetMapSettingsString();
     264           0 : }
     265             : 
     266           0 : BEGIN_COMMAND(SetMapSettings)
     267             : {
     268             :     std::string m_OldSettings, m_NewSettings;
     269             : 
     270           0 :     void SetSettings(const std::string& settings)
     271             :     {
     272           0 :         g_Game->GetSimulation2()->SetMapSettings(settings);
     273             :     }
     274             : 
     275           0 :     void Do()
     276             :     {
     277           0 :         m_OldSettings = g_Game->GetSimulation2()->GetMapSettingsString();
     278           0 :         m_NewSettings = *msg->settings;
     279             : 
     280           0 :         SetSettings(m_NewSettings);
     281           0 :     }
     282             : 
     283             :     // TODO: we need some way to notify the Atlas UI when the settings are changed
     284             :     //  externally, otherwise this will have no visible effect
     285           0 :     void Undo()
     286             :     {
     287             :         // SetSettings(m_OldSettings);
     288           0 :     }
     289             : 
     290           0 :     void Redo()
     291             :     {
     292             :         // SetSettings(m_NewSettings);
     293           0 :     }
     294             : 
     295           0 :     void MergeIntoPrevious(cSetMapSettings* prev)
     296             :     {
     297           0 :         prev->m_NewSettings = m_NewSettings;
     298             :     }
     299             : };
     300           0 : END_COMMAND(SetMapSettings)
     301             : 
     302           0 : MESSAGEHANDLER(LoadPlayerSettings)
     303             : {
     304           0 :     g_Game->GetSimulation2()->LoadPlayerSettings(msg->newplayers);
     305           0 : }
     306             : 
     307           0 : QUERYHANDLER(GetMapSizes)
     308             : {
     309           0 :     msg->sizes = g_Game->GetSimulation2()->GetMapSizes();
     310           0 : }
     311             : 
     312           0 : QUERYHANDLER(RasterizeMinimap)
     313             : {
     314             :     // TODO: remove the code duplication of the rasterization algorithm, using
     315             :     // CMinimap version.
     316           0 :     const CTerrain& terrain = g_Game->GetWorld()->GetTerrain();
     317           0 :     const ssize_t dimension = terrain.GetVerticesPerSide() - 1;
     318           0 :     const ssize_t bpp = 24;
     319           0 :     const ssize_t imageDataSize = dimension * dimension * (bpp / 8);
     320             : 
     321           0 :     std::vector<std::uint8_t> imageBytes(imageDataSize);
     322             : 
     323           0 :     float shallowPassageHeight = CMiniMapTexture::GetShallowPassageHeight();
     324             : 
     325           0 :     ssize_t w = dimension;
     326           0 :     ssize_t h = dimension;
     327           0 :     const float waterHeight = g_Renderer.GetSceneRenderer().GetWaterManager().m_WaterHeight;
     328             : 
     329           0 :     for (ssize_t j = 0; j < h; ++j)
     330             :     {
     331             :         // Work backwards to vertically flip the image.
     332           0 :         ssize_t position = 3 * (h - j - 1) * dimension;
     333           0 :         for (ssize_t i = 0; i < w; ++i)
     334             :         {
     335           0 :             const float avgHeight = (terrain.GetVertexGroundLevel(i, j)
     336           0 :                 + terrain.GetVertexGroundLevel(i + 1, j)
     337           0 :                 + terrain.GetVertexGroundLevel(i, j + 1)
     338           0 :                 + terrain.GetVertexGroundLevel(i + 1, j + 1)
     339           0 :                 ) / 4.0f;
     340             : 
     341           0 :             if (avgHeight < waterHeight && avgHeight > waterHeight - shallowPassageHeight)
     342             :             {
     343             :                 // shallow water
     344           0 :                 imageBytes[position++] = 0x70;
     345           0 :                 imageBytes[position++] = 0x98;
     346           0 :                 imageBytes[position++] = 0xc0;
     347             :             }
     348           0 :             else if (avgHeight < waterHeight)
     349             :             {
     350             :                 // Set water as constant color for consistency on different maps
     351           0 :                 imageBytes[position++] = 0x50;
     352           0 :                 imageBytes[position++] = 0x78;
     353           0 :                 imageBytes[position++] = 0xa0;
     354             :             }
     355             :             else
     356             :             {
     357           0 :                 std::uint32_t color = std::numeric_limits<std::uint32_t>::max();
     358           0 :                 const std::uint32_t hmap =
     359           0 :                     static_cast<std::uint32_t>(terrain.GetHeightMap()[j * dimension + i]) >> 8;
     360           0 :                 float scale = hmap / 3.0f + 170.0f / 255.0f;
     361             : 
     362           0 :                 CMiniPatch* const mp = terrain.GetTile(i, j);
     363           0 :                 if (mp)
     364             :                 {
     365           0 :                     CTerrainTextureEntry* tex = mp->GetTextureEntry();
     366           0 :                     if (tex)
     367           0 :                         color = tex->GetBaseColor();
     368             :                 }
     369             : 
     370             :                 // Convert
     371           0 :                 imageBytes[position++] = static_cast<std::uint8_t>(static_cast<float>(
     372           0 :                     color & 0xff) * scale);
     373           0 :                 imageBytes[position++] = static_cast<std::uint8_t>(static_cast<float>(
     374           0 :                     (color >> 8) & 0xff) * scale);
     375           0 :                 imageBytes[position++] = static_cast<std::uint8_t>(static_cast<float>(
     376           0 :                     (color >> 16) & 0xff) * scale);
     377             :             }
     378             :         }
     379             :     }
     380             : 
     381           0 :     msg->imageBytes = std::move(imageBytes);
     382           0 :     msg->dimension = dimension;
     383           0 : }
     384             : 
     385           0 : QUERYHANDLER(GetRMSData)
     386             : {
     387           0 :     msg->data = g_Game->GetSimulation2()->GetRMSData();
     388           0 : }
     389             : 
     390           0 : QUERYHANDLER(ExpandBiomes)
     391             : {
     392           0 :     std::vector<std::string> unexpandedBiomes = *msg->biomes;
     393           0 :     std::vector<std::string> expandedBiomes;
     394           0 :     for (const std::string& toExpand : unexpandedBiomes)
     395             :     {
     396           0 :         if (toExpand.empty())
     397             :         {
     398           0 :             LOGERROR("Got an empty biome");
     399           0 :             continue;
     400           0 :         }
     401           0 :         if (toExpand.back() != '/')
     402             :         {
     403           0 :             expandedBiomes.push_back(toExpand);
     404           0 :             continue;
     405             :         }
     406             : 
     407           0 :         VfsPaths biomesList;
     408           0 :         if (vfs::GetPathnames(g_VFS, "maps/random/rmbiome/" + toExpand, L"*.json", biomesList) ==
     409             :             INFO::OK)
     410             :         {
     411           0 :             std::transform(biomesList.begin(), biomesList.end(), std::back_inserter(expandedBiomes),
     412           0 :                 [&](const VfsPath& biome)
     413             :                 {
     414           0 :                     return toExpand + biome.Basename().string8();
     415             :                 });
     416             :         }
     417             :         else
     418           0 :             LOGERROR("Error reading biome files in {}", toExpand);
     419             : 
     420           0 :     }
     421             : 
     422           0 :     msg->biomes = std::move(expandedBiomes);
     423           0 : }
     424             : 
     425           0 : QUERYHANDLER(GetCurrentMapSize)
     426             : {
     427           0 :     msg->size = g_Game->GetWorld()->GetTerrain().GetTilesPerSide();
     428           0 : }
     429             : 
     430           0 : BEGIN_COMMAND(ResizeMap)
     431             : {
     432           0 :     bool Within(const CFixedVector3D& pos, const int centerX, const int centerZ, const int radius)
     433             :     {
     434           0 :         int dx = abs(pos.X.ToInt_RoundToZero() - centerX);
     435           0 :         if (dx > radius)
     436             :             return false;
     437           0 :         int dz = abs(pos.Z.ToInt_RoundToZero() - centerZ);
     438           0 :         if (dz > radius)
     439             :             return false;
     440           0 :         if (dx + dz <= radius)
     441             :             return true;
     442           0 :         return dx * dx + dz * dz <= radius * radius;
     443             :     }
     444             : 
     445           0 :     struct DeletedObject
     446             :     {
     447             :         entity_id_t entityId;
     448             :         CStr templateName;
     449             :         player_id_t owner;
     450             :         CFixedVector3D pos;
     451             :         CFixedVector3D rot;
     452             :         std::uint32_t actorSeed;
     453             :     };
     454             : 
     455             :     ssize_t m_OldPatches, m_NewPatches;
     456             :     int m_OffsetX, m_OffsetY;
     457             : 
     458             :     std::uint16_t* m_Heightmap;
     459             :     CPatch* m_Patches;
     460             : 
     461             :     std::vector<DeletedObject> m_DeletedObjects;
     462             :     std::vector<std::pair<entity_id_t, CFixedVector3D>> m_OldPositions;
     463             :     std::vector<std::pair<entity_id_t, CFixedVector3D>> m_NewPositions;
     464             : 
     465           0 :     cResizeMap() : m_Heightmap(nullptr), m_Patches(nullptr)
     466             :     {
     467             :     }
     468             : 
     469           0 :     ~cResizeMap()
     470           0 :     {
     471           0 :         delete[] m_Heightmap;
     472           0 :         delete[] m_Patches;
     473           0 :     }
     474             : 
     475           0 :     void MakeDirty()
     476             :     {
     477           0 :         CmpPtr<ICmpTerrain> cmpTerrain(*g_Game->GetSimulation2(), SYSTEM_ENTITY);
     478           0 :         if (cmpTerrain)
     479           0 :             cmpTerrain->ReloadTerrain();
     480             : 
     481             :         // The LOS texture won't normally get updated when running Atlas
     482             :         // (since there's no simulation updates), so explicitly dirty it
     483           0 :         g_Game->GetView()->GetLOSTexture().MakeDirty();
     484           0 :     }
     485             : 
     486           0 :     void ResizeTerrain(ssize_t patches, int offsetX, int offsetY)
     487             :     {
     488           0 :         CTerrain& terrain = g_Game->GetWorld()->GetTerrain();
     489           0 :         terrain.ResizeAndOffset(patches, -offsetX, -offsetY);
     490           0 :     }
     491             : 
     492           0 :     void DeleteObjects(const std::vector<DeletedObject>& deletedObjects)
     493             :     {
     494           0 :         for (const DeletedObject& deleted : deletedObjects)
     495           0 :             g_Game->GetSimulation2()->DestroyEntity(deleted.entityId);
     496             : 
     497           0 :         g_Game->GetSimulation2()->FlushDestroyedEntities();
     498           0 :     }
     499             : 
     500           0 :     void RestoreObjects(const std::vector<DeletedObject>& deletedObjects)
     501             :     {
     502           0 :         CSimulation2& sim = *g_Game->GetSimulation2();
     503             : 
     504           0 :         for (const DeletedObject& deleted : deletedObjects)
     505             :         {
     506           0 :             entity_id_t ent = sim.AddEntity(deleted.templateName.FromUTF8(), deleted.entityId);
     507           0 :             if (ent == INVALID_ENTITY)
     508             :             {
     509           0 :                 LOGERROR("Failed to load entity template '{}'", deleted.templateName);
     510             :             }
     511             :             else
     512             :             {
     513           0 :                 CmpPtr<ICmpPosition> cmpPosition(sim, deleted.entityId);
     514           0 :                 if (cmpPosition)
     515             :                 {
     516           0 :                     cmpPosition->JumpTo(deleted.pos.X, deleted.pos.Z);
     517           0 :                     cmpPosition->SetXZRotation(deleted.rot.X, deleted.rot.Z);
     518           0 :                     cmpPosition->SetYRotation(deleted.rot.Y);
     519             :                 }
     520             : 
     521           0 :                 CmpPtr<ICmpOwnership> cmpOwnership(sim, deleted.entityId);
     522           0 :                 if (cmpOwnership)
     523           0 :                     cmpOwnership->SetOwner(deleted.owner);
     524             : 
     525           0 :                 CmpPtr<ICmpVisual> cmpVisual(sim, deleted.entityId);
     526           0 :                 if (cmpVisual)
     527           0 :                     cmpVisual->SetActorSeed(deleted.actorSeed);
     528             :             }
     529             :         }
     530           0 :     }
     531             : 
     532           0 :     void SetMovedEntitiesPosition(const std::vector<std::pair<entity_id_t, CFixedVector3D>>& movedObjects)
     533             :     {
     534           0 :         for (const std::pair<entity_id_t, CFixedVector3D>& obj : movedObjects)
     535             :         {
     536           0 :             const entity_id_t id = obj.first;
     537           0 :             const CFixedVector3D position = obj.second;
     538           0 :             CmpPtr<ICmpPosition> cmpPosition(*g_Game->GetSimulation2(), id);
     539           0 :             ENSURE(cmpPosition);
     540           0 :             cmpPosition->JumpTo(position.X, position.Z);
     541             :         }
     542           0 :     }
     543             : 
     544           0 :     void Do()
     545             :     {
     546           0 :         CSimulation2& sim = *g_Game->GetSimulation2();
     547           0 :         CmpPtr<ICmpTemplateManager> cmpTemplateManager(sim, SYSTEM_ENTITY);
     548           0 :         ENSURE(cmpTemplateManager);
     549             : 
     550           0 :         CmpPtr<ICmpTerrain> cmpTerrain(sim, SYSTEM_ENTITY);
     551           0 :         if (!cmpTerrain)
     552             :         {
     553           0 :             m_OldPatches = m_NewPatches = 0;
     554           0 :             m_OffsetX = m_OffsetY = 0;
     555             :         }
     556             :         else
     557             :         {
     558           0 :             m_OldPatches = static_cast<ssize_t>(cmpTerrain->GetTilesPerSide() / PATCH_SIZE);
     559           0 :             m_NewPatches = msg->tiles / PATCH_SIZE;
     560           0 :             m_OffsetX = msg->offsetX / PATCH_SIZE;
     561             :             // Need to flip direction of vertical offset, due to screen mapping order.
     562           0 :             m_OffsetY = -(msg->offsetY / PATCH_SIZE);
     563             : 
     564           0 :             CTerrain* terrain = cmpTerrain->GetCTerrain();
     565           0 :             m_Heightmap = new std::uint16_t[(m_OldPatches * PATCH_SIZE + 1) * (m_OldPatches * PATCH_SIZE + 1)];
     566           0 :             std::copy_n(terrain->GetHeightMap(), (m_OldPatches * PATCH_SIZE + 1) * (m_OldPatches * PATCH_SIZE + 1), m_Heightmap);
     567           0 :             m_Patches = new CPatch[m_OldPatches * m_OldPatches];
     568           0 :             for (ssize_t j = 0; j < m_OldPatches; ++j)
     569           0 :                 for (ssize_t i = 0; i < m_OldPatches; ++i)
     570             :                 {
     571           0 :                     CPatch& src = *(terrain->GetPatch(i, j));
     572           0 :                     CPatch& dst = m_Patches[j * m_OldPatches + i];
     573           0 :                     std::copy_n(&src.m_MiniPatches[0][0], PATCH_SIZE * PATCH_SIZE, &dst.m_MiniPatches[0][0]);
     574             :                 }
     575             :         }
     576             : 
     577           0 :         const int radiusInTerrainUnits = m_NewPatches * PATCH_SIZE * TERRAIN_TILE_SIZE / 2 * (1.f - 1e-6f);
     578             :         // Opposite direction offset, as we move the destination onto the source, not the source into the destination.
     579           0 :         const int mapCenterX = (m_OldPatches / 2 - m_OffsetX) * PATCH_SIZE * TERRAIN_TILE_SIZE;
     580           0 :         const int mapCenterZ = (m_OldPatches / 2 - m_OffsetY) * PATCH_SIZE * TERRAIN_TILE_SIZE;
     581             :         // The offset to move units by is opposite the direction the map is moved, and from the corner.
     582           0 :         const int offsetX = ((m_NewPatches - m_OldPatches) / 2 + m_OffsetX) * PATCH_SIZE * TERRAIN_TILE_SIZE;
     583           0 :         const int offsetZ = ((m_NewPatches - m_OldPatches) / 2 + m_OffsetY) * PATCH_SIZE * TERRAIN_TILE_SIZE;
     584           0 :         const CFixedVector3D offset = CFixedVector3D(fixed::FromInt(offsetX), fixed::FromInt(0), fixed::FromInt(offsetZ));
     585             : 
     586           0 :         const CSimulation2::InterfaceListUnordered& ents = sim.GetEntitiesWithInterfaceUnordered(IID_Selectable);
     587           0 :         for (const std::pair<const entity_id_t, IComponent*>& ent : ents)
     588             :         {
     589           0 :             const entity_id_t entityId = ent.first;
     590           0 :             CmpPtr<ICmpPosition> cmpPosition(sim, entityId);
     591             : 
     592           0 :             if (cmpPosition && cmpPosition->IsInWorld() && Within(cmpPosition->GetPosition(), mapCenterX, mapCenterZ, radiusInTerrainUnits))
     593             :             {
     594           0 :                 CFixedVector3D position = cmpPosition->GetPosition();
     595             : 
     596           0 :                 m_NewPositions.emplace_back(entityId, position + offset);
     597           0 :                 m_OldPositions.emplace_back(entityId, position);
     598             :             }
     599             :             else
     600             :             {
     601           0 :                 DeletedObject deleted;
     602           0 :                 deleted.entityId = entityId;
     603           0 :                 deleted.templateName = cmpTemplateManager->GetCurrentTemplateName(entityId);
     604             : 
     605             :                 // If the entity has a position, but the ending position is not valid;
     606           0 :                 if (cmpPosition)
     607             :                 {
     608           0 :                     deleted.pos = cmpPosition->GetPosition();
     609           0 :                     deleted.rot = cmpPosition->GetRotation();
     610             :                 }
     611             : 
     612           0 :                 CmpPtr<ICmpOwnership> cmpOwnership(sim, entityId);
     613           0 :                 if (cmpOwnership)
     614           0 :                     deleted.owner = cmpOwnership->GetOwner();
     615             : 
     616           0 :                 CmpPtr<ICmpVisual> cmpVisual(sim, deleted.entityId);
     617           0 :                 if (cmpVisual)
     618           0 :                     deleted.actorSeed = cmpVisual->GetActorSeed();
     619             : 
     620           0 :                 m_DeletedObjects.push_back(deleted);
     621           0 :             }
     622             :         }
     623             : 
     624           0 :         DeleteObjects(m_DeletedObjects);
     625           0 :         ResizeTerrain(m_NewPatches, m_OffsetX, m_OffsetY);
     626           0 :         SetMovedEntitiesPosition(m_NewPositions);
     627           0 :         MakeDirty();
     628           0 :     }
     629             : 
     630           0 :     void Undo()
     631             :     {
     632           0 :         if (m_Heightmap == nullptr || m_Patches == nullptr)
     633             :         {
     634             :             // If there previously was no data, just resize to old (probably not originally valid).
     635           0 :             ResizeTerrain(m_OldPatches, -m_OffsetX, -m_OffsetY);
     636             :         }
     637             :         else
     638             :         {
     639           0 :             CSimulation2& sim = *g_Game->GetSimulation2();
     640           0 :             CmpPtr<ICmpTerrain> cmpTerrain(sim, SYSTEM_ENTITY);
     641           0 :             CTerrain* terrain = cmpTerrain->GetCTerrain();
     642             : 
     643           0 :             terrain->Initialize(m_OldPatches, m_Heightmap);
     644             :             // Copy terrain data back.
     645           0 :             for (ssize_t j = 0; j < m_OldPatches; ++j)
     646           0 :                 for (ssize_t i = 0; i < m_OldPatches; ++i)
     647             :                 {
     648           0 :                     CPatch& src = m_Patches[j * m_OldPatches + i];
     649           0 :                     CPatch& dst = *(terrain->GetPatch(i, j));
     650           0 :                     std::copy_n(&src.m_MiniPatches[0][0], PATCH_SIZE * PATCH_SIZE, &dst.m_MiniPatches[0][0]);
     651             :                 }
     652             :         }
     653           0 :         RestoreObjects(m_DeletedObjects);
     654           0 :         SetMovedEntitiesPosition(m_OldPositions);
     655           0 :         MakeDirty();
     656           0 :     }
     657             : 
     658           0 :     void Redo()
     659             :     {
     660           0 :         DeleteObjects(m_DeletedObjects);
     661           0 :         ResizeTerrain(m_NewPatches, m_OffsetX, m_OffsetY);
     662           0 :         SetMovedEntitiesPosition(m_NewPositions);
     663           0 :         MakeDirty();
     664           0 :     }
     665             : };
     666           0 : END_COMMAND(ResizeMap)
     667             : 
     668           0 : QUERYHANDLER(VFSFileExists)
     669             : {
     670           0 :     msg->exists = VfsFileExists(*msg->path);
     671           0 : }
     672             : 
     673           0 : QUERYHANDLER(VFSFileRealPath)
     674             : {
     675           0 :     VfsPath pathname(*msg->path);
     676           0 :     if (pathname.empty())
     677           0 :         return;
     678           0 :     OsPath realPathname;
     679           0 :     if (g_VFS->GetRealPath(pathname, realPathname) == INFO::OK)
     680           0 :         msg->realPath = realPathname.string();
     681           0 : }
     682             : 
     683           0 : static Status AddToFilenames(const VfsPath& pathname, const CFileInfo& /*fileInfo*/, const uintptr_t cbData)
     684             : {
     685           0 :     std::vector<std::wstring>& filenames = *(std::vector<std::wstring>*)cbData;
     686           0 :     filenames.push_back(pathname.string().c_str());
     687           0 :     return INFO::OK;
     688             : }
     689             : 
     690           0 : QUERYHANDLER(GetMapList)
     691             : {
     692             : #define GET_FILE_LIST(path, list) \
     693             :     std::vector<std::wstring> list; \
     694             :     vfs::ForEachFile(g_VFS, path, AddToFilenames, (uintptr_t)&list, L"*.xml", vfs::DIR_RECURSIVE); \
     695             :     msg->list = list;
     696             : 
     697           0 :     GET_FILE_LIST(L"maps/scenarios/", scenarioFilenames);
     698           0 :     GET_FILE_LIST(L"maps/skirmishes/", skirmishFilenames);
     699           0 :     GET_FILE_LIST(L"maps/tutorials/", tutorialFilenames);
     700             : #undef GET_FILE_LIST
     701           0 : }
     702             : 
     703           0 : QUERYHANDLER(GetVictoryConditionData)
     704             : {
     705           0 :     msg->data = g_Game->GetSimulation2()->GetVictoryConditiondData();
     706           0 : }
     707             : 
     708             : }

Generated by: LCOV version 1.16