d3d11-shader.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include "d3d11-subsystem.hpp"
  15. #include "d3d11-shaderprocessor.hpp"
  16. #include <graphics/vec2.h>
  17. #include <graphics/vec3.h>
  18. #include <graphics/matrix3.h>
  19. #include <graphics/matrix4.h>
  20. #include <util/platform.h>
  21. #include <util/util.hpp>
  22. #include <filesystem>
  23. #include <fstream>
  24. #include <d3dcompiler.h>
  25. void gs_vertex_shader::GetBuffersExpected(const vector<D3D11_INPUT_ELEMENT_DESC> &inputs)
  26. {
  27. for (size_t i = 0; i < inputs.size(); i++) {
  28. const D3D11_INPUT_ELEMENT_DESC &input = inputs[i];
  29. if (strcmp(input.SemanticName, "NORMAL") == 0)
  30. hasNormals = true;
  31. else if (strcmp(input.SemanticName, "TANGENT") == 0)
  32. hasTangents = true;
  33. else if (strcmp(input.SemanticName, "COLOR") == 0)
  34. hasColors = true;
  35. else if (strcmp(input.SemanticName, "TEXCOORD") == 0)
  36. nTexUnits++;
  37. }
  38. }
  39. gs_vertex_shader::gs_vertex_shader(gs_device_t *device, const char *file, const char *shaderString)
  40. : gs_shader(device, gs_type::gs_vertex_shader, GS_SHADER_VERTEX),
  41. hasNormals(false),
  42. hasColors(false),
  43. hasTangents(false),
  44. nTexUnits(0)
  45. {
  46. ShaderProcessor processor(device);
  47. ComPtr<ID3D10Blob> shaderBlob;
  48. string outputString;
  49. HRESULT hr;
  50. processor.Process(shaderString, file);
  51. processor.BuildString(outputString);
  52. processor.BuildParams(params);
  53. processor.BuildInputLayout(layoutData);
  54. GetBuffersExpected(layoutData);
  55. BuildConstantBuffer();
  56. Compile(outputString.c_str(), file, "vs_4_0", shaderBlob.Assign());
  57. data.resize(shaderBlob->GetBufferSize());
  58. memcpy(&data[0], shaderBlob->GetBufferPointer(), data.size());
  59. hr = device->device->CreateVertexShader(data.data(), data.size(), NULL, shader.Assign());
  60. if (FAILED(hr))
  61. throw HRError("Failed to create vertex shader", hr);
  62. const UINT layoutSize = (UINT)layoutData.size();
  63. if (layoutSize > 0) {
  64. hr = device->device->CreateInputLayout(layoutData.data(), (UINT)layoutSize, data.data(), data.size(),
  65. layout.Assign());
  66. if (FAILED(hr))
  67. throw HRError("Failed to create input layout", hr);
  68. }
  69. viewProj = gs_shader_get_param_by_name(this, "ViewProj");
  70. world = gs_shader_get_param_by_name(this, "World");
  71. }
  72. gs_pixel_shader::gs_pixel_shader(gs_device_t *device, const char *file, const char *shaderString)
  73. : gs_shader(device, gs_type::gs_pixel_shader, GS_SHADER_PIXEL)
  74. {
  75. ShaderProcessor processor(device);
  76. ComPtr<ID3D10Blob> shaderBlob;
  77. string outputString;
  78. HRESULT hr;
  79. processor.Process(shaderString, file);
  80. processor.BuildString(outputString);
  81. processor.BuildParams(params);
  82. processor.BuildSamplers(samplers);
  83. BuildConstantBuffer();
  84. Compile(outputString.c_str(), file, "ps_4_0", shaderBlob.Assign());
  85. data.resize(shaderBlob->GetBufferSize());
  86. memcpy(&data[0], shaderBlob->GetBufferPointer(), data.size());
  87. hr = device->device->CreatePixelShader(data.data(), data.size(), NULL, shader.Assign());
  88. if (FAILED(hr))
  89. throw HRError("Failed to create pixel shader", hr);
  90. }
  91. /*
  92. * Shader compilers will pack constants in to single registers when possible.
  93. * For example:
  94. *
  95. * uniform float3 test1;
  96. * uniform float test2;
  97. *
  98. * will inhabit a single constant register (c0.xyz for 'test1', and c0.w for
  99. * 'test2')
  100. *
  101. * However, if two constants cannot inhabit the same register, the second one
  102. * must begin at a new register, for example:
  103. *
  104. * uniform float2 test1;
  105. * uniform float3 test2;
  106. *
  107. * 'test1' will inhabit register constant c0.xy. However, because there's no
  108. * room for 'test2, it must use a new register constant entirely (c1.xyz).
  109. *
  110. * So if we want to calculate the position of the constants in the constant
  111. * buffer, we must take this in to account.
  112. */
  113. void gs_shader::BuildConstantBuffer()
  114. {
  115. for (size_t i = 0; i < params.size(); i++) {
  116. gs_shader_param &param = params[i];
  117. size_t size = 0;
  118. switch (param.type) {
  119. case GS_SHADER_PARAM_BOOL:
  120. case GS_SHADER_PARAM_INT:
  121. case GS_SHADER_PARAM_FLOAT:
  122. size = sizeof(float);
  123. break;
  124. case GS_SHADER_PARAM_INT2:
  125. case GS_SHADER_PARAM_VEC2:
  126. size = sizeof(vec2);
  127. break;
  128. case GS_SHADER_PARAM_INT3:
  129. case GS_SHADER_PARAM_VEC3:
  130. size = sizeof(float) * 3;
  131. break;
  132. case GS_SHADER_PARAM_INT4:
  133. case GS_SHADER_PARAM_VEC4:
  134. size = sizeof(vec4);
  135. break;
  136. case GS_SHADER_PARAM_MATRIX4X4:
  137. size = sizeof(float) * 4 * 4;
  138. break;
  139. case GS_SHADER_PARAM_TEXTURE:
  140. case GS_SHADER_PARAM_STRING:
  141. case GS_SHADER_PARAM_UNKNOWN:
  142. continue;
  143. }
  144. if (param.arrayCount)
  145. size *= param.arrayCount;
  146. /* checks to see if this constant needs to start at a new
  147. * register */
  148. if (size && (constantSize & 15) != 0) {
  149. size_t alignMax = (constantSize + 15) & ~15;
  150. if ((size + constantSize) > alignMax)
  151. constantSize = alignMax;
  152. }
  153. param.pos = constantSize;
  154. constantSize += size;
  155. }
  156. memset(&bd, 0, sizeof(bd));
  157. if (constantSize) {
  158. HRESULT hr;
  159. bd.ByteWidth = (constantSize + 15) & 0xFFFFFFF0; /* align */
  160. bd.Usage = D3D11_USAGE_DYNAMIC;
  161. bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
  162. bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
  163. hr = device->device->CreateBuffer(&bd, NULL, constants.Assign());
  164. if (FAILED(hr))
  165. throw HRError("Failed to create constant buffer", hr);
  166. }
  167. for (size_t i = 0; i < params.size(); i++)
  168. gs_shader_set_default(&params[i]);
  169. }
  170. static uint64_t fnv1a_hash(const char *str, size_t len)
  171. {
  172. const uint64_t FNV_OFFSET = 14695981039346656037ULL;
  173. const uint64_t FNV_PRIME = 1099511628211ULL;
  174. uint64_t hash = FNV_OFFSET;
  175. for (size_t i = 0; i < len; i++) {
  176. hash ^= (uint64_t)str[i];
  177. hash *= FNV_PRIME;
  178. }
  179. return hash;
  180. }
  181. void gs_shader::Compile(const char *shaderString, const char *file, const char *target, ID3D10Blob **shader)
  182. {
  183. ComPtr<ID3D10Blob> errorsBlob;
  184. HRESULT hr;
  185. bool is_cached = false;
  186. char hashstr[20];
  187. if (!shaderString)
  188. throw "No shader string specified";
  189. size_t shaderStrLen = strlen(shaderString);
  190. uint64_t hash = fnv1a_hash(shaderString, shaderStrLen);
  191. snprintf(hashstr, sizeof(hashstr), "%02llx", hash);
  192. BPtr program_data = os_get_program_data_path_ptr("obs-studio/shader-cache");
  193. auto cachePath = filesystem::u8path(program_data.Get()) / hashstr;
  194. // Increment if on-disk format changes
  195. cachePath += ".v2";
  196. std::fstream cacheFile;
  197. cacheFile.exceptions(fstream::badbit | fstream::eofbit);
  198. if (filesystem::exists(cachePath) && !filesystem::is_empty(cachePath))
  199. cacheFile.open(cachePath, ios::in | ios::binary | ios::ate);
  200. if (cacheFile.is_open()) {
  201. uint64_t checksum;
  202. try {
  203. streampos len = cacheFile.tellg();
  204. // Not enough data for checksum + shader
  205. if (len <= sizeof(checksum))
  206. throw length_error("File truncated");
  207. cacheFile.seekg(0, ios::beg);
  208. len -= sizeof(checksum);
  209. D3DCreateBlob(len, shader);
  210. cacheFile.read((char *)(*shader)->GetBufferPointer(), len);
  211. uint64_t calculated_checksum = fnv1a_hash((char *)(*shader)->GetBufferPointer(), len);
  212. cacheFile.read((char *)&checksum, sizeof(checksum));
  213. if (calculated_checksum != checksum)
  214. throw exception("Checksum mismatch");
  215. is_cached = true;
  216. } catch (const exception &e) {
  217. // Something went wrong reading the cache file, delete it
  218. blog(LOG_WARNING, "Loading shader cache file failed with \"%s\": %s", e.what(), file);
  219. cacheFile.close();
  220. filesystem::remove(cachePath);
  221. }
  222. }
  223. if (!is_cached) {
  224. hr = D3DCompile(shaderString, shaderStrLen, file, NULL, NULL, "main", target,
  225. D3D10_SHADER_OPTIMIZATION_LEVEL3, 0, shader, errorsBlob.Assign());
  226. if (FAILED(hr)) {
  227. if (errorsBlob != NULL && errorsBlob->GetBufferSize())
  228. throw ShaderError(errorsBlob, hr);
  229. else
  230. throw HRError("Failed to compile shader", hr);
  231. }
  232. cacheFile.open(cachePath, ios::out | ios::binary);
  233. if (cacheFile.is_open()) {
  234. try {
  235. uint64_t calculated_checksum =
  236. fnv1a_hash((char *)(*shader)->GetBufferPointer(), (*shader)->GetBufferSize());
  237. cacheFile.write((char *)(*shader)->GetBufferPointer(), (*shader)->GetBufferSize());
  238. cacheFile.write((char *)&calculated_checksum, sizeof(calculated_checksum));
  239. } catch (const exception &e) {
  240. blog(LOG_WARNING, "Writing shader cache file failed with \"%s\": %s", e.what(), file);
  241. cacheFile.close();
  242. filesystem::remove(cachePath);
  243. }
  244. }
  245. }
  246. #ifdef DISASSEMBLE_SHADERS
  247. ComPtr<ID3D10Blob> asmBlob;
  248. hr = D3DDisassemble((*shader)->GetBufferPointer(), (*shader)->GetBufferSize(), 0, nullptr, &asmBlob);
  249. if (SUCCEEDED(hr) && !!asmBlob && asmBlob->GetBufferSize()) {
  250. blog(LOG_INFO, "=============================================");
  251. blog(LOG_INFO, "Disassembly output for shader '%s':\n%s", file, asmBlob->GetBufferPointer());
  252. }
  253. #endif
  254. }
  255. inline void gs_shader::UpdateParam(vector<uint8_t> &constData, gs_shader_param &param, bool &upload)
  256. {
  257. if (param.type != GS_SHADER_PARAM_TEXTURE) {
  258. if (!param.curValue.size())
  259. throw "Not all shader parameters were set";
  260. /* padding in case the constant needs to start at a new
  261. * register */
  262. if (param.pos > constData.size()) {
  263. uint8_t zero = 0;
  264. constData.insert(constData.end(), param.pos - constData.size(), zero);
  265. }
  266. constData.insert(constData.end(), param.curValue.begin(), param.curValue.end());
  267. if (param.changed) {
  268. upload = true;
  269. param.changed = false;
  270. }
  271. } else if (param.curValue.size() == sizeof(struct gs_shader_texture)) {
  272. struct gs_shader_texture shader_tex;
  273. memcpy(&shader_tex, param.curValue.data(), sizeof(shader_tex));
  274. if (shader_tex.srgb)
  275. device_load_texture_srgb(device, shader_tex.tex, param.textureID);
  276. else
  277. device_load_texture(device, shader_tex.tex, param.textureID);
  278. if (param.nextSampler) {
  279. ID3D11SamplerState *state = param.nextSampler->state;
  280. device->context->PSSetSamplers(param.textureID, 1, &state);
  281. param.nextSampler = nullptr;
  282. }
  283. }
  284. }
  285. void gs_shader::UploadParams()
  286. {
  287. vector<uint8_t> constData;
  288. bool upload = false;
  289. constData.reserve(constantSize);
  290. for (size_t i = 0; i < params.size(); i++)
  291. UpdateParam(constData, params[i], upload);
  292. if (constData.size() != constantSize)
  293. throw "Invalid constant data size given to shader";
  294. if (upload) {
  295. D3D11_MAPPED_SUBRESOURCE map;
  296. HRESULT hr;
  297. hr = device->context->Map(constants, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);
  298. if (FAILED(hr))
  299. throw HRError("Could not lock constant buffer", hr);
  300. memcpy(map.pData, constData.data(), constData.size());
  301. device->context->Unmap(constants, 0);
  302. }
  303. }
  304. void gs_shader_destroy(gs_shader_t *shader)
  305. {
  306. if (shader && shader->device->lastVertexShader == shader)
  307. shader->device->lastVertexShader = nullptr;
  308. delete shader;
  309. }
  310. int gs_shader_get_num_params(const gs_shader_t *shader)
  311. {
  312. return (int)shader->params.size();
  313. }
  314. gs_sparam_t *gs_shader_get_param_by_idx(gs_shader_t *shader, uint32_t param)
  315. {
  316. return &shader->params[param];
  317. }
  318. gs_sparam_t *gs_shader_get_param_by_name(gs_shader_t *shader, const char *name)
  319. {
  320. for (size_t i = 0; i < shader->params.size(); i++) {
  321. gs_shader_param &param = shader->params[i];
  322. if (strcmp(param.name.c_str(), name) == 0)
  323. return &param;
  324. }
  325. return NULL;
  326. }
  327. gs_sparam_t *gs_shader_get_viewproj_matrix(const gs_shader_t *shader)
  328. {
  329. if (shader->type != GS_SHADER_VERTEX)
  330. return NULL;
  331. return static_cast<const gs_vertex_shader *>(shader)->viewProj;
  332. }
  333. gs_sparam_t *gs_shader_get_world_matrix(const gs_shader_t *shader)
  334. {
  335. if (shader->type != GS_SHADER_VERTEX)
  336. return NULL;
  337. return static_cast<const gs_vertex_shader *>(shader)->world;
  338. }
  339. void gs_shader_get_param_info(const gs_sparam_t *param, struct gs_shader_param_info *info)
  340. {
  341. if (!param)
  342. return;
  343. info->name = param->name.c_str();
  344. info->type = param->type;
  345. }
  346. static inline void shader_setval_inline(gs_shader_param *param, const void *data, size_t size)
  347. {
  348. assert(param);
  349. if (!param)
  350. return;
  351. bool size_changed = param->curValue.size() != size;
  352. if (size_changed)
  353. param->curValue.resize(size);
  354. if (size_changed || memcmp(param->curValue.data(), data, size) != 0) {
  355. memcpy(param->curValue.data(), data, size);
  356. param->changed = true;
  357. }
  358. }
  359. void gs_shader_set_bool(gs_sparam_t *param, bool val)
  360. {
  361. int b_val = (int)val;
  362. shader_setval_inline(param, &b_val, sizeof(int));
  363. }
  364. void gs_shader_set_float(gs_sparam_t *param, float val)
  365. {
  366. shader_setval_inline(param, &val, sizeof(float));
  367. }
  368. void gs_shader_set_int(gs_sparam_t *param, int val)
  369. {
  370. shader_setval_inline(param, &val, sizeof(int));
  371. }
  372. void gs_shader_set_matrix3(gs_sparam_t *param, const struct matrix3 *val)
  373. {
  374. struct matrix4 mat;
  375. matrix4_from_matrix3(&mat, val);
  376. shader_setval_inline(param, &mat, sizeof(matrix4));
  377. }
  378. void gs_shader_set_matrix4(gs_sparam_t *param, const struct matrix4 *val)
  379. {
  380. shader_setval_inline(param, val, sizeof(matrix4));
  381. }
  382. void gs_shader_set_vec2(gs_sparam_t *param, const struct vec2 *val)
  383. {
  384. shader_setval_inline(param, val, sizeof(vec2));
  385. }
  386. void gs_shader_set_vec3(gs_sparam_t *param, const struct vec3 *val)
  387. {
  388. shader_setval_inline(param, val, sizeof(float) * 3);
  389. }
  390. void gs_shader_set_vec4(gs_sparam_t *param, const struct vec4 *val)
  391. {
  392. shader_setval_inline(param, val, sizeof(vec4));
  393. }
  394. void gs_shader_set_texture(gs_sparam_t *param, gs_texture_t *val)
  395. {
  396. shader_setval_inline(param, &val, sizeof(gs_texture_t *));
  397. }
  398. void gs_shader_set_val(gs_sparam_t *param, const void *val, size_t size)
  399. {
  400. shader_setval_inline(param, val, size);
  401. }
  402. void gs_shader_set_default(gs_sparam_t *param)
  403. {
  404. if (param->defaultValue.size())
  405. shader_setval_inline(param, param->defaultValue.data(), param->defaultValue.size());
  406. }
  407. void gs_shader_set_next_sampler(gs_sparam_t *param, gs_samplerstate_t *sampler)
  408. {
  409. param->nextSampler = sampler;
  410. }