Rise
The Vieneo Province
Loading...
Searching...
No Matches
GeometryBounds.h
Go to the documentation of this file.
1#pragma once
2
3#include <algorithm>
4#include <cmath>
5#include <limits>
6
7// Bounds in the same local coordinates as the uploaded vertex buffer. Unknown
8// bounds fail open. Build from every emitted vertex, including terrain's curved
9// midpoints and the full height/overhang of structures.
11{
12 float low[3] = {}, high[3] = {};
13 bool valid = false;
14
15 template<class Vector> void Include(const Vector& p)
16 {
17 const float values[] = { p.x, p.y, p.z };
18 for (int i = 0; i < 3; ++i)
19 {
20 low[i] = valid ? (std::min)(low[i], values[i]) : values[i];
21 high[i] = valid ? (std::max)(high[i], values[i]) : values[i];
22 }
23 valid = true;
24 }
25
26 template<class Vector> bool IsWithinDistance(const Vector& point, float distance) const
27 {
28 if (!valid)
29 return true;
30 // Measure to the nearest point on the bounds, so a nearby edge keeps
31 // local lighting even when the plot's origin or center is farther away.
32 const float values[] = { point.x, point.y, point.z };
33 float distanceSquared = 0.0f;
34 for (int i = 0; i < 3; ++i)
35 {
36 const float delta = (std::max)(low[i] - values[i],
37 (std::max)(values[i] - high[i], 0.0f));
38 distanceSquared += delta * delta;
39 }
40 return distanceSquared <= distance * distance;
41 }
42
43 template<class Matrix> bool IntersectsFrustum(const Matrix& m, float guardX = 0, float guardY = 0) const
44 {
45 if (!valid)
46 return true;
47 // Row-vector D3D clip volume: -w <= x,y <= w and 0 <= z <= w.
48 // Testing a support point against each plane is conservative even when
49 // all box corners lie outside, or the box crosses the eye/near plane.
50 for (int plane = 0; plane < 6; ++plane)
51 {
52 const int axis = plane / 2;
53 const float sign = plane % 2 ? -1.0f : 1.0f;
54 // Expand the side planes for the shader's pixel-center correction
55 // and rasterizer edge precision. Guards are in normalized clip XY.
56 const float w = plane == 4 ? 0.0f : 1.0f + (axis == 0 ? guardX : axis == 1 ? guardY : 0.0f);
57 float d = w * m.m[3][3] + sign * m.m[3][axis];
58 float magnitude = std::fabs(w * m.m[3][3]) + std::fabs(m.m[3][axis]);
59 for (int i = 0; i < 3; ++i)
60 {
61 const float n = w * m.m[i][3] + sign * m.m[i][axis];
62 d += n * (n >= 0 ? high[i] : low[i]);
63 magnitude += (std::fabs(w * m.m[i][3]) + std::fabs(m.m[i][axis])) *
64 (std::max)(std::fabs(low[i]), std::fabs(high[i]));
65 }
66 // Fail open around cancellation in large translated coordinates.
67 if (d < -0.001f - 16 * std::numeric_limits<float>::epsilon() * magnitude)
68 return false;
69 }
70 return true;
71 }
72};
bool IsWithinDistance(const Vector &point, float distance) const
void Include(const Vector &p)
bool IntersectsFrustum(const Matrix &m, float guardX=0, float guardY=0) const