Ray.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "BoundingBox.h"
  24. #include "Frustum.h"
  25. #include "Plane.h"
  26. #include "Ray.h"
  27. #include "Sphere.h"
  28. namespace Urho3D
  29. {
  30. Vector3 Ray::ClosestPoint(const Ray& ray) const
  31. {
  32. // Algorithm based on http://paulbourke.net/geometry/lineline3d/
  33. Vector3 p13 = origin_ - ray.origin_;
  34. Vector3 p43 = ray.direction_;
  35. Vector3 p21 = direction_;
  36. float d1343 = p13.DotProduct(p43);
  37. float d4321 = p43.DotProduct(p21);
  38. float d1321 = p13.DotProduct(p21);
  39. float d4343 = p43.DotProduct(p43);
  40. float d2121 = p21.DotProduct(p21);
  41. float d = d2121 * d4343 - d4321 * d4321;
  42. if (Abs(d) < M_EPSILON)
  43. return origin_;
  44. float n = d1343 * d4321 - d1321 * d4343;
  45. float a = n / d;
  46. return origin_ + a * direction_;
  47. }
  48. float Ray::HitDistance(const Plane& plane) const
  49. {
  50. float d = plane.normal_.DotProduct(direction_);
  51. if (Abs(d) >= M_EPSILON)
  52. {
  53. float t = -(plane.normal_.DotProduct(origin_) + plane.d_) / d;
  54. if (t >= 0.0f)
  55. return t;
  56. else
  57. return M_INFINITY;
  58. }
  59. else
  60. return M_INFINITY;
  61. }
  62. float Ray::HitDistance(const BoundingBox& box) const
  63. {
  64. // If undefined, no hit (infinite distance)
  65. if (!box.defined_)
  66. return M_INFINITY;
  67. // Check for ray origin being inside the box
  68. if (box.IsInside(origin_))
  69. return 0.0f;
  70. float dist = M_INFINITY;
  71. // Check for intersecting in the X-direction
  72. if (origin_.x_ < box.min_.x_ && direction_.x_ > 0.0f)
  73. {
  74. float x = (box.min_.x_ - origin_.x_) / direction_.x_;
  75. if (x < dist)
  76. {
  77. Vector3 point = origin_ + x * direction_;
  78. if (point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
  79. dist = x;
  80. }
  81. }
  82. if (origin_.x_ > box.max_.x_ && direction_.x_ < 0.0f)
  83. {
  84. float x = (box.max_.x_ - origin_.x_) / direction_.x_;
  85. if (x < dist)
  86. {
  87. Vector3 point = origin_ + x * direction_;
  88. if (point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
  89. dist = x;
  90. }
  91. }
  92. // Check for intersecting in the Y-direction
  93. if (origin_.y_ < box.min_.y_ && direction_.y_ > 0.0f)
  94. {
  95. float x = (box.min_.y_ - origin_.y_) / direction_.y_;
  96. if (x < dist)
  97. {
  98. Vector3 point = origin_ + x * direction_;
  99. if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
  100. dist = x;
  101. }
  102. }
  103. if (origin_.y_ > box.max_.y_ && direction_.y_ < 0.0f)
  104. {
  105. float x = (box.max_.y_ - origin_.y_) / direction_.y_;
  106. if (x < dist)
  107. {
  108. Vector3 point = origin_ + x * direction_;
  109. if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
  110. dist = x;
  111. }
  112. }
  113. // Check for intersecting in the Z-direction
  114. if (origin_.z_ < box.min_.z_ && direction_.z_ > 0.0f)
  115. {
  116. float x = (box.min_.z_ - origin_.z_) / direction_.z_;
  117. if (x < dist)
  118. {
  119. Vector3 point = origin_ + x * direction_;
  120. if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_)
  121. dist = x;
  122. }
  123. }
  124. if (origin_.z_ > box.max_.z_ && direction_.z_ < 0.0f)
  125. {
  126. float x = (box.max_.z_ - origin_.z_) / direction_.z_;
  127. if (x < dist)
  128. {
  129. Vector3 point = origin_ + x * direction_;
  130. if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_)
  131. dist = x;
  132. }
  133. }
  134. return dist;
  135. }
  136. float Ray::HitDistance(const Frustum& frustum, bool solidInside) const
  137. {
  138. float maxOutside = 0.0f;
  139. float minInside = M_INFINITY;
  140. bool allInside = true;
  141. for (unsigned i = 0; i < NUM_FRUSTUM_PLANES; ++i)
  142. {
  143. const Plane& plane = frustum.planes_[i];
  144. float distance = HitDistance(frustum.planes_[i]);
  145. if (plane.Distance(origin_) < 0.0f)
  146. {
  147. maxOutside = Max(maxOutside, distance);
  148. allInside = false;
  149. }
  150. else
  151. minInside = Min(minInside, distance);
  152. }
  153. if (allInside)
  154. return solidInside ? 0.0f : minInside;
  155. else if (maxOutside <= minInside)
  156. return maxOutside;
  157. else
  158. return M_INFINITY;
  159. }
  160. float Ray::HitDistance(const Sphere& sphere) const
  161. {
  162. Vector3 centeredOrigin = origin_ - sphere.center_;
  163. float squaredRadius = sphere.radius_ * sphere.radius_;
  164. // Check if ray originates inside the sphere
  165. if (centeredOrigin.LengthSquared() <= squaredRadius)
  166. return 0.0f;
  167. // Calculate intersection by quadratic equation
  168. float a = direction_.DotProduct(direction_);
  169. float b = 2.0f * centeredOrigin.DotProduct(direction_);
  170. float c = centeredOrigin.DotProduct(centeredOrigin) - squaredRadius;
  171. float d = b * b - 4.0f * a * c;
  172. // No solution
  173. if (d < 0.0f)
  174. return M_INFINITY;
  175. // Get the nearer solution
  176. float dSqrt = sqrtf(d);
  177. float dist = (-b - dSqrt) / (2.0f * a);
  178. if (dist >= 0.0f)
  179. return dist;
  180. else
  181. return (-b + dSqrt) / (2.0f * a);
  182. }
  183. float Ray::HitDistance(const Vector3& v0, const Vector3& v1, const Vector3& v2) const
  184. {
  185. return HitDistance(v0, v1, v2, 0);
  186. }
  187. float Ray::HitDistance(const Vector3& v0, const Vector3& v1, const Vector3& v2, Vector3* outNormal) const
  188. {
  189. // Based on Fast, Minimum Storage Ray/Triangle Intersection by Möller & Trumbore
  190. // http://www.graphics.cornell.edu/pubs/1997/MT97.pdf
  191. // Calculate edge vectors
  192. Vector3 edge1(v1 - v0);
  193. Vector3 edge2(v2 - v0);
  194. // Calculate determinant & check backfacing
  195. Vector3 p(direction_.CrossProduct(edge2));
  196. float det = edge1.DotProduct(p);
  197. if (det >= M_EPSILON)
  198. {
  199. // Calculate u & v parameters and test
  200. Vector3 t(origin_ - v0);
  201. float u = t.DotProduct(p);
  202. if (u >= 0.0f && u <= det)
  203. {
  204. Vector3 q(t.CrossProduct(edge1));
  205. float v = direction_.DotProduct(q);
  206. if (v >= 0.0f && u + v <= det)
  207. {
  208. float distance = edge2.DotProduct(q) / det;
  209. // Discard hits behind the ray
  210. if (distance >= 0.0f)
  211. {
  212. // There is an intersection, so calculate distance & optional normal
  213. if (outNormal)
  214. *outNormal = edge1.CrossProduct(edge2);
  215. return distance;
  216. }
  217. }
  218. }
  219. }
  220. return M_INFINITY;
  221. }
  222. float Ray::HitDistance(const void* vertexData, unsigned vertexSize, unsigned vertexStart, unsigned vertexCount, Vector3* outNormal) const
  223. {
  224. float nearest = M_INFINITY;
  225. const unsigned char* vertices = ((const unsigned char*)vertexData) + vertexStart * vertexSize;
  226. unsigned index = 0;
  227. while (index + 2 < vertexCount)
  228. {
  229. const Vector3& v0 = *((const Vector3*)(&vertices[index * vertexSize]));
  230. const Vector3& v1 = *((const Vector3*)(&vertices[(index + 1) * vertexSize]));
  231. const Vector3& v2 = *((const Vector3*)(&vertices[(index + 2) * vertexSize]));
  232. nearest = Min(nearest, HitDistance(v0, v1, v2, outNormal));
  233. index += 3;
  234. }
  235. return nearest;
  236. }
  237. float Ray::HitDistance(const void* vertexData, unsigned vertexSize, const void* indexData, unsigned indexSize,
  238. unsigned indexStart, unsigned indexCount, Vector3* outNormal) const
  239. {
  240. float nearest = M_INFINITY;
  241. const unsigned char* vertices = (const unsigned char*)vertexData;
  242. // 16-bit indices
  243. if (indexSize == sizeof(unsigned short))
  244. {
  245. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  246. const unsigned short* indicesEnd = indices + indexCount;
  247. while (indices < indicesEnd)
  248. {
  249. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexSize]));
  250. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexSize]));
  251. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexSize]));
  252. nearest = Min(nearest, HitDistance(v0, v1, v2, outNormal));
  253. indices += 3;
  254. }
  255. }
  256. // 32-bit indices
  257. else
  258. {
  259. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  260. const unsigned* indicesEnd = indices + indexCount;
  261. while (indices < indicesEnd)
  262. {
  263. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexSize]));
  264. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexSize]));
  265. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexSize]));
  266. nearest = Min(nearest, HitDistance(v0, v1, v2, outNormal));
  267. indices += 3;
  268. }
  269. }
  270. return nearest;
  271. }
  272. bool Ray::InsideGeometry(const void* vertexData, unsigned vertexSize, unsigned vertexStart, unsigned vertexCount) const
  273. {
  274. float currentFrontFace = M_INFINITY;
  275. float currentBackFace = M_INFINITY;
  276. const unsigned char* vertices = ((const unsigned char*)vertexData) + vertexStart * vertexSize;
  277. unsigned index = 0;
  278. while (index + 2 < vertexCount)
  279. {
  280. const Vector3& v0 = *((const Vector3*)(&vertices[index * vertexSize]));
  281. const Vector3& v1 = *((const Vector3*)(&vertices[(index + 1) * vertexSize]));
  282. const Vector3& v2 = *((const Vector3*)(&vertices[(index + 2) * vertexSize]));
  283. float frontFaceDistance = HitDistance(v0, v1, v2);
  284. float backFaceDistance = HitDistance(v2, v1, v0);
  285. currentFrontFace = Min(frontFaceDistance > 0.0f ? frontFaceDistance : M_INFINITY, currentFrontFace);
  286. // A backwards face is just a regular one, with the vertices in the opposite order. This essentially checks backfaces by
  287. // checking reversed frontfaces
  288. currentBackFace = Min(backFaceDistance > 0.0f ? backFaceDistance : M_INFINITY, currentBackFace);
  289. index += 3;
  290. }
  291. // If the closest face is a backface, that means that the ray originates from the inside of the geometry
  292. // NOTE: there may be cases where both are equal, as in, no collision to either. This is prevented in the most likely case
  293. // (ray doesnt hit either) by this conditional
  294. if (currentFrontFace != M_INFINITY || currentBackFace != M_INFINITY)
  295. return currentBackFace < currentFrontFace;
  296. // It is still possible for two triangles to be equally distant from the triangle, however, this is extremely unlikely.
  297. // As such, it is safe to assume they are not
  298. return false;
  299. }
  300. bool Ray::InsideGeometry(const void* vertexData, unsigned vertexSize, const void* indexData, unsigned indexSize,
  301. unsigned indexStart, unsigned indexCount) const
  302. {
  303. float currentFrontFace = M_INFINITY;
  304. float currentBackFace = M_INFINITY;
  305. const unsigned char* vertices = (const unsigned char*)vertexData;
  306. // 16-bit indices
  307. if (indexSize == sizeof(unsigned short))
  308. {
  309. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  310. const unsigned short* indicesEnd = indices + indexCount;
  311. while (indices < indicesEnd)
  312. {
  313. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexSize]));
  314. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexSize]));
  315. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexSize]));
  316. float frontFaceDistance = HitDistance(v0, v1, v2);
  317. float backFaceDistance = HitDistance(v2, v1, v0);
  318. currentFrontFace = Min(frontFaceDistance > 0.0f ? frontFaceDistance : M_INFINITY, currentFrontFace);
  319. // A backwards face is just a regular one, with the vertices in the opposite order. This essentially checks backfaces by
  320. // checking reversed frontfaces
  321. currentBackFace = Min(backFaceDistance > 0.0f ? backFaceDistance : M_INFINITY, currentBackFace);
  322. indices += 3;
  323. }
  324. }
  325. // 32-bit indices
  326. else
  327. {
  328. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  329. const unsigned* indicesEnd = indices + indexCount;
  330. while (indices < indicesEnd)
  331. {
  332. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexSize]));
  333. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexSize]));
  334. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexSize]));
  335. float frontFaceDistance = HitDistance(v0, v1, v2);
  336. float backFaceDistance = HitDistance(v2, v1, v0);
  337. currentFrontFace = Min(frontFaceDistance > 0.0f ? frontFaceDistance : M_INFINITY, currentFrontFace);
  338. // A backwards face is just a regular one, with the vertices in the opposite order. This essentially checks backfaces by
  339. // checking reversed frontfaces
  340. currentBackFace = Min(backFaceDistance > 0.0f ? backFaceDistance : M_INFINITY, currentBackFace);
  341. indices += 3;
  342. }
  343. }
  344. // If the closest face is a backface, that means that the ray originates from the inside of the geometry
  345. // NOTE: there may be cases where both are equal, as in, no collision to either. This is prevented in the most likely case
  346. // (ray doesnt hit either) by this conditional
  347. if (currentFrontFace != M_INFINITY || currentBackFace != M_INFINITY)
  348. return currentBackFace < currentFrontFace;
  349. // It is still possible for two triangles to be equally distant from the triangle, however, this is extremely unlikely.
  350. // As such, it is safe to assume they are not
  351. return false;
  352. }
  353. Ray Ray::Transformed(const Matrix3x4& transform) const
  354. {
  355. Ray ret;
  356. ret.origin_ = transform * origin_;
  357. ret.direction_ = transform * Vector4(direction_, 0.0f);
  358. return ret;
  359. }
  360. }