PerformanceTest.cpp 14 KB

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