PerformanceTest.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. // Jolt includes
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/RegisterTypes.h>
  6. #include <Jolt/Core/Factory.h>
  7. #include <Jolt/Core/TempAllocator.h>
  8. #include <Jolt/Core/JobSystemThreadPool.h>
  9. #include <Jolt/Physics/PhysicsSettings.h>
  10. #include <Jolt/Physics/PhysicsSystem.h>
  11. #include <Jolt/Physics/Collision/NarrowPhaseStats.h>
  12. #include <Jolt/Physics/StateRecorderImpl.h>
  13. #include <Jolt/Physics/DeterminismLog.h>
  14. #ifdef JPH_DEBUG_RENDERER
  15. #include <Jolt/Renderer/DebugRendererRecorder.h>
  16. #include <Jolt/Core/StreamWrapper.h>
  17. #endif // JPH_DEBUG_RENDERER
  18. // STL includes
  19. #include <iostream>
  20. #include <thread>
  21. #include <chrono>
  22. #include <memory>
  23. #include <cstdarg>
  24. using namespace JPH;
  25. using namespace std;
  26. // Disable common warnings triggered by Jolt
  27. JPH_SUPPRESS_WARNINGS
  28. // Local includes
  29. #include "RagdollScene.h"
  30. #include "ConvexVsMeshScene.h"
  31. // Time step for physics
  32. constexpr float cDeltaTime = 1.0f / 60.0f;
  33. static void TraceImpl(const char *inFMT, ...)
  34. {
  35. // Format the message
  36. va_list list;
  37. va_start(list, inFMT);
  38. char buffer[1024];
  39. vsnprintf(buffer, sizeof(buffer), inFMT, list);
  40. va_end(list);
  41. // Print to the TTY
  42. cout << buffer << endl;
  43. }
  44. // Program entry point
  45. int main(int argc, char** argv)
  46. {
  47. // Register allocation hook
  48. RegisterDefaultAllocator();
  49. // Parse command line parameters
  50. int specified_quality = -1;
  51. int specified_threads = -1;
  52. uint max_iterations = 500;
  53. bool disable_sleep = false;
  54. bool enable_profiler = false;
  55. #ifdef JPH_DEBUG_RENDERER
  56. bool enable_debug_renderer = false;
  57. #endif // JPH_DEBUG_RENDERER
  58. bool enable_per_frame_recording = false;
  59. bool record_state = false;
  60. bool validate_state = false;
  61. unique_ptr<PerformanceTestScene> scene;
  62. const char *validate_hash = nullptr;
  63. for (int argidx = 1; argidx < argc; ++argidx)
  64. {
  65. const char *arg = argv[argidx];
  66. if (strncmp(arg, "-s=", 3) == 0)
  67. {
  68. // Parse scene
  69. if (strcmp(arg + 3, "Ragdoll") == 0)
  70. scene = unique_ptr<PerformanceTestScene>(new RagdollScene);
  71. else if (strcmp(arg + 3, "ConvexVsMesh") == 0)
  72. scene = unique_ptr<PerformanceTestScene>(new ConvexVsMeshScene);
  73. else
  74. {
  75. cerr << "Invalid scene" << endl;
  76. return 1;
  77. }
  78. }
  79. else if (strncmp(arg, "-i=", 3) == 0)
  80. {
  81. // Parse max iterations
  82. max_iterations = (uint)atoi(arg + 3);
  83. }
  84. else if (strncmp(arg, "-q=", 3) == 0)
  85. {
  86. // Parse quality
  87. if (strcmp(arg + 3, "Discrete") == 0)
  88. specified_quality = 0;
  89. else if (strcmp(arg + 3, "LinearCast") == 0)
  90. specified_quality = 1;
  91. else
  92. {
  93. cerr << "Invalid quality" << endl;
  94. return 1;
  95. }
  96. }
  97. else if (strncmp(arg, "-t=", 3) == 0)
  98. {
  99. // Parse threads
  100. specified_threads = atoi(arg + 3);
  101. }
  102. else if (strcmp(arg, "-no_sleep") == 0)
  103. {
  104. disable_sleep = true;
  105. }
  106. else if (strcmp(arg, "-p") == 0)
  107. {
  108. enable_profiler = true;
  109. }
  110. #ifdef JPH_DEBUG_RENDERER
  111. else if (strcmp(arg, "-r") == 0)
  112. {
  113. enable_debug_renderer = true;
  114. }
  115. #endif // JPH_DEBUG_RENDERER
  116. else if (strcmp(arg, "-f") == 0)
  117. {
  118. enable_per_frame_recording = true;
  119. }
  120. else if (strcmp(arg, "-rs") == 0)
  121. {
  122. record_state = true;
  123. }
  124. else if (strcmp(arg, "-vs") == 0)
  125. {
  126. validate_state = true;
  127. }
  128. else if (strncmp(arg, "-validate_hash=", 15) == 0)
  129. {
  130. validate_hash = arg + 15;
  131. }
  132. else if (strcmp(arg, "-h") == 0)
  133. {
  134. // Print usage
  135. cerr << "Usage:" << endl
  136. << "-s=<scene>: Select scene (Ragdoll, ConvexVsMesh)" << endl
  137. << "-i=<num physics steps>: Number of physics steps to simulate (default 500)" << endl
  138. << "-q=<quality>: Test only with specified quality (Discrete, LinearCast)" << endl
  139. << "-t=<num threads>: Test only with N threads (default is to iterate over 1 .. num hardware threads)" << endl
  140. << "-p: Write out profiles" << endl
  141. << "-r: Record debug renderer output for JoltViewer" << endl
  142. << "-f: Record per frame timings" << endl
  143. << "-no_sleep: Disable sleeping" << endl
  144. << "-rs: Record state" << endl
  145. << "-vs: Validate state" << endl
  146. << "-validate_hash=<hash>: Validate hash (return 0 if successful, 1 if failed)" << endl;
  147. return 0;
  148. }
  149. }
  150. // Install callbacks
  151. Trace = TraceImpl;
  152. // Create a factory
  153. Factory::sInstance = new Factory();
  154. // Register all Jolt physics types
  155. RegisterTypes();
  156. // Create temp allocator
  157. TempAllocatorImpl temp_allocator(10 * 1024 * 1024);
  158. // Load the scene
  159. if (scene == nullptr)
  160. scene = unique_ptr<PerformanceTestScene>(new RagdollScene);
  161. if (!scene->Load())
  162. return 1;
  163. // Output scene we're running
  164. cout << "Running scene: " << scene->GetName() << endl;
  165. // Create mapping table from object layer to broadphase layer
  166. BPLayerInterfaceImpl broad_phase_layer_interface;
  167. // Start profiling this program
  168. JPH_PROFILE_START("Main");
  169. // Trace header
  170. cout << "Motion Quality, Thread Count, Steps / Second, Hash" << endl;
  171. // Iterate motion qualities
  172. for (uint mq = 0; mq < 2; ++mq)
  173. {
  174. // Skip quality if another was specified
  175. if (specified_quality != -1 && mq != (uint)specified_quality)
  176. continue;
  177. // Determine motion quality
  178. EMotionQuality motion_quality = mq == 0? EMotionQuality::Discrete : EMotionQuality::LinearCast;
  179. String motion_quality_str = mq == 0? "Discrete" : "LinearCast";
  180. // Determine which thread counts to test
  181. Array<uint> thread_permutations;
  182. if (specified_threads > 0)
  183. thread_permutations.push_back((uint)specified_threads - 1);
  184. else
  185. for (uint num_threads = 0; num_threads < thread::hardware_concurrency(); ++num_threads)
  186. thread_permutations.push_back(num_threads);
  187. // Test thread permutations
  188. for (uint num_threads : thread_permutations)
  189. {
  190. // Create job system with desired number of threads
  191. JobSystemThreadPool job_system(cMaxPhysicsJobs, cMaxPhysicsBarriers, num_threads);
  192. // Create physics system
  193. PhysicsSystem physics_system;
  194. physics_system.Init(10240, 0, 65536, 10240, broad_phase_layer_interface, BroadPhaseCanCollide, ObjectCanCollide);
  195. // Start test scene
  196. scene->StartTest(physics_system, motion_quality);
  197. // Disable sleeping if requested
  198. if (disable_sleep)
  199. {
  200. const BodyLockInterface &bli = physics_system.GetBodyLockInterfaceNoLock();
  201. BodyIDVector body_ids;
  202. physics_system.GetBodies(body_ids);
  203. for (BodyID id : body_ids)
  204. {
  205. BodyLockWrite lock(bli, id);
  206. if (lock.Succeeded())
  207. {
  208. Body &body = lock.GetBody();
  209. if (!body.IsStatic())
  210. body.SetAllowSleeping(false);
  211. }
  212. }
  213. }
  214. // Optimize the broadphase to prevent an expensive first frame
  215. physics_system.OptimizeBroadPhase();
  216. // A tag used to identify the test
  217. String tag = ToLower(motion_quality_str) + "_th" + ConvertToString(num_threads + 1);
  218. #ifdef JPH_DEBUG_RENDERER
  219. // Open renderer output
  220. ofstream renderer_file;
  221. if (enable_debug_renderer)
  222. renderer_file.open(("performance_test_" + tag + ".jor").c_str(), ofstream::out | ofstream::binary | ofstream::trunc);
  223. StreamOutWrapper renderer_stream(renderer_file);
  224. DebugRendererRecorder renderer(renderer_stream);
  225. #endif // JPH_DEBUG_RENDERER
  226. // Open per frame timing output
  227. ofstream per_frame_file;
  228. if (enable_per_frame_recording)
  229. {
  230. per_frame_file.open(("per_frame_" + tag + ".csv").c_str(), ofstream::out | ofstream::trunc);
  231. per_frame_file << "Frame, Time (ms)" << endl;
  232. }
  233. ofstream record_state_file;
  234. ifstream validate_state_file;
  235. if (record_state)
  236. record_state_file.open(("state_" + ToLower(motion_quality_str) + ".bin").c_str(), ofstream::out | ofstream::binary | ofstream::trunc);
  237. else if (validate_state)
  238. validate_state_file.open(("state_" + ToLower(motion_quality_str) + ".bin").c_str(), ifstream::in | ifstream::binary);
  239. chrono::nanoseconds total_duration(0);
  240. // Step the world for a fixed amount of iterations
  241. for (uint iterations = 0; iterations < max_iterations; ++iterations)
  242. {
  243. JPH_PROFILE_NEXTFRAME();
  244. JPH_DET_LOG("Iteration: " << iterations);
  245. // Start measuring
  246. chrono::high_resolution_clock::time_point clock_start = chrono::high_resolution_clock::now();
  247. // Do a physics step
  248. physics_system.Update(cDeltaTime, 1, 1, &temp_allocator, &job_system);
  249. // Stop measuring
  250. chrono::high_resolution_clock::time_point clock_end = chrono::high_resolution_clock::now();
  251. chrono::nanoseconds duration = chrono::duration_cast<chrono::nanoseconds>(clock_end - clock_start);
  252. total_duration += duration;
  253. #ifdef JPH_DEBUG_RENDERER
  254. if (enable_debug_renderer)
  255. {
  256. // Draw the state of the world
  257. BodyManager::DrawSettings settings;
  258. physics_system.DrawBodies(settings, &renderer);
  259. // Mark end of frame
  260. renderer.EndFrame();
  261. }
  262. #endif // JPH_DEBUG_RENDERER
  263. // Record time taken this iteration
  264. if (enable_per_frame_recording)
  265. per_frame_file << iterations << ", " << (1.0e-6 * duration.count()) << endl;
  266. // Dump profile information every 100 iterations
  267. if (enable_profiler && iterations % 100 == 0)
  268. {
  269. JPH_PROFILE_DUMP(tag + "_it" + ConvertToString(iterations));
  270. }
  271. if (record_state)
  272. {
  273. // Record state
  274. StateRecorderImpl recorder;
  275. physics_system.SaveState(recorder);
  276. // Write to file
  277. string data = recorder.GetData();
  278. size_t size = data.size();
  279. record_state_file.write((char *)&size, sizeof(size));
  280. record_state_file.write(data.data(), size);
  281. }
  282. else if (validate_state)
  283. {
  284. // Read state
  285. size_t size = 0;
  286. validate_state_file.read((char *)&size, sizeof(size));
  287. string data;
  288. data.resize(size);
  289. validate_state_file.read(data.data(), size);
  290. // Copy to validator
  291. StateRecorderImpl validator;
  292. validator.WriteBytes(data.data(), size);
  293. // Validate state
  294. validator.SetValidating(true);
  295. physics_system.RestoreState(validator);
  296. }
  297. #ifdef JPH_ENABLE_DETERMINISM_LOG
  298. const BodyLockInterface &bli = physics_system.GetBodyLockInterfaceNoLock();
  299. BodyIDVector body_ids;
  300. physics_system.GetBodies(body_ids);
  301. for (BodyID id : body_ids)
  302. {
  303. BodyLockRead lock(bli, id);
  304. const Body &body = lock.GetBody();
  305. if (!body.IsStatic())
  306. JPH_DET_LOG(id << ": p: " << body.GetPosition() << " r: " << body.GetRotation() << " v: " << body.GetLinearVelocity() << " w: " << body.GetAngularVelocity());
  307. }
  308. #endif // JPH_ENABLE_DETERMINISM_LOG
  309. }
  310. // Calculate hash of all positions and rotations of the bodies
  311. uint64 hash = HashBytes(nullptr, 0); // Ensure we start with the proper seed
  312. BodyInterface &bi = physics_system.GetBodyInterfaceNoLock();
  313. BodyIDVector body_ids;
  314. physics_system.GetBodies(body_ids);
  315. for (BodyID id : body_ids)
  316. {
  317. Vec3 pos = bi.GetPosition(id);
  318. hash = HashBytes(&pos, 3 * sizeof(float), hash);
  319. Quat rot = bi.GetRotation(id);
  320. hash = HashBytes(&rot, sizeof(Quat), hash);
  321. }
  322. // Convert hash to string
  323. stringstream hash_stream;
  324. hash_stream << "0x" << hex << hash << dec;
  325. string hash_str = hash_stream.str();
  326. // Stop test scene
  327. scene->StopTest(physics_system);
  328. // Trace stat line
  329. cout << motion_quality_str << ", " << num_threads + 1 << ", " << double(max_iterations) / (1.0e-9 * total_duration.count()) << ", " << hash_str << endl;
  330. // Check hash code
  331. if (validate_hash != nullptr && hash_str != validate_hash)
  332. {
  333. cout << "Fail hash validation. Was: " << hash_str << ", expected: " << validate_hash << endl;
  334. return 1;
  335. }
  336. }
  337. }
  338. #ifdef JPH_TRACK_NARROWPHASE_STATS
  339. NarrowPhaseStat::sReportStats();
  340. #endif // JPH_TRACK_NARROWPHASE_STATS
  341. // Destroy the factory
  342. delete Factory::sInstance;
  343. Factory::sInstance = nullptr;
  344. // End profiling this program
  345. JPH_PROFILE_END();
  346. return 0;
  347. }