1 |
using System; |
2 |
|
3 |
namespace Oni |
4 |
{ |
5 |
internal struct Plane : IEquatable<Plane> |
6 |
{ |
7 |
public Vector3 Normal; |
8 |
public float D; |
9 |
|
10 |
public Plane(Vector3 normal, float d) |
11 |
{ |
12 |
Normal = normal; |
13 |
D = d; |
14 |
} |
15 |
|
16 |
public Plane(Vector3 point1, Vector3 point2, Vector3 point3) |
17 |
{ |
18 |
Normal = Vector3.Normalize(Vector3.Cross(point2 - point1, point3 - point1)); |
19 |
D = -Vector3.Dot(Normal, point1); |
20 |
} |
21 |
|
22 |
public float DotCoordinate(Vector3 point) => Vector3.Dot(Normal, point) + D; |
23 |
|
24 |
public float DotNormal(Vector3 value) => Vector3.Dot(Normal, value); |
25 |
|
26 |
public void Flip() |
27 |
{ |
28 |
Normal = -Normal; |
29 |
D = -D; |
30 |
} |
31 |
|
32 |
public static Plane Flip(Plane plane) |
33 |
{ |
34 |
plane.Normal = -plane.Normal; |
35 |
plane.D = -plane.D; |
36 |
|
37 |
return plane; |
38 |
} |
39 |
|
40 |
public static bool operator ==(Plane p1, Plane p2) => p1.D == p2.D && p1.Normal == p2.Normal; |
41 |
public static bool operator !=(Plane p1, Plane p2) => p1.D != p2.D || p1.Normal != p2.Normal; |
42 |
|
43 |
public bool Equals(Plane other) => other.D == D && other.Normal == Normal; |
44 |
|
45 |
public override bool Equals(object obj) => obj is Plane && Equals((Plane)obj); |
46 |
public override int GetHashCode() => Normal.GetHashCode() ^ D.GetHashCode(); |
47 |
|
48 |
public override string ToString() => $"{{Normal:{Normal} D:{D}}}"; |
49 |
|
50 |
public int Intersects(BoundingBox box) |
51 |
{ |
52 |
Vector3 max, min; |
53 |
|
54 |
if (Normal.X >= 0.0f) |
55 |
{ |
56 |
min.X = box.Min.X; |
57 |
max.X = box.Max.X; |
58 |
} |
59 |
else |
60 |
{ |
61 |
min.X = box.Max.X; |
62 |
max.X = box.Min.X; |
63 |
} |
64 |
|
65 |
if (Normal.Y >= 0.0f) |
66 |
{ |
67 |
min.Y = box.Min.Y; |
68 |
max.Y = box.Max.Y; |
69 |
} |
70 |
else |
71 |
{ |
72 |
min.Y = box.Max.Y; |
73 |
max.Y = box.Min.Y; |
74 |
} |
75 |
|
76 |
if (Normal.Z >= 0.0f) |
77 |
{ |
78 |
min.Z = box.Min.Z; |
79 |
max.Z = box.Max.Z; |
80 |
} |
81 |
else |
82 |
{ |
83 |
min.Z = box.Max.Z; |
84 |
max.Z = box.Min.Z; |
85 |
} |
86 |
|
87 |
if (Vector3.Dot(Normal, min) + D > 0.0f) |
88 |
return 1; |
89 |
else if (Vector3.Dot(Normal, max) + D < 0.0f) |
90 |
return -1; |
91 |
else |
92 |
return 0; |
93 |
} |
94 |
} |
95 |
} |