ComputeTests.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2025 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include "UnitTestFramework.h"
  5. #if defined(JPH_USE_DX12) || defined(JPH_USE_VK) || defined(JPH_USE_MTL) || defined(JPH_USE_CPU_COMPUTE)
  6. #include <Jolt/Compute/ComputeSystem.h>
  7. #include <Jolt/Compute/CPU/ComputeSystemCPU.h>
  8. #include <Jolt/Shaders/TestComputeBindings.h>
  9. #include <Jolt/Shaders/TestCompute2Bindings.h>
  10. #include <Jolt/Core/IncludeWindows.h>
  11. #include <Jolt/Core/RTTI.h>
  12. JPH_SUPPRESS_WARNINGS_STD_BEGIN
  13. #include <fstream>
  14. #include <filesystem>
  15. #ifdef JPH_PLATFORM_LINUX
  16. #include <unistd.h>
  17. #endif
  18. JPH_SUPPRESS_WARNINGS_STD_END
  19. #if defined(JPH_PLATFORM_MACOS) || defined(JPH_PLATFORM_IOS)
  20. #include <CoreFoundation/CoreFoundation.h>
  21. #endif
  22. #ifdef JPH_USE_CPU_COMPUTE
  23. JPH_DECLARE_REGISTER_SHADER(TestCompute)
  24. JPH_DECLARE_REGISTER_SHADER(TestCompute2)
  25. #endif // JPH_USE_CPU_COMPUTE
  26. TEST_SUITE("ComputeTests")
  27. {
  28. static const char *cInvalidShaderName = "InvalidShader";
  29. static const char *cInvalidShaderCode = "invalid_shader_code";
  30. static void RunTests(ComputeSystem *inComputeSystem)
  31. {
  32. inComputeSystem->mShaderLoader = [](const char *inName, Array<uint8> &outData, String &outError) {
  33. // Special case to test what happens when an invalid file is returned
  34. if (strstr(inName, cInvalidShaderName) != nullptr)
  35. {
  36. outData.assign(cInvalidShaderCode, cInvalidShaderCode + strlen(cInvalidShaderCode));
  37. return true;
  38. }
  39. #if defined(JPH_PLATFORM_MACOS) || defined(JPH_PLATFORM_IOS)
  40. // In macOS the shaders are copied to the bundle
  41. CFBundleRef bundle = CFBundleGetMainBundle();
  42. CFURLRef resources = CFBundleCopyResourcesDirectoryURL(bundle);
  43. CFURLRef absolute = CFURLCopyAbsoluteURL(resources);
  44. CFRelease(resources);
  45. CFStringRef path_string = CFURLCopyFileSystemPath(absolute, kCFURLPOSIXPathStyle);
  46. CFRelease(absolute);
  47. char path[PATH_MAX];
  48. CFStringGetCString(path_string, path, PATH_MAX, kCFStringEncodingUTF8);
  49. CFRelease(path_string);
  50. String base_path = String(path) + "/Jolt/Shaders/";
  51. #else
  52. // On other platforms, start searching up from the application path
  53. #ifdef JPH_PLATFORM_WINDOWS
  54. char application_path[MAX_PATH] = { 0 };
  55. GetModuleFileName(nullptr, application_path, MAX_PATH);
  56. #elif defined(JPH_PLATFORM_LINUX)
  57. char application_path[PATH_MAX] = { 0 };
  58. int count = readlink("/proc/self/exe", application_path, PATH_MAX);
  59. if (count > 0)
  60. application_path[count] = 0;
  61. #else
  62. // Not implemented
  63. const char *application_path = "";
  64. #endif
  65. String base_path;
  66. filesystem::path shader_path(application_path);
  67. while (!shader_path.empty())
  68. {
  69. filesystem::path parent_path = shader_path.parent_path();
  70. if (parent_path == shader_path)
  71. break;
  72. shader_path = parent_path;
  73. filesystem::path full_path = shader_path / "Jolt" / "Shaders" / "";
  74. if (filesystem::exists(full_path))
  75. {
  76. base_path = String(full_path.string());
  77. break;
  78. }
  79. }
  80. #endif
  81. // Open file
  82. std::ifstream input((base_path + inName).c_str(), std::ios::in | std::ios::binary);
  83. if (!input.is_open())
  84. {
  85. outError = String("Could not open shader file: ") + base_path + inName;
  86. #if defined(JPH_PLATFORM_MACOS) || defined(JPH_PLATFORM_IOS)
  87. outError += "\nThis can fail on macOS when dxc or spirv-cross could not be found so the shaders could not be compiled.";
  88. #endif
  89. return false;
  90. }
  91. // Read contents of file
  92. input.seekg(0, ios_base::end);
  93. ifstream::pos_type length = input.tellg();
  94. input.seekg(0, ios_base::beg);
  95. outData.resize(size_t(length));
  96. if (length == 0)
  97. return true;
  98. input.read((char *)&outData[0], length);
  99. return true;
  100. };
  101. // Create a queue
  102. ComputeQueueResult queue_result = inComputeSystem->CreateComputeQueue();
  103. CHECK(!queue_result.HasError());
  104. Ref<ComputeQueue> queue = queue_result.Get();
  105. CHECK(queue != nullptr);
  106. // Test failing shader creation
  107. {
  108. ComputeShaderResult shader_result = inComputeSystem->CreateComputeShader("NonExistingShader", 64);
  109. CHECK(shader_result.HasError());
  110. }
  111. {
  112. constexpr uint32 cNumElements = 1234; // Not a multiple of cTestComputeGroupSize
  113. constexpr uint32 cNumIterations = 10;
  114. constexpr JPH_float3 cFloat3Value = JPH_float3(0, 0, 0);
  115. constexpr JPH_float3 cFloat3Value2 = JPH_float3(0, 13, 0);
  116. constexpr uint32 cUIntValue = 7;
  117. constexpr uint32 cUploadValue = 42;
  118. // Can't change context buffer while commands are queued, so create multiple constant buffers
  119. Ref<ComputeBuffer> context[cNumIterations];
  120. for (uint32 iter = 0; iter < cNumIterations; ++iter)
  121. {
  122. ComputeBufferResult buffer_result = inComputeSystem->CreateComputeBuffer(ComputeBuffer::EType::ConstantBuffer, 1, sizeof(TestComputeContext));
  123. CHECK(!buffer_result.HasError());
  124. context[iter] = buffer_result.Get();
  125. }
  126. CHECK(context != nullptr);
  127. // Create an upload buffer
  128. ComputeBufferResult upload_buffer_result = inComputeSystem->CreateComputeBuffer(ComputeBuffer::EType::UploadBuffer, 1, sizeof(uint32));
  129. CHECK(!upload_buffer_result.HasError());
  130. Ref<ComputeBuffer> upload_buffer = upload_buffer_result.Get();
  131. CHECK(upload_buffer != nullptr);
  132. uint32 *upload_data = upload_buffer->Map<uint32>(ComputeBuffer::EMode::Write);
  133. upload_data[0] = cUploadValue;
  134. upload_buffer->Unmap();
  135. // Create a read buffer
  136. UnitTestRandom rnd;
  137. Array<uint32> optional_data(cNumElements);
  138. for (uint32 &d : optional_data)
  139. d = rnd();
  140. ComputeBufferResult optional_buffer_result = inComputeSystem->CreateComputeBuffer(ComputeBuffer::EType::Buffer, cNumElements, sizeof(uint32), optional_data.data());
  141. CHECK(!optional_buffer_result.HasError());
  142. Ref<ComputeBuffer> optional_buffer = optional_buffer_result.Get();
  143. CHECK(optional_buffer != nullptr);
  144. // Create a read-write buffer
  145. ComputeBufferResult buffer_result = inComputeSystem->CreateComputeBuffer(ComputeBuffer::EType::RWBuffer, cNumElements, sizeof(uint32));
  146. CHECK(!buffer_result.HasError());
  147. Ref<ComputeBuffer> buffer = buffer_result.Get();
  148. CHECK(buffer != nullptr);
  149. // Create a read back buffer
  150. ComputeBufferResult readback_buffer_result = buffer->CreateReadBackBuffer();
  151. CHECK(!readback_buffer_result.HasError());
  152. Ref<ComputeBuffer> readback_buffer = readback_buffer_result.Get();
  153. CHECK(readback_buffer != nullptr);
  154. // Create the shader
  155. ComputeShaderResult shader_result = inComputeSystem->CreateComputeShader("TestCompute", cTestComputeGroupSize);
  156. if (shader_result.HasError())
  157. {
  158. Trace("Shader could not be created: %s", shader_result.GetError().c_str());
  159. return;
  160. }
  161. Ref<ComputeShader> shader = shader_result.Get();
  162. CHECK(shader != nullptr);
  163. // Schedule work
  164. for (uint32 iter = 0; iter < cNumIterations; ++iter)
  165. {
  166. // Fill in the context
  167. TestComputeContext *value = context[iter]->Map<TestComputeContext>(ComputeBuffer::EMode::Write);
  168. value->cFloat3Value = cFloat3Value;
  169. value->cUIntValue = cUIntValue;
  170. value->cFloat3Value2 = cFloat3Value2;
  171. value->cUIntValue2 = iter;
  172. value->cNumElements = cNumElements;
  173. context[iter]->Unmap();
  174. queue->SetShader(shader);
  175. queue->SetConstantBuffer("gContext", context[iter]);
  176. context[iter] = nullptr; // Release the reference to ensure the queue keeps ownership
  177. queue->SetBuffer("gOptionalData", optional_buffer);
  178. optional_buffer = nullptr; // Release the reference so we test that the queue keeps ownership and that in the 2nd iteration we can set a null buffer
  179. queue->SetBuffer("gUploadData", upload_buffer);
  180. queue->SetRWBuffer("gData", buffer);
  181. queue->Dispatch((cNumElements + cTestComputeGroupSize - 1) / cTestComputeGroupSize);
  182. }
  183. // Run all queued commands
  184. queue->ScheduleReadback(readback_buffer, buffer);
  185. queue->ExecuteAndWait();
  186. // Calculate the expected result
  187. Array<uint32> expected_data(cNumElements);
  188. for (uint32 iter = 0; iter < cNumIterations; ++iter)
  189. {
  190. // Copy of the shader logic
  191. uint cUIntValue2 = iter;
  192. if (cUIntValue2 == 0)
  193. {
  194. // First write, uses optional data and tests that the packing of float3/uint3's works
  195. for (uint32 i = 0; i < cNumElements; ++i)
  196. expected_data[i] = optional_data[i] + int(cFloat3Value2.y) + cUploadValue;
  197. }
  198. else
  199. {
  200. // Read-modify-write gData
  201. for (uint32 i = 0; i < cNumElements; ++i)
  202. expected_data[i] = (expected_data[i] + cUIntValue) * cUIntValue2;
  203. }
  204. }
  205. // Compare computed data with expected data
  206. uint32 *data = readback_buffer->Map<uint32>(ComputeBuffer::EMode::Read);
  207. for (uint32 i = 0; i < cNumElements; ++i)
  208. CHECK(data[i] == expected_data[i]);
  209. readback_buffer->Unmap();
  210. }
  211. // Test helper functions
  212. {
  213. // Create the shader
  214. ComputeShaderResult shader_result = inComputeSystem->CreateComputeShader("TestCompute2", cTestCompute2GroupSize);
  215. if (shader_result.HasError())
  216. {
  217. Trace("Shader could not be created: %s", shader_result.GetError().c_str());
  218. return;
  219. }
  220. Ref<ComputeShader> shader = shader_result.Get();
  221. CHECK(shader != nullptr);
  222. const Mat44 cMat44Value(Vec4(2, 3, 5, 0), Vec4(7, 11, 13, 0), Vec4(13, 15, 17, 0), Vec4(17, 19, 23, 0));
  223. const Vec3 cMat44MulValue(29, 31, 37);
  224. const Vec3 cDecompressedVec3(Vec3(-2, 3, -5).Normalized());
  225. const uint32 cCompressedVec3 = cDecompressedVec3.CompressUnitVector();
  226. const Quat cDecompressedQuat(Vec4(2, -3, 5, -7).Normalized());
  227. const uint32 cCompressedQuat = cDecompressedQuat.CompressUnitQuat();
  228. // Generate input data
  229. TestCompute2Input input;
  230. cMat44Value.StoreFloat4x4(input.mMat44Value);
  231. cMat44MulValue.StoreFloat3(&input.mMat44MulValue);
  232. input.mCompressedVec3 = cCompressedVec3;
  233. input.mCompressedQuat = cCompressedQuat;
  234. // Create input buffer
  235. ComputeBufferResult buffer_result = inComputeSystem->CreateComputeBuffer(ComputeBuffer::EType::Buffer, 1, sizeof(TestCompute2Input), &input);
  236. CHECK(!buffer_result.HasError());
  237. Ref<ComputeBuffer> input_buffer = buffer_result.Get();
  238. // Create a read-write buffer for the output
  239. buffer_result = inComputeSystem->CreateComputeBuffer(ComputeBuffer::EType::RWBuffer, 1, sizeof(TestCompute2Output));
  240. CHECK(!buffer_result.HasError());
  241. Ref<ComputeBuffer> output_buffer = buffer_result.Get();
  242. CHECK(output_buffer != nullptr);
  243. // Create a read back buffer
  244. buffer_result = output_buffer->CreateReadBackBuffer();
  245. CHECK(!buffer_result.HasError());
  246. Ref<ComputeBuffer> readback_buffer = buffer_result.Get();
  247. CHECK(readback_buffer != nullptr);
  248. // Execute the shader
  249. queue->SetShader(shader);
  250. queue->SetBuffer("gInput", input_buffer);
  251. queue->SetRWBuffer("gOutput", output_buffer);
  252. queue->Dispatch(1);
  253. queue->ScheduleReadback(readback_buffer, output_buffer);
  254. queue->ExecuteAndWait();
  255. // Verify the output
  256. TestCompute2Output *output = readback_buffer->Map<TestCompute2Output>(ComputeBuffer::EMode::Read);
  257. const Vec3 expected_mul3x4 = cMat44Value * cMat44MulValue;
  258. CHECK(Vec3(output->mMul3x4Output) == expected_mul3x4);
  259. const Vec3 expected_mul3x3 = cMat44Value.Multiply3x3(cMat44MulValue);
  260. CHECK(Vec3(output->mMul3x3Output) == expected_mul3x3);
  261. const Vec3 expected_decompressed_vec3 = Vec3::sDecompressUnitVector(cCompressedVec3);
  262. CHECK(Vec3(output->mDecompressedVec3).IsClose(expected_decompressed_vec3));
  263. const Quat expected_decompressed_quat = Quat::sDecompressUnitQuat(cCompressedQuat);
  264. CHECK(Quat(output->mDecompressedQuat).IsClose(expected_decompressed_quat));
  265. readback_buffer->Unmap();
  266. }
  267. }
  268. #ifdef JPH_USE_DX12
  269. TEST_CASE("TestComputeDX12")
  270. {
  271. ComputeSystemResult compute_system = CreateComputeSystemDX12();
  272. CHECK(!compute_system.HasError());
  273. if (!compute_system.HasError())
  274. {
  275. CHECK(compute_system.Get() != nullptr);
  276. RunTests(compute_system.Get());
  277. // Test failing shader compilation
  278. {
  279. ComputeShaderResult shader_result = compute_system.Get()->CreateComputeShader(cInvalidShaderName, 64);
  280. CHECK(shader_result.HasError());
  281. CHECK(strstr(shader_result.GetError().c_str(), cInvalidShaderCode) != nullptr); // Assume that the error message contains the invalid code
  282. }
  283. }
  284. }
  285. #endif // JPH_USE_DX12
  286. #ifdef JPH_USE_MTL
  287. TEST_CASE("TestComputeMTL")
  288. {
  289. ComputeSystemResult compute_system = CreateComputeSystemMTL();
  290. CHECK(!compute_system.HasError());
  291. if (!compute_system.HasError())
  292. {
  293. CHECK(compute_system.Get() != nullptr);
  294. RunTests(compute_system.Get());
  295. }
  296. }
  297. #endif // JPH_USE_MTL
  298. #ifdef JPH_USE_VK
  299. TEST_CASE("TestComputeVK")
  300. {
  301. ComputeSystemResult compute_system = CreateComputeSystemVK();
  302. CHECK(!compute_system.HasError());
  303. if (!compute_system.HasError())
  304. {
  305. CHECK(compute_system.Get() != nullptr);
  306. RunTests(compute_system.Get());
  307. }
  308. }
  309. #endif // JPH_USE_VK
  310. #ifdef JPH_USE_CPU_COMPUTE
  311. TEST_CASE("TestComputeCPU")
  312. {
  313. ComputeSystemResult compute_system = CreateComputeSystemCPU();
  314. CHECK(!compute_system.HasError());
  315. if (!compute_system.HasError())
  316. {
  317. CHECK(compute_system.Get() != nullptr);
  318. JPH_REGISTER_SHADER(StaticCast<ComputeSystemCPU>(compute_system.Get()), TestCompute);
  319. JPH_REGISTER_SHADER(StaticCast<ComputeSystemCPU>(compute_system.Get()), TestCompute2);
  320. RunTests(compute_system.Get());
  321. }
  322. }
  323. #endif // JPH_USE_CPU_COMPUTE
  324. }
  325. #endif // defined(JPH_USE_DX12) || defined(JPH_USE_VK) || defined(JPH_USE_MTL) || defined(JPH_USE_CPU_COMPUTE)