karl2d_windows.odin 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. #+build windows
  2. package karl2d
  3. import "base:runtime"
  4. import win "core:sys/windows"
  5. import D3D11 "vendor:directx/d3d11"
  6. import DXGI "vendor:directx/dxgi"
  7. import D3D "vendor:directx/d3d_compiler"
  8. import "core:strings"
  9. import "core:log"
  10. import "core:math/linalg"
  11. import "core:slice"
  12. _ :: log
  13. //import "core:math"
  14. _init :: proc(width: int, height: int, title: string,
  15. allocator := context.allocator, loc := #caller_location) -> ^State {
  16. s = new(State, allocator, loc)
  17. s.custom_context = context
  18. CLASS_NAME :: "karl2d"
  19. instance := win.HINSTANCE(win.GetModuleHandleW(nil))
  20. s.run = true
  21. s.width = width
  22. s.height = height
  23. cls := win.WNDCLASSW {
  24. lpfnWndProc = window_proc,
  25. lpszClassName = CLASS_NAME,
  26. hInstance = instance,
  27. hCursor = win.LoadCursorA(nil, win.IDC_ARROW),
  28. }
  29. _ = cls
  30. class := win.RegisterClassW(&cls)
  31. _ = class
  32. r: win.RECT
  33. r.right = i32(width)
  34. r.bottom = i32(height)
  35. style := win.WS_OVERLAPPEDWINDOW | win.WS_VISIBLE
  36. win.AdjustWindowRect(&r, style, false)
  37. hwnd := win.CreateWindowW(CLASS_NAME,
  38. win.utf8_to_wstring(title),
  39. style,
  40. 100, 10, r.right - r.left, r.bottom - r.top,
  41. nil, nil, instance, nil)
  42. feature_levels := [?]D3D11.FEATURE_LEVEL{ ._11_0 }
  43. base_device: ^D3D11.IDevice
  44. base_device_context: ^D3D11.IDeviceContext
  45. D3D11.CreateDevice(
  46. nil,
  47. .HARDWARE,
  48. nil,
  49. {.BGRA_SUPPORT},
  50. &feature_levels[0], len(feature_levels),
  51. D3D11.SDK_VERSION, &base_device, nil, &base_device_context)
  52. device: ^D3D11.IDevice
  53. base_device->QueryInterface(D3D11.IDevice_UUID, (^rawptr)(&device))
  54. base_device_context->QueryInterface(D3D11.IDeviceContext_UUID, (^rawptr)(&s.device_context))
  55. dxgi_device: ^DXGI.IDevice
  56. device->QueryInterface(DXGI.IDevice_UUID, (^rawptr)(&dxgi_device))
  57. dxgi_adapter: ^DXGI.IAdapter
  58. dxgi_device->GetAdapter(&dxgi_adapter)
  59. dxgi_factory: ^DXGI.IFactory2
  60. dxgi_adapter->GetParent(DXGI.IFactory2_UUID, (^rawptr)(&dxgi_factory))
  61. swapchain_desc := DXGI.SWAP_CHAIN_DESC1 {
  62. Format = .B8G8R8A8_UNORM,
  63. SampleDesc = {
  64. Count = 1,
  65. },
  66. BufferUsage = {.RENDER_TARGET_OUTPUT},
  67. BufferCount = 2,
  68. Scaling = .STRETCH,
  69. SwapEffect = .DISCARD,
  70. }
  71. dxgi_factory->CreateSwapChainForHwnd(device, hwnd, &swapchain_desc, nil, nil, &s.swapchain)
  72. framebuffer: ^D3D11.ITexture2D
  73. s.swapchain->GetBuffer(0, D3D11.ITexture2D_UUID, (^rawptr)(&framebuffer))
  74. device->CreateRenderTargetView(framebuffer, nil, &s.framebuffer_view)
  75. depth_buffer_desc: D3D11.TEXTURE2D_DESC
  76. framebuffer->GetDesc(&depth_buffer_desc)
  77. depth_buffer_desc.Format = .D24_UNORM_S8_UINT
  78. depth_buffer_desc.BindFlags = {.DEPTH_STENCIL}
  79. depth_buffer: ^D3D11.ITexture2D
  80. device->CreateTexture2D(&depth_buffer_desc, nil, &depth_buffer)
  81. device->CreateDepthStencilView(depth_buffer, nil, &s.depth_buffer_view)
  82. //////////
  83. vs_blob: ^D3D11.IBlob
  84. D3D.Compile(raw_data(shader_hlsl), len(shader_hlsl), "shader.hlsl", nil, nil, "vs_main", "vs_5_0", 0, 0, &vs_blob, nil)
  85. assert(vs_blob != nil)
  86. device->CreateVertexShader(vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), nil, &vertex_shader)
  87. input_element_desc := [?]D3D11.INPUT_ELEMENT_DESC{
  88. { "POS", 0, .R32G32_FLOAT, 0, 0, .VERTEX_DATA, 0 },
  89. { "COL", 0, .R8G8B8A8_UNORM , 0, D3D11.APPEND_ALIGNED_ELEMENT, .VERTEX_DATA, 0 },
  90. }
  91. device->CreateInputLayout(&input_element_desc[0], len(input_element_desc), vs_blob->GetBufferPointer(), vs_blob->GetBufferSize(), &input_layout)
  92. ps_blob: ^D3D11.IBlob
  93. D3D.Compile(raw_data(shader_hlsl), len(shader_hlsl), "shader.hlsl", nil, nil, "ps_main", "ps_5_0", 0, 0, &ps_blob, nil)
  94. device->CreatePixelShader(ps_blob->GetBufferPointer(), ps_blob->GetBufferSize(), nil, &pixel_shader)
  95. //////////
  96. rasterizer_desc := D3D11.RASTERIZER_DESC{
  97. FillMode = .SOLID,
  98. CullMode = .BACK,
  99. }
  100. device->CreateRasterizerState(&rasterizer_desc, &rasterizer_state)
  101. depth_stencil_desc := D3D11.DEPTH_STENCIL_DESC{
  102. DepthEnable = false,
  103. DepthWriteMask = .ALL,
  104. DepthFunc = .LESS,
  105. }
  106. device->CreateDepthStencilState(&depth_stencil_desc, &depth_stencil_state)
  107. constant_buffer_desc := D3D11.BUFFER_DESC{
  108. ByteWidth = size_of(Constants),
  109. Usage = .DYNAMIC,
  110. BindFlags = {.CONSTANT_BUFFER},
  111. CPUAccessFlags = {.WRITE},
  112. }
  113. device->CreateBuffer(&constant_buffer_desc, nil, &constant_buffer)
  114. vertex_buffer_desc := D3D11.BUFFER_DESC{
  115. ByteWidth = VERTEX_BUFFER_MAX * size_of(Vertex),
  116. Usage = .DYNAMIC,
  117. BindFlags = {.VERTEX_BUFFER},
  118. CPUAccessFlags = {.WRITE},
  119. }
  120. device->CreateBuffer(&vertex_buffer_desc, nil, &s.vertex_buffer)
  121. vb_data: D3D11.MAPPED_SUBRESOURCE
  122. s.device_context->Map(s.vertex_buffer, 0, .WRITE_NO_OVERWRITE, {}, &vb_data)
  123. s.vertex_buffer_map = slice.from_ptr((^Vertex)(vb_data.pData), VERTEX_BUFFER_MAX)
  124. s.proj_matrix = make_default_projection(s.width, s.height)
  125. return s
  126. }
  127. VERTEX_BUFFER_MAX :: 10000
  128. shader_hlsl :: #load("shader.hlsl")
  129. Vertex :: struct {
  130. pos: Vec2,
  131. color: Color,
  132. }
  133. s: ^State
  134. constant_buffer: ^D3D11.IBuffer
  135. vertex_shader: ^D3D11.IVertexShader
  136. pixel_shader: ^D3D11.IPixelShader
  137. depth_stencil_state: ^D3D11.IDepthStencilState
  138. rasterizer_state: ^D3D11.IRasterizerState
  139. input_layout: ^D3D11.IInputLayout
  140. State :: struct {
  141. swapchain: ^DXGI.ISwapChain1,
  142. framebuffer_view: ^D3D11.IRenderTargetView,
  143. depth_buffer_view: ^D3D11.IDepthStencilView,
  144. device_context: ^D3D11.IDeviceContext,
  145. vertex_buffer: ^D3D11.IBuffer,
  146. vertex_buffer_count: int,
  147. vertex_buffer_map: []Vertex,
  148. run: bool,
  149. custom_context: runtime.Context,
  150. width: int,
  151. height: int,
  152. keys_went_down: #sparse [Keyboard_Key]bool,
  153. keys_went_up: #sparse [Keyboard_Key]bool,
  154. keys_is_held: #sparse [Keyboard_Key]bool,
  155. proj_matrix: matrix[4,4]f32,
  156. }
  157. VK_MAP := [255]Keyboard_Key {
  158. win.VK_A = .A,
  159. win.VK_B = .B,
  160. win.VK_C = .C,
  161. win.VK_D = .D,
  162. win.VK_E = .E,
  163. win.VK_F = .F,
  164. win.VK_G = .G,
  165. win.VK_H = .H,
  166. win.VK_I = .I,
  167. win.VK_J = .J,
  168. win.VK_K = .K,
  169. win.VK_L = .L,
  170. win.VK_M = .M,
  171. win.VK_N = .N,
  172. win.VK_O = .O,
  173. win.VK_P = .P,
  174. win.VK_Q = .Q,
  175. win.VK_R = .R,
  176. win.VK_S = .S,
  177. win.VK_T = .T,
  178. win.VK_U = .U,
  179. win.VK_V = .V,
  180. win.VK_W = .W,
  181. win.VK_X = .X,
  182. win.VK_Y = .Y,
  183. win.VK_Z = .Z,
  184. win.VK_LEFT = .Left,
  185. win.VK_RIGHT = .Right,
  186. win.VK_UP = .Up,
  187. win.VK_DOWN = .Down,
  188. }
  189. window_proc :: proc "stdcall" (hwnd: win.HWND, msg: win.UINT, wparam: win.WPARAM, lparam: win.LPARAM) -> win.LRESULT {
  190. context = s.custom_context
  191. switch msg {
  192. case win.WM_DESTROY:
  193. win.PostQuitMessage(0)
  194. s.run = false
  195. case win.WM_CLOSE:
  196. s.run = false
  197. case win.WM_KEYDOWN:
  198. key := VK_MAP[wparam]
  199. s.keys_went_down[key] = true
  200. s.keys_is_held[key] = true
  201. case win.WM_KEYUP:
  202. key := VK_MAP[wparam]
  203. s.keys_is_held[key] = false
  204. s.keys_went_up[key] = true
  205. }
  206. return win.DefWindowProcW(hwnd, msg, wparam, lparam)
  207. }
  208. _shutdown :: proc() {
  209. }
  210. _set_internal_state :: proc(new_state: ^State) {
  211. s = new_state
  212. }
  213. Color_F32 :: [4]f32
  214. f32_color_from_color :: proc(color: Color) -> Color_F32 {
  215. return {
  216. f32(color.r) / 255,
  217. f32(color.g) / 255,
  218. f32(color.b) / 255,
  219. f32(color.a) / 255,
  220. }
  221. }
  222. _clear :: proc(color: Color) {
  223. c := f32_color_from_color(color)
  224. s.device_context->ClearRenderTargetView(s.framebuffer_view, &c)
  225. s.device_context->ClearDepthStencilView(s.depth_buffer_view, {.DEPTH}, 1, 0)
  226. }
  227. _load_texture :: proc(filename: string) -> Texture {
  228. return {}
  229. }
  230. _destroy_texture :: proc(tex: Texture) {
  231. }
  232. _draw_texture :: proc(tex: Texture, pos: Vec2, tint := WHITE) {
  233. _draw_texture_ex(
  234. tex,
  235. {0, 0, f32(tex.width), f32(tex.height)},
  236. {pos.x, pos.y, f32(tex.width), f32(tex.height)},
  237. {},
  238. 0,
  239. tint,
  240. )
  241. }
  242. _draw_texture_rect :: proc(tex: Texture, rect: Rect, pos: Vec2, tint := WHITE) {
  243. _draw_texture_ex(
  244. tex,
  245. rect,
  246. {pos.x, pos.y, rect.w, rect.h},
  247. {},
  248. 0,
  249. tint,
  250. )
  251. }
  252. add_vertex :: proc(v: Vec2, color: Color) {
  253. s.vertex_buffer_map[s.vertex_buffer_count] = {
  254. pos = v,
  255. color = color,
  256. }
  257. s.vertex_buffer_count += 1
  258. }
  259. _draw_texture_ex :: proc(tex: Texture, src: Rect, dst: Rect, origin: Vec2, rot: f32, tint := WHITE) {
  260. p := Vec2 {
  261. dst.x, dst.y,
  262. }
  263. p -= origin
  264. add_vertex({p.x, p.y}, tint)
  265. add_vertex({p.x + dst.w, p.y}, tint)
  266. add_vertex({p.x + dst.w, p.y + dst.h}, tint)
  267. add_vertex({p.x, p.y}, tint)
  268. add_vertex({p.x + dst.w, p.y + dst.h}, tint)
  269. add_vertex({p.x, p.y + dst.h}, tint)
  270. }
  271. _draw_rectangle :: proc(r: Rect, color: Color) {
  272. add_vertex({r.x, r.y}, color)
  273. add_vertex({r.x + r.w, r.y}, color)
  274. add_vertex({r.x + r.w, r.y + r.h}, color)
  275. add_vertex({r.x, r.y}, color)
  276. add_vertex({r.x + r.w, r.y + r.h}, color)
  277. add_vertex({r.x, r.y + r.h}, color)
  278. }
  279. _draw_rectangle_outline :: proc(rect: Rect, thickness: f32, color: Color) {
  280. }
  281. _draw_circle :: proc(center: Vec2, radius: f32, color: Color) {
  282. }
  283. _draw_line :: proc(start: Vec2, end: Vec2, thickness: f32, color: Color) {
  284. }
  285. _get_screen_width :: proc() -> int {
  286. return 0
  287. }
  288. _get_screen_height :: proc() -> int {
  289. return 0
  290. }
  291. _key_went_down :: proc(key: Keyboard_Key) -> bool {
  292. return s.keys_went_down[key]
  293. }
  294. _key_went_up :: proc(key: Keyboard_Key) -> bool {
  295. return s.keys_went_up[key]
  296. }
  297. _key_is_held :: proc(key: Keyboard_Key) -> bool {
  298. return s.keys_is_held[key]
  299. }
  300. _window_should_close :: proc() -> bool {
  301. return !s.run
  302. }
  303. _draw_text :: proc(text: string, pos: Vec2, font_size: f32, color: Color) {
  304. }
  305. _mouse_button_pressed :: proc(button: Mouse_Button) -> bool {
  306. return false
  307. }
  308. _mouse_button_released :: proc(button: Mouse_Button) -> bool {
  309. return false
  310. }
  311. _mouse_button_held :: proc(button: Mouse_Button) -> bool {
  312. return false
  313. }
  314. _mouse_wheel_delta :: proc() -> f32 {
  315. return 0
  316. }
  317. _mouse_position :: proc() -> Vec2 {
  318. return {}
  319. }
  320. _enable_scissor :: proc(x, y, w, h: int) {
  321. }
  322. _disable_scissor :: proc() {
  323. }
  324. _set_window_size :: proc(width: int, height: int) {
  325. }
  326. _set_window_position :: proc(x: int, y: int) {
  327. }
  328. _screen_to_world :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  329. return pos
  330. }
  331. _set_camera :: proc(camera: Maybe(Camera)) {
  332. if c, c_ok := camera.?; c_ok {
  333. s.proj_matrix = make_default_projection(s.width, s.height)
  334. s.proj_matrix[0, 0] *= c.zoom
  335. s.proj_matrix[1, 1] *= c.zoom
  336. } else {
  337. s.proj_matrix = make_default_projection(s.width, s.height)
  338. }
  339. }
  340. _set_scissor_rect :: proc(scissor_rect: Maybe(Rect)) {
  341. }
  342. _set_shader :: proc(shader: Maybe(Shader)) {
  343. }
  344. _process_events :: proc() {
  345. s.keys_went_up = {}
  346. s.keys_went_down = {}
  347. msg: win.MSG
  348. for win.PeekMessageW(&msg, nil, 0, 0, win.PM_REMOVE) {
  349. win.TranslateMessage(&msg)
  350. win.DispatchMessageW(&msg)
  351. }
  352. }
  353. _flush :: proc() {
  354. }
  355. Constants :: struct #align (16) {
  356. projection: matrix[4, 4]f32,
  357. }
  358. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  359. return linalg.matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  360. }
  361. _present :: proc(do_flush := true) {
  362. viewport := D3D11.VIEWPORT{
  363. 0, 0,
  364. f32(s.width), f32(s.height),
  365. 0, 1,
  366. }
  367. dc := s.device_context
  368. // matrix[0.002, 0, -0, -1; 0, 0.002, -0, -1; 0, 0, -1.0005003, -1.0010005; 0, 0, -0, 1]
  369. // matrix[0.002, 0, -0, -1; 0, 0.002, -0, 1; 0, 0, 1.0005002, -1.0010005; 0, 0, -0, 1]
  370. cb_data: D3D11.MAPPED_SUBRESOURCE
  371. dc->Map(constant_buffer, 0, .WRITE_DISCARD, {}, &cb_data)
  372. {
  373. constants := (^Constants)(cb_data.pData)
  374. constants.projection = s.proj_matrix
  375. }
  376. dc->Unmap(constant_buffer, 0)
  377. dc->IASetPrimitiveTopology(.TRIANGLELIST)
  378. dc->IASetInputLayout(input_layout)
  379. vertex_buffer_offset := u32(0)
  380. vertex_buffer_stride := u32(size_of(Vertex))
  381. dc->IASetVertexBuffers(0, 1, &s.vertex_buffer, &vertex_buffer_stride, &vertex_buffer_offset)
  382. dc->VSSetShader(vertex_shader, nil, 0)
  383. dc->VSSetConstantBuffers(0, 1, &constant_buffer)
  384. dc->RSSetViewports(1, &viewport)
  385. dc->RSSetState(rasterizer_state)
  386. dc->PSSetShader(pixel_shader, nil, 0)
  387. dc->OMSetRenderTargets(1, &s.framebuffer_view, s.depth_buffer_view)
  388. dc->OMSetDepthStencilState(depth_stencil_state, 0)
  389. dc->OMSetBlendState(nil, nil, ~u32(0)) // use default blend mode (i.e. disable)
  390. dc->Draw(u32(s.vertex_buffer_count), 0)
  391. s.swapchain->Present(1, {})
  392. s.vertex_buffer_count = 0
  393. }
  394. _load_shader :: proc(vs: string, fs: string) -> Shader {
  395. return {}
  396. }
  397. _destroy_shader :: proc(shader: Shader) {
  398. }
  399. _get_shader_location :: proc(shader: Shader, uniform_name: string) -> int {
  400. return 0
  401. }
  402. _set_shader_value_f32 :: proc(shader: Shader, loc: int, val: f32) {
  403. }
  404. _set_shader_value_vec2 :: proc(shader: Shader, loc: int, val: Vec2) {
  405. }
  406. temp_cstring :: proc(str: string) -> cstring {
  407. return strings.clone_to_cstring(str, context.temp_allocator)
  408. }