add world coordinate transformations to math library

This commit is contained in:
ohsqueezy 2023-07-05 20:08:11 -04:00
parent f7f6bee582
commit 6cb9688bec
1 changed files with 44 additions and 3 deletions

View File

@ -10,9 +10,8 @@
[math.hpp]
For math helper functions that require only GLM primitives, especially trigonometric functions.
Angle values are in radians. 0 is directly up on the screen in GL coordinates, and the angle increases
clockwise.
For math helper functions that require only GLM primitives, especially trigonometric functions. Angle values are in radians. 0 is
directly up on the screen in GL coordinates, and the angle increases clockwise.
This test of points on a square and one point below the square should print the output below.
@ -235,4 +234,46 @@ namespace sb
return segments;
}
/*!
* @param world world coordinates
* @param transformation transformation to apply to the given world coordinates, if any
*/
template<glm::length_t dimensions, typename Type, glm::qualifier qualifier>
glm::vec4 world_to_clip(const glm::vec<dimensions, Type, qualifier>& world, const glm::mat4& transformation = glm::mat4{1.0f})
{
/* Create a 4-D vertex with the w-coordinate normalized to 1.0f. */
glm::vec4 _world {world.x, world.y, 0.0f, 1.0f};
/* If a third dimension was passed, get it from the caller. */
if constexpr (dimensions > 2)
{
_world.z = world.z;
}
/* Apply projection and view transformations */
return transformation * _world;
}
/*!
* @param world world coordinates
* @param transformation transformation to apply to the given world coordinates, if any
*/
template<glm::length_t dimensions, typename Type, glm::qualifier qualifier>
glm::vec3 world_to_ndc(const glm::vec<dimensions, Type, qualifier>& world, const glm::mat4& transformation = glm::mat4{1.0f})
{
glm::vec4 clip = world_to_clip(world, transformation);
return glm::vec3{clip.x, clip.y, clip.z} / clip.w;
}
/*!
* @param world world coordinates
* @param transformation transformation to apply to the given world coordinates, if any
*/
template<glm::length_t dimensions, typename Type, glm::qualifier qualifier>
glm::vec2 world_to_viewport(const glm::vec<dimensions, Type, qualifier>& world, const glm::vec2& viewport, const glm::mat4& transformation = glm::mat4{1.0f})
{
glm::vec3 ndc = world_to_ndc(world, transformation);
return (glm::vec2{ndc.x, ndc.y} + 1.0f) / 2.0f * viewport;
}
}