render_backend_gl.odin 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. #+build windows, darwin, linux
  2. #+private file
  3. package karl2d
  4. @(private="package")
  5. RENDER_BACKEND_INTERFACE_GL :: Render_Backend_Interface {
  6. state_size = gl_state_size,
  7. init = gl_init,
  8. shutdown = gl_shutdown,
  9. clear = gl_clear,
  10. present = gl_present,
  11. draw = gl_draw,
  12. resize_swapchain = gl_resize_swapchain,
  13. get_swapchain_width = gl_get_swapchain_width,
  14. get_swapchain_height = gl_get_swapchain_height,
  15. flip_z = gl_flip_z,
  16. set_internal_state = gl_set_internal_state,
  17. create_texture = gl_create_texture,
  18. load_texture = gl_load_texture,
  19. update_texture = gl_update_texture,
  20. destroy_texture = gl_destroy_texture,
  21. load_shader = gl_load_shader,
  22. destroy_shader = gl_destroy_shader,
  23. default_shader_vertex_source = gl_default_shader_vertex_source,
  24. default_shader_fragment_source = gl_default_shader_fragment_source,
  25. }
  26. import "base:runtime"
  27. import gl "vendor:OpenGL"
  28. import hm "handle_map"
  29. import "core:log"
  30. import win32 "core:sys/windows"
  31. import "core:strings"
  32. import "core:slice"
  33. import la "core:math/linalg"
  34. _ :: la
  35. GL_State :: struct {
  36. width: int,
  37. height: int,
  38. allocator: runtime.Allocator,
  39. shaders: hm.Handle_Map(GL_Shader, Shader_Handle, 1024*10),
  40. dc: win32.HDC,
  41. vertex_buffer_gpu: u32,
  42. }
  43. GL_Shader_Constant_Buffer :: struct {
  44. gpu_data: rawptr,
  45. }
  46. GL_Shader :: struct {
  47. handle: Shader_Handle,
  48. // This is like the "input layout"
  49. vao: u32,
  50. program: u32,
  51. }
  52. s: ^GL_State
  53. gl_state_size :: proc() -> int {
  54. return size_of(GL_State)
  55. }
  56. gl_init :: proc(state: rawptr, window_handle: Window_Handle, swapchain_width, swapchain_height: int, allocator := context.allocator) {
  57. s = (^GL_State)(state)
  58. s.width = swapchain_width
  59. s.height = swapchain_height
  60. s.allocator = allocator
  61. hdc := win32.GetWindowDC(win32.HWND(window_handle))
  62. s.dc = hdc
  63. pfd := win32.PIXELFORMATDESCRIPTOR {
  64. size_of(win32.PIXELFORMATDESCRIPTOR),
  65. 1,
  66. win32.PFD_DRAW_TO_WINDOW | win32.PFD_SUPPORT_OPENGL | win32.PFD_DOUBLEBUFFER, // Flags
  67. win32.PFD_TYPE_RGBA, // The kind of framebuffer. RGBA or palette.
  68. 32, // Colordepth of the framebuffer.
  69. 0, 0, 0, 0, 0, 0,
  70. 0,
  71. 0,
  72. 0,
  73. 0, 0, 0, 0,
  74. 24, // Number of bits for the depthbuffer
  75. 8, // Number of bits for the stencilbuffer
  76. 0, // Number of Aux buffers in the framebuffer.
  77. win32.PFD_MAIN_PLANE,
  78. 0,
  79. 0, 0, 0,
  80. }
  81. fmt := win32.ChoosePixelFormat(hdc, &pfd)
  82. win32.SetPixelFormat(hdc, fmt, &pfd)
  83. ctx := win32.wglCreateContext(hdc)
  84. win32.wglMakeCurrent(hdc, ctx)
  85. win32.gl_set_proc_address(&win32.wglChoosePixelFormatARB, "wglChoosePixelFormatARB")
  86. win32.gl_set_proc_address(&win32.wglCreateContextAttribsARB, "wglCreateContextAttribsARB")
  87. pixel_format_ilist := [?]i32 {
  88. win32.WGL_DRAW_TO_WINDOW_ARB, 1,
  89. win32.WGL_SUPPORT_OPENGL_ARB, 1,
  90. win32.WGL_DOUBLE_BUFFER_ARB, 1,
  91. win32.WGL_PIXEL_TYPE_ARB, win32.WGL_TYPE_RGBA_ARB,
  92. win32.WGL_COLOR_BITS_ARB, 32,
  93. win32.WGL_DEPTH_BITS_ARB, 24,
  94. win32.WGL_STENCIL_BITS_ARB, 8,
  95. 0,
  96. }
  97. pixel_format: i32
  98. num_formats: u32
  99. valid_pixel_format := win32.wglChoosePixelFormatARB(hdc, raw_data(pixel_format_ilist[:]),
  100. nil, 1, &pixel_format, &num_formats)
  101. if !valid_pixel_format {
  102. log.panic("Could not find a valid pixel format for gl context")
  103. }
  104. win32.SetPixelFormat(hdc, pixel_format, nil)
  105. ctx = win32.wglCreateContextAttribsARB(hdc, nil, nil)
  106. win32.wglMakeCurrent(hdc, ctx)
  107. gl.load_up_to(3, 3, win32.gl_set_proc_address)
  108. //gl.Enable(gl.DEPTH_TEST)
  109. //gl.CullFace(gl.FRONT)
  110. gl.GenBuffers(1, &s.vertex_buffer_gpu)
  111. gl.BindBuffer(gl.ARRAY_BUFFER, s.vertex_buffer_gpu)
  112. gl.BufferData(gl.ARRAY_BUFFER, VERTEX_BUFFER_MAX, nil, gl.DYNAMIC_DRAW)
  113. }
  114. gl_shutdown :: proc() {
  115. }
  116. gl_clear :: proc(color: Color) {
  117. c := f32_color_from_color(color)
  118. gl.ClearColor(c.r, c.g, c.b, c.a)
  119. gl.Clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
  120. }
  121. gl_present :: proc() {
  122. win32.SwapBuffers(s.dc)
  123. }
  124. gl_draw :: proc(shd: Shader, texture: Texture_Handle, view_proj: Mat4, scissor: Maybe(Rect), vertex_buffer: []u8) {
  125. shader := hm.get(&s.shaders, shd.handle)
  126. if shader == nil {
  127. return
  128. }
  129. gl.EnableVertexAttribArray(0)
  130. gl.EnableVertexAttribArray(1)
  131. gl.EnableVertexAttribArray(2)
  132. gl.UseProgram(shader.program)
  133. mvp_loc := gl.GetUniformLocation(shader.program, "mvp")
  134. //mvp := la.transpose(view_proj)
  135. mvp := view_proj
  136. gl.UniformMatrix4fv(mvp_loc, 1, gl.FALSE, (^f32)(&mvp))
  137. gl.BindBuffer(gl.ARRAY_BUFFER, s.vertex_buffer_gpu)
  138. vb_data := gl.MapBuffer(gl.ARRAY_BUFFER, gl.WRITE_ONLY)
  139. {
  140. gpu_map := slice.from_ptr((^u8)(vb_data), VERTEX_BUFFER_MAX)
  141. copy(
  142. gpu_map,
  143. vertex_buffer,
  144. )
  145. }
  146. gl.UnmapBuffer(gl.ARRAY_BUFFER)
  147. gl.DrawArrays(gl.TRIANGLES, 0, i32(len(vertex_buffer)/shd.vertex_size))
  148. }
  149. gl_resize_swapchain :: proc(w, h: int) {
  150. }
  151. gl_get_swapchain_width :: proc() -> int {
  152. return s.width
  153. }
  154. gl_get_swapchain_height :: proc() -> int {
  155. return s.height
  156. }
  157. gl_flip_z :: proc() -> bool {
  158. return true
  159. }
  160. gl_set_internal_state :: proc(state: rawptr) {
  161. }
  162. gl_create_texture :: proc(width: int, height: int, format: Pixel_Format) -> Texture_Handle {
  163. return {}
  164. }
  165. gl_load_texture :: proc(data: []u8, width: int, height: int, format: Pixel_Format) -> Texture_Handle {
  166. return {}
  167. }
  168. gl_update_texture :: proc(th: Texture_Handle, data: []u8, rect: Rect) -> bool {
  169. return false
  170. }
  171. gl_destroy_texture :: proc(th: Texture_Handle) {
  172. }
  173. Shader_Compile_Result_OK :: struct {}
  174. Shader_Compile_Result_Error :: string
  175. Shader_Compile_Result :: union #no_nil {
  176. Shader_Compile_Result_OK,
  177. Shader_Compile_Result_Error,
  178. }
  179. compile_shader_from_source :: proc(shader_data: string, shader_type: gl.Shader_Type, err_buf: []u8, err_msg: ^string) -> (shader_id: u32, ok: bool) {
  180. shader_id = gl.CreateShader(u32(shader_type))
  181. length := i32(len(shader_data))
  182. shader_cstr := cstring(raw_data(shader_data))
  183. gl.ShaderSource(shader_id, 1, &shader_cstr, &length)
  184. gl.CompileShader(shader_id)
  185. result: i32
  186. gl.GetShaderiv(shader_id, gl.COMPILE_STATUS, &result)
  187. if result != 1 {
  188. info_len: i32
  189. gl.GetShaderInfoLog(shader_id, i32(len(err_buf)), &info_len, raw_data(err_buf))
  190. err_msg^ = string(err_buf[:info_len])
  191. gl.DeleteShader(shader_id)
  192. return 0, false
  193. }
  194. return shader_id, true
  195. }
  196. link_shader :: proc(vs_shader: u32, fs_shader: u32, err_buf: []u8, err_msg: ^string) -> (program_id: u32, ok: bool) {
  197. program_id = gl.CreateProgram()
  198. gl.AttachShader(program_id, vs_shader)
  199. gl.AttachShader(program_id, fs_shader)
  200. gl.LinkProgram(program_id)
  201. result: i32
  202. gl.GetProgramiv(program_id, gl.LINK_STATUS, &result)
  203. if result != 1 {
  204. info_len: i32
  205. gl.GetProgramInfoLog(program_id, i32(len(err_buf)), &info_len, raw_data(err_buf))
  206. err_msg^ = string(err_buf[:info_len])
  207. gl.DeleteProgram(program_id)
  208. return 0, false
  209. }
  210. return program_id, true
  211. }
  212. gl_load_shader :: proc(vs_source: string, fs_source: string, desc_allocator := frame_allocator, layout_formats: []Pixel_Format = {}) -> (handle: Shader_Handle, desc: Shader_Desc) {
  213. @static err: [1024]u8
  214. err_msg: string
  215. vs_shader, vs_shader_ok := compile_shader_from_source(vs_source, gl.Shader_Type.VERTEX_SHADER, err[:], &err_msg)
  216. if !vs_shader_ok {
  217. log.error(err_msg)
  218. return {}, {}
  219. }
  220. fs_shader, fs_shader_ok := compile_shader_from_source(fs_source, gl.Shader_Type.FRAGMENT_SHADER, err[:], &err_msg)
  221. if !fs_shader_ok {
  222. log.error(err_msg)
  223. return {}, {}
  224. }
  225. program, program_ok := link_shader(vs_shader, fs_shader, err[:], &err_msg)
  226. if !program_ok {
  227. log.error(err_msg)
  228. return {}, {}
  229. }
  230. stride: int
  231. {
  232. num_attribs: i32
  233. gl.GetProgramiv(program, gl.ACTIVE_ATTRIBUTES, &num_attribs)
  234. desc.inputs = make([]Shader_Input, num_attribs, desc_allocator)
  235. attrib_name_buf: [256]u8
  236. for i in 0..<num_attribs {
  237. attrib_name_len: i32
  238. attrib_size: i32
  239. attrib_type: u32
  240. gl.GetActiveAttrib(program, u32(i), i32(len(attrib_name_buf)), &attrib_name_len, &attrib_size, &attrib_type, raw_data(attrib_name_buf[:]))
  241. name_cstr := strings.clone_to_cstring(string(attrib_name_buf[:attrib_name_len]), desc_allocator)
  242. loc := gl.GetAttribLocation(program, name_cstr)
  243. log.info(loc)
  244. type: Shader_Input_Type
  245. switch attrib_type {
  246. case gl.FLOAT: type = .F32
  247. case gl.FLOAT_VEC2: type = .Vec2
  248. case gl.FLOAT_VEC3: type = .Vec3
  249. case gl.FLOAT_VEC4: type = .Vec4
  250. /* Possible (gl.) types:
  251. FLOAT, FLOAT_VEC2, FLOAT_VEC3, FLOAT_VEC4, FLOAT_MAT2,
  252. FLOAT_MAT3, FLOAT_MAT4, FLOAT_MAT2x3, FLOAT_MAT2x4,
  253. FLOAT_MAT3x2, FLOAT_MAT3x4, FLOAT_MAT4x2, FLOAT_MAT4x3,
  254. INT, INT_VEC2, INT_VEC3, INT_VEC4, UNSIGNED_INT,
  255. UNSIGNED_INT_VEC2, UNSIGNED_INT_VEC3, UNSIGNED_INT_VEC4,
  256. DOUBLE, DOUBLE_VEC2, DOUBLE_VEC3, DOUBLE_VEC4, DOUBLE_MAT2,
  257. DOUBLE_MAT3, DOUBLE_MAT4, DOUBLE_MAT2x3, DOUBLE_MAT2x4,
  258. DOUBLE_MAT3x2, DOUBLE_MAT3x4, DOUBLE_MAT4x2, or DOUBLE_MAT4x3 */
  259. case: log.errorf("Unknwon type: %v", attrib_type)
  260. }
  261. name := strings.clone(string(attrib_name_buf[:attrib_name_len]), desc_allocator)
  262. log.info(name)
  263. format := len(layout_formats) > 0 ? layout_formats[loc] : get_shader_input_format(name, type)
  264. desc.inputs[loc] = {
  265. name = name,
  266. register = int(loc),
  267. format = format,
  268. type = type,
  269. }
  270. input_format := get_shader_input_format(name, type)
  271. format_size := pixel_format_size(input_format)
  272. stride += format_size
  273. //
  274. //log.info(i, attrib_name_len, attrib_size, attrib_type, string(attrib_name_buf[:attrib_name_len]))
  275. }
  276. }
  277. shader := GL_Shader {
  278. program = program,
  279. }
  280. gl.GenVertexArrays(1, &shader.vao)
  281. gl.BindVertexArray(shader.vao)
  282. gl.BindBuffer(gl.ARRAY_BUFFER, s.vertex_buffer_gpu)
  283. offset: int
  284. for idx in 0..<len(desc.inputs) {
  285. input := desc.inputs[idx]
  286. //input_format := get_shader_input_format(input.name, input.type)
  287. input_format: Pixel_Format
  288. switch input.type {
  289. case .F32: input_format = .R_32_Float
  290. case .Vec2: input_format = .RG_32_Float
  291. case .Vec3: input_format = .RGB_32_Float
  292. case .Vec4: input_format = .RGBA_32_Float
  293. }
  294. format_size := pixel_format_size(input_format)
  295. //num_components := get_shader_format_num_components(input_format)
  296. gl.EnableVertexAttribArray(u32(idx))
  297. format, num_components, norm := gl_format_from_pixel_format(get_shader_input_format(input.name, input.type))
  298. gl.VertexAttribPointer(u32(idx), num_components, format, norm ? gl.TRUE : gl.FALSE, i32(stride), uintptr(offset))
  299. offset += format_size
  300. log.info(input.name)
  301. }
  302. {
  303. /*num_constant_buffers: i32
  304. gl.GetProgramiv(program, gl.ACTIVE_UNIFORM_BLOCKS, &num_attribs)
  305. desc.constant_buffers = make([]Shader_Constant_Buffer_Desc, num_constant_buffers, desc_allocator)
  306. shader.constant_buffers = make([]GL_Shader_Constant_Buffer, num_constant_buffers, s.allocator)
  307. for cb_idx in 0..<num_constant_buffers {
  308. buf: u32
  309. gl.GenBuffers(1, &buf)*/
  310. /*
  311. GetUniformIndices :: proc "c" (program: u32, uniformCount: i32, uniformNames: [^]cstring, uniformIndices: [^]u32) { impl_GetUniformIndices(program, uniformCount, uniformNames, uniformIndices) }
  312. GetActiveUniformsiv :: proc "c" (program: u32, uniformCount: i32, uniformIndices: [^]u32, pname: u32, params: [^]i32) { impl_GetActiveUniformsiv(program, uniformCount, uniformIndices, pname, params) }
  313. GetActiveUniformName :: proc "c" (program: u32, uniformIndex: u32, bufSize: i32, length: ^i32, uniformName: [^]u8) { impl_GetActiveUniformName(program, uniformIndex, bufSize, length, uniformName) }
  314. GetUniformBlockIndex :: proc "c" (program: u32, uniformBlockName: cstring) -> u32 { ret := impl_GetUniformBlockIndex(program, uniformBlockName); return ret }
  315. GetActiveUniformBlockiv :: proc "c" (program: u32, uniformBlockIndex: u32, pname: u32, params: [^]i32) { impl_GetActiveUniformBlockiv(program, uniformBlockIndex, pname, params) }
  316. */
  317. }
  318. h := hm.add(&s.shaders, shader)
  319. return h, desc
  320. }
  321. gl_format_from_pixel_format :: proc(f: Pixel_Format) -> (u32, i32, bool) {
  322. switch f {
  323. case .RGBA_32_Float: return gl.FLOAT, 4, false
  324. case .RGB_32_Float: return gl.FLOAT, 3, false
  325. case .RG_32_Float: return gl.FLOAT, 2, false
  326. case .R_32_Float: return gl.FLOAT, 1, false
  327. case .RGBA_8_Norm: return gl.INT, 4, true
  328. case .RG_8_Norm: return gl.INT, 2, true
  329. case .R_8_Norm: return gl.INT, 1, true
  330. case .R_8_UInt: return gl.INT, 1, true
  331. case .Unknown:
  332. }
  333. log.error("Unknown format")
  334. return 0, 0, false
  335. }
  336. gl_destroy_shader :: proc(h: Shader_Handle) {
  337. }
  338. gl_default_shader_vertex_source :: proc() -> string {
  339. return #load("default_shader_vertex.glsl")
  340. }
  341. gl_default_shader_fragment_source :: proc() -> string {
  342. return #load("default_shader_fragment.glsl")
  343. }