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 "OverlayRenderer.h"
21 :
22 : #include "graphics/Camera.h"
23 : #include "graphics/Color.h"
24 : #include "graphics/LOSTexture.h"
25 : #include "graphics/Overlay.h"
26 : #include "graphics/RenderableObject.h"
27 : #include "graphics/SColor.h"
28 : #include "graphics/ShaderDefines.h"
29 : #include "graphics/ShaderManager.h"
30 : #include "graphics/ShaderTechnique.h"
31 : #include "graphics/ShaderTechniquePtr.h"
32 : #include "graphics/Texture.h"
33 : #include "graphics/TextureManager.h"
34 : #include "lib/debug.h"
35 : #include "lib/hash.h"
36 : #include "maths/Matrix3D.h"
37 : #include "maths/Vector2D.h"
38 : #include "maths/Vector3D.h"
39 : #include "maths/Vector4D.h"
40 : #include "ps/CStrIntern.h"
41 : #include "ps/CStrInternStatic.h"
42 : #include "ps/Profile.h"
43 : #include "renderer/DebugRenderer.h"
44 : #include "renderer/Renderer.h"
45 : #include "renderer/Scene.h"
46 : #include "renderer/SceneRenderer.h"
47 : #include "renderer/TexturedLineRData.h"
48 : #include "renderer/VertexArray.h"
49 : #include "renderer/backend/Format.h"
50 : #include "renderer/backend/IBuffer.h"
51 : #include "renderer/backend/IDeviceCommandContext.h"
52 : #include "renderer/backend/IShaderProgram.h"
53 : #include "renderer/backend/PipelineState.h"
54 :
55 : #include <array>
56 : #include <cmath>
57 : #include <cstddef>
58 : #include <cstdint>
59 : #include <iterator>
60 : #include <memory>
61 : #include <unordered_map>
62 : #include <utility>
63 : #include <vector>
64 :
65 : namespace Renderer::Backend { class IDevice; }
66 :
67 : namespace
68 : {
69 :
70 10 : struct Shader
71 : {
72 : CShaderTechniquePtr technique, techniqueWireframe;
73 :
74 0 : const CShaderTechniquePtr& GetTechnique() const
75 : {
76 0 : return g_Renderer.GetSceneRenderer().GetOverlayRenderMode() == WIREFRAME
77 0 : ? techniqueWireframe : technique;
78 : }
79 : };
80 :
81 0 : void AdjustOverlayGraphicsPipelineState(
82 : Renderer::Backend::SGraphicsPipelineStateDesc& pipelineStateDesc,
83 : const bool depthTestEnabled)
84 : {
85 0 : pipelineStateDesc.depthStencilState.depthTestEnabled = depthTestEnabled;
86 0 : pipelineStateDesc.depthStencilState.depthWriteEnabled = false;
87 0 : pipelineStateDesc.blendState.enabled = true;
88 0 : pipelineStateDesc.blendState.srcColorBlendFactor = pipelineStateDesc.blendState.srcAlphaBlendFactor =
89 : Renderer::Backend::BlendFactor::SRC_ALPHA;
90 0 : pipelineStateDesc.blendState.dstColorBlendFactor = pipelineStateDesc.blendState.dstAlphaBlendFactor =
91 : Renderer::Backend::BlendFactor::ONE_MINUS_SRC_ALPHA;
92 0 : pipelineStateDesc.blendState.colorBlendOp = pipelineStateDesc.blendState.alphaBlendOp =
93 : Renderer::Backend::BlendOp::ADD;
94 : }
95 :
96 50 : Shader CreateShader(
97 : const CStrIntern name, const CShaderDefines& defines,
98 : const bool depthTestEnabled)
99 : {
100 50 : Shader shader;
101 :
102 100 : shader.technique = g_Renderer.GetShaderManager().LoadEffect(
103 : name, defines,
104 50 : [depthTestEnabled](Renderer::Backend::SGraphicsPipelineStateDesc& pipelineStateDesc)
105 : {
106 0 : AdjustOverlayGraphicsPipelineState(pipelineStateDesc, depthTestEnabled);
107 50 : });
108 100 : shader.techniqueWireframe = g_Renderer.GetShaderManager().LoadEffect(
109 : name, defines,
110 50 : [depthTestEnabled](Renderer::Backend::SGraphicsPipelineStateDesc& pipelineStateDesc)
111 : {
112 0 : AdjustOverlayGraphicsPipelineState(pipelineStateDesc, depthTestEnabled);
113 0 : pipelineStateDesc.rasterizationState.polygonMode = Renderer::Backend::PolygonMode::LINE;
114 50 : });
115 :
116 50 : return shader;
117 0 : }
118 :
119 : /**
120 : * Key used to group quads into batches for more efficient rendering. Currently groups by the combination
121 : * of the main texture and the texture mask, to minimize texture swapping during rendering.
122 : */
123 : struct QuadBatchKey
124 : {
125 0 : QuadBatchKey (const CTexturePtr& texture, const CTexturePtr& textureMask)
126 0 : : m_Texture(texture), m_TextureMask(textureMask)
127 : { }
128 :
129 0 : bool operator==(const QuadBatchKey& other) const
130 : {
131 0 : return (m_Texture == other.m_Texture && m_TextureMask == other.m_TextureMask);
132 : }
133 :
134 : CTexturePtr m_Texture;
135 : CTexturePtr m_TextureMask;
136 : };
137 :
138 : struct QuadBatchHash
139 : {
140 0 : std::size_t operator()(const QuadBatchKey& d) const
141 : {
142 0 : size_t seed = 0;
143 0 : hash_combine(seed, d.m_Texture);
144 0 : hash_combine(seed, d.m_TextureMask);
145 0 : return seed;
146 : }
147 : };
148 :
149 : /**
150 : * Holds information about a single quad rendering batch.
151 : */
152 : class QuadBatchData : public CRenderData
153 : {
154 : public:
155 0 : QuadBatchData() : m_IndicesBase(0), m_NumRenderQuads(0) { }
156 :
157 : /// Holds the quad overlay structures requested to be rendered in this batch. Must be cleared
158 : /// after each frame.
159 : std::vector<SOverlayQuad*> m_Quads;
160 :
161 : /// Start index of this batch into the dedicated quad indices VertexArray (see OverlayInternals).
162 : size_t m_IndicesBase;
163 : /// Amount of quads to actually render in this batch. Potentially (although unlikely to be)
164 : /// different from m_Quads.size() due to restrictions on the total amount of quads that can be
165 : /// rendered. Must be reset after each frame.
166 : size_t m_NumRenderQuads;
167 : };
168 :
169 : } // anonymous namespace
170 :
171 : struct OverlayRendererInternals
172 : {
173 : using QuadBatchMap = std::unordered_map<QuadBatchKey, QuadBatchData, QuadBatchHash>;
174 :
175 : OverlayRendererInternals();
176 10 : ~OverlayRendererInternals() = default;
177 :
178 : Renderer::Backend::IDevice* device = nullptr;
179 :
180 : std::vector<SOverlayLine*> lines;
181 : std::vector<SOverlayTexturedLine*> texlines;
182 : std::vector<SOverlaySprite*> sprites;
183 : std::vector<SOverlayQuad*> quads;
184 : std::vector<SOverlaySphere*> spheres;
185 :
186 : QuadBatchMap quadBatchMap;
187 :
188 : // Dedicated vertex/index buffers for rendering all quads (to within the limits set by
189 : // MAX_QUAD_OVERLAYS).
190 : VertexArray quadVertices;
191 : VertexArray::Attribute quadAttributePos;
192 : VertexArray::Attribute quadAttributeColor;
193 : VertexArray::Attribute quadAttributeUV;
194 : VertexIndexArray quadIndices;
195 :
196 : // Maximum amount of quad overlays we support for rendering. This limit is set to be able to
197 : // render all quads from a single dedicated VB without having to reallocate it, which is much
198 : // faster in the typical case of rendering only a handful of quads. When modifying this value,
199 : // you must take care for the new amount of quads to fit in a single backend buffer (which is
200 : // not likely to be a problem).
201 : static const size_t MAX_QUAD_OVERLAYS = 1024;
202 :
203 : // Sets of commonly-(re)used shader defines.
204 : CShaderDefines defsOverlayLineNormal;
205 : CShaderDefines defsOverlayLineAlwaysVisible;
206 : CShaderDefines defsQuadOverlay;
207 :
208 : Shader shaderTexLineNormal;
209 : Shader shaderTexLineAlwaysVisible;
210 : Shader shaderQuadOverlay;
211 : Shader shaderForegroundOverlay;
212 : Shader shaderOverlaySolid;
213 :
214 : Renderer::Backend::IVertexInputLayout* quadVertexInputLayout = nullptr;
215 : Renderer::Backend::IVertexInputLayout* foregroundVertexInputLayout = nullptr;
216 : Renderer::Backend::IVertexInputLayout* sphereVertexInputLayout = nullptr;
217 :
218 : Renderer::Backend::IVertexInputLayout* texturedLineVertexInputLayout = nullptr;
219 :
220 : // Geometry for a unit sphere
221 : std::vector<float> sphereVertexes;
222 : std::vector<std::uint16_t> sphereIndexes;
223 : void GenerateSphere();
224 :
225 : // Performs one-time setup. Called from CRenderer::Open, after graphics capabilities have
226 : // been detected. Note that no backend buffer must be created before this is called, since
227 : // the shader path and graphics capabilities are not guaranteed to be stable before this
228 : // point.
229 : void Initialize();
230 : };
231 :
232 : const float OverlayRenderer::OVERLAY_VOFFSET = 0.2f;
233 :
234 10 : OverlayRendererInternals::OverlayRendererInternals()
235 10 : : quadVertices(Renderer::Backend::IBuffer::Type::VERTEX,
236 : Renderer::Backend::IBuffer::Usage::DYNAMIC | Renderer::Backend::IBuffer::Usage::TRANSFER_DST),
237 10 : quadIndices(Renderer::Backend::IBuffer::Usage::TRANSFER_DST)
238 : {
239 10 : quadAttributePos.format = Renderer::Backend::Format::R32G32B32_SFLOAT;
240 10 : quadVertices.AddAttribute(&quadAttributePos);
241 :
242 10 : quadAttributeColor.format = Renderer::Backend::Format::R8G8B8A8_UNORM;
243 10 : quadVertices.AddAttribute(&quadAttributeColor);
244 :
245 10 : quadAttributeUV.format = Renderer::Backend::Format::R32G32_SFLOAT;
246 10 : quadVertices.AddAttribute(&quadAttributeUV);
247 :
248 : // Note that we're reusing the textured overlay line shader for the quad overlay rendering. This
249 : // is because their code is almost identical; the only difference is that for the quad overlays
250 : // we want to use a vertex color stream as opposed to an objectColor uniform. To this end, the
251 : // shader has been set up to switch between the two behaviours based on the USE_OBJECTCOLOR define.
252 10 : defsOverlayLineNormal.Add(str_USE_OBJECTCOLOR, str_1);
253 10 : defsOverlayLineAlwaysVisible.Add(str_USE_OBJECTCOLOR, str_1);
254 10 : defsOverlayLineAlwaysVisible.Add(str_IGNORE_LOS, str_1);
255 10 : }
256 :
257 10 : void OverlayRendererInternals::Initialize()
258 : {
259 : // Perform any initialization after graphics capabilities have been detected. Notably,
260 : // only at this point can we safely allocate backend buffer (in contrast to e.g. in the constructor),
261 : // because their creation depends on the shader path, which is not reliably set before this point.
262 :
263 10 : quadVertices.SetNumberOfVertices(MAX_QUAD_OVERLAYS * 4);
264 10 : quadVertices.Layout(); // allocate backing store
265 :
266 10 : quadIndices.SetNumberOfVertices(MAX_QUAD_OVERLAYS * 6);
267 10 : quadIndices.Layout(); // allocate backing store
268 :
269 : // Since the quads in the vertex array are independent and always consist of exactly 4 vertices per quad, the
270 : // indices are always the same; we can therefore fill in all the indices once and pretty much forget about
271 : // them. We then also no longer need its backing store, since we never change any indices afterwards.
272 10 : VertexArrayIterator<std::uint16_t> index = quadIndices.GetIterator();
273 10250 : for (std::uint16_t i = 0; i < static_cast<std::uint16_t>(MAX_QUAD_OVERLAYS); ++i)
274 : {
275 10240 : *index++ = i * 4 + 0;
276 10240 : *index++ = i * 4 + 1;
277 10240 : *index++ = i * 4 + 2;
278 10240 : *index++ = i * 4 + 2;
279 10240 : *index++ = i * 4 + 3;
280 10240 : *index++ = i * 4 + 0;
281 : }
282 10 : quadIndices.Upload();
283 10 : quadIndices.FreeBackingStore();
284 :
285 10 : shaderTexLineNormal =
286 10 : CreateShader(str_overlay_line, defsOverlayLineNormal, true);
287 10 : shaderTexLineAlwaysVisible =
288 10 : CreateShader(str_overlay_line, defsOverlayLineAlwaysVisible, true);
289 10 : shaderQuadOverlay =
290 10 : CreateShader(str_overlay_line, defsQuadOverlay, true);
291 10 : shaderForegroundOverlay =
292 10 : CreateShader(str_foreground_overlay, {}, false);
293 10 : shaderOverlaySolid =
294 10 : CreateShader(str_overlay_solid, {}, true);
295 :
296 10 : const uint32_t quadStride = quadVertices.GetStride();
297 10 : const std::array<Renderer::Backend::SVertexAttributeFormat, 3> quadAttributes{{
298 : {Renderer::Backend::VertexAttributeStream::POSITION,
299 10 : quadAttributePos.format, quadAttributePos.offset, quadStride,
300 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
301 : {Renderer::Backend::VertexAttributeStream::COLOR,
302 10 : quadAttributeColor.format, quadAttributeColor.offset, quadStride,
303 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
304 : {Renderer::Backend::VertexAttributeStream::UV0,
305 10 : quadAttributeUV.format, quadAttributeUV.offset, quadStride,
306 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
307 10 : }};
308 10 : quadVertexInputLayout = g_Renderer.GetVertexInputLayout(quadAttributes);
309 :
310 10 : const std::array<Renderer::Backend::SVertexAttributeFormat, 2> foregroundAttributes{{
311 : {Renderer::Backend::VertexAttributeStream::POSITION,
312 : Renderer::Backend::Format::R32G32B32_SFLOAT, 0, sizeof(float) * 3,
313 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
314 : {Renderer::Backend::VertexAttributeStream::UV0,
315 : Renderer::Backend::Format::R32G32_SFLOAT, 0, sizeof(float) * 2,
316 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 1}
317 : }};
318 10 : foregroundVertexInputLayout = g_Renderer.GetVertexInputLayout(foregroundAttributes);
319 :
320 10 : const std::array<Renderer::Backend::SVertexAttributeFormat, 1> shpereAttributes{{
321 : {Renderer::Backend::VertexAttributeStream::POSITION,
322 : Renderer::Backend::Format::R32G32B32_SFLOAT, 0, sizeof(float) * 3,
323 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
324 : }};
325 10 : sphereVertexInputLayout = g_Renderer.GetVertexInputLayout(shpereAttributes);
326 :
327 10 : texturedLineVertexInputLayout = CTexturedLineRData::GetVertexInputLayout();
328 10 : }
329 :
330 10 : OverlayRenderer::OverlayRenderer()
331 : {
332 10 : m = new OverlayRendererInternals();
333 10 : }
334 :
335 10 : OverlayRenderer::~OverlayRenderer()
336 : {
337 10 : delete m;
338 10 : }
339 :
340 10 : void OverlayRenderer::Initialize()
341 : {
342 10 : m->Initialize();
343 10 : }
344 :
345 0 : void OverlayRenderer::Submit(SOverlayLine* line)
346 : {
347 0 : m->lines.push_back(line);
348 0 : }
349 :
350 0 : void OverlayRenderer::Submit(SOverlayTexturedLine* line)
351 : {
352 : // Simplify the rest of the code by guaranteeing non-empty lines
353 0 : if (line->m_Coords.empty())
354 : return;
355 :
356 0 : m->texlines.push_back(line);
357 : }
358 :
359 0 : void OverlayRenderer::Submit(SOverlaySprite* overlay)
360 : {
361 0 : m->sprites.push_back(overlay);
362 0 : }
363 :
364 0 : void OverlayRenderer::Submit(SOverlayQuad* overlay)
365 : {
366 0 : m->quads.push_back(overlay);
367 0 : }
368 :
369 0 : void OverlayRenderer::Submit(SOverlaySphere* overlay)
370 : {
371 0 : m->spheres.push_back(overlay);
372 0 : }
373 :
374 0 : void OverlayRenderer::EndFrame()
375 : {
376 0 : m->lines.clear();
377 0 : m->texlines.clear();
378 0 : m->sprites.clear();
379 0 : m->quads.clear();
380 0 : m->spheres.clear();
381 :
382 : // this should leave the capacity unchanged, which is okay since it
383 : // won't be very large or very variable
384 :
385 : // Empty the batch rendering data structures, but keep their key mappings around for the next frames
386 0 : for (OverlayRendererInternals::QuadBatchMap::iterator it = m->quadBatchMap.begin(); it != m->quadBatchMap.end(); ++it)
387 : {
388 0 : QuadBatchData& quadBatchData = (it->second);
389 0 : quadBatchData.m_Quads.clear();
390 0 : quadBatchData.m_NumRenderQuads = 0;
391 0 : quadBatchData.m_IndicesBase = 0;
392 : }
393 0 : }
394 :
395 0 : void OverlayRenderer::PrepareForRendering()
396 : {
397 0 : PROFILE3("prepare overlays");
398 :
399 : // This is where we should do something like sort the overlays by
400 : // color/sprite/etc for more efficient rendering
401 :
402 0 : for (size_t i = 0; i < m->texlines.size(); ++i)
403 : {
404 0 : SOverlayTexturedLine* line = m->texlines[i];
405 0 : if (!line->m_RenderData)
406 : {
407 0 : line->m_RenderData = std::make_shared<CTexturedLineRData>();
408 0 : line->m_RenderData->Update(*line);
409 : // We assume the overlay line will get replaced by the caller
410 : // if terrain changes, so we don't need to detect that here and
411 : // call Update again. Also we assume the caller won't change
412 : // any of the parameters after first submitting the line.
413 : }
414 : }
415 :
416 : // Group quad overlays by their texture/mask combination for efficient rendering
417 : // TODO: consider doing this directly in Submit()
418 0 : for (size_t i = 0; i < m->quads.size(); ++i)
419 : {
420 0 : SOverlayQuad* const quad = m->quads[i];
421 :
422 0 : QuadBatchKey textures(quad->m_Texture, quad->m_TextureMask);
423 0 : QuadBatchData& batchRenderData = m->quadBatchMap[textures]; // will create entry if it doesn't already exist
424 :
425 : // add overlay to list of quads
426 0 : batchRenderData.m_Quads.push_back(quad);
427 0 : }
428 :
429 0 : const CVector3D vOffset(0, OverlayRenderer::OVERLAY_VOFFSET, 0);
430 :
431 : // Write quad overlay vertices/indices to VA backing store
432 0 : VertexArrayIterator<CVector3D> vertexPos = m->quadAttributePos.GetIterator<CVector3D>();
433 0 : VertexArrayIterator<SColor4ub> vertexColor = m->quadAttributeColor.GetIterator<SColor4ub>();
434 0 : VertexArrayIterator<float[2]> vertexUV = m->quadAttributeUV.GetIterator<float[2]>();
435 :
436 0 : size_t indicesIdx = 0;
437 0 : size_t totalNumQuads = 0;
438 :
439 0 : for (OverlayRendererInternals::QuadBatchMap::iterator it = m->quadBatchMap.begin(); it != m->quadBatchMap.end(); ++it)
440 : {
441 0 : QuadBatchData& batchRenderData = (it->second);
442 0 : batchRenderData.m_NumRenderQuads = 0;
443 :
444 0 : if (batchRenderData.m_Quads.empty())
445 0 : continue;
446 :
447 : // Remember the current index into the (entire) indices array as our base offset for this batch
448 0 : batchRenderData.m_IndicesBase = indicesIdx;
449 :
450 : // points to the index where each iteration's vertices will be appended
451 0 : for (size_t i = 0; i < batchRenderData.m_Quads.size() && totalNumQuads < OverlayRendererInternals::MAX_QUAD_OVERLAYS; i++)
452 : {
453 0 : const SOverlayQuad* quad = batchRenderData.m_Quads[i];
454 :
455 0 : const SColor4ub quadColor = quad->m_Color.AsSColor4ub();
456 :
457 0 : *vertexPos++ = quad->m_Corners[0] + vOffset;
458 0 : *vertexPos++ = quad->m_Corners[1] + vOffset;
459 0 : *vertexPos++ = quad->m_Corners[2] + vOffset;
460 0 : *vertexPos++ = quad->m_Corners[3] + vOffset;
461 :
462 0 : (*vertexUV)[0] = 0;
463 0 : (*vertexUV)[1] = 0;
464 0 : ++vertexUV;
465 0 : (*vertexUV)[0] = 0;
466 0 : (*vertexUV)[1] = 1;
467 0 : ++vertexUV;
468 0 : (*vertexUV)[0] = 1;
469 0 : (*vertexUV)[1] = 1;
470 0 : ++vertexUV;
471 0 : (*vertexUV)[0] = 1;
472 0 : (*vertexUV)[1] = 0;
473 0 : ++vertexUV;
474 :
475 0 : *vertexColor++ = quadColor;
476 0 : *vertexColor++ = quadColor;
477 0 : *vertexColor++ = quadColor;
478 0 : *vertexColor++ = quadColor;
479 :
480 0 : indicesIdx += 6;
481 :
482 0 : totalNumQuads++;
483 0 : batchRenderData.m_NumRenderQuads++;
484 : }
485 : }
486 :
487 0 : m->quadVertices.Upload();
488 : // don't free the backing store! we'll overwrite it on the next frame to save a reallocation.
489 :
490 0 : m->quadVertices.PrepareForRendering();
491 0 : }
492 :
493 0 : void OverlayRenderer::Upload(
494 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
495 : {
496 0 : m->quadVertices.UploadIfNeeded(deviceCommandContext);
497 0 : m->quadIndices.UploadIfNeeded(deviceCommandContext);
498 0 : }
499 :
500 0 : void OverlayRenderer::RenderOverlaysBeforeWater(
501 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
502 : {
503 0 : PROFILE3("overlays (before)");
504 0 : GPU_SCOPED_LABEL(deviceCommandContext, "Render overlays before water");
505 :
506 0 : for (SOverlayLine* line : m->lines)
507 : {
508 0 : if (line->m_Coords.empty())
509 0 : continue;
510 :
511 0 : g_Renderer.GetDebugRenderer().DrawLine(*deviceCommandContext, line->m_Coords, line->m_Color, static_cast<float>(line->m_Thickness));
512 : }
513 0 : }
514 :
515 0 : void OverlayRenderer::RenderOverlaysAfterWater(
516 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
517 : {
518 0 : PROFILE3("overlays (after)");
519 0 : GPU_SCOPED_LABEL(deviceCommandContext, "Render overlays after water");
520 :
521 0 : RenderTexturedOverlayLines(deviceCommandContext);
522 0 : RenderQuadOverlays(deviceCommandContext);
523 0 : RenderSphereOverlays(deviceCommandContext);
524 0 : }
525 :
526 0 : void OverlayRenderer::RenderTexturedOverlayLines(Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
527 : {
528 0 : if (m->texlines.empty())
529 : return;
530 :
531 0 : CLOSTexture& los = g_Renderer.GetSceneRenderer().GetScene().GetLOSTexture();
532 :
533 0 : if (m->shaderTexLineNormal.technique)
534 : {
535 0 : const CShaderTechniquePtr& shaderTechnique = m->shaderTexLineNormal.GetTechnique();
536 0 : deviceCommandContext->SetGraphicsPipelineState(
537 : shaderTechnique->GetGraphicsPipelineState());
538 0 : deviceCommandContext->BeginPass();
539 :
540 0 : Renderer::Backend::IShaderProgram* shaderTexLineNormal = shaderTechnique->GetShader();
541 :
542 0 : deviceCommandContext->SetTexture(
543 0 : shaderTexLineNormal->GetBindingSlot(str_losTex), los.GetTexture());
544 :
545 0 : const CMatrix3D transform =
546 0 : g_Renderer.GetSceneRenderer().GetViewCamera().GetViewProjection();
547 0 : deviceCommandContext->SetUniform(
548 0 : shaderTexLineNormal->GetBindingSlot(str_transform), transform.AsFloatArray());
549 0 : deviceCommandContext->SetUniform(
550 0 : shaderTexLineNormal->GetBindingSlot(str_losTransform),
551 0 : los.GetTextureMatrix()[0], los.GetTextureMatrix()[12]);
552 :
553 : // batch render only the non-always-visible overlay lines using the normal shader
554 0 : RenderTexturedOverlayLines(deviceCommandContext, shaderTexLineNormal, false);
555 :
556 0 : deviceCommandContext->EndPass();
557 : }
558 :
559 0 : if (m->shaderTexLineAlwaysVisible.technique)
560 : {
561 0 : const CShaderTechniquePtr& shaderTechnique = m->shaderTexLineAlwaysVisible.GetTechnique();
562 0 : deviceCommandContext->SetGraphicsPipelineState(
563 : shaderTechnique->GetGraphicsPipelineState());
564 0 : deviceCommandContext->BeginPass();
565 :
566 0 : Renderer::Backend::IShaderProgram* shaderTexLineAlwaysVisible =
567 0 : shaderTechnique->GetShader();
568 :
569 : // TODO: losTex and losTransform are unused in the always visible shader; see if these can be safely omitted
570 0 : deviceCommandContext->SetTexture(
571 0 : shaderTexLineAlwaysVisible->GetBindingSlot(str_losTex), los.GetTexture());
572 :
573 0 : const CMatrix3D transform =
574 0 : g_Renderer.GetSceneRenderer().GetViewCamera().GetViewProjection();
575 0 : deviceCommandContext->SetUniform(
576 0 : shaderTexLineAlwaysVisible->GetBindingSlot(str_transform), transform.AsFloatArray());
577 0 : deviceCommandContext->SetUniform(
578 0 : shaderTexLineAlwaysVisible->GetBindingSlot(str_losTransform),
579 0 : los.GetTextureMatrix()[0], los.GetTextureMatrix()[12]);
580 :
581 : // batch render only the always-visible overlay lines using the LoS-ignored shader
582 0 : RenderTexturedOverlayLines(deviceCommandContext, shaderTexLineAlwaysVisible, true);
583 :
584 0 : deviceCommandContext->EndPass();
585 : }
586 : }
587 :
588 0 : void OverlayRenderer::RenderTexturedOverlayLines(
589 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
590 : Renderer::Backend::IShaderProgram* shader, bool alwaysVisible)
591 : {
592 0 : for (size_t i = 0; i < m->texlines.size(); ++i)
593 : {
594 0 : SOverlayTexturedLine* line = m->texlines[i];
595 :
596 : // render only those lines matching the requested alwaysVisible status
597 0 : if (!line->m_RenderData || line->m_AlwaysVisible != alwaysVisible)
598 0 : continue;
599 :
600 0 : ENSURE(line->m_RenderData);
601 0 : line->m_RenderData->Render(
602 : deviceCommandContext, m->texturedLineVertexInputLayout, *line, shader);
603 : }
604 0 : }
605 :
606 0 : void OverlayRenderer::RenderQuadOverlays(
607 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
608 : {
609 0 : if (m->quadBatchMap.empty())
610 0 : return;
611 :
612 0 : if (!m->shaderQuadOverlay.technique)
613 : return;
614 :
615 0 : const CShaderTechniquePtr& shaderTechnique = m->shaderQuadOverlay.GetTechnique();
616 0 : deviceCommandContext->SetGraphicsPipelineState(
617 : shaderTechnique->GetGraphicsPipelineState());
618 0 : deviceCommandContext->BeginPass();
619 :
620 0 : Renderer::Backend::IShaderProgram* shader = shaderTechnique->GetShader();
621 :
622 0 : CLOSTexture& los = g_Renderer.GetSceneRenderer().GetScene().GetLOSTexture();
623 :
624 0 : deviceCommandContext->SetTexture(
625 0 : shader->GetBindingSlot(str_losTex), los.GetTexture());
626 0 : deviceCommandContext->SetUniform(
627 0 : shader->GetBindingSlot(str_losTransform),
628 0 : los.GetTextureMatrix()[0], los.GetTextureMatrix()[12]);
629 :
630 0 : const CMatrix3D transform =
631 0 : g_Renderer.GetSceneRenderer().GetViewCamera().GetViewProjection();
632 0 : deviceCommandContext->SetUniform(
633 0 : shader->GetBindingSlot(str_transform), transform.AsFloatArray());
634 :
635 0 : const uint32_t vertexStride = m->quadVertices.GetStride();
636 0 : const uint32_t firstVertexOffset = m->quadVertices.GetOffset() * vertexStride;
637 :
638 0 : deviceCommandContext->SetVertexInputLayout(m->quadVertexInputLayout);
639 :
640 0 : deviceCommandContext->SetVertexBuffer(
641 0 : 0, m->quadVertices.GetBuffer(), firstVertexOffset);
642 0 : deviceCommandContext->SetIndexBuffer(m->quadIndices.GetBuffer());
643 :
644 0 : const int32_t baseTexBindingSlot = shader->GetBindingSlot(str_baseTex);
645 0 : const int32_t maskTexBindingSlot = shader->GetBindingSlot(str_maskTex);
646 :
647 0 : for (OverlayRendererInternals::QuadBatchMap::iterator it = m->quadBatchMap.begin(); it != m->quadBatchMap.end(); ++it)
648 : {
649 0 : QuadBatchData& batchRenderData = it->second;
650 0 : const size_t batchNumQuads = batchRenderData.m_NumRenderQuads;
651 :
652 0 : if (batchNumQuads == 0)
653 0 : continue;
654 :
655 0 : const QuadBatchKey& maskPair = it->first;
656 :
657 0 : maskPair.m_Texture->UploadBackendTextureIfNeeded(deviceCommandContext);
658 0 : maskPair.m_TextureMask->UploadBackendTextureIfNeeded(deviceCommandContext);
659 :
660 0 : deviceCommandContext->SetTexture(
661 0 : baseTexBindingSlot, maskPair.m_Texture->GetBackendTexture());
662 0 : deviceCommandContext->SetTexture(
663 0 : maskTexBindingSlot, maskPair.m_TextureMask->GetBackendTexture());
664 :
665 0 : deviceCommandContext->DrawIndexed(m->quadIndices.GetOffset() + batchRenderData.m_IndicesBase, batchNumQuads * 6, 0);
666 :
667 0 : g_Renderer.GetStats().m_DrawCalls++;
668 0 : g_Renderer.GetStats().m_OverlayTris += batchNumQuads*2;
669 : }
670 :
671 0 : deviceCommandContext->EndPass();
672 : }
673 :
674 0 : void OverlayRenderer::RenderForegroundOverlays(
675 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
676 : const CCamera& viewCamera)
677 : {
678 0 : PROFILE3("overlays (fg)");
679 0 : GPU_SCOPED_LABEL(deviceCommandContext, "Render foreground overlays");
680 :
681 0 : const CVector3D right = -viewCamera.GetOrientation().GetLeft();
682 0 : const CVector3D up = viewCamera.GetOrientation().GetUp();
683 :
684 0 : const CShaderTechniquePtr& shaderTechnique = m->shaderForegroundOverlay.GetTechnique();
685 0 : deviceCommandContext->SetGraphicsPipelineState(
686 : shaderTechnique->GetGraphicsPipelineState());
687 0 : deviceCommandContext->BeginPass();
688 :
689 0 : Renderer::Backend::IShaderProgram* shader = shaderTechnique->GetShader();
690 :
691 0 : const CMatrix3D transform =
692 0 : g_Renderer.GetSceneRenderer().GetViewCamera().GetViewProjection();
693 0 : deviceCommandContext->SetUniform(
694 0 : shader->GetBindingSlot(str_transform), transform.AsFloatArray());
695 :
696 0 : const CVector2D uvs[6] =
697 : {
698 : {0.0f, 1.0f},
699 : {1.0f, 1.0f},
700 : {1.0f, 0.0f},
701 : {0.0f, 1.0f},
702 : {1.0f, 0.0f},
703 : {0.0f, 0.0f},
704 0 : };
705 :
706 0 : deviceCommandContext->SetVertexInputLayout(m->foregroundVertexInputLayout);
707 :
708 0 : deviceCommandContext->SetVertexBufferData(
709 : 1, &uvs[0], std::size(uvs) * sizeof(uvs[0]));
710 :
711 0 : const int32_t baseTexBindingSlot = shader->GetBindingSlot(str_baseTex);
712 0 : const int32_t colorMulBindingSlot = shader->GetBindingSlot(str_colorMul);
713 :
714 0 : for (size_t i = 0; i < m->sprites.size(); ++i)
715 : {
716 0 : SOverlaySprite* sprite = m->sprites[i];
717 0 : if (!i || sprite->m_Texture != m->sprites[i - 1]->m_Texture)
718 : {
719 0 : sprite->m_Texture->UploadBackendTextureIfNeeded(deviceCommandContext);
720 0 : deviceCommandContext->SetTexture(
721 0 : baseTexBindingSlot, sprite->m_Texture->GetBackendTexture());
722 : }
723 :
724 0 : deviceCommandContext->SetUniform(
725 0 : colorMulBindingSlot, sprite->m_Color.AsFloatArray());
726 :
727 0 : const CVector3D position[6] =
728 : {
729 0 : sprite->m_Position + right*sprite->m_X0 + up*sprite->m_Y0,
730 0 : sprite->m_Position + right*sprite->m_X1 + up*sprite->m_Y0,
731 0 : sprite->m_Position + right*sprite->m_X1 + up*sprite->m_Y1,
732 0 : sprite->m_Position + right*sprite->m_X0 + up*sprite->m_Y0,
733 0 : sprite->m_Position + right*sprite->m_X1 + up*sprite->m_Y1,
734 0 : sprite->m_Position + right*sprite->m_X0 + up*sprite->m_Y1
735 : };
736 :
737 0 : deviceCommandContext->SetVertexBufferData(
738 : 0, &position[0].X, std::size(position) * sizeof(position[0]));
739 :
740 0 : deviceCommandContext->Draw(0, 6);
741 :
742 0 : g_Renderer.GetStats().m_DrawCalls++;
743 0 : g_Renderer.GetStats().m_OverlayTris += 2;
744 : }
745 :
746 0 : deviceCommandContext->EndPass();
747 0 : }
748 :
749 0 : static void TessellateSphereFace(const CVector3D& a, std::uint16_t ai, const CVector3D& b,
750 : std::uint16_t bi, const CVector3D& c, std::uint16_t ci, std::vector<float>& vertexes,
751 : std::vector<std::uint16_t>& indexes, int level)
752 : {
753 0 : if (level == 0)
754 : {
755 0 : indexes.push_back(ai);
756 0 : indexes.push_back(bi);
757 0 : indexes.push_back(ci);
758 : }
759 : else
760 : {
761 0 : CVector3D d = (a + b).Normalized();
762 0 : CVector3D e = (b + c).Normalized();
763 0 : CVector3D f = (c + a).Normalized();
764 0 : int di = vertexes.size() / 3; vertexes.push_back(d.X); vertexes.push_back(d.Y); vertexes.push_back(d.Z);
765 0 : int ei = vertexes.size() / 3; vertexes.push_back(e.X); vertexes.push_back(e.Y); vertexes.push_back(e.Z);
766 0 : int fi = vertexes.size() / 3; vertexes.push_back(f.X); vertexes.push_back(f.Y); vertexes.push_back(f.Z);
767 0 : TessellateSphereFace(a,ai, d,di, f,fi, vertexes, indexes, level-1);
768 0 : TessellateSphereFace(d,di, b,bi, e,ei, vertexes, indexes, level-1);
769 0 : TessellateSphereFace(f,fi, e,ei, c,ci, vertexes, indexes, level-1);
770 0 : TessellateSphereFace(d,di, e,ei, f,fi, vertexes, indexes, level-1);
771 : }
772 0 : }
773 :
774 0 : static void TessellateSphere(std::vector<float>& vertexes, std::vector<std::uint16_t>& indexes, int level)
775 : {
776 : /* Start with a tetrahedron, then tessellate */
777 0 : float s = sqrtf(0.5f);
778 : #define VERT(a,b,c) vertexes.push_back(a); vertexes.push_back(b); vertexes.push_back(c);
779 0 : VERT(-s, 0, -s);
780 0 : VERT( s, 0, -s);
781 0 : VERT( s, 0, s);
782 0 : VERT(-s, 0, s);
783 0 : VERT( 0, -1, 0);
784 0 : VERT( 0, 1, 0);
785 : #define FACE(a,b,c) \
786 : TessellateSphereFace( \
787 : CVector3D(vertexes[a*3], vertexes[a*3+1], vertexes[a*3+2]), a, \
788 : CVector3D(vertexes[b*3], vertexes[b*3+1], vertexes[b*3+2]), b, \
789 : CVector3D(vertexes[c*3], vertexes[c*3+1], vertexes[c*3+2]), c, \
790 : vertexes, indexes, level);
791 0 : FACE(0,4,1);
792 0 : FACE(1,4,2);
793 0 : FACE(2,4,3);
794 0 : FACE(3,4,0);
795 0 : FACE(1,5,0);
796 0 : FACE(2,5,1);
797 0 : FACE(3,5,2);
798 0 : FACE(0,5,3);
799 : #undef FACE
800 : #undef VERT
801 0 : }
802 :
803 0 : void OverlayRendererInternals::GenerateSphere()
804 : {
805 0 : if (sphereVertexes.empty())
806 0 : TessellateSphere(sphereVertexes, sphereIndexes, 3);
807 0 : }
808 :
809 0 : void OverlayRenderer::RenderSphereOverlays(
810 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
811 : {
812 0 : PROFILE3("overlays (spheres)");
813 :
814 0 : if (m->spheres.empty() || m->shaderOverlaySolid.technique)
815 0 : return;
816 :
817 0 : const CShaderTechniquePtr& shaderTechnique = m->shaderOverlaySolid.GetTechnique();
818 0 : deviceCommandContext->SetGraphicsPipelineState(
819 : shaderTechnique->GetGraphicsPipelineState());
820 0 : deviceCommandContext->BeginPass();
821 :
822 0 : Renderer::Backend::IShaderProgram* shader = shaderTechnique->GetShader();
823 :
824 0 : const CMatrix3D transform =
825 0 : g_Renderer.GetSceneRenderer().GetViewCamera().GetViewProjection();
826 0 : deviceCommandContext->SetUniform(
827 0 : shader->GetBindingSlot(str_transform), transform.AsFloatArray());
828 :
829 0 : m->GenerateSphere();
830 :
831 0 : deviceCommandContext->SetVertexInputLayout(m->sphereVertexInputLayout);
832 :
833 0 : deviceCommandContext->SetVertexBufferData(
834 0 : 0, m->sphereVertexes.data(), m->sphereVertexes.size() * sizeof(m->sphereVertexes[0]));
835 0 : deviceCommandContext->SetIndexBufferData(
836 0 : m->sphereIndexes.data(), m->sphereIndexes.size() * sizeof(m->sphereIndexes[0]));
837 :
838 0 : for (const SOverlaySphere* sphere : m->spheres)
839 : {
840 0 : const CVector4D instancingTransform{
841 0 : sphere->m_Center.X, sphere->m_Center.Y, sphere->m_Center.Z, sphere->m_Radius};
842 :
843 0 : deviceCommandContext->SetUniform(
844 0 : shader->GetBindingSlot(str_instancingTransform),
845 0 : instancingTransform.AsFloatArray());
846 :
847 0 : deviceCommandContext->SetUniform(
848 0 : shader->GetBindingSlot(str_color), sphere->m_Color.AsFloatArray());
849 :
850 0 : deviceCommandContext->DrawIndexed(0, m->sphereIndexes.size(), 0);
851 :
852 0 : g_Renderer.GetStats().m_DrawCalls++;
853 0 : g_Renderer.GetStats().m_OverlayTris = m->sphereIndexes.size()/3;
854 : }
855 :
856 0 : deviceCommandContext->EndPass();
857 0 : }
|