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 : /*
19 : * Determine intersection of rays with a heightfield.
20 : */
21 :
22 : #include "precompiled.h"
23 :
24 : #include "HFTracer.h"
25 :
26 : #include "graphics/Patch.h"
27 : #include "graphics/Terrain.h"
28 : #include "lib/debug.h"
29 : #include "maths/BoundingBoxAligned.h"
30 : #include "maths/MathUtil.h"
31 : #include "maths/Vector3D.h"
32 :
33 : #include <cfloat>
34 : #include <cmath>
35 :
36 : // To cope well with points that are slightly off the edge of the map,
37 : // we act as if there's an N-tile margin around the edges of the heightfield.
38 : // (N shouldn't be too huge else it'll hurt performance a little when
39 : // RayIntersect loops through it all.)
40 : // CTerrain::CalcPosition implements clamp-to-edge behaviour so the tracer
41 : // will have that behaviour.
42 : static const int MARGIN_SIZE = 64;
43 :
44 : ///////////////////////////////////////////////////////////////////////////////
45 : // CHFTracer constructor
46 0 : CHFTracer::CHFTracer(CTerrain& terrain):
47 0 : m_Terrain(terrain),
48 0 : m_Heightfield(m_Terrain.GetHeightMap()),
49 0 : m_MapSize(m_Terrain.GetVerticesPerSide()),
50 0 : m_CellSize((float)TERRAIN_TILE_SIZE),
51 0 : m_HeightScale(HEIGHT_SCALE)
52 : {
53 0 : }
54 :
55 :
56 : ///////////////////////////////////////////////////////////////////////////////
57 : // RayTriIntersect: intersect a ray with triangle defined by vertices
58 : // v0,v1,v2; return true if ray hits triangle at distance less than dist,
59 : // or false otherwise
60 0 : static bool RayTriIntersect(const CVector3D& v0, const CVector3D& v1, const CVector3D& v2,
61 : const CVector3D& origin, const CVector3D& dir, float& dist)
62 : {
63 0 : const float EPSILON=0.00001f;
64 :
65 : // calculate edge vectors
66 0 : CVector3D edge0=v1-v0;
67 0 : CVector3D edge1=v2-v0;
68 :
69 : // begin calculating determinant - also used to calculate U parameter
70 0 : CVector3D pvec=dir.Cross(edge1);
71 :
72 : // if determinant is near zero, ray lies in plane of triangle
73 0 : float det = edge0.Dot(pvec);
74 0 : if (fabs(det)<EPSILON)
75 : return false;
76 :
77 0 : float inv_det = 1.0f/det;
78 :
79 : // calculate vector from vert0 to ray origin
80 0 : CVector3D tvec=origin-v0;
81 :
82 : // calculate U parameter, test bounds
83 0 : float u=tvec.Dot(pvec)*inv_det;
84 0 : if (u<-0.01f || u>1.01f)
85 : return false;
86 :
87 : // prepare to test V parameter
88 0 : CVector3D qvec=tvec.Cross(edge0);
89 :
90 : // calculate V parameter and test bounds
91 0 : float v=dir.Dot(qvec)*inv_det;
92 0 : if (v<0.0f || u+v>1.0f)
93 : return false;
94 :
95 : // calculate distance to intersection point from ray origin
96 0 : float d=edge1.Dot(qvec)*inv_det;
97 0 : if (d>=0 && d<dist) {
98 0 : dist=d;
99 0 : return true;
100 : }
101 :
102 : return false;
103 : }
104 :
105 : ///////////////////////////////////////////////////////////////////////////////
106 : // CellIntersect: test if ray intersects either of the triangles in the given
107 : // cell - return hit result, and distance to hit, if hit occurred
108 0 : bool CHFTracer::CellIntersect(int cx, int cz, const CVector3D& origin, const CVector3D& dir, float& dist) const
109 : {
110 0 : bool res=false;
111 :
112 : // get vertices for this cell
113 0 : CVector3D vpos[4];
114 0 : m_Terrain.CalcPosition(cx,cz,vpos[0]);
115 0 : m_Terrain.CalcPosition(cx+1,cz,vpos[1]);
116 0 : m_Terrain.CalcPosition(cx+1,cz+1,vpos[2]);
117 0 : m_Terrain.CalcPosition(cx,cz+1,vpos[3]);
118 :
119 0 : dist=1.0e30f;
120 0 : if (RayTriIntersect(vpos[0],vpos[1],vpos[2],origin,dir,dist)) {
121 : res=true;
122 : }
123 :
124 0 : if (RayTriIntersect(vpos[0],vpos[2],vpos[3],origin,dir,dist)) {
125 0 : res=true;
126 : }
127 :
128 0 : return res;
129 : }
130 :
131 : ///////////////////////////////////////////////////////////////////////////////
132 : // RayIntersect: intersect ray with this heightfield; return true if
133 : // intersection occurs (and fill in grid coordinates of intersection), or false
134 : // otherwise
135 0 : bool CHFTracer::RayIntersect(const CVector3D& origin, const CVector3D& dir, int& x, int& z, CVector3D& ipt) const
136 : {
137 : // If the map is empty (which should never happen),
138 : // return early before we crash when reading zero-sized heightmaps
139 0 : if (!m_MapSize)
140 : {
141 0 : debug_warn(L"CHFTracer::RayIntersect called with zero-size map");
142 0 : return false;
143 : }
144 :
145 : // intersect first against bounding box
146 0 : CBoundingBoxAligned bound;
147 0 : bound[0] = CVector3D(-MARGIN_SIZE * m_CellSize, 0, -MARGIN_SIZE * m_CellSize);
148 0 : bound[1] = CVector3D((m_MapSize + MARGIN_SIZE) * m_CellSize, 65535 * m_HeightScale, (m_MapSize + MARGIN_SIZE) * m_CellSize);
149 :
150 0 : float tmin,tmax;
151 0 : if (!bound.RayIntersect(origin,dir,tmin,tmax)) {
152 : // ray missed world bounds; no intersection
153 : return false;
154 : }
155 :
156 : // project origin onto grid, if necessary, to get starting point for traversal
157 0 : CVector3D traversalPt;
158 0 : if (tmin>0) {
159 0 : traversalPt=origin+dir*tmin;
160 : } else {
161 0 : traversalPt=origin;
162 : }
163 :
164 : // setup traversal variables
165 0 : int sx=dir.X<0 ? -1 : 1;
166 0 : int sz=dir.Z<0 ? -1 : 1;
167 :
168 0 : float invCellSize=1.0f/float(m_CellSize);
169 :
170 0 : float fcx=traversalPt.X*invCellSize;
171 0 : int cx=(int)floor(fcx);
172 :
173 0 : float fcz=traversalPt.Z*invCellSize;
174 0 : int cz=(int)floor(fcz);
175 :
176 0 : float invdx = 1.0e20f;
177 0 : float invdz = 1.0e20f;
178 :
179 0 : if (fabs(dir.X) > 1.0e-20)
180 0 : invdx = float(1.0/fabs(dir.X));
181 0 : if (fabs(dir.Z) > 1.0e-20)
182 0 : invdz = float(1.0/fabs(dir.Z));
183 :
184 0 : do {
185 : // test current cell
186 0 : if (cx >= -MARGIN_SIZE && cx < int(m_MapSize + MARGIN_SIZE - 1) && cz >= -MARGIN_SIZE && cz < int(m_MapSize + MARGIN_SIZE - 1))
187 : {
188 0 : float dist;
189 :
190 0 : if (CellIntersect(cx,cz,origin,dir,dist)) {
191 0 : x=cx;
192 0 : z=cz;
193 0 : ipt=origin+dir*dist;
194 0 : return true;
195 : }
196 0 : }
197 : else
198 : {
199 : // Degenerate case: y close to zero
200 : // catch travelling off the map
201 0 : if ((cx < -MARGIN_SIZE) && (sx < 0))
202 : return false;
203 0 : if ((cx >= (int)(m_MapSize + MARGIN_SIZE - 1)) && (sx > 0))
204 : return false;
205 0 : if ((cz < -MARGIN_SIZE) && (sz < 0))
206 : return false;
207 0 : if ((cz >= (int)(m_MapSize + MARGIN_SIZE - 1)) && (sz > 0))
208 : return false;
209 : }
210 :
211 : // get coords of current cell
212 0 : fcx=traversalPt.X*invCellSize;
213 0 : fcz=traversalPt.Z*invCellSize;
214 :
215 : // get distance to next cell in x,z
216 0 : float dx=(sx==-1) ? fcx-float(cx) : 1-(fcx-float(cx));
217 0 : dx*=invdx;
218 0 : float dz=(sz==-1) ? fcz-float(cz) : 1-(fcz-float(cz));
219 0 : dz*=invdz;
220 :
221 : // advance ..
222 0 : float dist;
223 0 : if (dx<dz) {
224 0 : cx+=sx;
225 0 : dist=dx;
226 : } else {
227 0 : cz+=sz;
228 0 : dist=dz;
229 : }
230 :
231 0 : traversalPt+=dir*dist;
232 0 : } while (traversalPt.Y>=0);
233 :
234 : // fell off end of heightmap with no intersection; return a miss
235 : return false;
236 : }
237 :
238 0 : static bool TestTile(std::uint16_t* heightmap, int stride, int i, int j, const CVector3D& pos, const CVector3D& dir, CVector3D& isct)
239 : {
240 0 : std::uint16_t y00 = heightmap[i + j*stride];
241 0 : std::uint16_t y10 = heightmap[i+1 + j*stride];
242 0 : std::uint16_t y01 = heightmap[i + (j+1)*stride];
243 0 : std::uint16_t y11 = heightmap[i+1 + (j+1)*stride];
244 :
245 0 : CVector3D p00( i * TERRAIN_TILE_SIZE, y00 * HEIGHT_SCALE, j * TERRAIN_TILE_SIZE);
246 0 : CVector3D p10((i+1) * TERRAIN_TILE_SIZE, y10 * HEIGHT_SCALE, j * TERRAIN_TILE_SIZE);
247 0 : CVector3D p01( i * TERRAIN_TILE_SIZE, y01 * HEIGHT_SCALE, (j+1) * TERRAIN_TILE_SIZE);
248 0 : CVector3D p11((i+1) * TERRAIN_TILE_SIZE, y11 * HEIGHT_SCALE, (j+1) * TERRAIN_TILE_SIZE);
249 :
250 0 : int mid1 = y00+y11;
251 0 : int mid2 = y01+y10;
252 0 : int triDir = (mid1 < mid2);
253 :
254 0 : float dist = FLT_MAX;
255 :
256 0 : if (triDir)
257 : {
258 0 : if (RayTriIntersect(p00, p10, p01, pos, dir, dist) || // lower-left triangle
259 0 : RayTriIntersect(p11, p01, p10, pos, dir, dist)) // upper-right triangle
260 : {
261 0 : isct = pos + dir * dist;
262 0 : return true;
263 : }
264 : }
265 : else
266 : {
267 0 : if (RayTriIntersect(p00, p11, p01, pos, dir, dist) || // upper-left triangle
268 0 : RayTriIntersect(p00, p10, p11, pos, dir, dist)) // lower-right triangle
269 : {
270 0 : isct = pos + dir * dist;
271 0 : return true;
272 : }
273 : }
274 : return false;
275 : }
276 :
277 0 : bool CHFTracer::PatchRayIntersect(CPatch* patch, const CVector3D& origin, const CVector3D& dir, CVector3D* out)
278 : {
279 : // (TODO: This largely duplicates RayIntersect - some refactoring might be
280 : // nice in the future.)
281 :
282 : // General approach:
283 : // Given the ray defined by origin + dir * t, we increase t until it
284 : // enters the patch's bounding box. The x,z coordinates identify which
285 : // tile it is currently above/below. Do an intersection test vs the tile's
286 : // two triangles. If it doesn't hit, do a 2D line rasterisation to find
287 : // the next tiles the ray will pass through, and test each of them.
288 :
289 : // Start by jumping to the point where the ray enters the bounding box
290 0 : CBoundingBoxAligned bound = patch->GetWorldBounds();
291 0 : float tmin, tmax;
292 0 : if (!bound.RayIntersect(origin, dir, tmin, tmax))
293 : {
294 : // Ray missed patch; no intersection
295 : return false;
296 : }
297 :
298 0 : int heightmapStride = patch->m_Parent->GetVerticesPerSide();
299 :
300 : // Get heightmap, offset to start at this patch
301 0 : std::uint16_t* heightmap = patch->m_Parent->GetHeightMap() +
302 0 : patch->m_X * PATCH_SIZE +
303 0 : patch->m_Z * PATCH_SIZE * heightmapStride;
304 :
305 : // Get patch-space position of ray origin and bbox entry point
306 0 : CVector3D patchPos(
307 0 : patch->m_X * PATCH_SIZE * TERRAIN_TILE_SIZE,
308 : 0.0f,
309 0 : patch->m_Z * PATCH_SIZE * TERRAIN_TILE_SIZE);
310 0 : CVector3D originPatch = origin - patchPos;
311 0 : CVector3D entryPatch = originPatch + dir * tmin;
312 :
313 : // We want to do a simple 2D line rasterisation (with the 3D ray projected
314 : // down onto the Y plane). That will tell us which cells are intersected
315 : // in 2D dimensions, then we can do a more precise 3D intersection test.
316 : //
317 : // WLOG, assume the ray has direction dir.x > 0, dir.z > 0, and starts in
318 : // cell (i,j). The next cell intersecting the line must be either (i+1,j)
319 : // or (i,j+1). To tell which, just check whether the point (i+1,j+1) is
320 : // above or below the ray. Advance into that cell and repeat.
321 : //
322 : // (If the ray passes precisely through (i+1,j+1), we can pick either.
323 : // If the ray is parallel to Y, only the first cell matters, then we can
324 : // carry on rasterising in any direction (a bit of a waste of time but
325 : // should be extremely rare, and it's safe and simple).)
326 :
327 : // Work out which tile we're starting in
328 0 : int i = Clamp<int>(entryPatch.X / TERRAIN_TILE_SIZE, 0, PATCH_SIZE - 1);
329 0 : int j = Clamp<int>(entryPatch.Z / TERRAIN_TILE_SIZE, 0, PATCH_SIZE - 1);
330 :
331 : // Work out which direction the ray is going in
332 0 : int di = (dir.X >= 0 ? 1 : 0);
333 0 : int dj = (dir.Z >= 0 ? 1 : 0);
334 :
335 0 : do
336 : {
337 0 : CVector3D isct;
338 0 : if (TestTile(heightmap, heightmapStride, i, j, originPatch, dir, isct))
339 : {
340 0 : if (out)
341 0 : *out = isct + patchPos;
342 0 : return true;
343 : }
344 :
345 : // Get the vertex between the two possible next cells
346 0 : float nx = (i + di) * (int)TERRAIN_TILE_SIZE;
347 0 : float nz = (j + dj) * (int)TERRAIN_TILE_SIZE;
348 :
349 : // Test which side of the ray the vertex is on, and advance into the
350 : // appropriate cell, using a test that works for all 4 combinations
351 : // of di,dj
352 0 : float dot = dir.Z * (nx - originPatch.X) - dir.X * (nz - originPatch.Z);
353 0 : if ((di == dj) == (dot > 0.0f))
354 0 : j += dj*2-1;
355 : else
356 0 : i += di*2-1;
357 : }
358 0 : while (i >= 0 && j >= 0 && i < PATCH_SIZE && j < PATCH_SIZE);
359 :
360 : // Ran off the edge of the patch, so no intersection
361 : return false;
362 : }
|