Please refer to 3D Math Primer for Graphics and Game Development
| 1735 | |
| 1736 | // Please refer to 3D Math Primer for Graphics and Game Development |
| 1737 | bool Terrain::Triangle::getIntersectPoint(const Ray& ray, Vec3& intersectPoint) const |
| 1738 | { |
| 1739 | // E1 |
| 1740 | Vec3 E1 = _p2 - _p1; |
| 1741 | |
| 1742 | // E2 |
| 1743 | Vec3 E2 = _p3 - _p1; |
| 1744 | |
| 1745 | // P |
| 1746 | Vec3 P; |
| 1747 | Vec3::cross(ray._direction, E2, &P); |
| 1748 | |
| 1749 | // determinant |
| 1750 | float det = E1.dot(P); |
| 1751 | |
| 1752 | // keep det > 0, modify T accordingly |
| 1753 | Vec3 T; |
| 1754 | if (det > 0) |
| 1755 | { |
| 1756 | T = ray._origin - _p1; |
| 1757 | } |
| 1758 | else |
| 1759 | { |
| 1760 | T = _p1 - ray._origin; |
| 1761 | det = -det; |
| 1762 | } |
| 1763 | |
| 1764 | // If determinant is near zero, ray lies in plane of triangle |
| 1765 | if (det < 0.0001f) |
| 1766 | return false; |
| 1767 | |
| 1768 | float t; // ray dist |
| 1769 | float u, v; // barycentric coordinate |
| 1770 | // Calculate u and make sure u <= 1 |
| 1771 | u = T.dot(P); |
| 1772 | if (u < 0.0f || u > det) |
| 1773 | return false; |
| 1774 | |
| 1775 | // Q |
| 1776 | Vec3 Q; |
| 1777 | Vec3::cross(T, E1, &Q); |
| 1778 | |
| 1779 | // Calculate v and make sure u + v <= 1 |
| 1780 | v = ray._direction.dot(Q); |
| 1781 | if (v < 0.0f || u + v > det) |
| 1782 | return false; |
| 1783 | |
| 1784 | // Calculate t, scale parameters, ray intersects triangle |
| 1785 | t = E2.dot(Q); |
| 1786 | |
| 1787 | float fInvDet = 1.0f / det; |
| 1788 | t *= fInvDet; |
| 1789 | |
| 1790 | intersectPoint = ray._origin + ray._direction * t; |
| 1791 | return true; |
| 1792 | } |
| 1793 | |
| 1794 | void Terrain::onBeforeDraw() |
no test coverage detected