karl2d.odin 49 KB

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