render_backend_d3d11.odin 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. #+build windows
  2. #+vet explicit-allocators
  3. #+private file
  4. package karl2d
  5. @(private="package")
  6. RENDER_BACKEND_INTERFACE_D3D11 :: Render_Backend_Interface {
  7. state_size = d3d11_state_size,
  8. init = d3d11_init,
  9. shutdown = d3d11_shutdown,
  10. clear = d3d11_clear,
  11. present = d3d11_present,
  12. draw = d3d11_draw,
  13. resize_swapchain = d3d11_resize_swapchain,
  14. get_swapchain_width = d3d11_get_swapchain_width,
  15. get_swapchain_height = d3d11_get_swapchain_height,
  16. flip_z = d3d11_flip_z,
  17. set_internal_state = d3d11_set_internal_state,
  18. create_texture = d3d11_create_texture,
  19. load_texture = d3d11_load_texture,
  20. update_texture = d3d11_update_texture,
  21. destroy_texture = d3d11_destroy_texture,
  22. create_render_texture = d3d11_create_render_texture,
  23. destroy_render_target = d3d11_destroy_render_target,
  24. set_texture_filter = d3d11_set_texture_filter,
  25. load_shader = d3d11_load_shader,
  26. destroy_shader = d3d11_destroy_shader,
  27. default_shader_vertex_source = d3d11_default_shader_vertex_source,
  28. default_shader_fragment_source = d3d11_default_shader_fragment_source,
  29. }
  30. import d3d11 "vendor:directx/d3d11"
  31. import dxgi "vendor:directx/dxgi"
  32. import "vendor:directx/d3d_compiler"
  33. import "core:strings"
  34. import "core:log"
  35. import "core:slice"
  36. import "core:mem"
  37. import hm "handle_map"
  38. import "base:runtime"
  39. d3d11_state_size :: proc() -> int {
  40. return size_of(D3D11_State)
  41. }
  42. d3d11_init :: proc(state: rawptr, window_handle: Window_Handle, swapchain_width, swapchain_height: int, allocator := context.allocator) {
  43. s = (^D3D11_State)(state)
  44. s.allocator = allocator
  45. s.window_handle = dxgi.HWND(window_handle)
  46. s.width = swapchain_width
  47. s.height = swapchain_height
  48. feature_levels := [?]d3d11.FEATURE_LEVEL{
  49. ._11_1,
  50. ._11_0,
  51. }
  52. base_device: ^d3d11.IDevice
  53. base_device_context: ^d3d11.IDeviceContext
  54. base_device_flags := d3d11.CREATE_DEVICE_FLAGS {
  55. .BGRA_SUPPORT,
  56. }
  57. when ODIN_DEBUG {
  58. device_flags := base_device_flags + { .DEBUG }
  59. device_err := ch(d3d11.CreateDevice(
  60. nil,
  61. .HARDWARE,
  62. nil,
  63. device_flags,
  64. &feature_levels[0], len(feature_levels),
  65. d3d11.SDK_VERSION, &base_device, nil, &base_device_context))
  66. if u32(device_err) == 0x887a002d {
  67. log.error("You're running in debug mode. So we are trying to create a debug D3D11 device. But you don't have DirectX SDK installed, so we can't enable debug layers. Creating a device without debug layers (you'll get no good D3D11 errors).")
  68. ch(d3d11.CreateDevice(
  69. nil,
  70. .HARDWARE,
  71. nil,
  72. base_device_flags,
  73. &feature_levels[0], len(feature_levels),
  74. d3d11.SDK_VERSION, &base_device, nil, &base_device_context))
  75. } else {
  76. ch(base_device->QueryInterface(d3d11.IInfoQueue_UUID, (^rawptr)(&s.info_queue)))
  77. }
  78. } else {
  79. ch(d3d11.CreateDevice(
  80. nil,
  81. .HARDWARE,
  82. nil,
  83. base_device_flags,
  84. &feature_levels[0], len(feature_levels),
  85. d3d11.SDK_VERSION, &base_device, nil, &base_device_context))
  86. }
  87. ch(base_device->QueryInterface(d3d11.IDevice_UUID, (^rawptr)(&s.device)))
  88. ch(base_device_context->QueryInterface(d3d11.IDeviceContext_UUID, (^rawptr)(&s.device_context)))
  89. dxgi_device: ^dxgi.IDevice
  90. ch(s.device->QueryInterface(dxgi.IDevice_UUID, (^rawptr)(&dxgi_device)))
  91. base_device->Release()
  92. base_device_context->Release()
  93. ch(dxgi_device->GetAdapter(&s.dxgi_adapter))
  94. create_swapchain(swapchain_width, swapchain_height)
  95. rasterizer_desc := d3d11.RASTERIZER_DESC{
  96. FillMode = .SOLID,
  97. CullMode = .BACK,
  98. ScissorEnable = true,
  99. }
  100. ch(s.device->CreateRasterizerState(&rasterizer_desc, &s.rasterizer_state))
  101. depth_stencil_desc := d3d11.DEPTH_STENCIL_DESC{
  102. DepthEnable = true,
  103. DepthWriteMask = .ALL,
  104. DepthFunc = .LESS,
  105. }
  106. ch(s.device->CreateDepthStencilState(&depth_stencil_desc, &s.depth_stencil_state))
  107. vertex_buffer_desc := d3d11.BUFFER_DESC{
  108. ByteWidth = VERTEX_BUFFER_MAX,
  109. Usage = .DYNAMIC,
  110. BindFlags = {.VERTEX_BUFFER},
  111. CPUAccessFlags = {.WRITE},
  112. }
  113. ch(s.device->CreateBuffer(&vertex_buffer_desc, nil, &s.vertex_buffer_gpu))
  114. blend_desc := d3d11.BLEND_DESC {
  115. RenderTarget = {
  116. 0 = {
  117. BlendEnable = true,
  118. SrcBlend = .SRC_ALPHA,
  119. DestBlend = .INV_SRC_ALPHA,
  120. BlendOp = .ADD,
  121. SrcBlendAlpha = .SRC_ALPHA,
  122. DestBlendAlpha = .INV_SRC_ALPHA,
  123. BlendOpAlpha = .ADD,
  124. RenderTargetWriteMask = u8(d3d11.COLOR_WRITE_ENABLE_ALL),
  125. },
  126. },
  127. }
  128. ch(s.device->CreateBlendState(&blend_desc, &s.blend_state))
  129. }
  130. d3d11_shutdown :: proc() {
  131. s.framebuffer_view->Release()
  132. s.depth_buffer_view->Release()
  133. s.depth_buffer->Release()
  134. s.framebuffer->Release()
  135. s.device_context->Release()
  136. s.vertex_buffer_gpu->Release()
  137. s.depth_stencil_state->Release()
  138. s.rasterizer_state->Release()
  139. s.swapchain->Release()
  140. s.blend_state->Release()
  141. s.dxgi_adapter->Release()
  142. when ODIN_DEBUG {
  143. debug: ^d3d11.IDebug
  144. if ch(s.device->QueryInterface(d3d11.IDebug_UUID, (^rawptr)(&debug))) >= 0 {
  145. ch(debug->ReportLiveDeviceObjects({.DETAIL, .IGNORE_INTERNAL}))
  146. log_messages()
  147. }
  148. debug->Release()
  149. }
  150. s.device->Release()
  151. s.info_queue->Release()
  152. }
  153. d3d11_clear :: proc(render_target: Render_Target_Handle, color: Color) {
  154. c := f32_color_from_color(color)
  155. if rt := hm.get(&s.render_targets, render_target); rt != nil {
  156. s.device_context->ClearRenderTargetView(rt.render_target_view, &c)
  157. s.device_context->ClearDepthStencilView(rt.depth_stencil_texture_view, {.DEPTH}, 1, 0)
  158. } else {
  159. s.device_context->ClearRenderTargetView(s.framebuffer_view, &c)
  160. s.device_context->ClearDepthStencilView(s.depth_buffer_view, {.DEPTH}, 1, 0)
  161. }
  162. }
  163. d3d11_present :: proc() {
  164. ch(s.swapchain->Present(1, {}))
  165. }
  166. d3d11_draw :: proc(
  167. shd: Shader,
  168. render_target: Render_Target_Handle,
  169. bound_textures: []Texture_Handle,
  170. scissor: Maybe(Rect),
  171. vertex_buffer: []u8,
  172. ) {
  173. if len(vertex_buffer) == 0 {
  174. return
  175. }
  176. d3d_shd := hm.get(&s.shaders, shd.handle)
  177. if d3d_shd == nil {
  178. log.error("Trying to draw with invalid shader %v", shd.handle)
  179. return
  180. }
  181. dc := s.device_context
  182. vb_data: d3d11.MAPPED_SUBRESOURCE
  183. ch(dc->Map(s.vertex_buffer_gpu, 0, .WRITE_DISCARD, {}, &vb_data))
  184. {
  185. gpu_map := slice.from_ptr((^u8)(vb_data.pData), VERTEX_BUFFER_MAX)
  186. copy(
  187. gpu_map,
  188. vertex_buffer,
  189. )
  190. }
  191. dc->Unmap(s.vertex_buffer_gpu, 0)
  192. dc->IASetPrimitiveTopology(.TRIANGLELIST)
  193. dc->IASetInputLayout(d3d_shd.input_layout)
  194. vertex_buffer_offset: u32
  195. vertex_buffer_stride := u32(shd.vertex_size)
  196. dc->IASetVertexBuffers(0, 1, &s.vertex_buffer_gpu, &vertex_buffer_stride, &vertex_buffer_offset)
  197. dc->VSSetShader(d3d_shd.vertex_shader, nil, 0)
  198. assert(len(shd.constants) == len(d3d_shd.constants))
  199. maps := make([]rawptr, len(d3d_shd.constant_buffers), frame_allocator)
  200. cpu_data := shd.constants_data
  201. for cidx in 0..<len(shd.constants) {
  202. cpu_loc := shd.constants[cidx]
  203. gpu_loc := d3d_shd.constants[cidx]//cpu_loc.gpu_constant_idx]
  204. gpu_buffer_info := d3d_shd.constant_buffers[gpu_loc.buffer_idx]
  205. gpu_data := gpu_buffer_info.gpu_data
  206. if gpu_data == nil {
  207. continue
  208. }
  209. if maps[gpu_loc.buffer_idx] == nil {
  210. // We do this little dance with the 'maps' array so we only have to map the memory once.
  211. // There can be multiple constants within a single constant buffer. So mapping and
  212. // unmapping for each one is slow.
  213. map_data: d3d11.MAPPED_SUBRESOURCE
  214. ch(dc->Map(gpu_data, 0, .WRITE_DISCARD, {}, &map_data))
  215. maps[gpu_loc.buffer_idx] = map_data.pData
  216. }
  217. data_slice := slice.bytes_from_ptr(maps[gpu_loc.buffer_idx], gpu_buffer_info.size)
  218. dst := data_slice[gpu_loc.offset:gpu_loc.offset+u32(cpu_loc.size)]
  219. src := cpu_data[cpu_loc.offset:cpu_loc.offset+cpu_loc.size]
  220. copy(dst, src)
  221. }
  222. for &cb, cb_idx in d3d_shd.constant_buffers {
  223. if .Vertex in cb.bound_shaders {
  224. dc->VSSetConstantBuffers(cb.bind_point, 1, &cb.gpu_data)
  225. }
  226. if .Pixel in cb.bound_shaders {
  227. dc->PSSetConstantBuffers(cb.bind_point, 1, &cb.gpu_data)
  228. }
  229. if maps[cb_idx] != nil {
  230. dc->Unmap(cb.gpu_data, 0)
  231. maps[cb_idx] = nil
  232. }
  233. }
  234. viewport := d3d11.VIEWPORT{
  235. 0, 0,
  236. f32(s.width), f32(s.height),
  237. 0, 1,
  238. }
  239. dc->RSSetViewports(1, &viewport)
  240. dc->RSSetState(s.rasterizer_state)
  241. scissor_rect := d3d11.RECT {
  242. right = i32(s.width),
  243. bottom = i32(s.height),
  244. }
  245. if sciss, sciss_ok := scissor.?; sciss_ok {
  246. scissor_rect = d3d11.RECT {
  247. left = i32(sciss.x),
  248. top = i32(sciss.y),
  249. right = i32(sciss.x + sciss.w),
  250. bottom = i32(sciss.y + sciss.h),
  251. }
  252. }
  253. dc->RSSetScissorRects(1, &scissor_rect)
  254. dc->PSSetShader(d3d_shd.pixel_shader, nil, 0)
  255. if len(bound_textures) == len(d3d_shd.texture_bindings) {
  256. for t, t_idx in bound_textures {
  257. d3d_t := d3d_shd.texture_bindings[t_idx]
  258. if t := hm.get(&s.textures, t); t != nil {
  259. dc->PSSetShaderResources(d3d_t.bind_point, 1, &t.view)
  260. dc->PSSetSamplers(d3d_t.sampler_bind_point, 1, &t.sampler)
  261. }
  262. }
  263. }
  264. if rt := hm.get(&s.render_targets, render_target); rt != nil {
  265. dc->OMSetRenderTargets(1, &rt.render_target_view, rt.depth_stencil_texture_view)
  266. } else {
  267. dc->OMSetRenderTargets(1, &s.framebuffer_view, s.depth_buffer_view)
  268. }
  269. dc->OMSetDepthStencilState(s.depth_stencil_state, 0)
  270. dc->OMSetBlendState(s.blend_state, nil, ~u32(0))
  271. dc->Draw(u32(len(vertex_buffer)/shd.vertex_size), 0)
  272. dc->OMSetRenderTargets(0, nil, nil)
  273. log_messages()
  274. }
  275. d3d11_resize_swapchain :: proc(w, h: int) {
  276. s.depth_buffer->Release()
  277. s.depth_buffer_view->Release()
  278. s.framebuffer->Release()
  279. s.framebuffer_view->Release()
  280. s.swapchain->Release()
  281. s.width = w
  282. s.height = h
  283. create_swapchain(w, h)
  284. }
  285. d3d11_get_swapchain_width :: proc() -> int {
  286. return s.width
  287. }
  288. d3d11_get_swapchain_height :: proc() -> int {
  289. return s.height
  290. }
  291. d3d11_flip_z :: proc() -> bool {
  292. return true
  293. }
  294. d3d11_set_internal_state :: proc(state: rawptr) {
  295. s = (^D3D11_State)(state)
  296. }
  297. create_texture :: proc(
  298. width: int,
  299. height: int,
  300. format: Pixel_Format,
  301. data: rawptr,
  302. ) -> (
  303. Texture_Handle,
  304. ) {
  305. texture_desc := d3d11.TEXTURE2D_DESC{
  306. Width = u32(width),
  307. Height = u32(height),
  308. MipLevels = 1,
  309. ArraySize = 1,
  310. Format = dxgi_format_from_pixel_format(format),
  311. SampleDesc = {Count = 1},
  312. Usage = .DEFAULT,
  313. BindFlags = {.SHADER_RESOURCE},
  314. }
  315. texture: ^d3d11.ITexture2D
  316. if data != nil {
  317. texture_data := d3d11.SUBRESOURCE_DATA{
  318. pSysMem = data,
  319. SysMemPitch = u32(width * pixel_format_size(format)),
  320. }
  321. s.device->CreateTexture2D(&texture_desc, &texture_data, &texture)
  322. } else {
  323. s.device->CreateTexture2D(&texture_desc, nil, &texture)
  324. }
  325. texture_view: ^d3d11.IShaderResourceView
  326. s.device->CreateShaderResourceView(texture, nil, &texture_view)
  327. tex := D3D11_Texture {
  328. tex = texture,
  329. format = format,
  330. view = texture_view,
  331. sampler = create_sampler(.MIN_MAG_MIP_POINT),
  332. }
  333. return hm.add(&s.textures, tex)
  334. }
  335. d3d11_create_texture :: proc(width: int, height: int, format: Pixel_Format) -> Texture_Handle {
  336. return create_texture(width, height, format, nil)
  337. }
  338. d3d11_create_render_texture :: proc(width: int, height: int) -> (Texture_Handle, Render_Target_Handle) {
  339. texture_desc := d3d11.TEXTURE2D_DESC{
  340. Width = u32(width),
  341. Height = u32(height),
  342. MipLevels = 1,
  343. ArraySize = 1,
  344. Format = dxgi_format_from_pixel_format(.RGBA_32_Float),
  345. SampleDesc = {Count = 1},
  346. Usage = .DEFAULT,
  347. BindFlags = {.SHADER_RESOURCE, .RENDER_TARGET},
  348. }
  349. texture: ^d3d11.ITexture2D
  350. ch(s.device->CreateTexture2D(&texture_desc, nil, &texture))
  351. texture_view: ^d3d11.IShaderResourceView
  352. ch(s.device->CreateShaderResourceView(texture, nil, &texture_view))
  353. depth_stencil_desc := d3d11.TEXTURE2D_DESC{
  354. Width = u32(width),
  355. Height = u32(height),
  356. MipLevels = 1,
  357. ArraySize = 1,
  358. Format = .D24_UNORM_S8_UINT,
  359. SampleDesc = {Count = 1},
  360. Usage = .DEFAULT,
  361. BindFlags = {.DEPTH_STENCIL},
  362. }
  363. depth_stencil_texture: ^d3d11.ITexture2D
  364. ch(ch(s.device->CreateTexture2D(&depth_stencil_desc, nil, &depth_stencil_texture)))
  365. depth_stencil_texture_view: ^d3d11.IDepthStencilView
  366. ch(s.device->CreateDepthStencilView(depth_stencil_texture, nil, &depth_stencil_texture_view))
  367. render_target_view_desc := d3d11.RENDER_TARGET_VIEW_DESC {
  368. Format = texture_desc.Format,
  369. ViewDimension = .TEXTURE2D,
  370. }
  371. render_target_view: ^d3d11.IRenderTargetView
  372. ch(s.device->CreateRenderTargetView(texture, &render_target_view_desc, &render_target_view))
  373. d3d11_texture := D3D11_Texture {
  374. tex = texture,
  375. view = texture_view,
  376. format = .RGBA_32_Float,
  377. sampler = create_sampler(.MIN_MAG_MIP_POINT),
  378. }
  379. d3d11_render_target := D3D11_Render_Target {
  380. depth_stencil_texture = depth_stencil_texture,
  381. depth_stencil_texture_view = depth_stencil_texture_view,
  382. render_target_view = render_target_view,
  383. }
  384. return hm.add(&s.textures, d3d11_texture), hm.add(&s.render_targets, d3d11_render_target)
  385. }
  386. d3d11_destroy_render_target :: proc(render_target: Render_Target_Handle) {
  387. if rt := hm.get(&s.render_targets, render_target); rt != nil {
  388. rt.depth_stencil_texture->Release()
  389. rt.depth_stencil_texture_view->Release()
  390. rt.render_target_view->Release()
  391. }
  392. hm.remove(&s.render_targets, render_target)
  393. }
  394. d3d11_load_texture :: proc(data: []u8, width: int, height: int, format: Pixel_Format) -> Texture_Handle {
  395. return create_texture(width, height, format, raw_data(data))
  396. }
  397. d3d11_update_texture :: proc(th: Texture_Handle, data: []u8, rect: Rect) -> bool {
  398. tex := hm.get(&s.textures, th)
  399. if tex == nil || tex.tex == nil {
  400. log.errorf("Trying to update texture %v with new data, but it is invalid.", th)
  401. return false
  402. }
  403. box := d3d11.BOX {
  404. left = u32(rect.x),
  405. top = u32(rect.y),
  406. bottom = u32(rect.y + rect.h),
  407. right = u32(rect.x + rect.w),
  408. back = 1,
  409. front = 0,
  410. }
  411. row_pitch := pixel_format_size(tex.format) * int(rect.w)
  412. s.device_context->UpdateSubresource(tex.tex, 0, &box, raw_data(data), u32(row_pitch), 0)
  413. return true
  414. }
  415. d3d11_destroy_texture :: proc(th: Texture_Handle) {
  416. if t := hm.get(&s.textures, th); t != nil {
  417. t.tex->Release()
  418. t.view->Release()
  419. if t.sampler != nil {
  420. t.sampler->Release()
  421. }
  422. }
  423. hm.remove(&s.textures, th)
  424. }
  425. d3d11_set_texture_filter :: proc(
  426. th: Texture_Handle,
  427. scale_down_filter: Texture_Filter,
  428. scale_up_filter: Texture_Filter,
  429. mip_filter: Texture_Filter,
  430. ) {
  431. t := hm.get(&s.textures, th)
  432. if t == nil {
  433. log.error("Trying to set texture filter for invalid texture %v", th)
  434. return
  435. }
  436. d := scale_down_filter
  437. u := scale_up_filter
  438. m := mip_filter
  439. f: d3d11.FILTER
  440. if d == .Point && u == .Point && m == .Point {
  441. f = .MIN_MAG_MIP_POINT
  442. } else if d == .Linear && u == .Linear && m == .Linear {
  443. f = .MIN_MAG_MIP_LINEAR
  444. } else if d == .Point && u == .Point && m == .Linear {
  445. f = .MIN_MAG_POINT_MIP_LINEAR
  446. } else if d == .Point && u == .Linear && m == .Linear {
  447. f = .MIN_POINT_MAG_MIP_LINEAR
  448. } else if d == .Linear && u == .Linear && m == .Linear {
  449. f = .MIN_MAG_MIP_LINEAR
  450. } else if d == .Linear && u == .Linear && m == .Point {
  451. f = .MIN_MAG_LINEAR_MIP_POINT
  452. } else if d == .Linear && u == .Point && m == .Point {
  453. f = .MIN_LINEAR_MAG_MIP_POINT
  454. } else if d == .Linear && u == .Point && m == .Linear {
  455. f = .MIN_LINEAR_MAG_POINT_MIP_LINEAR
  456. } else if d == .Point && u == .Linear && m == .Point {
  457. f = .MIN_POINT_MAG_LINEAR_MIP_POINT
  458. }
  459. if t.sampler != nil {
  460. t.sampler->Release()
  461. }
  462. t.sampler = create_sampler(f)
  463. }
  464. create_sampler :: proc(filter: d3d11.FILTER) -> ^d3d11.ISamplerState {
  465. sampler_desc := d3d11.SAMPLER_DESC{
  466. Filter = filter,
  467. AddressU = .WRAP,
  468. AddressV = .WRAP,
  469. AddressW = .WRAP,
  470. ComparisonFunc = .NEVER,
  471. }
  472. smp: ^d3d11.ISamplerState
  473. ch(s.device->CreateSamplerState(&sampler_desc, &smp))
  474. return smp
  475. }
  476. d3d11_load_shader :: proc(
  477. vs_source: string,
  478. ps_source: string,
  479. desc_allocator := frame_allocator,
  480. layout_formats: []Pixel_Format = {},
  481. ) -> (
  482. handle: Shader_Handle,
  483. desc: Shader_Desc,
  484. ) {
  485. vs_blob: ^d3d11.IBlob
  486. vs_blob_errors: ^d3d11.IBlob
  487. ch(d3d_compiler.Compile(raw_data(vs_source), len(vs_source), nil, nil, nil, "vs_main", "vs_5_0", 0, 0, &vs_blob, &vs_blob_errors))
  488. if vs_blob_errors != nil {
  489. log.error("Failed compiling shader:")
  490. log.error(strings.string_from_ptr((^u8)(vs_blob_errors->GetBufferPointer()), int(vs_blob_errors->GetBufferSize())))
  491. return
  492. }
  493. // VERTEX SHADER
  494. vertex_shader: ^d3d11.IVertexShader
  495. ch(s.device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), nil, &vertex_shader))
  496. vs_ref: ^d3d11.IShaderReflection
  497. ch(d3d_compiler.Reflect(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), d3d11.ID3D11ShaderReflection_UUID, (^rawptr)(&vs_ref)))
  498. vs_desc: d3d11.SHADER_DESC
  499. ch(vs_ref->GetDesc(&vs_desc))
  500. {
  501. desc.inputs = make([]Shader_Input, vs_desc.InputParameters, desc_allocator)
  502. assert(len(layout_formats) == 0 || len(layout_formats) == len(desc.inputs))
  503. for in_idx in 0..<vs_desc.InputParameters {
  504. in_desc: d3d11.SIGNATURE_PARAMETER_DESC
  505. if ch(vs_ref->GetInputParameterDesc(in_idx, &in_desc)) < 0 {
  506. log.errorf("Invalid shader input: %v", in_idx)
  507. continue
  508. }
  509. type: Shader_Input_Type
  510. if in_desc.SemanticIndex > 0 {
  511. log.errorf("Matrix shader input types not yet implemented")
  512. continue
  513. }
  514. switch in_desc.ComponentType {
  515. case .UNKNOWN: log.errorf("Unknown component type")
  516. case .UINT32: log.errorf("Not implemented")
  517. case .SINT32: log.errorf("Not implemented")
  518. case .FLOAT32:
  519. switch in_desc.Mask {
  520. case 0: log.errorf("Invalid input mask"); continue
  521. case 1: type = .F32
  522. case 3: type = .Vec2
  523. case 7: type = .Vec3
  524. case 15: type = .Vec4
  525. }
  526. }
  527. name := strings.clone_from_cstring(in_desc.SemanticName, desc_allocator)
  528. format := len(layout_formats) > 0 ? layout_formats[in_idx] : get_shader_input_format(name, type)
  529. desc.inputs[in_idx] = {
  530. name = name,
  531. register = int(in_idx),
  532. format = format,
  533. type = type,
  534. }
  535. }
  536. }
  537. constant_descs := make([dynamic]Shader_Constant_Desc, desc_allocator)
  538. d3d_constants := make([dynamic]D3D11_Shader_Constant, s.allocator)
  539. d3d_constant_buffers := make([dynamic]D3D11_Shader_Constant_Buffer, s.allocator)
  540. d3d_texture_bindings := make([dynamic]D3D11_Texture_Binding, s.allocator)
  541. texture_bindpoint_descs := make([dynamic]Shader_Texture_Bindpoint_Desc, desc_allocator)
  542. reflect_shader_constants(
  543. vs_desc,
  544. vs_ref,
  545. &constant_descs,
  546. &d3d_constants,
  547. &d3d_constant_buffers,
  548. &d3d_texture_bindings,
  549. &texture_bindpoint_descs,
  550. desc_allocator,
  551. .Vertex,
  552. )
  553. input_layout_desc := make([]d3d11.INPUT_ELEMENT_DESC, len(desc.inputs), frame_allocator)
  554. for idx in 0..<len(desc.inputs) {
  555. input := desc.inputs[idx]
  556. input_layout_desc[idx] = {
  557. SemanticName = frame_cstring(input.name),
  558. Format = dxgi_format_from_pixel_format(input.format),
  559. AlignedByteOffset = idx == 0 ? 0 : d3d11.APPEND_ALIGNED_ELEMENT,
  560. InputSlotClass = .VERTEX_DATA,
  561. }
  562. }
  563. input_layout: ^d3d11.IInputLayout
  564. ch(s.device->CreateInputLayout(raw_data(input_layout_desc), u32(len(input_layout_desc)), vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), &input_layout))
  565. // PIXEL SHADER
  566. ps_blob: ^d3d11.IBlob
  567. ps_blob_errors: ^d3d11.IBlob
  568. ch(d3d_compiler.Compile(raw_data(ps_source), len(ps_source), nil, nil, nil, "ps_main", "ps_5_0", 0, 0, &ps_blob, &ps_blob_errors))
  569. if ps_blob_errors != nil {
  570. log.error("Failed compiling shader:")
  571. log.error(strings.string_from_ptr((^u8)(ps_blob_errors->GetBufferPointer()), int(ps_blob_errors->GetBufferSize())))
  572. return
  573. }
  574. pixel_shader: ^d3d11.IPixelShader
  575. ch(s.device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), nil, &pixel_shader))
  576. ps_ref: ^d3d11.IShaderReflection
  577. ch(d3d_compiler.Reflect(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), d3d11.ID3D11ShaderReflection_UUID, (^rawptr)(&ps_ref)))
  578. ps_desc: d3d11.SHADER_DESC
  579. ch(ps_ref->GetDesc(&ps_desc))
  580. reflect_shader_constants(
  581. ps_desc,
  582. ps_ref,
  583. &constant_descs,
  584. &d3d_constants,
  585. &d3d_constant_buffers,
  586. &d3d_texture_bindings,
  587. &texture_bindpoint_descs,
  588. desc_allocator,
  589. .Pixel,
  590. )
  591. // Done with vertex and pixel shader. Just combine all the state.
  592. desc.constants = constant_descs[:]
  593. desc.texture_bindpoints = texture_bindpoint_descs[:]
  594. d3d_shd := D3D11_Shader {
  595. constants = d3d_constants[:],
  596. constant_buffers = d3d_constant_buffers[:],
  597. vertex_shader = vertex_shader,
  598. pixel_shader = pixel_shader,
  599. input_layout = input_layout,
  600. texture_bindings = d3d_texture_bindings[:],
  601. }
  602. h := hm.add(&s.shaders, d3d_shd)
  603. return h, desc
  604. }
  605. D3D11_Shader_Type :: enum {
  606. Vertex,
  607. Pixel,
  608. }
  609. reflect_shader_constants :: proc(
  610. d3d_desc: d3d11.SHADER_DESC,
  611. ref: ^d3d11.IShaderReflection,
  612. constant_descs: ^[dynamic]Shader_Constant_Desc,
  613. d3d_constants: ^[dynamic]D3D11_Shader_Constant,
  614. d3d_constant_buffers: ^[dynamic]D3D11_Shader_Constant_Buffer,
  615. d3d_texture_bindings: ^[dynamic]D3D11_Texture_Binding,
  616. texture_bindpoint_descs: ^[dynamic]Shader_Texture_Bindpoint_Desc,
  617. desc_allocator: runtime.Allocator,
  618. shader_type: D3D11_Shader_Type,
  619. ) {
  620. found_sampler_bindpoints := make([dynamic]u32, frame_allocator)
  621. for br_idx in 0..<d3d_desc.BoundResources {
  622. bind_desc: d3d11.SHADER_INPUT_BIND_DESC
  623. ref->GetResourceBindingDesc(br_idx, &bind_desc)
  624. #partial switch bind_desc.Type {
  625. case .SAMPLER:
  626. append(&found_sampler_bindpoints, bind_desc.BindPoint)
  627. case .TEXTURE:
  628. append(d3d_texture_bindings, D3D11_Texture_Binding {
  629. bind_point = bind_desc.BindPoint,
  630. })
  631. append(texture_bindpoint_descs, Shader_Texture_Bindpoint_Desc {
  632. name = strings.clone_from_cstring(bind_desc.Name, desc_allocator),
  633. })
  634. case .CBUFFER:
  635. cb_info := ref->GetConstantBufferByName(bind_desc.Name)
  636. if cb_info == nil {
  637. continue
  638. }
  639. cb_desc: d3d11.SHADER_BUFFER_DESC
  640. cb_info->GetDesc(&cb_desc)
  641. if cb_desc.Size == 0 {
  642. continue
  643. }
  644. constant_buffer_desc := d3d11.BUFFER_DESC{
  645. ByteWidth = cb_desc.Size,
  646. Usage = .DYNAMIC,
  647. BindFlags = {.CONSTANT_BUFFER},
  648. CPUAccessFlags = {.WRITE},
  649. }
  650. buffer_idx := -1
  651. for &existing, existing_idx in d3d_constant_buffers {
  652. if existing.bind_point == bind_desc.BindPoint {
  653. existing.bound_shaders += {shader_type}
  654. buffer_idx = existing_idx
  655. break
  656. }
  657. }
  658. if buffer_idx == -1 {
  659. buffer_idx = len(d3d_constant_buffers)
  660. buf := D3D11_Shader_Constant_Buffer {
  661. bound_shaders = {shader_type},
  662. }
  663. ch(s.device->CreateBuffer(&constant_buffer_desc, nil, &buf.gpu_data))
  664. buf.size = int(cb_desc.Size)
  665. buf.bind_point = bind_desc.BindPoint
  666. append(d3d_constant_buffers, buf)
  667. }
  668. for var_idx in 0..<cb_desc.Variables {
  669. var_info := cb_info->GetVariableByIndex(var_idx)
  670. if var_info == nil {
  671. continue
  672. }
  673. var_desc: d3d11.SHADER_VARIABLE_DESC
  674. var_info->GetDesc(&var_desc)
  675. if var_desc.Name != "" {
  676. append(constant_descs, Shader_Constant_Desc {
  677. name = strings.clone_from_cstring(var_desc.Name, desc_allocator),
  678. size = int(var_desc.Size),
  679. })
  680. append(d3d_constants, D3D11_Shader_Constant {
  681. buffer_idx = u32(buffer_idx),
  682. offset = var_desc.StartOffset,
  683. })
  684. }
  685. }
  686. case:
  687. log.errorf("Type is %v", bind_desc.Type)
  688. }
  689. }
  690. // Make sure each texture has a sampler. In GL samplers are associated with textures. In D3D11
  691. // several textures can use a single sampler. We don't want this as we want to be able to
  692. // configure filters etc on a per-texture level. Since two textures can arrive at a draw call
  693. // with different filters set, if they use the same sampler, then it will be impossible to set
  694. // that filtering up.
  695. for t, t_idx in d3d_texture_bindings {
  696. found := false
  697. for sampler_bindpoint in found_sampler_bindpoints {
  698. if t.bind_point == sampler_bindpoint {
  699. found = true
  700. break
  701. }
  702. }
  703. if !found {
  704. log.errorf(
  705. "Texture %v at bindpoint %v does not have a dedicated sampler at " +
  706. "the sampler register with the same bindpoint number. This is required to " +
  707. "in order to make D3D11 behave the same way as OpenGL etc",
  708. texture_bindpoint_descs[t_idx].name,
  709. t.bind_point,
  710. )
  711. }
  712. }
  713. }
  714. d3d11_destroy_shader :: proc(h: Shader_Handle) {
  715. shd := hm.get(&s.shaders, h)
  716. if shd == nil {
  717. log.errorf("Invalid shader: %v", h)
  718. return
  719. }
  720. shd.input_layout->Release()
  721. shd.vertex_shader->Release()
  722. shd.pixel_shader->Release()
  723. for c in shd.constant_buffers {
  724. if c.gpu_data != nil {
  725. c.gpu_data->Release()
  726. }
  727. }
  728. delete(shd.texture_bindings, s.allocator)
  729. delete(shd.constants, s.allocator)
  730. delete(shd.constant_buffers, s.allocator)
  731. hm.remove(&s.shaders, h)
  732. }
  733. // API END
  734. s: ^D3D11_State
  735. D3D11_Shader_Constant_Buffer :: struct {
  736. gpu_data: ^d3d11.IBuffer,
  737. size: int,
  738. bound_shaders: bit_set[D3D11_Shader_Type],
  739. bind_point: u32,
  740. }
  741. D3D11_Texture_Binding :: struct {
  742. bind_point: u32,
  743. sampler_bind_point: u32,
  744. }
  745. D3D11_Shader_Constant :: struct {
  746. buffer_idx: u32,
  747. offset: u32,
  748. }
  749. D3D11_Shader :: struct {
  750. handle: Shader_Handle,
  751. vertex_shader: ^d3d11.IVertexShader,
  752. pixel_shader: ^d3d11.IPixelShader,
  753. input_layout: ^d3d11.IInputLayout,
  754. constant_buffers: []D3D11_Shader_Constant_Buffer,
  755. constants: []D3D11_Shader_Constant,
  756. texture_bindings: []D3D11_Texture_Binding,
  757. }
  758. D3D11_State :: struct {
  759. allocator: runtime.Allocator,
  760. window_handle: dxgi.HWND,
  761. width: int,
  762. height: int,
  763. dxgi_adapter: ^dxgi.IAdapter,
  764. swapchain: ^dxgi.ISwapChain1,
  765. framebuffer_view: ^d3d11.IRenderTargetView,
  766. depth_buffer_view: ^d3d11.IDepthStencilView,
  767. device_context: ^d3d11.IDeviceContext,
  768. depth_stencil_state: ^d3d11.IDepthStencilState,
  769. rasterizer_state: ^d3d11.IRasterizerState,
  770. device: ^d3d11.IDevice,
  771. depth_buffer: ^d3d11.ITexture2D,
  772. framebuffer: ^d3d11.ITexture2D,
  773. blend_state: ^d3d11.IBlendState,
  774. textures: hm.Handle_Map(D3D11_Texture, Texture_Handle, 1024*10),
  775. render_targets: hm.Handle_Map(D3D11_Render_Target, Render_Target_Handle, 1024*10),
  776. shaders: hm.Handle_Map(D3D11_Shader, Shader_Handle, 1024*10),
  777. info_queue: ^d3d11.IInfoQueue,
  778. vertex_buffer_gpu: ^d3d11.IBuffer,
  779. all_samplers: map[^d3d11.ISamplerState]struct{},
  780. }
  781. create_swapchain :: proc(w, h: int) {
  782. swapchain_desc := dxgi.SWAP_CHAIN_DESC1 {
  783. Width = u32(w),
  784. Height = u32(h),
  785. Format = .B8G8R8A8_UNORM,
  786. SampleDesc = {
  787. Count = 1,
  788. },
  789. BufferUsage = {.RENDER_TARGET_OUTPUT},
  790. BufferCount = 2,
  791. Scaling = .STRETCH,
  792. SwapEffect = .DISCARD,
  793. }
  794. dxgi_factory: ^dxgi.IFactory2
  795. ch(s.dxgi_adapter->GetParent(dxgi.IFactory2_UUID, (^rawptr)(&dxgi_factory)))
  796. ch(dxgi_factory->CreateSwapChainForHwnd(s.device, s.window_handle, &swapchain_desc, nil, nil, &s.swapchain))
  797. ch(s.swapchain->GetBuffer(0, d3d11.ITexture2D_UUID, (^rawptr)(&s.framebuffer)))
  798. ch(s.device->CreateRenderTargetView(s.framebuffer, nil, &s.framebuffer_view))
  799. depth_buffer_desc: d3d11.TEXTURE2D_DESC
  800. s.framebuffer->GetDesc(&depth_buffer_desc)
  801. depth_buffer_desc.Format = .D24_UNORM_S8_UINT
  802. depth_buffer_desc.BindFlags = {.DEPTH_STENCIL}
  803. ch(s.device->CreateTexture2D(&depth_buffer_desc, nil, &s.depth_buffer))
  804. ch(s.device->CreateDepthStencilView(s.depth_buffer, nil, &s.depth_buffer_view))
  805. s.device_context->ClearDepthStencilView(s.depth_buffer_view, {.DEPTH}, 1, 0)
  806. }
  807. D3D11_Texture :: struct {
  808. handle: Texture_Handle,
  809. tex: ^d3d11.ITexture2D,
  810. view: ^d3d11.IShaderResourceView,
  811. format: Pixel_Format,
  812. // It may seem strange that we have a sampler here. But samplers are reused if you recreate them
  813. // with the same options. D3D11 will return the same object. So each time we set the filter
  814. // mode or the UV wrapping settings, then we just ask D3D11 for the sampler state for those
  815. // settings.
  816. //
  817. // Moreover, in order to make D3D11 behave a bit like GL (or rather, to make them behave more
  818. // similarly), we require that each texture in the HLSL shaders have a dedicated sampler.
  819. sampler: ^d3d11.ISamplerState,
  820. }
  821. D3D11_Render_Target :: struct {
  822. handle: Render_Target_Handle,
  823. depth_stencil_texture: ^d3d11.ITexture2D,
  824. depth_stencil_texture_view: ^d3d11.IDepthStencilView,
  825. render_target_view: ^d3d11.IRenderTargetView,
  826. }
  827. dxgi_format_from_pixel_format :: proc(f: Pixel_Format) -> dxgi.FORMAT {
  828. switch f {
  829. case .Unknown: return .UNKNOWN
  830. case .RGBA_32_Float: return .R32G32B32A32_FLOAT
  831. case .RGB_32_Float: return .R32G32B32_FLOAT
  832. case .RG_32_Float: return .R32G32_FLOAT
  833. case .R_32_Float: return .R32_FLOAT
  834. case .RGBA_8_Norm: return .R8G8B8A8_UNORM
  835. case .RG_8_Norm: return .R8G8_UNORM
  836. case .R_8_Norm: return .R8_UNORM
  837. case .R_8_UInt: return .R8_UINT
  838. }
  839. log.error("Unknown format")
  840. return .UNKNOWN
  841. }
  842. // CHeck win errors and print message log if there is any error
  843. ch :: proc(hr: dxgi.HRESULT, loc := #caller_location) -> dxgi.HRESULT {
  844. if hr >= 0 {
  845. return hr
  846. }
  847. log.errorf("d3d11 error: %0x", u32(hr), location = loc)
  848. log_messages(loc)
  849. return hr
  850. }
  851. log_messages :: proc(loc := #caller_location) {
  852. iq := s.info_queue
  853. if iq == nil {
  854. return
  855. }
  856. n := iq->GetNumStoredMessages()
  857. longest_msg: d3d11.SIZE_T
  858. for i in 0..=n {
  859. msglen: d3d11.SIZE_T
  860. iq->GetMessage(i, nil, &msglen)
  861. if msglen > longest_msg {
  862. longest_msg = msglen
  863. }
  864. }
  865. if longest_msg > 0 {
  866. msg_raw_ptr, _ := (mem.alloc(int(longest_msg), allocator = frame_allocator))
  867. for i in 0..=n {
  868. msglen: d3d11.SIZE_T
  869. iq->GetMessage(i, nil, &msglen)
  870. if msglen > 0 {
  871. msg := (^d3d11.MESSAGE)(msg_raw_ptr)
  872. iq->GetMessage(i, msg, &msglen)
  873. log.error(msg.pDescription, location = loc)
  874. }
  875. }
  876. }
  877. iq->ClearStoredMessages()
  878. }
  879. DEFAULT_SHADER_SOURCE :: #load("render_backend_d3d11_default_shader.hlsl")
  880. d3d11_default_shader_vertex_source :: proc() -> string {
  881. return string(DEFAULT_SHADER_SOURCE)
  882. }
  883. d3d11_default_shader_fragment_source :: proc() -> string {
  884. return string(DEFAULT_SHADER_SOURCE)
  885. }