karl2d.odin 40 KB

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