| 1 | /* |
| 2 | * Copyright 2016-2017 Uber Technologies, Inc. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | /** @file vec2d.c |
| 17 | * @brief 2D floating point vector functions. |
| 18 | */ |
| 19 | |
| 20 | #include "vec2d.h" |
| 21 | #include <math.h> |
| 22 | #include <stdio.h> |
| 23 | |
| 24 | /** |
| 25 | * Calculates the magnitude of a 2D cartesian vector. |
| 26 | * @param v The 2D cartesian vector. |
| 27 | * @return The magnitude of the vector. |
| 28 | */ |
| 29 | double _v2dMag(const Vec2d* v) { return sqrt(v->x * v->x + v->y * v->y); } |
| 30 | |
| 31 | /** |
| 32 | * Finds the intersection between two lines. Assumes that the lines intersect |
| 33 | * and that the intersection is not at an endpoint of either line. |
| 34 | * @param p0 The first endpoint of the first line. |
| 35 | * @param p1 The second endpoint of the first line. |
| 36 | * @param p2 The first endpoint of the second line. |
| 37 | * @param p3 The second endpoint of the second line. |
| 38 | * @param inter The intersection point. |
| 39 | */ |
| 40 | void _v2dIntersect(const Vec2d* p0, const Vec2d* p1, const Vec2d* p2, |
| 41 | const Vec2d* p3, Vec2d* inter) { |
| 42 | Vec2d s1, s2; |
| 43 | s1.x = p1->x - p0->x; |
| 44 | s1.y = p1->y - p0->y; |
| 45 | s2.x = p3->x - p2->x; |
| 46 | s2.y = p3->y - p2->y; |
| 47 | |
| 48 | float t; |
| 49 | t = (s2.x * (p0->y - p2->y) - s2.y * (p0->x - p2->x)) / |
| 50 | (-s2.x * s1.y + s1.x * s2.y); |
| 51 | |
| 52 | inter->x = p0->x + (t * s1.x); |
| 53 | inter->y = p0->y + (t * s1.y); |
| 54 | } |
| 55 | |
| 56 | /** |
| 57 | * Whether two 2D vectors are equal. Does not consider possible false |
| 58 | * negatives due to floating-point errors. |
| 59 | * @param v1 First vector to compare |
| 60 | * @param v2 Second vector to compare |
| 61 | * @return Whether the vectors are equal |
| 62 | */ |
| 63 | bool _v2dEquals(const Vec2d* v1, const Vec2d* v2) { |
| 64 | return v1->x == v2->x && v1->y == v2->y; |
| 65 | } |
| 66 | |