karl2d.odin 40 KB

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