src/geometry.cpp

Fri, 06 Mar 2020 16:08:53 +0200

author
Teemu Piippo <teemu@hecknology.net>
date
Fri, 06 Mar 2020 16:08:53 +0200
changeset 69
a36913fc552a
parent 64
f99d52b1646b
child 71
198d25fe4e21
permissions
-rw-r--r--

begin work on axes program

#include <glm/gtc/matrix_transform.hpp>
#include "geometry.h"

/**
 * @brief Computes a line from two points
 * @param point_1
 * @param point_2
 * @return line
 */
geom::Line geom::lineFromPoints(const glm::vec3& point_1, const glm::vec3 point_2)
{
	return {point_2 - point_1, point_1};
}

/**
 * @brief Computes line-plane intersection
 * @param line
 * @param plane
 * @return point of intersection. Does not return a value if the line is in parallel to the plane.
 */
std::optional<glm::vec3> geom::linePlaneIntersection(const geom::Line& line, const geom::Plane& plane, const float epsilon)
{
	const float denominator = glm::dot(line.direction, plane.normal);
	if (std::abs(denominator) < epsilon)
	{
		return {};
	}
	else
	{
		const float d = glm::dot(plane.anchor - line.anchor, plane.normal) / denominator;
		return line.anchor + d * line.direction;
	}
}

/**
 * @brief Computes the plane of a triangle
 * @param triangle
 * @return plane
 */
geom::Plane geom::planeFromTriangle(const geom::Triangle& triangle)
{
	return geom::Plane{normalVector(triangle), triangle.points[0]};
}

/**
 * @brief Computes the normal vector of a triangle
 * @param triangle
 * @return normal vector
 */
glm::vec3 geom::normalVector(const geom::Triangle& triangle)
{
	return glm::normalize(
		glm::cross(
			triangle.points[1] - triangle.points[0],
			triangle.points[2] - triangle.points[0]));
}

/**
 * @brief Extracts the scaling component of the specified matrix into a vector and returns both the scaling
 * components as well as the unscaled matrix.
 * @param matrix Matrix to compute
 * @return scaling vector and unscaled matrix
 */
geom::ScalingExtract geom::extractScaling(const glm::mat4& matrix)
{
	geom::ScalingExtract result;
	result.scaling = geom::scalingVector(matrix);
	result.unscaled = glm::scale(matrix, 1.0f / result.scaling);
	return result;
}

/**
 * @brief Computes the scaling vector, which contains the scaling of the specified matrix
 * @param matrix
 * @return scaling vector
 */
glm::vec3 geom::scalingVector(const glm::mat4 matrix)
{
	auto component = [](const glm::mat4& matrix, const int i) -> float
	{
		return std::hypot(std::hypot(matrix[i][0], matrix[i][1]), matrix[i][2]);
	};
	return glm::vec3{component(matrix, 0), component(matrix, 1), component(matrix, 2)};
}

mercurial