PerformanceTest.cpp 13 KB

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