45 lines
2.4 KiB
C++
45 lines
2.4 KiB
C++
#pragma once
|
|
#include <array>
|
|
#include <cmath>
|
|
namespace ava2 {
|
|
// Portions Copyright (C) John W. Ratcliff, 2001 (AVA2 SphereLib/frustum.cpp).
|
|
struct PerspectiveMetadata {float fovDegrees=0,aspect=0,nearPlane=0,farPlane=0;};
|
|
struct DepthState {bool enabled=true,write=true;};
|
|
struct ViewFrustum {
|
|
std::array<std::array<float,4>,6> planes{};
|
|
std::array<float,3> sphereCenter{};
|
|
float sphereRadius=-1;
|
|
ViewFrustum(const float* view,const float* projection,const std::array<float,3>& eye,const std::array<float,3>& forward,const PerspectiveMetadata* metadata=nullptr) {
|
|
float matrix[16]={};for(int r=0;r<4;++r)for(int c=0;c<4;++c)for(int k=0;k<4;++k)matrix[r*4+c]+=view[r*4+k]*projection[k*4+c];
|
|
for(int k=0;k<4;++k) {
|
|
planes[0][k]=matrix[k*4+2];planes[1][k]=matrix[k*4+3]-matrix[k*4+2];
|
|
planes[2][k]=matrix[k*4+3]+matrix[k*4];planes[3][k]=matrix[k*4+3]-matrix[k*4];
|
|
planes[4][k]=matrix[k*4+3]+matrix[k*4+1];planes[5][k]=matrix[k*4+3]-matrix[k*4+1];
|
|
}
|
|
for(auto& plane:planes) {
|
|
const float length=std::sqrt(plane[0]*plane[0]+plane[1]*plane[1]+plane[2]*plane[2]);
|
|
if(length>0 && std::isfinite(length))for(auto& value:plane)value/=length;
|
|
else plane={0,0,0,1}; // Invalid/degenerate plane cannot safely reject a segment.
|
|
}
|
|
// BuildViewFrustum2 uses saved perspective metadata even for ortho/off-axis matrices.
|
|
if(metadata) {
|
|
const float near=metadata->nearPlane,far=metadata->farPlane;
|
|
const float length=far-near,half=near+length*0.5f;
|
|
const float h=length*std::tan(metadata->fovDegrees*0.5f),w=h*metadata->aspect,z=half-length;
|
|
const float radius=std::sqrt(w*w+h*h+z*z);
|
|
if(std::isfinite(radius)) {
|
|
sphereRadius=radius;for(int k=0;k<3;++k)sphereCenter[k]=eye[k]+forward[k]*half;
|
|
}
|
|
}
|
|
}
|
|
bool Outside(const std::array<float,3>& center,float radius) const {
|
|
if(sphereRadius>=0) {
|
|
float distance=0;for(int k=0;k<3;++k){const float delta=center[k]-sphereCenter[k];distance+=delta*delta;}
|
|
if((radius+sphereRadius)*(radius+sphereRadius)<distance)return true;
|
|
}
|
|
for(const auto& plane:planes)if(plane[0]*center[0]+plane[1]*center[1]+plane[2]*center[2]+plane[3]<=-radius)return true;
|
|
return false;
|
|
}
|
|
};
|
|
} // namespace ava2
|