PerformanceTest.cpp 12 KB

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