PerformanceTest.cpp 15 KB

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