karl2d.odin 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837
  1. #+vet explicit-allocators
  2. package karl2d
  3. import "base:runtime"
  4. import "core:mem"
  5. import "core:log"
  6. import "core:math"
  7. import "core:math/linalg"
  8. import "core:slice"
  9. import "core:strings"
  10. import "core:reflect"
  11. import "core:os"
  12. import fs "vendor:fontstash"
  13. import "core:image"
  14. import "core:image/jpeg"
  15. import "core:image/bmp"
  16. import "core:image/png"
  17. import "core:image/tga"
  18. import hm "handle_map"
  19. //-----------------------------------------------//
  20. // SETUP, WINDOW MANAGEMENT AND FRAME MANAGEMENT //
  21. //-----------------------------------------------//
  22. // Opens a window and initializes some internal state. The internal state will use `allocator` for
  23. // all dynamically allocated memory. The return value can be ignored unless you need to later call
  24. // `set_internal_state`.
  25. init :: proc(window_width: int, window_height: int, window_title: string,
  26. window_creation_flags := Window_Flags {},
  27. allocator := context.allocator, loc := #caller_location) -> ^State {
  28. assert(s == nil, "Don't call 'init' twice.")
  29. context.allocator = allocator
  30. s = new(State, allocator, loc)
  31. // This is the same type of arena as the default temp allocator. This arena is for allocations
  32. // that have a lifetime of "one frame". They are valid until you call `present()`, at which
  33. // point the frame allocator is cleared.
  34. s.frame_allocator = runtime.arena_allocator(&s.frame_arena)
  35. frame_allocator = s.frame_allocator
  36. s.allocator = allocator
  37. s.win = WINDOW_INTERFACE_WIN32
  38. win = s.win
  39. // We alloc memory for the windowing backend and pass the blob of memory to it.
  40. window_state_alloc_error: runtime.Allocator_Error
  41. s.window_state, window_state_alloc_error = mem.alloc(win.state_size(), allocator = allocator)
  42. log.assertf(window_state_alloc_error == nil, "Failed allocating memory for window state: %v", window_state_alloc_error)
  43. win.init(s.window_state, window_width, window_height, window_title, window_creation_flags, allocator)
  44. // This is a OS-independent handle that we can pass to any rendering backend.
  45. s.window = win.window_handle()
  46. // See `config.odin` for how this is picked.
  47. s.rb = RENDER_BACKEND
  48. // Depending on backend the depth is counted in one of two ways. It can be counted from `1` and
  49. // to lower numbers. Or from `-1` and to higher numbers.
  50. s.depth_start = DEPTH_START
  51. s.depth_increment = DEPTH_INCREMENT
  52. if s.rb.flip_z() {
  53. s.depth_start = -DEPTH_START
  54. s.depth_increment = -DEPTH_INCREMENT
  55. }
  56. s.depth = s.depth_start
  57. rb = s.rb
  58. rb_alloc_error: runtime.Allocator_Error
  59. s.rb_state, rb_alloc_error = mem.alloc(rb.state_size(), allocator = allocator)
  60. log.assertf(rb_alloc_error == nil, "Failed allocating memory for rendering backend: %v", rb_alloc_error)
  61. s.proj_matrix = make_default_projection(window_width, window_height)
  62. s.view_matrix = 1
  63. // Boot up the render backend. It will render into our previously created window.
  64. rb.init(s.rb_state, s.window, window_width, window_height, allocator)
  65. // The vertex buffer is created in a render backend-independent way. It is passed to the
  66. // render backend each frame as part of `draw_current_batch()`
  67. s.vertex_buffer_cpu = make([]u8, VERTEX_BUFFER_MAX, allocator, loc)
  68. // The shapes drawing texture is sampled when any shape is drawn. This way we can use the same
  69. // shader for textured drawing and shape drawing. It's just a white box.
  70. white_rect: [16*16*4]u8
  71. slice.fill(white_rect[:], 255)
  72. s.shape_drawing_texture = rb.load_texture(white_rect[:], 16, 16, .RGBA_8_Norm)
  73. // The default shader will arrive in a different format depending on backend. GLSL for GL,
  74. // HLSL for d3d etc.
  75. s.default_shader = load_shader(rb.default_shader_vertex_source(), rb.default_shader_fragment_source())
  76. s.batch_shader = s.default_shader
  77. // FontStash enables us to bake fonts from TTF files on-the-fly.
  78. fs.Init(&s.fs, FONT_DEFAULT_ATLAS_SIZE, FONT_DEFAULT_ATLAS_SIZE, .TOPLEFT)
  79. DEFAULT_FONT_DATA :: #load("roboto.ttf")
  80. // Dummy element so font with index 0 means 'no font'.
  81. append_nothing(&s.fonts)
  82. s.default_font = load_font_from_bytes(DEFAULT_FONT_DATA)
  83. set_font(s.default_font)
  84. return s
  85. }
  86. // Returns true if the program wants to shut down. This happens when for example pressing the close
  87. // button on the window. The application can decide if it wants to shut down or if it wants to show
  88. // some kind of confirmation dialogue and shut down later.
  89. //
  90. // Commonly used for creating the "main loop" of a game.
  91. shutdown_wanted :: proc() -> bool {
  92. return s.shutdown_wanted
  93. }
  94. // Closes the window and cleans up the internal state.
  95. shutdown :: proc() {
  96. assert(s != nil, "You've called 'shutdown' without calling 'init' first")
  97. context.allocator = s.allocator
  98. destroy_font(s.default_font)
  99. rb.destroy_texture(s.shape_drawing_texture)
  100. destroy_shader(s.default_shader)
  101. rb.shutdown()
  102. delete(s.vertex_buffer_cpu, s.allocator)
  103. win.shutdown()
  104. fs.Destroy(&s.fs)
  105. delete(s.fonts)
  106. a := s.allocator
  107. free(s.window_state, a)
  108. free(s.rb_state, a)
  109. free(s, a)
  110. s = nil
  111. }
  112. // Clear the backbuffer with supplied color.
  113. clear :: proc(color: Color) {
  114. rb.clear(s.batch_render_target, color)
  115. s.depth = s.depth_start
  116. }
  117. // Present the backbuffer. Call at end of frame to make everything you've drawn appear on the
  118. // screen. Also clears the frame_allocator that Karl2D uses for allocations that have the lifetime
  119. // of a single frame.
  120. present :: proc() {
  121. draw_current_batch()
  122. rb.present()
  123. free_all(s.frame_allocator)
  124. }
  125. // Call at start or end of frame to process all events that have arrived to the window. This
  126. // includes keyboard, mouse, gamepad and window events.
  127. //
  128. // WARNING: Not calling this will make your program impossible to interact with.
  129. process_events :: proc() {
  130. s.key_went_up = {}
  131. s.key_went_down = {}
  132. s.mouse_button_went_up = {}
  133. s.mouse_button_went_down = {}
  134. s.gamepad_button_went_up = {}
  135. s.gamepad_button_went_down = {}
  136. s.mouse_delta = {}
  137. s.mouse_wheel_delta = 0
  138. win.process_events()
  139. events := win.get_events()
  140. for &event in events {
  141. switch &e in event {
  142. case Window_Event_Close_Wanted:
  143. s.shutdown_wanted = true
  144. case Window_Event_Key_Went_Down:
  145. s.key_went_down[e.key] = true
  146. s.key_is_held[e.key] = true
  147. case Window_Event_Key_Went_Up:
  148. s.key_went_up[e.key] = true
  149. s.key_is_held[e.key] = false
  150. case Window_Event_Mouse_Button_Went_Down:
  151. s.mouse_button_went_down[e.button] = true
  152. s.mouse_button_is_held[e.button] = true
  153. case Window_Event_Mouse_Button_Went_Up:
  154. s.mouse_button_went_up[e.button] = true
  155. s.mouse_button_is_held[e.button] = false
  156. case Window_Event_Mouse_Move:
  157. prev_pos := s.mouse_position
  158. s.mouse_position = e.position
  159. s.mouse_delta = s.mouse_position - prev_pos
  160. case Window_Event_Mouse_Wheel:
  161. s.mouse_wheel_delta = e.delta
  162. case Window_Event_Gamepad_Button_Went_Down:
  163. if e.gamepad < MAX_GAMEPADS {
  164. s.gamepad_button_went_down[e.gamepad][e.button] = true
  165. s.gamepad_button_is_held[e.gamepad][e.button] = true
  166. }
  167. case Window_Event_Gamepad_Button_Went_Up:
  168. if e.gamepad < MAX_GAMEPADS {
  169. s.gamepad_button_went_up[e.gamepad][e.button] = true
  170. s.gamepad_button_is_held[e.gamepad][e.button] = false
  171. }
  172. case Window_Event_Resize:
  173. rb.resize_swapchain(e.width, e.height)
  174. s.proj_matrix = make_default_projection(e.width, e.height)
  175. }
  176. }
  177. win.clear_events()
  178. }
  179. get_screen_width :: proc() -> int {
  180. return win.get_width()
  181. }
  182. get_screen_height :: proc() -> int {
  183. return win.get_height()
  184. }
  185. set_window_position :: proc(x: int, y: int) {
  186. win.set_position(x, y)
  187. }
  188. set_window_size :: proc(width: int, height: int) {
  189. // TODO not sure if we should resize swapchain here. On windows the WM_SIZE event fires and
  190. // it all works out. But perhaps not on all platforms?
  191. win.set_size(width, height)
  192. }
  193. // Fetch the scale of the window. This usually comes from some DPI scaling setting in the OS.
  194. // 1 means 100% scale, 1.5 means 150% etc.
  195. get_window_scale :: proc() -> f32 {
  196. return win.get_window_scale()
  197. }
  198. set_window_flags :: proc(flags: Window_Flags) {
  199. win.set_flags(flags)
  200. }
  201. // Flushes the current batch. This sends off everything to the GPU that has been queued in the
  202. // current batch. Normally, you do not need to do this manually. It is done automatically when these
  203. // procedures run:
  204. //
  205. // - present
  206. // - set_camera
  207. // - set_shader
  208. // - set_shader_constant
  209. // - set_scissor_rect
  210. // - draw_texture_* IF previous draw did not use the same texture (1)
  211. // - draw_rect_*, draw_circle_*, draw_line IF previous draw did not use the shapes drawing texture (2)
  212. //
  213. // (1) When drawing textures, the current texture is fed into the active shader. Everything within
  214. // the same batch must use the same texture. So drawing with a new texture will draw the current
  215. // batch. You can combine several textures into an atlas to get bigger batches.
  216. //
  217. // (2) In order to use the same shader for shapes drawing and textured drawing, the shapes drawing
  218. // uses a blank, white texture. For the same reasons as (1), drawing something else than shapes
  219. // before drawing a shape will break up the batches. TODO: Add possibility to customize shape
  220. // drawing texture so that you can put it into an atlas.
  221. //
  222. // The batch has maximum size of VERTEX_BUFFER_MAX bytes. The shader dictates how big a vertex is
  223. // so the maximum number of vertices that can be drawn in each batch is
  224. // VERTEX_BUFFER_MAX / shader.vertex_size
  225. draw_current_batch :: proc() {
  226. update_font(s.batch_font)
  227. if s.vertex_buffer_cpu_used == 0 {
  228. return
  229. }
  230. shader := s.batch_shader
  231. mvp := s.proj_matrix * s.view_matrix
  232. for mloc, builtin in shader.constant_builtin_locations {
  233. constant, constant_ok := mloc.?
  234. if !constant_ok {
  235. continue
  236. }
  237. switch builtin {
  238. case .MVP:
  239. if constant.size == size_of(mvp) {
  240. dst := (^matrix[4,4]f32)(&shader.constants_data[constant.offset])
  241. dst^ = mvp
  242. }
  243. }
  244. }
  245. if def_tex_idx, has_def_tex_idx := shader.default_texture_index.?; has_def_tex_idx {
  246. shader.texture_bindpoints[def_tex_idx] = s.batch_texture
  247. }
  248. rb.draw(shader, s.batch_render_target, shader.texture_bindpoints, s.batch_scissor, s.vertex_buffer_cpu[:s.vertex_buffer_cpu_used])
  249. s.vertex_buffer_cpu_used = 0
  250. }
  251. //-------//
  252. // INPUT //
  253. //-------//
  254. // Returns true if a keyboard key went down between the current and the previous frame. Set when
  255. // 'process_events' runs (probably once per frame).
  256. key_went_down :: proc(key: Keyboard_Key) -> bool {
  257. return s.key_went_down[key]
  258. }
  259. // Returns true if a keyboard key went up (was released) between the current and the previous frame.
  260. // Set when 'process_events' runs (probably once per frame).
  261. key_went_up :: proc(key: Keyboard_Key) -> bool {
  262. return s.key_went_up[key]
  263. }
  264. // Returns true if a keyboard is currently being held down. Set when 'process_events' runs (probably
  265. // once per frame).
  266. key_is_held :: proc(key: Keyboard_Key) -> bool {
  267. return s.key_is_held[key]
  268. }
  269. mouse_button_went_down :: proc(button: Mouse_Button) -> bool {
  270. return s.mouse_button_went_down[button]
  271. }
  272. mouse_button_went_up :: proc(button: Mouse_Button) -> bool {
  273. return s.mouse_button_went_up[button]
  274. }
  275. mouse_button_is_held :: proc(button: Mouse_Button) -> bool {
  276. return s.mouse_button_is_held[button]
  277. }
  278. get_mouse_wheel_delta :: proc() -> f32 {
  279. return s.mouse_wheel_delta
  280. }
  281. get_mouse_position :: proc() -> Vec2 {
  282. return s.mouse_position
  283. }
  284. get_mouse_delta :: proc() -> Vec2 {
  285. return s.mouse_delta
  286. }
  287. is_gamepad_active :: proc(gamepad: Gamepad_Index) -> bool {
  288. return win.is_gamepad_active(gamepad)
  289. }
  290. gamepad_button_went_down :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  291. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  292. return false
  293. }
  294. return s.gamepad_button_went_down[gamepad][button]
  295. }
  296. gamepad_button_went_up :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  297. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  298. return false
  299. }
  300. return s.gamepad_button_went_up[gamepad][button]
  301. }
  302. gamepad_button_is_held :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  303. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  304. return false
  305. }
  306. return s.gamepad_button_is_held[gamepad][button]
  307. }
  308. get_gamepad_axis :: proc(gamepad: Gamepad_Index, axis: Gamepad_Axis) -> f32 {
  309. return win.get_gamepad_axis(gamepad, axis)
  310. }
  311. // Set the left and right vibration motor speed. The range of left and right is 0 to 1. Note that on
  312. // most gamepads, the left motor is "low frequency" and the right motor is "high frequency". They do
  313. // not vibrate with the same speed.
  314. set_gamepad_vibration :: proc(gamepad: Gamepad_Index, left: f32, right: f32) {
  315. win.set_gamepad_vibration(gamepad, left, right)
  316. }
  317. //---------//
  318. // DRAWING //
  319. //---------//
  320. draw_rect :: proc(r: Rect, c: Color) {
  321. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  322. draw_current_batch()
  323. }
  324. if s.batch_texture != s.shape_drawing_texture {
  325. draw_current_batch()
  326. }
  327. s.batch_texture = s.shape_drawing_texture
  328. z := get_next_depth()
  329. batch_vertex({r.x, r.y, z}, {0, 0}, c)
  330. batch_vertex({r.x + r.w, r.y, z}, {1, 0}, c)
  331. batch_vertex({r.x + r.w, r.y + r.h, z}, {1, 1}, c)
  332. batch_vertex({r.x, r.y, z}, {0, 0}, c)
  333. batch_vertex({r.x + r.w, r.y + r.h, z}, {1, 1}, c)
  334. batch_vertex({r.x, r.y + r.h, z}, {0, 1}, c)
  335. }
  336. draw_rect_vec :: proc(pos: Vec2, size: Vec2, c: Color) {
  337. draw_rect({pos.x, pos.y, size.x, size.y}, c)
  338. }
  339. draw_rect_ex :: proc(r: Rect, origin: Vec2, rot: f32, c: Color) {
  340. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  341. draw_current_batch()
  342. }
  343. if s.batch_texture != s.shape_drawing_texture {
  344. draw_current_batch()
  345. }
  346. s.batch_texture = s.shape_drawing_texture
  347. tl, tr, bl, br: Vec2
  348. // Rotation adapted from Raylib's "DrawTexturePro"
  349. if rot == 0 {
  350. x := r.x - origin.x
  351. y := r.y - origin.y
  352. tl = { x, y }
  353. tr = { x + r.w, y }
  354. bl = { x, y + r.h }
  355. br = { x + r.w, y + r.h }
  356. } else {
  357. sin_rot := math.sin(rot * math.RAD_PER_DEG)
  358. cos_rot := math.cos(rot * math.RAD_PER_DEG)
  359. x := r.x
  360. y := r.y
  361. dx := -origin.x
  362. dy := -origin.y
  363. tl = {
  364. x + dx * cos_rot - dy * sin_rot,
  365. y + dx * sin_rot + dy * cos_rot,
  366. }
  367. tr = {
  368. x + (dx + r.w) * cos_rot - dy * sin_rot,
  369. y + (dx + r.w) * sin_rot + dy * cos_rot,
  370. }
  371. bl = {
  372. x + dx * cos_rot - (dy + r.h) * sin_rot,
  373. y + dx * sin_rot + (dy + r.h) * cos_rot,
  374. }
  375. br = {
  376. x + (dx + r.w) * cos_rot - (dy + r.h) * sin_rot,
  377. y + (dx + r.w) * sin_rot + (dy + r.h) * cos_rot,
  378. }
  379. }
  380. z := get_next_depth()
  381. batch_vertex(vec3(tl, z), {0, 0}, c)
  382. batch_vertex(vec3(tr, z), {1, 0}, c)
  383. batch_vertex(vec3(br, z), {1, 1}, c)
  384. batch_vertex(vec3(tl, z), {0, 0}, c)
  385. batch_vertex(vec3(br, z), {1, 1}, c)
  386. batch_vertex(vec3(bl, z), {0, 1}, c)
  387. }
  388. draw_rect_outline :: proc(r: Rect, thickness: f32, color: Color) {
  389. t := thickness
  390. // Based on DrawRectangleLinesEx from Raylib
  391. top := Rect {
  392. r.x,
  393. r.y,
  394. r.w,
  395. t,
  396. }
  397. bottom := Rect {
  398. r.x,
  399. r.y + r.h - t,
  400. r.w,
  401. t,
  402. }
  403. left := Rect {
  404. r.x,
  405. r.y + t,
  406. t,
  407. r.h - t * 2,
  408. }
  409. right := Rect {
  410. r.x + r.w - t,
  411. r.y + t,
  412. t,
  413. r.h - t * 2,
  414. }
  415. draw_rect(top, color)
  416. draw_rect(bottom, color)
  417. draw_rect(left, color)
  418. draw_rect(right, color)
  419. }
  420. draw_circle :: proc(center: Vec2, radius: f32, color: Color, segments := 16) {
  421. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 3 * segments > len(s.vertex_buffer_cpu) {
  422. draw_current_batch()
  423. }
  424. if s.batch_texture != s.shape_drawing_texture {
  425. draw_current_batch()
  426. }
  427. s.batch_texture = s.shape_drawing_texture
  428. z := get_next_depth()
  429. prev := center + {radius, 0}
  430. for s in 1..=segments {
  431. sr := (f32(s)/f32(segments)) * 2*math.PI
  432. rot := linalg.matrix2_rotate(sr)
  433. p := center + rot * Vec2{radius, 0}
  434. batch_vertex(vec3(prev, z), {0, 0}, color)
  435. batch_vertex(vec3(p, z), {1, 0}, color)
  436. batch_vertex(vec3(center, z), {1, 1}, color)
  437. prev = p
  438. }
  439. }
  440. draw_circle_outline :: proc(center: Vec2, radius: f32, thickness: f32, color: Color, segments := 16) {
  441. prev := center + {radius, 0}
  442. for s in 1..=segments {
  443. sr := (f32(s)/f32(segments)) * 2*math.PI
  444. rot := linalg.matrix2_rotate(sr)
  445. p := center + rot * Vec2{radius, 0}
  446. draw_line(prev, p, thickness, color)
  447. prev = p
  448. }
  449. }
  450. draw_line :: proc(start: Vec2, end: Vec2, thickness: f32, color: Color) {
  451. p := Vec2{start.x, start.y + thickness*0.5}
  452. s := Vec2{linalg.length(end - start), thickness}
  453. origin := Vec2 {0, thickness*0.5}
  454. r := Rect {p.x, p.y, s.x, s.y}
  455. rot := math.atan2(end.y - start.y, end.x - start.x)
  456. draw_rect_ex(r, origin, rot * math.DEG_PER_RAD, color)
  457. }
  458. draw_texture :: proc(tex: Texture, pos: Vec2, tint := WHITE) {
  459. draw_texture_ex(
  460. tex,
  461. {0, 0, f32(tex.width), f32(tex.height)},
  462. {pos.x, pos.y, f32(tex.width), f32(tex.height)},
  463. {},
  464. 0,
  465. tint,
  466. )
  467. }
  468. draw_texture_rect :: proc(tex: Texture, rect: Rect, pos: Vec2, tint := WHITE) {
  469. draw_texture_ex(
  470. tex,
  471. rect,
  472. {pos.x, pos.y, rect.w, rect.h},
  473. {},
  474. 0,
  475. tint,
  476. )
  477. }
  478. draw_texture_ex :: proc(tex: Texture, src: Rect, dst: Rect, origin: Vec2, rotation: f32, tint := WHITE) {
  479. if tex.width == 0 || tex.height == 0 {
  480. return
  481. }
  482. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  483. draw_current_batch()
  484. }
  485. if s.batch_texture != tex.handle {
  486. draw_current_batch()
  487. }
  488. s.batch_texture = tex.handle
  489. flip_x, flip_y: bool
  490. src := src
  491. dst := dst
  492. if src.w < 0 {
  493. flip_x = true
  494. src.w = -src.w
  495. }
  496. if src.h < 0 {
  497. flip_y = true
  498. src.h = -src.h
  499. }
  500. if dst.w < 0 {
  501. dst.w *= -1
  502. }
  503. if dst.h < 0 {
  504. dst.h *= -1
  505. }
  506. tl, tr, bl, br: Vec2
  507. // Rotation adapted from Raylib's "DrawTexturePro"
  508. if rotation == 0 {
  509. x := dst.x - origin.x
  510. y := dst.y - origin.y
  511. tl = { x, y }
  512. tr = { x + dst.w, y }
  513. bl = { x, y + dst.h }
  514. br = { x + dst.w, y + dst.h }
  515. } else {
  516. sin_rot := math.sin(rotation * math.RAD_PER_DEG)
  517. cos_rot := math.cos(rotation * math.RAD_PER_DEG)
  518. x := dst.x
  519. y := dst.y
  520. dx := -origin.x
  521. dy := -origin.y
  522. tl = {
  523. x + dx * cos_rot - dy * sin_rot,
  524. y + dx * sin_rot + dy * cos_rot,
  525. }
  526. tr = {
  527. x + (dx + dst.w) * cos_rot - dy * sin_rot,
  528. y + (dx + dst.w) * sin_rot + dy * cos_rot,
  529. }
  530. bl = {
  531. x + dx * cos_rot - (dy + dst.h) * sin_rot,
  532. y + dx * sin_rot + (dy + dst.h) * cos_rot,
  533. }
  534. br = {
  535. x + (dx + dst.w) * cos_rot - (dy + dst.h) * sin_rot,
  536. y + (dx + dst.w) * sin_rot + (dy + dst.h) * cos_rot,
  537. }
  538. }
  539. ts := Vec2{f32(tex.width), f32(tex.height)}
  540. up := Vec2{src.x, src.y} / ts
  541. us := Vec2{src.w, src.h} / ts
  542. c := tint
  543. uv0 := up
  544. uv1 := up + {us.x, 0}
  545. uv2 := up + us
  546. uv3 := up
  547. uv4 := up + us
  548. uv5 := up + {0, us.y}
  549. if flip_x {
  550. uv0.x += us.x
  551. uv1.x -= us.x
  552. uv2.x -= us.x
  553. uv3.x += us.x
  554. uv4.x -= us.x
  555. uv5.x += us.x
  556. }
  557. if flip_y {
  558. uv0.y += us.y
  559. uv1.y += us.y
  560. uv2.y -= us.y
  561. uv3.y += us.y
  562. uv4.y -= us.y
  563. uv5.y -= us.y
  564. }
  565. z := get_next_depth()
  566. batch_vertex(vec3(tl, z), uv0, c)
  567. batch_vertex(vec3(tr, z), uv1, c)
  568. batch_vertex(vec3(br, z), uv2, c)
  569. batch_vertex(vec3(tl, z), uv3, c)
  570. batch_vertex(vec3(br, z), uv4, c)
  571. batch_vertex(vec3(bl, z), uv5, c)
  572. }
  573. measure_text :: proc(text: string, font_size: f32) -> Vec2 {
  574. fs.SetSize(&s.fs, font_size)
  575. b: [4]f32
  576. fs.TextBounds(&s.fs, text, bounds = &b)
  577. return {b[2] - b[0], b[3] - b[1]}
  578. }
  579. draw_text :: proc(text: string, pos: Vec2, font_size: f32, color: Color) {
  580. draw_text_ex(s.default_font, text, pos, font_size, color)
  581. }
  582. draw_text_ex :: proc(font: Font_Handle, text: string, pos: Vec2, font_size: f32, color: Color) {
  583. if int(font) >= len(s.fonts) {
  584. return
  585. }
  586. set_font(font)
  587. font := &s.fonts[font]
  588. fs.SetSize(&s.fs, font_size)
  589. iter := fs.TextIterInit(&s.fs, pos.x, pos.y+font_size/2, text)
  590. q: fs.Quad
  591. for fs.TextIterNext(&s.fs, &iter, &q) {
  592. src := Rect {
  593. q.s0, q.t0,
  594. q.s1 - q.s0, q.t1 - q.t0,
  595. }
  596. w := f32(FONT_DEFAULT_ATLAS_SIZE)
  597. h := f32(FONT_DEFAULT_ATLAS_SIZE)
  598. src.x *= w
  599. src.y *= h
  600. src.w *= w
  601. src.h *= h
  602. dst := Rect {
  603. q.x0, q.y0,
  604. q.x1 - q.x0, q.y1 - q.y0,
  605. }
  606. draw_texture_ex(font.atlas, src, dst, {}, 0, color)
  607. }
  608. }
  609. //--------------------//
  610. // TEXTURE MANAGEMENT //
  611. //--------------------//
  612. create_texture :: proc(width: int, height: int, format: Pixel_Format) -> Texture {
  613. h := rb.create_texture(width, height, format)
  614. return {
  615. handle = h,
  616. width = width,
  617. height = height,
  618. }
  619. }
  620. load_texture_from_file :: proc(filename: string) -> Texture {
  621. img, img_err := image.load_from_file(filename, options = {.alpha_add_if_missing}, allocator = s.frame_allocator)
  622. if img_err != nil {
  623. log.errorf("Error loading texture %v: %v", filename, img_err)
  624. return {}
  625. }
  626. return load_texture_from_bytes(img.pixels.buf[:], img.width, img.height, .RGBA_8_Norm)
  627. }
  628. // TODO should we have an error here or rely on check the handle of the texture?
  629. load_texture_from_bytes :: proc(bytes: []u8, width: int, height: int, format: Pixel_Format) -> Texture {
  630. backend_tex := rb.load_texture(bytes[:], width, height, format)
  631. if backend_tex == TEXTURE_NONE {
  632. return {}
  633. }
  634. return {
  635. handle = backend_tex,
  636. width = width,
  637. height = height,
  638. }
  639. }
  640. // Get a rectangle that spans the whole texture. Coordinates will be (x, y) = (0, 0) and size
  641. // (w, h) = (texture_width, texture_height)
  642. get_texture_rect :: proc(t: Texture) -> Rect {
  643. return {
  644. 0, 0,
  645. f32(t.width), f32(t.height),
  646. }
  647. }
  648. // Update a texture with new pixels. `bytes` is the new pixel data. `rect` is the rectangle in
  649. // `tex` where the new pixels should end up.
  650. update_texture :: proc(tex: Texture, bytes: []u8, rect: Rect) -> bool {
  651. return rb.update_texture(tex.handle, bytes, rect)
  652. }
  653. destroy_texture :: proc(tex: Texture) {
  654. rb.destroy_texture(tex.handle)
  655. }
  656. // Controls how a texture should be filtered. You can choose "point" or "linear" filtering. Which
  657. // means "pixly" or "smooth". This filter will be used for up and down-scaling as well as for
  658. // mipmap sampling. Use `set_texture_filter_ex` if you need to control these settings separately.
  659. set_texture_filter :: proc(t: Texture, filter: Texture_Filter) {
  660. set_texture_filter_ex(t, filter, filter, filter)
  661. }
  662. // Controls how a texture should be filtered. `scale_down_filter` and `scale_up_filter` controls how
  663. // the texture is filtered when we render the texture at a smaller or larger size.
  664. // `mip_filter` controls how the texture is filtered when it is sampled using _mipmapping_.
  665. //
  666. // TODO: Add mipmapping generation controls for texture and refer to it from here.
  667. set_texture_filter_ex :: proc(
  668. t: Texture,
  669. scale_down_filter: Texture_Filter,
  670. scale_up_filter: Texture_Filter,
  671. mip_filter: Texture_Filter,
  672. ) {
  673. rb.set_texture_filter(t.handle, scale_down_filter, scale_up_filter, mip_filter)
  674. }
  675. //-----------------//
  676. // RENDER TEXTURES //
  677. //-----------------//
  678. create_render_texture :: proc(width: int, height: int) -> Render_Texture {
  679. texture, render_target := rb.create_render_texture(width, height)
  680. return {
  681. texture = {
  682. handle = texture,
  683. width = width,
  684. height = height,
  685. },
  686. render_target = render_target,
  687. }
  688. }
  689. destroy_render_texture :: proc(render_texture: Render_Texture) {
  690. rb.destroy_texture(render_texture.texture.handle)
  691. rb.destroy_render_target(render_texture.render_target)
  692. }
  693. set_render_texture :: proc(render_texture: Maybe(Render_Texture)) {
  694. if rt, rt_ok := render_texture.?; rt_ok {
  695. if s.batch_render_target == rt.render_target {
  696. return
  697. }
  698. draw_current_batch()
  699. s.batch_render_target = rt.render_target
  700. } else {
  701. if s.batch_render_target == RENDER_TARGET_NONE {
  702. return
  703. }
  704. draw_current_batch()
  705. s.batch_render_target = RENDER_TARGET_NONE
  706. }
  707. }
  708. //-------//
  709. // FONTS //
  710. //-------//
  711. load_font_from_file :: proc(filename: string) -> Font_Handle {
  712. if data, data_ok := os.read_entire_file(filename, frame_allocator); data_ok {
  713. return load_font_from_bytes(data)
  714. }
  715. return FONT_NONE
  716. }
  717. load_font_from_bytes :: proc(data: []u8) -> Font_Handle {
  718. font := fs.AddFontMem(&s.fs, "", data, false)
  719. h := Font_Handle(len(s.fonts))
  720. append(&s.fonts, Font {
  721. fontstash_handle = font,
  722. atlas = {
  723. handle = rb.create_texture(FONT_DEFAULT_ATLAS_SIZE, FONT_DEFAULT_ATLAS_SIZE, .RGBA_8_Norm),
  724. width = FONT_DEFAULT_ATLAS_SIZE,
  725. height = FONT_DEFAULT_ATLAS_SIZE,
  726. },
  727. })
  728. return h
  729. }
  730. destroy_font :: proc(font: Font_Handle) {
  731. if int(font) >= len(s.fonts) {
  732. return
  733. }
  734. f := &s.fonts[font]
  735. rb.destroy_texture(f.atlas.handle)
  736. // TODO fontstash has no "destroy font" proc... I should make my own version of fontstash
  737. delete(s.fs.fonts[f.fontstash_handle].glyphs)
  738. s.fs.fonts[f.fontstash_handle].glyphs = {}
  739. }
  740. get_default_font :: proc() -> Font_Handle {
  741. return s.default_font
  742. }
  743. //---------//
  744. // SHADERS //
  745. //---------//
  746. load_shader :: proc(
  747. vertex_shader_source: string,
  748. fragment_shader_source: string,
  749. layout_formats: []Pixel_Format = {},
  750. ) -> Shader {
  751. handle, desc := rb.load_shader(
  752. vertex_shader_source,
  753. fragment_shader_source,
  754. s.frame_allocator,
  755. layout_formats,
  756. )
  757. if handle == SHADER_NONE {
  758. log.error("Failed loading shader")
  759. return {}
  760. }
  761. constants_size: int
  762. for c in desc.constants {
  763. constants_size += c.size
  764. }
  765. shd := Shader {
  766. handle = handle,
  767. constants_data = make([]u8, constants_size, s.allocator),
  768. constants = make([]Shader_Constant_Location, len(desc.constants), s.allocator),
  769. constant_lookup = make(map[string]Shader_Constant_Location, s.allocator),
  770. inputs = slice.clone(desc.inputs, s.allocator),
  771. input_overrides = make([]Shader_Input_Value_Override, len(desc.inputs), s.allocator),
  772. texture_bindpoints = make([]Texture_Handle, len(desc.texture_bindpoints), s.allocator),
  773. texture_lookup = make(map[string]int, s.allocator),
  774. }
  775. for &input in shd.inputs {
  776. input.name = strings.clone(input.name, s.allocator)
  777. }
  778. constant_offset: int
  779. for cidx in 0..<len(desc.constants) {
  780. constant_desc := &desc.constants[cidx]
  781. loc := Shader_Constant_Location {
  782. offset = constant_offset,
  783. size = constant_desc.size,
  784. }
  785. shd.constants[cidx] = loc
  786. constant_offset += constant_desc.size
  787. if constant_desc.name != "" {
  788. shd.constant_lookup[strings.clone(constant_desc.name, s.allocator)] = loc
  789. switch constant_desc.name {
  790. case "mvp":
  791. shd.constant_builtin_locations[.MVP] = loc
  792. }
  793. }
  794. }
  795. for tbp, tbp_idx in desc.texture_bindpoints {
  796. shd.texture_lookup[tbp.name] = tbp_idx
  797. if tbp.name == "tex" {
  798. shd.default_texture_index = tbp_idx
  799. }
  800. }
  801. for &d in shd.default_input_offsets {
  802. d = -1
  803. }
  804. input_offset: int
  805. for &input in shd.inputs {
  806. default_format := get_shader_input_default_type(input.name, input.type)
  807. if default_format != .Unknown {
  808. shd.default_input_offsets[default_format] = input_offset
  809. }
  810. input_offset += pixel_format_size(input.format)
  811. }
  812. shd.vertex_size = input_offset
  813. return shd
  814. }
  815. destroy_shader :: proc(shader: Shader) {
  816. rb.destroy_shader(shader.handle)
  817. a := s.allocator
  818. delete(shader.constants_data, a)
  819. delete(shader.constants, a)
  820. delete(shader.texture_lookup)
  821. delete(shader.texture_bindpoints, a)
  822. for k, _ in shader.constant_lookup {
  823. delete(k, a)
  824. }
  825. delete(shader.constant_lookup)
  826. for i in shader.inputs {
  827. delete(i.name, a)
  828. }
  829. delete(shader.inputs, a)
  830. delete(shader.input_overrides, a)
  831. }
  832. get_default_shader :: proc() -> Shader {
  833. return s.default_shader
  834. }
  835. set_shader :: proc(shader: Maybe(Shader)) {
  836. if shd, shd_ok := shader.?; shd_ok {
  837. if shd.handle == s.batch_shader.handle {
  838. return
  839. }
  840. } else {
  841. if s.batch_shader.handle == s.default_shader.handle {
  842. return
  843. }
  844. }
  845. draw_current_batch()
  846. s.batch_shader = shader.? or_else s.default_shader
  847. }
  848. set_shader_constant :: proc(shd: Shader, loc: Shader_Constant_Location, val: any) {
  849. if shd.handle == SHADER_NONE {
  850. log.error("Invalid shader")
  851. return
  852. }
  853. if loc.size == 0 {
  854. log.error("Could not find shader constant")
  855. return
  856. }
  857. draw_current_batch()
  858. if loc.offset + loc.size > len(shd.constants_data) {
  859. log.errorf("Constant with offset %v and size %v is out of bounds. Buffer ends at %v", loc.offset, loc.size, len(shd.constants_data))
  860. return
  861. }
  862. sz := reflect.size_of_typeid(val.id)
  863. if sz != loc.size {
  864. log.errorf("Trying to set constant of type %v, but it is not of correct size %v", val.id, loc.size)
  865. return
  866. }
  867. mem.copy(&shd.constants_data[loc.offset], val.data, sz)
  868. }
  869. override_shader_input :: proc(shader: Shader, input: int, val: any) {
  870. sz := reflect.size_of_typeid(val.id)
  871. assert(sz < SHADER_INPUT_VALUE_MAX_SIZE)
  872. if input >= len(shader.input_overrides) {
  873. log.errorf("Input override out of range. Wanted to override input %v, but shader only has %v inputs", input, len(shader.input_overrides))
  874. return
  875. }
  876. o := &shader.input_overrides[input]
  877. o.val = {}
  878. if sz > 0 {
  879. mem.copy(raw_data(&o.val), val.data, sz)
  880. }
  881. o.used = sz
  882. }
  883. pixel_format_size :: proc(f: Pixel_Format) -> int {
  884. switch f {
  885. case .Unknown: return 0
  886. case .RGBA_32_Float: return 32
  887. case .RGB_32_Float: return 12
  888. case .RG_32_Float: return 8
  889. case .R_32_Float: return 4
  890. case .RGBA_8_Norm: return 4
  891. case .RG_8_Norm: return 2
  892. case .R_8_Norm: return 1
  893. case .R_8_UInt: return 1
  894. }
  895. return 0
  896. }
  897. //-------------------------------//
  898. // CAMERA AND COORDINATE SYSTEMS //
  899. //-------------------------------//
  900. set_camera :: proc(camera: Maybe(Camera)) {
  901. if camera == s.batch_camera {
  902. return
  903. }
  904. draw_current_batch()
  905. s.batch_camera = camera
  906. s.proj_matrix = make_default_projection(win.get_width(), win.get_height())
  907. if c, c_ok := camera.?; c_ok {
  908. s.view_matrix = get_camera_view_matrix(c)
  909. } else {
  910. s.view_matrix = 1
  911. }
  912. }
  913. screen_to_world :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  914. return (get_camera_world_matrix(camera) * Vec4 { pos.x, pos.y, 0, 1 }).xy
  915. }
  916. world_to_screen :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  917. return (get_camera_view_matrix(camera) * Vec4 { pos.x, pos.y, 0, 1 }).xy
  918. }
  919. get_camera_view_matrix :: proc(c: Camera) -> Mat4 {
  920. inv_target_translate := linalg.matrix4_translate(vec3_from_vec2(-c.target))
  921. inv_rot := linalg.matrix4_rotate_f32(c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  922. inv_scale := linalg.matrix4_scale(Vec3{c.zoom, c.zoom, 1})
  923. inv_offset_translate := linalg.matrix4_translate(vec3_from_vec2(c.offset))
  924. // A view matrix is essentially the world transform matrix of the camera, but inverted. We
  925. // bring everything in the world "in front of the camera".
  926. //
  927. // Instead of constructing the camera matrix and doing a matrix inverse, here we just do the
  928. // maths in "backwards order". I.e. a camera transform matrix would be:
  929. //
  930. // target_translate * rot * scale * offset_translate
  931. return inv_offset_translate * inv_scale * inv_rot * inv_target_translate
  932. }
  933. get_camera_world_matrix :: proc(c: Camera) -> Mat4 {
  934. offset_translate := linalg.matrix4_translate(vec3_from_vec2(-c.offset))
  935. rot := linalg.matrix4_rotate_f32(-c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  936. scale := linalg.matrix4_scale(Vec3{1/c.zoom, 1/c.zoom, 1})
  937. target_translate := linalg.matrix4_translate(vec3_from_vec2(c.target))
  938. return target_translate * rot * scale * offset_translate
  939. }
  940. //------//
  941. // MISC //
  942. //------//
  943. set_scissor_rect :: proc(scissor_rect: Maybe(Rect)) {
  944. draw_current_batch()
  945. s.batch_scissor = scissor_rect
  946. }
  947. // Restore the internal state using the pointer returned by `init`. Useful after reloading the
  948. // library (for example, when doing code hot reload).
  949. set_internal_state :: proc(state: ^State) {
  950. s = state
  951. rb = s.rb
  952. win = s.win
  953. rb.set_internal_state(s.rb_state)
  954. win.set_internal_state(s.window_state)
  955. }
  956. //---------------------//
  957. // TYPES AND CONSTANTS //
  958. //---------------------//
  959. Vec2 :: [2]f32
  960. Vec3 :: [3]f32
  961. Vec4 :: [4]f32
  962. Mat4 :: matrix[4,4]f32
  963. // A two dimensional vector of integer numeric type.
  964. Vec2i :: [2]int
  965. // A rectangle that sits at position (x, y) and has size (w, h).
  966. Rect :: struct {
  967. x, y: f32,
  968. w, h: f32,
  969. }
  970. // An RGBA (Red, Green, Blue, Alpha) color. Each channel can have a value between 0 and 255.
  971. Color :: [4]u8
  972. WHITE :: Color { 255, 255, 255, 255 }
  973. BLACK :: Color { 0, 0, 0, 255 }
  974. GRAY :: Color { 127, 127, 127, 255 }
  975. RED :: Color { 198, 40, 90, 255 }
  976. GREEN :: Color { 30, 240, 30, 255 }
  977. BLANK :: Color { 0, 0, 0, 0 }
  978. BLUE :: Color { 30, 116, 240, 255 }
  979. // These are from Raylib. They are here so you can easily port a Raylib program to Karl2D.
  980. RL_LIGHTGRAY :: Color { 200, 200, 200, 255 }
  981. RL_GRAY :: Color { 130, 130, 130, 255 }
  982. RL_DARKGRAY :: Color { 80, 80, 80, 255 }
  983. RL_YELLOW :: Color { 253, 249, 0, 255 }
  984. RL_GOLD :: Color { 255, 203, 0, 255 }
  985. RL_ORANGE :: Color { 255, 161, 0, 255 }
  986. RL_PINK :: Color { 255, 109, 194, 255 }
  987. RL_RED :: Color { 230, 41, 55, 255 }
  988. RL_MAROON :: Color { 190, 33, 55, 255 }
  989. RL_GREEN :: Color { 0, 228, 48, 255 }
  990. RL_LIME :: Color { 0, 158, 47, 255 }
  991. RL_DARKGREEN :: Color { 0, 117, 44, 255 }
  992. RL_SKYBLUE :: Color { 102, 191, 255, 255 }
  993. RL_BLUE :: Color { 0, 121, 241, 255 }
  994. RL_DARKBLUE :: Color { 0, 82, 172, 255 }
  995. RL_PURPLE :: Color { 200, 122, 255, 255 }
  996. RL_VIOLET :: Color { 135, 60, 190, 255 }
  997. RL_DARKPURPLE :: Color { 112, 31, 126, 255 }
  998. RL_BEIGE :: Color { 211, 176, 131, 255 }
  999. RL_BROWN :: Color { 127, 106, 79, 255 }
  1000. RL_DARKBROWN :: Color { 76, 63, 47, 255 }
  1001. RL_WHITE :: WHITE
  1002. RL_BLACK :: BLACK
  1003. RL_BLANK :: BLANK
  1004. RL_MAGENTA :: Color { 255, 0, 255, 255 }
  1005. RL_RAYWHITE :: Color { 245, 245, 245, 255 }
  1006. Texture :: struct {
  1007. handle: Texture_Handle,
  1008. width: int,
  1009. height: int,
  1010. }
  1011. Render_Texture :: struct {
  1012. texture: Texture,
  1013. render_target: Render_Target_Handle,
  1014. }
  1015. Texture_Filter :: enum {
  1016. Point, // Similar to "nearest neighbor". Pixly texture scaling.
  1017. Linear, // Smoothed texture scaling.
  1018. }
  1019. Camera :: struct {
  1020. target: Vec2,
  1021. offset: Vec2,
  1022. rotation: f32,
  1023. zoom: f32,
  1024. }
  1025. Window_Flag :: enum {
  1026. Resizable,
  1027. }
  1028. Window_Flags :: bit_set[Window_Flag]
  1029. Shader_Handle :: distinct Handle
  1030. SHADER_NONE :: Shader_Handle {}
  1031. Shader_Constant_Location :: struct {
  1032. offset: int,
  1033. size: int,
  1034. }
  1035. Shader :: struct {
  1036. handle: Shader_Handle,
  1037. // We store the CPU-side value of all constants in a single buffer to have less allocations.
  1038. // The 'constants' array says where in this buffer each constant is, and 'constant_lookup'
  1039. // maps a name to a constant location.
  1040. constants_data: []u8,
  1041. constants: []Shader_Constant_Location,
  1042. constant_lookup: map[string]Shader_Constant_Location,
  1043. // Maps built in constant types such as "model view projection matrix" to a location.
  1044. constant_builtin_locations: [Shader_Builtin_Constant]Maybe(Shader_Constant_Location),
  1045. texture_bindpoints: []Texture_Handle,
  1046. texture_lookup: map[string]int,
  1047. default_texture_index: Maybe(int),
  1048. inputs: []Shader_Input,
  1049. input_overrides: []Shader_Input_Value_Override,
  1050. default_input_offsets: [Shader_Default_Inputs]int,
  1051. vertex_size: int,
  1052. }
  1053. SHADER_INPUT_VALUE_MAX_SIZE :: 256
  1054. Shader_Input_Value_Override :: struct {
  1055. val: [SHADER_INPUT_VALUE_MAX_SIZE]u8,
  1056. used: int,
  1057. }
  1058. Shader_Input_Type :: enum {
  1059. F32,
  1060. Vec2,
  1061. Vec3,
  1062. Vec4,
  1063. }
  1064. Shader_Builtin_Constant :: enum {
  1065. MVP,
  1066. }
  1067. Shader_Default_Inputs :: enum {
  1068. Unknown,
  1069. Position,
  1070. UV,
  1071. Color,
  1072. }
  1073. Shader_Input :: struct {
  1074. name: string,
  1075. register: int,
  1076. type: Shader_Input_Type,
  1077. format: Pixel_Format,
  1078. }
  1079. Pixel_Format :: enum {
  1080. Unknown,
  1081. RGBA_32_Float,
  1082. RGB_32_Float,
  1083. RG_32_Float,
  1084. R_32_Float,
  1085. RGBA_8_Norm,
  1086. RG_8_Norm,
  1087. R_8_Norm,
  1088. R_8_UInt,
  1089. }
  1090. Font :: struct {
  1091. atlas: Texture,
  1092. // internal
  1093. fontstash_handle: int,
  1094. }
  1095. Handle :: hm.Handle
  1096. Texture_Handle :: distinct Handle
  1097. Render_Target_Handle :: distinct Handle
  1098. Font_Handle :: distinct int
  1099. FONT_NONE :: Font_Handle {}
  1100. TEXTURE_NONE :: Texture_Handle {}
  1101. RENDER_TARGET_NONE :: Render_Target_Handle {}
  1102. // This keeps track of the internal state of the library. Usually, you do not need to poke at it.
  1103. // It is created and kept as a global variable when 'init' is called. However, 'init' also returns
  1104. // the pointer to it, so you can later use 'set_internal_state' to restore it (after for example hot
  1105. // reload).
  1106. State :: struct {
  1107. allocator: runtime.Allocator,
  1108. frame_arena: runtime.Arena,
  1109. frame_allocator: runtime.Allocator,
  1110. win: Window_Interface,
  1111. window_state: rawptr,
  1112. rb: Render_Backend_Interface,
  1113. rb_state: rawptr,
  1114. fs: fs.FontContext,
  1115. shutdown_wanted: bool,
  1116. mouse_position: Vec2,
  1117. mouse_delta: Vec2,
  1118. mouse_wheel_delta: f32,
  1119. key_went_down: #sparse [Keyboard_Key]bool,
  1120. key_went_up: #sparse [Keyboard_Key]bool,
  1121. key_is_held: #sparse [Keyboard_Key]bool,
  1122. mouse_button_went_down: #sparse [Mouse_Button]bool,
  1123. mouse_button_went_up: #sparse [Mouse_Button]bool,
  1124. mouse_button_is_held: #sparse [Mouse_Button]bool,
  1125. gamepad_button_went_down: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1126. gamepad_button_went_up: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1127. gamepad_button_is_held: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1128. window: Window_Handle,
  1129. default_font: Font_Handle,
  1130. fonts: [dynamic]Font,
  1131. shape_drawing_texture: Texture_Handle,
  1132. batch_font: Font_Handle,
  1133. batch_camera: Maybe(Camera),
  1134. batch_shader: Shader,
  1135. batch_scissor: Maybe(Rect),
  1136. batch_texture: Texture_Handle,
  1137. batch_render_target: Render_Target_Handle,
  1138. view_matrix: Mat4,
  1139. proj_matrix: Mat4,
  1140. depth: f32,
  1141. depth_start: f32,
  1142. depth_increment: f32,
  1143. vertex_buffer_cpu: []u8,
  1144. vertex_buffer_cpu_used: int,
  1145. default_shader: Shader,
  1146. }
  1147. // Support for up to 255 mouse buttons. Cast an int to type `Mouse_Button` to use things outside the
  1148. // options presented here.
  1149. Mouse_Button :: enum {
  1150. Left,
  1151. Right,
  1152. Middle,
  1153. Max = 255,
  1154. }
  1155. // Based on Raylib / GLFW
  1156. Keyboard_Key :: enum {
  1157. None = 0,
  1158. // Numeric keys (top row)
  1159. N0 = 48,
  1160. N1 = 49,
  1161. N2 = 50,
  1162. N3 = 51,
  1163. N4 = 52,
  1164. N5 = 53,
  1165. N6 = 54,
  1166. N7 = 55,
  1167. N8 = 56,
  1168. N9 = 57,
  1169. // Letter keys
  1170. A = 65,
  1171. B = 66,
  1172. C = 67,
  1173. D = 68,
  1174. E = 69,
  1175. F = 70,
  1176. G = 71,
  1177. H = 72,
  1178. I = 73,
  1179. J = 74,
  1180. K = 75,
  1181. L = 76,
  1182. M = 77,
  1183. N = 78,
  1184. O = 79,
  1185. P = 80,
  1186. Q = 81,
  1187. R = 82,
  1188. S = 83,
  1189. T = 84,
  1190. U = 85,
  1191. V = 86,
  1192. W = 87,
  1193. X = 88,
  1194. Y = 89,
  1195. Z = 90,
  1196. // Special characters
  1197. Apostrophe = 39,
  1198. Comma = 44,
  1199. Minus = 45,
  1200. Period = 46,
  1201. Slash = 47,
  1202. Semicolon = 59,
  1203. Equal = 61,
  1204. Left_Bracket = 91,
  1205. Backslash = 92,
  1206. Right_Bracket = 93,
  1207. Grave_Accent = 96,
  1208. // Function keys, modifiers, caret control etc
  1209. Space = 32,
  1210. Escape = 256,
  1211. Enter = 257,
  1212. Tab = 258,
  1213. Backspace = 259,
  1214. Insert = 260,
  1215. Delete = 261,
  1216. Right = 262,
  1217. Left = 263,
  1218. Down = 264,
  1219. Up = 265,
  1220. Page_Up = 266,
  1221. Page_Down = 267,
  1222. Home = 268,
  1223. End = 269,
  1224. Caps_Lock = 280,
  1225. Scroll_Lock = 281,
  1226. Num_Lock = 282,
  1227. Print_Screen = 283,
  1228. Pause = 284,
  1229. F1 = 290,
  1230. F2 = 291,
  1231. F3 = 292,
  1232. F4 = 293,
  1233. F5 = 294,
  1234. F6 = 295,
  1235. F7 = 296,
  1236. F8 = 297,
  1237. F9 = 298,
  1238. F10 = 299,
  1239. F11 = 300,
  1240. F12 = 301,
  1241. Left_Shift = 340,
  1242. Left_Control = 341,
  1243. Left_Alt = 342,
  1244. Left_Super = 343,
  1245. Right_Shift = 344,
  1246. Right_Control = 345,
  1247. Right_Alt = 346,
  1248. Right_Super = 347,
  1249. Menu = 348,
  1250. // Numpad keys
  1251. NP_0 = 320,
  1252. NP_1 = 321,
  1253. NP_2 = 322,
  1254. NP_3 = 323,
  1255. NP_4 = 324,
  1256. NP_5 = 325,
  1257. NP_6 = 326,
  1258. NP_7 = 327,
  1259. NP_8 = 328,
  1260. NP_9 = 329,
  1261. NP_Decimal = 330,
  1262. NP_Divide = 331,
  1263. NP_Multiply = 332,
  1264. NP_Subtract = 333,
  1265. NP_Add = 334,
  1266. NP_Enter = 335,
  1267. NP_Equal = 336,
  1268. }
  1269. MAX_GAMEPADS :: 4
  1270. // A value between 0 and MAX_GAMEPADS - 1
  1271. Gamepad_Index :: int
  1272. Gamepad_Axis :: enum {
  1273. Left_Stick_X,
  1274. Left_Stick_Y,
  1275. Right_Stick_X,
  1276. Right_Stick_Y,
  1277. Left_Trigger,
  1278. Right_Trigger,
  1279. }
  1280. Gamepad_Button :: enum {
  1281. // DPAD buttons
  1282. Left_Face_Up,
  1283. Left_Face_Down,
  1284. Left_Face_Left,
  1285. Left_Face_Right,
  1286. Right_Face_Up, // XBOX: Y, PS: Triangle
  1287. Right_Face_Down, // XBOX: A, PS: X
  1288. Right_Face_Left, // XBOX: X, PS: Square
  1289. Right_Face_Right, // XBOX: B, PS: Circle
  1290. Left_Shoulder,
  1291. Left_Trigger,
  1292. Right_Shoulder,
  1293. Right_Trigger,
  1294. Left_Stick_Press, // Clicking the left analogue stick
  1295. Right_Stick_Press, // Clicking the right analogue stick
  1296. Middle_Face_Left, // Select / back / options button
  1297. Middle_Face_Middle, // PS button (not available on XBox)
  1298. Middle_Face_Right, // Start
  1299. }
  1300. // Used by API builder. Everything after this constant will not be in karl2d.doc.odin
  1301. API_END :: true
  1302. batch_vertex :: proc(v: Vec3, uv: Vec2, color: Color) {
  1303. v := v
  1304. if s.vertex_buffer_cpu_used == len(s.vertex_buffer_cpu) {
  1305. draw_current_batch()
  1306. }
  1307. shd := s.batch_shader
  1308. base_offset := s.vertex_buffer_cpu_used
  1309. pos_offset := shd.default_input_offsets[.Position]
  1310. uv_offset := shd.default_input_offsets[.UV]
  1311. color_offset := shd.default_input_offsets[.Color]
  1312. mem.set(&s.vertex_buffer_cpu[base_offset], 0, shd.vertex_size)
  1313. if pos_offset != -1 {
  1314. (^Vec3)(&s.vertex_buffer_cpu[base_offset + pos_offset])^ = v
  1315. }
  1316. if uv_offset != -1 {
  1317. (^Vec2)(&s.vertex_buffer_cpu[base_offset + uv_offset])^ = uv
  1318. }
  1319. if color_offset != -1 {
  1320. (^Color)(&s.vertex_buffer_cpu[base_offset + color_offset])^ = color
  1321. }
  1322. override_offset: int
  1323. for &o, idx in shd.input_overrides {
  1324. input := &shd.inputs[idx]
  1325. sz := pixel_format_size(input.format)
  1326. if o.used != 0 {
  1327. mem.copy(&s.vertex_buffer_cpu[base_offset + override_offset], raw_data(&o.val), o.used)
  1328. }
  1329. override_offset += sz
  1330. }
  1331. s.vertex_buffer_cpu_used += shd.vertex_size
  1332. }
  1333. VERTEX_BUFFER_MAX :: 1000000
  1334. @(private="file")
  1335. s: ^State
  1336. // These globals are here for access from other files. The state struct above is private to make
  1337. // sure global state sharing doesn't become too messy.
  1338. frame_allocator: runtime.Allocator
  1339. win: Window_Interface
  1340. rb: Render_Backend_Interface
  1341. get_shader_input_default_type :: proc(name: string, type: Shader_Input_Type) -> Shader_Default_Inputs {
  1342. if name == "position" && type == .Vec3 {
  1343. return .Position
  1344. } else if name == "texcoord" && type == .Vec2 {
  1345. return .UV
  1346. } else if name == "color" && type == .Vec4 {
  1347. return .Color
  1348. }
  1349. return .Unknown
  1350. }
  1351. get_shader_format_num_components :: proc(format: Pixel_Format) -> int {
  1352. switch format {
  1353. case .Unknown: return 0
  1354. case .RGBA_32_Float: return 4
  1355. case .RGB_32_Float: return 3
  1356. case .RG_32_Float: return 2
  1357. case .R_32_Float: return 1
  1358. case .RGBA_8_Norm: return 4
  1359. case .RG_8_Norm: return 2
  1360. case .R_8_Norm: return 1
  1361. case .R_8_UInt: return 1
  1362. }
  1363. return 0
  1364. }
  1365. get_shader_input_format :: proc(name: string, type: Shader_Input_Type) -> Pixel_Format {
  1366. default_type := get_shader_input_default_type(name, type)
  1367. if default_type != .Unknown {
  1368. switch default_type {
  1369. case .Position: return .RGB_32_Float
  1370. case .UV: return .RG_32_Float
  1371. case .Color: return .RGBA_8_Norm
  1372. case .Unknown: unreachable()
  1373. }
  1374. }
  1375. switch type {
  1376. case .F32: return .R_32_Float
  1377. case .Vec2: return .RG_32_Float
  1378. case .Vec3: return .RGB_32_Float
  1379. case .Vec4: return .RGBA_32_Float
  1380. }
  1381. return .Unknown
  1382. }
  1383. vec3_from_vec2 :: proc(v: Vec2) -> Vec3 {
  1384. return {
  1385. v.x, v.y, 0,
  1386. }
  1387. }
  1388. frame_cstring :: proc(str: string, loc := #caller_location) -> cstring {
  1389. return strings.clone_to_cstring(str, s.frame_allocator, loc)
  1390. }
  1391. @(require_results)
  1392. matrix_ortho3d_f32 :: proc "contextless" (left, right, bottom, top, near, far: f32) -> Mat4 #no_bounds_check {
  1393. m: Mat4
  1394. m[0, 0] = +2 / (right - left)
  1395. m[1, 1] = +2 / (top - bottom)
  1396. m[2, 2] = +1
  1397. m[0, 3] = -(right + left) / (right - left)
  1398. m[1, 3] = -(top + bottom) / (top - bottom)
  1399. m[2, 3] = 0
  1400. m[3, 3] = 1
  1401. return m
  1402. }
  1403. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  1404. return matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  1405. }
  1406. FONT_DEFAULT_ATLAS_SIZE :: 1024
  1407. update_font :: proc(fh: Font_Handle) {
  1408. font := &s.fonts[fh]
  1409. font_dirty_rect: [4]f32
  1410. tw := FONT_DEFAULT_ATLAS_SIZE
  1411. if fs.ValidateTexture(&s.fs, &font_dirty_rect) {
  1412. fdr := font_dirty_rect
  1413. r := Rect {
  1414. fdr[0],
  1415. fdr[1],
  1416. fdr[2] - fdr[0],
  1417. fdr[3] - fdr[1],
  1418. }
  1419. x := int(r.x)
  1420. y := int(r.y)
  1421. w := int(fdr[2]) - int(fdr[0])
  1422. h := int(fdr[3]) - int(fdr[1])
  1423. expanded_pixels := make([]Color, w * h, frame_allocator)
  1424. start := x + tw * y
  1425. for i in 0..<w*h {
  1426. px := i%w
  1427. py := i/w
  1428. dst_pixel_idx := (px) + (py * w)
  1429. src_pixel_idx := start + (px) + (py * tw)
  1430. src := s.fs.textureData[src_pixel_idx]
  1431. expanded_pixels[dst_pixel_idx] = {255,255,255, src}
  1432. }
  1433. rb.update_texture(font.atlas.handle, slice.reinterpret([]u8, expanded_pixels), r)
  1434. }
  1435. }
  1436. set_font :: proc(fh: Font_Handle) {
  1437. fh := fh
  1438. if s.batch_font == fh {
  1439. return
  1440. }
  1441. s.batch_font = fh
  1442. if s.batch_font != FONT_NONE {
  1443. update_font(s.batch_font)
  1444. }
  1445. if fh == 0 {
  1446. fh = s.default_font
  1447. }
  1448. font := &s.fonts[fh]
  1449. fs.SetFont(&s.fs, font.fontstash_handle)
  1450. }
  1451. DEPTH_START :: -1 + DEPTH_INCREMENT
  1452. DEPTH_INCREMENT :: (1.0/10000000.0)
  1453. _ :: jpeg
  1454. _ :: bmp
  1455. _ :: png
  1456. _ :: tga
  1457. Color_F32 :: [4]f32
  1458. f32_color_from_color :: proc(color: Color) -> Color_F32 {
  1459. return {
  1460. f32(color.r) / 255,
  1461. f32(color.g) / 255,
  1462. f32(color.b) / 255,
  1463. f32(color.a) / 255,
  1464. }
  1465. }
  1466. vec3 :: proc(v2: Vec2, z: f32) -> Vec3 {
  1467. return {
  1468. v2.x, v2.y, z,
  1469. }
  1470. }
  1471. get_next_depth :: proc() -> f32 {
  1472. d := s.depth
  1473. s.depth += s.depth_increment
  1474. return d
  1475. }