karl2d.odin 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215
  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 "core:time"
  13. import fs "vendor:fontstash"
  14. import "core:image"
  15. import "core:image/jpeg"
  16. import "core:image/bmp"
  17. import "core:image/png"
  18. import "core:image/tga"
  19. import hm "handle_map"
  20. //-----------------------------------------------//
  21. // SETUP, WINDOW MANAGEMENT AND FRAME MANAGEMENT //
  22. //-----------------------------------------------//
  23. // Opens a window and initializes some internal state. The internal state will use `allocator` for
  24. // all dynamically allocated memory. The return value can be ignored unless you need to later call
  25. // `set_internal_state`.
  26. //
  27. // `screen_width` and `screen_height` refer to the the resolution of the drawable area of the
  28. // window. The window might be slightly larger due borders and headers.
  29. init :: proc(
  30. screen_width: int,
  31. screen_height: int,
  32. window_title: string,
  33. options := Init_Options {},
  34. allocator := context.allocator,
  35. loc := #caller_location
  36. ) -> ^State {
  37. assert(s == nil, "Don't call 'init' twice.")
  38. context.allocator = allocator
  39. s = new(State, allocator, loc)
  40. // This is the same type of arena as the default temp allocator. This arena is for allocations
  41. // that have a lifetime of "one frame". They are valid until you call `present()`, at which
  42. // point the frame allocator is cleared.
  43. s.frame_allocator = runtime.arena_allocator(&s.frame_arena)
  44. frame_allocator = s.frame_allocator
  45. s.allocator = allocator
  46. s.win = WINDOW_INTERFACE
  47. win = s.win
  48. // We alloc memory for the windowing backend and pass the blob of memory to it.
  49. window_state_alloc_error: runtime.Allocator_Error
  50. s.window_state, window_state_alloc_error = mem.alloc(win.state_size(), allocator = allocator)
  51. log.assertf(window_state_alloc_error == nil, "Failed allocating memory for window state: %v", window_state_alloc_error)
  52. win.init(s.window_state, screen_width, screen_height, window_title, options, allocator)
  53. // This is a OS-independent handle that we can pass to any rendering backend.
  54. s.window = win.window_handle()
  55. // See `config.odin` for how this is picked.
  56. s.rb = RENDER_BACKEND
  57. // Depending on backend the depth is counted in one of two ways. It can be counted from `1` and
  58. // to lower numbers. Or from `-1` and to higher numbers.
  59. s.depth_start = DEPTH_START
  60. s.depth_increment = DEPTH_INCREMENT
  61. if s.rb.flip_z() {
  62. s.depth_start = -DEPTH_START
  63. s.depth_increment = -DEPTH_INCREMENT
  64. }
  65. s.depth = s.depth_start
  66. rb = s.rb
  67. rb_alloc_error: runtime.Allocator_Error
  68. s.rb_state, rb_alloc_error = mem.alloc(rb.state_size(), allocator = allocator)
  69. log.assertf(rb_alloc_error == nil, "Failed allocating memory for rendering backend: %v", rb_alloc_error)
  70. s.proj_matrix = make_default_projection(win.get_width(), win.get_height())
  71. s.view_matrix = 1
  72. // Boot up the render backend. It will render into our previously created window.
  73. rb.init(s.rb_state, s.window, win.get_width(), win.get_height(), allocator)
  74. // The vertex buffer is created in a render backend-independent way. It is passed to the
  75. // render backend each frame as part of `draw_current_batch()`
  76. s.vertex_buffer_cpu = make([]u8, VERTEX_BUFFER_MAX, allocator, loc)
  77. // The shapes drawing texture is sampled when any shape is drawn. This way we can use the same
  78. // shader for textured drawing and shape drawing. It's just a white box.
  79. white_rect: [16*16*4]u8
  80. slice.fill(white_rect[:], 255)
  81. s.shape_drawing_texture = rb.load_texture(white_rect[:], 16, 16, .RGBA_8_Norm)
  82. // The default shader will arrive in a different format depending on backend. GLSL for GL,
  83. // HLSL for d3d etc.
  84. s.default_shader = load_shader_from_bytes(rb.default_shader_vertex_source(), rb.default_shader_fragment_source())
  85. s.batch_shader = s.default_shader
  86. // FontStash enables us to bake fonts from TTF files on-the-fly.
  87. fs.Init(&s.fs, FONT_DEFAULT_ATLAS_SIZE, FONT_DEFAULT_ATLAS_SIZE, .TOPLEFT)
  88. fs.SetAlignVertical(&s.fs, .TOP)
  89. DEFAULT_FONT_DATA :: #load("roboto.ttf")
  90. // Dummy element so font with index 0 means 'no font'.
  91. append_nothing(&s.fonts)
  92. s.default_font = load_font_from_bytes(DEFAULT_FONT_DATA)
  93. _set_font(s.default_font)
  94. return s
  95. }
  96. // Returns true the user has pressed the close button on the window, or used a key stroke such as
  97. // ALT+F4 on Windows. The application can decide if it wants to shut down or if it wants to show
  98. // some kind of confirmation dialogue.
  99. //
  100. // Commonly used for creating the "main loop" of a game: `for !k2.shutdown_wanted {}`
  101. shutdown_wanted :: proc() -> bool {
  102. return s.shutdown_wanted
  103. }
  104. // Closes the window and cleans up Karl2D's internal state.
  105. shutdown :: proc() {
  106. assert(s != nil, "You've called 'shutdown' without calling 'init' first")
  107. context.allocator = s.allocator
  108. destroy_font(s.default_font)
  109. rb.destroy_texture(s.shape_drawing_texture)
  110. destroy_shader(s.default_shader)
  111. rb.shutdown()
  112. delete(s.vertex_buffer_cpu, s.allocator)
  113. win.shutdown()
  114. fs.Destroy(&s.fs)
  115. delete(s.fonts)
  116. a := s.allocator
  117. free(s.window_state, a)
  118. free(s.rb_state, a)
  119. free(s, a)
  120. s = nil
  121. }
  122. // Clear the "screen" with the supplied color. By default this will clear your window. But if you
  123. // have set a Render Texture using the `set_render_texture` procedure, then that Render Texture will
  124. // be cleared instead.
  125. clear :: proc(color: Color) {
  126. draw_current_batch()
  127. rb.clear(s.batch_render_target, color)
  128. // This is problematic -- if you switch from backbuffer drawing to a render texture and back
  129. // again, then the depth will be messed with. Should we rethink our depth usage and always use
  130. // "painter's algorithm" instead?
  131. s.depth = s.depth_start
  132. }
  133. // Call at the start of each frame. This procedure does two main things:
  134. // - Fetches how long the previous frame took and how long since the program started. These values
  135. // can be fetched using `get_frame_time()` and `get_time()`
  136. // - Clears Karl2D's internal "frame_allocator" -- that's the allocator the library uses for
  137. // dynamic memory that has a lifetime of a single frame.
  138. new_frame :: proc() {
  139. free_all(s.frame_allocator)
  140. now := time.now()
  141. if s.prev_frame_time != {} {
  142. since := time.diff(s.prev_frame_time, now)
  143. s.frame_time = f32(time.duration_seconds(since))
  144. }
  145. s.prev_frame_time = now
  146. if s.start_time == {} {
  147. s.start_time = time.now()
  148. }
  149. s.time = time.duration_seconds(time.since(s.start_time))
  150. }
  151. // "Flips the backbuffer": Call at end of frame to make everything you've drawn appear on the screen.
  152. //
  153. // When you draw using for example `draw_texture`, then that stuff is drawn to an invisible texture
  154. // called a "backbuffer". This makes sure that we don't see half-drawn frames. So when you are happy
  155. // with a frame and want to show it to the player, call this procedure.
  156. //
  157. // WebGL note: WebGL does the backbuffer flipping automatically. But you should still call this to
  158. // make sure that all rendering has been sent off to the GPU (it calls `draw_current_batch()`).
  159. present :: proc() {
  160. draw_current_batch()
  161. rb.present()
  162. }
  163. // Call at start or end of frame to process all events that have arrived to the window. This
  164. // includes keyboard, mouse, gamepad and window events.
  165. //
  166. // WARNING: Not calling this will make your program impossible to interact with.
  167. process_events :: proc() {
  168. s.key_went_up = {}
  169. s.key_went_down = {}
  170. s.mouse_button_went_up = {}
  171. s.mouse_button_went_down = {}
  172. s.gamepad_button_went_up = {}
  173. s.gamepad_button_went_down = {}
  174. s.mouse_delta = {}
  175. s.mouse_wheel_delta = 0
  176. win.process_events()
  177. events := win.get_events()
  178. for &event in events {
  179. switch &e in event {
  180. case Window_Event_Close_Wanted:
  181. s.shutdown_wanted = true
  182. case Window_Event_Key_Went_Down:
  183. s.key_went_down[e.key] = true
  184. s.key_is_held[e.key] = true
  185. case Window_Event_Key_Went_Up:
  186. s.key_went_up[e.key] = true
  187. s.key_is_held[e.key] = false
  188. case Window_Event_Mouse_Button_Went_Down:
  189. s.mouse_button_went_down[e.button] = true
  190. s.mouse_button_is_held[e.button] = true
  191. case Window_Event_Mouse_Button_Went_Up:
  192. s.mouse_button_went_up[e.button] = true
  193. s.mouse_button_is_held[e.button] = false
  194. case Window_Event_Mouse_Move:
  195. prev_pos := s.mouse_position
  196. s.mouse_position = e.position
  197. s.mouse_delta = s.mouse_position - prev_pos
  198. case Window_Event_Mouse_Wheel:
  199. s.mouse_wheel_delta = e.delta
  200. case Window_Event_Gamepad_Button_Went_Down:
  201. if e.gamepad < MAX_GAMEPADS {
  202. s.gamepad_button_went_down[e.gamepad][e.button] = true
  203. s.gamepad_button_is_held[e.gamepad][e.button] = true
  204. }
  205. case Window_Event_Gamepad_Button_Went_Up:
  206. if e.gamepad < MAX_GAMEPADS {
  207. s.gamepad_button_went_up[e.gamepad][e.button] = true
  208. s.gamepad_button_is_held[e.gamepad][e.button] = false
  209. }
  210. case Window_Event_Resize:
  211. rb.resize_swapchain(e.width, e.height)
  212. s.proj_matrix = make_default_projection(e.width, e.height)
  213. }
  214. }
  215. win.clear_events()
  216. }
  217. // Returns how many seconds the previous frame took. Often a tiny number such as 0.016 s.
  218. //
  219. // You must call `new_frame()` at the start of your frame in order for the frame_time to be updated.
  220. get_frame_time :: proc() -> f32 {
  221. return s.frame_time
  222. }
  223. // Returns how many seconds has elapsed since the game started.
  224. //
  225. // You must call `new_frame()` at the start of your frame for this value to get updated.
  226. get_time :: proc() -> f64 {
  227. return s.time
  228. }
  229. // Gets the width of the drawing area within the window. The returned number is not scaled by any
  230. // monitor DPI scaling. You do that manually using the number returned by `get_window_scale()`.
  231. get_screen_width :: proc() -> int {
  232. return win.get_width()
  233. }
  234. // Gets the height of the drawing area within the window. The returned number is not scaled by any
  235. // monitor DPI scaling. You do that manually using the number returned by `get_window_scale()`.
  236. get_screen_height :: proc() -> int {
  237. return win.get_height()
  238. }
  239. // Moves the window.
  240. //
  241. // This does nothing for web builds.
  242. set_window_position :: proc(x: int, y: int) {
  243. win.set_position(x, y)
  244. }
  245. // Resize the window to a new size. If the window has the flag Resizable set, then the backbuffer
  246. // will also be resized.
  247. set_window_size :: proc(width: int, height: int) {
  248. // TODO not sure if we should resize swapchain here. On windows the WM_SIZE event fires and
  249. // it all works out. But perhaps not on all platforms?
  250. win.set_size(width, height)
  251. }
  252. // Fetch the scale of the window. This usually comes from some DPI scaling setting in the OS.
  253. // 1 means 100% scale, 1.5 means 150% etc.
  254. get_window_scale :: proc() -> f32 {
  255. return win.get_window_scale()
  256. }
  257. // Use to change between windowed mode, resizable windowed mode and fullscreen
  258. set_window_mode :: proc(window_mode: Window_Mode) {
  259. win.set_window_mode(window_mode)
  260. }
  261. // Flushes the current batch. This sends off everything to the GPU that has been queued in the
  262. // current batch. Normally, you do not need to do this manually. It is done automatically when these
  263. // procedures run:
  264. //
  265. // - present
  266. // - set_camera
  267. // - set_shader
  268. // - set_shader_constant
  269. // - set_scissor_rect
  270. // - set_blend_mode
  271. // - set_render_texture
  272. // - clear
  273. // - draw_texture_* IF previous draw did not use the same texture (1)
  274. // - draw_rect_*, draw_circle_*, draw_line IF previous draw did not use the shapes drawing texture (2)
  275. //
  276. // (1) When drawing textures, the current texture is fed into the active shader. Everything within
  277. // the same batch must use the same texture. So drawing with a new texture forces the current to
  278. // be drawn. You can combine several textures into an atlas to get bigger batches.
  279. //
  280. // (2) In order to use the same shader for shapes drawing and textured drawing, the shapes drawing
  281. // uses a blank, white texture. For the same reasons as (1), drawing something else than shapes
  282. // before drawing a shape will break up the batches. In a future update I'll add so that you can
  283. // set your own shapes drawing texture, making it possible to combine it with a bigger atlas.
  284. //
  285. // The batch has maximum size of VERTEX_BUFFER_MAX bytes. The shader dictates how big a vertex is
  286. // so the maximum number of vertices that can be drawn in each batch is
  287. // VERTEX_BUFFER_MAX / shader.vertex_size
  288. draw_current_batch :: proc() {
  289. if s.vertex_buffer_cpu_used == 0 {
  290. return
  291. }
  292. _update_font(s.batch_font)
  293. shader := s.batch_shader
  294. mvp := s.proj_matrix * s.view_matrix
  295. for mloc, builtin in shader.constant_builtin_locations {
  296. constant, constant_ok := mloc.?
  297. if !constant_ok {
  298. continue
  299. }
  300. switch builtin {
  301. case .MVP:
  302. if constant.size == size_of(mvp) {
  303. dst := (^matrix[4,4]f32)(&shader.constants_data[constant.offset])
  304. dst^ = mvp
  305. }
  306. }
  307. }
  308. if def_tex_idx, has_def_tex_idx := shader.default_texture_index.?; has_def_tex_idx {
  309. shader.texture_bindpoints[def_tex_idx] = s.batch_texture
  310. }
  311. rb.draw(shader, s.batch_render_target, shader.texture_bindpoints, s.batch_scissor, s.batch_blend_mode, s.vertex_buffer_cpu[:s.vertex_buffer_cpu_used])
  312. s.vertex_buffer_cpu_used = 0
  313. }
  314. //-------//
  315. // INPUT //
  316. //-------//
  317. // Returns true if a keyboard key went down between the current and the previous frame. Set when
  318. // 'process_events' runs.
  319. key_went_down :: proc(key: Keyboard_Key) -> bool {
  320. return s.key_went_down[key]
  321. }
  322. // Returns true if a keyboard key went up (was released) between the current and the previous frame.
  323. // Set when 'process_events' runs.
  324. key_went_up :: proc(key: Keyboard_Key) -> bool {
  325. return s.key_went_up[key]
  326. }
  327. // Returns true if a keyboard is currently being held down. Set when 'process_events' runs.
  328. key_is_held :: proc(key: Keyboard_Key) -> bool {
  329. return s.key_is_held[key]
  330. }
  331. // Returns true if a mouse button went down between the current and the previous frame. Specify
  332. // which mouse button using the `button` parameter.
  333. //
  334. // Set when 'process_events' runs.
  335. mouse_button_went_down :: proc(button: Mouse_Button) -> bool {
  336. return s.mouse_button_went_down[button]
  337. }
  338. // Returns true if a mouse button went up (was released) between the current and the previous frame.
  339. // Specify which mouse button using the `button` parameter.
  340. //
  341. // Set when 'process_events' runs.
  342. mouse_button_went_up :: proc(button: Mouse_Button) -> bool {
  343. return s.mouse_button_went_up[button]
  344. }
  345. // Returns true if a mouse button is currently being held down. Specify which mouse button using the
  346. // `button` parameter. Set when 'process_events' runs.
  347. mouse_button_is_held :: proc(button: Mouse_Button) -> bool {
  348. return s.mouse_button_is_held[button]
  349. }
  350. // Returns how many clicks the mouse wheel has scrolled between the previous and current frame.
  351. get_mouse_wheel_delta :: proc() -> f32 {
  352. return s.mouse_wheel_delta
  353. }
  354. // Returns the mouse position, measured from the top-left corner of the window.
  355. get_mouse_position :: proc() -> Vec2 {
  356. return s.mouse_position
  357. }
  358. // Returns how many pixels the mouse moved between the previous and the current frame.
  359. get_mouse_delta :: proc() -> Vec2 {
  360. return s.mouse_delta
  361. }
  362. // Returns true if a gamepad with the supplied index is connected. The parameter should be a value
  363. // between 0 and MAX_GAMEPADS.
  364. is_gamepad_active :: proc(gamepad: Gamepad_Index) -> bool {
  365. return win.is_gamepad_active(gamepad)
  366. }
  367. // Returns true if a gamepad button went down between the previous and the current frame.
  368. gamepad_button_went_down :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  369. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  370. return false
  371. }
  372. return s.gamepad_button_went_down[gamepad][button]
  373. }
  374. // Returns true if a gamepad button went up (was released) between the previous and the current
  375. // frame.
  376. gamepad_button_went_up :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  377. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  378. return false
  379. }
  380. return s.gamepad_button_went_up[gamepad][button]
  381. }
  382. // Returns true if a gamepad button is currently held down.
  383. //
  384. // The "trigger buttons" on some gamepads also have an analogue "axis value" associated with them.
  385. // Fetch that value using `get_gamepad_axis()`.
  386. gamepad_button_is_held :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  387. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  388. return false
  389. }
  390. return s.gamepad_button_is_held[gamepad][button]
  391. }
  392. // Returns the value of analogue gamepad axes such as the thumbsticks and trigger buttons. The value
  393. // is in the range -1 to 1 for sticks and 0 to 1 for trigger buttons.
  394. get_gamepad_axis :: proc(gamepad: Gamepad_Index, axis: Gamepad_Axis) -> f32 {
  395. return win.get_gamepad_axis(gamepad, axis)
  396. }
  397. // Set the left and right vibration motor speed. The range of left and right is 0 to 1. Note that on
  398. // most gamepads, the left motor is "low frequency" and the right motor is "high frequency". They do
  399. // not vibrate with the same speed.
  400. set_gamepad_vibration :: proc(gamepad: Gamepad_Index, left: f32, right: f32) {
  401. win.set_gamepad_vibration(gamepad, left, right)
  402. }
  403. //---------//
  404. // DRAWING //
  405. //---------//
  406. // Draw a colored rectangle. The rectangles have their (x, y) position in the top-left corner of the
  407. // rectangle.
  408. draw_rect :: proc(r: Rect, c: Color) {
  409. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  410. draw_current_batch()
  411. }
  412. if s.batch_texture != s.shape_drawing_texture {
  413. draw_current_batch()
  414. }
  415. s.batch_texture = s.shape_drawing_texture
  416. z := get_next_depth()
  417. batch_vertex({r.x, r.y, z}, {0, 0}, c)
  418. batch_vertex({r.x + r.w, r.y, z}, {1, 0}, c)
  419. batch_vertex({r.x + r.w, r.y + r.h, z}, {1, 1}, c)
  420. batch_vertex({r.x, r.y, z}, {0, 0}, c)
  421. batch_vertex({r.x + r.w, r.y + r.h, z}, {1, 1}, c)
  422. batch_vertex({r.x, r.y + r.h, z}, {0, 1}, c)
  423. }
  424. // Creates a rectangle from a position and a size and draws it.
  425. draw_rect_vec :: proc(pos: Vec2, size: Vec2, c: Color) {
  426. draw_rect({pos.x, pos.y, size.x, size.y}, c)
  427. }
  428. // Draw a rectangle with a custom origin and rotation.
  429. //
  430. // The origin says which point the rotation rotates around. If the origin is `(0, 0)`, then the
  431. // rectangle rotates around the top-left corner of the rectangle. If it is `(rect.w/2, rect.h/2)`
  432. // then the rectangle rotates around its center.
  433. draw_rect_ex :: proc(r: Rect, origin: Vec2, rot: f32, c: Color) {
  434. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  435. draw_current_batch()
  436. }
  437. if s.batch_texture != s.shape_drawing_texture {
  438. draw_current_batch()
  439. }
  440. s.batch_texture = s.shape_drawing_texture
  441. tl, tr, bl, br: Vec2
  442. // Rotation adapted from Raylib's "DrawTexturePro"
  443. if rot == 0 {
  444. x := r.x - origin.x
  445. y := r.y - origin.y
  446. tl = { x, y }
  447. tr = { x + r.w, y }
  448. bl = { x, y + r.h }
  449. br = { x + r.w, y + r.h }
  450. } else {
  451. sin_rot := math.sin(rot * math.RAD_PER_DEG)
  452. cos_rot := math.cos(rot * math.RAD_PER_DEG)
  453. x := r.x
  454. y := r.y
  455. dx := -origin.x
  456. dy := -origin.y
  457. tl = {
  458. x + dx * cos_rot - dy * sin_rot,
  459. y + dx * sin_rot + dy * cos_rot,
  460. }
  461. tr = {
  462. x + (dx + r.w) * cos_rot - dy * sin_rot,
  463. y + (dx + r.w) * sin_rot + dy * cos_rot,
  464. }
  465. bl = {
  466. x + dx * cos_rot - (dy + r.h) * sin_rot,
  467. y + dx * sin_rot + (dy + r.h) * cos_rot,
  468. }
  469. br = {
  470. x + (dx + r.w) * cos_rot - (dy + r.h) * sin_rot,
  471. y + (dx + r.w) * sin_rot + (dy + r.h) * cos_rot,
  472. }
  473. }
  474. z := get_next_depth()
  475. batch_vertex(vec3(tl, z), {0, 0}, c)
  476. batch_vertex(vec3(tr, z), {1, 0}, c)
  477. batch_vertex(vec3(br, z), {1, 1}, c)
  478. batch_vertex(vec3(tl, z), {0, 0}, c)
  479. batch_vertex(vec3(br, z), {1, 1}, c)
  480. batch_vertex(vec3(bl, z), {0, 1}, c)
  481. }
  482. // Draw the outline of a rectangle with a specific thickness. The outline is drawn using four
  483. // rectangles.
  484. draw_rect_outline :: proc(r: Rect, thickness: f32, color: Color) {
  485. t := thickness
  486. // Based on DrawRectangleLinesEx from Raylib
  487. top := Rect {
  488. r.x,
  489. r.y,
  490. r.w,
  491. t,
  492. }
  493. bottom := Rect {
  494. r.x,
  495. r.y + r.h - t,
  496. r.w,
  497. t,
  498. }
  499. left := Rect {
  500. r.x,
  501. r.y + t,
  502. t,
  503. r.h - t * 2,
  504. }
  505. right := Rect {
  506. r.x + r.w - t,
  507. r.y + t,
  508. t,
  509. r.h - t * 2,
  510. }
  511. draw_rect(top, color)
  512. draw_rect(bottom, color)
  513. draw_rect(left, color)
  514. draw_rect(right, color)
  515. }
  516. // Draw a circle with a certain center and radius. Note the `segments` parameter: This circle is not
  517. // perfect! It is drawn using a number of "cake segments".
  518. draw_circle :: proc(center: Vec2, radius: f32, color: Color, segments := 16) {
  519. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 3 * segments > len(s.vertex_buffer_cpu) {
  520. draw_current_batch()
  521. }
  522. if s.batch_texture != s.shape_drawing_texture {
  523. draw_current_batch()
  524. }
  525. s.batch_texture = s.shape_drawing_texture
  526. z := get_next_depth()
  527. prev := center + {radius, 0}
  528. for s in 1..=segments {
  529. sr := (f32(s)/f32(segments)) * 2*math.PI
  530. rot := linalg.matrix2_rotate(sr)
  531. p := center + rot * Vec2{radius, 0}
  532. batch_vertex(vec3(prev, z), {0, 0}, color)
  533. batch_vertex(vec3(p, z), {1, 0}, color)
  534. batch_vertex(vec3(center, z), {1, 1}, color)
  535. prev = p
  536. }
  537. }
  538. // Like `draw_circle` but only draws the outer edge of the circle.
  539. draw_circle_outline :: proc(center: Vec2, radius: f32, thickness: f32, color: Color, segments := 16) {
  540. prev := center + {radius, 0}
  541. for s in 1..=segments {
  542. sr := (f32(s)/f32(segments)) * 2*math.PI
  543. rot := linalg.matrix2_rotate(sr)
  544. p := center + rot * Vec2{radius, 0}
  545. draw_line(prev, p, thickness, color)
  546. prev = p
  547. }
  548. }
  549. // Draws a line from `start` to `end` of a certain thickness.
  550. draw_line :: proc(start: Vec2, end: Vec2, thickness: f32, color: Color) {
  551. p := Vec2{start.x, start.y + thickness*0.5}
  552. s := Vec2{linalg.length(end - start), thickness}
  553. origin := Vec2 {0, thickness*0.5}
  554. r := Rect {p.x, p.y, s.x, s.y}
  555. rot := math.atan2(end.y - start.y, end.x - start.x)
  556. draw_rect_ex(r, origin, rot * math.DEG_PER_RAD, color)
  557. }
  558. // Draw a texture at a specific position. The texture will be drawn with its top-left corner at
  559. // position `pos`.
  560. //
  561. // Load textures using `load_texture_from_file` or `load_texture_from_bytes`.
  562. draw_texture :: proc(tex: Texture, pos: Vec2, tint := WHITE) {
  563. draw_texture_ex(
  564. tex,
  565. {0, 0, f32(tex.width), f32(tex.height)},
  566. {pos.x, pos.y, f32(tex.width), f32(tex.height)},
  567. {},
  568. 0,
  569. tint,
  570. )
  571. }
  572. // Draw a section of a texture at a specific position. `rect` is a rectangle measured in pixels. It
  573. // tells the procedure which part of the texture to display. The texture will be drawn with its
  574. // top-left corner at position `pos`.
  575. draw_texture_rect :: proc(tex: Texture, rect: Rect, pos: Vec2, tint := WHITE) {
  576. draw_texture_ex(
  577. tex,
  578. rect,
  579. {pos.x, pos.y, rect.w, rect.h},
  580. {},
  581. 0,
  582. tint,
  583. )
  584. }
  585. // Draw a texture by taking a section of the texture specified by `src` and draw it into the area of
  586. // the screen specified by `dst`. You can also rotate the texture around an origin point of your
  587. // choice.
  588. //
  589. // Tip: Use `k2.get_texture_rect(tex)` for `src` if you want to draw the whole texture.
  590. draw_texture_ex :: proc(tex: Texture, src: Rect, dst: Rect, origin: Vec2, rotation: f32, tint := WHITE) {
  591. if tex.width == 0 || tex.height == 0 {
  592. return
  593. }
  594. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  595. draw_current_batch()
  596. }
  597. if s.batch_texture != tex.handle {
  598. draw_current_batch()
  599. }
  600. s.batch_texture = tex.handle
  601. flip_x, flip_y: bool
  602. src := src
  603. dst := dst
  604. if src.w < 0 {
  605. flip_x = true
  606. src.w = -src.w
  607. }
  608. if src.h < 0 {
  609. flip_y = true
  610. src.h = -src.h
  611. }
  612. if dst.w < 0 {
  613. dst.w *= -1
  614. }
  615. if dst.h < 0 {
  616. dst.h *= -1
  617. }
  618. tl, tr, bl, br: Vec2
  619. // Rotation adapted from Raylib's "DrawTexturePro"
  620. if rotation == 0 {
  621. x := dst.x - origin.x
  622. y := dst.y - origin.y
  623. tl = { x, y }
  624. tr = { x + dst.w, y }
  625. bl = { x, y + dst.h }
  626. br = { x + dst.w, y + dst.h }
  627. } else {
  628. sin_rot := math.sin(rotation * math.RAD_PER_DEG)
  629. cos_rot := math.cos(rotation * math.RAD_PER_DEG)
  630. x := dst.x
  631. y := dst.y
  632. dx := -origin.x
  633. dy := -origin.y
  634. tl = {
  635. x + dx * cos_rot - dy * sin_rot,
  636. y + dx * sin_rot + dy * cos_rot,
  637. }
  638. tr = {
  639. x + (dx + dst.w) * cos_rot - dy * sin_rot,
  640. y + (dx + dst.w) * sin_rot + dy * cos_rot,
  641. }
  642. bl = {
  643. x + dx * cos_rot - (dy + dst.h) * sin_rot,
  644. y + dx * sin_rot + (dy + dst.h) * cos_rot,
  645. }
  646. br = {
  647. x + (dx + dst.w) * cos_rot - (dy + dst.h) * sin_rot,
  648. y + (dx + dst.w) * sin_rot + (dy + dst.h) * cos_rot,
  649. }
  650. }
  651. ts := Vec2{f32(tex.width), f32(tex.height)}
  652. up := Vec2{src.x, src.y} / ts
  653. us := Vec2{src.w, src.h} / ts
  654. c := tint
  655. uv0 := up
  656. uv1 := up + {us.x, 0}
  657. uv2 := up + us
  658. uv3 := up
  659. uv4 := up + us
  660. uv5 := up + {0, us.y}
  661. if flip_x {
  662. uv0.x += us.x
  663. uv1.x -= us.x
  664. uv2.x -= us.x
  665. uv3.x += us.x
  666. uv4.x -= us.x
  667. uv5.x += us.x
  668. }
  669. // HACK: We ask the render backend if this texture needs flipping. The idea is that GL will
  670. // flip render textures, so we need to automatically unflip them.
  671. //
  672. // Could we do something with the projection matrix while drawing into those render textures
  673. // instead? I tried that, but couldn't get it to work.
  674. if rb.texture_needs_vertical_flip(tex.handle) {
  675. flip_y = !flip_y
  676. }
  677. if flip_y {
  678. uv0.y += us.y
  679. uv1.y += us.y
  680. uv2.y -= us.y
  681. uv3.y += us.y
  682. uv4.y -= us.y
  683. uv5.y -= us.y
  684. }
  685. z := get_next_depth()
  686. batch_vertex(vec3(tl, z), uv0, c)
  687. batch_vertex(vec3(tr, z), uv1, c)
  688. batch_vertex(vec3(br, z), uv2, c)
  689. batch_vertex(vec3(tl, z), uv3, c)
  690. batch_vertex(vec3(br, z), uv4, c)
  691. batch_vertex(vec3(bl, z), uv5, c)
  692. }
  693. // Tells you how much space some text of a certain size will use on the screen. The font used is the
  694. // default font. The return value contains the width and height of the text.
  695. measure_text :: proc(text: string, font_size: f32) -> Vec2 {
  696. fs.SetSize(&s.fs, font_size)
  697. b: [4]f32
  698. fs.TextBounds(&s.fs, text, bounds = &b)
  699. return {b[2] - b[0], b[3] - b[1]}
  700. }
  701. // Tells you how much space some text of a certain size will use on the screen, using a custom font.
  702. // The return value contains the width and height of the text.
  703. measure_text_ex :: proc(font_handle: Font, text: string, font_size: f32) -> Vec2 {
  704. _set_font(font_handle)
  705. fs.SetSize(&s.fs, font_size)
  706. b: [4]f32
  707. fs.TextBounds(&s.fs, text, bounds = &b)
  708. return {b[2] - b[0], b[3] - b[1]}
  709. }
  710. // Draw text at a position with a size. This uses the default font. `pos` will be equal to the
  711. // top-left position of the text.
  712. draw_text :: proc(text: string, pos: Vec2, font_size: f32, color := BLACK) {
  713. draw_text_ex(s.default_font, text, pos, font_size, color)
  714. }
  715. // Draw text at a position with a size, using a custom font. `pos` will be equal to the top-left
  716. // position of the text.
  717. draw_text_ex :: proc(font_handle: Font, text: string, pos: Vec2, font_size: f32, color := BLACK) {
  718. if int(font_handle) >= len(s.fonts) {
  719. return
  720. }
  721. _set_font(font_handle)
  722. font := &s.fonts[font_handle]
  723. fs.SetSize(&s.fs, font_size)
  724. iter := fs.TextIterInit(&s.fs, pos.x, pos.y, text)
  725. q: fs.Quad
  726. for fs.TextIterNext(&s.fs, &iter, &q) {
  727. src := Rect {
  728. q.s0, q.t0,
  729. q.s1 - q.s0, q.t1 - q.t0,
  730. }
  731. w := f32(FONT_DEFAULT_ATLAS_SIZE)
  732. h := f32(FONT_DEFAULT_ATLAS_SIZE)
  733. src.x *= w
  734. src.y *= h
  735. src.w *= w
  736. src.h *= h
  737. dst := Rect {
  738. q.x0, q.y0,
  739. q.x1 - q.x0, q.y1 - q.y0,
  740. }
  741. draw_texture_ex(font.atlas, src, dst, {}, 0, color)
  742. }
  743. }
  744. //--------------------//
  745. // TEXTURE MANAGEMENT //
  746. //--------------------//
  747. // Create an empty texture.
  748. create_texture :: proc(width: int, height: int, format: Pixel_Format) -> Texture {
  749. h := rb.create_texture(width, height, format)
  750. return {
  751. handle = h,
  752. width = width,
  753. height = height,
  754. }
  755. }
  756. // Load a texture from disk and upload it to the GPU so you can draw it to the screen.
  757. // Supports PNG, BMP, TGA and baseline PNG. Note that progressive PNG files are not supported!
  758. //
  759. // The `options` parameter can be used to specify things things such as premultiplication of alpha.
  760. load_texture_from_file :: proc(filename: string, options: Load_Texture_Options = {}) -> Texture {
  761. when FILESYSTEM_SUPPORTED {
  762. load_options := image.Options {
  763. .alpha_add_if_missing,
  764. }
  765. if .Premultiply_Alpha in options {
  766. load_options += { .alpha_premultiply }
  767. }
  768. img, img_err := image.load_from_file(filename, options = load_options, allocator = s.frame_allocator)
  769. if img_err != nil {
  770. log.errorf("Error loading texture %v: %v", filename, img_err)
  771. return {}
  772. }
  773. return load_texture_from_bytes_raw(img.pixels.buf[:], img.width, img.height, .RGBA_8_Norm)
  774. } else {
  775. log.errorf("load_texture_from_file failed: OS %v has no filesystem support! Tip: Use load_texture_from_bytes(#load(\"the_texture.png\")) instead.", ODIN_OS)
  776. return {}
  777. }
  778. }
  779. // Load a texture from a byte slice and upload it to the GPU so you can draw it to the screen.
  780. // Supports PNG, BMP, TGA and baseline PNG. Note that progressive PNG files are not supported!
  781. //
  782. // The `options` parameter can be used to specify things things such as premultiplication of alpha.
  783. load_texture_from_bytes :: proc(bytes: []u8, options: Load_Texture_Options = {}) -> Texture {
  784. load_options := image.Options {
  785. .alpha_add_if_missing,
  786. }
  787. if .Premultiply_Alpha in options {
  788. load_options += { .alpha_premultiply }
  789. }
  790. img, img_err := image.load_from_bytes(bytes, options = load_options, allocator = s.frame_allocator)
  791. if img_err != nil {
  792. log.errorf("Error loading texture: %v", img_err)
  793. return {}
  794. }
  795. return load_texture_from_bytes_raw(img.pixels.buf[:], img.width, img.height, .RGBA_8_Norm)
  796. }
  797. // Load raw texture data. You need to specify the data, size and format of the texture yourself.
  798. // This assumes that there is no header in the data. If your data has a header (you read the data
  799. // from a file on disk), then please use `load_texture_from_bytes` instead.
  800. load_texture_from_bytes_raw :: proc(bytes: []u8, width: int, height: int, format: Pixel_Format) -> Texture {
  801. backend_tex := rb.load_texture(bytes[:], width, height, format)
  802. if backend_tex == TEXTURE_NONE {
  803. return {}
  804. }
  805. return {
  806. handle = backend_tex,
  807. width = width,
  808. height = height,
  809. }
  810. }
  811. // Get a rectangle that spans the whole texture. Coordinates will be (x, y) = (0, 0) and size
  812. // (w, h) = (texture_width, texture_height)
  813. get_texture_rect :: proc(t: Texture) -> Rect {
  814. return {
  815. 0, 0,
  816. f32(t.width), f32(t.height),
  817. }
  818. }
  819. // Update a texture with new pixels. `bytes` is the new pixel data. `rect` is the rectangle in
  820. // `tex` where the new pixels should end up.
  821. update_texture :: proc(tex: Texture, bytes: []u8, rect: Rect) -> bool {
  822. return rb.update_texture(tex.handle, bytes, rect)
  823. }
  824. // Destroy a texture, freeing up any memory it has used on the GPU.
  825. destroy_texture :: proc(tex: Texture) {
  826. rb.destroy_texture(tex.handle)
  827. }
  828. // Controls how a texture should be filtered. You can choose "point" or "linear" filtering. Which
  829. // means "pixly" or "smooth". This filter will be used for up and down-scaling as well as for
  830. // mipmap sampling. Use `set_texture_filter_ex` if you need to control these settings separately.
  831. set_texture_filter :: proc(t: Texture, filter: Texture_Filter) {
  832. set_texture_filter_ex(t, filter, filter, filter)
  833. }
  834. // Controls how a texture should be filtered. `scale_down_filter` and `scale_up_filter` controls how
  835. // the texture is filtered when we render the texture at a smaller or larger size.
  836. // `mip_filter` controls how the texture is filtered when it is sampled using _mipmapping_.
  837. //
  838. // TODO: Add mipmapping generation controls for texture and refer to it from here.
  839. set_texture_filter_ex :: proc(
  840. t: Texture,
  841. scale_down_filter: Texture_Filter,
  842. scale_up_filter: Texture_Filter,
  843. mip_filter: Texture_Filter,
  844. ) {
  845. rb.set_texture_filter(t.handle, scale_down_filter, scale_up_filter, mip_filter)
  846. }
  847. //-----------------//
  848. // RENDER TEXTURES //
  849. //-----------------//
  850. // Create a texture that you can render into. Meaning that you can draw into it instead of drawing
  851. // onto the screen. Use `set_render_texture` to enable this Render Texture for drawing.
  852. create_render_texture :: proc(width: int, height: int) -> Render_Texture {
  853. texture, render_target := rb.create_render_texture(width, height)
  854. return {
  855. texture = {
  856. handle = texture,
  857. width = width,
  858. height = height,
  859. },
  860. render_target = render_target,
  861. }
  862. }
  863. // Destroy a Render_Texture previously created using `create_render_texture`.
  864. destroy_render_texture :: proc(render_texture: Render_Texture) {
  865. rb.destroy_texture(render_texture.texture.handle)
  866. rb.destroy_render_target(render_texture.render_target)
  867. }
  868. // Make all rendering go into a texture instead of onto the screen. Create the render texture using
  869. // `create_render_texture`. Pass `nil` to resume drawing onto the screen.
  870. set_render_texture :: proc(render_texture: Maybe(Render_Texture)) {
  871. if rt, rt_ok := render_texture.?; rt_ok {
  872. if s.batch_render_target == rt.render_target {
  873. return
  874. }
  875. draw_current_batch()
  876. s.batch_render_target = rt.render_target
  877. s.proj_matrix = make_default_projection(rt.texture.width, rt.texture.height)
  878. } else {
  879. if s.batch_render_target == RENDER_TARGET_NONE {
  880. return
  881. }
  882. draw_current_batch()
  883. s.batch_render_target = RENDER_TARGET_NONE
  884. s.proj_matrix = make_default_projection(win.get_width(), win.get_height())
  885. }
  886. }
  887. //-------//
  888. // FONTS //
  889. //-------//
  890. // Loads a font from disk and returns a handle that represents it.
  891. load_font_from_file :: proc(filename: string) -> Font {
  892. when !FILESYSTEM_SUPPORTED {
  893. log.errorf("load_font_from_file failed: OS %v has no filesystem support! Tip: Use load_font_from_bytes(#load(\"the_font.ttf\")) instead.", ODIN_OS)
  894. return {}
  895. }
  896. if data, data_ok := os.read_entire_file(filename, frame_allocator); data_ok {
  897. return load_font_from_bytes(data)
  898. }
  899. return FONT_NONE
  900. }
  901. // Loads a font from a block of memory and returns a handle that represents it.
  902. load_font_from_bytes :: proc(data: []u8) -> Font {
  903. font := fs.AddFontMem(&s.fs, "", data, false)
  904. h := Font(len(s.fonts))
  905. append(&s.fonts, Font_Data {
  906. fontstash_handle = font,
  907. atlas = {
  908. handle = rb.create_texture(FONT_DEFAULT_ATLAS_SIZE, FONT_DEFAULT_ATLAS_SIZE, .RGBA_8_Norm),
  909. width = FONT_DEFAULT_ATLAS_SIZE,
  910. height = FONT_DEFAULT_ATLAS_SIZE,
  911. },
  912. })
  913. return h
  914. }
  915. // Destroy a font previously loaded using `load_font_from_file` or `load_font_from_bytes`.
  916. destroy_font :: proc(font: Font) {
  917. if int(font) >= len(s.fonts) {
  918. return
  919. }
  920. f := &s.fonts[font]
  921. rb.destroy_texture(f.atlas.handle)
  922. // TODO fontstash has no "destroy font" proc... I should make my own version of fontstash
  923. delete(s.fs.fonts[f.fontstash_handle].glyphs)
  924. s.fs.fonts[f.fontstash_handle].glyphs = {}
  925. }
  926. // Returns the built-in font of Karl2D (the font is known as "roboto")
  927. get_default_font :: proc() -> Font {
  928. return s.default_font
  929. }
  930. //---------//
  931. // SHADERS //
  932. //---------//
  933. // Load a shader from a vertex and fragment shader file. If the vertex and fragment shaders live in
  934. // the same file, then pass it twice.
  935. //
  936. // `layout_formats` can in many cases be left default initialized. It is used to specify the format
  937. // of the vertex shader inputs. By formats this means the format that you pass on the CPU side.
  938. load_shader_from_file :: proc(
  939. vertex_filename: string,
  940. fragment_filename: string,
  941. layout_formats: []Pixel_Format = {}
  942. ) -> Shader {
  943. vertex_source, vertex_source_ok := os.read_entire_file(vertex_filename, frame_allocator)
  944. if !vertex_source_ok {
  945. log.errorf("Failed loading shader %s", vertex_filename)
  946. return {}
  947. }
  948. fragment_source: []byte
  949. if fragment_filename == vertex_filename {
  950. fragment_source = vertex_source
  951. } else {
  952. fragment_source_ok: bool
  953. fragment_source, fragment_source_ok = os.read_entire_file(fragment_filename, frame_allocator)
  954. if !fragment_source_ok {
  955. log.errorf("Failed loading shader %s", fragment_filename)
  956. return {}
  957. }
  958. }
  959. return load_shader_from_bytes(vertex_source, fragment_source, layout_formats)
  960. }
  961. // Load a vertex and fragment shader from a block of memory. See `load_shader_from_file` for what
  962. // `layout_formats` means.
  963. load_shader_from_bytes :: proc(
  964. vertex_shader_bytes: []byte,
  965. fragment_shader_bytes: []byte,
  966. layout_formats: []Pixel_Format = {},
  967. ) -> Shader {
  968. handle, desc := rb.load_shader(
  969. vertex_shader_bytes,
  970. fragment_shader_bytes,
  971. s.frame_allocator,
  972. layout_formats,
  973. )
  974. if handle == SHADER_NONE {
  975. log.error("Failed loading shader")
  976. return {}
  977. }
  978. constants_size: int
  979. for c in desc.constants {
  980. constants_size += c.size
  981. }
  982. shd := Shader {
  983. handle = handle,
  984. constants_data = make([]u8, constants_size, s.allocator),
  985. constants = make([]Shader_Constant_Location, len(desc.constants), s.allocator),
  986. constant_lookup = make(map[string]Shader_Constant_Location, s.allocator),
  987. inputs = slice.clone(desc.inputs, s.allocator),
  988. input_overrides = make([]Shader_Input_Value_Override, len(desc.inputs), s.allocator),
  989. texture_bindpoints = make([]Texture_Handle, len(desc.texture_bindpoints), s.allocator),
  990. texture_lookup = make(map[string]int, s.allocator),
  991. }
  992. for &input in shd.inputs {
  993. input.name = strings.clone(input.name, s.allocator)
  994. }
  995. constant_offset: int
  996. for cidx in 0..<len(desc.constants) {
  997. constant_desc := &desc.constants[cidx]
  998. loc := Shader_Constant_Location {
  999. offset = constant_offset,
  1000. size = constant_desc.size,
  1001. }
  1002. shd.constants[cidx] = loc
  1003. constant_offset += constant_desc.size
  1004. if constant_desc.name != "" {
  1005. shd.constant_lookup[strings.clone(constant_desc.name, s.allocator)] = loc
  1006. switch constant_desc.name {
  1007. case "mvp":
  1008. shd.constant_builtin_locations[.MVP] = loc
  1009. }
  1010. }
  1011. }
  1012. for tbp, tbp_idx in desc.texture_bindpoints {
  1013. shd.texture_lookup[tbp.name] = tbp_idx
  1014. if tbp.name == "tex" {
  1015. shd.default_texture_index = tbp_idx
  1016. }
  1017. }
  1018. for &d in shd.default_input_offsets {
  1019. d = -1
  1020. }
  1021. input_offset: int
  1022. for &input in shd.inputs {
  1023. default_format := get_shader_input_default_type(input.name, input.type)
  1024. if default_format != .Unknown {
  1025. shd.default_input_offsets[default_format] = input_offset
  1026. }
  1027. input_offset += pixel_format_size(input.format)
  1028. }
  1029. shd.vertex_size = input_offset
  1030. return shd
  1031. }
  1032. // Destroy a shader previously loaded using `load_shader_from_file` or `load_shader_from_bytes`
  1033. destroy_shader :: proc(shader: Shader) {
  1034. rb.destroy_shader(shader.handle)
  1035. a := s.allocator
  1036. delete(shader.constants_data, a)
  1037. delete(shader.constants, a)
  1038. delete(shader.texture_lookup)
  1039. delete(shader.texture_bindpoints, a)
  1040. for k, _ in shader.constant_lookup {
  1041. delete(k, a)
  1042. }
  1043. delete(shader.constant_lookup)
  1044. for i in shader.inputs {
  1045. delete(i.name, a)
  1046. }
  1047. delete(shader.inputs, a)
  1048. delete(shader.input_overrides, a)
  1049. }
  1050. // Fetches the shader that Karl2D uses by default.
  1051. get_default_shader :: proc() -> Shader {
  1052. return s.default_shader
  1053. }
  1054. // The supplied shader will be used for subsequent drawing. Return to the default shader by calling
  1055. // `set_shader(nil)`.
  1056. set_shader :: proc(shader: Maybe(Shader)) {
  1057. if shd, shd_ok := shader.?; shd_ok {
  1058. if shd.handle == s.batch_shader.handle {
  1059. return
  1060. }
  1061. } else {
  1062. if s.batch_shader.handle == s.default_shader.handle {
  1063. return
  1064. }
  1065. }
  1066. draw_current_batch()
  1067. s.batch_shader = shader.? or_else s.default_shader
  1068. }
  1069. // Set the value of a constant (also known as uniform in OpenGL). Look up shader constant locations
  1070. // (the kind of value needed for `loc`) by running `loc := shader.constant_lookup["constant_name"]`.
  1071. set_shader_constant :: proc(shd: Shader, loc: Shader_Constant_Location, val: any) {
  1072. if shd.handle == SHADER_NONE {
  1073. log.error("Invalid shader")
  1074. return
  1075. }
  1076. if loc.size == 0 {
  1077. log.error("Could not find shader constant")
  1078. return
  1079. }
  1080. draw_current_batch()
  1081. if loc.offset + loc.size > len(shd.constants_data) {
  1082. 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))
  1083. return
  1084. }
  1085. sz := reflect.size_of_typeid(val.id)
  1086. if sz != loc.size {
  1087. log.errorf("Trying to set constant of type %v, but it is not of correct size %v", val.id, loc.size)
  1088. return
  1089. }
  1090. mem.copy(&shd.constants_data[loc.offset], val.data, sz)
  1091. }
  1092. // Sets the value of a shader input (also known as a shader attribute). There are three default
  1093. // shader inputs known as position, texcoord and color. If you have shader with additional inputs,
  1094. // then you can use this procedure to set their values. This is a way to feed per-object data into
  1095. // your shader.
  1096. //
  1097. // `input` should be the index of the input and `val` should be a value of the correct size.
  1098. //
  1099. // You can modify which type that is expected for `val` by passing a custom `layout_formats` when
  1100. // you load the shader.
  1101. override_shader_input :: proc(shader: Shader, input: int, val: any) {
  1102. sz := reflect.size_of_typeid(val.id)
  1103. assert(sz < SHADER_INPUT_VALUE_MAX_SIZE)
  1104. if input >= len(shader.input_overrides) {
  1105. log.errorf("Input override out of range. Wanted to override input %v, but shader only has %v inputs", input, len(shader.input_overrides))
  1106. return
  1107. }
  1108. o := &shader.input_overrides[input]
  1109. o.val = {}
  1110. if sz > 0 {
  1111. mem.copy(raw_data(&o.val), val.data, sz)
  1112. }
  1113. o.used = sz
  1114. }
  1115. // Returns the number of bytes that a pixel in a texture uses.
  1116. pixel_format_size :: proc(f: Pixel_Format) -> int {
  1117. switch f {
  1118. case .Unknown: return 0
  1119. case .RGBA_32_Float: return 32
  1120. case .RGB_32_Float: return 12
  1121. case .RG_32_Float: return 8
  1122. case .R_32_Float: return 4
  1123. case .RGBA_8_Norm: return 4
  1124. case .RG_8_Norm: return 2
  1125. case .R_8_Norm: return 1
  1126. case .R_8_UInt: return 1
  1127. }
  1128. return 0
  1129. }
  1130. //-------------------------------//
  1131. // CAMERA AND COORDINATE SYSTEMS //
  1132. //-------------------------------//
  1133. // Make Karl2D use a camera. Return to the "default camera" by passing `nil`. All drawing operations
  1134. // will use this camera until you again change it.
  1135. set_camera :: proc(camera: Maybe(Camera)) {
  1136. if camera == s.batch_camera {
  1137. return
  1138. }
  1139. draw_current_batch()
  1140. s.batch_camera = camera
  1141. s.proj_matrix = make_default_projection(win.get_width(), win.get_height())
  1142. if c, c_ok := camera.?; c_ok {
  1143. s.view_matrix = get_camera_view_matrix(c)
  1144. } else {
  1145. s.view_matrix = 1
  1146. }
  1147. }
  1148. // Transform a point `pos` that lives on the screen to a point in the world. This can be useful for
  1149. // bringing (for example) mouse positions (k2.get_mouse_position()) into world-space.
  1150. screen_to_world :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  1151. return (get_camera_world_matrix(camera) * Vec4 { pos.x, pos.y, 0, 1 }).xy
  1152. }
  1153. // Transform a point `pos` that lices in the world to a point on the screen. This can be useful when
  1154. // you need to take a position in the world and compare it to a screen-space point.
  1155. world_to_screen :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  1156. return (get_camera_view_matrix(camera) * Vec4 { pos.x, pos.y, 0, 1 }).xy
  1157. }
  1158. // Get the matrix that `screen_to_world` and `world_to_screen` uses to do their transformations.
  1159. //
  1160. // A view matrix is essentially the world transform matrix of the camera, but inverted. In other
  1161. // words, instead of bringing the camera in front of things in the world, we bring everything in the
  1162. // world "in front of the camera".
  1163. //
  1164. // Instead of constructing the camera matrix and doing a matrix inverse, here we just do the
  1165. // maths in "backwards order". I.e. a camera transform matrix would be:
  1166. //
  1167. // target_translate * rot * scale * offset_translate
  1168. //
  1169. // but we do
  1170. //
  1171. // inv_offset_translate * inv_scale * inv_rot * inv_target_translate
  1172. //
  1173. // This is faster, since matrix inverses are expensive.
  1174. get_camera_view_matrix :: proc(c: Camera) -> Mat4 {
  1175. inv_target_translate := linalg.matrix4_translate(vec3_from_vec2(-c.target))
  1176. inv_rot := linalg.matrix4_rotate_f32(c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  1177. inv_scale := linalg.matrix4_scale(Vec3{c.zoom, c.zoom, 1})
  1178. inv_offset_translate := linalg.matrix4_translate(vec3_from_vec2(c.offset))
  1179. return inv_offset_translate * inv_scale * inv_rot * inv_target_translate
  1180. }
  1181. // Get the matrix that brings something in front of the camera.
  1182. get_camera_world_matrix :: proc(c: Camera) -> Mat4 {
  1183. offset_translate := linalg.matrix4_translate(vec3_from_vec2(-c.offset))
  1184. rot := linalg.matrix4_rotate_f32(-c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  1185. scale := linalg.matrix4_scale(Vec3{1/c.zoom, 1/c.zoom, 1})
  1186. target_translate := linalg.matrix4_translate(vec3_from_vec2(c.target))
  1187. return target_translate * rot * scale * offset_translate
  1188. }
  1189. //------//
  1190. // MISC //
  1191. //------//
  1192. // Choose how the alpha channel is used when mixing half-transparent color with what is already
  1193. // drawn. The default is the .Alpha mode, but you also have the option of using .Premultiply_Alpha.
  1194. set_blend_mode :: proc(mode: Blend_Mode) {
  1195. if s.batch_blend_mode == mode {
  1196. return
  1197. }
  1198. draw_current_batch()
  1199. s.batch_blend_mode = mode
  1200. }
  1201. // Make everything outside of the screen-space rectangle `scissor_rect` not render. Disable the
  1202. // scissor rectangle by running `set_scissor_rect(nil)`.
  1203. set_scissor_rect :: proc(scissor_rect: Maybe(Rect)) {
  1204. draw_current_batch()
  1205. s.batch_scissor = scissor_rect
  1206. }
  1207. // Restore the internal state using the pointer returned by `init`. Useful after reloading the
  1208. // library (for example, when doing code hot reload).
  1209. set_internal_state :: proc(state: ^State) {
  1210. s = state
  1211. rb = s.rb
  1212. win = s.win
  1213. rb.set_internal_state(s.rb_state)
  1214. win.set_internal_state(s.window_state)
  1215. }
  1216. //---------------------//
  1217. // TYPES AND CONSTANTS //
  1218. //---------------------//
  1219. Vec2 :: [2]f32
  1220. Vec3 :: [3]f32
  1221. Vec4 :: [4]f32
  1222. Mat4 :: matrix[4,4]f32
  1223. // A rectangle that sits at position (x, y) and has size (w, h).
  1224. Rect :: struct {
  1225. x, y: f32,
  1226. w, h: f32,
  1227. }
  1228. // An RGBA (Red, Green, Blue, Alpha) color. Each channel can have a value between 0 and 255.
  1229. Color :: [4]u8
  1230. // See the folder examples/palette for a demo that shows all colors
  1231. BLACK :: Color { 0, 0, 0, 255 }
  1232. WHITE :: Color { 255, 255, 255, 255 }
  1233. BLANK :: Color { 0, 0, 0, 0 }
  1234. GRAY :: Color { 183, 183, 183, 255 }
  1235. DARK_GRAY :: Color { 66, 66, 66, 255}
  1236. BLUE :: Color { 25, 198, 236, 255 }
  1237. DARK_BLUE :: Color { 7, 47, 88, 255 }
  1238. LIGHT_BLUE :: Color { 200, 230, 255, 255 }
  1239. GREEN :: Color { 16, 130, 11, 255 }
  1240. DARK_GREEN :: Color { 6, 53, 34, 255}
  1241. LIGHT_GREEN :: Color { 175, 246, 184, 255 }
  1242. ORANGE :: Color { 255, 114, 0, 255 }
  1243. RED :: Color { 239, 53, 53, 255 }
  1244. DARK_RED :: Color { 127, 10, 10, 255 }
  1245. LIGHT_RED :: Color { 248, 183, 183, 255 }
  1246. BROWN :: Color { 115, 78, 74, 255 }
  1247. DARK_BROWN :: Color { 50, 36, 32, 255 }
  1248. LIGHT_BROWN :: Color { 146, 119, 119, 255 }
  1249. PURPLE :: Color { 155, 31, 232, 255 }
  1250. LIGHT_PURPLE :: Color { 217, 172, 248, 255 }
  1251. MAGENTA :: Color { 209, 17, 209, 255 }
  1252. YELLOW :: Color { 250, 250, 129, 255 }
  1253. LIGHT_YELLOW :: Color { 253, 250, 222, 255 }
  1254. // These are from Raylib. They are here so you can easily port a Raylib program to Karl2D.
  1255. RL_LIGHTGRAY :: Color { 200, 200, 200, 255 }
  1256. RL_GRAY :: Color { 130, 130, 130, 255 }
  1257. RL_DARKGRAY :: Color { 80, 80, 80, 255 }
  1258. RL_YELLOW :: Color { 253, 249, 0, 255 }
  1259. RL_GOLD :: Color { 255, 203, 0, 255 }
  1260. RL_ORANGE :: Color { 255, 161, 0, 255 }
  1261. RL_PINK :: Color { 255, 109, 194, 255 }
  1262. RL_RED :: Color { 230, 41, 55, 255 }
  1263. RL_MAROON :: Color { 190, 33, 55, 255 }
  1264. RL_GREEN :: Color { 0, 228, 48, 255 }
  1265. RL_LIME :: Color { 0, 158, 47, 255 }
  1266. RL_DARKGREEN :: Color { 0, 117, 44, 255 }
  1267. RL_SKYBLUE :: Color { 102, 191, 255, 255 }
  1268. RL_BLUE :: Color { 0, 121, 241, 255 }
  1269. RL_DARKBLUE :: Color { 0, 82, 172, 255 }
  1270. RL_PURPLE :: Color { 200, 122, 255, 255 }
  1271. RL_VIOLET :: Color { 135, 60, 190, 255 }
  1272. RL_DARKPURPLE :: Color { 112, 31, 126, 255 }
  1273. RL_BEIGE :: Color { 211, 176, 131, 255 }
  1274. RL_BROWN :: Color { 127, 106, 79, 255 }
  1275. RL_DARKBROWN :: Color { 76, 63, 47, 255 }
  1276. RL_WHITE :: WHITE
  1277. RL_BLACK :: BLACK
  1278. RL_BLANK :: BLANK
  1279. RL_MAGENTA :: Color { 255, 0, 255, 255 }
  1280. RL_RAYWHITE :: Color { 245, 245, 245, 255 }
  1281. color_alpha :: proc(c: Color, a: u8) -> Color {
  1282. return {c.r, c.g, c.b, a}
  1283. }
  1284. Texture :: struct {
  1285. // The render-backend specific texture identifier.
  1286. handle: Texture_Handle,
  1287. // The horizontal size of the texture, measured in pixels.
  1288. width: int,
  1289. // The vertical size of the texture, measure in pixels.
  1290. height: int,
  1291. }
  1292. Load_Texture_Option :: enum {
  1293. // Will multiply the alpha value of the each pixel into the its RGB values. Useful if you want
  1294. // to use `set_blend_mode(.Premultiplied_Alpha)`
  1295. Premultiply_Alpha,
  1296. }
  1297. Load_Texture_Options :: bit_set[Load_Texture_Option]
  1298. Blend_Mode :: enum {
  1299. Alpha,
  1300. // Requires the alpha-channel to be multiplied into texture RGB channels. You can automatically
  1301. // do this using the `Premultiply_Alpha` option when loading a texture.
  1302. Premultiplied_Alpha,
  1303. }
  1304. // A render texture is a texture that you can draw into, instead of drawing to the screen. Create
  1305. // one using `create_render_texture`.
  1306. Render_Texture :: struct {
  1307. // The texture that the things will be drawn into. You can use this as a normal texture, for
  1308. // example, you can pass it to `draw_texture`.
  1309. texture: Texture,
  1310. // The render backend's internal identifier. It describes how to use the texture as something
  1311. // the render backend can draw into.
  1312. render_target: Render_Target_Handle,
  1313. }
  1314. Texture_Filter :: enum {
  1315. Point, // Similar to "nearest neighbor". Pixly texture scaling.
  1316. Linear, // Smoothed texture scaling.
  1317. }
  1318. Camera :: struct {
  1319. // Where the camera looks.
  1320. target: Vec2,
  1321. // By default `target` will be the position of the upper-left corner of the camera. Use this
  1322. // offset to change that. If you set the offset to half the size of the camera view, then the
  1323. // target position will end up in the middle of the scren.
  1324. offset: Vec2,
  1325. // Rotate the camera (unit: degrees)
  1326. rotation: f32,
  1327. // Zoom the camera. A bigger value means "more zoom".
  1328. //
  1329. // To make a certain amount of pixels always occupy the height of the camera, set the zoom to:
  1330. //
  1331. // k2.get_screen_height()/wanted_pixel_height
  1332. zoom: f32,
  1333. }
  1334. Window_Mode :: enum {
  1335. Windowed,
  1336. Windowed_Resizable,
  1337. Borderless_Fullscreen,
  1338. }
  1339. Init_Options :: struct {
  1340. window_mode: Window_Mode,
  1341. }
  1342. Shader_Handle :: distinct Handle
  1343. SHADER_NONE :: Shader_Handle {}
  1344. Shader_Constant_Location :: struct {
  1345. offset: int,
  1346. size: int,
  1347. }
  1348. Shader :: struct {
  1349. // The render backend's internal identifier.
  1350. handle: Shader_Handle,
  1351. // We store the CPU-side value of all constants in a single buffer to have less allocations.
  1352. // The 'constants' array says where in this buffer each constant is, and 'constant_lookup'
  1353. // maps a name to a constant location.
  1354. constants_data: []u8,
  1355. constants: []Shader_Constant_Location,
  1356. // Look up named constants. If you have a constant (uniform) in the shader called "bob", then
  1357. // you can find its location by running `shader.constant_lookup["bob"]`. You can then use that
  1358. // location in combination with `set_shader_constant`
  1359. constant_lookup: map[string]Shader_Constant_Location,
  1360. // Maps built in constant types such as "model view projection matrix" to a location.
  1361. constant_builtin_locations: [Shader_Builtin_Constant]Maybe(Shader_Constant_Location),
  1362. texture_bindpoints: []Texture_Handle,
  1363. // Used to lookup bindpoints of textures. You can then set the texture by overriding
  1364. // `shader.texture_bindpoints[shader.texture_lookup["some_tex"]] = some_texture.handle`
  1365. texture_lookup: map[string]int,
  1366. default_texture_index: Maybe(int),
  1367. inputs: []Shader_Input,
  1368. // Overrides the value of a specific vertex input.
  1369. //
  1370. // It's recommended you use `override_shader_input` to modify these overrides.
  1371. input_overrides: []Shader_Input_Value_Override,
  1372. default_input_offsets: [Shader_Default_Inputs]int,
  1373. // How many bytes a vertex uses gives the input of the shader.
  1374. vertex_size: int,
  1375. }
  1376. SHADER_INPUT_VALUE_MAX_SIZE :: 256
  1377. Shader_Input_Value_Override :: struct {
  1378. val: [SHADER_INPUT_VALUE_MAX_SIZE]u8,
  1379. used: int,
  1380. }
  1381. Shader_Input_Type :: enum {
  1382. F32,
  1383. Vec2,
  1384. Vec3,
  1385. Vec4,
  1386. }
  1387. Shader_Builtin_Constant :: enum {
  1388. MVP,
  1389. }
  1390. Shader_Default_Inputs :: enum {
  1391. Unknown,
  1392. Position,
  1393. UV,
  1394. Color,
  1395. }
  1396. Shader_Input :: struct {
  1397. name: string,
  1398. register: int,
  1399. type: Shader_Input_Type,
  1400. format: Pixel_Format,
  1401. }
  1402. Pixel_Format :: enum {
  1403. Unknown,
  1404. RGBA_32_Float,
  1405. RGB_32_Float,
  1406. RG_32_Float,
  1407. R_32_Float,
  1408. RGBA_8_Norm,
  1409. RG_8_Norm,
  1410. R_8_Norm,
  1411. R_8_UInt,
  1412. }
  1413. Font_Data :: struct {
  1414. atlas: Texture,
  1415. // internal
  1416. fontstash_handle: int,
  1417. }
  1418. Handle :: hm.Handle
  1419. Texture_Handle :: distinct Handle
  1420. Render_Target_Handle :: distinct Handle
  1421. Font :: distinct int
  1422. FONT_NONE :: Font {}
  1423. TEXTURE_NONE :: Texture_Handle {}
  1424. RENDER_TARGET_NONE :: Render_Target_Handle {}
  1425. // This keeps track of the internal state of the library. Usually, you do not need to poke at it.
  1426. // It is created and kept as a global variable when 'init' is called. However, 'init' also returns
  1427. // the pointer to it, so you can later use 'set_internal_state' to restore it (after for example hot
  1428. // reload).
  1429. State :: struct {
  1430. allocator: runtime.Allocator,
  1431. frame_arena: runtime.Arena,
  1432. frame_allocator: runtime.Allocator,
  1433. win: Window_Interface,
  1434. window_state: rawptr,
  1435. rb: Render_Backend_Interface,
  1436. rb_state: rawptr,
  1437. fs: fs.FontContext,
  1438. shutdown_wanted: bool,
  1439. mouse_position: Vec2,
  1440. mouse_delta: Vec2,
  1441. mouse_wheel_delta: f32,
  1442. key_went_down: #sparse [Keyboard_Key]bool,
  1443. key_went_up: #sparse [Keyboard_Key]bool,
  1444. key_is_held: #sparse [Keyboard_Key]bool,
  1445. mouse_button_went_down: #sparse [Mouse_Button]bool,
  1446. mouse_button_went_up: #sparse [Mouse_Button]bool,
  1447. mouse_button_is_held: #sparse [Mouse_Button]bool,
  1448. gamepad_button_went_down: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1449. gamepad_button_went_up: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1450. gamepad_button_is_held: [MAX_GAMEPADS]#sparse [Gamepad_Button]bool,
  1451. window: Window_Handle,
  1452. default_font: Font,
  1453. fonts: [dynamic]Font_Data,
  1454. shape_drawing_texture: Texture_Handle,
  1455. batch_font: Font,
  1456. batch_camera: Maybe(Camera),
  1457. batch_shader: Shader,
  1458. batch_scissor: Maybe(Rect),
  1459. batch_texture: Texture_Handle,
  1460. batch_render_target: Render_Target_Handle,
  1461. batch_blend_mode: Blend_Mode,
  1462. view_matrix: Mat4,
  1463. proj_matrix: Mat4,
  1464. depth: f32,
  1465. depth_start: f32,
  1466. depth_increment: f32,
  1467. vertex_buffer_cpu: []u8,
  1468. vertex_buffer_cpu_used: int,
  1469. default_shader: Shader,
  1470. // Time when the first call to `new_frame` happened
  1471. start_time: time.Time,
  1472. prev_frame_time: time.Time,
  1473. // "dt"
  1474. frame_time: f32,
  1475. time: f64,
  1476. }
  1477. // Support for up to 255 mouse buttons. Cast an int to type `Mouse_Button` to use things outside the
  1478. // options presented here.
  1479. Mouse_Button :: enum {
  1480. Left,
  1481. Right,
  1482. Middle,
  1483. Max = 255,
  1484. }
  1485. // Based on Raylib / GLFW
  1486. Keyboard_Key :: enum {
  1487. None = 0,
  1488. // Numeric keys (top row)
  1489. N0 = 48,
  1490. N1 = 49,
  1491. N2 = 50,
  1492. N3 = 51,
  1493. N4 = 52,
  1494. N5 = 53,
  1495. N6 = 54,
  1496. N7 = 55,
  1497. N8 = 56,
  1498. N9 = 57,
  1499. // Letter keys
  1500. A = 65,
  1501. B = 66,
  1502. C = 67,
  1503. D = 68,
  1504. E = 69,
  1505. F = 70,
  1506. G = 71,
  1507. H = 72,
  1508. I = 73,
  1509. J = 74,
  1510. K = 75,
  1511. L = 76,
  1512. M = 77,
  1513. N = 78,
  1514. O = 79,
  1515. P = 80,
  1516. Q = 81,
  1517. R = 82,
  1518. S = 83,
  1519. T = 84,
  1520. U = 85,
  1521. V = 86,
  1522. W = 87,
  1523. X = 88,
  1524. Y = 89,
  1525. Z = 90,
  1526. // Special characters
  1527. Apostrophe = 39,
  1528. Comma = 44,
  1529. Minus = 45,
  1530. Period = 46,
  1531. Slash = 47,
  1532. Semicolon = 59,
  1533. Equal = 61,
  1534. Left_Bracket = 91,
  1535. Backslash = 92,
  1536. Right_Bracket = 93,
  1537. Backtick = 96,
  1538. // Function keys, modifiers, caret control etc
  1539. Space = 32,
  1540. Escape = 256,
  1541. Enter = 257,
  1542. Tab = 258,
  1543. Backspace = 259,
  1544. Insert = 260,
  1545. Delete = 261,
  1546. Right = 262,
  1547. Left = 263,
  1548. Down = 264,
  1549. Up = 265,
  1550. Page_Up = 266,
  1551. Page_Down = 267,
  1552. Home = 268,
  1553. End = 269,
  1554. Caps_Lock = 280,
  1555. Scroll_Lock = 281,
  1556. Num_Lock = 282,
  1557. Print_Screen = 283,
  1558. Pause = 284,
  1559. F1 = 290,
  1560. F2 = 291,
  1561. F3 = 292,
  1562. F4 = 293,
  1563. F5 = 294,
  1564. F6 = 295,
  1565. F7 = 296,
  1566. F8 = 297,
  1567. F9 = 298,
  1568. F10 = 299,
  1569. F11 = 300,
  1570. F12 = 301,
  1571. Left_Shift = 340,
  1572. Left_Control = 341,
  1573. Left_Alt = 342,
  1574. Left_Super = 343,
  1575. Right_Shift = 344,
  1576. Right_Control = 345,
  1577. Right_Alt = 346,
  1578. Right_Super = 347,
  1579. Menu = 348,
  1580. // Numpad keys
  1581. NP_0 = 320,
  1582. NP_1 = 321,
  1583. NP_2 = 322,
  1584. NP_3 = 323,
  1585. NP_4 = 324,
  1586. NP_5 = 325,
  1587. NP_6 = 326,
  1588. NP_7 = 327,
  1589. NP_8 = 328,
  1590. NP_9 = 329,
  1591. NP_Decimal = 330,
  1592. NP_Divide = 331,
  1593. NP_Multiply = 332,
  1594. NP_Subtract = 333,
  1595. NP_Add = 334,
  1596. NP_Enter = 335,
  1597. NP_Equal = 336,
  1598. }
  1599. MAX_GAMEPADS :: 4
  1600. // A value between 0 and MAX_GAMEPADS - 1
  1601. Gamepad_Index :: int
  1602. Gamepad_Axis :: enum {
  1603. Left_Stick_X,
  1604. Left_Stick_Y,
  1605. Right_Stick_X,
  1606. Right_Stick_Y,
  1607. Left_Trigger,
  1608. Right_Trigger,
  1609. }
  1610. Gamepad_Button :: enum {
  1611. // DPAD buttons
  1612. Left_Face_Up,
  1613. Left_Face_Down,
  1614. Left_Face_Left,
  1615. Left_Face_Right,
  1616. Right_Face_Up, // XBOX: Y, PS: Triangle
  1617. Right_Face_Down, // XBOX: A, PS: X
  1618. Right_Face_Left, // XBOX: X, PS: Square
  1619. Right_Face_Right, // XBOX: B, PS: Circle
  1620. Left_Shoulder,
  1621. Left_Trigger,
  1622. Right_Shoulder,
  1623. Right_Trigger,
  1624. Left_Stick_Press, // Clicking the left analogue stick
  1625. Right_Stick_Press, // Clicking the right analogue stick
  1626. Middle_Face_Left, // Select / back / options button
  1627. Middle_Face_Middle, // PS button (not available on XBox)
  1628. Middle_Face_Right, // Start
  1629. }
  1630. // Used by API builder. Everything after this constant will not be in karl2d.doc.odin
  1631. API_END :: true
  1632. batch_vertex :: proc(v: Vec3, uv: Vec2, color: Color) {
  1633. v := v
  1634. if s.vertex_buffer_cpu_used == len(s.vertex_buffer_cpu) {
  1635. draw_current_batch()
  1636. }
  1637. shd := s.batch_shader
  1638. base_offset := s.vertex_buffer_cpu_used
  1639. pos_offset := shd.default_input_offsets[.Position]
  1640. uv_offset := shd.default_input_offsets[.UV]
  1641. color_offset := shd.default_input_offsets[.Color]
  1642. mem.set(&s.vertex_buffer_cpu[base_offset], 0, shd.vertex_size)
  1643. if pos_offset != -1 {
  1644. (^Vec3)(&s.vertex_buffer_cpu[base_offset + pos_offset])^ = v
  1645. }
  1646. if uv_offset != -1 {
  1647. (^Vec2)(&s.vertex_buffer_cpu[base_offset + uv_offset])^ = uv
  1648. }
  1649. if color_offset != -1 {
  1650. (^Color)(&s.vertex_buffer_cpu[base_offset + color_offset])^ = color
  1651. }
  1652. override_offset: int
  1653. for &o, idx in shd.input_overrides {
  1654. input := &shd.inputs[idx]
  1655. sz := pixel_format_size(input.format)
  1656. if o.used != 0 {
  1657. mem.copy(&s.vertex_buffer_cpu[base_offset + override_offset], raw_data(&o.val), o.used)
  1658. }
  1659. override_offset += sz
  1660. }
  1661. s.vertex_buffer_cpu_used += shd.vertex_size
  1662. }
  1663. VERTEX_BUFFER_MAX :: 1000000
  1664. @(private="file")
  1665. s: ^State
  1666. // These globals are here for access from other files. The state struct above is private to make
  1667. // sure global state sharing doesn't become too messy.
  1668. frame_allocator: runtime.Allocator
  1669. win: Window_Interface
  1670. rb: Render_Backend_Interface
  1671. get_shader_input_default_type :: proc(name: string, type: Shader_Input_Type) -> Shader_Default_Inputs {
  1672. if name == "position" && type == .Vec3 {
  1673. return .Position
  1674. } else if name == "texcoord" && type == .Vec2 {
  1675. return .UV
  1676. } else if name == "color" && type == .Vec4 {
  1677. return .Color
  1678. }
  1679. return .Unknown
  1680. }
  1681. get_shader_format_num_components :: proc(format: Pixel_Format) -> int {
  1682. switch format {
  1683. case .Unknown: return 0
  1684. case .RGBA_32_Float: return 4
  1685. case .RGB_32_Float: return 3
  1686. case .RG_32_Float: return 2
  1687. case .R_32_Float: return 1
  1688. case .RGBA_8_Norm: return 4
  1689. case .RG_8_Norm: return 2
  1690. case .R_8_Norm: return 1
  1691. case .R_8_UInt: return 1
  1692. }
  1693. return 0
  1694. }
  1695. get_shader_input_format :: proc(name: string, type: Shader_Input_Type) -> Pixel_Format {
  1696. default_type := get_shader_input_default_type(name, type)
  1697. if default_type != .Unknown {
  1698. switch default_type {
  1699. case .Position: return .RGB_32_Float
  1700. case .UV: return .RG_32_Float
  1701. case .Color: return .RGBA_8_Norm
  1702. case .Unknown: unreachable()
  1703. }
  1704. }
  1705. switch type {
  1706. case .F32: return .R_32_Float
  1707. case .Vec2: return .RG_32_Float
  1708. case .Vec3: return .RGB_32_Float
  1709. case .Vec4: return .RGBA_32_Float
  1710. }
  1711. return .Unknown
  1712. }
  1713. vec3_from_vec2 :: proc(v: Vec2) -> Vec3 {
  1714. return {
  1715. v.x, v.y, 0,
  1716. }
  1717. }
  1718. frame_cstring :: proc(str: string, loc := #caller_location) -> cstring {
  1719. return strings.clone_to_cstring(str, s.frame_allocator, loc)
  1720. }
  1721. @(require_results)
  1722. matrix_ortho3d_f32 :: proc "contextless" (left, right, bottom, top, near, far: f32) -> Mat4 #no_bounds_check {
  1723. m: Mat4
  1724. m[0, 0] = +2 / (right - left)
  1725. m[1, 1] = +2 / (top - bottom)
  1726. m[2, 2] = +1
  1727. m[0, 3] = -(right + left) / (right - left)
  1728. m[1, 3] = -(top + bottom) / (top - bottom)
  1729. m[2, 3] = 0
  1730. m[3, 3] = 1
  1731. return m
  1732. }
  1733. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  1734. return matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  1735. }
  1736. FONT_DEFAULT_ATLAS_SIZE :: 1024
  1737. _update_font :: proc(fh: Font) {
  1738. font := &s.fonts[fh]
  1739. font_dirty_rect: [4]f32
  1740. tw := FONT_DEFAULT_ATLAS_SIZE
  1741. if fs.ValidateTexture(&s.fs, &font_dirty_rect) {
  1742. fdr := font_dirty_rect
  1743. r := Rect {
  1744. fdr[0],
  1745. fdr[1],
  1746. fdr[2] - fdr[0],
  1747. fdr[3] - fdr[1],
  1748. }
  1749. x := int(r.x)
  1750. y := int(r.y)
  1751. w := int(fdr[2]) - int(fdr[0])
  1752. h := int(fdr[3]) - int(fdr[1])
  1753. expanded_pixels := make([]Color, w * h, frame_allocator)
  1754. start := x + tw * y
  1755. for i in 0..<w*h {
  1756. px := i%w
  1757. py := i/w
  1758. dst_pixel_idx := (px) + (py * w)
  1759. src_pixel_idx := start + (px) + (py * tw)
  1760. src := s.fs.textureData[src_pixel_idx]
  1761. expanded_pixels[dst_pixel_idx] = {255,255,255, src}
  1762. }
  1763. rb.update_texture(font.atlas.handle, slice.reinterpret([]u8, expanded_pixels), r)
  1764. }
  1765. }
  1766. // Not for direct use. Specify font to `draw_text_ex`
  1767. _set_font :: proc(fh: Font) {
  1768. fh := fh
  1769. if s.batch_font == fh {
  1770. return
  1771. }
  1772. draw_current_batch()
  1773. s.batch_font = fh
  1774. if s.batch_font != FONT_NONE {
  1775. _update_font(s.batch_font)
  1776. }
  1777. if fh == 0 {
  1778. fh = s.default_font
  1779. }
  1780. font := &s.fonts[fh]
  1781. fs.SetFont(&s.fs, font.fontstash_handle)
  1782. }
  1783. DEPTH_START :: -1 + DEPTH_INCREMENT
  1784. DEPTH_INCREMENT :: (1.0/10000000.0)
  1785. _ :: jpeg
  1786. _ :: bmp
  1787. _ :: png
  1788. _ :: tga
  1789. Color_F32 :: [4]f32
  1790. f32_color_from_color :: proc(color: Color) -> Color_F32 {
  1791. return {
  1792. f32(color.r) / 255,
  1793. f32(color.g) / 255,
  1794. f32(color.b) / 255,
  1795. f32(color.a) / 255,
  1796. }
  1797. }
  1798. vec3 :: proc(v2: Vec2, z: f32) -> Vec3 {
  1799. return {
  1800. v2.x, v2.y, z,
  1801. }
  1802. }
  1803. get_next_depth :: proc() -> f32 {
  1804. d := s.depth
  1805. s.depth += s.depth_increment
  1806. return d
  1807. }
  1808. FILESYSTEM_SUPPORTED :: ODIN_OS != .JS && ODIN_OS != .Freestanding