PolygonPrismShape.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include "PolygonPrismShape.h"
  9. #include <AzCore/Math/Aabb.h>
  10. #include <AzCore/Math/IntersectSegment.h>
  11. #include <AzCore/Math/Transform.h>
  12. #include <AzCore/Serialization/EditContext.h>
  13. #include <AzCore/std/smart_ptr/make_shared.h>
  14. #include <AzFramework/Entity/EntityDebugDisplayBus.h>
  15. #include <MathConversion.h>
  16. #include <Shape/ShapeGeometryUtil.h>
  17. #include <Shape/ShapeDisplay.h>
  18. #include <ISystem.h>
  19. namespace LmbrCentral
  20. {
  21. /// Generates solid polygon prism mesh.
  22. /// Applies non-uniform scale, but does not apply any scale from the transform, which is assumed to be applied separately elsewhere.
  23. static void GenerateSolidPolygonPrismMesh(
  24. const AZStd::vector<AZ::Vector2>& vertices,
  25. const float height,
  26. const AZ::Vector3& nonUniformScale,
  27. AZStd::vector<AZ::Vector3>& meshTriangles)
  28. {
  29. // must have at least one triangle
  30. if (vertices.size() < 3)
  31. {
  32. meshTriangles.clear();
  33. return;
  34. }
  35. // deal with the possibility that the scaled height is negative
  36. const float scaledHeight = height * nonUniformScale.GetZ();
  37. const float top = AZ::GetMax(0.0f, scaledHeight);
  38. const float bottom = AZ::GetMin(0.0f, scaledHeight);
  39. const AZ::Vector3 topVector = AZ::Vector3::CreateAxisZ(top);
  40. const AZ::Vector3 bottomVector = AZ::Vector3::CreateAxisZ(bottom);
  41. // generate triangles for one face of polygon prism
  42. const AZStd::vector<AZ::Vector3> faceTriangles = GenerateTriangles(vertices);
  43. const size_t halfTriangleCount = faceTriangles.size();
  44. const size_t fullTriangleCount = faceTriangles.size() * 2;
  45. const size_t wallTriangleCount = vertices.size() * 2 * 3;
  46. // allocate space for both faces (polygons) and walls
  47. meshTriangles.resize_no_construct(fullTriangleCount + wallTriangleCount);
  48. // copy vertices into triangle list
  49. const typename AZStd::vector<AZ::Vector3>::iterator midFace = meshTriangles.begin() + halfTriangleCount;
  50. AZStd::transform(faceTriangles.cbegin(), faceTriangles.cend(), meshTriangles.begin(),
  51. [&nonUniformScale, &topVector](AZ::Vector3 vertex) { return nonUniformScale * vertex + topVector; });
  52. // due to winding order, reverse copy triangles for other face/polygon
  53. AZStd::transform(faceTriangles.crbegin(), faceTriangles.crend(), midFace,
  54. [&nonUniformScale, &bottomVector](AZ::Vector3 vertex) { return nonUniformScale * vertex + bottomVector; });
  55. // end of face/polygon vertices is start of side/wall vertices
  56. const typename AZStd::vector<AZ::Vector3>::iterator endFaceIt = meshTriangles.begin() + fullTriangleCount;
  57. typename AZStd::vector<AZ::Vector3>::iterator sideIt = endFaceIt;
  58. // build quad triangles from vertices util
  59. const auto quadTriangles =
  60. [](const AZ::Vector3& a, const AZ::Vector3& b, const AZ::Vector3& c, const AZ::Vector3& d, typename AZStd::vector<AZ::Vector3>::iterator& tri)
  61. {
  62. *tri = a; ++tri;
  63. *tri = b; ++tri;
  64. *tri = c; ++tri;
  65. *tri = c; ++tri;
  66. *tri = b; ++tri;
  67. *tri = d; ++tri;
  68. };
  69. // generate walls
  70. const bool clockwise = ClockwiseOrder(vertices);
  71. const size_t vertexCount = vertices.size();
  72. for (size_t i = 0; i < vertexCount; ++i)
  73. {
  74. // local vertex positions
  75. const AZ::Vector3 currentPoint = nonUniformScale * AZ::Vector3(vertices[i]);
  76. const AZ::Vector3 nextPoint = nonUniformScale * AZ::Vector3(vertices[(i + 1) % vertexCount]);
  77. const AZ::Vector3 p1 = currentPoint + bottomVector;
  78. const AZ::Vector3 p2 = nextPoint + bottomVector;
  79. const AZ::Vector3 p3 = currentPoint + topVector;
  80. const AZ::Vector3 p4 = nextPoint + topVector;
  81. // generate triangles for wall quad
  82. if (clockwise)
  83. {
  84. quadTriangles(p1, p3, p2, p4, sideIt);
  85. }
  86. else
  87. {
  88. quadTriangles(p1, p2, p3, p4, sideIt);
  89. }
  90. }
  91. }
  92. static void GenerateWirePolygonPrismMesh(
  93. const AZStd::vector<AZ::Vector2>& vertices,
  94. const float height,
  95. const AZ::Vector3& nonUniformScale,
  96. AZStd::vector<AZ::Vector3>& lines)
  97. {
  98. const size_t vertexCount = vertices.size();
  99. const size_t verticalLineCount = vertexCount;
  100. const size_t horizontalLineCount = vertexCount > 2
  101. ? vertexCount
  102. : vertexCount > 1
  103. ? 1
  104. : 0;
  105. lines.resize((verticalLineCount + (horizontalLineCount * 2)) * 2);
  106. size_t lineVertIndex = 0;
  107. for (size_t i = 0; i < verticalLineCount; ++i)
  108. {
  109. // vertical line
  110. lines[lineVertIndex++] = nonUniformScale * AZ::Vector3(vertices[i]);
  111. lines[lineVertIndex++] = nonUniformScale * AZ::Vector3(vertices[i], height);
  112. }
  113. for (size_t i = 0; i < horizontalLineCount; ++i)
  114. {
  115. // bottom line
  116. lines[lineVertIndex++] = nonUniformScale * AZ::Vector3(vertices[i]);
  117. lines[lineVertIndex++] = nonUniformScale * AZ::Vector3(vertices[(i + 1) % vertexCount]);
  118. }
  119. for (size_t i = 0; i < horizontalLineCount; ++i)
  120. {
  121. // top line
  122. lines[lineVertIndex++] = nonUniformScale * AZ::Vector3(vertices[i], height);
  123. lines[lineVertIndex++] = nonUniformScale * AZ::Vector3(vertices[(i + 1) % vertexCount], height);
  124. }
  125. }
  126. void GeneratePolygonPrismMesh(
  127. const AZStd::vector<AZ::Vector2>& vertices, const float height, const AZ::Vector3& nonUniformScale,
  128. PolygonPrismMesh& polygonPrismMeshOut)
  129. {
  130. GenerateSolidPolygonPrismMesh(
  131. vertices, height, nonUniformScale, polygonPrismMeshOut.m_triangles);
  132. GenerateWirePolygonPrismMesh(
  133. vertices, height, nonUniformScale, polygonPrismMeshOut.m_lines);
  134. }
  135. PolygonPrismShape::PolygonPrismShape()
  136. : m_polygonPrism(AZStd::make_shared<AZ::PolygonPrism>())
  137. , m_nonUniformScaleChangedHandler([this](const AZ::Vector3& scale) {this->OnNonUniformScaleChanged(scale); })
  138. {
  139. }
  140. PolygonPrismShape::PolygonPrismShape(const PolygonPrismShape& other)
  141. : m_polygonPrism(other.m_polygonPrism)
  142. , m_intersectionDataCache(other.m_intersectionDataCache)
  143. , m_currentTransform(other.m_currentTransform)
  144. , m_entityId(other.m_entityId)
  145. {
  146. }
  147. PolygonPrismShape& PolygonPrismShape::operator=(const PolygonPrismShape& other)
  148. {
  149. m_polygonPrism = other.m_polygonPrism;
  150. m_intersectionDataCache = other.m_intersectionDataCache;
  151. m_currentTransform = other.m_currentTransform;
  152. m_entityId = other.m_entityId;
  153. return *this;
  154. }
  155. void PolygonPrismShape::Reflect(AZ::ReflectContext* context)
  156. {
  157. PolygonPrismShapeConfig::Reflect(context);
  158. if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  159. {
  160. serializeContext->Class<PolygonPrismShape>()
  161. ->Version(1)
  162. ->Field("PolygonPrism", &PolygonPrismShape::m_polygonPrism)
  163. ;
  164. if (AZ::EditContext* editContext = serializeContext->GetEditContext())
  165. {
  166. editContext->Class<PolygonPrismShape>("Configuration", "Polygon Prism configuration parameters")
  167. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  168. ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
  169. ->Attribute(AZ::Edit::Attributes::AutoExpand, true)
  170. ->DataElement(AZ::Edit::UIHandlers::Default, &PolygonPrismShape::m_polygonPrism,
  171. "Polygon Prism", "Data representing the shape in the entity's local coordinate space.")
  172. ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
  173. ->Attribute(AZ::Edit::Attributes::ContainerCanBeModified, false)
  174. ->Attribute(AZ::Edit::Attributes::AutoExpand, true)
  175. ;
  176. }
  177. }
  178. }
  179. void PolygonPrismShape::Activate(AZ::EntityId entityId)
  180. {
  181. // Clear out callbacks at the start of activation. Otherwise, the underlying polygonPrism will attempt to trigger callbacks
  182. // before this shape is fully activated, which we want to avoid.
  183. m_polygonPrism->SetCallbacks({}, {}, {}, {});
  184. m_entityId = entityId;
  185. m_currentTransform = AZ::Transform::CreateIdentity();
  186. AZ::TransformBus::EventResult(m_currentTransform, entityId, &AZ::TransformBus::Events::GetWorldTM);
  187. AZ::TransformNotificationBus::Handler::BusConnect(entityId);
  188. m_currentNonUniformScale = AZ::Vector3::CreateOne();
  189. AZ::NonUniformScaleRequestBus::EventResult(m_currentNonUniformScale, m_entityId, &AZ::NonUniformScaleRequests::GetScale);
  190. // This will trigger an OnChangeNonUniformScale callback if one is set, which is why we clear out the callbacks at the
  191. // start of activation. Those callbacks might try to query back to this shape, which isn't fully initialized or activated yet
  192. // (see for example EditorPolygonPrismShapeComponent), so they would end up retrieving invalid data.
  193. m_polygonPrism->SetNonUniformScale(m_currentNonUniformScale);
  194. m_intersectionDataCache.InvalidateCache(InvalidateShapeCacheReason::ShapeChange);
  195. AZ::NonUniformScaleRequestBus::Event(m_entityId, &AZ::NonUniformScaleRequests::RegisterScaleChangedEvent,
  196. m_nonUniformScaleChangedHandler);
  197. // Now that we've finished initializing the other data, set up the default change callbacks.
  198. const auto polygonPrismChanged = [this]()
  199. {
  200. ShapeChanged();
  201. };
  202. m_polygonPrism->SetCallbacks(
  203. polygonPrismChanged,
  204. polygonPrismChanged,
  205. polygonPrismChanged,
  206. polygonPrismChanged);
  207. // Connect to these last so that the shape doesn't start responding to requests until after everything is initialized
  208. PolygonPrismShapeComponentRequestBus::Handler::BusConnect(entityId);
  209. AZ::VariableVerticesRequestBus<AZ::Vector2>::Handler::BusConnect(entityId);
  210. AZ::FixedVerticesRequestBus<AZ::Vector2>::Handler::BusConnect(entityId);
  211. ShapeComponentRequestsBus::Handler::BusConnect(entityId);
  212. }
  213. void PolygonPrismShape::Deactivate()
  214. {
  215. ShapeComponentRequestsBus::Handler::BusDisconnect();
  216. AZ::VariableVerticesRequestBus<AZ::Vector2>::Handler::BusDisconnect();
  217. AZ::FixedVerticesRequestBus<AZ::Vector2>::Handler::BusDisconnect();
  218. PolygonPrismShapeComponentRequestBus::Handler::BusDisconnect();
  219. m_nonUniformScaleChangedHandler.Disconnect();
  220. AZ::TransformNotificationBus::Handler::BusDisconnect();
  221. // Clear out callbacks to ensure that they don't get called while the component is deactivated.
  222. m_polygonPrism->SetCallbacks({}, {}, {}, {});
  223. }
  224. void PolygonPrismShape::InvalidateCache(InvalidateShapeCacheReason reason)
  225. {
  226. PolygonPrismUniqueLockGuard lock(m_mutex, m_uniqueLockThreadId);
  227. m_intersectionDataCache.InvalidateCache(reason);
  228. }
  229. void PolygonPrismShape::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world)
  230. {
  231. {
  232. PolygonPrismUniqueLockGuard lock(m_mutex, m_uniqueLockThreadId);
  233. m_currentTransform = world;
  234. m_intersectionDataCache.InvalidateCache(InvalidateShapeCacheReason::TransformChange);
  235. }
  236. ShapeComponentNotificationsBus::Event(
  237. m_entityId, &ShapeComponentNotificationsBus::Events::OnShapeChanged,
  238. ShapeComponentNotifications::ShapeChangeReasons::TransformChanged);
  239. }
  240. void PolygonPrismShape::OnNonUniformScaleChanged(const AZ::Vector3& scale)
  241. {
  242. {
  243. PolygonPrismUniqueLockGuard lock(m_mutex, m_uniqueLockThreadId);
  244. m_currentNonUniformScale = scale;
  245. m_polygonPrism->SetNonUniformScale(scale);
  246. m_intersectionDataCache.InvalidateCache(InvalidateShapeCacheReason::ShapeChange);
  247. }
  248. ShapeComponentNotificationsBus::Event(
  249. m_entityId, &ShapeComponentNotificationsBus::Events::OnShapeChanged,
  250. ShapeComponentNotifications::ShapeChangeReasons::ShapeChanged);
  251. }
  252. void PolygonPrismShape::ShapeChanged()
  253. {
  254. m_intersectionDataCache.InvalidateCache(InvalidateShapeCacheReason::ShapeChange);
  255. ShapeComponentNotificationsBus::Event(
  256. m_entityId, &ShapeComponentNotificationsBus::Events::OnShapeChanged,
  257. ShapeComponentNotifications::ShapeChangeReasons::ShapeChanged);
  258. }
  259. AZ::PolygonPrismPtr PolygonPrismShape::GetPolygonPrism()
  260. {
  261. PolygonPrismSharedLockGuard lock(m_mutex, m_uniqueLockThreadId);
  262. return m_polygonPrism;
  263. }
  264. bool PolygonPrismShape::GetVertex(const size_t index, AZ::Vector2& vertex) const
  265. {
  266. PolygonPrismSharedLockGuard lock(m_mutex, m_uniqueLockThreadId);
  267. return m_polygonPrism->m_vertexContainer.GetVertex(index, vertex);
  268. }
  269. void PolygonPrismShape::AddVertex(const AZ::Vector2& vertex)
  270. {
  271. PolygonPrismUniqueLockGuard lock(m_mutex, m_uniqueLockThreadId);
  272. m_polygonPrism->m_vertexContainer.AddVertex(vertex);
  273. }
  274. bool PolygonPrismShape::UpdateVertex(const size_t index, const AZ::Vector2& vertex)
  275. {
  276. PolygonPrismUniqueLockGuard lock(m_mutex, m_uniqueLockThreadId);
  277. return m_polygonPrism->m_vertexContainer.UpdateVertex(index, vertex);
  278. }
  279. bool PolygonPrismShape::InsertVertex(const size_t index, const AZ::Vector2& vertex)
  280. {
  281. PolygonPrismUniqueLockGuard lock(m_mutex, m_uniqueLockThreadId);
  282. return m_polygonPrism->m_vertexContainer.InsertVertex(index, vertex);
  283. }
  284. bool PolygonPrismShape::RemoveVertex(const size_t index)
  285. {
  286. PolygonPrismUniqueLockGuard lock(m_mutex, m_uniqueLockThreadId);
  287. return m_polygonPrism->m_vertexContainer.RemoveVertex(index);
  288. }
  289. void PolygonPrismShape::SetVertices(const AZStd::vector<AZ::Vector2>& vertices)
  290. {
  291. PolygonPrismUniqueLockGuard lock(m_mutex, m_uniqueLockThreadId);
  292. m_polygonPrism->m_vertexContainer.SetVertices(vertices);
  293. }
  294. void PolygonPrismShape::ClearVertices()
  295. {
  296. PolygonPrismUniqueLockGuard lock(m_mutex, m_uniqueLockThreadId);
  297. m_polygonPrism->m_vertexContainer.Clear();
  298. }
  299. size_t PolygonPrismShape::Size() const
  300. {
  301. PolygonPrismSharedLockGuard lock(m_mutex, m_uniqueLockThreadId);
  302. return m_polygonPrism->m_vertexContainer.Size();
  303. }
  304. bool PolygonPrismShape::Empty() const
  305. {
  306. PolygonPrismSharedLockGuard lock(m_mutex, m_uniqueLockThreadId);
  307. return m_polygonPrism->m_vertexContainer.Empty();
  308. }
  309. void PolygonPrismShape::SetHeight(const float height)
  310. {
  311. PolygonPrismUniqueLockGuard lock(m_mutex, m_uniqueLockThreadId);
  312. m_polygonPrism->SetHeight(height);
  313. m_intersectionDataCache.InvalidateCache(InvalidateShapeCacheReason::ShapeChange);
  314. }
  315. AZ::Aabb PolygonPrismShape::GetEncompassingAabb() const
  316. {
  317. PolygonPrismSharedLockGuard lock(m_mutex, m_uniqueLockThreadId);
  318. m_intersectionDataCache.UpdateIntersectionParams(
  319. m_currentTransform, *m_polygonPrism, lock.GetMutexForIntersectionDataCache(), m_currentNonUniformScale);
  320. return m_intersectionDataCache.m_aabb;
  321. }
  322. void PolygonPrismShape::GetTransformAndLocalBounds(AZ::Transform& transform, AZ::Aabb& bounds) const
  323. {
  324. PolygonPrismSharedLockGuard lock(m_mutex, m_uniqueLockThreadId);
  325. bounds = PolygonPrismUtil::CalculateAabb(*m_polygonPrism, AZ::Transform::Identity());
  326. transform = m_currentTransform;
  327. }
  328. /// Return if the point is inside of the polygon prism volume or not.
  329. /// Use 'Crossings Test' to determine if point lies in or out of the polygon.
  330. /// @param point Position in world space to test against.
  331. bool PolygonPrismShape::IsPointInside(const AZ::Vector3& point) const
  332. {
  333. PolygonPrismSharedLockGuard lock(m_mutex, m_uniqueLockThreadId);
  334. m_intersectionDataCache.UpdateIntersectionParams(
  335. m_currentTransform, *m_polygonPrism, lock.GetMutexForIntersectionDataCache(), m_currentNonUniformScale);
  336. // initial early aabb rejection test
  337. // note: will implicitly do height test too
  338. if (!GetEncompassingAabb().Contains(point))
  339. {
  340. return false;
  341. }
  342. return PolygonPrismUtil::IsPointInside(*m_polygonPrism, point, m_currentTransform);
  343. }
  344. float PolygonPrismShape::DistanceSquaredFromPoint(const AZ::Vector3& point) const
  345. {
  346. PolygonPrismSharedLockGuard lock(m_mutex, m_uniqueLockThreadId);
  347. m_intersectionDataCache.UpdateIntersectionParams(
  348. m_currentTransform, *m_polygonPrism, lock.GetMutexForIntersectionDataCache(), m_currentNonUniformScale);
  349. return PolygonPrismUtil::DistanceSquaredFromPoint(*m_polygonPrism, point, m_currentTransform);
  350. }
  351. bool PolygonPrismShape::IntersectRay(const AZ::Vector3& src, const AZ::Vector3& dir, float& distance) const
  352. {
  353. PolygonPrismSharedLockGuard lock(m_mutex, m_uniqueLockThreadId);
  354. m_intersectionDataCache.UpdateIntersectionParams(
  355. m_currentTransform, *m_polygonPrism, lock.GetMutexForIntersectionDataCache(), m_currentNonUniformScale);
  356. return PolygonPrismUtil::IntersectRay(m_intersectionDataCache.m_triangles, m_currentTransform, src, dir, distance);
  357. }
  358. void PolygonPrismShape::PolygonPrismIntersectionDataCache::UpdateIntersectionParamsImpl(
  359. const AZ::Transform& currentTransform, const AZ::PolygonPrism& polygonPrism,
  360. const AZ::Vector3& currentNonUniformScale)
  361. {
  362. m_aabb = PolygonPrismUtil::CalculateAabb(polygonPrism, currentTransform);
  363. GenerateSolidPolygonPrismMesh(
  364. polygonPrism.m_vertexContainer.GetVertices(),
  365. polygonPrism.GetHeight(), currentNonUniformScale, m_triangles);
  366. }
  367. void DrawPolygonPrismShape(
  368. const ShapeDrawParams& shapeDrawParams, const PolygonPrismMesh& polygonPrismMesh,
  369. AzFramework::DebugDisplayRequests& debugDisplay)
  370. {
  371. if (shapeDrawParams.m_filled)
  372. {
  373. if (!polygonPrismMesh.m_triangles.empty())
  374. {
  375. auto rendererState = debugDisplay.GetState();
  376. // ensure render state is configured correctly - we want to read the depth
  377. // buffer but do not want to write to it (ensure objects inside the volume are not obscured)
  378. debugDisplay.DepthWriteOff();
  379. debugDisplay.DepthTestOn();
  380. debugDisplay.DrawTriangles(polygonPrismMesh.m_triangles, shapeDrawParams.m_shapeColor);
  381. // restore the previous renderer state
  382. debugDisplay.SetState(rendererState);
  383. }
  384. }
  385. if (!polygonPrismMesh.m_lines.empty())
  386. {
  387. debugDisplay.DrawLines(polygonPrismMesh.m_lines, shapeDrawParams.m_wireColor);
  388. }
  389. }
  390. namespace PolygonPrismUtil
  391. {
  392. AZ::Aabb CalculateAabb(const AZ::PolygonPrism& polygonPrism, const AZ::Transform& worldFromLocal)
  393. {
  394. const AZ::VertexContainer<AZ::Vector2>& vertexContainer = polygonPrism.m_vertexContainer;
  395. const float height = polygonPrism.GetHeight();
  396. const AZ::Vector3& nonUniformScale = polygonPrism.GetNonUniformScale();
  397. AZ::Transform worldFromLocalUniformScale = worldFromLocal;
  398. worldFromLocalUniformScale.SetUniformScale(worldFromLocalUniformScale.GetUniformScale());
  399. AZ::Aabb aabb = AZ::Aabb::CreateNull();
  400. // check base of prism
  401. for (const AZ::Vector2& vertex : vertexContainer.GetVertices())
  402. {
  403. aabb.AddPoint(worldFromLocalUniformScale.TransformPoint(nonUniformScale * AZ::Vector3(vertex.GetX(), vertex.GetY(), 0.0f)));
  404. }
  405. // check top of prism
  406. // set aabb to be height of prism - ensure entire polygon prism shape is enclosed in aabb
  407. for (const AZ::Vector2& vertex : vertexContainer.GetVertices())
  408. {
  409. aabb.AddPoint(worldFromLocalUniformScale.TransformPoint(nonUniformScale * AZ::Vector3(vertex.GetX(), vertex.GetY(), height)));
  410. }
  411. return aabb;
  412. }
  413. bool IsPointInside(const AZ::PolygonPrism& polygonPrism, const AZ::Vector3& point, const AZ::Transform& worldFromLocal)
  414. {
  415. using namespace PolygonPrismUtil;
  416. const float epsilon = 0.0001f;
  417. const float projectRayLength = 1000.0f;
  418. const AZStd::vector<AZ::Vector2>& vertices = polygonPrism.m_vertexContainer.GetVertices();
  419. const size_t vertexCount = vertices.size();
  420. AZ::Transform worldFromLocalWithUniformScale = worldFromLocal;
  421. worldFromLocalWithUniformScale.SetUniformScale(worldFromLocalWithUniformScale.GetUniformScale());
  422. // transform point to local space
  423. // it's fine to invert the transform including scale here, because it won't affect whether the point is inside the prism
  424. const AZ::Vector3 localPoint =
  425. worldFromLocalWithUniformScale.GetInverse().TransformPoint(point) / polygonPrism.GetNonUniformScale();
  426. // ensure the point is not above or below the prism (in its local space)
  427. if (localPoint.GetZ() < 0.0f || localPoint.GetZ() > polygonPrism.GetHeight())
  428. {
  429. return false;
  430. }
  431. const AZ::Vector3 localPointFlattened = AZ::Vector3(localPoint.GetX(), localPoint.GetY(), 0.0f);
  432. const AZ::Vector3 localEndFlattened = localPointFlattened + AZ::Vector3::CreateAxisX() * projectRayLength;
  433. size_t intersections = 0;
  434. // use 'crossing test' algorithm to decide if the point lies within the volume or not
  435. // (odd number of intersections - inside, even number of intersections - outside)
  436. for (size_t i = 0; i < vertexCount; ++i)
  437. {
  438. const AZ::Vector3 segmentStart = AZ::Vector3(vertices[i]);
  439. const AZ::Vector3 segmentEnd = AZ::Vector3(vertices[(i + 1) % vertexCount]);
  440. AZ::Vector3 closestPosRay, closestPosSegment;
  441. float rayProportion, segmentProportion;
  442. AZ::Intersect::ClosestSegmentSegment(localPointFlattened, localEndFlattened, segmentStart, segmentEnd, rayProportion, segmentProportion, closestPosRay, closestPosSegment);
  443. const float delta = (closestPosRay - closestPosSegment).GetLengthSq();
  444. // have we crossed/touched a line on the polygon
  445. if (delta < epsilon)
  446. {
  447. const AZ::Vector3 highestVertex = segmentStart.GetY() > segmentEnd.GetY() ? segmentStart : segmentEnd;
  448. const float threshold = (highestVertex - point).Dot(AZ::Vector3::CreateAxisY());
  449. if (AZ::IsClose(segmentProportion, 0.0f, AZ::Constants::FloatEpsilon))
  450. {
  451. // if at beginning of segment, only count intersection if segment is going up (y-axis)
  452. // (prevent counting segments twice when intersecting at vertex)
  453. if (threshold > 0.0f)
  454. {
  455. intersections++;
  456. }
  457. }
  458. else
  459. {
  460. intersections++;
  461. }
  462. }
  463. }
  464. // odd inside, even outside - bitwise AND to convert to bool
  465. return intersections & 1;
  466. }
  467. float DistanceSquaredFromPoint(const AZ::PolygonPrism& polygonPrism, const AZ::Vector3& point, const AZ::Transform& worldFromLocal)
  468. {
  469. const float height = polygonPrism.GetHeight();
  470. const AZ::Vector3& nonUniformScale = polygonPrism.GetNonUniformScale();
  471. // we want to invert the rotation and translation from the transform to get the point into the local space of the prism
  472. // but inverting any scale in the transform would mess up the distance, so extract that first and apply scale separately to the
  473. // prism
  474. AZ::Transform worldFromLocalNoScale = worldFromLocal;
  475. const float transformScale = worldFromLocalNoScale.ExtractUniformScale();
  476. const AZ::Vector3 combinedScale = transformScale * nonUniformScale;
  477. const float scaledHeight = height * combinedScale.GetZ();
  478. // find the bottom and top which may be reversed from the usual order if the height or Z component of the scale is negative
  479. const float bottom = AZ::GetMin(scaledHeight, 0.0f);
  480. const float top = AZ::GetMax(scaledHeight, 0.0f);
  481. // translate and rotate (but don't scale) the point into the local space of the prism
  482. const AZ::Vector3 localPoint = worldFromLocalNoScale.GetInverse().TransformPoint(point);
  483. const AZ::Vector3 localPointFlattened = AZ::Vector3(localPoint.GetX(), localPoint.GetY(), 0.5f * (bottom + top));
  484. const AZ::Vector3 worldPointFlattened = worldFromLocalNoScale.TransformPoint(localPointFlattened);
  485. // first test if the point is contained within the polygon (flatten)
  486. if (IsPointInside(polygonPrism, worldPointFlattened, worldFromLocal))
  487. {
  488. if (localPoint.GetZ() < bottom)
  489. {
  490. // if it's inside the 2d polygon but below the volume
  491. const float distance = bottom - localPoint.GetZ();
  492. return distance * distance;
  493. }
  494. if (localPoint.GetZ() > top)
  495. {
  496. // if it's inside the 2d polygon but above the volume
  497. const float distance = localPoint.GetZ() - top;
  498. return distance * distance;
  499. }
  500. // if it's fully contained, return 0
  501. return 0.0f;
  502. }
  503. const AZStd::vector<AZ::Vector2>& vertices = polygonPrism.m_vertexContainer.GetVertices();
  504. const size_t vertexCount = vertices.size();
  505. // find closest segment
  506. AZ::Vector3 closestPos;
  507. float minDistanceSq = std::numeric_limits<float>::max();
  508. for (size_t i = 0; i < vertexCount; ++i)
  509. {
  510. const AZ::Vector3 segmentStart = combinedScale * AZ::Vector3(vertices[i]);
  511. const AZ::Vector3 segmentEnd = combinedScale * AZ::Vector3(vertices[(i + 1) % vertexCount]);
  512. AZ::Vector3 position;
  513. float proportion;
  514. AZ::Intersect::ClosestPointSegment(localPointFlattened, segmentStart, segmentEnd, proportion, position);
  515. const float distanceSq = (position - localPointFlattened).GetLengthSq();
  516. if (distanceSq < minDistanceSq)
  517. {
  518. minDistanceSq = distanceSq;
  519. closestPos = position;
  520. }
  521. }
  522. // constrain closest pos to [bottom, top] of volume
  523. closestPos += AZ::Vector3(0.0f, 0.0f, AZ::GetClamp<float>(localPoint.GetZ(), bottom, top));
  524. // return distanceSq from closest pos on prism
  525. return (closestPos - localPoint).GetLengthSq();
  526. }
  527. bool IntersectRay(
  528. AZStd::vector<AZ::Vector3> triangles, const AZ::Transform& worldFromLocal,
  529. const AZ::Vector3& src, const AZ::Vector3& dir, float& distance)
  530. {
  531. // must have at least one triangle
  532. if (triangles.size() < 3)
  533. {
  534. distance = std::numeric_limits<float>::max();
  535. return false;
  536. }
  537. // transform ray into local space
  538. AZ::Transform worldFromLocalNormalized = worldFromLocal;
  539. const float entityScale = worldFromLocalNormalized.ExtractUniformScale();
  540. const AZ::Transform localFromWorldNormalized = worldFromLocalNormalized.GetInverse();
  541. const float rayLength = 1000.0f;
  542. const AZ::Vector3 localSrc = localFromWorldNormalized.TransformPoint(src);
  543. const AZ::Vector3 localDir = localFromWorldNormalized.TransformVector(dir);
  544. const AZ::Vector3 localEnd = localSrc + localDir * rayLength;
  545. AZ::Intersect::SegmentTriangleHitTester hitTester(localSrc, localEnd);
  546. // iterate over all triangles in polygon prism and
  547. // test ray against each in turn
  548. bool intersection = false;
  549. distance = std::numeric_limits<float>::max();
  550. for (size_t i = 0; i < triangles.size(); i += 3)
  551. {
  552. float t;
  553. AZ::Vector3 normal;
  554. if (hitTester.IntersectSegmentTriangle(
  555. triangles[i] * entityScale,
  556. triangles[i + 1] * entityScale,
  557. triangles[i + 2] * entityScale, normal, t))
  558. {
  559. intersection |= true;
  560. const float dist = t * rayLength;
  561. if (dist < distance)
  562. {
  563. distance = dist;
  564. }
  565. }
  566. }
  567. return intersection;
  568. }
  569. }
  570. } // namespace LmbrCentral