karl2d_windows.odin 25 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078
  1. #+build windows
  2. package karl2d
  3. import "base:runtime"
  4. import win32 "core:sys/windows"
  5. import d3d11 "vendor:directx/d3d11"
  6. import dxgi "vendor:directx/dxgi"
  7. import "vendor:directx/d3d_compiler"
  8. import "core:strings"
  9. import "core:log"
  10. import "core:math/linalg"
  11. import "core:slice"
  12. import "core:mem"
  13. import "core:math"
  14. import "core:image"
  15. import hm "handle_map"
  16. import "core:image/bmp"
  17. import "core:image/png"
  18. import "core:image/tga"
  19. _ :: bmp
  20. _ :: png
  21. _ :: tga
  22. _init :: proc(width: int, height: int, title: string,
  23. allocator := context.allocator, loc := #caller_location) -> ^State {
  24. win32.SetProcessDPIAware()
  25. s = new(State, allocator, loc)
  26. s.allocator = allocator
  27. s.custom_context = context
  28. CLASS_NAME :: "karl2d"
  29. instance := win32.HINSTANCE(win32.GetModuleHandleW(nil))
  30. s.run = true
  31. s.width = width
  32. s.height = height
  33. cls := win32.WNDCLASSW {
  34. lpfnWndProc = window_proc,
  35. lpszClassName = CLASS_NAME,
  36. hInstance = instance,
  37. hCursor = win32.LoadCursorA(nil, win32.IDC_ARROW),
  38. }
  39. win32.RegisterClassW(&cls)
  40. r: win32.RECT
  41. r.right = i32(width)
  42. r.bottom = i32(height)
  43. style := win32.WS_OVERLAPPEDWINDOW | win32.WS_VISIBLE
  44. win32.AdjustWindowRect(&r, style, false)
  45. hwnd := win32.CreateWindowW(CLASS_NAME,
  46. win32.utf8_to_wstring(title),
  47. style,
  48. 100, 10, r.right - r.left, r.bottom - r.top,
  49. nil, nil, instance, nil)
  50. assert(hwnd != nil, "Failed creating window")
  51. feature_levels := [?]d3d11.FEATURE_LEVEL{
  52. ._11_1,
  53. ._11_0,
  54. }
  55. base_device: ^d3d11.IDevice
  56. base_device_context: ^d3d11.IDeviceContext
  57. device_flags := d3d11.CREATE_DEVICE_FLAGS {
  58. .BGRA_SUPPORT,
  59. }
  60. when ODIN_DEBUG {
  61. device_flags += { .DEBUG }
  62. }
  63. ch(d3d11.CreateDevice(
  64. nil,
  65. .HARDWARE,
  66. nil,
  67. device_flags,
  68. &feature_levels[0], len(feature_levels),
  69. d3d11.SDK_VERSION, &base_device, nil, &base_device_context))
  70. ch(base_device->QueryInterface(d3d11.IInfoQueue_UUID, (^rawptr)(&s.info_queue)))
  71. ch(base_device->QueryInterface(d3d11.IDevice_UUID, (^rawptr)(&s.device)))
  72. ch(base_device_context->QueryInterface(d3d11.IDeviceContext_UUID, (^rawptr)(&s.device_context)))
  73. dxgi_device: ^dxgi.IDevice
  74. ch(s.device->QueryInterface(dxgi.IDevice_UUID, (^rawptr)(&dxgi_device)))
  75. base_device->Release()
  76. base_device_context->Release()
  77. dxgi_adapter: ^dxgi.IAdapter
  78. ch(dxgi_device->GetAdapter(&dxgi_adapter))
  79. dxgi_device->Release()
  80. dxgi_factory: ^dxgi.IFactory2
  81. ch(dxgi_adapter->GetParent(dxgi.IFactory2_UUID, (^rawptr)(&dxgi_factory)))
  82. swapchain_desc := dxgi.SWAP_CHAIN_DESC1 {
  83. Format = .B8G8R8A8_UNORM,
  84. SampleDesc = {
  85. Count = 1,
  86. },
  87. BufferUsage = {.RENDER_TARGET_OUTPUT},
  88. BufferCount = 2,
  89. Scaling = .STRETCH,
  90. SwapEffect = .DISCARD,
  91. }
  92. ch(dxgi_factory->CreateSwapChainForHwnd(s.device, hwnd, &swapchain_desc, nil, nil, &s.swapchain))
  93. ch(s.swapchain->GetBuffer(0, d3d11.ITexture2D_UUID, (^rawptr)(&s.framebuffer)))
  94. ch(s.device->CreateRenderTargetView(s.framebuffer, nil, &s.framebuffer_view))
  95. depth_buffer_desc: d3d11.TEXTURE2D_DESC
  96. s.framebuffer->GetDesc(&depth_buffer_desc)
  97. depth_buffer_desc.Format = .D24_UNORM_S8_UINT
  98. depth_buffer_desc.BindFlags = {.DEPTH_STENCIL}
  99. ch(s.device->CreateTexture2D(&depth_buffer_desc, nil, &s.depth_buffer))
  100. ch(s.device->CreateDepthStencilView(s.depth_buffer, nil, &s.depth_buffer_view))
  101. rasterizer_desc := d3d11.RASTERIZER_DESC{
  102. FillMode = .SOLID,
  103. CullMode = .BACK,
  104. }
  105. ch(s.device->CreateRasterizerState(&rasterizer_desc, &s.rasterizer_state))
  106. depth_stencil_desc := d3d11.DEPTH_STENCIL_DESC{
  107. DepthEnable = false,
  108. DepthWriteMask = .ALL,
  109. DepthFunc = .LESS,
  110. }
  111. ch(s.device->CreateDepthStencilState(&depth_stencil_desc, &s.depth_stencil_state))
  112. vertex_buffer_desc := d3d11.BUFFER_DESC{
  113. ByteWidth = VERTEX_BUFFER_MAX * size_of(Vertex),
  114. Usage = .DYNAMIC,
  115. BindFlags = {.VERTEX_BUFFER},
  116. CPUAccessFlags = {.WRITE},
  117. }
  118. ch(s.device->CreateBuffer(&vertex_buffer_desc, nil, &s.vertex_buffer_gpu))
  119. s.vertex_buffer_cpu = make([]Vertex, VERTEX_BUFFER_MAX, allocator, loc)
  120. blend_desc := d3d11.BLEND_DESC {
  121. RenderTarget = {
  122. 0 = {
  123. BlendEnable = true,
  124. SrcBlend = .SRC_ALPHA,
  125. DestBlend = .INV_SRC_ALPHA,
  126. BlendOp = .ADD,
  127. SrcBlendAlpha = .ONE,
  128. DestBlendAlpha = .ZERO,
  129. BlendOpAlpha = .ADD,
  130. RenderTargetWriteMask = u8(d3d11.COLOR_WRITE_ENABLE_ALL),
  131. },
  132. },
  133. }
  134. ch(s.device->CreateBlendState(&blend_desc, &s.blend_state))
  135. s.proj_matrix = make_default_projection(s.width, s.height)
  136. s.view_matrix = 1
  137. sampler_desc := d3d11.SAMPLER_DESC{
  138. Filter = .MIN_MAG_MIP_POINT,
  139. AddressU = .WRAP,
  140. AddressV = .WRAP,
  141. AddressW = .WRAP,
  142. ComparisonFunc = .NEVER,
  143. }
  144. s.device->CreateSamplerState(&sampler_desc, &s.sampler_state)
  145. s.default_shader = _load_shader(string(shader_hlsl))
  146. white_rect: [16*16*4]u8
  147. slice.fill(white_rect[:], 255)
  148. s.shape_drawing_texture = _load_texture_from_memory(white_rect[:], 16, 16)
  149. return s
  150. }
  151. shader_hlsl :: #load("shader.hlsl")
  152. Vertex :: struct {
  153. pos: Vec2,
  154. uv: Vec2,
  155. color: Color,
  156. }
  157. s: ^State
  158. VERTEX_BUFFER_MAX :: 10000
  159. Handle :: hm.Handle
  160. Texture_Handle :: distinct hm.Handle
  161. TEXTURE_NONE :: Texture_Handle {}
  162. Shader_Constant_Buffer :: struct {
  163. gpu_data: ^d3d11.IBuffer,
  164. cpu_data: []u8,
  165. }
  166. Shader_Builtin_Constant :: enum {
  167. MVP,
  168. }
  169. Shader :: struct {
  170. handle: Shader_Handle,
  171. vertex_shader: ^d3d11.IVertexShader,
  172. pixel_shader: ^d3d11.IPixelShader,
  173. input_layout: ^d3d11.IInputLayout,
  174. constant_buffers: []Shader_Constant_Buffer,
  175. constant_lookup: map[string]Shader_Constant_Location,
  176. constant_builtin_locations: [Shader_Builtin_Constant]Maybe(Shader_Constant_Location),
  177. }
  178. State :: struct {
  179. swapchain: ^dxgi.ISwapChain1,
  180. framebuffer_view: ^d3d11.IRenderTargetView,
  181. depth_buffer_view: ^d3d11.IDepthStencilView,
  182. device_context: ^d3d11.IDeviceContext,
  183. depth_stencil_state: ^d3d11.IDepthStencilState,
  184. rasterizer_state: ^d3d11.IRasterizerState,
  185. device: ^d3d11.IDevice,
  186. depth_buffer: ^d3d11.ITexture2D,
  187. framebuffer: ^d3d11.ITexture2D,
  188. blend_state: ^d3d11.IBlendState,
  189. shape_drawing_texture: Texture,
  190. sampler_state: ^d3d11.ISamplerState,
  191. default_shader: Shader_Handle,
  192. textures: hm.Handle_Map(_Texture, Texture_Handle, 1024*10),
  193. shaders: hm.Handle_Map(Shader, Shader_Handle, 1024*10),
  194. info_queue: ^d3d11.IInfoQueue,
  195. vertex_buffer_gpu: ^d3d11.IBuffer,
  196. vertex_buffer_cpu: []Vertex,
  197. vertex_buffer_cpu_count: int,
  198. vertex_buffer_offset: int,
  199. run: bool,
  200. custom_context: runtime.Context,
  201. allocator: runtime.Allocator,
  202. batch_texture: Texture_Handle,
  203. batch_camera: Maybe(Camera),
  204. batch_shader: Shader_Handle,
  205. width: int,
  206. height: int,
  207. keys_went_down: #sparse [Keyboard_Key]bool,
  208. keys_went_up: #sparse [Keyboard_Key]bool,
  209. keys_is_held: #sparse [Keyboard_Key]bool,
  210. view_matrix: matrix[4,4]f32,
  211. proj_matrix: matrix[4,4]f32,
  212. }
  213. VK_MAP := [255]Keyboard_Key {
  214. win32.VK_A = .A,
  215. win32.VK_B = .B,
  216. win32.VK_C = .C,
  217. win32.VK_D = .D,
  218. win32.VK_E = .E,
  219. win32.VK_F = .F,
  220. win32.VK_G = .G,
  221. win32.VK_H = .H,
  222. win32.VK_I = .I,
  223. win32.VK_J = .J,
  224. win32.VK_K = .K,
  225. win32.VK_L = .L,
  226. win32.VK_M = .M,
  227. win32.VK_N = .N,
  228. win32.VK_O = .O,
  229. win32.VK_P = .P,
  230. win32.VK_Q = .Q,
  231. win32.VK_R = .R,
  232. win32.VK_S = .S,
  233. win32.VK_T = .T,
  234. win32.VK_U = .U,
  235. win32.VK_V = .V,
  236. win32.VK_W = .W,
  237. win32.VK_X = .X,
  238. win32.VK_Y = .Y,
  239. win32.VK_Z = .Z,
  240. win32.VK_LEFT = .Left,
  241. win32.VK_RIGHT = .Right,
  242. win32.VK_UP = .Up,
  243. win32.VK_DOWN = .Down,
  244. }
  245. window_proc :: proc "stdcall" (hwnd: win32.HWND, msg: win32.UINT, wparam: win32.WPARAM, lparam: win32.LPARAM) -> win32.LRESULT {
  246. context = s.custom_context
  247. switch msg {
  248. case win32.WM_DESTROY:
  249. win32.PostQuitMessage(0)
  250. s.run = false
  251. case win32.WM_CLOSE:
  252. s.run = false
  253. case win32.WM_KEYDOWN:
  254. key := VK_MAP[wparam]
  255. s.keys_went_down[key] = true
  256. s.keys_is_held[key] = true
  257. case win32.WM_KEYUP:
  258. key := VK_MAP[wparam]
  259. s.keys_is_held[key] = false
  260. s.keys_went_up[key] = true
  261. }
  262. return win32.DefWindowProcW(hwnd, msg, wparam, lparam)
  263. }
  264. _shutdown :: proc() {
  265. _destroy_texture(s.shape_drawing_texture)
  266. _destroy_shader(s.default_shader)
  267. s.sampler_state->Release()
  268. s.framebuffer_view->Release()
  269. s.depth_buffer_view->Release()
  270. s.depth_buffer->Release()
  271. s.framebuffer->Release()
  272. s.device_context->Release()
  273. s.vertex_buffer_gpu->Release()
  274. //s.constant_buffer->Release()
  275. s.depth_stencil_state->Release()
  276. s.rasterizer_state->Release()
  277. s.swapchain->Release()
  278. s.blend_state->Release()
  279. delete(s.vertex_buffer_cpu, s.allocator)
  280. when ODIN_DEBUG {
  281. debug: ^d3d11.IDebug
  282. if ch(s.device->QueryInterface(d3d11.IDebug_UUID, (^rawptr)(&debug))) >= 0 {
  283. ch(debug->ReportLiveDeviceObjects({.DETAIL, .IGNORE_INTERNAL}))
  284. log_messages()
  285. }
  286. debug->Release()
  287. }
  288. s.device->Release()
  289. s.info_queue->Release()
  290. a := s.allocator
  291. free(s, a)
  292. s = nil
  293. }
  294. _set_internal_state :: proc(new_state: ^State) {
  295. s = new_state
  296. }
  297. Color_F32 :: [4]f32
  298. f32_color_from_color :: proc(color: Color) -> Color_F32 {
  299. return {
  300. f32(color.r) / 255,
  301. f32(color.g) / 255,
  302. f32(color.b) / 255,
  303. f32(color.a) / 255,
  304. }
  305. }
  306. _clear :: proc(color: Color) {
  307. c := f32_color_from_color(color)
  308. s.device_context->ClearRenderTargetView(s.framebuffer_view, &c)
  309. s.device_context->ClearDepthStencilView(s.depth_buffer_view, {.DEPTH}, 1, 0)
  310. }
  311. _Texture :: struct {
  312. handle: Texture_Handle,
  313. tex: ^d3d11.ITexture2D,
  314. view: ^d3d11.IShaderResourceView,
  315. }
  316. _load_texture_from_file :: proc(filename: string) -> Texture {
  317. img, img_err := image.load_from_file(filename, options = {.alpha_add_if_missing}, allocator = context.temp_allocator)
  318. if img_err != nil {
  319. log.errorf("Error loading texture %v: %v", filename, img_err)
  320. return {}
  321. }
  322. return _load_texture_from_memory(img.pixels.buf[:], img.width, img.height)
  323. }
  324. _load_texture_from_memory :: proc(data: []u8, width: int, height: int) -> Texture {
  325. texture_desc := d3d11.TEXTURE2D_DESC{
  326. Width = u32(width),
  327. Height = u32(height),
  328. MipLevels = 1,
  329. ArraySize = 1,
  330. // TODO: _SRGB or not?
  331. Format = .R8G8B8A8_UNORM,
  332. SampleDesc = {Count = 1},
  333. Usage = .IMMUTABLE,
  334. BindFlags = {.SHADER_RESOURCE},
  335. }
  336. texture_data := d3d11.SUBRESOURCE_DATA{
  337. pSysMem = raw_data(data),
  338. SysMemPitch = u32(width * 4),
  339. }
  340. texture: ^d3d11.ITexture2D
  341. s.device->CreateTexture2D(&texture_desc, &texture_data, &texture)
  342. texture_view: ^d3d11.IShaderResourceView
  343. s.device->CreateShaderResourceView(texture, nil, &texture_view)
  344. tex := _Texture {
  345. tex = texture,
  346. view = texture_view,
  347. }
  348. handle := hm.add(&s.textures, tex)
  349. return {
  350. id = handle,
  351. width = width,
  352. height = height,
  353. }
  354. }
  355. _destroy_texture :: proc(tex: Texture) {
  356. if t := hm.get(&s.textures, tex.id); t != nil {
  357. t.tex->Release()
  358. t.view->Release()
  359. }
  360. hm.remove(&s.textures, tex.id)
  361. }
  362. _draw_texture :: proc(tex: Texture, pos: Vec2, tint := WHITE) {
  363. _draw_texture_ex(
  364. tex,
  365. {0, 0, f32(tex.width), f32(tex.height)},
  366. {pos.x, pos.y, f32(tex.width), f32(tex.height)},
  367. {},
  368. 0,
  369. tint,
  370. )
  371. }
  372. _draw_texture_rect :: proc(tex: Texture, rect: Rect, pos: Vec2, tint := WHITE) {
  373. _draw_texture_ex(
  374. tex,
  375. rect,
  376. {pos.x, pos.y, rect.w, rect.h},
  377. {},
  378. 0,
  379. tint,
  380. )
  381. }
  382. batch_vertex :: proc(v: Vec2, uv: Vec2, color: Color) {
  383. v := v
  384. if s.vertex_buffer_cpu_count == len(s.vertex_buffer_cpu) {
  385. panic("Must dispatch here")
  386. }
  387. s.vertex_buffer_cpu[s.vertex_buffer_cpu_count] = {
  388. pos = v,
  389. uv = uv,
  390. color = color,
  391. }
  392. s.vertex_buffer_cpu_count += 1
  393. }
  394. _draw_texture_ex :: proc(tex: Texture, src: Rect, dst: Rect, origin: Vec2, rot: f32, tint := WHITE) {
  395. if tex.width == 0 || tex.height == 0 {
  396. return
  397. }
  398. if s.batch_texture != TEXTURE_NONE && s.batch_texture != tex.id {
  399. _draw_current_batch()
  400. }
  401. r := dst
  402. r.x -= origin.x
  403. r.y -= origin.y
  404. s.batch_texture = tex.id
  405. tl, tr, bl, br: Vec2
  406. // Rotation adapted from Raylib's "DrawTexturePro"
  407. if rot == 0 {
  408. x := dst.x - origin.x
  409. y := dst.y - origin.y
  410. tl = { x, y }
  411. tr = { x + dst.w, y }
  412. bl = { x, y + dst.h }
  413. br = { x + dst.w, y + dst.h }
  414. } else {
  415. sin_rot := math.sin(rot * math.RAD_PER_DEG)
  416. cos_rot := math.cos(rot * math.RAD_PER_DEG)
  417. x := dst.x
  418. y := dst.y
  419. dx := -origin.x
  420. dy := -origin.y
  421. tl = {
  422. x + dx * cos_rot - dy * sin_rot,
  423. y + dx * sin_rot + dy * cos_rot,
  424. }
  425. tr = {
  426. x + (dx + dst.w) * cos_rot - dy * sin_rot,
  427. y + (dx + dst.w) * sin_rot + dy * cos_rot,
  428. }
  429. bl = {
  430. x + dx * cos_rot - (dy + dst.h) * sin_rot,
  431. y + dx * sin_rot + (dy + dst.h) * cos_rot,
  432. }
  433. br = {
  434. x + (dx + dst.w) * cos_rot - (dy + dst.h) * sin_rot,
  435. y + (dx + dst.w) * sin_rot + (dy + dst.h) * cos_rot,
  436. }
  437. }
  438. ts := Vec2{f32(tex.width), f32(tex.height)}
  439. up := Vec2{src.x, src.y} / ts
  440. us := Vec2{src.w, src.h} / ts
  441. c := tint
  442. batch_vertex(tl, up, c)
  443. batch_vertex(tr, up + {us.x, 0}, c)
  444. batch_vertex(br, up + us, c)
  445. batch_vertex(tl, up, c)
  446. batch_vertex(br, up + us, c)
  447. batch_vertex(bl, up + {0, us.y}, c)
  448. }
  449. _draw_rectangle :: proc(r: Rect, c: Color) {
  450. if s.batch_texture != TEXTURE_NONE && s.batch_texture != s.shape_drawing_texture.id {
  451. _draw_current_batch()
  452. }
  453. s.batch_texture = s.shape_drawing_texture.id
  454. batch_vertex({r.x, r.y}, {0, 0}, c)
  455. batch_vertex({r.x + r.w, r.y}, {1, 0}, c)
  456. batch_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
  457. batch_vertex({r.x, r.y}, {0, 0}, c)
  458. batch_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
  459. batch_vertex({r.x, r.y + r.h}, {0, 1}, c)
  460. }
  461. _draw_rectangle_outline :: proc(r: Rect, thickness: f32, color: Color) {
  462. t := thickness
  463. // Based on DrawRectangleLinesEx from Raylib
  464. top := Rect {
  465. r.x,
  466. r.y,
  467. r.w,
  468. t,
  469. }
  470. bottom := Rect {
  471. r.x,
  472. r.y + r.h - t,
  473. r.w,
  474. t,
  475. }
  476. left := Rect {
  477. r.x,
  478. r.y + t,
  479. t,
  480. r.h - t * 2,
  481. }
  482. right := Rect {
  483. r.x + r.w - t,
  484. r.y + t,
  485. t,
  486. r.h - t * 2,
  487. }
  488. _draw_rectangle(top, color)
  489. _draw_rectangle(bottom, color)
  490. _draw_rectangle(left, color)
  491. _draw_rectangle(right, color)
  492. }
  493. _draw_circle :: proc(center: Vec2, radius: f32, color: Color) {
  494. }
  495. _draw_line :: proc(start: Vec2, end: Vec2, thickness: f32, color: Color) {
  496. }
  497. _get_screen_width :: proc() -> int {
  498. return s.width
  499. }
  500. _get_screen_height :: proc() -> int {
  501. return s.height
  502. }
  503. _key_went_down :: proc(key: Keyboard_Key) -> bool {
  504. return s.keys_went_down[key]
  505. }
  506. _key_went_up :: proc(key: Keyboard_Key) -> bool {
  507. return s.keys_went_up[key]
  508. }
  509. _key_is_held :: proc(key: Keyboard_Key) -> bool {
  510. return s.keys_is_held[key]
  511. }
  512. _window_should_close :: proc() -> bool {
  513. return !s.run
  514. }
  515. _draw_text :: proc(text: string, pos: Vec2, font_size: f32, color: Color) {
  516. }
  517. _mouse_button_pressed :: proc(button: Mouse_Button) -> bool {
  518. return false
  519. }
  520. _mouse_button_released :: proc(button: Mouse_Button) -> bool {
  521. return false
  522. }
  523. _mouse_button_held :: proc(button: Mouse_Button) -> bool {
  524. return false
  525. }
  526. _mouse_wheel_delta :: proc() -> f32 {
  527. return 0
  528. }
  529. _mouse_position :: proc() -> Vec2 {
  530. return {}
  531. }
  532. _enable_scissor :: proc(x, y, w, h: int) {
  533. }
  534. _disable_scissor :: proc() {
  535. }
  536. _set_window_size :: proc(width: int, height: int) {
  537. }
  538. _set_window_position :: proc(x: int, y: int) {
  539. }
  540. _screen_to_world :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  541. return pos
  542. }
  543. Vec3 :: [3]f32
  544. vec3_from_vec2 :: proc(v: Vec2) -> Vec3 {
  545. return {
  546. v.x, v.y, 0,
  547. }
  548. }
  549. _set_camera :: proc(camera: Maybe(Camera)) {
  550. if camera == s.batch_camera {
  551. return
  552. }
  553. _draw_current_batch()
  554. s.batch_camera = camera
  555. if c, c_ok := camera.?; c_ok {
  556. origin_trans := linalg.matrix4_translate(vec3_from_vec2(-c.origin))
  557. translate := linalg.matrix4_translate(vec3_from_vec2(c.target))
  558. rot := linalg.matrix4_rotate_f32(c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  559. camera_matrix := translate * rot * origin_trans
  560. s.view_matrix = linalg.inverse(camera_matrix)
  561. s.proj_matrix = make_default_projection(s.width, s.height)
  562. s.proj_matrix[0, 0] *= c.zoom
  563. s.proj_matrix[1, 1] *= c.zoom
  564. } else {
  565. s.proj_matrix = make_default_projection(s.width, s.height)
  566. s.view_matrix = 1
  567. }
  568. }
  569. _set_scissor_rect :: proc(scissor_rect: Maybe(Rect)) {
  570. }
  571. _set_shader :: proc(shader: Shader_Handle) {
  572. if shader == s.batch_shader {
  573. return
  574. }
  575. _draw_current_batch()
  576. s.batch_shader = shader
  577. }
  578. _set_shader_constant :: proc(shader: Shader_Handle, loc: Shader_Constant_Location, val: $T) {
  579. _draw_current_batch()
  580. shd := hm.get(&s.shaders, shader)
  581. if shd == nil {
  582. return
  583. }
  584. if int(loc.buffer_idx) >= len(shd.constant_buffers) {
  585. log.warnf("Constant buffer idx %v is out of bounds", loc.buffer_idx)
  586. return
  587. }
  588. b := &shd.constant_buffers[loc.buffer_idx]
  589. if int(loc.offset) + size_of(val) > len(b.cpu_data) {
  590. log.warnf("Constant buffer idx %v is trying to be written out of bounds by at offset %v with %v bytes", loc.buffer_idx, loc.offset, size_of(val))
  591. return
  592. }
  593. dst := (^T)(&b.cpu_data[loc.offset])
  594. dst^ = val
  595. }
  596. _set_shader_constant_mat4 :: proc(shader: Shader_Handle, loc: Shader_Constant_Location, val: matrix[4,4]f32) {
  597. _set_shader_constant(shader, loc, val)
  598. }
  599. _set_shader_constant_f32 :: proc(shader: Shader_Handle, loc: Shader_Constant_Location, val: f32) {
  600. _set_shader_constant(shader, loc, val)
  601. }
  602. _set_shader_constant_vec2 :: proc(shader: Shader_Handle, loc: Shader_Constant_Location, val: Vec2) {
  603. _set_shader_constant(shader, loc, val)
  604. }
  605. _process_events :: proc() {
  606. s.keys_went_up = {}
  607. s.keys_went_down = {}
  608. msg: win32.MSG
  609. for win32.PeekMessageW(&msg, nil, 0, 0, win32.PM_REMOVE) {
  610. win32.TranslateMessage(&msg)
  611. win32.DispatchMessageW(&msg)
  612. }
  613. }
  614. _draw_current_batch :: proc() {
  615. if s.vertex_buffer_cpu_count == s.vertex_buffer_offset {
  616. return
  617. }
  618. viewport := d3d11.VIEWPORT{
  619. 0, 0,
  620. f32(s.width), f32(s.height),
  621. 0, 1,
  622. }
  623. dc := s.device_context
  624. vb_data: d3d11.MAPPED_SUBRESOURCE
  625. ch(dc->Map(s.vertex_buffer_gpu, 0, .WRITE_NO_OVERWRITE, {}, &vb_data))
  626. {
  627. gpu_map := slice.from_ptr((^Vertex)(vb_data.pData), VERTEX_BUFFER_MAX)
  628. copy(
  629. gpu_map[s.vertex_buffer_offset:s.vertex_buffer_cpu_count],
  630. s.vertex_buffer_cpu[s.vertex_buffer_offset:s.vertex_buffer_cpu_count],
  631. )
  632. }
  633. dc->Unmap(s.vertex_buffer_gpu, 0)
  634. dc->IASetPrimitiveTopology(.TRIANGLELIST)
  635. shd := hm.get(&s.shaders, s.batch_shader)
  636. if shd == nil {
  637. shd = hm.get(&s.shaders, s.default_shader)
  638. assert(shd != nil, "Failed fetching default shader")
  639. }
  640. dc->IASetInputLayout(shd.input_layout)
  641. vertex_buffer_offset := u32(0)
  642. vertex_buffer_stride := u32(size_of(Vertex))
  643. dc->IASetVertexBuffers(0, 1, &s.vertex_buffer_gpu, &vertex_buffer_stride, &vertex_buffer_offset)
  644. for mloc, builtin in shd.constant_builtin_locations {
  645. loc, loc_ok := mloc.?
  646. if !loc_ok {
  647. continue
  648. }
  649. switch builtin {
  650. case .MVP:
  651. dst := (^matrix[4,4]f32)(&shd.constant_buffers[loc.buffer_idx].cpu_data[loc.offset])
  652. dst^ = s.proj_matrix * s.view_matrix
  653. }
  654. }
  655. dc->VSSetShader(shd.vertex_shader, nil, 0)
  656. for &c, c_idx in shd.constant_buffers {
  657. if c.gpu_data == nil {
  658. continue
  659. }
  660. cb_data: d3d11.MAPPED_SUBRESOURCE
  661. ch(dc->Map(c.gpu_data, 0, .WRITE_DISCARD, {}, &cb_data))
  662. mem.copy(cb_data.pData, raw_data(c.cpu_data), len(c.cpu_data))
  663. dc->Unmap(c.gpu_data, 0)
  664. dc->VSSetConstantBuffers(u32(c_idx), 1, &c.gpu_data)
  665. dc->PSSetConstantBuffers(u32(c_idx), 1, &c.gpu_data)
  666. }
  667. dc->RSSetViewports(1, &viewport)
  668. dc->RSSetState(s.rasterizer_state)
  669. dc->PSSetShader(shd.pixel_shader, nil, 0)
  670. if t := hm.get(&s.textures, s.batch_texture); t != nil {
  671. dc->PSSetShaderResources(0, 1, &t.view)
  672. }
  673. dc->PSSetSamplers(0, 1, &s.sampler_state)
  674. dc->OMSetRenderTargets(1, &s.framebuffer_view, s.depth_buffer_view)
  675. dc->OMSetDepthStencilState(s.depth_stencil_state, 0)
  676. dc->OMSetBlendState(s.blend_state, nil, ~u32(0))
  677. dc->Draw(u32(s.vertex_buffer_cpu_count - s.vertex_buffer_offset), u32(s.vertex_buffer_offset))
  678. s.vertex_buffer_offset = s.vertex_buffer_cpu_count
  679. log_messages()
  680. }
  681. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  682. return linalg.matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  683. }
  684. _present :: proc() {
  685. _draw_current_batch()
  686. ch(s.swapchain->Present(1, {}))
  687. s.vertex_buffer_offset = 0
  688. s.vertex_buffer_cpu_count = 0
  689. }
  690. Shader_Constant_Location :: struct {
  691. buffer_idx: u32,
  692. offset: u32,
  693. }
  694. _load_shader :: proc(shader: string) -> Shader_Handle {
  695. vs_blob: ^d3d11.IBlob
  696. vs_blob_errors: ^d3d11.IBlob
  697. ch(d3d_compiler.Compile(raw_data(shader), len(shader), nil, nil, nil, "vs_main", "vs_5_0", 0, 0, &vs_blob, &vs_blob_errors))
  698. if vs_blob_errors != nil {
  699. log.error("Failed compiling shader:")
  700. log.error(strings.string_from_ptr((^u8)(vs_blob_errors->GetBufferPointer()), int(vs_blob_errors->GetBufferSize())))
  701. }
  702. vertex_shader: ^d3d11.IVertexShader
  703. ch(s.device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), nil, &vertex_shader))
  704. ref: ^d3d11.IShaderReflection
  705. ch(d3d_compiler.Reflect(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), d3d11.ID3D11ShaderReflection_UUID, (^rawptr)(&ref)))
  706. constant_buffers: []Shader_Constant_Buffer
  707. constant_lookup: map[string]Shader_Constant_Location
  708. constant_builtin_locations: [Shader_Builtin_Constant]Maybe(Shader_Constant_Location)
  709. {
  710. context.allocator = s.allocator
  711. d: d3d11.SHADER_DESC
  712. ch(ref->GetDesc(&d))
  713. constant_buffers = make([]Shader_Constant_Buffer, d.ConstantBuffers)
  714. for cb_idx in 0..<d.ConstantBuffers {
  715. cb_info := ref->GetConstantBufferByIndex(cb_idx)
  716. if cb_info == nil {
  717. continue
  718. }
  719. cb_desc: d3d11.SHADER_BUFFER_DESC
  720. cb_info->GetDesc(&cb_desc)
  721. if cb_desc.Size == 0 {
  722. continue
  723. }
  724. b := &constant_buffers[cb_idx]
  725. b.cpu_data = make([]u8, cb_desc.Size, s.allocator)
  726. constant_buffer_desc := d3d11.BUFFER_DESC{
  727. ByteWidth = cb_desc.Size,
  728. Usage = .DYNAMIC,
  729. BindFlags = {.CONSTANT_BUFFER},
  730. CPUAccessFlags = {.WRITE},
  731. }
  732. ch(s.device->CreateBuffer(&constant_buffer_desc, nil, &b.gpu_data))
  733. for var_idx in 0..<cb_desc.Variables {
  734. var_info := cb_info->GetVariableByIndex(var_idx)
  735. if var_info == nil {
  736. continue
  737. }
  738. var_desc: d3d11.SHADER_VARIABLE_DESC
  739. var_info->GetDesc(&var_desc)
  740. if var_desc.Name != "" {
  741. loc := Shader_Constant_Location {
  742. buffer_idx = cb_idx,
  743. offset = var_desc.StartOffset,
  744. }
  745. constant_lookup[strings.clone_from_cstring(var_desc.Name)] = loc
  746. switch var_desc.Name {
  747. case "mvp":
  748. constant_builtin_locations[.MVP] = loc
  749. }
  750. }
  751. // TODO add the size or type somewhere so we set it correctly
  752. /*log.info(var_desc)
  753. type_info := var_info->GetType()
  754. type_info_desc: d3d11.SHADER_TYPE_DESC
  755. type_info->GetDesc(&type_info_desc)
  756. log.info(type_info_desc)*/
  757. }
  758. }
  759. }
  760. input_element_desc := [?]d3d11.INPUT_ELEMENT_DESC{
  761. { "POS", 0, .R32G32_FLOAT, 0, 0, .VERTEX_DATA, 0 },
  762. { "UV", 0, .R32G32_FLOAT, 0, d3d11.APPEND_ALIGNED_ELEMENT, .VERTEX_DATA, 0 },
  763. { "COL", 0, .R8G8B8A8_UNORM, 0, d3d11.APPEND_ALIGNED_ELEMENT, .VERTEX_DATA, 0 },
  764. }
  765. input_layout: ^d3d11.IInputLayout
  766. ch(s.device->CreateInputLayout(&input_element_desc[0], len(input_element_desc), vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), &input_layout))
  767. ps_blob: ^d3d11.IBlob
  768. ps_blob_errors: ^d3d11.IBlob
  769. ch(d3d_compiler.Compile(raw_data(shader), len(shader), nil, nil, nil, "ps_main", "ps_5_0", 0, 0, &ps_blob, &ps_blob_errors))
  770. if ps_blob_errors != nil {
  771. log.error("Failed compiling shader:")
  772. log.error(strings.string_from_ptr((^u8)(ps_blob_errors->GetBufferPointer()), int(ps_blob_errors->GetBufferSize())))
  773. }
  774. pixel_shader: ^d3d11.IPixelShader
  775. ch(s.device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), nil, &pixel_shader))
  776. shd := Shader {
  777. vertex_shader = vertex_shader,
  778. pixel_shader = pixel_shader,
  779. input_layout = input_layout,
  780. constant_buffers = constant_buffers,
  781. constant_lookup = constant_lookup,
  782. constant_builtin_locations = constant_builtin_locations,
  783. }
  784. h := hm.add(&s.shaders, shd)
  785. return h
  786. }
  787. _destroy_shader :: proc(shader: Shader_Handle) {
  788. if shd := hm.get(&s.shaders, shader); shd != nil {
  789. shd.input_layout->Release()
  790. shd.vertex_shader->Release()
  791. shd.pixel_shader->Release()
  792. for c in shd.constant_buffers {
  793. if c.gpu_data != nil {
  794. c.gpu_data->Release()
  795. }
  796. delete(c.cpu_data)
  797. }
  798. delete(shd.constant_buffers)
  799. for k,_ in shd.constant_lookup {
  800. delete(k)
  801. }
  802. delete(shd.constant_lookup)
  803. }
  804. hm.remove(&s.shaders, shader)
  805. }
  806. _get_shader_constant_location :: proc(shader: Shader_Handle, name: string) -> Shader_Constant_Location {
  807. shd := hm.get(&s.shaders, shader)
  808. if shd == nil {
  809. return {}
  810. }
  811. return shd.constant_lookup[name]
  812. }
  813. temp_cstring :: proc(str: string, loc := #caller_location) -> cstring {
  814. return strings.clone_to_cstring(str, context.temp_allocator, loc)
  815. }
  816. // CHeck win errors and print message log if there is any error
  817. ch :: proc(hr: win32.HRESULT, loc := #caller_location) -> win32.HRESULT {
  818. if hr >= 0 {
  819. return hr
  820. }
  821. log.errorf("d3d11 error: %0x", u32(hr), location = loc)
  822. log_messages(loc)
  823. return hr
  824. }
  825. log_messages :: proc(loc := #caller_location) {
  826. iq := s.info_queue
  827. if iq == nil {
  828. return
  829. }
  830. n := iq->GetNumStoredMessages()
  831. longest_msg: d3d11.SIZE_T
  832. for i in 0..=n {
  833. msglen: d3d11.SIZE_T
  834. iq->GetMessage(i, nil, &msglen)
  835. if msglen > longest_msg {
  836. longest_msg = msglen
  837. }
  838. }
  839. if longest_msg > 0 {
  840. msg_raw_ptr, _ := (mem.alloc(int(longest_msg), allocator = context.temp_allocator))
  841. for i in 0..=n {
  842. msglen: d3d11.SIZE_T
  843. iq->GetMessage(i, nil, &msglen)
  844. if msglen > 0 {
  845. msg := (^d3d11.MESSAGE)(msg_raw_ptr)
  846. iq->GetMessage(i, msg, &msglen)
  847. log.error(msg.pDescription, location = loc)
  848. }
  849. }
  850. }
  851. iq->ClearStoredMessages()
  852. }