karl2d.odin 56 KB

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