karl2d.odin 37 KB

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