karl2d.odin 37 KB

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