aboutsummaryrefslogtreecommitdiff
path: root/dep/src/g3dlite/Line.cpp
blob: 195ae7197f22c08817bdcccd2c3cde2ec6078862 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
  @file Line.cpp
 
  Line class
 
  @maintainer Morgan McGuire, graphics3d.com
 
  @created 2001-06-02
  @edited  2006-01-28
 */

#include "G3D/Line.h"
#include "G3D/Plane.h"

namespace G3D {

Vector3 Line::intersection(const Plane& plane) const {
    float d;
    Vector3 normal = plane.normal();
    plane.getEquation(normal, d);
    float rate = _direction.dot(normal);

    if (rate == 0) {

        return Vector3::inf();

    } else {
        float t = -(d + _point.dot(normal)) / rate;

        return _point + _direction * t;
    }
}


Line::Line(class BinaryInput& b) {
	deserialize(b);
}


void Line::serialize(class BinaryOutput& b) const {
	_point.serialize(b);
	_direction.serialize(b);
}


void Line::deserialize(class BinaryInput& b) {
	_point.deserialize(b);
	_direction.deserialize(b);
}


Vector3 Line::closestPoint(const Vector3& pt) const {
    float t = _direction.dot(pt - _point);
    return _point + _direction * t;
}


Vector3 Line::point() const {
    return _point;
}


Vector3 Line::direction() const {
    return _direction;
}


Vector3 Line::closestPoint(const Line& B, float& minDist) const {
    const Vector3& P1 = _point;
    const Vector3& U1 = _direction;

    Vector3 P2 = B.point();
    Vector3 U2 = B.direction();
    
    const Vector3& P21 = P2 - P1;
    const Vector3& M = U2.cross(U1);
    float m2 = M.length();

    Vector3 R = P21.cross(M) / m2;
    
    float t1 = R.dot(U2);
    
    minDist = abs(P21.dot(M)) / sqrt(m2);

    return P1 + t1 * U1;
}

}