PerformanceTest.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. // Jolt includes
  4. #include <Jolt.h>
  5. #include <RegisterTypes.h>
  6. #include <Core/TempAllocator.h>
  7. #include <Core/JobSystemThreadPool.h>
  8. #include <Physics/PhysicsSettings.h>
  9. #include <Physics/PhysicsSystem.h>
  10. #include <Physics/Collision/NarrowPhaseStats.h>
  11. #ifdef JPH_DEBUG_RENDERER
  12. #include <Renderer/DebugRendererRecorder.h>
  13. #include <Core/StreamWrapper.h>
  14. #endif // JPH_DEBUG_RENDERER
  15. // STL includes
  16. #include <iostream>
  17. #include <thread>
  18. #include <chrono>
  19. #include <memory>
  20. #include <cstdarg>
  21. using namespace JPH;
  22. using namespace std;
  23. // Local includes
  24. #include "RagdollScene.h"
  25. #include "ConvexVsMeshScene.h"
  26. // Time step for physics
  27. constexpr float cDeltaTime = 1.0f / 60.0f;
  28. static void TraceImpl(const char *inFMT, ...)
  29. {
  30. // Format the message
  31. va_list list;
  32. va_start(list, inFMT);
  33. char buffer[1024];
  34. vsnprintf(buffer, sizeof(buffer), inFMT, list);
  35. // Print to the TTY
  36. cout << buffer << endl;
  37. }
  38. // Program entry point
  39. int main(int argc, char** argv)
  40. {
  41. // Parse command line parameters
  42. int specified_quality = -1;
  43. int specified_threads = -1;
  44. uint max_iterations = 500;
  45. bool disable_sleep = false;
  46. bool enable_profiler = false;
  47. bool enable_debug_renderer = false;
  48. bool enable_per_frame_recording = false;
  49. unique_ptr<PerformanceTestScene> scene;
  50. for (int argidx = 1; argidx < argc; ++argidx)
  51. {
  52. const char *arg = argv[argidx];
  53. if (strncmp(arg, "-s=", 3) == 0)
  54. {
  55. // Parse scene
  56. if (strcmp(arg + 3, "Ragdoll") == 0)
  57. scene = unique_ptr<PerformanceTestScene>(new RagdollScene);
  58. else if (strcmp(arg + 3, "ConvexVsMesh") == 0)
  59. scene = unique_ptr<PerformanceTestScene>(new ConvexVsMeshScene);
  60. else
  61. {
  62. cerr << "Invalid scene" << endl;
  63. return 1;
  64. }
  65. }
  66. else if (strncmp(arg, "-i=", 3) == 0)
  67. {
  68. // Parse max iterations
  69. max_iterations = (uint)atoi(arg + 3);
  70. }
  71. else if (strncmp(arg, "-q=", 3) == 0)
  72. {
  73. // Parse quality
  74. if (strcmp(arg + 3, "Discrete") == 0)
  75. specified_quality = 0;
  76. else if (strcmp(arg + 3, "LinearCast") == 0)
  77. specified_quality = 1;
  78. else
  79. {
  80. cerr << "Invalid quality" << endl;
  81. return 1;
  82. }
  83. }
  84. else if (strncmp(arg, "-t=", 3) == 0)
  85. {
  86. // Parse threads
  87. specified_threads = atoi(arg + 3);
  88. }
  89. else if (strcmp(arg, "-no_sleep") == 0)
  90. {
  91. disable_sleep = true;
  92. }
  93. else if (strcmp(arg, "-p") == 0)
  94. {
  95. enable_profiler = true;
  96. }
  97. else if (strcmp(arg, "-r") == 0)
  98. {
  99. enable_debug_renderer = true;
  100. }
  101. else if (strcmp(arg, "-f") == 0)
  102. {
  103. enable_per_frame_recording = true;
  104. }
  105. else if (strcmp(arg, "-h") == 0)
  106. {
  107. // Print usage
  108. cerr << "Usage:" << endl
  109. << "-s=<scene>: Select scene (Ragdoll, ConvexVsMesh)" << endl
  110. << "-i=<num physics steps>: Number of physics steps to simulate (default 500)" << endl
  111. << "-q=<quality>: Test only with specified quality (Discrete, LinearCast)" << endl
  112. << "-t=<num threads>: Test only with N threads (default is to iterate over 1 .. num hardware threads)" << endl
  113. << "-p: Write out profiles" << endl
  114. << "-r: Record debug renderer output for JoltViewer" << endl
  115. << "-f: Record per frame timings" << endl
  116. << "-no_sleep: Disable sleeping" << endl;
  117. return 0;
  118. }
  119. }
  120. // Install callbacks
  121. Trace = TraceImpl;
  122. // Register all Jolt physics types
  123. RegisterTypes();
  124. // Create temp allocator
  125. TempAllocatorImpl temp_allocator(10 * 1024 * 1024);
  126. // Load the scene
  127. if (scene == nullptr)
  128. scene = unique_ptr<PerformanceTestScene>(new RagdollScene);
  129. if (!scene->Load())
  130. return 1;
  131. // Output scene we're running
  132. cout << "Running scene: " << scene->GetName() << endl;
  133. // Create mapping table from object layer to broadphase layer
  134. ObjectToBroadPhaseLayer object_to_broadphase = GetObjectToBroadPhaseLayer();
  135. // Start profiling this thread
  136. JPH_PROFILE_THREAD_START("Main");
  137. // Trace header
  138. cout << "Motion Quality, Thread Count, Steps / Second, Hash" << endl;
  139. // Iterate motion qualities
  140. for (uint mq = 0; mq < 2; ++mq)
  141. {
  142. // Skip quality if another was specified
  143. if (specified_quality != -1 && mq != (uint)specified_quality)
  144. continue;
  145. // Determine motion quality
  146. EMotionQuality motion_quality = mq == 0? EMotionQuality::Discrete : EMotionQuality::LinearCast;
  147. string motion_quality_str = mq == 0? "Discrete" : "LinearCast";
  148. // Determine which thread counts to test
  149. vector<uint> thread_permutations;
  150. if (specified_threads > 0)
  151. thread_permutations.push_back((uint)specified_threads - 1);
  152. else
  153. for (uint num_threads = 0; num_threads < thread::hardware_concurrency(); ++num_threads)
  154. thread_permutations.push_back(num_threads);
  155. // Test thread permutations
  156. for (uint num_threads : thread_permutations)
  157. {
  158. // Create job system with desired number of threads
  159. JobSystemThreadPool job_system(cMaxPhysicsJobs, cMaxPhysicsBarriers, num_threads);
  160. // Create physics system
  161. PhysicsSystem physics_system;
  162. physics_system.Init(10240, 0, 65536, 10240, object_to_broadphase, BroadPhaseCanCollide, ObjectCanCollide);
  163. // Start test scene
  164. scene->StartTest(physics_system, motion_quality);
  165. // Disable sleeping if requested
  166. if (disable_sleep)
  167. {
  168. const BodyLockInterface &bli = physics_system.GetBodyLockInterfaceNoLock();
  169. BodyIDVector body_ids;
  170. physics_system.GetBodies(body_ids);
  171. for (BodyID id : body_ids)
  172. {
  173. BodyLockWrite lock(bli, id);
  174. if (lock.Succeeded())
  175. {
  176. Body &body = lock.GetBody();
  177. if (!body.IsStatic())
  178. body.SetAllowSleeping(false);
  179. }
  180. }
  181. }
  182. // Optimize the broadphase to prevent an expensive first frame
  183. physics_system.OptimizeBroadPhase();
  184. // A tag used to identify the test
  185. string tag = ToLower(motion_quality_str) + "_th" + ConvertToString(num_threads + 1);
  186. #ifdef JPH_DEBUG_RENDERER
  187. // Open renderer output
  188. ofstream renderer_file;
  189. if (enable_debug_renderer)
  190. renderer_file.open(("performance_test_" + tag + ".jor").c_str(), ofstream::out | ofstream::binary | ofstream::trunc);
  191. StreamOutWrapper renderer_stream(renderer_file);
  192. DebugRendererRecorder renderer(renderer_stream);
  193. #endif // JPH_DEBUG_RENDERER
  194. // Open per frame timing output
  195. ofstream per_frame_file;
  196. if (enable_per_frame_recording)
  197. {
  198. per_frame_file.open(("per_frame_" + tag + ".csv").c_str(), ofstream::out | ofstream::trunc);
  199. per_frame_file << "Frame, Time (ms)" << endl;
  200. }
  201. chrono::nanoseconds total_duration(0);
  202. // Step the world for a fixed amount of iterations
  203. for (uint iterations = 0; iterations < max_iterations; ++iterations)
  204. {
  205. JPH_PROFILE_NEXTFRAME();
  206. // Start measuring
  207. chrono::high_resolution_clock::time_point clock_start = chrono::high_resolution_clock::now();
  208. // Do a physics step
  209. physics_system.Update(cDeltaTime, 1, 1, &temp_allocator, &job_system);
  210. // Stop measuring
  211. chrono::high_resolution_clock::time_point clock_end = chrono::high_resolution_clock::now();
  212. chrono::nanoseconds duration = chrono::duration_cast<chrono::nanoseconds>(clock_end - clock_start);
  213. total_duration += duration;
  214. #ifdef JPH_DEBUG_RENDERER
  215. if (enable_debug_renderer)
  216. {
  217. // Draw the state of the world
  218. BodyManager::DrawSettings settings;
  219. physics_system.DrawBodies(settings, &renderer);
  220. // Mark end of frame
  221. renderer.EndFrame();
  222. }
  223. #endif // JPH_DEBUG_RENDERER
  224. // Record time taken this iteration
  225. if (enable_per_frame_recording)
  226. per_frame_file << iterations << ", " << (1.0e-6 * duration.count()) << endl;
  227. // Dump profile information every 100 iterations
  228. if (enable_profiler && iterations % 100 == 0)
  229. {
  230. JPH_PROFILE_DUMP(tag + "_it" + ConvertToString(iterations));
  231. }
  232. }
  233. // Calculate hash of all positions and rotations of the bodies
  234. size_t hash = 0;
  235. BodyInterface &bi = physics_system.GetBodyInterfaceNoLock();
  236. BodyIDVector body_ids;
  237. physics_system.GetBodies(body_ids);
  238. for (BodyID id : body_ids)
  239. {
  240. Vec3 pos = bi.GetPosition(id);
  241. Quat rot = bi.GetRotation(id);
  242. hash_combine(hash, pos.GetX(), pos.GetY(), pos.GetZ(), rot.GetX(), rot.GetY(), rot.GetZ(), rot.GetW());
  243. }
  244. // Stop test scene
  245. scene->StopTest(physics_system);
  246. // Trace stat line
  247. cout << motion_quality_str << ", " << num_threads + 1 << ", " << double(max_iterations) / (1.0e-9 * total_duration.count()) << ", " << hash << endl;
  248. }
  249. }
  250. #ifdef JPH_TRACK_NARROWPHASE_STATS
  251. NarrowPhaseStat::sReportStats();
  252. #endif // JPH_TRACK_NARROWPHASE_STATS
  253. // End profiling this thread
  254. JPH_PROFILE_THREAD_END();
  255. return 0;
  256. }