d3d11-shader.cpp 14 KB

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