LCOV - code coverage report
Current view: top level - source/graphics - Terrain.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 264 356 74.2 %
Date: 2026-12-03 01:19:39 Functions: 17 25 68.0 %

          Line data    Source code
       1             : /* Copyright (C) 2025 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 "Terrain.h"
      21             : 
      22             : #include "graphics/MiniPatch.h"
      23             : #include "graphics/Patch.h"
      24             : #include "graphics/RenderableObject.h"
      25             : #include "maths/BoundingBoxAligned.h"
      26             : #include "maths/FixedVector3D.h"
      27             : #include "maths/MathUtil.h"
      28             : 
      29             : #include <algorithm>
      30             : #include <cmath>
      31             : #include <cstring>
      32             : #include <iterator>
      33             : 
      34             : ///////////////////////////////////////////////////////////////////////////////
      35             : // CTerrain constructor
      36          24 : CTerrain::CTerrain()
      37          24 : : m_Heightmap(0), m_Patches(0), m_MapSize(0), m_MapSizePatches(0),
      38          24 : m_BaseColor(255, 255, 255, 255)
      39             : {
      40          24 : }
      41             : 
      42             : ///////////////////////////////////////////////////////////////////////////////
      43             : // CTerrain constructor
      44          24 : CTerrain::~CTerrain()
      45             : {
      46          24 :     ReleaseData();
      47          24 : }
      48             : 
      49             : 
      50             : ///////////////////////////////////////////////////////////////////////////////
      51             : // ReleaseData: delete any data allocated by this terrain
      52          57 : void CTerrain::ReleaseData()
      53             : {
      54          57 :     m_HeightMipmap.ReleaseData();
      55             : 
      56          57 :     delete[] m_Heightmap;
      57         774 :     delete[] m_Patches;
      58          57 : }
      59             : 
      60             : 
      61             : ///////////////////////////////////////////////////////////////////////////////
      62             : // Initialise: initialise this terrain to the given size
      63             : // using given heightmap to setup elevation data
      64          26 : bool CTerrain::Initialize(ssize_t patchesPerSide, const std::uint16_t* data)
      65             : {
      66             :     // clean up any previous terrain
      67          26 :     ReleaseData();
      68             : 
      69             :     // store terrain size
      70          26 :     m_MapSize = patchesPerSide * PATCH_SIZE + 1;
      71          26 :     m_MapSizePatches = patchesPerSide;
      72             :     // allocate data for new terrain
      73          26 :     m_Heightmap = new std::uint16_t[m_MapSize * m_MapSize];
      74         679 :     m_Patches = new CPatch[m_MapSizePatches * m_MapSizePatches];
      75             : 
      76             :     // given a heightmap?
      77          26 :     if (data)
      78             :     {
      79             :         // yes; keep a copy of it
      80          13 :         memcpy(m_Heightmap, data, m_MapSize * m_MapSize * sizeof(std::uint16_t));
      81             :     }
      82             :     else
      83             :     {
      84             :         // build a flat terrain
      85          13 :         memset(m_Heightmap, 0, m_MapSize * m_MapSize * sizeof(std::uint16_t));
      86             :     }
      87             : 
      88             :     // setup patch parents, indices etc
      89          26 :     InitialisePatches();
      90             : 
      91             :     // initialise mipmap
      92          26 :     m_HeightMipmap.Initialize(m_MapSize, m_Heightmap);
      93             : 
      94          26 :     return true;
      95             : }
      96             : 
      97             : ///////////////////////////////////////////////////////////////////////////////
      98             : // CalcPosition: calculate the world space position of the vertex at (i,j)
      99             : // If i,j is off the map, it acts as if the edges of the terrain are extended
     100             : // outwards to infinity
     101      420799 : void CTerrain::CalcPosition(ssize_t i, ssize_t j, CVector3D& pos) const
     102             : {
     103      420799 :     ssize_t hi = Clamp<ssize_t>(i, 0, m_MapSize - 1);
     104      420799 :     ssize_t hj = Clamp<ssize_t>(j, 0, m_MapSize - 1);
     105      420799 :     std::uint16_t height = m_Heightmap[hj*m_MapSize + hi];
     106      420799 :     pos.X = float(i*TERRAIN_TILE_SIZE);
     107      420799 :     pos.Y = float(height*HEIGHT_SCALE);
     108      420799 :     pos.Z = float(j*TERRAIN_TILE_SIZE);
     109      420799 : }
     110             : 
     111             : ///////////////////////////////////////////////////////////////////////////////
     112             : // CalcPositionFixed: calculate the world space position of the vertex at (i,j)
     113          15 : void CTerrain::CalcPositionFixed(ssize_t i, ssize_t j, CFixedVector3D& pos) const
     114             : {
     115          15 :     ssize_t hi = Clamp<ssize_t>(i, 0, m_MapSize - 1);
     116          15 :     ssize_t hj = Clamp<ssize_t>(j, 0, m_MapSize - 1);
     117          15 :     std::uint16_t height = m_Heightmap[hj*m_MapSize + hi];
     118          15 :     pos.X = fixed::FromInt(i) * (int)TERRAIN_TILE_SIZE;
     119             :     // fixed max value is 32767, but height is a std::uint16_t, so divide by two to avoid overflow
     120          15 :     pos.Y = fixed::FromInt(height/ 2 ) / ((int)HEIGHT_UNITS_PER_METRE / 2);
     121          15 :     pos.Z = fixed::FromInt(j) * (int)TERRAIN_TILE_SIZE;
     122          15 : }
     123             : 
     124             : 
     125             : ///////////////////////////////////////////////////////////////////////////////
     126             : // CalcNormal: calculate the world space normal of the vertex at (i,j)
     127           3 : void CTerrain::CalcNormal(ssize_t i, ssize_t j, CVector3D& normal) const
     128             : {
     129           3 :     CVector3D left, right, up, down;
     130             : 
     131             :     // Calculate normals of the four half-tile triangles surrounding this vertex:
     132             : 
     133             :     // get position of vertex where normal is being evaluated
     134           3 :     CVector3D basepos;
     135           3 :     CalcPosition(i, j, basepos);
     136             : 
     137           3 :     if (i > 0) {
     138           3 :         CalcPosition(i-1, j, left);
     139           3 :         left -= basepos;
     140           3 :         left.Normalize();
     141             :     }
     142             : 
     143           3 :     if (i < m_MapSize-1) {
     144           3 :         CalcPosition(i+1, j, right);
     145           3 :         right -= basepos;
     146           3 :         right.Normalize();
     147             :     }
     148             : 
     149           3 :     if (j > 0) {
     150           3 :         CalcPosition(i, j-1, up);
     151           3 :         up -= basepos;
     152           3 :         up.Normalize();
     153             :     }
     154             : 
     155           3 :     if (j < m_MapSize-1) {
     156           3 :         CalcPosition(i, j+1, down);
     157           3 :         down -= basepos;
     158           3 :         down.Normalize();
     159             :     }
     160             : 
     161           3 :     CVector3D n0 = up.Cross(left);
     162           3 :     CVector3D n1 = left.Cross(down);
     163           3 :     CVector3D n2 = down.Cross(right);
     164           3 :     CVector3D n3 = right.Cross(up);
     165             : 
     166             :     // Compute the mean of the normals
     167           3 :     normal = n0 + n1 + n2 + n3;
     168           3 :     float nlen=normal.Length();
     169           3 :     if (nlen>0.00001f) normal*=1.0f/nlen;
     170           3 : }
     171             : 
     172             : ///////////////////////////////////////////////////////////////////////////////
     173             : // CalcNormalFixed: calculate the world space normal of the vertex at (i,j)
     174           3 : void CTerrain::CalcNormalFixed(ssize_t i, ssize_t j, CFixedVector3D& normal) const
     175             : {
     176           3 :     CFixedVector3D left, right, up, down;
     177             : 
     178             :     // Calculate normals of the four half-tile triangles surrounding this vertex:
     179             : 
     180             :     // get position of vertex where normal is being evaluated
     181           3 :     CFixedVector3D basepos;
     182           3 :     CalcPositionFixed(i, j, basepos);
     183             : 
     184           3 :     if (i > 0) {
     185           3 :         CalcPositionFixed(i-1, j, left);
     186           3 :         left -= basepos;
     187           3 :         left.Normalize();
     188             :     }
     189             : 
     190           3 :     if (i < m_MapSize-1) {
     191           3 :         CalcPositionFixed(i+1, j, right);
     192           3 :         right -= basepos;
     193           3 :         right.Normalize();
     194             :     }
     195             : 
     196           3 :     if (j > 0) {
     197           3 :         CalcPositionFixed(i, j-1, up);
     198           3 :         up -= basepos;
     199           3 :         up.Normalize();
     200             :     }
     201             : 
     202           3 :     if (j < m_MapSize-1) {
     203           3 :         CalcPositionFixed(i, j+1, down);
     204           3 :         down -= basepos;
     205           3 :         down.Normalize();
     206             :     }
     207             : 
     208           3 :     CFixedVector3D n0 = up.Cross(left);
     209           3 :     CFixedVector3D n1 = left.Cross(down);
     210           3 :     CFixedVector3D n2 = down.Cross(right);
     211           3 :     CFixedVector3D n3 = right.Cross(up);
     212             : 
     213             :     // Compute the mean of the normals
     214           3 :     normal = n0 + n1 + n2 + n3;
     215           3 :     normal.Normalize();
     216           3 : }
     217             : 
     218        3201 : CVector3D CTerrain::CalcExactNormal(float x, float z) const
     219             : {
     220             :     // Clamp to size-2 so we can use the tiles (xi,zi)-(xi+1,zi+1)
     221        3201 :     const ssize_t xi = Clamp<ssize_t>(floor(x / TERRAIN_TILE_SIZE), 0, m_MapSize - 2);
     222        3201 :     const ssize_t zi = Clamp<ssize_t>(floor(z / TERRAIN_TILE_SIZE), 0, m_MapSize - 2);
     223             : 
     224        3201 :     const float xf = Clamp(x / TERRAIN_TILE_SIZE-xi, 0.0f, 1.0f);
     225        3201 :     const float zf = Clamp(z / TERRAIN_TILE_SIZE-zi, 0.0f, 1.0f);
     226             : 
     227        3201 :     float h00 = m_Heightmap[zi*m_MapSize + xi];
     228        3201 :     float h01 = m_Heightmap[(zi+1)*m_MapSize + xi];
     229        3201 :     float h10 = m_Heightmap[zi*m_MapSize + (xi+1)];
     230        3201 :     float h11 = m_Heightmap[(zi+1)*m_MapSize + (xi+1)];
     231             : 
     232             :     // Determine which terrain triangle this point is on,
     233             :     // then compute the normal of that triangle's plane
     234             : 
     235        3201 :     if (GetTriangulationDir(xi, zi))
     236             :     {
     237           0 :         if (xf + zf <= 1.f)
     238             :         {
     239             :             // Lower-left triangle (don't use h11)
     240           0 :             return -CVector3D(TERRAIN_TILE_SIZE, (h10-h00)*HEIGHT_SCALE, 0).Cross(CVector3D(0, (h01-h00)*HEIGHT_SCALE, TERRAIN_TILE_SIZE)).Normalized();
     241             :         }
     242             :         else
     243             :         {
     244             :             // Upper-right triangle (don't use h00)
     245           0 :             return -CVector3D(TERRAIN_TILE_SIZE, (h11-h01)*HEIGHT_SCALE, 0).Cross(CVector3D(0, (h11-h10)*HEIGHT_SCALE, TERRAIN_TILE_SIZE)).Normalized();
     246             :         }
     247             :     }
     248             :     else
     249             :     {
     250        3201 :         if (xf <= zf)
     251             :         {
     252             :             // Upper-left triangle (don't use h10)
     253        1764 :             return -CVector3D(TERRAIN_TILE_SIZE, (h11-h01)*HEIGHT_SCALE, 0).Cross(CVector3D(0, (h01-h00)*HEIGHT_SCALE, TERRAIN_TILE_SIZE)).Normalized();
     254             :         }
     255             :         else
     256             :         {
     257             :             // Lower-right triangle (don't use h01)
     258        1437 :             return -CVector3D(TERRAIN_TILE_SIZE, (h10-h00)*HEIGHT_SCALE, 0).Cross(CVector3D(0, (h11-h10)*HEIGHT_SCALE, TERRAIN_TILE_SIZE)).Normalized();
     259             :         }
     260             :     }
     261             : }
     262             : 
     263             : ///////////////////////////////////////////////////////////////////////////////
     264             : // GetPatch: return the patch at (i,j) in patch space, or null if the patch is
     265             : // out of bounds
     266        2605 : CPatch* CTerrain::GetPatch(ssize_t i, ssize_t j) const
     267             : {
     268             :     // range check (invalid indices are passed in by the culling and
     269             :     // patch blend code because they iterate from 0..#patches and examine
     270             :     // neighbors without checking if they're already on the edge)
     271        2605 :     if( (size_t)i >= (size_t)m_MapSizePatches || (size_t)j >= (size_t)m_MapSizePatches )
     272             :         return 0;
     273             : 
     274        2605 :     return &m_Patches[(j*m_MapSizePatches)+i];
     275             : }
     276             : 
     277             : 
     278             : ///////////////////////////////////////////////////////////////////////////////
     279             : // GetTile: return the tile at (i,j) in tile space, or null if the tile is out
     280             : // of bounds
     281           0 : CMiniPatch* CTerrain::GetTile(ssize_t i, ssize_t j) const
     282             : {
     283             :     // see comment above
     284           0 :     if( (size_t)i >= (size_t)(m_MapSize-1) || (size_t)j >= (size_t)(m_MapSize-1) )
     285             :         return 0;
     286             : 
     287           0 :     CPatch* patch=GetPatch(i/PATCH_SIZE, j/PATCH_SIZE); // can't fail (due to above check)
     288           0 :     return &patch->m_MiniPatches[j%PATCH_SIZE][i%PATCH_SIZE];
     289             : }
     290             : 
     291           0 : float CTerrain::GetVertexGroundLevel(ssize_t i, ssize_t j) const
     292             : {
     293           0 :     i = Clamp<ssize_t>(i, 0, m_MapSize - 1);
     294           0 :     j = Clamp<ssize_t>(j, 0, m_MapSize - 1);
     295           0 :     return HEIGHT_SCALE * m_Heightmap[j*m_MapSize + i];
     296             : }
     297             : 
     298           0 : fixed CTerrain::GetVertexGroundLevelFixed(ssize_t i, ssize_t j) const
     299             : {
     300           0 :     i = Clamp<ssize_t>(i, 0, m_MapSize - 1);
     301           0 :     j = Clamp<ssize_t>(j, 0, m_MapSize - 1);
     302             :     // Convert to fixed metres (being careful to avoid intermediate overflows)
     303           0 :     return fixed::FromInt(m_Heightmap[j*m_MapSize + i] / 2) / (int)(HEIGHT_UNITS_PER_METRE / 2);
     304             : }
     305             : 
     306     5308416 : fixed CTerrain::GetSlopeFixed(ssize_t i, ssize_t j) const
     307             : {
     308             :     // Clamp to size-2 so we can use the tiles (i,j)-(i+1,j+1)
     309     5308416 :     i = Clamp<ssize_t>(i, 0, m_MapSize - 2);
     310     5308416 :     j = Clamp<ssize_t>(j, 0, m_MapSize - 2);
     311             : 
     312     5308416 :     std::uint16_t h00 = m_Heightmap[j*m_MapSize + i];
     313     5308416 :     std::uint16_t h01 = m_Heightmap[(j+1)*m_MapSize + i];
     314     5308416 :     std::uint16_t h10 = m_Heightmap[j*m_MapSize + (i+1)];
     315     5308416 :     std::uint16_t h11 = m_Heightmap[(j+1)*m_MapSize + (i+1)];
     316             : 
     317             :     // Difference of highest point from lowest point
     318     5308416 :     std::uint16_t delta = std::max(std::max(h00, h01), std::max(h10, h11)) -
     319     5308416 :         std::min(std::min(h00, h01), std::min(h10, h11));
     320             : 
     321             :     // Compute fractional slope (being careful to avoid intermediate overflows)
     322     5308416 :     return fixed::FromInt(delta / TERRAIN_TILE_SIZE) / (int)HEIGHT_UNITS_PER_METRE;
     323             : }
     324             : 
     325           0 : fixed CTerrain::GetExactSlopeFixed(fixed x, fixed z) const
     326             : {
     327             :     // Clamp to size-2 so we can use the tiles (xi,zi)-(xi+1,zi+1)
     328           0 :     const ssize_t xi = Clamp<ssize_t>((x / static_cast<int>(TERRAIN_TILE_SIZE)).ToInt_RoundToZero(), 0, m_MapSize - 2);
     329           0 :     const ssize_t zi = Clamp<ssize_t>((z / static_cast<int>(TERRAIN_TILE_SIZE)).ToInt_RoundToZero(), 0, m_MapSize - 2);
     330             : 
     331           0 :     const fixed one = fixed::FromInt(1);
     332             : 
     333           0 :     const fixed xf = Clamp((x / static_cast<int>(TERRAIN_TILE_SIZE)) - fixed::FromInt(xi), fixed::Zero(), one);
     334           0 :     const fixed zf = Clamp((z / static_cast<int>(TERRAIN_TILE_SIZE)) - fixed::FromInt(zi), fixed::Zero(), one);
     335             : 
     336           0 :     std::uint16_t h00 = m_Heightmap[zi*m_MapSize + xi];
     337           0 :     std::uint16_t h01 = m_Heightmap[(zi+1)*m_MapSize + xi];
     338           0 :     std::uint16_t h10 = m_Heightmap[zi*m_MapSize + (xi+1)];
     339           0 :     std::uint16_t h11 = m_Heightmap[(zi+1)*m_MapSize + (xi+1)];
     340             : 
     341           0 :     std::uint16_t delta;
     342           0 :     if (GetTriangulationDir(xi, zi))
     343             :     {
     344           0 :         if (xf + zf <= one)
     345             :         {
     346             :             // Lower-left triangle (don't use h11)
     347           0 :             delta = std::max(std::max(h00, h01), h10) -
     348           0 :                     std::min(std::min(h00, h01), h10);
     349             :         }
     350             :         else
     351             :         {
     352             :             // Upper-right triangle (don't use h00)
     353           0 :             delta = std::max(std::max(h01, h10), h11) -
     354           0 :                     std::min(std::min(h01, h10), h11);
     355             :         }
     356             :     }
     357             :     else
     358             :     {
     359           0 :         if (xf <= zf)
     360             :         {
     361             :             // Upper-left triangle (don't use h10)
     362           0 :             delta = std::max(std::max(h00, h01), h11) -
     363           0 :                     std::min(std::min(h00, h01), h11);
     364             :         }
     365             :         else
     366             :         {
     367             :             // Lower-right triangle (don't use h01)
     368           0 :             delta = std::max(std::max(h00, h10), h11) -
     369           0 :                     std::min(std::min(h00, h10), h11);
     370             :         }
     371             :     }
     372             : 
     373             :     // Compute fractional slope (being careful to avoid intermediate overflows)
     374           0 :     return fixed::FromInt(delta / TERRAIN_TILE_SIZE) / (int)HEIGHT_UNITS_PER_METRE;
     375             : }
     376             : 
     377           0 : float CTerrain::GetFilteredGroundLevel(float x, float z, float radius) const
     378             : {
     379             :     // convert to [0,1] interval
     380           0 :     float nx = x / (TERRAIN_TILE_SIZE*m_MapSize);
     381           0 :     float nz = z / (TERRAIN_TILE_SIZE*m_MapSize);
     382           0 :     float nr = radius / (TERRAIN_TILE_SIZE*m_MapSize);
     383             : 
     384             :     // get trilinear filtered mipmap height
     385           0 :     return HEIGHT_SCALE * m_HeightMipmap.GetTrilinearGroundLevel(nx, nz, nr);
     386             : }
     387             : 
     388       14292 : float CTerrain::GetExactGroundLevel(float x, float z) const
     389             : {
     390             :     // Clamp to size-2 so we can use the tiles (xi,zi)-(xi+1,zi+1)
     391       14292 :     const ssize_t xi = Clamp<ssize_t>(floor(x / TERRAIN_TILE_SIZE), 0, m_MapSize - 2);
     392       14292 :     const ssize_t zi = Clamp<ssize_t>(floor(z / TERRAIN_TILE_SIZE), 0, m_MapSize - 2);
     393             : 
     394       14292 :     const float xf = Clamp(x / TERRAIN_TILE_SIZE - xi, 0.0f, 1.0f);
     395       14292 :     const float zf = Clamp(z / TERRAIN_TILE_SIZE - zi, 0.0f, 1.0f);
     396             : 
     397       14292 :     float h00 = m_Heightmap[zi*m_MapSize + xi];
     398       14292 :     float h01 = m_Heightmap[(zi+1)*m_MapSize + xi];
     399       14292 :     float h10 = m_Heightmap[zi*m_MapSize + (xi+1)];
     400       14292 :     float h11 = m_Heightmap[(zi+1)*m_MapSize + (xi+1)];
     401             : 
     402             :     // Determine which terrain triangle this point is on,
     403             :     // then compute the linearly-interpolated height on that triangle's plane
     404             : 
     405       14292 :     if (GetTriangulationDir(xi, zi))
     406             :     {
     407           0 :         if (xf + zf <= 1.f)
     408             :         {
     409             :             // Lower-left triangle (don't use h11)
     410           0 :             return HEIGHT_SCALE * (h00 + (h10-h00)*xf + (h01-h00)*zf);
     411             :         }
     412             :         else
     413             :         {
     414             :             // Upper-right triangle (don't use h00)
     415           0 :             return HEIGHT_SCALE * (h11 + (h01-h11)*(1-xf) + (h10-h11)*(1-zf));
     416             :         }
     417             :     }
     418             :     else
     419             :     {
     420       14292 :         if (xf <= zf)
     421             :         {
     422             :             // Upper-left triangle (don't use h10)
     423        7944 :             return HEIGHT_SCALE * (h00 + (h11-h01)*xf + (h01-h00)*zf);
     424             :         }
     425             :         else
     426             :         {
     427             :             // Lower-right triangle (don't use h01)
     428        6348 :             return HEIGHT_SCALE * (h00 + (h10-h00)*xf + (h11-h10)*zf);
     429             :         }
     430             :     }
     431             : }
     432             : 
     433     5709201 : fixed CTerrain::GetExactGroundLevelFixed(fixed x, fixed z) const
     434             : {
     435             :     // Clamp to size-2 so we can use the tiles (xi,zi)-(xi+1,zi+1)
     436    11418402 :     const ssize_t xi = Clamp<ssize_t>((x / static_cast<int>(TERRAIN_TILE_SIZE)).ToInt_RoundToZero(), 0, m_MapSize - 2);
     437    11418402 :     const ssize_t zi = Clamp<ssize_t>((z / static_cast<int>(TERRAIN_TILE_SIZE)).ToInt_RoundToZero(), 0, m_MapSize - 2);
     438             : 
     439     5709201 :     const fixed one = fixed::FromInt(1);
     440             : 
     441     5709201 :     const fixed xf = Clamp((x / static_cast<int>(TERRAIN_TILE_SIZE)) - fixed::FromInt(xi), fixed::Zero(), one);
     442     5709201 :     const fixed zf = Clamp((z / static_cast<int>(TERRAIN_TILE_SIZE)) - fixed::FromInt(zi), fixed::Zero(), one);
     443             : 
     444     5709201 :     std::uint16_t h00 = m_Heightmap[zi*m_MapSize + xi];
     445     5709201 :     std::uint16_t h01 = m_Heightmap[(zi+1)*m_MapSize + xi];
     446     5709201 :     std::uint16_t h10 = m_Heightmap[zi*m_MapSize + (xi+1)];
     447     5709201 :     std::uint16_t h11 = m_Heightmap[(zi+1)*m_MapSize + (xi+1)];
     448             : 
     449             :     // Intermediate scaling of xf, so we don't overflow in the multiplications below
     450             :     // (h00 <= 65535, xf <= 1, max fixed is < 32768; divide by 2 here so xf1*h00 <= 32767.5)
     451     5709201 :     const fixed xf0 = xf / 2;
     452     5709201 :     const fixed xf1 = (one - xf) / 2;
     453             : 
     454             :     // Linearly interpolate
     455     5709201 :     return ((one - zf).Multiply(xf1 * h00 + xf0 * h10)
     456     5709201 :                   + zf.Multiply(xf1 * h01 + xf0 * h11)) / (int)(HEIGHT_UNITS_PER_METRE / 2);
     457             : 
     458             :     // TODO: This should probably be more like GetExactGroundLevel()
     459             :     // in handling triangulation properly
     460             : }
     461             : 
     462       17493 : bool CTerrain::GetTriangulationDir(ssize_t i, ssize_t j) const
     463             : {
     464             :     // Clamp to size-2 so we can use the tiles (i,j)-(i+1,j+1)
     465       17493 :     i = Clamp<ssize_t>(i, 0, m_MapSize - 2);
     466       17493 :     j = Clamp<ssize_t>(j, 0, m_MapSize - 2);
     467             : 
     468       17493 :     int h00 = m_Heightmap[j*m_MapSize + i];
     469       17493 :     int h01 = m_Heightmap[(j+1)*m_MapSize + i];
     470       17493 :     int h10 = m_Heightmap[j*m_MapSize + (i+1)];
     471       17493 :     int h11 = m_Heightmap[(j+1)*m_MapSize + (i+1)];
     472             : 
     473             :     // Prefer triangulating in whichever direction means the midpoint of the diagonal
     474             :     // will be the highest. (In particular this means a diagonal edge will be straight
     475             :     // along the top, and jagged along the bottom, which makes sense for terrain.)
     476       17493 :     int mid1 = h00+h11;
     477       17493 :     int mid2 = h01+h10;
     478       17493 :     return (mid1 < mid2);
     479             : }
     480             : 
     481          13 : void CTerrain::ResizeAndOffset(ssize_t size, ssize_t horizontalOffset, ssize_t verticalOffset)
     482             : {
     483          13 :     if (size == m_MapSizePatches && horizontalOffset == 0 && verticalOffset == 0)
     484             :     {
     485             :         // Inexplicable request to resize terrain to the same size, ignore it.
     486             :         return;
     487             :     }
     488             : 
     489          22 :     if (!m_Heightmap ||
     490          11 :         std::abs(horizontalOffset) >= size / 2 + m_MapSizePatches / 2 ||
     491           7 :         std::abs(verticalOffset) >= size / 2 + m_MapSizePatches / 2)
     492             :     {
     493             :         // We have not yet created a terrain, or we are offsetting outside the current source.
     494             :         // Let's build a default terrain of the given size now.
     495           4 :         Initialize(size, 0);
     496           4 :         return;
     497             :     }
     498             : 
     499             :     // Allocate data for new terrain.
     500           7 :     const ssize_t newMapSize = size * PATCH_SIZE + 1;
     501           7 :     std::uint16_t* newHeightmap = new std::uint16_t[newMapSize * newMapSize];
     502           7 :     memset(newHeightmap, 0, newMapSize * newMapSize * sizeof(std::uint16_t));
     503          71 :     CPatch* newPatches = new CPatch[size * size];
     504             : 
     505             :     // O--------------------+
     506             :     // | Source             |
     507             :     // |                    |
     508             :     // | Source Center (SC) |
     509             :     // |          X         |
     510             :     // |             A------+----------------+
     511             :     // |             |      |    Destination |
     512             :     // |             |      |                |
     513             :     // +-------------+------B                |
     514             :     //               |    Dest. Center (DC)  |
     515             :     //               |           X           |
     516             :     //               |                       |
     517             :     //               |                       |
     518             :     //               |                       |
     519             :     //               |                       |
     520             :     //               +-----------------------+
     521             :     //
     522             :     // Calculations below should also account cases like:
     523             :     //
     524             :     // +----------+   +----------+     +----------+   +---+--+---+   +------+
     525             :     // |S         |   |D         |     |S         |   |S  |  |  D|   |D     |
     526             :     // |   +---+  |   |   +---+  |   +-+-+        |   |   |  |   |   |  +---+--+
     527             :     // |   | D |  |   |   | S |  |   |D| |        |   +---+--+---+   +--+---+  |
     528             :     // |   +---+  |   |   +---+  |   +-+-+        |                     |     S|
     529             :     // +----------+   +----------+     +----------+                     +------+
     530             :     //
     531             :     // O = (0, 0)
     532             :     // SC = (m_MapSizePatches / 2, m_MapSizePatches / 2)
     533             :     // DC - SC = (horizontalOffset, verticalOffset)
     534             :     //
     535             :     // Source upper left:
     536             :     // A = (max(0, (m_MapSizePatches - size) / 2 + horizontalOffset),
     537             :     //      max(0, (m_MapSizePatches - size) / 2 + verticalOffset))
     538             :     // Source bottom right:
     539             :     // B = (min(m_MapSizePatches, (m_MapSizePatches + size) / 2 + horizontalOffset),
     540             :     //      min(m_MapSizePatches, (m_MapSizePatches + size) / 2 + verticalOffset))
     541             :     //
     542             :     // A-B is the area that we have to copy from the source to the destination.
     543             : 
     544             :     // Restate center offset as a window over destination.
     545             :     // This has the effect of always considering the source to be the same size or smaller.
     546          14 :     const ssize_t sourceUpperLeftX = std::max(
     547           7 :         static_cast<ssize_t>(0), m_MapSizePatches / 2 - size / 2 + horizontalOffset);
     548          14 :     const ssize_t sourceUpperLeftZ = std::max(
     549           7 :         static_cast<ssize_t>(0), m_MapSizePatches / 2 - size / 2 + verticalOffset);
     550             : 
     551          14 :     const ssize_t destUpperLeftX = std::max(
     552           7 :         static_cast<ssize_t>(0), (size / 2 - m_MapSizePatches / 2 - horizontalOffset));
     553          14 :     const ssize_t destUpperLeftZ = std::max(
     554           7 :         static_cast<ssize_t>(0), (size / 2 - m_MapSizePatches / 2 - verticalOffset));
     555             : 
     556           7 :     const ssize_t width =
     557           7 :         std::min(m_MapSizePatches, m_MapSizePatches / 2 + horizontalOffset + size / 2) - sourceUpperLeftX;
     558           7 :     const ssize_t depth =
     559           7 :         std::min(m_MapSizePatches, m_MapSizePatches / 2 + verticalOffset + size / 2) - sourceUpperLeftZ;
     560             : 
     561         215 :     for (ssize_t j = 0; j < depth * PATCH_SIZE; ++j)
     562             :     {
     563             :         // Copy the main part from the source. Destination heightmap:
     564             :         // +----------+
     565             :         // |          |
     566             :         // |   1234   | < current j-th row for example.
     567             :         // |   5678   |
     568             :         // |          |
     569             :         // +----------+
     570         208 :         std::uint16_t* dst = newHeightmap + (j + destUpperLeftZ * PATCH_SIZE) * newMapSize + destUpperLeftX * PATCH_SIZE;
     571         208 :         std::uint16_t* src = m_Heightmap + (j + sourceUpperLeftZ * PATCH_SIZE) * m_MapSize + sourceUpperLeftX * PATCH_SIZE;
     572         208 :         std::copy_n(src, width * PATCH_SIZE, dst);
     573         208 :         if (destUpperLeftX > 0)
     574             :         {
     575             :             // Fill the preceding part by copying the first elements of the
     576             :             // main part. Destination heightmap:
     577             :             // +----------+
     578             :             // |          |
     579             :             // |1111234   |  < current j-th row for example.
     580             :             // |   5678   |
     581             :             // |          |
     582             :             // +----------+
     583          96 :             std::uint16_t* dst_prefix = newHeightmap + (j + destUpperLeftZ * PATCH_SIZE) * newMapSize;
     584          96 :             std::fill_n(dst_prefix, destUpperLeftX * PATCH_SIZE, dst[0]);
     585             :         }
     586         208 :         if ((destUpperLeftX + width) * PATCH_SIZE < newMapSize)
     587             :         {
     588             :             // Fill the succeeding part by copying the last elements of the
     589             :             // main part. Destination heightmap:
     590             :             // +----------+
     591             :             // |          |
     592             :             // |1111234444|  < current j-th row for example.
     593             :             // |   5678   |
     594             :             // |          |
     595             :             // +----------+
     596         208 :             std::uint16_t* dst_suffix = dst + width * PATCH_SIZE;
     597         208 :             std::fill_n(
     598             :                 dst_suffix,
     599             :                 newMapSize - (width + destUpperLeftX) * PATCH_SIZE,
     600         208 :                 dst[width * PATCH_SIZE - 1]);
     601             :         }
     602             :     }
     603             :     // Copy over heights from the preceding row. Destination heightmap:
     604             :     // +----------+
     605             :     // |1111234444| < copied from the row below
     606             :     // |1111234444|
     607             :     // |5555678888|
     608             :     // |          |
     609             :     // +----------+
     610          71 :     for (ssize_t j = 0; j < destUpperLeftZ * PATCH_SIZE; ++j)
     611             :     {
     612             : 
     613          64 :         std::uint16_t* dst = newHeightmap + j * newMapSize;
     614          64 :         std::uint16_t* src = newHeightmap + destUpperLeftZ * PATCH_SIZE * newMapSize;
     615         128 :         std::copy_n(src, newMapSize, dst);
     616             :     }
     617             :     // Copy over heights from the succeeding row. Destination heightmap:
     618             :     // +----------+
     619             :     // |1111234444|
     620             :     // |1111234444|
     621             :     // |5555678888|
     622             :     // |5555678888| < copied from the row above
     623             :     // +----------+
     624          62 :     for (ssize_t j = (destUpperLeftZ + depth) * PATCH_SIZE; j < newMapSize; ++j)
     625             :     {
     626          55 :         std::uint16_t* dst = newHeightmap + j * newMapSize;
     627          55 :         std::uint16_t* src = newHeightmap + ((destUpperLeftZ + depth) * PATCH_SIZE - 1) * newMapSize;
     628         110 :         std::copy_n(src, newMapSize, dst);
     629             :     }
     630             : 
     631             :     // Now build new patches. The same process as for the heightmap.
     632          20 :     for (ssize_t j = 0; j < depth; ++j)
     633             :     {
     634          36 :         for (ssize_t i = 0; i < width; ++i)
     635             :         {
     636          23 :             const CPatch& src =
     637          23 :                 m_Patches[(sourceUpperLeftZ + j) * m_MapSizePatches + sourceUpperLeftX + i];
     638          23 :             CPatch& dst =
     639          23 :                 newPatches[(destUpperLeftZ + j) * size + destUpperLeftX + i];
     640          23 :             std::copy_n(&src.m_MiniPatches[0][0], PATCH_SIZE * PATCH_SIZE, &dst.m_MiniPatches[0][0]);
     641             :         }
     642          23 :         for (ssize_t i = 0; i < destUpperLeftX; ++i)
     643         170 :             for (ssize_t jPatch = 0; jPatch < PATCH_SIZE; ++jPatch)
     644             :             {
     645         160 :                 const CMiniPatch& src =
     646         160 :                     newPatches[(destUpperLeftZ + j) * size + destUpperLeftX]
     647             :                         .m_MiniPatches[jPatch][0];
     648        2720 :                 for (ssize_t iPatch = 0; iPatch < PATCH_SIZE; ++iPatch)
     649             :                 {
     650        2560 :                     CMiniPatch& dst =
     651        2560 :                         newPatches[(destUpperLeftZ + j) * size + i]
     652             :                             .m_MiniPatches[jPatch][iPatch];
     653        2560 :                     dst = src;
     654             :                 }
     655             :             }
     656          20 :         for (ssize_t i = destUpperLeftX + width; i < size; ++i)
     657             :         {
     658         119 :             for (ssize_t jPatch = 0; jPatch < PATCH_SIZE; ++jPatch)
     659             :             {
     660         112 :                 const CMiniPatch& src =
     661         112 :                     newPatches[(destUpperLeftZ + j) * size + destUpperLeftX + width - 1]
     662             :                         .m_MiniPatches[jPatch][PATCH_SIZE - 1];
     663        1904 :                 for (ssize_t iPatch = 0; iPatch < PATCH_SIZE; ++iPatch)
     664             :                 {
     665        1792 :                     CMiniPatch& dst =
     666        1792 :                         newPatches[(destUpperLeftZ + j) * size + i].m_MiniPatches[jPatch][iPatch];
     667        1792 :                     dst = src;
     668             :                 }
     669             :             }
     670             :         }
     671             :     }
     672             : 
     673          11 :     for (ssize_t j = 0; j < destUpperLeftZ; ++j)
     674          18 :         for (ssize_t i = 0; i < size; ++i)
     675         238 :             for (ssize_t iPatch = 0; iPatch < PATCH_SIZE; ++iPatch)
     676             :             {
     677         224 :                 const CMiniPatch& src =
     678         224 :                     newPatches[destUpperLeftZ * size + i].m_MiniPatches[0][iPatch];
     679        3808 :                 for (ssize_t jPatch = 0; jPatch < PATCH_SIZE; ++jPatch)
     680             :                 {
     681        3584 :                     CMiniPatch& dst =
     682        3584 :                         newPatches[j * size + i].m_MiniPatches[jPatch][iPatch];
     683        3584 :                     dst = src;
     684             :                 }
     685             :             }
     686          10 :     for (ssize_t j = destUpperLeftZ + depth; j < size; ++j)
     687          13 :         for (ssize_t i = 0; i < size; ++i)
     688         170 :             for (ssize_t iPatch = 0; iPatch < PATCH_SIZE; ++iPatch)
     689             :             {
     690         160 :                 const CMiniPatch& src =
     691         160 :                     newPatches[(destUpperLeftZ + depth - 1) * size + i].m_MiniPatches[0][iPatch];
     692        2720 :                 for (ssize_t jPatch = 0; jPatch < PATCH_SIZE; ++jPatch)
     693             :                 {
     694        2560 :                     CMiniPatch& dst =
     695        2560 :                         newPatches[j * size + i].m_MiniPatches[jPatch][iPatch];
     696        2560 :                     dst = src;
     697             :                 }
     698             :             }
     699             : 
     700             :     // Release all the original data.
     701           7 :     ReleaseData();
     702             : 
     703             :     // Store new data.
     704           7 :     m_Heightmap = newHeightmap;
     705           7 :     m_Patches = newPatches;
     706           7 :     m_MapSize = newMapSize;
     707           7 :     m_MapSizePatches = size;
     708             : 
     709             :     // Initialise all the new patches.
     710           7 :     InitialisePatches();
     711             : 
     712             :     // Initialise mipmap.
     713           7 :     m_HeightMipmap.Initialize(m_MapSize, m_Heightmap);
     714             : }
     715             : 
     716             : ///////////////////////////////////////////////////////////////////////////////
     717             : // InitialisePatches: initialise patch data
     718          33 : void CTerrain::InitialisePatches()
     719             : {
     720         156 :     for (ssize_t j = 0; j < m_MapSizePatches; j++)
     721             :     {
     722         840 :         for (ssize_t i = 0; i < m_MapSizePatches; i++)
     723             :         {
     724         717 :             CPatch* patch = GetPatch(i, j); // can't fail
     725         717 :             patch->Initialize(this, i, j);
     726             :         }
     727             :     }
     728          33 : }
     729             : 
     730             : ///////////////////////////////////////////////////////////////////////////////
     731             : // SetHeightMap: set up a new heightmap from 16-bit source data;
     732             : // assumes heightmap matches current terrain size
     733           0 : void CTerrain::SetHeightMap(std::uint16_t* heightmap)
     734             : {
     735             :     // keep a copy of the given heightmap
     736           0 :     memcpy(m_Heightmap, heightmap, m_MapSize * m_MapSize * sizeof(std::uint16_t));
     737             : 
     738             :     // recalculate patch bounds, invalidate vertices
     739           0 :     for (ssize_t j = 0; j < m_MapSizePatches; j++)
     740             :     {
     741           0 :         for (ssize_t i = 0; i < m_MapSizePatches; i++)
     742             :         {
     743           0 :             CPatch* patch = GetPatch(i, j); // can't fail
     744           0 :             patch->InvalidateBounds();
     745           0 :             patch->SetDirty(RENDERDATA_UPDATE_VERTICES);
     746             :         }
     747             :     }
     748             : 
     749             :     // update mipmap
     750           0 :     m_HeightMipmap.Update(m_Heightmap);
     751           0 : }
     752             : 
     753             : 
     754             : ///////////////////////////////////////////////////////////////////////////////
     755             : 
     756           0 : void CTerrain::MakeDirty(ssize_t i0, ssize_t j0, ssize_t i1, ssize_t j1, int dirtyFlags)
     757             : {
     758             :     // Finds the inclusive limits of the patches that include the specified range of tiles
     759           0 :     ssize_t pi0 = Clamp<ssize_t>( i0   /PATCH_SIZE, 0, m_MapSizePatches-1);
     760           0 :     ssize_t pi1 = Clamp<ssize_t>((i1-1)/PATCH_SIZE, 0, m_MapSizePatches-1);
     761           0 :     ssize_t pj0 = Clamp<ssize_t>( j0   /PATCH_SIZE, 0, m_MapSizePatches-1);
     762           0 :     ssize_t pj1 = Clamp<ssize_t>((j1-1)/PATCH_SIZE, 0, m_MapSizePatches-1);
     763             : 
     764           0 :     for (ssize_t j = pj0; j <= pj1; j++)
     765             :     {
     766           0 :         for (ssize_t i = pi0; i <= pi1; i++)
     767             :         {
     768           0 :             CPatch* patch = GetPatch(i, j); // can't fail (i,j were clamped)
     769           0 :             if (dirtyFlags & RENDERDATA_UPDATE_VERTICES)
     770           0 :                 patch->CalcBounds();
     771           0 :             patch->SetDirty(dirtyFlags);
     772             :         }
     773             :     }
     774             : 
     775           0 :     if (m_Heightmap)
     776             :     {
     777           0 :         m_HeightMipmap.Update(m_Heightmap,
     778           0 :             Clamp<ssize_t>(i0, 0, m_MapSize - 1),
     779           0 :             Clamp<ssize_t>(j0, 0, m_MapSize - 1),
     780           0 :             Clamp<ssize_t>(i1, 1, m_MapSize),
     781           0 :             Clamp<ssize_t>(j1, 1, m_MapSize)
     782             :         );
     783             :     }
     784           0 : }
     785             : 
     786          67 : void CTerrain::MakeDirty(int dirtyFlags)
     787             : {
     788         359 :     for (ssize_t j = 0; j < m_MapSizePatches; j++)
     789             :     {
     790        1748 :         for (ssize_t i = 0; i < m_MapSizePatches; i++)
     791             :         {
     792        1456 :             CPatch* patch = GetPatch(i, j); // can't fail
     793        1456 :             if (dirtyFlags & RENDERDATA_UPDATE_VERTICES)
     794        1456 :                 patch->CalcBounds();
     795        1456 :             patch->SetDirty(dirtyFlags);
     796             :         }
     797             :     }
     798             : 
     799          67 :     if (m_Heightmap)
     800          67 :         m_HeightMipmap.Update(m_Heightmap);
     801          67 : }
     802             : 
     803           0 : CBoundingBoxAligned CTerrain::GetVertexesBound(ssize_t i0, ssize_t j0, ssize_t i1, ssize_t j1)
     804             : {
     805           0 :     i0 = Clamp<ssize_t>(i0, 0, m_MapSize - 1);
     806           0 :     j0 = Clamp<ssize_t>(j0, 0, m_MapSize - 1);
     807           0 :     i1 = Clamp<ssize_t>(i1, 0, m_MapSize - 1);
     808           0 :     j1 = Clamp<ssize_t>(j1, 0, m_MapSize - 1);
     809             : 
     810           0 :     std::uint16_t minH = 65535;
     811           0 :     std::uint16_t maxH = 0;
     812             : 
     813           0 :     for (ssize_t j = j0; j <= j1; ++j)
     814             :     {
     815           0 :         for (ssize_t i = i0; i <= i1; ++i)
     816             :         {
     817           0 :             minH = std::min(minH, m_Heightmap[j*m_MapSize + i]);
     818           0 :             maxH = std::max(maxH, m_Heightmap[j*m_MapSize + i]);
     819             :         }
     820             :     }
     821             : 
     822           0 :     CBoundingBoxAligned bound;
     823           0 :     bound[0].X = (float)(i0*TERRAIN_TILE_SIZE);
     824           0 :     bound[0].Y = (float)(minH*HEIGHT_SCALE);
     825           0 :     bound[0].Z = (float)(j0*TERRAIN_TILE_SIZE);
     826           0 :     bound[1].X = (float)(i1*TERRAIN_TILE_SIZE);
     827           0 :     bound[1].Y = (float)(maxH*HEIGHT_SCALE);
     828           0 :     bound[1].Z = (float)(j1*TERRAIN_TILE_SIZE);
     829           0 :     return bound;
     830             : }

Generated by: LCOV version 1.16