Ray.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. //
  2. // Copyright (c) 2008-2015 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 "../Math/BoundingBox.h"
  23. #include "../Math/Frustum.h"
  24. #include "../Math/Plane.h"
  25. #include "../Math/Ray.h"
  26. #include "../Math/Sphere.h"
  27. namespace Urho3D
  28. {
  29. Vector3 Ray::ClosestPoint(const Ray& ray) const
  30. {
  31. // Algorithm based on http://paulbourke.net/geometry/lineline3d/
  32. Vector3 p13 = origin_ - ray.origin_;
  33. Vector3 p43 = ray.direction_;
  34. Vector3 p21 = direction_;
  35. float d1343 = p13.DotProduct(p43);
  36. float d4321 = p43.DotProduct(p21);
  37. float d1321 = p13.DotProduct(p21);
  38. float d4343 = p43.DotProduct(p43);
  39. float d2121 = p21.DotProduct(p21);
  40. float d = d2121 * d4343 - d4321 * d4321;
  41. if (Abs(d) < M_EPSILON)
  42. return origin_;
  43. float n = d1343 * d4321 - d1321 * d4343;
  44. float a = n / d;
  45. return origin_ + a * direction_;
  46. }
  47. float Ray::HitDistance(const Plane& plane) const
  48. {
  49. float d = plane.normal_.DotProduct(direction_);
  50. if (Abs(d) >= M_EPSILON)
  51. {
  52. float t = -(plane.normal_.DotProduct(origin_) + plane.d_) / d;
  53. if (t >= 0.0f)
  54. return t;
  55. else
  56. return M_INFINITY;
  57. }
  58. else
  59. return M_INFINITY;
  60. }
  61. float Ray::HitDistance(const BoundingBox& box) const
  62. {
  63. // If undefined, no hit (infinite distance)
  64. if (!box.defined_)
  65. return M_INFINITY;
  66. // Check for ray origin being inside the box
  67. if (box.IsInside(origin_))
  68. return 0.0f;
  69. float dist = M_INFINITY;
  70. // Check for intersecting in the X-direction
  71. if (origin_.x_ < box.min_.x_ && direction_.x_ > 0.0f)
  72. {
  73. float x = (box.min_.x_ - origin_.x_) / direction_.x_;
  74. if (x < dist)
  75. {
  76. Vector3 point = origin_ + x * direction_;
  77. if (point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
  78. dist = x;
  79. }
  80. }
  81. if (origin_.x_ > box.max_.x_ && direction_.x_ < 0.0f)
  82. {
  83. float x = (box.max_.x_ - origin_.x_) / direction_.x_;
  84. if (x < dist)
  85. {
  86. Vector3 point = origin_ + x * direction_;
  87. if (point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
  88. dist = x;
  89. }
  90. }
  91. // Check for intersecting in the Y-direction
  92. if (origin_.y_ < box.min_.y_ && direction_.y_ > 0.0f)
  93. {
  94. float x = (box.min_.y_ - origin_.y_) / direction_.y_;
  95. if (x < dist)
  96. {
  97. Vector3 point = origin_ + x * direction_;
  98. if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
  99. dist = x;
  100. }
  101. }
  102. if (origin_.y_ > box.max_.y_ && direction_.y_ < 0.0f)
  103. {
  104. float x = (box.max_.y_ - origin_.y_) / direction_.y_;
  105. if (x < dist)
  106. {
  107. Vector3 point = origin_ + x * direction_;
  108. if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.z_ >= box.min_.z_ && point.z_ <= box.max_.z_)
  109. dist = x;
  110. }
  111. }
  112. // Check for intersecting in the Z-direction
  113. if (origin_.z_ < box.min_.z_ && direction_.z_ > 0.0f)
  114. {
  115. float x = (box.min_.z_ - origin_.z_) / direction_.z_;
  116. if (x < dist)
  117. {
  118. Vector3 point = origin_ + x * direction_;
  119. if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_)
  120. dist = x;
  121. }
  122. }
  123. if (origin_.z_ > box.max_.z_ && direction_.z_ < 0.0f)
  124. {
  125. float x = (box.max_.z_ - origin_.z_) / direction_.z_;
  126. if (x < dist)
  127. {
  128. Vector3 point = origin_ + x * direction_;
  129. if (point.x_ >= box.min_.x_ && point.x_ <= box.max_.x_ && point.y_ >= box.min_.y_ && point.y_ <= box.max_.y_)
  130. dist = x;
  131. }
  132. }
  133. return dist;
  134. }
  135. float Ray::HitDistance(const Frustum& frustum, bool solidInside) const
  136. {
  137. float maxOutside = 0.0f;
  138. float minInside = M_INFINITY;
  139. bool allInside = true;
  140. for (unsigned i = 0; i < NUM_FRUSTUM_PLANES; ++i)
  141. {
  142. const Plane& plane = frustum.planes_[i];
  143. float distance = HitDistance(frustum.planes_[i]);
  144. if (plane.Distance(origin_) < 0.0f)
  145. {
  146. maxOutside = Max(maxOutside, distance);
  147. allInside = false;
  148. }
  149. else
  150. minInside = Min(minInside, distance);
  151. }
  152. if (allInside)
  153. return solidInside ? 0.0f : minInside;
  154. else if (maxOutside <= minInside)
  155. return maxOutside;
  156. else
  157. return M_INFINITY;
  158. }
  159. float Ray::HitDistance(const Sphere& sphere) const
  160. {
  161. Vector3 centeredOrigin = origin_ - sphere.center_;
  162. float squaredRadius = sphere.radius_ * sphere.radius_;
  163. // Check if ray originates inside the sphere
  164. if (centeredOrigin.LengthSquared() <= squaredRadius)
  165. return 0.0f;
  166. // Calculate intersection by quadratic equation
  167. float a = direction_.DotProduct(direction_);
  168. float b = 2.0f * centeredOrigin.DotProduct(direction_);
  169. float c = centeredOrigin.DotProduct(centeredOrigin) - squaredRadius;
  170. float d = b * b - 4.0f * a * c;
  171. // No solution
  172. if (d < 0.0f)
  173. return M_INFINITY;
  174. // Get the nearer solution
  175. float dSqrt = sqrtf(d);
  176. float dist = (-b - dSqrt) / (2.0f * a);
  177. if (dist >= 0.0f)
  178. return dist;
  179. else
  180. return (-b + dSqrt) / (2.0f * a);
  181. }
  182. float Ray::HitDistance(const Vector3& v0, const Vector3& v1, const Vector3& v2) const
  183. {
  184. return HitDistance(v0, v1, v2, 0, 0);
  185. }
  186. float Ray::HitDistance(const Vector3& v0, const Vector3& v1, const Vector3& v2, Vector3* outNormal,Vector3 *outBary) const
  187. {
  188. // Based on Fast, Minimum Storage Ray/Triangle Intersection by M�ller & Trumbore
  189. // http://www.graphics.cornell.edu/pubs/1997/MT97.pdf
  190. // Calculate edge vectors
  191. Vector3 edge1(v1 - v0);
  192. Vector3 edge2(v2 - v0);
  193. // Calculate determinant & check backfacing
  194. Vector3 p(direction_.CrossProduct(edge2));
  195. float det = edge1.DotProduct(p);
  196. if (det >= M_EPSILON)
  197. {
  198. // Calculate u & v parameters and test
  199. Vector3 t(origin_ - v0);
  200. float u = t.DotProduct(p);
  201. if (u >= 0.0f && u <= det)
  202. {
  203. Vector3 q(t.CrossProduct(edge1));
  204. float v = direction_.DotProduct(q);
  205. if (v >= 0.0f && u + v <= det)
  206. {
  207. float distance = edge2.DotProduct(q) / det;
  208. // Discard hits behind the ray
  209. if (distance >= 0.0f)
  210. {
  211. // There is an intersection, so calculate distance & optional normal
  212. if (outNormal)
  213. *outNormal = edge1.CrossProduct(edge2);
  214. if (outBary) {
  215. *outBary = Vector3(1-(u/det)-(v/det),u/det,v/det);
  216. }
  217. return distance;
  218. }
  219. }
  220. }
  221. }
  222. return M_INFINITY;
  223. }
  224. float Ray::HitDistance(const void* vertexData, unsigned vertexStride, unsigned vertexStart, unsigned vertexCount, Vector3* outNormal, Vector2 * outUV1, unsigned uvOffset) const
  225. {
  226. float nearest = M_INFINITY;
  227. const unsigned char* vertices = ((const unsigned char*)vertexData) + vertexStart * vertexStride;
  228. unsigned index = 0;
  229. if(outUV1) {
  230. unsigned nearestIdx = -1;
  231. Vector3 barycentric;
  232. while (index + 2 < vertexCount)
  233. {
  234. const Vector3& v0 = *((const Vector3*)(&vertices[index * vertexStride]));
  235. const Vector3& v1 = *((const Vector3*)(&vertices[(index + 1) * vertexStride]));
  236. const Vector3& v2 = *((const Vector3*)(&vertices[(index + 2) * vertexStride]));
  237. float interesectDist = HitDistance(v0, v1, v2, outNormal,&barycentric);
  238. if(interesectDist<nearest) {
  239. nearestIdx = index;
  240. nearest = interesectDist;
  241. }
  242. index += 3;
  243. }
  244. if(nearestIdx!=-1) {
  245. const Vector2& uv0 = *((const Vector2*)(&vertices[uvOffset + nearestIdx * vertexStride]));
  246. const Vector2& uv1 = *((const Vector2*)(&vertices[uvOffset + (nearestIdx + 1) * vertexStride]));
  247. const Vector2& uv2 = *((const Vector2*)(&vertices[uvOffset + (nearestIdx + 2) * vertexStride]));
  248. // get the uv value from barycentric coordinates
  249. *outUV1 = Vector2(uv0.x_ * barycentric.x_ + uv1.x_ * barycentric.y_ + uv2.x_ * barycentric.z_,
  250. uv0.y_ * barycentric.x_ + uv1.y_ * barycentric.y_ + uv2.y_ * barycentric.z_
  251. );
  252. }
  253. }
  254. else {
  255. while (index + 2 < vertexCount)
  256. {
  257. const Vector3& v0 = *((const Vector3*)(&vertices[index * vertexStride]));
  258. const Vector3& v1 = *((const Vector3*)(&vertices[(index + 1) * vertexStride]));
  259. const Vector3& v2 = *((const Vector3*)(&vertices[(index + 2) * vertexStride]));
  260. nearest = Min(nearest, HitDistance(v0, v1, v2, outNormal,0));
  261. index += 3;
  262. }
  263. }
  264. return nearest;
  265. }
  266. float Ray::HitDistance(const void* vertexData, unsigned vertexStride, const void* indexData, unsigned indexSize,
  267. unsigned indexStart, unsigned indexCount, Vector3* outNormal, Vector2 *outUV, unsigned uvOffset) const
  268. {
  269. float nearest = M_INFINITY;
  270. const unsigned char* vertices = (const unsigned char*)vertexData;
  271. if(outUV) {
  272. int nearestIdx[3] = {-1,-1,-1};
  273. Vector3 barycentric;
  274. // 16-bit indices
  275. if (indexSize == sizeof(unsigned short))
  276. {
  277. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  278. const unsigned short* indicesEnd = indices + indexCount;
  279. while (indices < indicesEnd)
  280. {
  281. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexStride]));
  282. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexStride]));
  283. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexStride]));
  284. float interesectDist = HitDistance(v0, v1, v2, outNormal,&barycentric);
  285. if(interesectDist<nearest) {
  286. nearestIdx[0] = indices[0];
  287. nearestIdx[1] = indices[1];
  288. nearestIdx[2] = indices[2];
  289. nearest = interesectDist;
  290. }
  291. indices += 3;
  292. }
  293. }
  294. // 32-bit indices
  295. else
  296. {
  297. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  298. const unsigned* indicesEnd = indices + indexCount;
  299. while (indices < indicesEnd)
  300. {
  301. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexStride]));
  302. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexStride]));
  303. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexStride]));
  304. float interesectDist = HitDistance(v0, v1, v2, outNormal,&barycentric);
  305. if(interesectDist<nearest) {
  306. nearestIdx[0] = indices[0];
  307. nearestIdx[1] = indices[1];
  308. nearestIdx[2] = indices[2];
  309. nearest = interesectDist;
  310. }
  311. indices += 3;
  312. }
  313. }
  314. if(nearestIdx[0]!=-1) {
  315. const Vector2& uv0 = *((const Vector2*)(&vertices[uvOffset + nearestIdx[0] * vertexStride]));
  316. const Vector2& uv1 = *((const Vector2*)(&vertices[uvOffset + nearestIdx[1] * vertexStride]));
  317. const Vector2& uv2 = *((const Vector2*)(&vertices[uvOffset + nearestIdx[2] * vertexStride]));
  318. // get the uv value from barycentric coordinates
  319. *outUV = Vector2(uv0.x_ * barycentric.x_ + uv1.x_ * barycentric.y_ + uv2.x_ * barycentric.z_,
  320. uv0.y_ * barycentric.x_ + uv1.y_ * barycentric.y_ + uv2.y_ * barycentric.z_
  321. );
  322. }
  323. }
  324. else {
  325. // 16-bit indices
  326. if (indexSize == sizeof(unsigned short))
  327. {
  328. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  329. const unsigned short* indicesEnd = indices + indexCount;
  330. while (indices < indicesEnd)
  331. {
  332. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexStride]));
  333. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexStride]));
  334. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexStride]));
  335. nearest = Min(nearest, HitDistance(v0, v1, v2, outNormal,0));
  336. indices += 3;
  337. }
  338. }
  339. // 32-bit indices
  340. else
  341. {
  342. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  343. const unsigned* indicesEnd = indices + indexCount;
  344. while (indices < indicesEnd)
  345. {
  346. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexStride]));
  347. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexStride]));
  348. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexStride]));
  349. nearest = Min(nearest, HitDistance(v0, v1, v2, outNormal,0));
  350. indices += 3;
  351. }
  352. }
  353. }
  354. return nearest;
  355. }
  356. bool Ray::InsideGeometry(const void* vertexData, unsigned vertexSize, unsigned vertexStart, unsigned vertexCount) const
  357. {
  358. float currentFrontFace = M_INFINITY;
  359. float currentBackFace = M_INFINITY;
  360. const unsigned char* vertices = ((const unsigned char*)vertexData) + vertexStart * vertexSize;
  361. unsigned index = 0;
  362. while (index + 2 < vertexCount)
  363. {
  364. const Vector3& v0 = *((const Vector3*)(&vertices[index * vertexSize]));
  365. const Vector3& v1 = *((const Vector3*)(&vertices[(index + 1) * vertexSize]));
  366. const Vector3& v2 = *((const Vector3*)(&vertices[(index + 2) * vertexSize]));
  367. float frontFaceDistance = HitDistance(v0, v1, v2);
  368. float backFaceDistance = HitDistance(v2, v1, v0);
  369. currentFrontFace = Min(frontFaceDistance > 0.0f ? frontFaceDistance : M_INFINITY, currentFrontFace);
  370. // A backwards face is just a regular one, with the vertices in the opposite order. This essentially checks backfaces by
  371. // checking reversed frontfaces
  372. currentBackFace = Min(backFaceDistance > 0.0f ? backFaceDistance : M_INFINITY, currentBackFace);
  373. index += 3;
  374. }
  375. // If the closest face is a backface, that means that the ray originates from the inside of the geometry
  376. // NOTE: there may be cases where both are equal, as in, no collision to either. This is prevented in the most likely case
  377. // (ray doesnt hit either) by this conditional
  378. if (currentFrontFace != M_INFINITY || currentBackFace != M_INFINITY)
  379. return currentBackFace < currentFrontFace;
  380. // It is still possible for two triangles to be equally distant from the triangle, however, this is extremely unlikely.
  381. // As such, it is safe to assume they are not
  382. return false;
  383. }
  384. bool Ray::InsideGeometry(const void* vertexData, unsigned vertexSize, const void* indexData, unsigned indexSize,
  385. unsigned indexStart, unsigned indexCount) const
  386. {
  387. float currentFrontFace = M_INFINITY;
  388. float currentBackFace = M_INFINITY;
  389. const unsigned char* vertices = (const unsigned char*)vertexData;
  390. // 16-bit indices
  391. if (indexSize == sizeof(unsigned short))
  392. {
  393. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  394. const unsigned short* indicesEnd = indices + indexCount;
  395. while (indices < indicesEnd)
  396. {
  397. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexSize]));
  398. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexSize]));
  399. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexSize]));
  400. float frontFaceDistance = HitDistance(v0, v1, v2);
  401. float backFaceDistance = HitDistance(v2, v1, v0);
  402. currentFrontFace = Min(frontFaceDistance > 0.0f ? frontFaceDistance : M_INFINITY, currentFrontFace);
  403. // A backwards face is just a regular one, with the vertices in the opposite order. This essentially checks backfaces by
  404. // checking reversed frontfaces
  405. currentBackFace = Min(backFaceDistance > 0.0f ? backFaceDistance : M_INFINITY, currentBackFace);
  406. indices += 3;
  407. }
  408. }
  409. // 32-bit indices
  410. else
  411. {
  412. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  413. const unsigned* indicesEnd = indices + indexCount;
  414. while (indices < indicesEnd)
  415. {
  416. const Vector3& v0 = *((const Vector3*)(&vertices[indices[0] * vertexSize]));
  417. const Vector3& v1 = *((const Vector3*)(&vertices[indices[1] * vertexSize]));
  418. const Vector3& v2 = *((const Vector3*)(&vertices[indices[2] * vertexSize]));
  419. float frontFaceDistance = HitDistance(v0, v1, v2);
  420. float backFaceDistance = HitDistance(v2, v1, v0);
  421. currentFrontFace = Min(frontFaceDistance > 0.0f ? frontFaceDistance : M_INFINITY, currentFrontFace);
  422. // A backwards face is just a regular one, with the vertices in the opposite order. This essentially checks backfaces by
  423. // checking reversed frontfaces
  424. currentBackFace = Min(backFaceDistance > 0.0f ? backFaceDistance : M_INFINITY, currentBackFace);
  425. indices += 3;
  426. }
  427. }
  428. // If the closest face is a backface, that means that the ray originates from the inside of the geometry
  429. // NOTE: there may be cases where both are equal, as in, no collision to either. This is prevented in the most likely case
  430. // (ray doesnt hit either) by this conditional
  431. if (currentFrontFace != M_INFINITY || currentBackFace != M_INFINITY)
  432. return currentBackFace < currentFrontFace;
  433. // It is still possible for two triangles to be equally distant from the triangle, however, this is extremely unlikely.
  434. // As such, it is safe to assume they are not
  435. return false;
  436. }
  437. Ray Ray::Transformed(const Matrix3x4& transform) const
  438. {
  439. Ray ret;
  440. ret.origin_ = transform * origin_;
  441. ret.direction_ = transform * Vector4(direction_, 0.0f);
  442. return ret;
  443. }
  444. }