| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- //
- // shape.cpp
- // math
- //
- // Created by Sam Jaffe on 7/5/16.
- //
- #include "game/math/shape.hpp"
- #include <vector>
- #include "game/math/compare.hpp"
- namespace math { namespace dim2 {
- float line::length() const { return (second - first).magnitude(); }
- float line::slope() const {
- return safe_div(second[1] - first[1], second[0] - first[0]);
- }
- rectangle::operator quad() const {
- return {origin, origin + vec2{{size.x(), 0.0}}, origin + size,
- origin + vec2{{0.0, size.y()}}};
- }
- square::operator rectangle() const { return {origin, vec2{{size, size}}}; }
- square::operator quad() const {
- return {origin, origin + vec2{{size, 0.0}}, origin + vec2{{size, size}},
- origin + vec2{{0.0, size}}};
- }
- }}
- namespace math { namespace shapes {
- std::vector<dim2::line> segments(dim2::quad const & shape) {
- return {{shape.ll, shape.lr},
- {shape.lr, shape.ur},
- {shape.ur, shape.ul},
- {shape.ul, shape.ll}};
- }
- }}
- namespace math { namespace lines {
- bool parallel(dim2::line const & lhs, dim2::line const & rhs) {
- return lhs.slope() == rhs.slope();
- }
- inline dim2::point intersection(float b1, float s1, float b2, float s2) {
- float const x = safe_div(b1 - b2, s2 - s1);
- return {{x, b1 + x * s1}};
- }
- inline dim2::point intersection(dim2::point const & p1, float s1,
- dim2::point const & p2, float s2) {
- // Solve for Inf * NaN
- float y1 = p1[0] == 0 ? 0 : s1 * p1[0];
- float y2 = p2[0] == 0 ? 0 : s2 * p2[0];
- return intersection(p1[1] - y1, s1, p2[1] - y2, s2);
- }
- dim2::point intersection(dim2::line const & lhs, dim2::line const & rhs) {
- return intersection(lhs.first, lhs.slope(), rhs.first, rhs.slope());
- }
- dim2::line orthogonal(dim2::line const & from, dim2::point const & to) {
- float const slope = from.slope();
- if (slope == 0 || isinf(slope)) { return {to, {{to[0], from.first[1]}}}; }
- return {to, intersection(from.first, slope, to, -1 / slope)};
- }
- }}
|