karl2d.odin 49 KB

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