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 "ShaderManager.h"
21 :
22 : #include "graphics/Color.h"
23 : #include "graphics/PreprocessorWrapper.h"
24 : #include "graphics/ShaderProgram.h"
25 : #include "graphics/ShaderTechnique.h"
26 : #include "lib/debug.h"
27 : #include "lib/hash.h"
28 : #include "lib/utf8.h"
29 : #include "ps/algorithm.h"
30 : #include "ps/CLogger.h"
31 : #include "ps/containers/StaticVector.h"
32 : #include "ps/CStrIntern.h"
33 : #include "ps/CStrInternStatic.h"
34 : #include "ps/Errors.h"
35 : #include "ps/Filesystem.h"
36 : #include "ps/Profiler2.h"
37 : #include "ps/XMB/XMBData.h"
38 : #include "ps/XMB/XMBStorage.h"
39 : #include "ps/XML/Xeromyces.h"
40 : #include "renderer/backend/Backend.h"
41 : #include "renderer/backend/CompareOp.h"
42 : #include "renderer/backend/IDevice.h"
43 : #include "renderer/backend/PipelineState.h"
44 :
45 : #include <optional>
46 : #include <utility>
47 : #include <vector>
48 :
49 : #define USE_SHADER_XML_VALIDATION 1
50 :
51 10 : CShaderManager::CShaderManager(Renderer::Backend::IDevice* device)
52 10 : : m_Device(device)
53 : {
54 : #if USE_SHADER_XML_VALIDATION
55 20 : if (!g_Xeromyces.AddValidator(g_VFS, "shader", "shaders/program.rng"))
56 20 : LOGERROR("CShaderManager: failed to load grammar shaders/program.rng");
57 : #endif
58 :
59 : // Allow hotloading of textures
60 10 : RegisterFileReloadFunc(ReloadChangedFileCB, this);
61 10 : }
62 :
63 10 : CShaderManager::~CShaderManager()
64 : {
65 10 : UnregisterFileReloadFunc(ReloadChangedFileCB, this);
66 10 : }
67 :
68 0 : CShaderProgramPtr CShaderManager::LoadProgram(const CStr& name, const CShaderDefines& defines)
69 : {
70 0 : CacheKey key = { name, defines };
71 0 : std::map<CacheKey, CShaderProgramPtr>::iterator it = m_ProgramCache.find(key);
72 0 : if (it != m_ProgramCache.end())
73 0 : return it->second;
74 :
75 0 : CShaderProgramPtr program = CShaderProgram::Create(m_Device, name, defines);
76 0 : if (program)
77 : {
78 0 : for (const VfsPath& path : program->GetFileDependencies())
79 0 : AddProgramFileDependency(program, path);
80 : }
81 : else
82 : {
83 0 : LOGERROR("Failed to load shader '{}'", name);
84 : }
85 :
86 0 : m_ProgramCache[key] = program;
87 0 : return program;
88 0 : }
89 :
90 50 : size_t CShaderManager::EffectCacheKeyHash::operator()(const EffectCacheKey& key) const
91 : {
92 50 : size_t hash = 0;
93 50 : hash_combine(hash, key.name.GetHash());
94 50 : hash_combine(hash, key.defines.GetHash());
95 50 : return hash;
96 : }
97 :
98 0 : bool CShaderManager::EffectCacheKey::operator==(const EffectCacheKey& b) const
99 : {
100 0 : return name == b.name && defines == b.defines;
101 : }
102 :
103 30 : CShaderTechniquePtr CShaderManager::LoadEffect(CStrIntern name)
104 : {
105 30 : return LoadEffect(name, CShaderDefines());
106 : }
107 :
108 30 : CShaderTechniquePtr CShaderManager::LoadEffect(CStrIntern name, const CShaderDefines& defines)
109 : {
110 : // Return the cached effect, if there is one
111 30 : EffectCacheKey key = { name, defines };
112 30 : EffectCacheMap::iterator it = m_EffectCache.find(key);
113 30 : if (it != m_EffectCache.end())
114 0 : return it->second;
115 :
116 : // First time we've seen this key, so construct a new effect:
117 120 : const VfsPath xmlFilename = L"shaders/effects/" + wstring_from_utf8(name.string()) + L".xml";
118 30 : CShaderTechniquePtr tech = std::make_shared<CShaderTechnique>(
119 30 : xmlFilename, defines, PipelineStateDescCallback{});
120 30 : if (!LoadTechnique(tech))
121 : {
122 60 : LOGERROR("Failed to load effect '{}'", name.string());
123 60 : tech = CShaderTechniquePtr();
124 : }
125 :
126 30 : m_EffectCache[key] = tech;
127 30 : return tech;
128 60 : }
129 :
130 100 : CShaderTechniquePtr CShaderManager::LoadEffect(
131 : CStrIntern name, const CShaderDefines& defines, const PipelineStateDescCallback& callback)
132 : {
133 : // We don't cache techniques with callbacks.
134 400 : const VfsPath xmlFilename = L"shaders/effects/" + wstring_from_utf8(name.string()) + L".xml";
135 100 : CShaderTechniquePtr technique = std::make_shared<CShaderTechnique>(xmlFilename, defines, callback);
136 100 : if (!LoadTechnique(technique))
137 : {
138 200 : LOGERROR("Failed to load effect '{}'", name.string());
139 100 : return {};
140 : }
141 100 : return technique;
142 200 : }
143 :
144 130 : bool CShaderManager::LoadTechnique(CShaderTechniquePtr& tech)
145 : {
146 130 : PROFILE2("loading technique");
147 130 : PROFILE2_ATTR("name: %s", tech->GetPath().string8().c_str());
148 :
149 130 : AddTechniqueFileDependency(tech, tech->GetPath());
150 :
151 130 : CXeromyces XeroFile;
152 130 : PSRETURN ret = XeroFile.Load(g_VFS, tech->GetPath());
153 130 : if (ret != PSRETURN_OK)
154 : return false;
155 :
156 : // By default we assume that we have techinques for every dummy shader.
157 0 : if (m_Device->GetBackend() == Renderer::Backend::Backend::DUMMY)
158 : {
159 0 : CShaderProgramPtr shaderProgram = LoadProgram(str_dummy.string(), tech->GetShaderDefines());
160 0 : std::vector<CShaderPass> techPasses;
161 0 : Renderer::Backend::SGraphicsPipelineStateDesc passPipelineStateDesc =
162 0 : Renderer::Backend::MakeDefaultGraphicsPipelineStateDesc();
163 0 : passPipelineStateDesc.shaderProgram = shaderProgram->GetBackendShaderProgram();
164 0 : techPasses.emplace_back(
165 0 : m_Device->CreateGraphicsPipelineState(passPipelineStateDesc), shaderProgram);
166 0 : tech->SetPasses(std::move(techPasses));
167 0 : return true;
168 0 : }
169 :
170 : // Define all the elements and attributes used in the XML file
171 : #define EL(x) int el_##x = XeroFile.GetElementID(#x)
172 : #define AT(x) int at_##x = XeroFile.GetAttributeID(#x)
173 0 : EL(blend);
174 0 : EL(color);
175 0 : EL(compute);
176 0 : EL(cull);
177 0 : EL(define);
178 0 : EL(depth);
179 0 : EL(pass);
180 0 : EL(polygon);
181 0 : EL(require);
182 0 : EL(sort_by_distance);
183 0 : EL(stencil);
184 0 : AT(compare);
185 0 : AT(constant);
186 0 : AT(context);
187 0 : AT(depth_fail);
188 0 : AT(dst);
189 0 : AT(fail);
190 0 : AT(front_face);
191 0 : AT(func);
192 0 : AT(mask);
193 0 : AT(mask_read);
194 0 : AT(mask_red);
195 0 : AT(mask_green);
196 0 : AT(mask_blue);
197 0 : AT(mask_alpha);
198 0 : AT(mode);
199 0 : AT(name);
200 0 : AT(op);
201 0 : AT(pass);
202 0 : AT(reference);
203 0 : AT(shader);
204 0 : AT(shaders);
205 0 : AT(src);
206 0 : AT(test);
207 0 : AT(value);
208 : #undef AT
209 : #undef EL
210 :
211 : // Prepare the preprocessor for conditional tests
212 0 : CPreprocessorWrapper preprocessor;
213 0 : preprocessor.AddDefines(tech->GetShaderDefines());
214 :
215 0 : XMBElement root = XeroFile.GetRoot();
216 :
217 0 : PS::StaticVector<std::string_view, 3> supportedShaders;
218 0 : if (m_Device->GetBackend() == Renderer::Backend::Backend::GL)
219 0 : supportedShaders.emplace_back("glsl");
220 0 : if (m_Device->GetBackend() == Renderer::Backend::Backend::VULKAN)
221 0 : supportedShaders.emplace_back("spirv");
222 :
223 : // Find a first suitable technique that we can use.
224 0 : std::optional<XMBElement> usableTech;
225 0 : std::optional<std::string_view> usableShader;
226 0 : for (XMBElement technique : root.GetChildNodes())
227 : {
228 0 : bool isUsable{true};
229 0 : usableShader.reset();
230 0 : for (XMBElement child : technique.GetChildNodes())
231 : {
232 0 : XMBAttributeList attrs = child.GetAttributes();
233 :
234 : // TODO: require should be an attribute of the tech and not its child.
235 0 : if (child.GetNodeName() == el_require)
236 : {
237 0 : if (!attrs.GetNamedItem(at_shaders).empty())
238 : {
239 0 : auto it = std::find(supportedShaders.begin(), supportedShaders.end(), std::string_view{attrs.GetNamedItem(at_shaders)});
240 0 : if (it != supportedShaders.end())
241 0 : usableShader.emplace(*it);
242 : }
243 0 : else if (!attrs.GetNamedItem(at_context).empty())
244 : {
245 0 : CStr cond = attrs.GetNamedItem(at_context);
246 0 : if (!preprocessor.TestConditional(cond))
247 0 : isUsable = false;
248 0 : }
249 : }
250 : }
251 :
252 0 : if (isUsable && usableShader)
253 : {
254 0 : usableTech.emplace(technique);
255 : break;
256 : }
257 : }
258 :
259 0 : if (!usableTech.has_value())
260 : {
261 0 : debug_warn(L"Can't find a usable technique");
262 0 : return false;
263 : }
264 :
265 0 : tech->SetSortByDistance(false);
266 :
267 0 : const auto loadShaderProgramForTech = [&](const CStr& name, const CShaderDefines& defines)
268 : {
269 0 : CShaderProgramPtr shaderProgram = LoadProgram(CStr{usableShader.value()} + "/" + name.c_str(), defines);
270 0 : if (shaderProgram)
271 : {
272 0 : for (const VfsPath& shaderProgramPath : shaderProgram->GetFileDependencies())
273 0 : AddTechniqueFileDependency(tech, shaderProgramPath);
274 : }
275 0 : return shaderProgram;
276 0 : };
277 :
278 0 : CShaderDefines techDefines = tech->GetShaderDefines();
279 0 : for (XMBElement Child : usableTech->GetChildNodes())
280 : {
281 0 : if (Child.GetNodeName() == el_define)
282 : {
283 0 : techDefines.Add(CStrIntern(Child.GetAttributes().GetNamedItem(at_name)), CStrIntern(Child.GetAttributes().GetNamedItem(at_value)));
284 : }
285 0 : else if (Child.GetNodeName() == el_sort_by_distance)
286 : {
287 0 : tech->SetSortByDistance(true);
288 : }
289 : }
290 : // We don't want to have a shader context depending on the order of define and
291 : // pass tags.
292 : // TODO: we might want to implement that in a proper way via splitting passes
293 : // and tags in different groups in XML.
294 0 : std::vector<CShaderPass> techPasses;
295 0 : for (XMBElement Child : usableTech->GetChildNodes())
296 : {
297 0 : if (Child.GetNodeName() == el_pass)
298 : {
299 0 : CShaderDefines passDefines = techDefines;
300 :
301 0 : Renderer::Backend::SGraphicsPipelineStateDesc passPipelineStateDesc =
302 0 : Renderer::Backend::MakeDefaultGraphicsPipelineStateDesc();
303 :
304 0 : for (XMBElement Element : Child.GetChildNodes())
305 : {
306 0 : if (Element.GetNodeName() == el_define)
307 : {
308 0 : passDefines.Add(CStrIntern(Element.GetAttributes().GetNamedItem(at_name)), CStrIntern(Element.GetAttributes().GetNamedItem(at_value)));
309 : }
310 0 : else if (Element.GetNodeName() == el_blend)
311 : {
312 0 : passPipelineStateDesc.blendState.enabled = true;
313 0 : passPipelineStateDesc.blendState.srcColorBlendFactor = passPipelineStateDesc.blendState.srcAlphaBlendFactor =
314 0 : Renderer::Backend::ParseBlendFactor(Element.GetAttributes().GetNamedItem(at_src));
315 0 : passPipelineStateDesc.blendState.dstColorBlendFactor = passPipelineStateDesc.blendState.dstAlphaBlendFactor =
316 0 : Renderer::Backend::ParseBlendFactor(Element.GetAttributes().GetNamedItem(at_dst));
317 0 : if (!Element.GetAttributes().GetNamedItem(at_op).empty())
318 : {
319 0 : passPipelineStateDesc.blendState.colorBlendOp = passPipelineStateDesc.blendState.alphaBlendOp =
320 0 : Renderer::Backend::ParseBlendOp(Element.GetAttributes().GetNamedItem(at_op));
321 : }
322 0 : if (!Element.GetAttributes().GetNamedItem(at_constant).empty())
323 : {
324 0 : if (!passPipelineStateDesc.blendState.constant.ParseString(
325 0 : Element.GetAttributes().GetNamedItem(at_constant)))
326 : {
327 0 : LOGERROR("Failed to parse blend constant: {}",
328 : Element.GetAttributes().GetNamedItem(at_constant));
329 : }
330 : }
331 : }
332 0 : else if (Element.GetNodeName() == el_color)
333 : {
334 0 : passPipelineStateDesc.blendState.colorWriteMask = 0;
335 : #define MASK_CHANNEL(ATTRIBUTE, VALUE) \
336 : if (Element.GetAttributes().GetNamedItem(ATTRIBUTE) == "TRUE") \
337 : passPipelineStateDesc.blendState.colorWriteMask |= Renderer::Backend::ColorWriteMask::VALUE
338 :
339 0 : MASK_CHANNEL(at_mask_red, RED);
340 0 : MASK_CHANNEL(at_mask_green, GREEN);
341 0 : MASK_CHANNEL(at_mask_blue, BLUE);
342 0 : MASK_CHANNEL(at_mask_alpha, ALPHA);
343 : #undef MASK_CHANNEL
344 : }
345 0 : else if (Element.GetNodeName() == el_cull)
346 : {
347 0 : if (!Element.GetAttributes().GetNamedItem(at_mode).empty())
348 : {
349 0 : passPipelineStateDesc.rasterizationState.cullMode =
350 0 : Renderer::Backend::ParseCullMode(Element.GetAttributes().GetNamedItem(at_mode));
351 : }
352 0 : if (!Element.GetAttributes().GetNamedItem(at_front_face).empty())
353 : {
354 0 : passPipelineStateDesc.rasterizationState.frontFace =
355 0 : Renderer::Backend::ParseFrontFace(Element.GetAttributes().GetNamedItem(at_front_face));
356 : }
357 : }
358 0 : else if (Element.GetNodeName() == el_depth)
359 : {
360 0 : if (!Element.GetAttributes().GetNamedItem(at_test).empty())
361 : {
362 0 : passPipelineStateDesc.depthStencilState.depthTestEnabled =
363 0 : Element.GetAttributes().GetNamedItem(at_test) == "TRUE";
364 : }
365 :
366 0 : if (!Element.GetAttributes().GetNamedItem(at_func).empty())
367 : {
368 0 : passPipelineStateDesc.depthStencilState.depthCompareOp =
369 0 : Renderer::Backend::ParseCompareOp(Element.GetAttributes().GetNamedItem(at_func));
370 : }
371 :
372 0 : if (!Element.GetAttributes().GetNamedItem(at_mask).empty())
373 : {
374 0 : passPipelineStateDesc.depthStencilState.depthWriteEnabled =
375 0 : Element.GetAttributes().GetNamedItem(at_mask) == "true";
376 : }
377 : }
378 0 : else if (Element.GetNodeName() == el_polygon)
379 : {
380 0 : if (!Element.GetAttributes().GetNamedItem(at_mode).empty())
381 : {
382 0 : passPipelineStateDesc.rasterizationState.polygonMode =
383 0 : Renderer::Backend::ParsePolygonMode(Element.GetAttributes().GetNamedItem(at_mode));
384 : }
385 : }
386 0 : else if (Element.GetNodeName() == el_stencil)
387 : {
388 0 : if (!Element.GetAttributes().GetNamedItem(at_test).empty())
389 : {
390 0 : passPipelineStateDesc.depthStencilState.stencilTestEnabled =
391 0 : Element.GetAttributes().GetNamedItem(at_test) == "TRUE";
392 : }
393 :
394 0 : if (!Element.GetAttributes().GetNamedItem(at_reference).empty())
395 : {
396 0 : passPipelineStateDesc.depthStencilState.stencilReference =
397 0 : Element.GetAttributes().GetNamedItem(at_reference).ToULong();
398 : }
399 0 : if (!Element.GetAttributes().GetNamedItem(at_mask_read).empty())
400 : {
401 0 : passPipelineStateDesc.depthStencilState.stencilReadMask =
402 0 : Element.GetAttributes().GetNamedItem(at_mask_read).ToULong();
403 : }
404 0 : if (!Element.GetAttributes().GetNamedItem(at_mask).empty())
405 : {
406 0 : passPipelineStateDesc.depthStencilState.stencilWriteMask =
407 0 : Element.GetAttributes().GetNamedItem(at_mask).ToULong();
408 : }
409 :
410 0 : if (!Element.GetAttributes().GetNamedItem(at_compare).empty())
411 : {
412 0 : passPipelineStateDesc.depthStencilState.stencilFrontFace.compareOp =
413 0 : passPipelineStateDesc.depthStencilState.stencilBackFace.compareOp =
414 0 : Renderer::Backend::ParseCompareOp(Element.GetAttributes().GetNamedItem(at_compare));
415 : }
416 0 : if (!Element.GetAttributes().GetNamedItem(at_fail).empty())
417 : {
418 0 : passPipelineStateDesc.depthStencilState.stencilFrontFace.failOp =
419 0 : passPipelineStateDesc.depthStencilState.stencilBackFace.failOp =
420 0 : Renderer::Backend::ParseStencilOp(Element.GetAttributes().GetNamedItem(at_fail));
421 : }
422 0 : if (!Element.GetAttributes().GetNamedItem(at_pass).empty())
423 : {
424 0 : passPipelineStateDesc.depthStencilState.stencilFrontFace.passOp =
425 0 : passPipelineStateDesc.depthStencilState.stencilBackFace.passOp =
426 0 : Renderer::Backend::ParseStencilOp(Element.GetAttributes().GetNamedItem(at_pass));
427 : }
428 0 : if (!Element.GetAttributes().GetNamedItem(at_depth_fail).empty())
429 : {
430 0 : passPipelineStateDesc.depthStencilState.stencilFrontFace.depthFailOp =
431 0 : passPipelineStateDesc.depthStencilState.stencilBackFace.depthFailOp =
432 0 : Renderer::Backend::ParseStencilOp(Element.GetAttributes().GetNamedItem(at_depth_fail));
433 : }
434 : }
435 : }
436 :
437 : // Load the shader program after we've read all the possibly-relevant <define>s.
438 0 : CShaderProgramPtr shaderProgram =
439 0 : loadShaderProgramForTech(Child.GetAttributes().GetNamedItem(at_shader), passDefines);
440 0 : if (shaderProgram)
441 : {
442 0 : if (tech->GetPipelineStateDescCallback())
443 0 : tech->GetPipelineStateDescCallback()(passPipelineStateDesc);
444 0 : passPipelineStateDesc.shaderProgram = shaderProgram->GetBackendShaderProgram();
445 0 : techPasses.emplace_back(
446 0 : m_Device->CreateGraphicsPipelineState(passPipelineStateDesc), shaderProgram);
447 : }
448 0 : }
449 0 : else if (Child.GetNodeName() == el_compute)
450 : {
451 0 : CShaderProgramPtr shaderProgram =
452 0 : loadShaderProgramForTech(Child.GetAttributes().GetNamedItem(at_shader), techDefines);
453 0 : if (shaderProgram)
454 : {
455 0 : Renderer::Backend::SComputePipelineStateDesc computePipelineStateDesc{};
456 0 : computePipelineStateDesc.shaderProgram = shaderProgram->GetBackendShaderProgram();
457 0 : tech->SetComputePipelineState(
458 0 : m_Device->CreateComputePipelineState(computePipelineStateDesc), shaderProgram);
459 : }
460 0 : }
461 : }
462 :
463 0 : if (!techPasses.empty())
464 0 : tech->SetPasses(std::move(techPasses));
465 :
466 0 : return true;
467 130 : }
468 :
469 0 : size_t CShaderManager::GetNumEffectsLoaded() const
470 : {
471 0 : return m_EffectCache.size();
472 : }
473 :
474 0 : /*static*/ Status CShaderManager::ReloadChangedFileCB(void* param, const VfsPath& path)
475 : {
476 0 : return static_cast<CShaderManager*>(param)->ReloadChangedFile(path);
477 : }
478 :
479 0 : Status CShaderManager::ReloadChangedFile(const VfsPath& path)
480 : {
481 : // Find all shader programs using this file.
482 0 : const auto programs = m_HotloadPrograms.find(path);
483 0 : if (programs != m_HotloadPrograms.end())
484 : {
485 : // Reload all shader programs using this file.
486 0 : for (const std::weak_ptr<CShaderProgram>& ptr : programs->second)
487 0 : if (std::shared_ptr<CShaderProgram> program = ptr.lock())
488 0 : program->Reload();
489 : }
490 :
491 : // Find all shader techinques using this file. We need to reload them after
492 : // shader programs.
493 0 : const auto techniques = m_HotloadTechniques.find(path);
494 0 : if (techniques != m_HotloadTechniques.end())
495 : {
496 : // Reload all shader techinques using this file.
497 0 : for (const std::weak_ptr<CShaderTechnique>& ptr : techniques->second)
498 0 : if (std::shared_ptr<CShaderTechnique> technique = ptr.lock())
499 : {
500 0 : if (!LoadTechnique(technique))
501 : {
502 0 : LOGERROR("Failed to reload technique '{}'",
503 : technique->GetPath().string8());
504 : }
505 0 : }
506 : }
507 :
508 0 : return INFO::OK;
509 : }
510 :
511 130 : void CShaderManager::AddTechniqueFileDependency(const CShaderTechniquePtr& technique, const VfsPath& path)
512 : {
513 130 : m_HotloadTechniques[path].insert(technique);
514 130 : }
515 :
516 0 : void CShaderManager::AddProgramFileDependency(const CShaderProgramPtr& program, const VfsPath& path)
517 : {
518 0 : m_HotloadPrograms[path].insert(program);
519 0 : }
|