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 "LOSTexture.h"
21 :
22 : #include "graphics/Color.h"
23 : #include "graphics/ShaderManager.h"
24 : #include "graphics/ShaderTechnique.h"
25 : #include "lib/bits.h"
26 : #include "lib/debug.h"
27 : #include "lib/timer.h"
28 : #include "maths/MathUtil.h"
29 : #include "ps/CLogger.h"
30 : #include "ps/CStrIntern.h"
31 : #include "ps/CStrInternStatic.h"
32 : #include "ps/Profile.h"
33 : #include "renderer/Renderer.h"
34 : #include "renderer/RenderingOptions.h"
35 : #include "renderer/TimeManager.h"
36 : #include "renderer/backend/Backend.h"
37 : #include "renderer/backend/IDevice.h"
38 : #include "renderer/backend/IDeviceCommandContext.h"
39 : #include "renderer/backend/IFramebuffer.h"
40 : #include "renderer/backend/IShaderProgram.h"
41 : #include "renderer/backend/ITexture.h"
42 : #include "renderer/backend/Sampler.h"
43 : #include "simulation2/Simulation2.h"
44 : #include "simulation2/components/ICmpRangeManager.h"
45 : #include "simulation2/helpers/Los.h"
46 : #include "simulation2/system/Component.h"
47 : #include "simulation2/system/Entity.h"
48 :
49 : #include <array>
50 : #include <bit>
51 : #include <cstring>
52 : #include <iterator>
53 :
54 : /*
55 :
56 : The LOS bitmap is computed with one value per LOS vertex, based on
57 : CCmpRangeManager's visibility information.
58 :
59 : The bitmap is then blurred using an NxN filter (in particular a
60 : 7-tap Binomial filter as an efficient integral approximation of a Gaussian).
61 : To implement the blur efficiently without using extra memory for a second copy
62 : of the bitmap, we generate the bitmap with (N-1)/2 pixels of padding on each side,
63 : then the blur shifts the image back into the corner.
64 :
65 : The blurred bitmap is then uploaded into a GL texture for use by the renderer.
66 :
67 : */
68 :
69 :
70 : // Blur with a NxN filter, where N = g_BlurSize must be an odd number.
71 : // Keep it in relation to the number of impassable tiles in MAP_EDGE_TILES.
72 : static const size_t g_BlurSize = 7;
73 :
74 : // Alignment (in bytes) of the pixel data passed into texture uploading.
75 : // This must be a multiple of GL_UNPACK_ALIGNMENT, which ought to be 1 (since
76 : // that's what we set it to) but in some weird cases appears to have a different
77 : // value. (See Trac #2594). Multiples of 4 are possibly good for performance anyway.
78 : static const size_t g_SubTextureAlignment = 4;
79 :
80 1 : CLOSTexture::CLOSTexture(CSimulation2& simulation)
81 1 : : m_Simulation(simulation)
82 : {
83 1 : if (!CRenderer::IsInitialised())
84 1 : return;
85 0 : m_SmoothTech = g_Renderer.GetShaderManager().LoadEffect(str_los_interp);
86 :
87 0 : if (!m_SmoothTech || !m_SmoothTech->GetShader())
88 : {
89 0 : LOGERROR("Failed to load SmoothLOS shader, disabling.");
90 0 : g_RenderingOptions.SetSmoothLOS(false);
91 : }
92 :
93 0 : const std::array<Renderer::Backend::SVertexAttributeFormat, 2> attributes{{
94 : {Renderer::Backend::VertexAttributeStream::POSITION,
95 : Renderer::Backend::Format::R32G32_SFLOAT, 0, sizeof(float) * 2,
96 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
97 : {Renderer::Backend::VertexAttributeStream::UV0,
98 : Renderer::Backend::Format::R32G32_SFLOAT, 0, sizeof(float) * 2,
99 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 1}
100 : }};
101 0 : m_VertexInputLayout = g_Renderer.GetVertexInputLayout(attributes);
102 0 : }
103 :
104 6 : CLOSTexture::~CLOSTexture()
105 : {
106 1 : m_SmoothFramebuffers[0].reset();
107 1 : m_SmoothFramebuffers[1].reset();
108 :
109 1 : if (m_Texture)
110 0 : DeleteTexture();
111 8 : }
112 :
113 0 : void CLOSTexture::DeleteTexture()
114 : {
115 0 : m_Texture.reset();
116 0 : m_SmoothTextures[0].reset();
117 0 : m_SmoothTextures[1].reset();
118 0 : }
119 :
120 0 : void CLOSTexture::MakeDirty()
121 : {
122 0 : m_Dirty = true;
123 0 : }
124 :
125 0 : Renderer::Backend::ITexture* CLOSTexture::GetTextureSmooth()
126 : {
127 0 : if (!g_RenderingOptions.GetSmoothLOS())
128 0 : return GetTexture();
129 : else
130 0 : return m_SmoothTextures[m_WhichTexture].get();
131 : }
132 :
133 0 : void CLOSTexture::InterpolateLOS(Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
134 : {
135 : // Check if smooth LOS has just been enabled. If so, while it was disabled, m_SmoothTextures weren't updated, so
136 : // they contain outdated LOS data or none at all yet. Therefore, in that case upload the current LOS data to them to
137 : // prevent any fading.
138 0 : const bool shouldUpdateSmoothTextures{g_RenderingOptions.GetSmoothLOS() && !m_WasSmoothLOSEnabled};
139 0 : m_WasSmoothLOSEnabled = g_RenderingOptions.GetSmoothLOS();
140 0 : if (m_Dirty || shouldUpdateSmoothTextures)
141 : {
142 0 : RecomputeTexture(deviceCommandContext, shouldUpdateSmoothTextures);
143 : // We need to subtract the frame time because without it we have the
144 : // same output images for the current and previous frames.
145 0 : m_LastTextureRecomputeTime = timer_Time() - g_Renderer.GetTimeManager().GetFrameDelta();
146 0 : m_WhichTexture = 1u - m_WhichTexture;
147 0 : m_Dirty = false;
148 : }
149 :
150 0 : if (!g_RenderingOptions.GetSmoothLOS())
151 0 : return;
152 :
153 0 : GPU_SCOPED_LABEL(deviceCommandContext, "Render LOS texture");
154 0 : deviceCommandContext->BeginFramebufferPass(m_SmoothFramebuffers[m_WhichTexture].get());
155 :
156 0 : deviceCommandContext->SetGraphicsPipelineState(
157 0 : m_SmoothTech->GetGraphicsPipelineState());
158 0 : deviceCommandContext->BeginPass();
159 :
160 0 : Renderer::Backend::IShaderProgram* shader = m_SmoothTech->GetShader();
161 :
162 0 : deviceCommandContext->SetTexture(
163 0 : shader->GetBindingSlot(str_losTex1), m_Texture.get());
164 0 : deviceCommandContext->SetTexture(
165 0 : shader->GetBindingSlot(str_losTex2), m_SmoothTextures[1u - m_WhichTexture].get());
166 :
167 0 : const float delta = Clamp<float>(
168 0 : (timer_Time() - m_LastTextureRecomputeTime) * 2.0f, 0.0f, 1.0f);
169 0 : deviceCommandContext->SetUniform(shader->GetBindingSlot(str_delta), delta);
170 :
171 0 : Renderer::Backend::IDeviceCommandContext::Rect viewportRect{};
172 0 : viewportRect.width = m_Texture->GetWidth();
173 0 : viewportRect.height = m_Texture->GetHeight();
174 0 : deviceCommandContext->SetViewports(1, &viewportRect);
175 :
176 0 : const bool flip =
177 0 : deviceCommandContext->GetDevice()->GetBackend() == Renderer::Backend::Backend::VULKAN;
178 0 : const float bottomV = flip ? 1.0 : 0.0f;
179 0 : const float topV = flip ? 0.0f : 1.0f;
180 :
181 0 : float quadVerts[] =
182 : {
183 : 1.0f, 1.0f,
184 : -1.0f, 1.0f,
185 : -1.0f, -1.0f,
186 :
187 : -1.0f, -1.0f,
188 : 1.0f, -1.0f,
189 : 1.0f, 1.0f
190 : };
191 0 : float quadTex[] =
192 : {
193 : 1.0f, topV,
194 : 0.0f, topV,
195 : 0.0f, bottomV,
196 :
197 : 0.0f, bottomV,
198 : 1.0f, bottomV,
199 : 1.0f, topV
200 0 : };
201 :
202 0 : deviceCommandContext->SetVertexInputLayout(m_VertexInputLayout);
203 :
204 0 : deviceCommandContext->SetVertexBufferData(
205 : 0, quadVerts, std::size(quadVerts) * sizeof(quadVerts[0]));
206 0 : deviceCommandContext->SetVertexBufferData(
207 : 1, quadTex, std::size(quadTex) * sizeof(quadTex[0]));
208 :
209 0 : deviceCommandContext->Draw(0, 6);
210 :
211 0 : deviceCommandContext->EndPass();
212 0 : deviceCommandContext->EndFramebufferPass();
213 0 : }
214 :
215 :
216 0 : Renderer::Backend::ITexture* CLOSTexture::GetTexture()
217 : {
218 0 : ENSURE(!m_Dirty);
219 0 : return m_Texture.get();
220 : }
221 :
222 0 : const CMatrix3D& CLOSTexture::GetTextureMatrix()
223 : {
224 0 : ENSURE(!m_Dirty);
225 0 : return m_TextureMatrix;
226 : }
227 :
228 0 : const CMatrix3D& CLOSTexture::GetMinimapTextureMatrix()
229 : {
230 0 : ENSURE(!m_Dirty);
231 0 : return m_MinimapTextureMatrix;
232 : }
233 :
234 0 : void CLOSTexture::ConstructTexture(Renderer::Backend::IDeviceCommandContext* deviceCommandContext)
235 : {
236 0 : CmpPtr<ICmpRangeManager> cmpRangeManager(m_Simulation, SYSTEM_ENTITY);
237 0 : if (!cmpRangeManager)
238 0 : return;
239 :
240 0 : m_MapSize = cmpRangeManager->GetVerticesPerSide();
241 :
242 0 : const size_t textureSize = std::bit_ceil(round_up((size_t)m_MapSize + g_BlurSize - 1, g_SubTextureAlignment));
243 :
244 0 : Renderer::Backend::IDevice* backendDevice = deviceCommandContext->GetDevice();
245 :
246 0 : const Renderer::Backend::Sampler::Desc defaultSamplerDesc =
247 0 : Renderer::Backend::Sampler::MakeDefaultSampler(
248 : Renderer::Backend::Sampler::Filter::LINEAR,
249 : Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE);
250 :
251 0 : if (backendDevice->IsFramebufferFormatSupported(Renderer::Backend::Format::R8_UNORM))
252 : {
253 0 : m_TextureFormat = Renderer::Backend::Format::R8_UNORM;
254 0 : m_TextureFormatStride = 1;
255 : }
256 : else
257 : {
258 0 : m_TextureFormat = Renderer::Backend::Format::R8G8B8A8_UNORM;
259 0 : m_TextureFormatStride = 4;
260 : }
261 :
262 0 : m_Texture = backendDevice->CreateTexture2D("LOSTexture",
263 : Renderer::Backend::ITexture::Usage::TRANSFER_DST |
264 : Renderer::Backend::ITexture::Usage::SAMPLED,
265 0 : m_TextureFormat, textureSize, textureSize, defaultSamplerDesc);
266 :
267 : // Initialise texture with SoD color, for the areas we don't
268 : // overwrite with uploading later.
269 0 : const size_t textureDataSize = textureSize * textureSize * m_TextureFormatStride;
270 0 : std::unique_ptr<std::uint8_t[]> texData = std::make_unique<std::uint8_t[]>(textureDataSize);
271 0 : memset(texData.get(), 0x00, textureDataSize);
272 :
273 0 : const uint32_t usage =
274 : Renderer::Backend::ITexture::Usage::TRANSFER_DST |
275 : Renderer::Backend::ITexture::Usage::SAMPLED |
276 : Renderer::Backend::ITexture::Usage::COLOR_ATTACHMENT;
277 0 : m_SmoothTextures[0] = backendDevice->CreateTexture2D("LOSSmoothTexture0",
278 0 : usage, m_TextureFormat, textureSize, textureSize, defaultSamplerDesc);
279 0 : m_SmoothTextures[1] = backendDevice->CreateTexture2D("LOSSmoothTexture1",
280 0 : usage, m_TextureFormat, textureSize, textureSize, defaultSamplerDesc);
281 :
282 0 : Renderer::Backend::SColorAttachment colorAttachment{};
283 0 : colorAttachment.texture = m_SmoothTextures[0].get();
284 0 : colorAttachment.loadOp = Renderer::Backend::AttachmentLoadOp::DONT_CARE;
285 0 : colorAttachment.storeOp = Renderer::Backend::AttachmentStoreOp::STORE;
286 0 : colorAttachment.clearColor = CColor{0.0f, 0.0f, 0.0f, 0.0f};
287 0 : m_SmoothFramebuffers[0] = backendDevice->CreateFramebuffer(
288 0 : "LOSSmoothFramebuffer0", &colorAttachment, nullptr);
289 0 : colorAttachment.texture = m_SmoothTextures[1].get();
290 0 : m_SmoothFramebuffers[1] = backendDevice->CreateFramebuffer(
291 0 : "LOSSmoothFramebuffer1", &colorAttachment, nullptr);
292 0 : if (!m_SmoothFramebuffers[0] || !m_SmoothFramebuffers[1])
293 : {
294 0 : LOGERROR("Failed to create LOS framebuffers");
295 0 : g_RenderingOptions.SetSmoothLOS(false);
296 : }
297 :
298 0 : deviceCommandContext->UploadTexture(
299 0 : m_SmoothTextures[0].get(), m_TextureFormat, texData.get(), textureDataSize);
300 0 : deviceCommandContext->UploadTexture(
301 0 : m_SmoothTextures[1].get(), m_TextureFormat, texData.get(), textureDataSize);
302 :
303 0 : deviceCommandContext->UploadTexture(
304 0 : m_Texture.get(), m_TextureFormat, texData.get(), textureDataSize);
305 :
306 0 : texData.reset();
307 :
308 0 : {
309 : // Texture matrix: We want to map
310 : // world pos (0, y, 0) (i.e. first vertex)
311 : // onto texcoord (0.5/texsize, 0.5/texsize) (i.e. middle of first texel);
312 : // world pos ((mapsize-1)*cellsize, y, (mapsize-1)*cellsize) (i.e. last vertex)
313 : // onto texcoord ((mapsize-0.5) / texsize, (mapsize-0.5) / texsize) (i.e. middle of last texel)
314 :
315 0 : float s = (m_MapSize-1) / static_cast<float>(textureSize * (m_MapSize-1) * LOS_TILE_SIZE);
316 0 : float t = 0.5f / textureSize;
317 0 : m_TextureMatrix.SetZero();
318 0 : m_TextureMatrix._11 = s;
319 0 : m_TextureMatrix._23 = s;
320 0 : m_TextureMatrix._14 = t;
321 0 : m_TextureMatrix._24 = t;
322 0 : m_TextureMatrix._44 = 1;
323 : }
324 :
325 0 : {
326 : // Minimap matrix: We want to map UV (0,0)-(1,1) onto (0,0)-(mapsize/texsize, mapsize/texsize)
327 :
328 0 : float s = m_MapSize / (float)textureSize;
329 0 : m_MinimapTextureMatrix.SetZero();
330 0 : m_MinimapTextureMatrix._11 = s;
331 0 : m_MinimapTextureMatrix._22 = s;
332 0 : m_MinimapTextureMatrix._44 = 1;
333 : }
334 0 : }
335 :
336 0 : void CLOSTexture::RecomputeTexture(Renderer::Backend::IDeviceCommandContext* deviceCommandContext, bool shouldUpdateSmoothTextures)
337 : {
338 : // If the map was resized, delete and regenerate the texture
339 0 : if (m_Texture)
340 : {
341 0 : CmpPtr<ICmpRangeManager> cmpRangeManager(m_Simulation, SYSTEM_ENTITY);
342 0 : if (!cmpRangeManager || m_MapSize != cmpRangeManager->GetVerticesPerSide())
343 0 : DeleteTexture();
344 : }
345 :
346 0 : bool recreated = false;
347 0 : if (!m_Texture)
348 : {
349 0 : ConstructTexture(deviceCommandContext);
350 : recreated = true;
351 : }
352 :
353 0 : PROFILE("recompute LOS texture");
354 :
355 0 : CmpPtr<ICmpRangeManager> cmpRangeManager(m_Simulation, SYSTEM_ENTITY);
356 0 : if (!cmpRangeManager)
357 0 : return;
358 :
359 0 : size_t pitch;
360 0 : const size_t dataSize = GetBitmapSize(m_MapSize, m_MapSize, &pitch);
361 0 : ENSURE(pitch * m_MapSize <= dataSize);
362 0 : std::unique_ptr<std::uint8_t[]> losData = std::make_unique<std::uint8_t[]>(
363 0 : dataSize * m_TextureFormatStride);
364 :
365 0 : CLosQuerier los(cmpRangeManager->GetLosQuerier(m_Simulation.GetSimContext().GetCurrentDisplayedPlayer()));
366 :
367 0 : GenerateBitmap(los, &losData[0], m_MapSize, m_MapSize, pitch);
368 :
369 : // GenerateBitmap writes data tightly packed and we need to offset it to fit
370 : // into the texture format properly.
371 0 : const size_t textureDataPitch = pitch * m_TextureFormatStride;
372 0 : if (m_TextureFormatStride > 1)
373 : {
374 : // We skip the last byte because it will be first in our order and we
375 : // don't need to move it.
376 0 : for (size_t index = 0; index + 1 < dataSize; ++index)
377 : {
378 0 : const size_t oldAddress = dataSize - 1 - index;
379 0 : const size_t newAddress = oldAddress * m_TextureFormatStride;
380 0 : losData[newAddress] = losData[oldAddress];
381 0 : losData[oldAddress] = 0;
382 : }
383 : }
384 :
385 0 : if (recreated || shouldUpdateSmoothTextures)
386 : {
387 0 : deviceCommandContext->UploadTextureRegion(
388 0 : m_SmoothTextures[0].get(), m_TextureFormat, losData.get(),
389 0 : textureDataPitch * m_MapSize, 0, 0, pitch, m_MapSize);
390 0 : deviceCommandContext->UploadTextureRegion(
391 0 : m_SmoothTextures[1].get(), m_TextureFormat, losData.get(),
392 0 : textureDataPitch * m_MapSize, 0, 0, pitch, m_MapSize);
393 : }
394 :
395 0 : deviceCommandContext->UploadTextureRegion(
396 0 : m_Texture.get(), m_TextureFormat, losData.get(),
397 0 : textureDataPitch * m_MapSize, 0, 0, pitch, m_MapSize);
398 0 : }
399 :
400 1 : size_t CLOSTexture::GetBitmapSize(size_t w, size_t h, size_t* pitch)
401 : {
402 0 : *pitch = round_up(w + g_BlurSize - 1, g_SubTextureAlignment);
403 0 : return *pitch * (h + g_BlurSize - 1);
404 : }
405 :
406 1 : void CLOSTexture::GenerateBitmap(const CLosQuerier& los, std::uint8_t* losData, size_t w, size_t h,
407 : size_t pitch)
408 : {
409 1 : std::uint8_t *dataPtr = losData;
410 :
411 : // Initialise the top padding
412 4 : for (size_t j = 0; j < g_BlurSize/2; ++j)
413 51 : for (size_t i = 0; i < pitch; ++i)
414 48 : *dataPtr++ = 0;
415 :
416 9 : for (size_t j = 0; j < h; ++j)
417 : {
418 : // Initialise the left padding
419 32 : for (size_t i = 0; i < g_BlurSize/2; ++i)
420 24 : *dataPtr++ = 0;
421 :
422 : // Fill in the visibility data
423 72 : for (size_t i = 0; i < w; ++i)
424 : {
425 64 : if (los.IsVisible_UncheckedRange(i, j))
426 10 : *dataPtr++ = 255;
427 54 : else if (los.IsExplored_UncheckedRange(i, j))
428 0 : *dataPtr++ = 127;
429 : else
430 54 : *dataPtr++ = 0;
431 : }
432 :
433 : // Initialise the right padding
434 48 : for (size_t i = 0; i < pitch - w - g_BlurSize/2; ++i)
435 40 : *dataPtr++ = 0;
436 : }
437 :
438 : // Initialise the bottom padding
439 4 : for (size_t j = 0; j < g_BlurSize/2; ++j)
440 51 : for (size_t i = 0; i < pitch; ++i)
441 48 : *dataPtr++ = 0;
442 :
443 : // Horizontal blur:
444 :
445 9 : for (size_t j = g_BlurSize/2; j < h + g_BlurSize/2; ++j)
446 : {
447 72 : for (size_t i = 0; i < w; ++i)
448 : {
449 64 : std::uint8_t* d = &losData[i+j*pitch];
450 64 : *d = (
451 64 : 1*d[0] +
452 64 : 6*d[1] +
453 64 : 15*d[2] +
454 64 : 20*d[3] +
455 64 : 15*d[4] +
456 64 : 6*d[5] +
457 64 : 1*d[6]
458 64 : ) / 64;
459 : }
460 : }
461 :
462 : // Vertical blur:
463 :
464 9 : for (size_t j = 0; j < h; ++j)
465 : {
466 72 : for (size_t i = 0; i < w; ++i)
467 : {
468 64 : std::uint8_t* d = &losData[i+j*pitch];
469 64 : *d = (
470 64 : 1*d[0*pitch] +
471 64 : 6*d[1*pitch] +
472 64 : 15*d[2*pitch] +
473 64 : 20*d[3*pitch] +
474 64 : 15*d[4*pitch] +
475 64 : 6*d[5*pitch] +
476 64 : 1*d[6*pitch]
477 64 : ) / 64;
478 : }
479 : }
480 1 : }
|