LCOV - code coverage report
Current view: top level - source/ps - TemplateLoader.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 77 86 89.5 %
Date: 2026-12-03 01:19:39 Functions: 8 9 88.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 "TemplateLoader.h"
      21             : 
      22             : #include "lib/code_annotation.h"
      23             : #include "lib/file/vfs/vfs_util.h"
      24             : #include "lib/path.h"
      25             : #include "lib/status.h"
      26             : #include "lib/utf8.h"
      27             : #include "ps/CLogger.h"
      28             : #include "ps/CStr.h"
      29             : #include "ps/Errors.h"
      30             : #include "ps/Filesystem.h"
      31             : #include "ps/XMB/XMBData.h"
      32             : #include "ps/XMB/XMBStorage.h"
      33             : #include "ps/XML/Xeromyces.h"
      34             : 
      35             : #include <cstddef>
      36             : #include <cstdint>
      37             : #include <utility>
      38             : 
      39             : class CFileInfo;
      40             : 
      41             : static const wchar_t TEMPLATE_ROOT[] = L"simulation/templates/";
      42             : static const wchar_t ACTOR_ROOT[] = L"art/actors/";
      43             : 
      44             : static CParamNode NULL_NODE(false);
      45             : 
      46       15055 : bool CTemplateLoader::LoadTemplateFile(CParamNode& node, std::string_view templateName, bool compositing, int depth)
      47             : {
      48             :     // Handle special case "actor|foo", which does not load 'foo' at all, just uses the name.
      49       15055 :     if (templateName.compare(0, 6, "actor|") == 0)
      50             :     {
      51        5710 :         ConstructTemplateActor(templateName.substr(6), node);
      52        5710 :         return true;
      53             :     }
      54             :     // Handle infinite loops more gracefully than running out of stack space and crashing
      55        9345 :     if (depth > 100)
      56             :     {
      57           6 :         LOGERROR("Probable infinite inheritance loop in entity template '{}'", templateName);
      58           3 :         return false;
      59             :     }
      60             : 
      61        9342 :     size_t pos = templateName.find_first_of('|');
      62        9342 :     if (pos != std::string::npos)
      63             :     {
      64             :         // 'foo|bar' pattern: 'bar' is treated as the parent of 'foo'.
      65         550 :         if (!LoadTemplateFile(node, templateName.substr(pos + 1), false, depth + 1))
      66             :             return false;
      67         549 :         if (!LoadTemplateFile(node, templateName.substr(0, pos), true, depth + 1))
      68             :             return false;
      69             :         return true;
      70             :     }
      71             : 
      72             :     // Load the data we need to apply on the node. This data may contain special modifiers,
      73             :     // such as filters, merges, multiplying the parent values, etc. Applying it to paramnode is destructive.
      74             :     // Find the XML file to load - by default, this assumes the files reside in 'special/filter'.
      75             :     // If not found there, it will be searched for in 'mixins/', then from the root.
      76             :     // The reason for this order is that filters are used at runtime, mixins at load time.
      77       26376 :     std::wstring wtempName = wstring_from_utf8(std::string(templateName) + ".xml");
      78       70336 :     VfsPath path = VfsPath(TEMPLATE_ROOT) / L"special" / L"filter" / wtempName;
      79        8792 :     if (!VfsFileExists(path))
      80       70280 :         path = VfsPath(TEMPLATE_ROOT) / L"mixins" / wtempName;
      81        8792 :     if (!VfsFileExists(path))
      82       48930 :         path = VfsPath(TEMPLATE_ROOT) / wtempName;
      83             : 
      84        8792 :     CXeromyces xero;
      85        8792 :     PSRETURN ok = xero.Load(g_VFS, path);
      86        8792 :     if (ok != PSRETURN_OK)
      87             :         return false; // (Xeromyces already logged an error with the full filename)
      88             : 
      89             :     // If the layer defines an explicit parent, we must load that and apply it before ourselves.
      90        8782 :     int attr_parent = xero.GetAttributeID("parent");
      91        8782 :     CStr parentName = xero.GetRoot().GetAttributes().GetNamedItem(attr_parent);
      92        8782 :     if (!parentName.empty() && !LoadTemplateFile(node, parentName, compositing, depth + 1))
      93             :         return false;
      94             : 
      95             :     // Load the new file into the template data (overriding parent values).
      96             :     // TODO: error handling.
      97        8476 :     CParamNode::LoadXML(node, xero);
      98             :     return true;
      99       41421 : }
     100             : 
     101        1980 : static Status AddToTemplates(const VfsPath& pathname, const CFileInfo&, const uintptr_t cbData)
     102             : {
     103        1980 :     std::vector<std::string>& templates = *(std::vector<std::string>*)cbData;
     104             : 
     105             :     // Strip the .xml extension
     106        1980 :     VfsPath pathstem = pathname.ChangeExtension(L"");
     107             :     // Strip the root from the path
     108        1980 :     std::string name = pathstem.string8().substr(ARRAY_SIZE(TEMPLATE_ROOT)-1);
     109             : 
     110             :     // We want to ignore template_*.xml templates, since they should never be built in the editor
     111        1980 :     if (name.substr(0, 9) == "template_")
     112             :         return INFO::OK;
     113             : 
     114             :     // Also ignore some subfolders.
     115        3531 :     if (name.substr(0, 8) == "special/" || name.substr(0, 7) == "mixins/")
     116             :         return INFO::OK;
     117             : 
     118        1713 :     templates.push_back(name);
     119             :     return INFO::OK;
     120        5940 : }
     121             : 
     122          16 : static Status AddToTemplatesUnrestricted(const VfsPath& pathname, const CFileInfo&, const uintptr_t cbData)
     123             : {
     124          16 :     std::vector<std::string>& templates = *(std::vector<std::string>*)cbData;
     125             : 
     126          16 :     VfsPath pathstem = pathname.ChangeExtension(L"");
     127          16 :     std::string name = pathstem.string8().substr(ARRAY_SIZE(TEMPLATE_ROOT)-1);
     128             : 
     129             :     // We want to ignore template_*.xml templates, since they may be incomplete.
     130          16 :     if (name.substr(0, 9) == "template_")
     131             :         return INFO::OK;
     132             : 
     133          16 :     templates.push_back(name);
     134             :     return INFO::OK;
     135          32 : }
     136             : 
     137        5706 : static Status AddActorToTemplates(const VfsPath& pathname, const CFileInfo&, const uintptr_t cbData)
     138             : {
     139        5706 :     std::vector<std::string>& templates = *(std::vector<std::string>*)cbData;
     140             : 
     141             :     // Strip the root from the path
     142        5706 :     std::wstring name = pathname.string().substr(ARRAY_SIZE(ACTOR_ROOT)-1);
     143             : 
     144       17118 :     templates.push_back("actor|" + std::string(name.begin(), name.end()));
     145        5706 :     return INFO::OK;
     146        5706 : }
     147             : 
     148           0 : bool CTemplateLoader::TemplateExists(const std::string& templateName) const
     149             : {
     150           0 :     size_t pos = templateName.rfind('|');
     151           0 :     std::string baseName(pos != std::string::npos ? templateName.substr(pos+1) : templateName);
     152           0 :     return VfsFileExists(VfsPath(TEMPLATE_ROOT) / wstring_from_utf8(baseName + ".xml"));
     153           0 : }
     154             : 
     155           1 : std::vector<std::string> CTemplateLoader::FindTemplates(const std::string& path, bool includeSubdirectories, ETemplatesType templatesType) const
     156             : {
     157           1 :     std::vector<std::string> templates;
     158             : 
     159           1 :     if (templatesType != SIMULATION_TEMPLATES && templatesType != ACTOR_TEMPLATES && templatesType != ALL_TEMPLATES)
     160             :     {
     161           0 :         LOGERROR("Undefined template type (valid: all, simulation, actor)");
     162           0 :         return templates;
     163             :     }
     164             : 
     165           1 :     size_t flags = includeSubdirectories ? vfs::DIR_RECURSIVE : 0;
     166             : 
     167           1 :     if (templatesType == SIMULATION_TEMPLATES || templatesType == ALL_TEMPLATES)
     168           3 :         WARN_IF_ERR(vfs::ForEachFile(g_VFS, VfsPath(TEMPLATE_ROOT) / path, AddToTemplates, (uintptr_t)&templates, L"*.xml", flags));
     169             : 
     170           1 :     if (templatesType == ACTOR_TEMPLATES || templatesType == ALL_TEMPLATES)
     171           3 :         WARN_IF_ERR(vfs::ForEachFile(g_VFS, VfsPath(ACTOR_ROOT) / path, AddActorToTemplates, (uintptr_t)&templates, L"*.xml", flags));
     172             : 
     173             :     return templates;
     174           0 : }
     175             : 
     176           1 : std::vector<std::string> CTemplateLoader::FindTemplatesUnrestricted(const std::string& path, bool includeSubdirectories) const
     177             : {
     178           1 :     std::vector<std::string> templates;
     179             : 
     180           1 :     size_t flags = includeSubdirectories ? vfs::DIR_RECURSIVE : 0;
     181             : 
     182           4 :     WARN_IF_ERR(vfs::ForEachFile(g_VFS, VfsPath(TEMPLATE_ROOT) / path, AddToTemplatesUnrestricted, (uintptr_t)&templates, L"*.xml", flags));
     183             : 
     184           1 :     return templates;
     185           0 : }
     186             : 
     187       13420 : const CParamNode& CTemplateLoader::GetTemplateFileData(const std::string& templateName)
     188             : {
     189       13420 :     if (std::unordered_map<std::string, CParamNode>::const_iterator it = m_TemplateFileData.find(templateName); it != m_TemplateFileData.end())
     190        5902 :         return it->second;
     191             : 
     192        7518 :     CParamNode ret;
     193        7518 :     if (!LoadTemplateFile(ret, templateName, false, 0))
     194             :     {
     195          26 :         LOGERROR("Failed to load entity template '{}'", templateName);
     196          13 :         return NULL_NODE;
     197             :     }
     198        7505 :     return m_TemplateFileData.insert_or_assign(templateName, ret).first->second;
     199        7518 : }
     200             : 
     201        5710 : void CTemplateLoader::ConstructTemplateActor(std::string_view actorName, CParamNode& out)
     202             : {
     203             :     // Copy the actor template
     204        5710 :     out = GetTemplateFileData("special/actor");
     205             : 
     206             :     // Initialize the actor's name and make it an Atlas selectable entity.
     207        5710 :     std::string source(actorName);
     208        5710 :     std::wstring actorNameW = wstring_from_utf8(source);
     209        5710 :     source = "<Entity>"
     210        5710 :                "<VisualActor><Actor>" + source + "</Actor><ActorOnly/></VisualActor>"
     211             :                // Arbitrary-sized Footprint definition to make actors' selection outlines show up in Atlas.
     212             :                "<Footprint><Circle radius='2.0'/><Height>1.0</Height></Footprint>"
     213             :                  "<Selectable>"
     214             :                    "<EditorOnly/>"
     215             :                    "<Overlay><Texture><MainTexture>128x128/ellipse.png</MainTexture><MainTextureMask>128x128/ellipse_mask.png</MainTextureMask></Texture></Overlay>"
     216             :                  "</Selectable>"
     217        5710 :                "</Entity>";
     218             :     // We'll assume that actorName is valid XML, otherwise this will fail and report the error anyways.
     219        5710 :     CParamNode::LoadXMLString(out, source.c_str(), actorNameW.c_str());
     220       17130 : }

Generated by: LCOV version 1.16