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 "MiniMapTexture.h"
21 :
22 : #include "graphics/LOSTexture.h"
23 : #include "graphics/MiniPatch.h"
24 : #include "graphics/ShaderDefines.h"
25 : #include "graphics/ShaderManager.h"
26 : #include "graphics/ShaderTechnique.h"
27 : #include "graphics/Terrain.h"
28 : #include "graphics/TerrainTextureEntry.h"
29 : #include "graphics/TerritoryTexture.h"
30 : #include "graphics/TextureManager.h"
31 : #include "lib/code_generation.h"
32 : #include "lib/debug.h"
33 : #include "lib/hash.h"
34 : #include "lib/path.h"
35 : #include "lib/timer.h"
36 : #include "maths/MathUtil.h"
37 : #include "maths/Matrix3D.h"
38 : #include "maths/Vector2D.h"
39 : #include "maths/Vector3D.h"
40 : #include "ps/CLogger.h"
41 : #include "ps/CStrIntern.h"
42 : #include "ps/CStrInternStatic.h"
43 : #include "ps/ConfigDB.h"
44 : #include "ps/Filesystem.h"
45 : #include "ps/Game.h"
46 : #include "ps/Profile.h"
47 : #include "ps/World.h"
48 : #include "ps/XML/Xeromyces.h"
49 : #include "renderer/Renderer.h"
50 : #include "renderer/SceneRenderer.h"
51 : #include "renderer/WaterManager.h"
52 : #include "renderer/backend/Backend.h"
53 : #include "renderer/backend/Format.h"
54 : #include "renderer/backend/IBuffer.h"
55 : #include "renderer/backend/IDevice.h"
56 : #include "renderer/backend/IDeviceCommandContext.h"
57 : #include "renderer/backend/IFramebuffer.h"
58 : #include "renderer/backend/IShaderProgram.h"
59 : #include "renderer/backend/ITexture.h"
60 : #include "renderer/backend/PipelineState.h"
61 : #include "renderer/backend/Sampler.h"
62 : #include "simulation2/Simulation2.h"
63 : #include "simulation2/components/ICmpMinimap.h"
64 : #include "simulation2/components/ICmpRangeManager.h"
65 : #include "simulation2/helpers/Position.h"
66 : #include "simulation2/system/Component.h"
67 : #include "simulation2/system/Entity.h"
68 :
69 : #include <algorithm>
70 : #include <array>
71 : #include <bit>
72 : #include <cmath>
73 : #include <cstdint>
74 : #include <iterator>
75 : #include <numbers>
76 : #include <utility>
77 :
78 : namespace
79 : {
80 :
81 : // Set max drawn entities to 64K / 4 for now, which is more than enough.
82 : // 4 is the number of vertices per entity.
83 : // TODO: we should be cleverer about drawing them to reduce clutter,
84 : // f.e. use instancing.
85 : constexpr size_t MAX_ENTITIES_DRAWN = 65536 / 4;
86 :
87 : constexpr size_t MAX_ICON_COUNT = 256;
88 : constexpr size_t MAX_UNIQUE_ICON_COUNT = 64;
89 : constexpr size_t ICON_COMBINING_GRID_SIZE = 10;
90 :
91 : constexpr size_t FINAL_TEXTURE_SIZE = 512;
92 :
93 0 : unsigned int ScaleColor(unsigned int color, float x)
94 : {
95 0 : unsigned int r = unsigned(float(color & 0xff) * x);
96 0 : unsigned int g = unsigned(float((color >> 8) & 0xff) * x);
97 0 : unsigned int b = unsigned(float((color >> 16) & 0xff) * x);
98 0 : return (0xff000000 | b | g << 8 | r << 16);
99 : }
100 :
101 0 : void DrawTexture(
102 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
103 : Renderer::Backend::IVertexInputLayout* quadVertexInputLayout)
104 : {
105 0 : const float quadUVs[] =
106 : {
107 : 0.0f, 0.0f,
108 : 1.0f, 0.0f,
109 : 1.0f, 1.0f,
110 :
111 : 1.0f, 1.0f,
112 : 0.0f, 1.0f,
113 : 0.0f, 0.0f
114 : };
115 0 : const float quadVertices[] =
116 : {
117 : -1.0f, -1.0f,
118 : 1.0f, -1.0f,
119 : 1.0f, 1.0f,
120 :
121 : 1.0f, 1.0f,
122 : -1.0f, 1.0f,
123 : -1.0f, -1.0f,
124 : };
125 :
126 0 : deviceCommandContext->SetVertexInputLayout(quadVertexInputLayout);
127 :
128 0 : deviceCommandContext->SetVertexBufferData(
129 : 0, quadVertices, std::size(quadVertices) * sizeof(quadVertices[0]));
130 0 : deviceCommandContext->SetVertexBufferData(
131 : 1, quadUVs, std::size(quadUVs) * sizeof(quadUVs[0]));
132 :
133 0 : deviceCommandContext->Draw(0, 6);
134 0 : }
135 :
136 0 : struct MinimapUnitVertex
137 : {
138 : // This struct is copyable for convenience and because to move is to copy for primitives.
139 : std::uint8_t r, g, b, a;
140 : CVector2D position;
141 : };
142 :
143 : // Adds a vertex to the passed VertexArray
144 0 : inline void AddEntity(const MinimapUnitVertex& v,
145 : VertexArrayIterator<std::uint8_t[4]>& attrColor,
146 : VertexArrayIterator<float[2]>& attrPos,
147 : const float entityRadius,
148 : const bool useInstancing)
149 : {
150 0 : if (useInstancing)
151 : {
152 0 : (*attrColor)[0] = v.r;
153 0 : (*attrColor)[1] = v.g;
154 0 : (*attrColor)[2] = v.b;
155 0 : (*attrColor)[3] = v.a;
156 0 : ++attrColor;
157 :
158 0 : (*attrPos)[0] = v.position.X;
159 0 : (*attrPos)[1] = v.position.Y;
160 0 : ++attrPos;
161 :
162 0 : return;
163 : }
164 :
165 0 : const CVector2D offsets[4] =
166 : {
167 : {-entityRadius, 0.0f},
168 : {0.0f, -entityRadius},
169 : {entityRadius, 0.0f},
170 : {0.0f, entityRadius}
171 0 : };
172 :
173 0 : for (const CVector2D& offset : offsets)
174 : {
175 0 : (*attrColor)[0] = v.r;
176 0 : (*attrColor)[1] = v.g;
177 0 : (*attrColor)[2] = v.b;
178 0 : (*attrColor)[3] = v.a;
179 0 : ++attrColor;
180 :
181 0 : (*attrPos)[0] = v.position.X + offset.X;
182 0 : (*attrPos)[1] = v.position.Y + offset.Y;
183 0 : ++attrPos;
184 : }
185 : }
186 :
187 : } // anonymous namespace
188 :
189 0 : size_t CMiniMapTexture::CellIconKeyHash::operator()(
190 : const CellIconKey& key) const
191 : {
192 0 : size_t seed = 0;
193 0 : hash_combine(seed, key.path);
194 0 : hash_combine(seed, key.r);
195 0 : hash_combine(seed, key.g);
196 0 : hash_combine(seed, key.b);
197 0 : return seed;
198 : }
199 :
200 0 : bool CMiniMapTexture::CellIconKeyEqual::operator()(
201 : const CellIconKey& lhs, const CellIconKey& rhs) const
202 : {
203 0 : return
204 0 : lhs.path == rhs.path &&
205 0 : lhs.r == rhs.r &&
206 0 : lhs.g == rhs.g &&
207 0 : lhs.b == rhs.b;
208 : }
209 :
210 0 : CMiniMapTexture::CMiniMapTexture(Renderer::Backend::IDevice* device, CSimulation2& simulation)
211 0 : : m_Simulation(simulation), m_IndexArray(Renderer::Backend::IBuffer::Usage::TRANSFER_DST),
212 0 : m_VertexArray(Renderer::Backend::IBuffer::Type::VERTEX,
213 : Renderer::Backend::IBuffer::Usage::DYNAMIC | Renderer::Backend::IBuffer::Usage::TRANSFER_DST),
214 0 : m_InstanceVertexArray(Renderer::Backend::IBuffer::Type::VERTEX,
215 : Renderer::Backend::IBuffer::Usage::TRANSFER_DST),
216 0 : m_PingDuration{CConfigDB::GetIfInitialised("gui.session.minimap.pingduration", 25.0)},
217 0 : m_HalfBlinkDuration{CConfigDB::GetIfInitialised("gui.session.minimap.blinkduration", 1.0) / 2.0}
218 : {
219 : // Register Relax NG validator.
220 0 : g_Xeromyces.AddValidator(g_VFS, "pathfinder", "simulation/data/pathfinder.rng");
221 :
222 0 : m_ShallowPassageHeight = GetShallowPassageHeight();
223 :
224 0 : m_AttributePos.format = Renderer::Backend::Format::R32G32_SFLOAT;
225 0 : m_VertexArray.AddAttribute(&m_AttributePos);
226 :
227 0 : m_AttributeColor.format = Renderer::Backend::Format::R8G8B8A8_UNORM;
228 0 : m_VertexArray.AddAttribute(&m_AttributeColor);
229 :
230 0 : m_VertexArray.SetNumberOfVertices(MAX_ENTITIES_DRAWN * 4);
231 0 : m_VertexArray.Layout();
232 :
233 0 : m_IndexArray.SetNumberOfVertices(MAX_ENTITIES_DRAWN * 6);
234 0 : m_IndexArray.Layout();
235 0 : VertexArrayIterator<std::uint16_t> index = m_IndexArray.GetIterator();
236 0 : for (size_t i = 0; i < m_IndexArray.GetNumberOfVertices(); ++i)
237 0 : *index++ = 0;
238 0 : m_IndexArray.Upload();
239 :
240 0 : VertexArrayIterator<float[2]> attrPos = m_AttributePos.GetIterator<float[2]>();
241 0 : VertexArrayIterator<std::uint8_t[4]> attrColor = m_AttributeColor.GetIterator<std::uint8_t[4]>();
242 0 : for (size_t i = 0; i < m_VertexArray.GetNumberOfVertices(); ++i)
243 : {
244 0 : (*attrColor)[0] = 0;
245 0 : (*attrColor)[1] = 0;
246 0 : (*attrColor)[2] = 0;
247 0 : (*attrColor)[3] = 0;
248 0 : ++attrColor;
249 :
250 0 : (*attrPos)[0] = -10000.0f;
251 0 : (*attrPos)[1] = -10000.0f;
252 :
253 0 : ++attrPos;
254 : }
255 0 : m_VertexArray.Upload();
256 :
257 0 : const std::array<Renderer::Backend::SVertexAttributeFormat, 2> attributes{{
258 : {Renderer::Backend::VertexAttributeStream::POSITION,
259 : Renderer::Backend::Format::R32G32_SFLOAT, 0, sizeof(float) * 2,
260 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
261 : {Renderer::Backend::VertexAttributeStream::UV0,
262 : Renderer::Backend::Format::R32G32_SFLOAT, 0, sizeof(float) * 2,
263 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 1}
264 : }};
265 0 : m_QuadVertexInputLayout = g_Renderer.GetVertexInputLayout(attributes);
266 :
267 0 : m_Flipped = device->GetBackend() == Renderer::Backend::Backend::VULKAN;
268 :
269 0 : const uint32_t stride = m_VertexArray.GetStride();
270 0 : if (device->GetCapabilities().instancing)
271 : {
272 0 : m_UseInstancing = true;
273 :
274 0 : const size_t numberOfCircleSegments = 8;
275 :
276 0 : m_InstanceAttributePosition.format = Renderer::Backend::Format::R32G32_SFLOAT;
277 0 : m_InstanceVertexArray.AddAttribute(&m_InstanceAttributePosition);
278 :
279 0 : m_InstanceVertexArray.SetNumberOfVertices(numberOfCircleSegments * 3);
280 0 : m_InstanceVertexArray.Layout();
281 :
282 0 : VertexArrayIterator<float[2]> attributePosition =
283 0 : m_InstanceAttributePosition.GetIterator<float[2]>();
284 0 : for (size_t segment = 0; segment < numberOfCircleSegments; ++segment)
285 : {
286 0 : const float currentAngle = static_cast<float>(segment) / numberOfCircleSegments * 2.0f * std::numbers::pi_v<float>;
287 0 : const float nextAngle = static_cast<float>(segment + 1) / numberOfCircleSegments * 2.0f * std::numbers::pi_v<float>;
288 :
289 0 : (*attributePosition)[0] = 0.0f;
290 0 : (*attributePosition)[1] = 0.0f;
291 0 : ++attributePosition;
292 :
293 0 : (*attributePosition)[0] = std::cos(currentAngle);
294 0 : (*attributePosition)[1] = std::sin(currentAngle);
295 0 : ++attributePosition;
296 :
297 0 : (*attributePosition)[0] = std::cos(nextAngle);
298 0 : (*attributePosition)[1] = std::sin(nextAngle);
299 0 : ++attributePosition;
300 : }
301 :
302 0 : m_InstanceVertexArray.Upload();
303 0 : m_InstanceVertexArray.FreeBackingStore();
304 :
305 0 : const std::array<Renderer::Backend::SVertexAttributeFormat, 3> attributes{{
306 : {Renderer::Backend::VertexAttributeStream::POSITION,
307 0 : m_InstanceAttributePosition.format, m_InstanceAttributePosition.offset,
308 0 : m_InstanceVertexArray.GetStride(),
309 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
310 : {Renderer::Backend::VertexAttributeStream::UV1,
311 0 : m_AttributePos.format, m_AttributePos.offset, stride,
312 : Renderer::Backend::VertexAttributeRate::PER_INSTANCE, 1},
313 : {Renderer::Backend::VertexAttributeStream::COLOR,
314 0 : m_AttributeColor.format, m_AttributeColor.offset, stride,
315 : Renderer::Backend::VertexAttributeRate::PER_INSTANCE, 1},
316 0 : }};
317 0 : m_EntitiesVertexInputLayout = g_Renderer.GetVertexInputLayout(attributes);
318 : }
319 : else
320 : {
321 0 : const std::array<Renderer::Backend::SVertexAttributeFormat, 2> entitiesAttributes{{
322 : {Renderer::Backend::VertexAttributeStream::POSITION,
323 0 : m_AttributePos.format, m_AttributePos.offset, stride,
324 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
325 : {Renderer::Backend::VertexAttributeStream::COLOR,
326 0 : m_AttributeColor.format, m_AttributeColor.offset, stride,
327 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
328 0 : }};
329 0 : m_EntitiesVertexInputLayout = g_Renderer.GetVertexInputLayout(entitiesAttributes);
330 : }
331 :
332 0 : CShaderDefines baseDefines;
333 0 : baseDefines.Add(str_MINIMAP_BASE, str_1);
334 :
335 0 : m_TerritoryTechnique = g_Renderer.GetShaderManager().LoadEffect(
336 : str_minimap, baseDefines,
337 0 : [](Renderer::Backend::SGraphicsPipelineStateDesc& pipelineStateDesc)
338 : {
339 0 : pipelineStateDesc.blendState.enabled = true;
340 0 : pipelineStateDesc.blendState.srcColorBlendFactor = pipelineStateDesc.blendState.srcAlphaBlendFactor =
341 : Renderer::Backend::BlendFactor::SRC_ALPHA;
342 0 : pipelineStateDesc.blendState.dstColorBlendFactor = pipelineStateDesc.blendState.dstAlphaBlendFactor =
343 : Renderer::Backend::BlendFactor::ONE_MINUS_SRC_ALPHA;
344 0 : pipelineStateDesc.blendState.colorBlendOp = pipelineStateDesc.blendState.alphaBlendOp =
345 : Renderer::Backend::BlendOp::ADD;
346 0 : pipelineStateDesc.blendState.colorWriteMask =
347 : Renderer::Backend::ColorWriteMask::RED |
348 : Renderer::Backend::ColorWriteMask::GREEN |
349 : Renderer::Backend::ColorWriteMask::BLUE;
350 0 : });
351 0 : }
352 :
353 0 : CMiniMapTexture::~CMiniMapTexture()
354 : {
355 0 : DestroyTextures();
356 0 : }
357 :
358 0 : void CMiniMapTexture::RequestRendering()
359 : {
360 0 : m_RenderingRequested = true;
361 0 : }
362 :
363 0 : void CMiniMapTexture::Update(const float /*deltaRealTime*/)
364 : {
365 0 : if (m_WaterHeight != g_Renderer.GetSceneRenderer().GetWaterManager().m_WaterHeight)
366 : {
367 0 : m_TerrainTextureDirty = true;
368 0 : m_FinalTextureDirty = true;
369 : }
370 0 : }
371 :
372 0 : void CMiniMapTexture::Render(
373 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
374 : CLOSTexture& losTexture, CTerritoryTexture& territoryTexture)
375 : {
376 0 : if (!std::exchange(m_RenderingRequested, false))
377 : return;
378 :
379 0 : const CTerrain& terrain = g_Game->GetWorld()->GetTerrain();
380 0 : if (!m_TerrainTexture)
381 0 : CreateTextures(deviceCommandContext, terrain);
382 :
383 0 : if (m_TerrainTextureDirty)
384 0 : RebuildTerrainTexture(deviceCommandContext, terrain);
385 :
386 0 : RenderFinalTexture(deviceCommandContext, losTexture, territoryTexture);
387 : }
388 :
389 0 : void CMiniMapTexture::CreateTextures(
390 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext, const CTerrain& terrain)
391 : {
392 0 : DestroyTextures();
393 :
394 0 : m_MapSize = terrain.GetVerticesPerSide();
395 0 : const size_t textureSize = std::bit_ceil(static_cast<size_t>(m_MapSize));
396 :
397 0 : const Renderer::Backend::Sampler::Desc defaultSamplerDesc =
398 0 : Renderer::Backend::Sampler::MakeDefaultSampler(
399 : Renderer::Backend::Sampler::Filter::LINEAR,
400 : Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE);
401 :
402 0 : Renderer::Backend::IDevice* backendDevice = deviceCommandContext->GetDevice();
403 :
404 : // Create terrain texture
405 0 : m_TerrainTexture = backendDevice->CreateTexture2D("MiniMapTerrainTexture",
406 : Renderer::Backend::ITexture::Usage::TRANSFER_DST |
407 : Renderer::Backend::ITexture::Usage::SAMPLED,
408 0 : Renderer::Backend::Format::R8G8B8A8_UNORM, textureSize, textureSize, defaultSamplerDesc);
409 :
410 : // Initialise texture with solid black, for the areas we don't
411 : // overwrite with uploading later.
412 0 : std::unique_ptr<std::uint32_t[]> texData = std::make_unique<std::uint32_t[]>(textureSize * textureSize);
413 0 : for (size_t i = 0; i < textureSize * textureSize; ++i)
414 0 : texData[i] = 0xFF000000;
415 0 : deviceCommandContext->UploadTexture(
416 : m_TerrainTexture.get(), Renderer::Backend::Format::R8G8B8A8_UNORM,
417 0 : texData.get(), textureSize * textureSize * 4);
418 0 : texData.reset();
419 :
420 0 : m_TerrainData = std::make_unique<std::uint32_t[]>((m_MapSize - 1) * (m_MapSize - 1));
421 :
422 0 : m_FinalTexture = g_Renderer.GetTextureManager().WrapBackendTexture(
423 0 : backendDevice->CreateTexture2D("MiniMapFinalTexture",
424 : Renderer::Backend::ITexture::Usage::SAMPLED |
425 : Renderer::Backend::ITexture::Usage::COLOR_ATTACHMENT,
426 : Renderer::Backend::Format::R8G8B8A8_UNORM,
427 0 : FINAL_TEXTURE_SIZE, FINAL_TEXTURE_SIZE, defaultSamplerDesc));
428 :
429 0 : Renderer::Backend::SColorAttachment colorAttachment{};
430 0 : colorAttachment.texture = m_FinalTexture->GetBackendTexture();
431 0 : colorAttachment.loadOp = Renderer::Backend::AttachmentLoadOp::DONT_CARE;
432 0 : colorAttachment.storeOp = Renderer::Backend::AttachmentStoreOp::STORE;
433 0 : colorAttachment.clearColor = CColor{0.0f, 0.0f, 0.0f, 0.0f};
434 0 : m_FinalTextureFramebuffer = backendDevice->CreateFramebuffer(
435 0 : "MiniMapFinalFramebuffer", &colorAttachment, nullptr);
436 0 : ENSURE(m_FinalTextureFramebuffer);
437 0 : }
438 :
439 0 : void CMiniMapTexture::DestroyTextures()
440 : {
441 0 : m_TerrainTexture.reset();
442 0 : m_FinalTexture.reset();
443 0 : m_TerrainData.reset();
444 0 : }
445 :
446 0 : void CMiniMapTexture::RebuildTerrainTexture(
447 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
448 : const CTerrain& terrain)
449 : {
450 0 : const std::uint32_t x = 0;
451 0 : const std::uint32_t y = 0;
452 0 : const std::uint32_t width = m_MapSize - 1;
453 0 : const std::uint32_t height = m_MapSize - 1;
454 :
455 0 : m_WaterHeight = g_Renderer.GetSceneRenderer().GetWaterManager().m_WaterHeight;
456 0 : m_TerrainTextureDirty = false;
457 :
458 0 : for (std::uint32_t j = 0; j < height; ++j)
459 : {
460 0 : std::uint32_t* dataPtr = m_TerrainData.get() + ((y + j) * width) + x;
461 0 : for (std::uint32_t i = 0; i < width; ++i)
462 : {
463 0 : const float avgHeight = (
464 0 : terrain.GetVertexGroundLevel(static_cast<int>(i), static_cast<int>(j))
465 0 : + terrain.GetVertexGroundLevel(static_cast<int>(i+1), static_cast<int>(j))
466 0 : + terrain.GetVertexGroundLevel(static_cast<int>(i), static_cast<int>(j+1))
467 0 : + terrain.GetVertexGroundLevel(static_cast<int>(i+1), static_cast<int>(j+1))
468 0 : ) / 4.0f;
469 :
470 0 : if (avgHeight < m_WaterHeight && avgHeight > m_WaterHeight - m_ShallowPassageHeight)
471 : {
472 : // shallow water
473 0 : *dataPtr++ = 0xffc09870;
474 : }
475 0 : else if (avgHeight < m_WaterHeight)
476 : {
477 : // Set water as constant color for consistency on different maps
478 0 : *dataPtr++ = 0xffa07850;
479 : }
480 : else
481 : {
482 0 : const int hmap =
483 0 : static_cast<int>(terrain.GetHeightMap()[(y + j) * m_MapSize + x + i]) >> 8;
484 0 : int val = (hmap / 3) + 170;
485 :
486 0 : std::uint32_t color = 0xFFFFFFFF;
487 :
488 0 : CMiniPatch* const mp = terrain.GetTile(x + i, y + j);
489 0 : if (mp)
490 : {
491 0 : CTerrainTextureEntry* tex = mp->GetTextureEntry();
492 0 : if (tex)
493 : {
494 : // If the texture can't be loaded yet, set the dirty flags
495 : // so we'll try regenerating the terrain texture again soon
496 0 : if (!tex->GetTexture()->TryLoad())
497 0 : m_TerrainTextureDirty = true;
498 :
499 0 : color = tex->GetBaseColor();
500 : }
501 : }
502 :
503 0 : *dataPtr++ = ScaleColor(color, float(val) / 255.0f);
504 : }
505 : }
506 : }
507 :
508 : // Upload the texture
509 0 : deviceCommandContext->UploadTextureRegion(
510 : m_TerrainTexture.get(), Renderer::Backend::Format::R8G8B8A8_UNORM,
511 0 : m_TerrainData.get(), width * height * 4, 0, 0, width, height);
512 0 : }
513 :
514 0 : void CMiniMapTexture::RenderFinalTexture(
515 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
516 : CLOSTexture& losTexture, CTerritoryTexture& territoryTexture)
517 : {
518 : // only update 2x / second
519 : // (note: since units only move a few pixels per second on the minimap,
520 : // we can get away with infrequent updates; this is slow)
521 : // TODO: Update all but camera at same speed as simulation
522 0 : const double currentTime = timer_Time();
523 0 : const bool doUpdate = (currentTime - m_LastFinalTextureUpdate > 0.5) || m_FinalTextureDirty;
524 0 : if (!doUpdate)
525 0 : return;
526 0 : m_LastFinalTextureUpdate = currentTime;
527 0 : m_FinalTextureDirty = false;
528 :
529 0 : CmpPtr<ICmpRangeManager> cmpRangeManager(m_Simulation, SYSTEM_ENTITY);
530 0 : ENSURE(cmpRangeManager);
531 :
532 : // We might scale entities properly in the vertex shader but it requires
533 : // additional space in the vertex buffer. So we assume that we don't need
534 : // to change an entity size so often.
535 : // Also compensate circular maps for being rendered closer than square maps.
536 0 : const float mapGeometryScale{cmpRangeManager->GetLosCircular() ? std::sqrt(2.0f) : 1.0f};
537 0 : const float entityRadiusScale{g_ConfigDB.Get("gui.session.minimap.entityradiusscale", 1.0f) / mapGeometryScale };
538 : // Radius with instancing is lower because an entity has a more round shape.
539 0 : const float entityRadius = static_cast<float>(m_MapSize) / 128.0f * (m_UseInstancing ? 5.0 : 6.0f) * entityRadiusScale;
540 :
541 0 : UpdateAndUploadEntities(deviceCommandContext, entityRadius, currentTime);
542 :
543 0 : PROFILE3("Render minimap texture");
544 0 : GPU_SCOPED_LABEL(deviceCommandContext, "Render minimap texture");
545 0 : deviceCommandContext->BeginFramebufferPass(m_FinalTextureFramebuffer.get());
546 :
547 0 : Renderer::Backend::IDeviceCommandContext::Rect viewportRect{};
548 0 : viewportRect.width = FINAL_TEXTURE_SIZE;
549 0 : viewportRect.height = FINAL_TEXTURE_SIZE;
550 0 : deviceCommandContext->SetViewports(1, &viewportRect);
551 :
552 0 : const float texCoordMax = m_TerrainTexture ? static_cast<float>(m_MapSize - 1) / m_TerrainTexture->GetWidth() : 1.0f;
553 :
554 0 : Renderer::Backend::IShaderProgram* shader = nullptr;
555 0 : CShaderTechniquePtr tech;
556 :
557 0 : CShaderDefines baseDefines;
558 0 : baseDefines.Add(str_MINIMAP_BASE, str_1);
559 :
560 0 : tech = g_Renderer.GetShaderManager().LoadEffect(str_minimap, baseDefines);
561 0 : deviceCommandContext->SetGraphicsPipelineState(
562 : tech->GetGraphicsPipelineState());
563 0 : deviceCommandContext->BeginPass();
564 0 : shader = tech->GetShader();
565 :
566 0 : if (m_TerrainTexture)
567 : {
568 0 : deviceCommandContext->SetTexture(
569 0 : shader->GetBindingSlot(str_baseTex), m_TerrainTexture.get());
570 : }
571 :
572 0 : CMatrix3D baseTransform;
573 0 : baseTransform.SetIdentity();
574 0 : CMatrix3D baseTextureTransform;
575 0 : baseTextureTransform.SetIdentity();
576 :
577 0 : CMatrix3D terrainTransform;
578 0 : terrainTransform.SetIdentity();
579 0 : terrainTransform.Scale(texCoordMax, texCoordMax, 1.0f);
580 :
581 0 : deviceCommandContext->SetUniform(
582 0 : shader->GetBindingSlot(str_transform),
583 : baseTransform._11, baseTransform._21, baseTransform._12, baseTransform._22);
584 0 : deviceCommandContext->SetUniform(
585 0 : shader->GetBindingSlot(str_textureTransform),
586 : terrainTransform._11, terrainTransform._21, terrainTransform._12, terrainTransform._22);
587 0 : deviceCommandContext->SetUniform(
588 0 : shader->GetBindingSlot(str_translation),
589 : baseTransform._14, baseTransform._24, terrainTransform._14, terrainTransform._24);
590 :
591 0 : if (m_TerrainTexture)
592 0 : DrawTexture(deviceCommandContext, m_QuadVertexInputLayout);
593 0 : deviceCommandContext->EndPass();
594 :
595 0 : deviceCommandContext->SetGraphicsPipelineState(
596 0 : m_TerritoryTechnique->GetGraphicsPipelineState());
597 0 : shader = m_TerritoryTechnique->GetShader();
598 0 : deviceCommandContext->BeginPass();
599 :
600 : // Draw territory boundaries
601 0 : deviceCommandContext->SetTexture(
602 0 : shader->GetBindingSlot(str_baseTex), territoryTexture.GetTexture());
603 0 : deviceCommandContext->SetUniform(
604 0 : shader->GetBindingSlot(str_transform),
605 : baseTransform._11, baseTransform._21, baseTransform._12, baseTransform._22);
606 0 : const CMatrix3D& territoryTransform = territoryTexture.GetMinimapTextureMatrix();
607 0 : deviceCommandContext->SetUniform(
608 0 : shader->GetBindingSlot(str_textureTransform),
609 0 : territoryTransform._11, territoryTransform._21, territoryTransform._12, territoryTransform._22);
610 0 : deviceCommandContext->SetUniform(
611 0 : shader->GetBindingSlot(str_translation),
612 0 : baseTransform._14, baseTransform._24, territoryTransform._14, territoryTransform._24);
613 :
614 0 : DrawTexture(deviceCommandContext, m_QuadVertexInputLayout);
615 0 : deviceCommandContext->EndPass();
616 :
617 0 : tech = g_Renderer.GetShaderManager().LoadEffect(str_minimap_los, CShaderDefines());
618 0 : deviceCommandContext->SetGraphicsPipelineState(
619 : tech->GetGraphicsPipelineState());
620 0 : deviceCommandContext->BeginPass();
621 0 : shader = tech->GetShader();
622 :
623 0 : deviceCommandContext->SetTexture(
624 0 : shader->GetBindingSlot(str_baseTex), losTexture.GetTexture());
625 0 : deviceCommandContext->SetUniform(
626 0 : shader->GetBindingSlot(str_transform),
627 : baseTransform._11, baseTransform._21, baseTransform._12, baseTransform._22);
628 0 : const CMatrix3D& losTransform = losTexture.GetMinimapTextureMatrix();
629 0 : deviceCommandContext->SetUniform(
630 0 : shader->GetBindingSlot(str_textureTransform),
631 0 : losTransform._11, losTransform._21, losTransform._12, losTransform._22);
632 0 : deviceCommandContext->SetUniform(
633 0 : shader->GetBindingSlot(str_translation),
634 0 : baseTransform._14, baseTransform._24, losTransform._14, losTransform._24);
635 :
636 0 : DrawTexture(deviceCommandContext, m_QuadVertexInputLayout);
637 :
638 0 : deviceCommandContext->EndPass();
639 :
640 0 : if (m_EntitiesDrawn > 0)
641 0 : DrawEntities(deviceCommandContext, entityRadius);
642 :
643 0 : deviceCommandContext->EndFramebufferPass();
644 : }
645 :
646 0 : void CMiniMapTexture::UpdateAndUploadEntities(
647 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
648 : const float entityRadius, const double& currentTime)
649 : {
650 0 : const float invTileMapSize = 1.0f / static_cast<float>(TERRAIN_TILE_SIZE * m_MapSize);
651 :
652 0 : m_Icons.clear();
653 0 : m_IconsCache.clear();
654 :
655 0 : CSimulation2::InterfaceList ents = m_Simulation.GetEntitiesWithInterface(IID_Minimap);
656 :
657 0 : VertexArrayIterator<float[2]> attrPos = m_AttributePos.GetIterator<float[2]>();
658 0 : VertexArrayIterator<std::uint8_t[4]> attrColor = m_AttributeColor.GetIterator<std::uint8_t[4]>();
659 :
660 0 : m_EntitiesDrawn = 0;
661 0 : MinimapUnitVertex v;
662 0 : std::vector<MinimapUnitVertex> pingingVertices;
663 0 : pingingVertices.reserve(MAX_ENTITIES_DRAWN / 2);
664 :
665 0 : CmpPtr<ICmpRangeManager> cmpRangeManager(m_Simulation, SYSTEM_ENTITY);
666 0 : ENSURE(cmpRangeManager);
667 :
668 0 : if (currentTime > m_NextBlinkTime)
669 : {
670 0 : m_BlinkState = !m_BlinkState;
671 0 : m_NextBlinkTime = currentTime + m_HalfBlinkDuration;
672 : }
673 :
674 0 : const bool iconsEnabled{g_ConfigDB.Get("gui.session.minimap.icons.enabled", false)};
675 0 : const float iconsOpacity{g_ConfigDB.Get("gui.session.minimap.icons.opacity", 1.0f)};
676 0 : const float iconsSizeScale{g_ConfigDB.Get("gui.session.minimap.icons.sizescale", 1.0f)};
677 :
678 0 : bool iconsCountOverflow = false;
679 :
680 0 : entity_pos_t posX, posZ;
681 0 : for (CSimulation2::InterfaceList::const_iterator it = ents.begin(); it != ents.end(); ++it)
682 : {
683 0 : ICmpMinimap* cmpMinimap = static_cast<ICmpMinimap*>(it->second);
684 0 : if (cmpMinimap->GetRenderData(v.r, v.g, v.b, posX, posZ))
685 : {
686 0 : LosVisibility vis = cmpRangeManager->GetLosVisibility(it->first, m_Simulation.GetSimContext().GetCurrentDisplayedPlayer());
687 0 : if (vis != LosVisibility::HIDDEN)
688 : {
689 0 : v.a = 255;
690 0 : v.position.X = posX.ToFloat();
691 0 : v.position.Y = posZ.ToFloat();
692 :
693 : // Check minimap pinging to indicate something
694 0 : if (m_BlinkState && cmpMinimap->CheckPing(currentTime, m_PingDuration))
695 : {
696 0 : v.r = 255; // ping color is white
697 0 : v.g = 255;
698 0 : v.b = 255;
699 0 : pingingVertices.push_back(v);
700 : }
701 0 : else if (m_EntitiesDrawn < MAX_ENTITIES_DRAWN)
702 : {
703 0 : AddEntity(v, attrColor, attrPos, entityRadius, m_UseInstancing);
704 0 : ++m_EntitiesDrawn;
705 : }
706 :
707 0 : if (!iconsEnabled || !cmpMinimap->HasIcon())
708 0 : continue;
709 :
710 0 : const CellIconKey key{
711 0 : cmpMinimap->GetIconPath(), v.r, v.g, v.b};
712 0 : const std::uint16_t gridX = Clamp<std::uint16_t>(
713 0 : (v.position.X * invTileMapSize) * ICON_COMBINING_GRID_SIZE, 0, ICON_COMBINING_GRID_SIZE - 1);
714 0 : const std::uint16_t gridY = Clamp<std::uint16_t>(
715 0 : (v.position.Y * invTileMapSize) * ICON_COMBINING_GRID_SIZE, 0, ICON_COMBINING_GRID_SIZE - 1);
716 0 : CellIcon icon{
717 0 : gridX, gridY, cmpMinimap->GetIconSize() * iconsSizeScale * 0.5f, v.position};
718 0 : if (m_IconsCache.find(key) == m_IconsCache.end() && m_IconsCache.size() >= MAX_UNIQUE_ICON_COUNT)
719 : {
720 : iconsCountOverflow = true;
721 : }
722 : else
723 : {
724 0 : m_IconsCache[key].emplace_back(std::move(icon));
725 : }
726 0 : }
727 : }
728 : }
729 :
730 : // We need to combine too close icons with the same path, we use a grid for
731 : // that. But to save some allocations and space we store only the current
732 : // row.
733 0 : struct Cell
734 : {
735 : std::uint32_t count;
736 : float maxHalfSize;
737 : CVector2D averagePosition;
738 : };
739 : std::array<Cell, ICON_COMBINING_GRID_SIZE> gridRow;
740 0 : for (auto& [key, icons] : m_IconsCache)
741 : {
742 0 : CTexturePtr texture = g_Renderer.GetTextureManager().CreateTexture(
743 0 : CTextureProperties(key.path));
744 0 : const CColor color(key.r / 255.0f, key.g / 255.0f, key.b / 255.0f, iconsOpacity);
745 :
746 0 : std::sort(icons.begin(), icons.end(),
747 0 : [](const CellIcon& lhs, const CellIcon& rhs) -> bool
748 : {
749 0 : if (lhs.gridY != rhs.gridY)
750 0 : return lhs.gridY < rhs.gridY;
751 0 : return lhs.gridX < rhs.gridX;
752 : });
753 :
754 0 : for (auto beginIt = icons.begin(); beginIt != icons.end();)
755 : {
756 0 : auto endIt = std::next(beginIt);
757 0 : while (endIt != icons.end() && beginIt->gridY == endIt->gridY)
758 0 : ++endIt;
759 0 : gridRow.fill({0, 0.0f, {}});
760 0 : for (; beginIt != endIt; ++beginIt)
761 : {
762 0 : Cell& cell = gridRow[beginIt->gridX];
763 0 : const float previousPositionWeight = static_cast<float>(cell.count) / (cell.count + 1);
764 0 : cell.averagePosition = cell.averagePosition * previousPositionWeight + beginIt->worldPosition / static_cast<float>(cell.count + 1);
765 0 : cell.maxHalfSize = std::max(cell.maxHalfSize, beginIt->halfSize);
766 0 : ++cell.count;
767 : }
768 0 : for (const Cell& cell : gridRow)
769 : {
770 0 : if (cell.count == 0)
771 0 : continue;
772 :
773 0 : if (m_Icons.size() < MAX_ICON_COUNT)
774 : {
775 0 : m_Icons.emplace_back(Icon{
776 0 : texture, color, cell.averagePosition, cell.maxHalfSize});
777 : }
778 : else
779 : iconsCountOverflow = true;
780 : }
781 : }
782 0 : }
783 :
784 0 : if (iconsCountOverflow)
785 0 : LOGWARNING("Too many minimap icons to draw.");
786 :
787 : // Add the pinged vertices at the end, so they are drawn on top
788 0 : for (const MinimapUnitVertex& vertex : pingingVertices)
789 : {
790 0 : AddEntity(vertex, attrColor, attrPos, entityRadius, m_UseInstancing);
791 0 : ++m_EntitiesDrawn;
792 0 : if (m_EntitiesDrawn == MAX_ENTITIES_DRAWN)
793 : break;
794 : }
795 :
796 0 : if (m_EntitiesDrawn == MAX_ENTITIES_DRAWN)
797 0 : ONCE(LOGERROR("Too many entities, some of them will be hidden on the minimap."));
798 :
799 0 : if (!m_UseInstancing)
800 : {
801 0 : VertexArrayIterator<std::uint16_t> index = m_IndexArray.GetIterator();
802 0 : for (size_t entityIndex = 0; entityIndex < m_EntitiesDrawn; ++entityIndex)
803 : {
804 0 : index[entityIndex * 6 + 0] = static_cast<std::uint16_t>(entityIndex * 4 + 0);
805 0 : index[entityIndex * 6 + 1] = static_cast<std::uint16_t>(entityIndex * 4 + 1);
806 0 : index[entityIndex * 6 + 2] = static_cast<std::uint16_t>(entityIndex * 4 + 2);
807 0 : index[entityIndex * 6 + 3] = static_cast<std::uint16_t>(entityIndex * 4 + 0);
808 0 : index[entityIndex * 6 + 4] = static_cast<std::uint16_t>(entityIndex * 4 + 2);
809 0 : index[entityIndex * 6 + 5] = static_cast<std::uint16_t>(entityIndex * 4 + 3);
810 : }
811 :
812 0 : m_IndexArray.Upload();
813 : }
814 :
815 0 : m_VertexArray.Upload();
816 :
817 0 : m_VertexArray.PrepareForRendering();
818 :
819 0 : m_VertexArray.UploadIfNeeded(deviceCommandContext);
820 0 : if (!m_UseInstancing)
821 0 : m_IndexArray.UploadIfNeeded(deviceCommandContext);
822 0 : }
823 :
824 0 : void CMiniMapTexture::DrawEntities(
825 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
826 : const float entityRadius)
827 : {
828 0 : const float invTileMapSize = 1.0f / static_cast<float>(TERRAIN_TILE_SIZE * m_MapSize);
829 :
830 0 : CShaderDefines pointDefines;
831 0 : pointDefines.Add(str_MINIMAP_POINT, str_1);
832 0 : if (m_UseInstancing)
833 0 : pointDefines.Add(str_USE_GPU_INSTANCING, str_1);
834 0 : CShaderTechniquePtr tech = g_Renderer.GetShaderManager().LoadEffect(str_minimap, pointDefines);
835 0 : deviceCommandContext->SetGraphicsPipelineState(
836 : tech->GetGraphicsPipelineState());
837 0 : deviceCommandContext->BeginPass();
838 0 : Renderer::Backend::IShaderProgram* shader = tech->GetShader();
839 :
840 0 : CMatrix3D unitMatrix;
841 0 : unitMatrix.SetIdentity();
842 : // Convert world space coordinates into [0, 2].
843 0 : const float unitScale = invTileMapSize;
844 0 : unitMatrix.Scale(unitScale * 2.0f, unitScale * 2.0f, 1.0f);
845 : // Offset the coordinates to [-1, 1].
846 0 : unitMatrix.Translate(CVector3D(-1.0f, -1.0f, 0.0f));
847 0 : deviceCommandContext->SetUniform(
848 0 : shader->GetBindingSlot(str_transform),
849 : unitMatrix._11, unitMatrix._21, unitMatrix._12, unitMatrix._22);
850 0 : deviceCommandContext->SetUniform(
851 0 : shader->GetBindingSlot(str_translation),
852 : unitMatrix._14, unitMatrix._24, 0.0f, 0.0f);
853 :
854 0 : Renderer::Backend::IDeviceCommandContext::Rect scissorRect;
855 0 : scissorRect.x = scissorRect.y = 1;
856 0 : scissorRect.width = scissorRect.height = FINAL_TEXTURE_SIZE - 2;
857 0 : deviceCommandContext->SetScissors(1, &scissorRect);
858 :
859 0 : const uint32_t stride = m_VertexArray.GetStride();
860 0 : const uint32_t firstVertexOffset = m_VertexArray.GetOffset() * stride;
861 :
862 0 : deviceCommandContext->SetVertexInputLayout(m_EntitiesVertexInputLayout);
863 0 : if (m_UseInstancing)
864 : {
865 0 : deviceCommandContext->SetVertexBuffer(
866 : 0, m_InstanceVertexArray.GetBuffer(), m_InstanceVertexArray.GetOffset());
867 0 : deviceCommandContext->SetVertexBuffer(
868 : 1, m_VertexArray.GetBuffer(), firstVertexOffset);
869 :
870 0 : deviceCommandContext->SetUniform(shader->GetBindingSlot(str_width), entityRadius);
871 :
872 0 : deviceCommandContext->DrawInstanced(0, m_InstanceVertexArray.GetNumberOfVertices(), 0, m_EntitiesDrawn);
873 : }
874 : else
875 : {
876 0 : deviceCommandContext->SetVertexBuffer(
877 : 0, m_VertexArray.GetBuffer(), firstVertexOffset);
878 0 : deviceCommandContext->SetIndexBuffer(m_IndexArray.GetBuffer());
879 :
880 0 : deviceCommandContext->DrawIndexed(m_IndexArray.GetOffset(), m_EntitiesDrawn * 6, 0);
881 : }
882 :
883 0 : g_Renderer.GetStats().m_DrawCalls++;
884 :
885 0 : deviceCommandContext->SetScissors(0, nullptr);
886 :
887 0 : deviceCommandContext->EndPass();
888 0 : }
889 :
890 : // static
891 0 : float CMiniMapTexture::GetShallowPassageHeight()
892 : {
893 0 : float shallowPassageHeight = 0.0f;
894 0 : CParamNode externalParamNode;
895 0 : CParamNode::LoadXML(externalParamNode, L"simulation/data/pathfinder.xml", "pathfinder");
896 0 : const CParamNode pathingSettings = externalParamNode.GetChild("Pathfinder").GetChild("PassabilityClasses");
897 0 : if (pathingSettings.GetChild("default").IsOk() && pathingSettings.GetChild("default").GetChild("MaxWaterDepth").IsOk())
898 0 : shallowPassageHeight = pathingSettings.GetChild("default").GetChild("MaxWaterDepth").ToFloat();
899 0 : return shallowPassageHeight;
900 0 : }
|