# Geometry snippets

### Line equation from two points

To obtain a line equation of the form ${\displaystyle Ax+By+C=0}$ from two points ${\displaystyle a}$ and ${\displaystyle b}$, set:

{\displaystyle {\begin{aligned}A&=a_{y}-b_{y}\\B&=b_{x}-a_{x}\\C&=a_{x}\cdot b_{y}-b_{x}\cdot a_{y}\end{aligned}}}

### Shortest distance from point to line

Given a line ${\displaystyle Ax+By+C=0}$ and a point ${\displaystyle p}$, the shortest distance from the point to the line is given by:

${\displaystyle {\frac {\left|A\cdot p_{x}+B\cdot p_{y}+C\right|}{\sqrt {A^{2}+B^{2}}}}}$

### Shortest distance from point to line segment

// https://www.iquilezles.org/www/articles/distfunctions2d/distfunctions2d.htm
static float sdLineSegment(glm::vec2 p, glm::vec2 a, glm::vec2 b)
{
auto pa = p - a;
auto ba = b - a;
auto h = glm::clamp(glm::dot(pa, ba) / glm::dot(ba, ba), 0.f, 1.f);
return glm::length(pa - ba * h);
}