karl2d.odin 39 KB

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