PerformanceTest.cpp 13 KB

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