PerformanceTest.cpp 12 KB

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