Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
PlanarReflectionCamera.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#pragma once
4#include "FrameConstants.hpp"
5#include <glm/gtc/matrix_access.hpp>
6#include <algorithm>
7#include <cmath>
8
9namespace esengine {
11 glm::mat4 projection{1.0f};
12 glm::mat4 samplingProjection{1.0f};
13};
14
19inline bool planarReflectionCamera(const glm::mat4& source, const glm::vec3& origin,
20 glm::vec3 normal, f32 offset, PlanarReflectionCamera& out) {
21 const f32 length = glm::length(normal);
22 if (!std::isfinite(length) || length < 1e-6f || !std::isfinite(offset)) return false;
23 normal /= length;
24 const glm::vec4 eye = cameraFromViewProjection(source);
25 const f32 side = eye.w > 0.5f ? glm::dot(glm::vec3(eye) - origin, normal)
26 : glm::dot(glm::vec3(eye), normal);
27 if (!std::isfinite(side) || std::abs(side) < 1e-5f) return false;
28 if (side < 0) normal = -normal;
29 const f32 d = -glm::dot(normal, origin);
30 glm::mat4 mirror(1.0f);
31 for (int c = 0; c < 3; ++c) {
32 for (int r = 0; r < 3; ++r) mirror[c][r] -= 2.0f * normal[c] * normal[r];
33 mirror[3][c] = -2.0f * d * normal[c];
34 }
35 glm::mat4 reflected = source * mirror;
36 // Reflection reverses handedness. Flip clip X as well so the existing
37 // front-face and two-sided normal rules stay valid; sampling uses this
38 // same projection, undoing the image flip on the receiving surface.
39 for (int c = 0; c < 4; ++c) reflected[c][0] = -reflected[c][0];
40 const f32 determinant = glm::determinant(reflected);
41 if (!std::isfinite(determinant) || std::abs(determinant) < 1e-12f) return false;
42 const glm::vec4 plane(normal, d - std::max(offset, 0.0f));
43 const glm::mat4 inverse = glm::inverse(reflected);
44 const glm::vec4 clipPlane = glm::transpose(inverse) * plane;
45 const glm::vec4 corner(clipPlane.x < 0 ? -1.0f : 1.0f,
46 clipPlane.y < 0 ? -1.0f : 1.0f, 1.0f, 1.0f);
47 const f32 denominator = glm::dot(plane, inverse * corner);
48 if (!std::isfinite(denominator) || denominator < 1e-6f) return false;
49 const glm::vec4 scaled = plane * (2.0f / denominator);
50 out.samplingProjection = reflected;
51 out.projection = reflected;
52 for (int c = 0; c < 4; ++c) out.projection[c][2] = scaled[c] - reflected[c][3];
53 return true;
54}
55} // namespace esengine
Per-frame shader constants shared via a single Uniform Buffer Object.
bool planarReflectionCamera(const glm::mat4 &source, const glm::vec3 &origin, glm::vec3 normal, f32 offset, PlanarReflectionCamera &out)
glm::vec4 cameraFromViewProjection(const glm::mat4 &viewProjection)
Where the frame is seen from, read out of the matrix that projects it.
float f32
32-bit floating point
Definition Types.hpp:59