karl2d_windows.odin 26 KB

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