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 "renderer/PatchRData.h"
21 :
22 : #include "graphics/Camera.h"
23 : #include "graphics/Color.h"
24 : #include "graphics/GameView.h"
25 : #include "graphics/Material.h"
26 : #include "graphics/MiniPatch.h"
27 : #include "graphics/Patch.h"
28 : #include "graphics/ShaderDefines.h"
29 : #include "graphics/ShaderManager.h"
30 : #include "graphics/ShaderTechnique.h"
31 : #include "graphics/ShaderTechniquePtr.h"
32 : #include "graphics/Terrain.h"
33 : #include "graphics/TerrainTextureEntry.h"
34 : #include "graphics/TerrainTextureManager.h"
35 : #include "graphics/TextRenderer.h"
36 : #include "graphics/TextureManager.h"
37 : #include "lib/alignment.h"
38 : #include "lib/code_generation.h"
39 : #include "lib/debug.h"
40 : #include "maths/Matrix3D.h"
41 : #include "ps/CLogger.h"
42 : #include "ps/CStr.h"
43 : #include "ps/CStrIntern.h"
44 : #include "ps/CStrInternStatic.h"
45 : #include "ps/Game.h"
46 : #include "ps/memory/AllocatorAdapter.h"
47 : #include "ps/memory/LinearAllocator.h"
48 : #include "ps/Profile.h"
49 : #include "renderer/AlphaMapCalculator.h"
50 : #include "renderer/BlendShapes.h"
51 : #include "renderer/DebugRenderer.h"
52 : #include "renderer/Renderer.h"
53 : #include "renderer/SceneRenderer.h"
54 : #include "renderer/TerrainRenderer.h"
55 : #include "renderer/VertexBuffer.h"
56 : #include "renderer/WaterManager.h"
57 : #include "renderer/backend/Format.h"
58 : #include "renderer/backend/IBuffer.h"
59 : #include "renderer/backend/IDeviceCommandContext.h"
60 : #include "renderer/backend/IShaderProgram.h"
61 : #include "simulation2/components/ICmpWaterManager.h"
62 : #include "simulation2/system/Component.h"
63 : #include "simulation2/system/Entity.h"
64 :
65 : #include <algorithm>
66 : #include <array>
67 : #include <cstdint>
68 : #include <cstring>
69 : #include <functional>
70 : #include <iterator>
71 : #include <map>
72 : #include <memory>
73 : #include <numeric>
74 : #include <string>
75 : #include <utility>
76 :
77 : namespace Renderer::Backend { class ITexture; }
78 :
79 : const ssize_t BlendOffsets[9][2] = {
80 : { 0, -1 },
81 : { -1, -1 },
82 : { -1, 0 },
83 : { -1, 1 },
84 : { 0, 1 },
85 : { 1, 1 },
86 : { 1, 0 },
87 : { 1, -1 },
88 : { 0, 0 }
89 : };
90 :
91 : // static
92 10 : Renderer::Backend::IVertexInputLayout* CPatchRData::GetBaseVertexInputLayout()
93 : {
94 10 : const uint32_t stride = sizeof(SBaseVertex);
95 10 : const std::array<Renderer::Backend::SVertexAttributeFormat, 3> attributes{{
96 : {Renderer::Backend::VertexAttributeStream::POSITION,
97 : Renderer::Backend::Format::R32G32B32_SFLOAT,
98 : offsetof(SBaseVertex, m_Position), stride,
99 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
100 : {Renderer::Backend::VertexAttributeStream::NORMAL,
101 : Renderer::Backend::Format::R32G32B32_SFLOAT,
102 : offsetof(SBaseVertex, m_Normal), stride,
103 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
104 : {Renderer::Backend::VertexAttributeStream::UV0,
105 : Renderer::Backend::Format::R32G32B32_SFLOAT,
106 : offsetof(SBaseVertex, m_Position), stride,
107 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
108 : }};
109 10 : return g_Renderer.GetVertexInputLayout(attributes);
110 : }
111 :
112 : // static
113 10 : Renderer::Backend::IVertexInputLayout* CPatchRData::GetBlendVertexInputLayout()
114 : {
115 10 : const uint32_t stride = sizeof(SBlendVertex);
116 10 : const std::array<Renderer::Backend::SVertexAttributeFormat, 4> attributes{{
117 : {Renderer::Backend::VertexAttributeStream::POSITION,
118 : Renderer::Backend::Format::R32G32B32_SFLOAT,
119 : offsetof(SBlendVertex, m_Position), stride,
120 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
121 : {Renderer::Backend::VertexAttributeStream::NORMAL,
122 : Renderer::Backend::Format::R32G32B32_SFLOAT,
123 : offsetof(SBlendVertex, m_Normal), stride,
124 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
125 : {Renderer::Backend::VertexAttributeStream::UV0,
126 : Renderer::Backend::Format::R32G32B32_SFLOAT,
127 : offsetof(SBlendVertex, m_Position), stride,
128 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
129 : {Renderer::Backend::VertexAttributeStream::UV1,
130 : Renderer::Backend::Format::R32G32_SFLOAT,
131 : offsetof(SBlendVertex, m_AlphaUVs), stride,
132 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
133 : }};
134 10 : return g_Renderer.GetVertexInputLayout(attributes);
135 : }
136 :
137 : // static
138 20 : Renderer::Backend::IVertexInputLayout* CPatchRData::GetStreamVertexInputLayout(
139 : const bool bindPositionAsTexCoord)
140 : {
141 20 : const uint32_t stride = sizeof(SBaseVertex);
142 20 : if (bindPositionAsTexCoord)
143 : {
144 10 : const std::array<Renderer::Backend::SVertexAttributeFormat, 2> attributes{{
145 : {Renderer::Backend::VertexAttributeStream::POSITION,
146 : Renderer::Backend::Format::R32G32B32_SFLOAT,
147 : offsetof(SBaseVertex, m_Position), stride,
148 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
149 : {Renderer::Backend::VertexAttributeStream::UV0,
150 : Renderer::Backend::Format::R32G32B32_SFLOAT,
151 : offsetof(SBaseVertex, m_Position), stride,
152 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
153 : }};
154 10 : return g_Renderer.GetVertexInputLayout(attributes);
155 : }
156 : else
157 : {
158 10 : const std::array<Renderer::Backend::SVertexAttributeFormat, 1> attributes{{
159 : {Renderer::Backend::VertexAttributeStream::POSITION,
160 : Renderer::Backend::Format::R32G32B32_SFLOAT,
161 : offsetof(SBaseVertex, m_Position), stride,
162 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
163 : }};
164 10 : return g_Renderer.GetVertexInputLayout(attributes);
165 : }
166 : }
167 :
168 : // static
169 10 : Renderer::Backend::IVertexInputLayout* CPatchRData::GetSideVertexInputLayout()
170 : {
171 10 : const uint32_t stride = sizeof(SSideVertex);
172 10 : const std::array<Renderer::Backend::SVertexAttributeFormat, 1> attributes{{
173 : {Renderer::Backend::VertexAttributeStream::POSITION,
174 : Renderer::Backend::Format::R32G32B32_SFLOAT,
175 : offsetof(SSideVertex, m_Position), stride,
176 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
177 : }};
178 10 : return g_Renderer.GetVertexInputLayout(attributes);
179 : }
180 :
181 : // static
182 20 : Renderer::Backend::IVertexInputLayout* CPatchRData::GetWaterSurfaceVertexInputLayout(
183 : const bool bindWaterData)
184 : {
185 20 : const uint32_t stride = sizeof(SWaterVertex);
186 20 : if (bindWaterData)
187 : {
188 10 : const std::array<Renderer::Backend::SVertexAttributeFormat, 2> attributes{{
189 : {Renderer::Backend::VertexAttributeStream::POSITION,
190 : Renderer::Backend::Format::R32G32B32_SFLOAT,
191 : offsetof(SWaterVertex, m_Position), stride,
192 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
193 : // UV1 will be used only in case of bindWaterData.
194 : {Renderer::Backend::VertexAttributeStream::UV1,
195 : Renderer::Backend::Format::R32G32_SFLOAT,
196 : offsetof(SWaterVertex, m_WaterData), stride,
197 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
198 : }};
199 10 : return g_Renderer.GetVertexInputLayout(attributes);
200 : }
201 : else
202 : {
203 10 : const std::array<Renderer::Backend::SVertexAttributeFormat, 1> attributes{{
204 : {Renderer::Backend::VertexAttributeStream::POSITION,
205 : Renderer::Backend::Format::R32G32B32_SFLOAT,
206 : offsetof(SWaterVertex, m_Position), stride,
207 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
208 : }};
209 10 : return g_Renderer.GetVertexInputLayout(attributes);
210 : }
211 : }
212 :
213 : // static
214 10 : Renderer::Backend::IVertexInputLayout* CPatchRData::GetWaterShoreVertexInputLayout()
215 : {
216 10 : const uint32_t stride = sizeof(SWaterVertex);
217 10 : const std::array<Renderer::Backend::SVertexAttributeFormat, 2> attributes{{
218 : {Renderer::Backend::VertexAttributeStream::POSITION,
219 : Renderer::Backend::Format::R32G32B32_SFLOAT,
220 : offsetof(SWaterVertex, m_Position), stride,
221 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0},
222 : {Renderer::Backend::VertexAttributeStream::UV1,
223 : Renderer::Backend::Format::R32G32_SFLOAT,
224 : offsetof(SWaterVertex, m_WaterData), stride,
225 : Renderer::Backend::VertexAttributeRate::PER_VERTEX, 0}
226 : }};
227 10 : return g_Renderer.GetVertexInputLayout(attributes);
228 : }
229 :
230 0 : CPatchRData::CPatchRData(CPatch* patch, CSimulation2* simulation) :
231 0 : m_Patch(patch), m_Simulation(simulation)
232 : {
233 0 : ENSURE(patch);
234 0 : Build();
235 0 : }
236 :
237 0 : CPatchRData::~CPatchRData() = default;
238 :
239 : /**
240 : * Represents a blend for a single tile, texture and shape.
241 : */
242 : struct STileBlend
243 : {
244 : CTerrainTextureEntry* m_Texture;
245 : int m_Priority;
246 : std::uint16_t m_TileMask; // bit n set if this blend contains neighbour tile BlendOffsets[n]
247 :
248 : struct DecreasingPriority
249 : {
250 0 : bool operator()(const STileBlend& a, const STileBlend& b) const
251 : {
252 0 : if (a.m_Priority > b.m_Priority)
253 : return true;
254 0 : if (a.m_Priority < b.m_Priority)
255 : return false;
256 0 : if (a.m_Texture && b.m_Texture)
257 0 : return a.m_Texture->GetTag() > b.m_Texture->GetTag();
258 : return false;
259 : }
260 : };
261 :
262 : struct CurrentTile
263 : {
264 0 : bool operator()(const STileBlend& a) const
265 : {
266 0 : return (a.m_TileMask & (1 << 8)) != 0;
267 : }
268 : };
269 : };
270 :
271 : /**
272 : * Represents the ordered collection of blends drawn on a particular tile.
273 : */
274 0 : struct STileBlendStack
275 : {
276 : std::uint8_t i, j;
277 : std::vector<STileBlend> blends; // back of vector is lowest-priority texture
278 : };
279 :
280 : /**
281 : * Represents a batched collection of blends using the same texture.
282 : */
283 0 : struct SBlendLayer
284 : {
285 : struct Tile
286 : {
287 : std::uint8_t i, j;
288 : std::uint8_t shape;
289 : };
290 :
291 : CTerrainTextureEntry* m_Texture;
292 : std::vector<Tile> m_Tiles;
293 : };
294 :
295 0 : void CPatchRData::BuildBlends()
296 : {
297 0 : PROFILE3("build blends");
298 :
299 0 : m_BlendSplats.clear();
300 :
301 0 : std::vector<SBlendVertex> blendVertices;
302 0 : std::vector<std::uint16_t> blendIndices;
303 :
304 0 : CTerrain* terrain = m_Patch->m_Parent;
305 :
306 0 : std::vector<STileBlendStack> blendStacks;
307 0 : blendStacks.reserve(PATCH_SIZE*PATCH_SIZE);
308 :
309 0 : std::vector<STileBlend> blends;
310 0 : blends.reserve(9);
311 :
312 : // For each tile in patch ..
313 0 : for (ssize_t j = 0; j < PATCH_SIZE; ++j)
314 : {
315 0 : for (ssize_t i = 0; i < PATCH_SIZE; ++i)
316 : {
317 0 : ssize_t gx = m_Patch->m_X * PATCH_SIZE + i;
318 0 : ssize_t gz = m_Patch->m_Z * PATCH_SIZE + j;
319 :
320 0 : blends.clear();
321 :
322 : // Compute a blend for every tile in the 3x3 square around this tile
323 0 : for (size_t n = 0; n < 9; ++n)
324 : {
325 0 : ssize_t ox = gx + BlendOffsets[n][1];
326 0 : ssize_t oz = gz + BlendOffsets[n][0];
327 :
328 0 : CMiniPatch* nmp = terrain->GetTile(ox, oz);
329 0 : if (!nmp)
330 0 : continue;
331 :
332 0 : STileBlend blend;
333 0 : blend.m_Texture = nmp->GetTextureEntry();
334 0 : blend.m_Priority = nmp->GetPriority();
335 0 : blend.m_TileMask = 1 << n;
336 0 : blends.push_back(blend);
337 : }
338 :
339 : // Sort the blends, highest priority first
340 0 : std::sort(blends.begin(), blends.end(), STileBlend::DecreasingPriority());
341 :
342 0 : STileBlendStack blendStack;
343 0 : blendStack.i = i;
344 0 : blendStack.j = j;
345 :
346 : // Put the blends into the tile's stack, merging any adjacent blends with the same texture
347 0 : for (size_t k = 0; k < blends.size(); ++k)
348 : {
349 0 : if (!blendStack.blends.empty() && blendStack.blends.back().m_Texture == blends[k].m_Texture)
350 0 : blendStack.blends.back().m_TileMask |= blends[k].m_TileMask;
351 : else
352 0 : blendStack.blends.push_back(blends[k]);
353 : }
354 :
355 : // Remove blends that are after (i.e. lower priority than) the current tile
356 : // (including the current tile), since we don't want to render them on top of
357 : // the tile's base texture
358 0 : blendStack.blends.erase(
359 0 : std::find_if(blendStack.blends.begin(), blendStack.blends.end(), STileBlend::CurrentTile()),
360 0 : blendStack.blends.end());
361 :
362 0 : blendStacks.push_back(blendStack);
363 0 : }
364 : }
365 :
366 : // Given the blend stack per tile, we want to batch together as many blends as possible.
367 : // Group them into a series of layers (each of which has a single texture):
368 : // (This is effectively a topological sort / linearisation of the partial order induced
369 : // by the per-tile stacks, preferring to make tiles with equal textures adjacent.)
370 :
371 0 : std::vector<SBlendLayer> blendLayers;
372 :
373 0 : while (true)
374 : {
375 0 : if (!blendLayers.empty())
376 : {
377 : // Try to grab as many tiles as possible that match our current layer,
378 : // from off the blend stacks of all the tiles
379 :
380 0 : CTerrainTextureEntry* tex = blendLayers.back().m_Texture;
381 :
382 0 : for (size_t k = 0; k < blendStacks.size(); ++k)
383 : {
384 0 : if (!blendStacks[k].blends.empty() && blendStacks[k].blends.back().m_Texture == tex)
385 : {
386 0 : SBlendLayer::Tile t = { blendStacks[k].i, blendStacks[k].j,
387 0 : static_cast<std::uint8_t>(blendStacks[k].blends.back().m_TileMask) };
388 0 : blendLayers.back().m_Tiles.push_back(t);
389 0 : blendStacks[k].blends.pop_back();
390 : }
391 : // (We've already merged adjacent entries of the same texture in each stack,
392 : // so we don't need to bother looping to check the next entry in this stack again)
393 : }
394 : }
395 :
396 : // We've grabbed as many tiles as possible; now we need to start a new layer.
397 : // The new layer's texture could come from the back of any non-empty stack;
398 : // choose the longest stack as a heuristic to reduce the number of layers
399 : CTerrainTextureEntry* bestTex = NULL;
400 : size_t bestStackSize = 0;
401 :
402 0 : for (size_t k = 0; k < blendStacks.size(); ++k)
403 : {
404 0 : if (blendStacks[k].blends.size() > bestStackSize)
405 : {
406 0 : bestStackSize = blendStacks[k].blends.size();
407 0 : bestTex = blendStacks[k].blends.back().m_Texture;
408 : }
409 : }
410 :
411 : // If all our stacks were empty, we're done
412 0 : if (bestStackSize == 0)
413 : break;
414 :
415 : // Otherwise add the new layer, then loop back and start filling it in
416 :
417 0 : SBlendLayer layer;
418 0 : layer.m_Texture = bestTex;
419 0 : blendLayers.push_back(layer);
420 0 : }
421 :
422 : // Now build outgoing splats
423 0 : m_BlendSplats.resize(blendLayers.size());
424 :
425 0 : for (size_t k = 0; k < blendLayers.size(); ++k)
426 : {
427 0 : SSplat& splat = m_BlendSplats[k];
428 0 : splat.m_IndexStart = blendIndices.size();
429 0 : splat.m_Texture = blendLayers[k].m_Texture;
430 :
431 0 : for (size_t t = 0; t < blendLayers[k].m_Tiles.size(); ++t)
432 : {
433 0 : SBlendLayer::Tile& tile = blendLayers[k].m_Tiles[t];
434 0 : AddBlend(blendVertices, blendIndices, tile.i, tile.j, tile.shape, splat.m_Texture);
435 : }
436 :
437 0 : splat.m_IndexCount = blendIndices.size() - splat.m_IndexStart;
438 : }
439 :
440 : // Release existing vertex buffer chunks
441 0 : m_VBBlends.Reset();
442 0 : m_VBBlendIndices.Reset();
443 :
444 0 : if (blendVertices.size())
445 : {
446 : // Construct vertex buffer
447 :
448 0 : m_VBBlends = g_Renderer.GetVertexBufferManager().AllocateChunk(
449 : sizeof(SBlendVertex), blendVertices.size(),
450 : Renderer::Backend::IBuffer::Type::VERTEX,
451 : Renderer::Backend::IBuffer::Usage::TRANSFER_DST,
452 0 : nullptr, CVertexBufferManager::Group::TERRAIN);
453 0 : m_VBBlends->m_Owner->UpdateChunkVertices(m_VBBlends.Get(), &blendVertices[0]);
454 :
455 : // Update the indices to include the base offset of the vertex data
456 0 : for (size_t k = 0; k < blendIndices.size(); ++k)
457 0 : blendIndices[k] += static_cast<std::uint16_t>(m_VBBlends->m_Index);
458 :
459 0 : m_VBBlendIndices = g_Renderer.GetVertexBufferManager().AllocateChunk(
460 : sizeof(std::uint16_t), blendIndices.size(),
461 : Renderer::Backend::IBuffer::Type::INDEX,
462 : Renderer::Backend::IBuffer::Usage::TRANSFER_DST,
463 0 : nullptr, CVertexBufferManager::Group::TERRAIN);
464 0 : m_VBBlendIndices->m_Owner->UpdateChunkVertices(m_VBBlendIndices.Get(), &blendIndices[0]);
465 : }
466 0 : }
467 :
468 0 : void CPatchRData::AddBlend(std::vector<SBlendVertex>& blendVertices,
469 : std::vector<std::uint16_t>& blendIndices, std::uint16_t i, std::uint16_t j, std::uint8_t shape,
470 : CTerrainTextureEntry* texture)
471 : {
472 0 : CTerrain* terrain = m_Patch->m_Parent;
473 :
474 0 : ssize_t gx = m_Patch->m_X * PATCH_SIZE + i;
475 0 : ssize_t gz = m_Patch->m_Z * PATCH_SIZE + j;
476 :
477 : // uses the current neighbour texture
478 0 : BlendShape8 shape8;
479 0 : for (size_t m = 0; m < 8; ++m)
480 0 : shape8[m] = (shape & (1 << m)) ? 0 : 1;
481 :
482 : // calculate the required alphamap and the required rotation of the alphamap from blendshape
483 0 : unsigned int alphamapflags;
484 0 : int alphamap = CAlphaMapCalculator::Calculate(shape8, alphamapflags);
485 :
486 : // now actually render the blend tile (if we need one)
487 0 : if (alphamap == -1)
488 0 : return;
489 :
490 0 : float u0 = texture->m_TerrainAlpha->second.m_AlphaMapCoords[alphamap].u0;
491 0 : float u1 = texture->m_TerrainAlpha->second.m_AlphaMapCoords[alphamap].u1;
492 0 : float v0 = texture->m_TerrainAlpha->second.m_AlphaMapCoords[alphamap].v0;
493 0 : float v1 = texture->m_TerrainAlpha->second.m_AlphaMapCoords[alphamap].v1;
494 :
495 0 : if (alphamapflags & BLENDMAP_FLIPU)
496 0 : std::swap(u0, u1);
497 :
498 0 : if (alphamapflags & BLENDMAP_FLIPV)
499 0 : std::swap(v0, v1);
500 :
501 0 : int base = 0;
502 0 : if (alphamapflags & BLENDMAP_ROTATE90)
503 : base = 1;
504 0 : else if (alphamapflags & BLENDMAP_ROTATE180)
505 : base = 2;
506 0 : else if (alphamapflags & BLENDMAP_ROTATE270)
507 0 : base = 3;
508 :
509 0 : SBlendVertex vtx[4];
510 0 : vtx[(base + 0) % 4].m_AlphaUVs[0] = u0;
511 0 : vtx[(base + 0) % 4].m_AlphaUVs[1] = v0;
512 0 : vtx[(base + 1) % 4].m_AlphaUVs[0] = u1;
513 0 : vtx[(base + 1) % 4].m_AlphaUVs[1] = v0;
514 0 : vtx[(base + 2) % 4].m_AlphaUVs[0] = u1;
515 0 : vtx[(base + 2) % 4].m_AlphaUVs[1] = v1;
516 0 : vtx[(base + 3) % 4].m_AlphaUVs[0] = u0;
517 0 : vtx[(base + 3) % 4].m_AlphaUVs[1] = v1;
518 :
519 0 : SBlendVertex dst;
520 :
521 0 : CVector3D normal;
522 :
523 0 : std::uint16_t index = static_cast<std::uint16_t>(blendVertices.size());
524 :
525 0 : terrain->CalcPosition(gx, gz, dst.m_Position);
526 0 : terrain->CalcNormal(gx, gz, normal);
527 0 : dst.m_Normal = normal;
528 0 : dst.m_AlphaUVs[0] = vtx[0].m_AlphaUVs[0];
529 0 : dst.m_AlphaUVs[1] = vtx[0].m_AlphaUVs[1];
530 0 : blendVertices.push_back(dst);
531 :
532 0 : terrain->CalcPosition(gx + 1, gz, dst.m_Position);
533 0 : terrain->CalcNormal(gx + 1, gz, normal);
534 0 : dst.m_Normal = normal;
535 0 : dst.m_AlphaUVs[0] = vtx[1].m_AlphaUVs[0];
536 0 : dst.m_AlphaUVs[1] = vtx[1].m_AlphaUVs[1];
537 0 : blendVertices.push_back(dst);
538 :
539 0 : terrain->CalcPosition(gx + 1, gz + 1, dst.m_Position);
540 0 : terrain->CalcNormal(gx + 1, gz + 1, normal);
541 0 : dst.m_Normal = normal;
542 0 : dst.m_AlphaUVs[0] = vtx[2].m_AlphaUVs[0];
543 0 : dst.m_AlphaUVs[1] = vtx[2].m_AlphaUVs[1];
544 0 : blendVertices.push_back(dst);
545 :
546 0 : terrain->CalcPosition(gx, gz + 1, dst.m_Position);
547 0 : terrain->CalcNormal(gx, gz + 1, normal);
548 0 : dst.m_Normal = normal;
549 0 : dst.m_AlphaUVs[0] = vtx[3].m_AlphaUVs[0];
550 0 : dst.m_AlphaUVs[1] = vtx[3].m_AlphaUVs[1];
551 0 : blendVertices.push_back(dst);
552 :
553 0 : bool dir = terrain->GetTriangulationDir(gx, gz);
554 0 : if (dir)
555 : {
556 0 : blendIndices.push_back(index+0);
557 0 : blendIndices.push_back(index+1);
558 0 : blendIndices.push_back(index+3);
559 :
560 0 : blendIndices.push_back(index+1);
561 0 : blendIndices.push_back(index+2);
562 0 : blendIndices.push_back(index+3);
563 : }
564 : else
565 : {
566 0 : blendIndices.push_back(index+0);
567 0 : blendIndices.push_back(index+1);
568 0 : blendIndices.push_back(index+2);
569 :
570 0 : blendIndices.push_back(index+2);
571 0 : blendIndices.push_back(index+3);
572 0 : blendIndices.push_back(index+0);
573 : }
574 : }
575 :
576 0 : void CPatchRData::BuildIndices()
577 : {
578 0 : PROFILE3("build indices");
579 :
580 0 : CTerrain* terrain = m_Patch->m_Parent;
581 :
582 0 : ssize_t px = m_Patch->m_X * PATCH_SIZE;
583 0 : ssize_t pz = m_Patch->m_Z * PATCH_SIZE;
584 :
585 : // must have allocated some vertices before trying to build corresponding indices
586 0 : ENSURE(m_VBBase);
587 :
588 : // number of vertices in each direction in each patch
589 0 : ssize_t vsize=PATCH_SIZE+1;
590 :
591 : // PATCH_SIZE must be 2^8-2 or less to not overflow std::uint16_t indices buffer. Thankfully this is
592 : // always true.
593 0 : ENSURE(vsize*vsize < 65536);
594 :
595 0 : std::vector<unsigned short> indices;
596 0 : indices.reserve(PATCH_SIZE * PATCH_SIZE * 4);
597 :
598 : // release existing splats
599 0 : m_Splats.clear();
600 :
601 : // build grid of textures on this patch
602 0 : std::vector<CTerrainTextureEntry*> textures;
603 0 : CTerrainTextureEntry* texgrid[PATCH_SIZE][PATCH_SIZE];
604 0 : for (ssize_t j=0;j<PATCH_SIZE;j++) {
605 0 : for (ssize_t i=0;i<PATCH_SIZE;i++) {
606 0 : CTerrainTextureEntry* tex=m_Patch->m_MiniPatches[j][i].GetTextureEntry();
607 0 : texgrid[j][i]=tex;
608 0 : if (std::find(textures.begin(),textures.end(),tex)==textures.end()) {
609 0 : textures.push_back(tex);
610 : }
611 : }
612 : }
613 :
614 : // now build base splats from interior textures
615 0 : m_Splats.resize(textures.size());
616 : // build indices for base splats
617 0 : size_t base=m_VBBase->m_Index;
618 :
619 0 : for (size_t k = 0; k < m_Splats.size(); ++k)
620 : {
621 0 : CTerrainTextureEntry* tex = textures[k];
622 :
623 0 : SSplat& splat=m_Splats[k];
624 0 : splat.m_Texture=tex;
625 0 : splat.m_IndexStart=indices.size();
626 :
627 0 : for (ssize_t j = 0; j < PATCH_SIZE; j++)
628 : {
629 0 : for (ssize_t i = 0; i < PATCH_SIZE; i++)
630 : {
631 0 : if (texgrid[j][i] == tex)
632 : {
633 0 : bool dir = terrain->GetTriangulationDir(px+i, pz+j);
634 0 : if (dir)
635 : {
636 0 : indices.push_back(static_cast<std::uint16_t>(((j+0)*vsize+(i+0))+base));
637 0 : indices.push_back(static_cast<std::uint16_t>(((j+0)*vsize+(i+1))+base));
638 0 : indices.push_back(static_cast<std::uint16_t>(((j+1)*vsize+(i+0))+base));
639 :
640 0 : indices.push_back(static_cast<std::uint16_t>(((j+0)*vsize+(i+1))+base));
641 0 : indices.push_back(static_cast<std::uint16_t>(((j+1)*vsize+(i+1))+base));
642 0 : indices.push_back(static_cast<std::uint16_t>(((j+1)*vsize+(i+0))+base));
643 : }
644 : else
645 : {
646 0 : indices.push_back(static_cast<std::uint16_t>(((j+0)*vsize+(i+0))+base));
647 0 : indices.push_back(static_cast<std::uint16_t>(((j+0)*vsize+(i+1))+base));
648 0 : indices.push_back(static_cast<std::uint16_t>(((j+1)*vsize+(i+1))+base));
649 :
650 0 : indices.push_back(static_cast<std::uint16_t>(((j+1)*vsize+(i+1))+base));
651 0 : indices.push_back(static_cast<std::uint16_t>(((j+1)*vsize+(i+0))+base));
652 0 : indices.push_back(static_cast<std::uint16_t>(((j+0)*vsize+(i+0))+base));
653 : }
654 : }
655 : }
656 : }
657 0 : splat.m_IndexCount=indices.size()-splat.m_IndexStart;
658 : }
659 :
660 : // Release existing vertex buffer chunk
661 0 : m_VBBaseIndices.Reset();
662 :
663 0 : ENSURE(indices.size());
664 :
665 : // Construct vertex buffer
666 0 : m_VBBaseIndices = g_Renderer.GetVertexBufferManager().AllocateChunk(
667 : sizeof(std::uint16_t), indices.size(),
668 : Renderer::Backend::IBuffer::Type::INDEX,
669 0 : Renderer::Backend::IBuffer::Usage::TRANSFER_DST, nullptr, CVertexBufferManager::Group::TERRAIN);
670 0 : m_VBBaseIndices->m_Owner->UpdateChunkVertices(m_VBBaseIndices.Get(), &indices[0]);
671 0 : }
672 :
673 :
674 0 : void CPatchRData::BuildVertices()
675 : {
676 0 : PROFILE3("build vertices");
677 :
678 : // create both vertices and lighting colors
679 :
680 : // number of vertices in each direction in each patch
681 0 : ssize_t vsize = PATCH_SIZE + 1;
682 :
683 0 : std::vector<SBaseVertex> vertices;
684 0 : vertices.resize(vsize * vsize);
685 :
686 : // get index of this patch
687 0 : ssize_t px = m_Patch->m_X;
688 0 : ssize_t pz = m_Patch->m_Z;
689 :
690 0 : CTerrain* terrain = m_Patch->m_Parent;
691 :
692 : // build vertices
693 0 : for (ssize_t j = 0; j < vsize; ++j)
694 : {
695 0 : for (ssize_t i = 0; i < vsize; ++i)
696 : {
697 0 : ssize_t ix = px * PATCH_SIZE + i;
698 0 : ssize_t iz = pz * PATCH_SIZE + j;
699 0 : ssize_t v = j * vsize + i;
700 :
701 : // calculate vertex data
702 0 : terrain->CalcPosition(ix, iz, vertices[v].m_Position);
703 :
704 0 : CVector3D normal;
705 0 : terrain->CalcNormal(ix, iz, normal);
706 0 : vertices[v].m_Normal = normal;
707 : }
708 : }
709 :
710 : // upload to vertex buffer
711 0 : if (!m_VBBase)
712 : {
713 0 : m_VBBase = g_Renderer.GetVertexBufferManager().AllocateChunk(
714 : sizeof(SBaseVertex), vsize * vsize,
715 : Renderer::Backend::IBuffer::Type::VERTEX,
716 : Renderer::Backend::IBuffer::Usage::TRANSFER_DST,
717 0 : nullptr, CVertexBufferManager::Group::TERRAIN);
718 : }
719 :
720 0 : m_VBBase->m_Owner->UpdateChunkVertices(m_VBBase.Get(), &vertices[0]);
721 0 : }
722 :
723 0 : void CPatchRData::BuildSide(std::vector<SSideVertex>& vertices, CPatchSideFlags side)
724 : {
725 0 : ssize_t vsize = PATCH_SIZE + 1;
726 0 : CTerrain* terrain = m_Patch->m_Parent;
727 0 : CmpPtr<ICmpWaterManager> cmpWaterManager(*m_Simulation, SYSTEM_ENTITY);
728 :
729 0 : for (ssize_t k = 0; k < vsize; k++)
730 : {
731 0 : ssize_t gx = m_Patch->m_X * PATCH_SIZE;
732 0 : ssize_t gz = m_Patch->m_Z * PATCH_SIZE;
733 0 : switch (side)
734 : {
735 0 : case CPATCH_SIDE_NEGX: gz += k; break;
736 0 : case CPATCH_SIDE_POSX: gx += PATCH_SIZE; gz += PATCH_SIZE-k; break;
737 0 : case CPATCH_SIDE_NEGZ: gx += PATCH_SIZE-k; break;
738 0 : case CPATCH_SIDE_POSZ: gz += PATCH_SIZE; gx += k; break;
739 : }
740 :
741 0 : CVector3D pos;
742 0 : terrain->CalcPosition(gx, gz, pos);
743 :
744 : // Clamp the height to the water level
745 0 : float waterHeight = 0.f;
746 0 : if (cmpWaterManager)
747 0 : waterHeight = cmpWaterManager->GetExactWaterLevel(pos.X, pos.Z);
748 0 : pos.Y = std::max(pos.Y, waterHeight);
749 :
750 0 : SSideVertex v0, v1;
751 0 : v0.m_Position = pos;
752 0 : v1.m_Position = pos;
753 0 : v1.m_Position.Y = 0;
754 :
755 0 : if (k == 0)
756 : {
757 0 : vertices.emplace_back(v1);
758 0 : vertices.emplace_back(v0);
759 : }
760 0 : if (k > 0)
761 : {
762 0 : const size_t lastIndex = vertices.size() - 1;
763 0 : vertices.emplace_back(v1);
764 0 : vertices.emplace_back(vertices[lastIndex]);
765 0 : vertices.emplace_back(v0);
766 0 : vertices.emplace_back(v1);
767 0 : if (k + 1 < vsize)
768 : {
769 0 : vertices.emplace_back(v1);
770 0 : vertices.emplace_back(v0);
771 : }
772 : }
773 : }
774 0 : }
775 :
776 0 : void CPatchRData::BuildSides()
777 : {
778 0 : PROFILE3("build sides");
779 :
780 0 : std::vector<SSideVertex> sideVertices;
781 :
782 0 : int sideFlags = m_Patch->GetSideFlags();
783 :
784 : // If no sides are enabled, we don't need to do anything
785 0 : if (!sideFlags)
786 : return;
787 :
788 : // For each side, generate a tristrip by adding a vertex at ground/water
789 : // level and a vertex underneath at height 0.
790 :
791 0 : if (sideFlags & CPATCH_SIDE_NEGX)
792 0 : BuildSide(sideVertices, CPATCH_SIDE_NEGX);
793 :
794 0 : if (sideFlags & CPATCH_SIDE_POSX)
795 0 : BuildSide(sideVertices, CPATCH_SIDE_POSX);
796 :
797 0 : if (sideFlags & CPATCH_SIDE_NEGZ)
798 0 : BuildSide(sideVertices, CPATCH_SIDE_NEGZ);
799 :
800 0 : if (sideFlags & CPATCH_SIDE_POSZ)
801 0 : BuildSide(sideVertices, CPATCH_SIDE_POSZ);
802 :
803 0 : if (sideVertices.empty())
804 : return;
805 :
806 0 : if (!m_VBSides)
807 : {
808 0 : m_VBSides = g_Renderer.GetVertexBufferManager().AllocateChunk(
809 : sizeof(SSideVertex), sideVertices.size(),
810 : Renderer::Backend::IBuffer::Type::VERTEX,
811 : Renderer::Backend::IBuffer::Usage::TRANSFER_DST,
812 0 : nullptr, CVertexBufferManager::Group::DEFAULT);
813 : }
814 0 : m_VBSides->m_Owner->UpdateChunkVertices(m_VBSides.Get(), &sideVertices[0]);
815 0 : }
816 :
817 0 : void CPatchRData::Build()
818 : {
819 0 : BuildVertices();
820 0 : BuildSides();
821 0 : BuildIndices();
822 0 : BuildBlends();
823 0 : BuildWater();
824 0 : }
825 :
826 0 : void CPatchRData::Update(CSimulation2* simulation)
827 : {
828 0 : m_Simulation = simulation;
829 0 : if (m_UpdateFlags!=0) {
830 : // TODO,RC 11/04/04 - need to only rebuild necessary bits of renderdata rather
831 : // than everything; it's complicated slightly because the blends are dependent
832 : // on both vertex and index data
833 0 : BuildVertices();
834 0 : BuildSides();
835 0 : BuildIndices();
836 0 : BuildBlends();
837 0 : BuildWater();
838 :
839 0 : m_UpdateFlags=0;
840 : }
841 0 : }
842 :
843 : // To minimise the cost of memory allocations, everything used for computing
844 : // batches uses a arena allocator. (All allocations are short-lived so we can
845 : // just throw away the whole arena at the end of each frame.)
846 :
847 : // std::map types with appropriate arena allocators and default comparison operator
848 : template<class Key, class Value>
849 : using PooledBatchMap = std::map<Key, Value, std::less<Key>, PS::Memory::AllocatorAdapter<std::pair<Key const, Value>, PS::Memory::ScopedLinearAllocator>>;
850 :
851 : // Equivalent to "m[k]", when it returns a arena-allocated std::map (since we can't
852 : // use the default constructor in that case)
853 : template<typename M>
854 0 : typename M::mapped_type& PooledMapGet(M& m, const typename M::key_type& k, PS::Memory::ScopedLinearAllocator& arena)
855 : {
856 0 : return m.insert(std::make_pair(k,
857 0 : typename M::mapped_type(typename M::mapped_type::key_compare(), typename M::mapped_type::allocator_type(arena))
858 0 : )).first->second;
859 : }
860 :
861 : // Equivalent to "m[k]", when it returns a std::pair of arena-allocated std::vectors
862 : template<typename M>
863 0 : typename M::mapped_type& PooledPairGet(M& m, const typename M::key_type& k, PS::Memory::ScopedLinearAllocator& arena)
864 : {
865 0 : return m.insert(std::make_pair(k, std::make_pair(
866 0 : typename M::mapped_type::first_type(typename M::mapped_type::first_type::allocator_type(arena)),
867 0 : typename M::mapped_type::second_type(typename M::mapped_type::second_type::allocator_type(arena))
868 0 : ))).first->second;
869 : }
870 :
871 : // Each multidraw batch has a list of index counts, and a list of pointers-to-first-indexes
872 : using BatchElements = std::pair<
873 : std::vector<std::uint32_t, PS::Memory::AllocatorAdapter<std::uint32_t, PS::Memory::ScopedLinearAllocator>>,
874 : std::vector<std::uint32_t, PS::Memory::AllocatorAdapter<std::uint32_t, PS::Memory::ScopedLinearAllocator>>>;
875 :
876 : // Group batches by index buffer
877 : using IndexBufferBatches = PooledBatchMap<CVertexBuffer*, BatchElements>;
878 :
879 : // Group batches by vertex buffer
880 : using VertexBufferBatches = PooledBatchMap<CVertexBuffer*, IndexBufferBatches>;
881 :
882 : // Group batches by texture
883 : using TextureBatches = PooledBatchMap<CTerrainTextureEntry*, VertexBufferBatches>;
884 :
885 : // Group batches by shaders.
886 : using ShaderTechniqueBatches = PooledBatchMap<std::pair<CStrIntern, CShaderDefines>, TextureBatches>;
887 :
888 0 : void CPatchRData::RenderBases(
889 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
890 : Renderer::Backend::IVertexInputLayout* vertexInputLayout,
891 : const std::vector<CPatchRData*>& patches, const CShaderDefines& context,
892 : ShadowMap* shadow, const CMaterial::Pass materialPass)
893 : {
894 0 : PROFILE3("render terrain bases");
895 0 : GPU_SCOPED_LABEL(deviceCommandContext, "Render terrain bases");
896 :
897 0 : PS::Memory::ScopedLinearAllocator scopedLinearAllocator{g_Renderer.GetLinearAllocator()};
898 :
899 0 : ShaderTechniqueBatches batches(ShaderTechniqueBatches::key_compare(), (ShaderTechniqueBatches::allocator_type(scopedLinearAllocator)));
900 :
901 0 : PROFILE_START("compute batches");
902 :
903 : // Collect all the patches' base splats into their appropriate batches
904 0 : for (size_t i = 0; i < patches.size(); ++i)
905 : {
906 0 : CPatchRData* patch = patches[i];
907 0 : for (size_t j = 0; j < patch->m_Splats.size(); ++j)
908 : {
909 0 : SSplat& splat = patch->m_Splats[j];
910 0 : const CMaterial& material = splat.m_Texture->GetMaterial();
911 0 : const auto& shader{material.GetShader(materialPass)};
912 0 : if (shader.effect.empty())
913 : {
914 0 : LOGERROR("Terrain renderer failed to load shader effect.\n");
915 0 : continue;
916 0 : }
917 :
918 0 : BatchElements& batch = PooledPairGet(
919 0 : PooledMapGet(
920 0 : PooledMapGet(
921 0 : PooledMapGet(
922 0 : batches, std::make_pair(shader.effect, shader.defines),
923 : scopedLinearAllocator),
924 0 : splat.m_Texture, scopedLinearAllocator
925 : ),
926 0 : patch->m_VBBase->m_Owner, scopedLinearAllocator
927 : ),
928 0 : patch->m_VBBaseIndices->m_Owner, scopedLinearAllocator
929 : );
930 :
931 0 : batch.first.push_back(splat.m_IndexCount);
932 :
933 0 : batch.second.push_back(patch->m_VBBaseIndices->m_Index + splat.m_IndexStart);
934 : }
935 : }
936 :
937 0 : PROFILE_END("compute batches");
938 :
939 : // Render each batch
940 0 : for (ShaderTechniqueBatches::iterator itTech = batches.begin(); itTech != batches.end(); ++itTech)
941 : {
942 0 : CShaderDefines defines = context;
943 0 : defines.SetMany(itTech->first.second);
944 0 : CShaderTechniquePtr techBase = g_Renderer.GetShaderManager().LoadEffect(
945 0 : itTech->first.first, defines);
946 :
947 0 : const int numPasses = techBase->GetNumPasses();
948 0 : for (int pass = 0; pass < numPasses; ++pass)
949 : {
950 0 : deviceCommandContext->SetGraphicsPipelineState(
951 : techBase->GetGraphicsPipelineState(pass));
952 0 : deviceCommandContext->BeginPass();
953 0 : Renderer::Backend::IShaderProgram* shader = techBase->GetShader(pass);
954 0 : TerrainRenderer::PrepareShader(deviceCommandContext, shader, shadow);
955 :
956 0 : const int32_t baseTexBindingSlot =
957 0 : shader->GetBindingSlot(str_baseTex);
958 0 : const int32_t textureTransformBindingSlot =
959 0 : shader->GetBindingSlot(str_textureTransform);
960 :
961 0 : TextureBatches& textureBatches = itTech->second;
962 0 : for (TextureBatches::iterator itt = textureBatches.begin(); itt != textureBatches.end(); ++itt)
963 : {
964 0 : if (!itt->first->GetMaterial().GetSamplers().empty())
965 : {
966 : const CMaterial::SamplersVector& samplers =
967 : itt->first->GetMaterial().GetSamplers();
968 0 : for(const CMaterial::TextureSampler& samp : samplers)
969 0 : samp.Sampler->UploadBackendTextureIfNeeded(deviceCommandContext);
970 0 : for(const CMaterial::TextureSampler& samp : samplers)
971 : {
972 0 : deviceCommandContext->SetTexture(
973 0 : shader->GetBindingSlot(samp.Name),
974 0 : samp.Sampler->GetBackendTexture());
975 : }
976 :
977 0 : itt->first->GetMaterial().GetStaticUniforms().BindUniforms(
978 : deviceCommandContext, shader);
979 :
980 0 : float c = itt->first->GetTextureMatrix()[0];
981 0 : float ms = itt->first->GetTextureMatrix()[8];
982 0 : deviceCommandContext->SetUniform(
983 : textureTransformBindingSlot, c, ms);
984 : }
985 : else
986 : {
987 0 : deviceCommandContext->SetTexture(
988 : baseTexBindingSlot,
989 0 : g_Renderer.GetTextureManager().GetErrorTexture()->GetBackendTexture());
990 : }
991 :
992 0 : for (VertexBufferBatches::iterator itv = itt->second.begin(); itv != itt->second.end(); ++itv)
993 : {
994 0 : ENSURE(!itv->first->GetBuffer()->IsDynamic());
995 :
996 0 : deviceCommandContext->SetVertexInputLayout(vertexInputLayout);
997 :
998 0 : deviceCommandContext->SetVertexBuffer(0, itv->first->GetBuffer(), 0);
999 :
1000 0 : for (IndexBufferBatches::iterator it = itv->second.begin(); it != itv->second.end(); ++it)
1001 : {
1002 0 : ENSURE(!it->first->GetBuffer()->IsDynamic());
1003 0 : deviceCommandContext->SetIndexBuffer(it->first->GetBuffer());
1004 :
1005 : BatchElements& batch = it->second;
1006 :
1007 0 : for (size_t i = 0; i < batch.first.size(); ++i)
1008 0 : deviceCommandContext->DrawIndexed(batch.second[i], batch.first[i], 0);
1009 :
1010 0 : g_Renderer.m_Stats.m_DrawCalls++;
1011 0 : g_Renderer.m_Stats.m_TerrainTris += std::accumulate(batch.first.begin(), batch.first.end(), 0) / 3;
1012 : }
1013 : }
1014 : }
1015 0 : deviceCommandContext->EndPass();
1016 : }
1017 0 : }
1018 0 : }
1019 :
1020 : /**
1021 : * Helper structure for RenderBlends.
1022 : */
1023 : struct SBlendBatch
1024 : {
1025 0 : SBlendBatch(PS::Memory::ScopedLinearAllocator& allocator) :
1026 0 : m_Batches(VertexBufferBatches::key_compare(), VertexBufferBatches::allocator_type(allocator))
1027 : {
1028 : }
1029 :
1030 : CTerrainTextureEntry* m_Texture;
1031 : CShaderTechniquePtr m_ShaderTech;
1032 : VertexBufferBatches m_Batches;
1033 : };
1034 :
1035 : /**
1036 : * Helper structure for RenderBlends.
1037 : */
1038 0 : struct SBlendStackItem
1039 : {
1040 0 : SBlendStackItem(CVertexBuffer::VBChunk* v, CVertexBuffer::VBChunk* i,
1041 0 : const std::vector<CPatchRData::SSplat>& s, PS::Memory::ScopedLinearAllocator& allocator) :
1042 0 : vertices(v), indices(i), splats(s.begin(), s.end(), SplatStack::allocator_type(allocator))
1043 : {
1044 : }
1045 :
1046 : using SplatStack = std::vector<CPatchRData::SSplat, PS::Memory::AllocatorAdapter<CPatchRData::SSplat, PS::Memory::ScopedLinearAllocator>>;
1047 : CVertexBuffer::VBChunk* vertices;
1048 : CVertexBuffer::VBChunk* indices;
1049 : SplatStack splats;
1050 : };
1051 :
1052 0 : void CPatchRData::RenderBlends(
1053 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
1054 : Renderer::Backend::IVertexInputLayout* vertexInputLayout,
1055 : const std::vector<CPatchRData*>& patches, const CShaderDefines& context,
1056 : ShadowMap* shadow, const CMaterial::Pass materialPass)
1057 : {
1058 0 : PROFILE3("render terrain blends");
1059 0 : GPU_SCOPED_LABEL(deviceCommandContext, "Render terrain blends");
1060 :
1061 0 : PS::Memory::ScopedLinearAllocator scopedLinearAllocator{g_Renderer.GetLinearAllocator()};
1062 :
1063 0 : using BatchesStack = std::vector<SBlendBatch, PS::Memory::AllocatorAdapter<SBlendBatch, PS::Memory::ScopedLinearAllocator>>;
1064 0 : BatchesStack batches((BatchesStack::allocator_type(scopedLinearAllocator)));
1065 :
1066 0 : CShaderDefines contextBlend = context;
1067 0 : contextBlend.Add(str_BLEND, str_1);
1068 :
1069 0 : PROFILE_START("compute batches");
1070 :
1071 : // Reserve an arbitrary size that's probably big enough in most cases,
1072 : // to avoid heavy reallocations
1073 0 : batches.reserve(256);
1074 :
1075 0 : using BlendStacks = std::vector<SBlendStackItem, PS::Memory::AllocatorAdapter<SBlendStackItem, PS::Memory::ScopedLinearAllocator>>;
1076 0 : BlendStacks blendStacks((BlendStacks::allocator_type(scopedLinearAllocator)));
1077 0 : blendStacks.reserve(patches.size());
1078 :
1079 : // Extract all the blend splats from each patch
1080 0 : for (size_t i = 0; i < patches.size(); ++i)
1081 : {
1082 0 : CPatchRData* patch = patches[i];
1083 0 : if (!patch->m_BlendSplats.empty())
1084 : {
1085 0 : blendStacks.push_back(SBlendStackItem(patch->m_VBBlends.Get(), patch->m_VBBlendIndices.Get(), patch->m_BlendSplats, scopedLinearAllocator));
1086 : // Reverse the splats so the first to be rendered is at the back of the list
1087 0 : std::reverse(blendStacks.back().splats.begin(), blendStacks.back().splats.end());
1088 : }
1089 : }
1090 :
1091 : // Rearrange the collection of splats to be grouped by texture, preserving
1092 : // order of splats within each patch:
1093 : // (This is exactly the same algorithm used in CPatchRData::BuildBlends,
1094 : // but applied to patch-sized splats rather than to tile-sized splats;
1095 : // see that function for comments on the algorithm.)
1096 0 : while (true)
1097 : {
1098 0 : if (!batches.empty())
1099 : {
1100 0 : CTerrainTextureEntry* tex = batches.back().m_Texture;
1101 :
1102 0 : for (size_t k = 0; k < blendStacks.size(); ++k)
1103 : {
1104 0 : SBlendStackItem::SplatStack& splats = blendStacks[k].splats;
1105 0 : if (!splats.empty() && splats.back().m_Texture == tex)
1106 : {
1107 0 : CVertexBuffer::VBChunk* vertices = blendStacks[k].vertices;
1108 0 : CVertexBuffer::VBChunk* indices = blendStacks[k].indices;
1109 :
1110 0 : BatchElements& batch = PooledPairGet(PooledMapGet(batches.back().m_Batches, vertices->m_Owner, scopedLinearAllocator), indices->m_Owner, scopedLinearAllocator);
1111 0 : batch.first.push_back(splats.back().m_IndexCount);
1112 :
1113 0 : batch.second.push_back(indices->m_Index + splats.back().m_IndexStart);
1114 :
1115 0 : splats.pop_back();
1116 : }
1117 : }
1118 : }
1119 :
1120 : CTerrainTextureEntry* bestTex = NULL;
1121 : size_t bestStackSize = 0;
1122 :
1123 0 : for (size_t k = 0; k < blendStacks.size(); ++k)
1124 : {
1125 0 : SBlendStackItem::SplatStack& splats = blendStacks[k].splats;
1126 0 : if (splats.size() > bestStackSize)
1127 : {
1128 0 : bestStackSize = splats.size();
1129 0 : bestTex = splats.back().m_Texture;
1130 : }
1131 : }
1132 :
1133 0 : if (bestStackSize == 0)
1134 : break;
1135 :
1136 0 : SBlendBatch layer(scopedLinearAllocator);
1137 0 : layer.m_Texture = bestTex;
1138 0 : if (!bestTex->GetMaterial().GetSamplers().empty())
1139 : {
1140 0 : CShaderDefines defines = contextBlend;
1141 0 : const auto& shader{bestTex->GetMaterial().GetShader(materialPass)};
1142 0 : defines.SetMany(shader.defines);
1143 : // TODO: move enabling blend to XML.
1144 0 : const CStrIntern shaderEffect{shader.effect};
1145 0 : if (shaderEffect != str_terrain_base && shaderEffect != str_terrain_base_reflections && shaderEffect != str_terrain_base_wireframe)
1146 : {
1147 0 : ONCE(LOGWARNING("Shader effect '{}' doesn't support semi-transparent terrain "
1148 : "rendering.", shaderEffect.string()));
1149 : }
1150 0 : layer.m_ShaderTech = g_Renderer.GetShaderManager().LoadEffect([](const CStrIntern shaderEffect)
1151 : {
1152 0 : if (shaderEffect == str_terrain_base)
1153 0 : return str_terrain_blend;
1154 0 : if (shaderEffect == str_terrain_base_reflections)
1155 0 : return str_terrain_blend_reflections;
1156 0 : if (shaderEffect == str_terrain_base_wireframe)
1157 0 : return str_terrain_blend_wireframe;
1158 : return shaderEffect;
1159 0 : }(shaderEffect), defines);
1160 : }
1161 0 : batches.push_back(layer);
1162 0 : }
1163 :
1164 0 : PROFILE_END("compute batches");
1165 :
1166 0 : CVertexBuffer* lastVB = nullptr;
1167 0 : Renderer::Backend::IShaderProgram* previousShader = nullptr;
1168 0 : for (BatchesStack::iterator itTechBegin = batches.begin(), itTechEnd = batches.begin(); itTechBegin != batches.end(); itTechBegin = itTechEnd)
1169 : {
1170 0 : while (itTechEnd != batches.end() && itTechEnd->m_ShaderTech == itTechBegin->m_ShaderTech)
1171 0 : ++itTechEnd;
1172 :
1173 0 : const CShaderTechniquePtr& techBase = itTechBegin->m_ShaderTech;
1174 0 : const int numPasses = techBase->GetNumPasses();
1175 0 : for (int pass = 0; pass < numPasses; ++pass)
1176 : {
1177 0 : deviceCommandContext->SetGraphicsPipelineState(
1178 : techBase->GetGraphicsPipelineState(pass));
1179 0 : deviceCommandContext->BeginPass();
1180 :
1181 0 : Renderer::Backend::IShaderProgram* shader = techBase->GetShader(pass);
1182 0 : TerrainRenderer::PrepareShader(deviceCommandContext, shader, shadow);
1183 :
1184 0 : Renderer::Backend::ITexture* lastBlendTex = nullptr;
1185 :
1186 0 : const int32_t baseTexBindingSlot =
1187 0 : shader->GetBindingSlot(str_baseTex);
1188 0 : const int32_t blendTexBindingSlot =
1189 0 : shader->GetBindingSlot(str_blendTex);
1190 0 : const int32_t textureTransformBindingSlot =
1191 0 : shader->GetBindingSlot(str_textureTransform);
1192 :
1193 0 : for (BatchesStack::iterator itt = itTechBegin; itt != itTechEnd; ++itt)
1194 : {
1195 0 : if (itt->m_Texture->GetMaterial().GetSamplers().empty())
1196 0 : continue;
1197 :
1198 : if (itt->m_Texture)
1199 : {
1200 : const CMaterial::SamplersVector& samplers = itt->m_Texture->GetMaterial().GetSamplers();
1201 0 : for (const CMaterial::TextureSampler& samp : samplers)
1202 0 : samp.Sampler->UploadBackendTextureIfNeeded(deviceCommandContext);
1203 0 : for (const CMaterial::TextureSampler& samp : samplers)
1204 : {
1205 0 : deviceCommandContext->SetTexture(
1206 0 : shader->GetBindingSlot(samp.Name),
1207 0 : samp.Sampler->GetBackendTexture());
1208 : }
1209 :
1210 0 : Renderer::Backend::ITexture* currentBlendTex = itt->m_Texture->m_TerrainAlpha->second.m_CompositeAlphaMap.get();
1211 0 : if (currentBlendTex != lastBlendTex)
1212 : {
1213 0 : deviceCommandContext->SetTexture(
1214 : blendTexBindingSlot, currentBlendTex);
1215 : lastBlendTex = currentBlendTex;
1216 : }
1217 :
1218 0 : itt->m_Texture->GetMaterial().GetStaticUniforms().BindUniforms(deviceCommandContext, shader);
1219 :
1220 0 : float c = itt->m_Texture->GetTextureMatrix()[0];
1221 0 : float ms = itt->m_Texture->GetTextureMatrix()[8];
1222 0 : deviceCommandContext->SetUniform(
1223 : textureTransformBindingSlot, c, ms);
1224 : }
1225 : else
1226 : {
1227 : deviceCommandContext->SetTexture(
1228 : baseTexBindingSlot, g_Renderer.GetTextureManager().GetErrorTexture()->GetBackendTexture());
1229 : }
1230 :
1231 0 : for (VertexBufferBatches::iterator itv = itt->m_Batches.begin(); itv != itt->m_Batches.end(); ++itv)
1232 : {
1233 : // Rebind the VB only if it changed since the last batch
1234 0 : if (itv->first != lastVB || shader != previousShader)
1235 : {
1236 0 : lastVB = itv->first;
1237 0 : previousShader = shader;
1238 :
1239 0 : ENSURE(!itv->first->GetBuffer()->IsDynamic());
1240 :
1241 0 : deviceCommandContext->SetVertexInputLayout(vertexInputLayout);
1242 :
1243 0 : deviceCommandContext->SetVertexBuffer(0, itv->first->GetBuffer(), 0);
1244 : }
1245 :
1246 0 : for (IndexBufferBatches::iterator it = itv->second.begin(); it != itv->second.end(); ++it)
1247 : {
1248 0 : ENSURE(!it->first->GetBuffer()->IsDynamic());
1249 0 : deviceCommandContext->SetIndexBuffer(it->first->GetBuffer());
1250 :
1251 : BatchElements& batch = it->second;
1252 :
1253 0 : for (size_t i = 0; i < batch.first.size(); ++i)
1254 0 : deviceCommandContext->DrawIndexed(batch.second[i], batch.first[i], 0);
1255 :
1256 0 : g_Renderer.m_Stats.m_DrawCalls++;
1257 0 : g_Renderer.m_Stats.m_BlendSplats++;
1258 0 : g_Renderer.m_Stats.m_TerrainTris += std::accumulate(batch.first.begin(), batch.first.end(), 0) / 3;
1259 : }
1260 : }
1261 : }
1262 0 : deviceCommandContext->EndPass();
1263 : }
1264 : }
1265 0 : }
1266 :
1267 0 : void CPatchRData::RenderStreams(
1268 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
1269 : Renderer::Backend::IVertexInputLayout* vertexInputLayout,
1270 : const std::vector<CPatchRData*>& patches)
1271 : {
1272 0 : PROFILE3("render terrain streams");
1273 :
1274 : // Each batch has a list of index counts, and a list of pointers-to-first-indexes
1275 0 : using StreamBatchElements = std::pair<std::vector<std::uint32_t>, std::vector<std::uint32_t>>;
1276 :
1277 : // Group batches by index buffer
1278 0 : using StreamIndexBufferBatches = std::map<CVertexBuffer*, StreamBatchElements>;
1279 :
1280 : // Group batches by vertex buffer
1281 0 : using StreamVertexBufferBatches = std::map<CVertexBuffer*, StreamIndexBufferBatches>;
1282 :
1283 0 : StreamVertexBufferBatches batches;
1284 :
1285 0 : PROFILE_START("compute batches");
1286 :
1287 : // Collect all the patches into their appropriate batches
1288 0 : for (const CPatchRData* patch : patches)
1289 : {
1290 0 : StreamBatchElements& batch = batches[patch->m_VBBase->m_Owner][patch->m_VBBaseIndices->m_Owner];
1291 :
1292 0 : batch.first.push_back(patch->m_VBBaseIndices->m_Count);
1293 :
1294 0 : batch.second.push_back(patch->m_VBBaseIndices->m_Index);
1295 : }
1296 :
1297 0 : PROFILE_END("compute batches");
1298 :
1299 0 : deviceCommandContext->SetVertexInputLayout(vertexInputLayout);
1300 :
1301 : // Render each batch
1302 0 : for (const std::pair<CVertexBuffer* const, StreamIndexBufferBatches>& streamBatch : batches)
1303 : {
1304 0 : ENSURE(!streamBatch.first->GetBuffer()->IsDynamic());
1305 :
1306 0 : deviceCommandContext->SetVertexBuffer(0, streamBatch.first->GetBuffer(), 0);
1307 :
1308 0 : for (const std::pair<CVertexBuffer* const, StreamBatchElements>& batchIndexBuffer : streamBatch.second)
1309 : {
1310 0 : ENSURE(!batchIndexBuffer.first->GetBuffer()->IsDynamic());
1311 0 : deviceCommandContext->SetIndexBuffer(batchIndexBuffer.first->GetBuffer());
1312 :
1313 : const StreamBatchElements& batch = batchIndexBuffer.second;
1314 :
1315 0 : for (size_t i = 0; i < batch.first.size(); ++i)
1316 0 : deviceCommandContext->DrawIndexed(batch.second[i], batch.first[i], 0);
1317 :
1318 0 : g_Renderer.m_Stats.m_DrawCalls++;
1319 0 : g_Renderer.m_Stats.m_TerrainTris += std::accumulate(batch.first.begin(), batch.first.end(), 0) / 3;
1320 : }
1321 : }
1322 0 : }
1323 :
1324 0 : void CPatchRData::RenderOutline(Renderer::Backend::IDeviceCommandContext& deviceCommandContext)
1325 : {
1326 0 : CTerrain* terrain = m_Patch->m_Parent;
1327 0 : ssize_t gx = m_Patch->m_X * PATCH_SIZE;
1328 0 : ssize_t gz = m_Patch->m_Z * PATCH_SIZE;
1329 :
1330 0 : CVector3D pos;
1331 0 : std::vector<CVector3D> line;
1332 0 : for (ssize_t i = 0, j = 0; i <= PATCH_SIZE; ++i)
1333 : {
1334 0 : terrain->CalcPosition(gx + i, gz + j, pos);
1335 0 : line.push_back(pos);
1336 : }
1337 0 : for (ssize_t i = PATCH_SIZE, j = 1; j <= PATCH_SIZE; ++j)
1338 : {
1339 0 : terrain->CalcPosition(gx + i, gz + j, pos);
1340 0 : line.push_back(pos);
1341 : }
1342 0 : for (ssize_t i = PATCH_SIZE-1, j = PATCH_SIZE; i >= 0; --i)
1343 : {
1344 0 : terrain->CalcPosition(gx + i, gz + j, pos);
1345 0 : line.push_back(pos);
1346 : }
1347 0 : for (ssize_t i = 0, j = PATCH_SIZE-1; j >= 0; --j)
1348 : {
1349 0 : terrain->CalcPosition(gx + i, gz + j, pos);
1350 0 : line.push_back(pos);
1351 : }
1352 :
1353 0 : g_Renderer.GetDebugRenderer().DrawLine(deviceCommandContext, line, CColor(0.0f, 0.0f, 1.0f, 1.0f), 0.1f);
1354 0 : }
1355 :
1356 0 : void CPatchRData::RenderSides(
1357 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
1358 : Renderer::Backend::IVertexInputLayout* vertexInputLayout,
1359 : const std::vector<CPatchRData*>& patches)
1360 : {
1361 0 : PROFILE3("render terrain sides");
1362 0 : GPU_SCOPED_LABEL(deviceCommandContext, "Render terrain sides");
1363 :
1364 0 : if (patches.empty())
1365 0 : return;
1366 :
1367 0 : deviceCommandContext->SetVertexInputLayout(vertexInputLayout);
1368 :
1369 0 : CVertexBuffer* lastVB = nullptr;
1370 0 : for (CPatchRData* patch : patches)
1371 : {
1372 0 : ENSURE(patch->m_UpdateFlags == 0);
1373 0 : if (!patch->m_VBSides)
1374 0 : continue;
1375 0 : if (lastVB != patch->m_VBSides->m_Owner)
1376 : {
1377 0 : lastVB = patch->m_VBSides->m_Owner;
1378 0 : ENSURE(!lastVB->GetBuffer()->IsDynamic());
1379 0 : deviceCommandContext->SetVertexBuffer(0, patch->m_VBSides->m_Owner->GetBuffer(), 0);
1380 : }
1381 :
1382 0 : deviceCommandContext->Draw(patch->m_VBSides->m_Index, patch->m_VBSides->m_Count);
1383 :
1384 : // bump stats
1385 0 : g_Renderer.m_Stats.m_DrawCalls++;
1386 0 : g_Renderer.m_Stats.m_TerrainTris += patch->m_VBSides->m_Count / 3;
1387 : }
1388 0 : }
1389 :
1390 0 : void CPatchRData::RenderPriorities(CTextRenderer& textRenderer)
1391 : {
1392 0 : CTerrain* terrain = m_Patch->m_Parent;
1393 0 : const CCamera& camera{g_Game->GetView()->GetCamera()};
1394 :
1395 0 : for (ssize_t j = 0; j < PATCH_SIZE; ++j)
1396 : {
1397 0 : for (ssize_t i = 0; i < PATCH_SIZE; ++i)
1398 : {
1399 0 : ssize_t gx = m_Patch->m_X * PATCH_SIZE + i;
1400 0 : ssize_t gz = m_Patch->m_Z * PATCH_SIZE + j;
1401 :
1402 0 : CVector3D pos;
1403 0 : terrain->CalcPosition(gx, gz, pos);
1404 :
1405 : // Move a bit towards the center of the tile
1406 0 : pos.X += TERRAIN_TILE_SIZE/4.f;
1407 0 : pos.Z += TERRAIN_TILE_SIZE/4.f;
1408 :
1409 0 : const CVector2D screenPos{camera.GetScreenCoordinates(pos)};
1410 :
1411 0 : textRenderer.PrintfAt(screenPos.X, screenPos.Y, L"%d",
1412 0 : m_Patch->m_MiniPatches[j][i].Priority);
1413 : }
1414 : }
1415 0 : }
1416 :
1417 : //
1418 : // Water build and rendering
1419 : //
1420 :
1421 : // Build vertex buffer for water vertices over our patch
1422 0 : void CPatchRData::BuildWater()
1423 : {
1424 0 : PROFILE3("build water");
1425 :
1426 : // Number of vertices in each direction in each patch
1427 0 : ENSURE(PATCH_SIZE % water_cell_size == 0);
1428 :
1429 0 : m_VBWater.Reset();
1430 0 : m_VBWaterIndices.Reset();
1431 0 : m_VBWaterShore.Reset();
1432 0 : m_VBWaterIndicesShore.Reset();
1433 :
1434 0 : m_WaterBounds.SetEmpty();
1435 :
1436 : // We need to use this to access the water manager or we may not have the
1437 : // actual values but some compiled-in defaults
1438 0 : CmpPtr<ICmpWaterManager> cmpWaterManager(*m_Simulation, SYSTEM_ENTITY);
1439 0 : if (!cmpWaterManager)
1440 0 : return;
1441 :
1442 : // Build data for water
1443 0 : std::vector<SWaterVertex> water_vertex_data;
1444 0 : std::vector<std::uint16_t> water_indices;
1445 0 : std::uint16_t water_index_map[PATCH_SIZE+1][PATCH_SIZE+1];
1446 0 : memset(water_index_map, 0xFF, sizeof(water_index_map));
1447 :
1448 : // Build data for shore
1449 0 : std::vector<SWaterVertex> water_vertex_data_shore;
1450 0 : std::vector<std::uint16_t> water_indices_shore;
1451 0 : std::uint16_t water_shore_index_map[PATCH_SIZE+1][PATCH_SIZE+1];
1452 0 : memset(water_shore_index_map, 0xFF, sizeof(water_shore_index_map));
1453 :
1454 0 : const WaterManager& waterManager = g_Renderer.GetSceneRenderer().GetWaterManager();
1455 :
1456 0 : CPatch* patch = m_Patch;
1457 0 : CTerrain* terrain = patch->m_Parent;
1458 :
1459 0 : ssize_t mapSize = terrain->GetVerticesPerSide();
1460 :
1461 : // Top-left coordinates of our patch.
1462 0 : ssize_t px = m_Patch->m_X * PATCH_SIZE;
1463 0 : ssize_t pz = m_Patch->m_Z * PATCH_SIZE;
1464 :
1465 : // To whoever implements different water heights, this is a TODO: water height)
1466 0 : float waterHeight = cmpWaterManager->GetExactWaterLevel(0.0f,0.0f);
1467 :
1468 : // The 4 points making a water tile.
1469 0 : int moves[4][2] = {
1470 : {0, 0},
1471 : {water_cell_size, 0},
1472 : {0, water_cell_size},
1473 : {water_cell_size, water_cell_size}
1474 : };
1475 : // Where to look for when checking for water for shore tiles.
1476 0 : int check[10][2] = {
1477 : {0, 0},
1478 : {water_cell_size, 0},
1479 : {water_cell_size*2, 0},
1480 : {0, water_cell_size},
1481 : {0, water_cell_size*2},
1482 : {water_cell_size, water_cell_size},
1483 : {water_cell_size*2, water_cell_size*2},
1484 : {-water_cell_size, 0},
1485 : {0, -water_cell_size},
1486 : {-water_cell_size, -water_cell_size}
1487 : };
1488 :
1489 : // build vertices, uv, and shader varying
1490 0 : for (ssize_t z = 0; z < PATCH_SIZE; z += water_cell_size)
1491 : {
1492 0 : for (ssize_t x = 0; x < PATCH_SIZE; x += water_cell_size)
1493 : {
1494 : // Check that this tile is close to water
1495 : bool nearWater = false;
1496 0 : for (size_t test = 0; test < 10; ++test)
1497 0 : if (terrain->GetVertexGroundLevel(x + px + check[test][0], z + pz + check[test][1]) < waterHeight)
1498 0 : nearWater = true;
1499 0 : if (!nearWater)
1500 0 : continue;
1501 :
1502 : // This is actually lying and I should call CcmpTerrain
1503 : /*if (!terrain->IsOnMap(x+x1, z+z1)
1504 : && !terrain->IsOnMap(x+x1, z+z1 + water_cell_size)
1505 : && !terrain->IsOnMap(x+x1 + water_cell_size, z+z1)
1506 : && !terrain->IsOnMap(x+x1 + water_cell_size, z+z1 + water_cell_size))
1507 : continue;*/
1508 :
1509 0 : for (int i = 0; i < 4; ++i)
1510 : {
1511 0 : if (water_index_map[z+moves[i][1]][x+moves[i][0]] != 0xFFFF)
1512 0 : continue;
1513 :
1514 0 : ssize_t xx = x + px + moves[i][0];
1515 0 : ssize_t zz = z + pz + moves[i][1];
1516 :
1517 0 : SWaterVertex vertex;
1518 0 : terrain->CalcPosition(xx,zz, vertex.m_Position);
1519 0 : float depth = waterHeight - vertex.m_Position.Y;
1520 :
1521 0 : vertex.m_Position.Y = waterHeight;
1522 :
1523 0 : m_WaterBounds += vertex.m_Position;
1524 :
1525 0 : vertex.m_WaterData = CVector2D(waterManager.m_WindStrength[xx + zz*mapSize], depth);
1526 :
1527 0 : water_index_map[z+moves[i][1]][x+moves[i][0]] = static_cast<std::uint16_t>(water_vertex_data.size());
1528 0 : water_vertex_data.push_back(vertex);
1529 : }
1530 0 : water_indices.push_back(water_index_map[z + moves[2][1]][x + moves[2][0]]);
1531 0 : water_indices.push_back(water_index_map[z + moves[0][1]][x + moves[0][0]]);
1532 0 : water_indices.push_back(water_index_map[z + moves[1][1]][x + moves[1][0]]);
1533 0 : water_indices.push_back(water_index_map[z + moves[1][1]][x + moves[1][0]]);
1534 0 : water_indices.push_back(water_index_map[z + moves[3][1]][x + moves[3][0]]);
1535 0 : water_indices.push_back(water_index_map[z + moves[2][1]][x + moves[2][0]]);
1536 :
1537 : // Check id this tile is partly over land.
1538 : // If so add a square over the terrain. This is necessary to render waves that go on shore.
1539 0 : if (terrain->GetVertexGroundLevel(x+px, z+pz) < waterHeight &&
1540 0 : terrain->GetVertexGroundLevel(x+px + water_cell_size, z+pz) < waterHeight &&
1541 0 : terrain->GetVertexGroundLevel(x+px, z+pz+water_cell_size) < waterHeight &&
1542 0 : terrain->GetVertexGroundLevel(x+px + water_cell_size, z+pz+water_cell_size) < waterHeight)
1543 0 : continue;
1544 :
1545 0 : for (int i = 0; i < 4; ++i)
1546 : {
1547 0 : if (water_shore_index_map[z+moves[i][1]][x+moves[i][0]] != 0xFFFF)
1548 0 : continue;
1549 0 : ssize_t xx = x + px + moves[i][0];
1550 0 : ssize_t zz = z + pz + moves[i][1];
1551 :
1552 0 : SWaterVertex vertex;
1553 0 : terrain->CalcPosition(xx,zz, vertex.m_Position);
1554 :
1555 0 : vertex.m_Position.Y += 0.02f;
1556 0 : m_WaterBounds += vertex.m_Position;
1557 :
1558 0 : vertex.m_WaterData = CVector2D(0.0f, -5.0f);
1559 :
1560 0 : water_shore_index_map[z+moves[i][1]][x+moves[i][0]] = static_cast<std::uint16_t>(water_vertex_data_shore.size());
1561 0 : water_vertex_data_shore.push_back(vertex);
1562 : }
1563 0 : if (terrain->GetTriangulationDir(x + px, z + pz))
1564 : {
1565 0 : water_indices_shore.push_back(water_shore_index_map[z + moves[2][1]][x + moves[2][0]]);
1566 0 : water_indices_shore.push_back(water_shore_index_map[z + moves[0][1]][x + moves[0][0]]);
1567 0 : water_indices_shore.push_back(water_shore_index_map[z + moves[1][1]][x + moves[1][0]]);
1568 0 : water_indices_shore.push_back(water_shore_index_map[z + moves[1][1]][x + moves[1][0]]);
1569 0 : water_indices_shore.push_back(water_shore_index_map[z + moves[3][1]][x + moves[3][0]]);
1570 0 : water_indices_shore.push_back(water_shore_index_map[z + moves[2][1]][x + moves[2][0]]);
1571 : }
1572 : else
1573 : {
1574 0 : water_indices_shore.push_back(water_shore_index_map[z + moves[3][1]][x + moves[3][0]]);
1575 0 : water_indices_shore.push_back(water_shore_index_map[z + moves[2][1]][x + moves[2][0]]);
1576 0 : water_indices_shore.push_back(water_shore_index_map[z + moves[0][1]][x + moves[0][0]]);
1577 0 : water_indices_shore.push_back(water_shore_index_map[z + moves[3][1]][x + moves[3][0]]);
1578 0 : water_indices_shore.push_back(water_shore_index_map[z + moves[0][1]][x + moves[0][0]]);
1579 0 : water_indices_shore.push_back(water_shore_index_map[z + moves[1][1]][x + moves[1][0]]);
1580 : }
1581 : }
1582 : }
1583 :
1584 : // No vertex buffers if no data generated
1585 0 : if (!water_indices.empty())
1586 : {
1587 0 : m_VBWater = g_Renderer.GetVertexBufferManager().AllocateChunk(
1588 : sizeof(SWaterVertex), water_vertex_data.size(),
1589 : Renderer::Backend::IBuffer::Type::VERTEX,
1590 : Renderer::Backend::IBuffer::Usage::TRANSFER_DST,
1591 0 : nullptr, CVertexBufferManager::Group::WATER);
1592 0 : m_VBWater->m_Owner->UpdateChunkVertices(m_VBWater.Get(), &water_vertex_data[0]);
1593 :
1594 0 : m_VBWaterIndices = g_Renderer.GetVertexBufferManager().AllocateChunk(
1595 : sizeof(std::uint16_t), water_indices.size(),
1596 : Renderer::Backend::IBuffer::Type::INDEX,
1597 : Renderer::Backend::IBuffer::Usage::TRANSFER_DST,
1598 0 : nullptr, CVertexBufferManager::Group::WATER);
1599 0 : m_VBWaterIndices->m_Owner->UpdateChunkVertices(m_VBWaterIndices.Get(), &water_indices[0]);
1600 : }
1601 :
1602 0 : if (!water_indices_shore.empty())
1603 : {
1604 0 : m_VBWaterShore = g_Renderer.GetVertexBufferManager().AllocateChunk(
1605 : sizeof(SWaterVertex), water_vertex_data_shore.size(),
1606 : Renderer::Backend::IBuffer::Type::VERTEX,
1607 : Renderer::Backend::IBuffer::Usage::TRANSFER_DST,
1608 0 : nullptr, CVertexBufferManager::Group::WATER);
1609 0 : m_VBWaterShore->m_Owner->UpdateChunkVertices(m_VBWaterShore.Get(), &water_vertex_data_shore[0]);
1610 :
1611 : // Construct indices buffer
1612 0 : m_VBWaterIndicesShore = g_Renderer.GetVertexBufferManager().AllocateChunk(
1613 : sizeof(std::uint16_t), water_indices_shore.size(),
1614 : Renderer::Backend::IBuffer::Type::INDEX,
1615 : Renderer::Backend::IBuffer::Usage::TRANSFER_DST,
1616 0 : nullptr, CVertexBufferManager::Group::WATER);
1617 0 : m_VBWaterIndicesShore->m_Owner->UpdateChunkVertices(m_VBWaterIndicesShore.Get(), &water_indices_shore[0]);
1618 : }
1619 0 : }
1620 :
1621 0 : void CPatchRData::RenderWaterSurface(
1622 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
1623 : Renderer::Backend::IVertexInputLayout* vertexInputLayout)
1624 : {
1625 0 : ASSERT(m_UpdateFlags == 0);
1626 :
1627 0 : if (!m_VBWater)
1628 : return;
1629 :
1630 0 : ENSURE(!m_VBWater->m_Owner->GetBuffer()->IsDynamic());
1631 0 : ENSURE(!m_VBWaterIndices->m_Owner->GetBuffer()->IsDynamic());
1632 :
1633 0 : const uint32_t stride = sizeof(SWaterVertex);
1634 0 : const uint32_t firstVertexOffset = m_VBWater->m_Index * stride;
1635 :
1636 0 : deviceCommandContext->SetVertexInputLayout(vertexInputLayout);
1637 :
1638 0 : deviceCommandContext->SetVertexBuffer(
1639 0 : 0, m_VBWater->m_Owner->GetBuffer(), firstVertexOffset);
1640 0 : deviceCommandContext->SetIndexBuffer(m_VBWaterIndices->m_Owner->GetBuffer());
1641 :
1642 0 : deviceCommandContext->DrawIndexed(m_VBWaterIndices->m_Index, m_VBWaterIndices->m_Count, 0);
1643 :
1644 0 : g_Renderer.m_Stats.m_DrawCalls++;
1645 0 : g_Renderer.m_Stats.m_WaterTris += m_VBWaterIndices->m_Count / 3;
1646 : }
1647 :
1648 0 : void CPatchRData::RenderWaterShore(
1649 : Renderer::Backend::IDeviceCommandContext* deviceCommandContext,
1650 : Renderer::Backend::IVertexInputLayout* vertexInputLayout)
1651 : {
1652 0 : ASSERT(m_UpdateFlags == 0);
1653 :
1654 0 : if (!m_VBWaterShore)
1655 : return;
1656 :
1657 0 : ENSURE(!m_VBWaterShore->m_Owner->GetBuffer()->IsDynamic());
1658 0 : ENSURE(!m_VBWaterIndicesShore->m_Owner->GetBuffer()->IsDynamic());
1659 :
1660 0 : const uint32_t stride = sizeof(SWaterVertex);
1661 0 : const uint32_t firstVertexOffset = m_VBWaterShore->m_Index * stride;
1662 :
1663 0 : deviceCommandContext->SetVertexInputLayout(vertexInputLayout);
1664 :
1665 0 : deviceCommandContext->SetVertexBuffer(
1666 0 : 0, m_VBWaterShore->m_Owner->GetBuffer(), firstVertexOffset);
1667 0 : deviceCommandContext->SetIndexBuffer(m_VBWaterIndicesShore->m_Owner->GetBuffer());
1668 :
1669 0 : deviceCommandContext->DrawIndexed(m_VBWaterIndicesShore->m_Index, m_VBWaterIndicesShore->m_Count, 0);
1670 :
1671 0 : g_Renderer.m_Stats.m_DrawCalls++;
1672 0 : g_Renderer.m_Stats.m_WaterTris += m_VBWaterIndicesShore->m_Count / 3;
1673 : }
|