Just for an explanation about the formula from Sam Hocevar:
- If A,B are on the line, then the vector
$$\vec{u} = \vec{AB} / \left\|\vec{AB}\right\| $$
is the unit vector for this line (don't forget that \$\left\|\vec{AB}\right\| = \sqrt {\vec{AB} \cdot \vec{AB}} \$ or respectively \$\vec{AB} \cdot \vec{AB} = \left\|\vec{AB}\right\|^2\$).
The line equation follows:
$$k \cdot{\vec{u}} + A $$ for any \$k\$ scalar.
Then when projecting P on this line, the projected point \$I\$ is defined as perpendicular to the line's unit vector, that is:
$$ \vec{IP} \cdot \vec{u} = 0 $$
and
$$ I = \vec{u} \cdot \left\|\vec{AI}\right\| + A $$
Since projecting P on the line is the dot product of \$\vec{AP}\$ and \$\vec{AB}\$, we can compute:
$$ \left\|\vec{AI}\right\| = \vec{AP} \cdot \vec{AB} / \left\|\vec{AB}\right\| $$
since \$\vec{AP} = \vec{AI} + \vec{IP}\$ and \$\vec{IP} \cdot \vec{u} = \vec{IP} \cdot \vec{AB} = 0\$, then:
$$ \vec{AP} \cdot \vec{AB} = \vec{AI} \cdot \vec{AB}=\vec{AI}\cdot\vec{u} *\left\|\vec{AB}\right\| = \left\|\vec{AI}\right\| * \left\|\vec{AB}\right\|$$
That means that only the colinear component of \$\vec{AP}\$ to \$\vec{AB}\$ is participating to the scalar result
Which finally gives:
$$ \begin{matrix} I_{x} \\ I_{y} \\ I_{z} \end{matrix} = \begin{matrix} A_{x} \\ A_{y} \\ A_{z} \end{matrix} + \begin{pmatrix} P_{x} - A_{x} \\ P_{y} - A_{y} \\ P_{z} - A_{z} \end{pmatrix} \cdot \begin{pmatrix} B_{x} - A_{x} \\ B_{y} - A_{y} \\ B_{z} - A_{z} \end{pmatrix} \cdot \begin{pmatrix} u_{x} \\ u_{y} \\ u_{z} \end{pmatrix} / \left\|\vec{AB}\right\|$$
This is the formula from Sam above.