DebugRenderer.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #ifndef JPH_DEBUG_RENDERER
  6. #error This file should only be included when JPH_DEBUG_RENDERER is defined
  7. #endif // !JPH_DEBUG_RENDERER
  8. #ifndef JPH_DEBUG_RENDERER_EXPORT
  9. // By default export the debug renderer
  10. #define JPH_DEBUG_RENDERER_EXPORT JPH_EXPORT
  11. #endif // !JPH_DEBUG_RENDERER_EXPORT
  12. #include <Jolt/Core/Color.h>
  13. #include <Jolt/Core/Reference.h>
  14. #include <Jolt/Core/HashCombine.h>
  15. #include <Jolt/Core/UnorderedMap.h>
  16. #include <Jolt/Math/Float2.h>
  17. #include <Jolt/Geometry/IndexedTriangle.h>
  18. #include <Jolt/Geometry/AABox.h>
  19. JPH_NAMESPACE_BEGIN
  20. class OrientedBox;
  21. /// Simple triangle renderer for debugging purposes.
  22. class JPH_DEBUG_RENDERER_EXPORT DebugRenderer
  23. {
  24. public:
  25. JPH_OVERRIDE_NEW_DELETE
  26. /// Constructor
  27. DebugRenderer();
  28. virtual ~DebugRenderer();
  29. /// Draw line
  30. virtual void DrawLine(RVec3Arg inFrom, RVec3Arg inTo, ColorArg inColor) = 0;
  31. /// Draw wireframe box
  32. void DrawWireBox(const AABox &inBox, ColorArg inColor);
  33. void DrawWireBox(const OrientedBox &inBox, ColorArg inColor);
  34. void DrawWireBox(RMat44Arg inMatrix, const AABox &inBox, ColorArg inColor);
  35. /// Draw a marker on a position
  36. void DrawMarker(RVec3Arg inPosition, ColorArg inColor, float inSize);
  37. /// Draw an arrow
  38. void DrawArrow(RVec3Arg inFrom, RVec3Arg inTo, ColorArg inColor, float inSize);
  39. /// Draw coordinate system (3 arrows, x = red, y = green, z = blue)
  40. void DrawCoordinateSystem(RMat44Arg inTransform, float inSize = 1.0f);
  41. /// Draw a plane through inPoint with normal inNormal
  42. void DrawPlane(RVec3Arg inPoint, Vec3Arg inNormal, ColorArg inColor, float inSize);
  43. /// Draw wireframe triangle
  44. void DrawWireTriangle(RVec3Arg inV1, RVec3Arg inV2, RVec3Arg inV3, ColorArg inColor);
  45. /// Draw a wireframe polygon
  46. template <class VERTEX_ARRAY>
  47. void DrawWirePolygon(RMat44Arg inTransform, const VERTEX_ARRAY &inVertices, ColorArg inColor, float inArrowSize = 0.0f) { for (typename VERTEX_ARRAY::size_type i = 0; i < inVertices.size(); ++i) DrawArrow(inTransform * inVertices[i], inTransform * inVertices[(i + 1) % inVertices.size()], inColor, inArrowSize); }
  48. /// Draw wireframe sphere
  49. void DrawWireSphere(RVec3Arg inCenter, float inRadius, ColorArg inColor, int inLevel = 3);
  50. void DrawWireUnitSphere(RMat44Arg inMatrix, ColorArg inColor, int inLevel = 3);
  51. /// Enum that determines if a shadow should be cast or not
  52. enum class ECastShadow
  53. {
  54. On, // This shape should cast a shadow
  55. Off // This shape should not cast a shadow
  56. };
  57. /// Determines how triangles are drawn
  58. enum class EDrawMode
  59. {
  60. Solid, ///< Draw as a solid shape
  61. Wireframe, ///< Draw as wireframe
  62. };
  63. /// Draw a single back face culled triangle
  64. virtual void DrawTriangle(RVec3Arg inV1, RVec3Arg inV2, RVec3Arg inV3, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::Off) = 0;
  65. /// Draw a box
  66. void DrawBox(const AABox &inBox, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  67. void DrawBox(RMat44Arg inMatrix, const AABox &inBox, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  68. /// Draw a sphere
  69. void DrawSphere(RVec3Arg inCenter, float inRadius, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  70. void DrawUnitSphere(RMat44Arg inMatrix, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  71. /// Draw a capsule with one half sphere at (0, -inHalfHeightOfCylinder, 0) and the other half sphere at (0, inHalfHeightOfCylinder, 0) and radius inRadius.
  72. /// The capsule will be transformed by inMatrix.
  73. void DrawCapsule(RMat44Arg inMatrix, float inHalfHeightOfCylinder, float inRadius, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  74. /// Draw a cylinder with top (0, inHalfHeight, 0) and bottom (0, -inHalfHeight, 0) and radius inRadius.
  75. /// The cylinder will be transformed by inMatrix
  76. void DrawCylinder(RMat44Arg inMatrix, float inHalfHeight, float inRadius, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  77. /// Draw a bottomless cone.
  78. /// @param inTop Top of cone, center of base is at inTop + inAxis.
  79. /// @param inAxis Height and direction of cone
  80. /// @param inPerpendicular Perpendicular vector to inAxis.
  81. /// @param inHalfAngle Specifies the cone angle in radians (angle measured between inAxis and cone surface).
  82. /// @param inLength The length of the cone.
  83. /// @param inColor Color to use for drawing the cone.
  84. /// @param inCastShadow determins if this geometry should cast a shadow or not.
  85. /// @param inDrawMode determines if we draw the geometry solid or in wireframe.
  86. void DrawOpenCone(RVec3Arg inTop, Vec3Arg inAxis, Vec3Arg inPerpendicular, float inHalfAngle, float inLength, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  87. /// Draws cone rotation limits as used by the SwingTwistConstraintPart.
  88. /// @param inMatrix Matrix that transforms from constraint space to world space
  89. /// @param inSwingYHalfAngle See SwingTwistConstraintPart
  90. /// @param inSwingZHalfAngle See SwingTwistConstraintPart
  91. /// @param inEdgeLength Size of the edge of the cone shape
  92. /// @param inColor Color to use for drawing the cone.
  93. /// @param inCastShadow determins if this geometry should cast a shadow or not.
  94. /// @param inDrawMode determines if we draw the geometry solid or in wireframe.
  95. void DrawSwingConeLimits(RMat44Arg inMatrix, float inSwingYHalfAngle, float inSwingZHalfAngle, float inEdgeLength, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  96. /// Draws rotation limits as used by the SwingTwistConstraintPart.
  97. /// @param inMatrix Matrix that transforms from constraint space to world space
  98. /// @param inMinSwingYAngle See SwingTwistConstraintPart
  99. /// @param inMaxSwingYAngle See SwingTwistConstraintPart
  100. /// @param inMinSwingZAngle See SwingTwistConstraintPart
  101. /// @param inMaxSwingZAngle See SwingTwistConstraintPart
  102. /// @param inEdgeLength Size of the edge of the cone shape
  103. /// @param inColor Color to use for drawing the cone.
  104. /// @param inCastShadow determins if this geometry should cast a shadow or not.
  105. /// @param inDrawMode determines if we draw the geometry solid or in wireframe.
  106. void DrawSwingPyramidLimits(RMat44Arg inMatrix, float inMinSwingYAngle, float inMaxSwingYAngle, float inMinSwingZAngle, float inMaxSwingZAngle, float inEdgeLength, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  107. /// Draw a pie (part of a circle).
  108. /// @param inCenter The center of the circle.
  109. /// @param inRadius Radius of the circle.
  110. /// @param inNormal The plane normal in which the pie resides.
  111. /// @param inAxis The axis that defines an angle of 0 radians.
  112. /// @param inMinAngle The pie will be drawn between [inMinAngle, inMaxAngle] (in radians).
  113. /// @param inMaxAngle The pie will be drawn between [inMinAngle, inMaxAngle] (in radians).
  114. /// @param inColor Color to use for drawing the pie.
  115. /// @param inCastShadow determins if this geometry should cast a shadow or not.
  116. /// @param inDrawMode determines if we draw the geometry solid or in wireframe.
  117. void DrawPie(RVec3Arg inCenter, float inRadius, Vec3Arg inNormal, Vec3Arg inAxis, float inMinAngle, float inMaxAngle, ColorArg inColor, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid);
  118. /// Singleton instance
  119. static DebugRenderer * sInstance;
  120. /// Vertex format used by the triangle renderer
  121. class Vertex
  122. {
  123. public:
  124. Float3 mPosition;
  125. Float3 mNormal;
  126. Float2 mUV;
  127. Color mColor;
  128. };
  129. /// A single triangle
  130. class JPH_DEBUG_RENDERER_EXPORT Triangle
  131. {
  132. public:
  133. Triangle() = default;
  134. Triangle(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3, ColorArg inColor);
  135. Triangle(Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3, ColorArg inColor, Vec3Arg inUVOrigin, Vec3Arg inUVDirection);
  136. Vertex mV[3];
  137. };
  138. /// Handle for a batch of triangles
  139. using Batch = Ref<RefTargetVirtual>;
  140. /// A single level of detail
  141. class LOD
  142. {
  143. public:
  144. Batch mTriangleBatch;
  145. float mDistance;
  146. };
  147. /// A geometry primitive containing triangle batches for various lods
  148. class Geometry : public RefTarget<Geometry>
  149. {
  150. public:
  151. JPH_OVERRIDE_NEW_DELETE
  152. /// Constructor
  153. Geometry(const AABox &inBounds) : mBounds(inBounds) { }
  154. Geometry(const Batch &inBatch, const AABox &inBounds) : mBounds(inBounds) { mLODs.push_back({ inBatch, FLT_MAX }); }
  155. /// All level of details for this mesh
  156. Array<LOD> mLODs;
  157. /// Bounding box that encapsulates all LODs
  158. AABox mBounds;
  159. };
  160. /// Handle for a lodded triangle batch
  161. using GeometryRef = Ref<Geometry>;
  162. /// Calculate bounding box for a batch of triangles
  163. static AABox sCalculateBounds(const Vertex *inVertices, int inVertexCount);
  164. /// Create a batch of triangles that can be drawn efficiently
  165. virtual Batch CreateTriangleBatch(const Triangle *inTriangles, int inTriangleCount) = 0;
  166. virtual Batch CreateTriangleBatch(const Vertex *inVertices, int inVertexCount, const uint32 *inIndices, int inIndexCount) = 0;
  167. Batch CreateTriangleBatch(const Array<Triangle> &inTriangles) { return CreateTriangleBatch(inTriangles.empty()? nullptr : &inTriangles[0], int(inTriangles.size())); }
  168. Batch CreateTriangleBatch(const Array<Vertex> &inVertices, const Array<uint32> &inIndices) { return CreateTriangleBatch(inVertices.empty()? nullptr : &inVertices[0], int(inVertices.size()), inIndices.empty()? nullptr : &inIndices[0], int(inIndices.size())); }
  169. Batch CreateTriangleBatch(const VertexList &inVertices, const IndexedTriangleNoMaterialList &inTriangles);
  170. /// Create a primitive for a convex shape using its support function
  171. using SupportFunction = function<Vec3 (Vec3Arg inDirection)>;
  172. Batch CreateTriangleBatchForConvex(SupportFunction inGetSupport, int inLevel, AABox *outBounds = nullptr);
  173. GeometryRef CreateTriangleGeometryForConvex(SupportFunction inGetSupport);
  174. /// Determines which polygons are culled
  175. enum class ECullMode
  176. {
  177. CullBackFace, ///< Don't draw backfacing polygons
  178. CullFrontFace, ///< Don't draw front facing polygons
  179. Off ///< Don't do culling and draw both sides
  180. };
  181. /// Draw some geometry
  182. /// @param inModelMatrix is the matrix that transforms the geometry to world space.
  183. /// @param inWorldSpaceBounds is the bounding box of the geometry after transforming it into world space.
  184. /// @param inLODScaleSq is the squared scale of the model matrix, it is multiplied with the LOD distances in inGeometry to calculate the real LOD distance (so a number > 1 will force a higher LOD).
  185. /// @param inModelColor is the color with which to multiply the vertex colors in inGeometry.
  186. /// @param inGeometry The geometry to draw.
  187. /// @param inCullMode determines which polygons are culled.
  188. /// @param inCastShadow determines if this geometry should cast a shadow or not.
  189. /// @param inDrawMode determines if we draw the geometry solid or in wireframe.
  190. virtual void DrawGeometry(RMat44Arg inModelMatrix, const AABox &inWorldSpaceBounds, float inLODScaleSq, ColorArg inModelColor, const GeometryRef &inGeometry, ECullMode inCullMode = ECullMode::CullBackFace, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid) = 0;
  191. void DrawGeometry(RMat44Arg inModelMatrix, ColorArg inModelColor, const GeometryRef &inGeometry, ECullMode inCullMode = ECullMode::CullBackFace, ECastShadow inCastShadow = ECastShadow::On, EDrawMode inDrawMode = EDrawMode::Solid) { DrawGeometry(inModelMatrix, inGeometry->mBounds.Transformed(inModelMatrix), max(max(inModelMatrix.GetAxisX().LengthSq(), inModelMatrix.GetAxisY().LengthSq()), inModelMatrix.GetAxisZ().LengthSq()), inModelColor, inGeometry, inCullMode, inCastShadow, inDrawMode); }
  192. /// Draw text
  193. virtual void DrawText3D(RVec3Arg inPosition, const string_view &inString, ColorArg inColor = Color::sWhite, float inHeight = 0.5f) = 0;
  194. protected:
  195. /// Initialize the system, must be called from the constructor of the DebugRenderer implementation
  196. void Initialize();
  197. private:
  198. /// Recursive helper function for DrawWireUnitSphere
  199. void DrawWireUnitSphereRecursive(RMat44Arg inMatrix, ColorArg inColor, Vec3Arg inDir1, Vec3Arg inDir2, Vec3Arg inDir3, int inLevel);
  200. /// Helper functions to create a box
  201. void CreateQuad(Array<uint32> &ioIndices, Array<Vertex> &ioVertices, Vec3Arg inV1, Vec3Arg inV2, Vec3Arg inV3, Vec3Arg inV4);
  202. /// Helper functions to create a vertex and index buffer for a sphere
  203. void Create8thSphereRecursive(Array<uint32> &ioIndices, Array<Vertex> &ioVertices, Vec3Arg inDir1, uint32 &ioIdx1, Vec3Arg inDir2, uint32 &ioIdx2, Vec3Arg inDir3, uint32 &ioIdx3, const Float2 &inUV, SupportFunction inGetSupport, int inLevel);
  204. void Create8thSphere(Array<uint32> &ioIndices, Array<Vertex> &ioVertices, Vec3Arg inDir1, Vec3Arg inDir2, Vec3Arg inDir3, const Float2 &inUV, SupportFunction inGetSupport, int inLevel);
  205. /// Helper function for DrawSwingConeLimits and DrawSwingPyramidLimits
  206. Geometry * CreateSwingLimitGeometry(int inNumSegments, const Vec3 *inVertices);
  207. // Predefined shapes
  208. GeometryRef mBox;
  209. GeometryRef mSphere;
  210. GeometryRef mCapsuleTop;
  211. GeometryRef mCapsuleMid;
  212. GeometryRef mCapsuleBottom;
  213. GeometryRef mOpenCone;
  214. GeometryRef mCylinder;
  215. struct SwingConeLimits
  216. {
  217. bool operator == (const SwingConeLimits &inRHS) const
  218. {
  219. return mSwingYHalfAngle == inRHS.mSwingYHalfAngle
  220. && mSwingZHalfAngle == inRHS.mSwingZHalfAngle;
  221. }
  222. float mSwingYHalfAngle;
  223. float mSwingZHalfAngle;
  224. };
  225. JPH_MAKE_HASH_STRUCT(SwingConeLimits, SwingConeLimitsHasher, t.mSwingYHalfAngle, t.mSwingZHalfAngle)
  226. using SwingConeBatches = UnorderedMap<SwingConeLimits, GeometryRef, SwingConeLimitsHasher>;
  227. SwingConeBatches mSwingConeLimits;
  228. struct SwingPyramidLimits
  229. {
  230. bool operator == (const SwingPyramidLimits &inRHS) const
  231. {
  232. return mMinSwingYAngle == inRHS.mMinSwingYAngle
  233. && mMaxSwingYAngle == inRHS.mMaxSwingYAngle
  234. && mMinSwingZAngle == inRHS.mMinSwingZAngle
  235. && mMaxSwingZAngle == inRHS.mMaxSwingZAngle;
  236. }
  237. float mMinSwingYAngle;
  238. float mMaxSwingYAngle;
  239. float mMinSwingZAngle;
  240. float mMaxSwingZAngle;
  241. };
  242. JPH_MAKE_HASH_STRUCT(SwingPyramidLimits, SwingPyramidLimitsHasher, t.mMinSwingYAngle, t.mMaxSwingYAngle, t.mMinSwingZAngle, t.mMaxSwingZAngle)
  243. using SwingPyramidBatches = UnorderedMap<SwingPyramidLimits, GeometryRef, SwingPyramidLimitsHasher>;
  244. SwingPyramidBatches mSwingPyramidLimits;
  245. using PieBatces = UnorderedMap<float, GeometryRef>;
  246. PieBatces mPieLimits;
  247. };
  248. JPH_NAMESPACE_END