karl2d.odin 61 KB

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