File: CCmpTemplateManager.cpp

package info (click to toggle)
0ad 0.0.26-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 130,460 kB
  • sloc: cpp: 261,824; ansic: 198,392; javascript: 19,067; python: 14,557; sh: 7,629; perl: 4,072; xml: 849; makefile: 741; java: 533; ruby: 229; php: 190; pascal: 30; sql: 21; tcl: 4
file content (257 lines) | stat: -rw-r--r-- 7,998 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/* Copyright (C) 2022 Wildfire Games.
 * This file is part of 0 A.D.
 *
 * 0 A.D. is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * 0 A.D. is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "precompiled.h"

#include "simulation2/system/Component.h"
#include "ICmpTemplateManager.h"

#include "simulation2/MessageTypes.h"
#include "simulation2/serialization/SerializedTypes.h"

#include "lib/utf8.h"
#include "ps/CLogger.h"
#include "ps/TemplateLoader.h"
#include "ps/XML/RelaxNG.h"

class CCmpTemplateManager final : public ICmpTemplateManager
{
public:
	static void ClassInit(CComponentManager& componentManager)
	{
		componentManager.SubscribeGloballyToMessageType(MT_Destroy);
	}

	DEFAULT_COMPONENT_ALLOCATOR(TemplateManager)

	static std::string GetSchema()
	{
		return "<a:component type='system'/><empty/>";
	}

	void Init(const CParamNode& UNUSED(paramNode)) override
	{
		m_DisableValidation = false;

		m_Validator.LoadGrammar(GetSimContext().GetComponentManager().GenerateSchema());
		// TODO: handle errors loading the grammar here?
		// TODO: support hotloading changes to the grammar
	}

	void Deinit() override
	{
	}

	void Serialize(ISerializer& serialize) override
	{
		std::map<std::string, std::vector<entity_id_t>> templateMap;

		for (const std::pair<const entity_id_t, std::string>& templateEnt : m_LatestTemplates)
			if (!ENTITY_IS_LOCAL(templateEnt.first))
				templateMap[templateEnt.second].push_back(templateEnt.first);

		Serializer(serialize, "templates", templateMap);
	}

	void Deserialize(const CParamNode& paramNode, IDeserializer& deserialize) override
	{
		Init(paramNode);

		std::map<std::string, std::vector<entity_id_t>> templateMap;
		Serializer(deserialize, "templates", templateMap);
		for (const std::pair<const std::string, std::vector<entity_id_t>>& mapEl : templateMap)
			for (entity_id_t id : mapEl.second)
				m_LatestTemplates[id] = mapEl.first;
	}

	void HandleMessage(const CMessage& msg, bool UNUSED(global)) override
	{
		switch (msg.GetType())
		{
		case MT_Destroy:
		{
			const CMessageDestroy& msgData = static_cast<const CMessageDestroy&> (msg);

			// Clean up m_LatestTemplates so it doesn't record any data for destroyed entities
			m_LatestTemplates.erase(msgData.entity);

			break;
		}
		}
	}

	void DisableValidation() override
	{
		m_DisableValidation = true;
	}

	const CParamNode* LoadTemplate(entity_id_t ent, const std::string& templateName) override;

	const CParamNode* GetTemplate(const std::string& templateName) override;

	const CParamNode* GetTemplateWithoutValidation(const std::string& templateName) override;

	bool TemplateExists(const std::string& templateName) const override;

	const CParamNode* LoadLatestTemplate(entity_id_t ent) override;

	std::string GetCurrentTemplateName(entity_id_t ent) const override;

	std::vector<std::string> FindAllTemplates(bool includeActors) const override;

	std::vector<std::vector<std::wstring>> GetCivData() override;

	std::vector<std::string> FindUsedTemplates() const override;

	std::vector<entity_id_t> GetEntitiesUsingTemplate(const std::string& templateName) const override;

private:
	// Template loader
	CTemplateLoader m_templateLoader;

	// Entity template XML validator
	RelaxNGValidator m_Validator;

	// Disable validation, for test cases
	bool m_DisableValidation;

	// Map from template name to schema validation status.
	// (Some files, e.g. inherited parent templates, may not be valid themselves but we still need to load
	// them and use them; we only reject invalid templates that were requested directly by GetTemplate/etc)
	std::map<std::string, bool> m_TemplateSchemaValidity;

	// Remember the template used by each entity, so we can return them
	// again for deserialization.
	std::map<entity_id_t, std::string> m_LatestTemplates;
};

REGISTER_COMPONENT_TYPE(TemplateManager)

const CParamNode* CCmpTemplateManager::LoadTemplate(entity_id_t ent, const std::string& templateName)
{
	m_LatestTemplates[ent] = templateName;

	return GetTemplate(templateName);
}

const CParamNode* CCmpTemplateManager::GetTemplate(const std::string& templateName)
{
	const CParamNode& fileData = m_templateLoader.GetTemplateFileData(templateName);
	if (!fileData.IsOk())
		return NULL;

	if (!m_DisableValidation)
	{
		// Compute validity, if it's not computed before
		if (m_TemplateSchemaValidity.find(templateName) == m_TemplateSchemaValidity.end())
		{
			m_TemplateSchemaValidity[templateName] = m_Validator.Validate(templateName, fileData.ToXMLString());

			// Show error on the first failure to validate the template
			if (!m_TemplateSchemaValidity[templateName])
				LOGERROR("Failed to validate entity template '%s'", templateName.c_str());
		}
		// Refuse to return invalid templates
		if (!m_TemplateSchemaValidity[templateName])
			return NULL;
	}

	const CParamNode& templateRoot = fileData.GetChild("Entity");
	if (!templateRoot.IsOk())
	{
		// The validator should never let this happen
		LOGERROR("Invalid root element in entity template '%s'", templateName.c_str());
		return NULL;
	}

	return &templateRoot;
}

const CParamNode* CCmpTemplateManager::GetTemplateWithoutValidation(const std::string& templateName)
{
	const CParamNode& templateRoot = m_templateLoader.GetTemplateFileData(templateName).GetChild("Entity");
	if (!templateRoot.IsOk())
		return NULL;

	return &templateRoot;
}

bool CCmpTemplateManager::TemplateExists(const std::string& templateName) const
{
	return m_templateLoader.TemplateExists(templateName);
}

const CParamNode* CCmpTemplateManager::LoadLatestTemplate(entity_id_t ent)
{
	std::map<entity_id_t, std::string>::const_iterator it = m_LatestTemplates.find(ent);
	if (it == m_LatestTemplates.end())
		return NULL;
	return LoadTemplate(ent, it->second);
}

std::string CCmpTemplateManager::GetCurrentTemplateName(entity_id_t ent) const
{
	std::map<entity_id_t, std::string>::const_iterator it = m_LatestTemplates.find(ent);
	if (it == m_LatestTemplates.end())
		return "";
	return it->second;
}

std::vector<std::string> CCmpTemplateManager::FindAllTemplates(bool includeActors) const
{
	ETemplatesType templatesType = includeActors ? ALL_TEMPLATES : SIMULATION_TEMPLATES;
	return m_templateLoader.FindTemplates("", true, templatesType);
}

std::vector<std::vector<std::wstring>> CCmpTemplateManager::GetCivData()
{
	std::vector<std::vector<std::wstring>> data;

	std::vector<std::string> names = m_templateLoader.FindTemplatesUnrestricted("special/players/", false);
	data.reserve(names.size());
	for (const std::string& name : names)
	{
		const CParamNode& identity = GetTemplate(name)->GetChild("Identity");
		data.push_back(std::vector<std::wstring> {
			identity.GetChild("Civ").ToWString(),
			identity.GetChild("GenericName").ToWString()
		});
	}
	return data;
}

std::vector<std::string> CCmpTemplateManager::FindUsedTemplates() const
{
	std::vector<std::string> usedTemplates;
	for (const std::pair<const entity_id_t, std::string>& p : m_LatestTemplates)
		if (std::find(usedTemplates.begin(), usedTemplates.end(), p.second) == usedTemplates.end())
			usedTemplates.push_back(p.second);
	return usedTemplates;
}

/**
 * Get the list of entities using the specified template
 */
std::vector<entity_id_t> CCmpTemplateManager::GetEntitiesUsingTemplate(const std::string& templateName) const
{
	std::vector<entity_id_t> entities;
	for (const std::pair<const entity_id_t, std::string>& p : m_LatestTemplates)
		if (p.second == templateName)
			entities.push_back(p.first);

	return entities;
}