karl2d.odin 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608
  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 fs "vendor:fontstash"
  11. import "core:image"
  12. import "core:image/jpeg"
  13. import "core:image/bmp"
  14. import "core:image/png"
  15. import "core:image/tga"
  16. import hm "handle_map"
  17. //-----------------------------------------------//
  18. // SETUP, WINDOW MANAGEMENT AND FRAME MANAGEMENT //
  19. //-----------------------------------------------//
  20. // Opens a window and initializes some internal state. The internal state will use `allocator` for
  21. // all dynamically allocated memory. The return value can be ignored unless you need to later call
  22. // `set_internal_state`.
  23. init :: proc(window_width: int, window_height: int, window_title: string,
  24. window_creation_flags := Window_Flags {},
  25. allocator := context.allocator, loc := #caller_location) -> ^State {
  26. assert(s == nil, "Don't call 'init' twice.")
  27. s = new(State, allocator, loc)
  28. s.frame_allocator = runtime.arena_allocator(&s.frame_arena)
  29. frame_allocator = s.frame_allocator
  30. s.allocator = allocator
  31. s.custom_context = context
  32. s.width = window_width
  33. s.height = window_height
  34. s.win = WINDOW_INTERFACE_WIN32
  35. win = s.win
  36. window_state_alloc_error: runtime.Allocator_Error
  37. s.window_state, window_state_alloc_error = mem.alloc(win.state_size())
  38. log.assertf(window_state_alloc_error == nil, "Failed allocating memory for window state: %v", window_state_alloc_error)
  39. win.init(s.window_state, window_width, window_height, window_title, window_creation_flags, allocator)
  40. s.window = win.window_handle()
  41. s.rb = RENDER_BACKEND_INTERFACE_D3D11
  42. rb = s.rb
  43. rb_alloc_error: runtime.Allocator_Error
  44. s.rb_state, rb_alloc_error = mem.alloc(rb.state_size())
  45. log.assertf(rb_alloc_error == nil, "Failed allocating memory for rendering backend: %v", rb_alloc_error)
  46. s.proj_matrix = make_default_projection(window_width, window_height)
  47. s.view_matrix = 1
  48. rb.init(s.rb_state, s.window, window_width, window_height, allocator)
  49. s.vertex_buffer_cpu = make([]u8, VERTEX_BUFFER_MAX, allocator, loc)
  50. white_rect: [16*16*4]u8
  51. slice.fill(white_rect[:], 255)
  52. s.shape_drawing_texture = rb.load_texture(white_rect[:], 16, 16, .RGBA_8_Norm)
  53. s.default_shader = load_shader(string(DEFAULT_SHADER_SOURCE))
  54. s.batch_shader = s.default_shader
  55. /*if font, font_err := load_default_font(); font_err == .OK {
  56. s.default_font = font
  57. } else {
  58. log.infof("Loading of 'default_font.ttf' failed: %v", font_err)
  59. }*/
  60. fs.Init(&s.fs, FONT_DEFAULT_ATLAS_SIZE, FONT_DEFAULT_ATLAS_SIZE, .TOPLEFT)
  61. ROBOTO_FONT_DATA :: #load("roboto.ttf")
  62. roboto_font := fs.AddFontMem(&s.fs, "roboto", ROBOTO_FONT_DATA, false)
  63. fs.SetFont(&s.fs, roboto_font)
  64. s.default_font = Font_Handle(len(s.fonts))
  65. append(&s.fonts, Font {
  66. fontstash_handle = roboto_font,
  67. atlas = {
  68. handle = rb.create_texture(FONT_DEFAULT_ATLAS_SIZE, FONT_DEFAULT_ATLAS_SIZE, .RGBA_8_Norm),
  69. width = FONT_DEFAULT_ATLAS_SIZE,
  70. height = FONT_DEFAULT_ATLAS_SIZE,
  71. },
  72. })
  73. return s
  74. }
  75. // Returns true if the program wants to shut down. This happens when for example pressing the close
  76. // button on the window. The application can decide if it wants to shut down or if it wants to show
  77. // some kind of confirmation dialogue and shut down later.
  78. //
  79. // Commonly used for creating the "main loop" of a game.
  80. shutdown_wanted :: proc() -> bool {
  81. return s.shutdown_wanted
  82. }
  83. // Closes the window and cleans up the internal state.
  84. shutdown :: proc() {
  85. assert(s != nil, "You've called 'shutdown' without calling 'init' first")
  86. rb.destroy_texture(s.shape_drawing_texture)
  87. destroy_shader(s.default_shader)
  88. rb.shutdown()
  89. delete(s.vertex_buffer_cpu, s.allocator)
  90. win.shutdown()
  91. fs.Destroy(&s.fs)
  92. a := s.allocator
  93. free(s.window_state, a)
  94. free(s.rb_state, a)
  95. free(s, a)
  96. s = nil
  97. }
  98. // Clear the backbuffer with supplied color.
  99. clear :: proc(color: Color) {
  100. rb.clear(color)
  101. }
  102. // Present the backbuffer. Call at end of frame to make everything you've drawn appear on the screen.
  103. present :: proc() {
  104. draw_current_batch()
  105. rb.present()
  106. free_all(s.frame_allocator)
  107. }
  108. // Call at start or end of frame to process all events that have arrived to the window.
  109. //
  110. // WARNING: Not calling this will make your program impossible to interact with.
  111. process_events :: proc() {
  112. s.key_went_up = {}
  113. s.key_went_down = {}
  114. s.mouse_button_went_up = {}
  115. s.mouse_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.default_font)
  209. //for &f in s.fonts {
  210. //}
  211. 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])
  212. s.vertex_buffer_cpu_used = 0
  213. }
  214. //-------//
  215. // INPUT //
  216. //-------//
  217. // Returns true if a keyboard key went down between the current and the previous frame. Set when
  218. // 'process_events' runs (probably once per frame).
  219. key_went_down :: proc(key: Keyboard_Key) -> bool {
  220. return s.key_went_down[key]
  221. }
  222. // Returns true if a keyboard key went up (was released) between the current and the previous frame.
  223. // Set when 'process_events' runs (probably once per frame).
  224. key_went_up :: proc(key: Keyboard_Key) -> bool {
  225. return s.key_went_up[key]
  226. }
  227. // Returns true if a keyboard is currently being held down. Set when 'process_events' runs (probably
  228. // once per frame).
  229. key_is_held :: proc(key: Keyboard_Key) -> bool {
  230. return s.key_is_held[key]
  231. }
  232. mouse_button_went_down :: proc(button: Mouse_Button) -> bool {
  233. return s.mouse_button_went_down[button]
  234. }
  235. mouse_button_went_up :: proc(button: Mouse_Button) -> bool {
  236. return s.mouse_button_went_up[button]
  237. }
  238. mouse_button_is_held :: proc(button: Mouse_Button) -> bool {
  239. return s.mouse_button_is_held[button]
  240. }
  241. get_mouse_wheel_delta :: proc() -> f32 {
  242. return s.mouse_wheel_delta
  243. }
  244. get_mouse_position :: proc() -> Vec2 {
  245. return s.mouse_position
  246. }
  247. gamepad_button_went_down :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  248. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  249. return false
  250. }
  251. return s.gamepad_button_went_down[gamepad][button]
  252. }
  253. gamepad_button_went_up :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  254. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  255. return false
  256. }
  257. return s.gamepad_button_went_up[gamepad][button]
  258. }
  259. gamepad_button_is_held :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
  260. if gamepad < 0 || gamepad >= MAX_GAMEPADS {
  261. return false
  262. }
  263. return s.gamepad_button_is_held[gamepad][button]
  264. }
  265. get_gamepad_axis :: proc(gamepad: Gamepad_Index, axis: Gamepad_Axis) -> f32 {
  266. return win.get_gamepad_axis(gamepad, axis)
  267. }
  268. // Set the left and right vibration motor speed. The range of left and right is 0 to 1. Note that on
  269. // most gamepads, the left motor is "low frequency" and the right motor is "high frequency". They do
  270. // not vibrate with the same speed.
  271. set_gamepad_vibration :: proc(gamepad: Gamepad_Index, left: f32, right: f32) {
  272. win.set_gamepad_vibration(gamepad, left, right)
  273. }
  274. //---------//
  275. // DRAWING //
  276. //---------//
  277. draw_rect :: proc(r: Rect, c: Color) {
  278. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  279. draw_current_batch()
  280. }
  281. if s.batch_texture != s.shape_drawing_texture {
  282. draw_current_batch()
  283. }
  284. s.batch_texture = s.shape_drawing_texture
  285. batch_vertex({r.x, r.y}, {0, 0}, c)
  286. batch_vertex({r.x + r.w, r.y}, {1, 0}, c)
  287. batch_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
  288. batch_vertex({r.x, r.y}, {0, 0}, c)
  289. batch_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
  290. batch_vertex({r.x, r.y + r.h}, {0, 1}, c)
  291. }
  292. draw_rect_vec :: proc(pos: Vec2, size: Vec2, c: Color) {
  293. draw_rect({pos.x, pos.y, size.x, size.y}, c)
  294. }
  295. draw_rect_ex :: proc(r: Rect, origin: Vec2, rot: f32, c: Color) {
  296. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  297. draw_current_batch()
  298. }
  299. if s.batch_texture != s.shape_drawing_texture {
  300. draw_current_batch()
  301. }
  302. s.batch_texture = s.shape_drawing_texture
  303. tl, tr, bl, br: Vec2
  304. // Rotation adapted from Raylib's "DrawTexturePro"
  305. if rot == 0 {
  306. x := r.x - origin.x
  307. y := r.y - origin.y
  308. tl = { x, y }
  309. tr = { x + r.w, y }
  310. bl = { x, y + r.h }
  311. br = { x + r.w, y + r.h }
  312. } else {
  313. sin_rot := math.sin(rot * math.RAD_PER_DEG)
  314. cos_rot := math.cos(rot * math.RAD_PER_DEG)
  315. x := r.x
  316. y := r.y
  317. dx := -origin.x
  318. dy := -origin.y
  319. tl = {
  320. x + dx * cos_rot - dy * sin_rot,
  321. y + dx * sin_rot + dy * cos_rot,
  322. }
  323. tr = {
  324. x + (dx + r.w) * cos_rot - dy * sin_rot,
  325. y + (dx + r.w) * sin_rot + dy * cos_rot,
  326. }
  327. bl = {
  328. x + dx * cos_rot - (dy + r.h) * sin_rot,
  329. y + dx * sin_rot + (dy + r.h) * cos_rot,
  330. }
  331. br = {
  332. x + (dx + r.w) * cos_rot - (dy + r.h) * sin_rot,
  333. y + (dx + r.w) * sin_rot + (dy + r.h) * cos_rot,
  334. }
  335. }
  336. batch_vertex(tl, {0, 0}, c)
  337. batch_vertex(tr, {1, 0}, c)
  338. batch_vertex(br, {1, 1}, c)
  339. batch_vertex(tl, {0, 0}, c)
  340. batch_vertex(br, {1, 1}, c)
  341. batch_vertex(bl, {0, 1}, c)
  342. }
  343. draw_rect_outline :: proc(r: Rect, thickness: f32, color: Color) {
  344. t := thickness
  345. // Based on DrawRectangleLinesEx from Raylib
  346. top := Rect {
  347. r.x,
  348. r.y,
  349. r.w,
  350. t,
  351. }
  352. bottom := Rect {
  353. r.x,
  354. r.y + r.h - t,
  355. r.w,
  356. t,
  357. }
  358. left := Rect {
  359. r.x,
  360. r.y + t,
  361. t,
  362. r.h - t * 2,
  363. }
  364. right := Rect {
  365. r.x + r.w - t,
  366. r.y + t,
  367. t,
  368. r.h - t * 2,
  369. }
  370. draw_rect(top, color)
  371. draw_rect(bottom, color)
  372. draw_rect(left, color)
  373. draw_rect(right, color)
  374. }
  375. draw_circle :: proc(center: Vec2, radius: f32, color: Color, segments := 16) {
  376. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 3 * segments > len(s.vertex_buffer_cpu) {
  377. draw_current_batch()
  378. }
  379. if s.batch_texture != s.shape_drawing_texture {
  380. draw_current_batch()
  381. }
  382. s.batch_texture = s.shape_drawing_texture
  383. prev := center + {radius, 0}
  384. for s in 1..=segments {
  385. sr := (f32(s)/f32(segments)) * 2*math.PI
  386. rot := linalg.matrix2_rotate(sr)
  387. p := center + rot * Vec2{radius, 0}
  388. batch_vertex(prev, {0, 0}, color)
  389. batch_vertex(p, {1, 0}, color)
  390. batch_vertex(center, {1, 1}, color)
  391. prev = p
  392. }
  393. }
  394. draw_circle_outline :: proc(center: Vec2, radius: f32, thickness: f32, color: Color, segments := 16) {
  395. prev := center + {radius, 0}
  396. for s in 1..=segments {
  397. sr := (f32(s)/f32(segments)) * 2*math.PI
  398. rot := linalg.matrix2_rotate(sr)
  399. p := center + rot * Vec2{radius, 0}
  400. draw_line(prev, p, thickness, color)
  401. prev = p
  402. }
  403. }
  404. draw_line :: proc(start: Vec2, end: Vec2, thickness: f32, color: Color) {
  405. p := Vec2{start.x, start.y + thickness*0.5}
  406. s := Vec2{linalg.length(end - start), thickness}
  407. origin := Vec2 {0, thickness*0.5}
  408. r := Rect {p.x, p.y, s.x, s.y}
  409. rot := math.atan2(end.y - start.y, end.x - start.x)
  410. draw_rect_ex(r, origin, rot * math.DEG_PER_RAD, color)
  411. }
  412. draw_texture :: proc(tex: Texture, pos: Vec2, tint := WHITE) {
  413. draw_texture_ex(
  414. tex,
  415. {0, 0, f32(tex.width), f32(tex.height)},
  416. {pos.x, pos.y, f32(tex.width), f32(tex.height)},
  417. {},
  418. 0,
  419. tint,
  420. )
  421. }
  422. draw_texture_rect :: proc(tex: Texture, rect: Rect, pos: Vec2, tint := WHITE) {
  423. draw_texture_ex(
  424. tex,
  425. rect,
  426. {pos.x, pos.y, rect.w, rect.h},
  427. {},
  428. 0,
  429. tint,
  430. )
  431. }
  432. draw_texture_ex :: proc(tex: Texture, src: Rect, dst: Rect, origin: Vec2, rotation: f32, tint := WHITE) {
  433. if tex.width == 0 || tex.height == 0 {
  434. return
  435. }
  436. if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
  437. draw_current_batch()
  438. }
  439. if s.batch_texture != tex.handle {
  440. draw_current_batch()
  441. }
  442. s.batch_texture = tex.handle
  443. flip_x, flip_y: bool
  444. src := src
  445. dst := dst
  446. if src.w < 0 {
  447. flip_x = true
  448. src.w = -src.w
  449. }
  450. if src.h < 0 {
  451. flip_y = true
  452. src.h = -src.h
  453. }
  454. if dst.w < 0 {
  455. dst.w *= -1
  456. }
  457. if dst.h < 0 {
  458. dst.h *= -1
  459. }
  460. tl, tr, bl, br: Vec2
  461. // Rotation adapted from Raylib's "DrawTexturePro"
  462. if rotation == 0 {
  463. x := dst.x - origin.x
  464. y := dst.y - origin.y
  465. tl = { x, y }
  466. tr = { x + dst.w, y }
  467. bl = { x, y + dst.h }
  468. br = { x + dst.w, y + dst.h }
  469. } else {
  470. sin_rot := math.sin(rotation * math.RAD_PER_DEG)
  471. cos_rot := math.cos(rotation * math.RAD_PER_DEG)
  472. x := dst.x
  473. y := dst.y
  474. dx := -origin.x
  475. dy := -origin.y
  476. tl = {
  477. x + dx * cos_rot - dy * sin_rot,
  478. y + dx * sin_rot + dy * cos_rot,
  479. }
  480. tr = {
  481. x + (dx + dst.w) * cos_rot - dy * sin_rot,
  482. y + (dx + dst.w) * sin_rot + dy * cos_rot,
  483. }
  484. bl = {
  485. x + dx * cos_rot - (dy + dst.h) * sin_rot,
  486. y + dx * sin_rot + (dy + dst.h) * cos_rot,
  487. }
  488. br = {
  489. x + (dx + dst.w) * cos_rot - (dy + dst.h) * sin_rot,
  490. y + (dx + dst.w) * sin_rot + (dy + dst.h) * cos_rot,
  491. }
  492. }
  493. ts := Vec2{f32(tex.width), f32(tex.height)}
  494. up := Vec2{src.x, src.y} / ts
  495. us := Vec2{src.w, src.h} / ts
  496. c := tint
  497. uv0 := up
  498. uv1 := up + {us.x, 0}
  499. uv2 := up + us
  500. uv3 := up
  501. uv4 := up + us
  502. uv5 := up + {0, us.y}
  503. if flip_x {
  504. uv0.x += us.x
  505. uv1.x -= us.x
  506. uv2.x -= us.x
  507. uv3.x += us.x
  508. uv4.x -= us.x
  509. uv5.x += us.x
  510. }
  511. if flip_y {
  512. uv0.y += us.y
  513. uv1.y += us.y
  514. uv2.y -= us.y
  515. uv3.y += us.y
  516. uv4.y -= us.y
  517. uv5.y -= us.y
  518. }
  519. batch_vertex(tl, uv0, c)
  520. batch_vertex(tr, uv1, c)
  521. batch_vertex(br, uv2, c)
  522. batch_vertex(tl, uv3, c)
  523. batch_vertex(br, uv4, c)
  524. batch_vertex(bl, uv5, c)
  525. }
  526. measure_text :: proc(text: string, font_size: f32) -> Vec2 {
  527. fs.SetSize(&s.fs, font_size)
  528. b: [4]f32
  529. fs.TextBounds(&s.fs, text, bounds = &b)
  530. return {b[2] - b[0], b[3] - b[1]}
  531. }
  532. draw_text :: proc(text: string, pos: Vec2, font_size: f32, color: Color) {
  533. //set_font(s.default_font)
  534. font := &s.fonts[s.default_font]
  535. fs.SetSize(&s.fs, font_size)
  536. iter := fs.TextIterInit(&s.fs, pos.x, pos.y+font_size/2, text)
  537. q: fs.Quad
  538. for fs.TextIterNext(&s.fs, &iter, &q) {
  539. src := Rect {
  540. q.s0, q.t0,
  541. q.s1 - q.s0, q.t1 - q.t0,
  542. }
  543. w := f32(FONT_DEFAULT_ATLAS_SIZE)
  544. h := f32(FONT_DEFAULT_ATLAS_SIZE)
  545. src.x *= w
  546. src.y *= h
  547. src.w *= w
  548. src.h *= h
  549. dst := Rect {
  550. q.x0, q.y0,
  551. q.x1 - q.x0, q.y1 - q.y0,
  552. }
  553. draw_texture_ex(font.atlas, src, dst, {}, 0, color)
  554. }
  555. /*if font_size == 0 || s.default_font.size == 0 {
  556. return
  557. }
  558. x := pos.x
  559. scl := (font_size / s.default_font.size)
  560. for t in text {
  561. if t >= FONT_MAX_CHARS {
  562. continue
  563. }
  564. chr := s.default_font.chars[int(t)]
  565. src := chr.rect
  566. dst := Rect {
  567. x = x + chr.offset.x * scl,
  568. y = pos.y + chr.offset.y * scl + font_size*0.5,
  569. w = src.w * scl,
  570. h = src.h * scl,
  571. }
  572. x += chr.xadvance * scl
  573. if t != ' ' {
  574. draw_texture_ex(s.default_font.texture, src, dst, {}, 0, color)
  575. }
  576. }*/
  577. }
  578. //--------------------//
  579. // TEXTURE MANAGEMENT //
  580. //--------------------//
  581. load_texture_from_file :: proc(filename: string) -> Texture {
  582. img, img_err := image.load_from_file(filename, options = {.alpha_add_if_missing}, allocator = s.frame_allocator)
  583. if img_err != nil {
  584. log.errorf("Error loading texture %v: %v", filename, img_err)
  585. return {}
  586. }
  587. return load_texture_from_bytes(img.pixels.buf[:], img.width, img.height, .RGBA_8_Norm)
  588. }
  589. // TODO should we have an error here or rely on check the handle of the texture?
  590. load_texture_from_bytes :: proc(bytes: []u8, width: int, height: int, format: Pixel_Format) -> Texture {
  591. backend_tex := rb.load_texture(bytes[:], width, height, format)
  592. if backend_tex == TEXTURE_NONE {
  593. return {}
  594. }
  595. return {
  596. handle = backend_tex,
  597. width = width,
  598. height = height,
  599. }
  600. }
  601. // Get a rectangle that spans the whole texture. Coordinates will be (x, y) = (0, 0) and size
  602. // (w, h) = (texture_width, texture_height)
  603. get_texture_rect :: proc(t: Texture) -> Rect {
  604. return {
  605. 0, 0,
  606. f32(t.width), f32(t.height),
  607. }
  608. }
  609. // Update a texture with new pixels. `bytes` is the new pixel data. `rect` is the rectangle in
  610. // `tex` where the new pixels should end up.
  611. update_texture :: proc(tex: Texture, bytes: []u8, rect: Rect) -> bool {
  612. return rb.update_texture(tex.handle, bytes, rect)
  613. }
  614. destroy_texture :: proc(tex: Texture) {
  615. rb.destroy_texture(tex.handle)
  616. }
  617. //---------//
  618. // SHADERS //
  619. //---------//
  620. load_shader :: proc(shader_source: string, layout_formats: []Pixel_Format = {}) -> Shader {
  621. handle, desc := rb.load_shader(shader_source, s.frame_allocator, layout_formats)
  622. if handle == SHADER_NONE {
  623. log.error("Failed loading shader")
  624. return {}
  625. }
  626. shd := Shader {
  627. handle = handle,
  628. constant_buffers = make([]Shader_Constant_Buffer, len(desc.constant_buffers), s.allocator),
  629. constant_lookup = make(map[string]Shader_Constant_Location, s.allocator),
  630. inputs = slice.clone(desc.inputs, s.allocator),
  631. input_overrides = make([]Shader_Input_Value_Override, len(desc.inputs), s.allocator),
  632. }
  633. for &input in shd.inputs {
  634. input.name = strings.clone(input.name, s.allocator)
  635. }
  636. for cb_idx in 0..<len(desc.constant_buffers) {
  637. cb_desc := &desc.constant_buffers[cb_idx]
  638. shd.constant_buffers[cb_idx] = {
  639. cpu_data = make([]u8, desc.constant_buffers[cb_idx].size, s.allocator),
  640. }
  641. for &v in cb_desc.variables {
  642. if v.name == "" {
  643. continue
  644. }
  645. shd.constant_lookup[strings.clone(v.name, s.allocator)] = v.loc
  646. switch v.name {
  647. case "mvp":
  648. shd.constant_builtin_locations[.MVP] = v.loc
  649. }
  650. }
  651. }
  652. for &d in shd.default_input_offsets {
  653. d = -1
  654. }
  655. input_offset: int
  656. for &input in shd.inputs {
  657. default_format := get_shader_input_default_type(input.name, input.type)
  658. if default_format != .Unknown {
  659. shd.default_input_offsets[default_format] = input_offset
  660. }
  661. input_offset += pixel_format_size(input.format)
  662. }
  663. shd.vertex_size = input_offset
  664. return shd
  665. }
  666. destroy_shader :: proc(shader: Shader) {
  667. rb.destroy_shader(shader.handle)
  668. for c in shader.constant_buffers {
  669. delete(c.cpu_data)
  670. }
  671. delete(shader.constant_buffers)
  672. for k, _ in shader.constant_lookup {
  673. delete(k)
  674. }
  675. delete(shader.constant_lookup)
  676. for i in shader.inputs {
  677. delete(i.name)
  678. }
  679. delete(shader.inputs)
  680. delete(shader.input_overrides)
  681. }
  682. get_default_shader :: proc() -> Shader {
  683. return s.default_shader
  684. }
  685. set_shader :: proc(shader: Maybe(Shader)) {
  686. if shd, shd_ok := shader.?; shd_ok {
  687. if shd.handle == s.batch_shader.handle {
  688. return
  689. }
  690. } else {
  691. if s.batch_shader.handle == s.default_shader.handle {
  692. return
  693. }
  694. }
  695. draw_current_batch()
  696. s.batch_shader = shader.? or_else s.default_shader
  697. }
  698. set_shader_constant :: proc(shd: Shader, loc: Shader_Constant_Location, val: any) {
  699. draw_current_batch()
  700. if int(loc.buffer_idx) >= len(shd.constant_buffers) {
  701. log.warnf("Constant buffer idx %v is out of bounds", loc.buffer_idx)
  702. return
  703. }
  704. sz := reflect.size_of_typeid(val.id)
  705. b := &shd.constant_buffers[loc.buffer_idx]
  706. if int(loc.offset) + sz > len(b.cpu_data) {
  707. 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))
  708. return
  709. }
  710. mem.copy(&b.cpu_data[loc.offset], val.data, sz)
  711. }
  712. override_shader_input :: proc(shader: Shader, input: int, val: any) {
  713. sz := reflect.size_of_typeid(val.id)
  714. assert(sz < SHADER_INPUT_VALUE_MAX_SIZE)
  715. if input >= len(shader.input_overrides) {
  716. log.errorf("Input override out of range. Wanted to override input %v, but shader only has %v inputs", input, len(shader.input_overrides))
  717. return
  718. }
  719. o := &shader.input_overrides[input]
  720. o.val = {}
  721. if sz > 0 {
  722. mem.copy(raw_data(&o.val), val.data, sz)
  723. }
  724. o.used = sz
  725. }
  726. pixel_format_size :: proc(f: Pixel_Format) -> int {
  727. switch f {
  728. case .Unknown: return 0
  729. case .RGBA_32_Float: return 32
  730. case .RGB_32_Float: return 12
  731. case .RG_32_Float: return 8
  732. case .R_32_Float: return 4
  733. case .RGBA_8_Norm: return 4
  734. case .RG_8_Norm: return 2
  735. case .R_8_Norm: return 1
  736. case .R_8_UInt: return 1
  737. }
  738. return 0
  739. }
  740. //-------------------------------//
  741. // CAMERA AND COORDINATE SYSTEMS //
  742. //-------------------------------//
  743. set_camera :: proc(camera: Maybe(Camera)) {
  744. if camera == s.batch_camera {
  745. return
  746. }
  747. draw_current_batch()
  748. s.batch_camera = camera
  749. s.proj_matrix = make_default_projection(s.width, s.height)
  750. if c, c_ok := camera.?; c_ok {
  751. s.view_matrix = get_camera_view_matrix(c)
  752. } else {
  753. s.view_matrix = 1
  754. }
  755. }
  756. screen_to_world :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  757. return (get_camera_world_matrix(camera) * Vec4 { pos.x, pos.y, 0, 1 }).xy
  758. }
  759. world_to_screen :: proc(pos: Vec2, camera: Camera) -> Vec2 {
  760. return (get_camera_view_matrix(camera) * Vec4 { pos.x, pos.y, 0, 1 }).xy
  761. }
  762. get_camera_view_matrix :: proc(c: Camera) -> Mat4 {
  763. inv_target_translate := linalg.matrix4_translate(vec3_from_vec2(-c.target))
  764. inv_rot := linalg.matrix4_rotate_f32(c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  765. inv_scale := linalg.matrix4_scale(Vec3{c.zoom, c.zoom, 1})
  766. inv_offset_translate := linalg.matrix4_translate(vec3_from_vec2(c.offset))
  767. // A view matrix is essentially the world transform matrix of the camera, but inverted. We
  768. // bring everything in the world "in front of the camera".
  769. //
  770. // Instead of constructing the camera matrix and doing a matrix inverse, here we just do the
  771. // maths in "backwards order". I.e. a camera transform matrix would be:
  772. //
  773. // target_translate * rot * scale * offset_translate
  774. return inv_offset_translate * inv_scale * inv_rot * inv_target_translate
  775. }
  776. get_camera_world_matrix :: proc(c: Camera) -> Mat4 {
  777. offset_translate := linalg.matrix4_translate(vec3_from_vec2(-c.offset))
  778. rot := linalg.matrix4_rotate_f32(-c.rotation * math.RAD_PER_DEG, {0, 0, 1})
  779. scale := linalg.matrix4_scale(Vec3{1/c.zoom, 1/c.zoom, 1})
  780. target_translate := linalg.matrix4_translate(vec3_from_vec2(c.target))
  781. return target_translate * rot * scale * offset_translate
  782. }
  783. //------//
  784. // MISC //
  785. //------//
  786. set_scissor_rect :: proc(scissor_rect: Maybe(Rect)) {
  787. draw_current_batch()
  788. s.batch_scissor = scissor_rect
  789. }
  790. // Restore the internal state using the pointer returned by `init`. Useful after reloading the
  791. // library (for example, when doing code hot reload).
  792. set_internal_state :: proc(state: ^State) {
  793. s = state
  794. rb = s.rb
  795. win = s.win
  796. rb.set_internal_state(s.rb_state)
  797. win.set_internal_state(s.window_state)
  798. }
  799. //---------------------//
  800. // TYPES AND CONSTANTS //
  801. //---------------------//
  802. Vec2 :: [2]f32
  803. Vec3 :: [3]f32
  804. Vec4 :: [4]f32
  805. Mat4 :: matrix[4,4]f32
  806. // A two dimensional vector of integer numeric type.
  807. Vec2i :: [2]int
  808. // A rectangle that sits at position (x, y) and has size (w, h).
  809. Rect :: struct {
  810. x, y: f32,
  811. w, h: f32,
  812. }
  813. // An RGBA (Red, Green, Blue, Alpha) color. Each channel can have a value between 0 and 255.
  814. Color :: [4]u8
  815. WHITE :: Color { 255, 255, 255, 255 }
  816. BLACK :: Color { 0, 0, 0, 255 }
  817. GRAY :: Color { 127, 127, 127, 255 }
  818. RED :: Color { 198, 80, 90, 255 }
  819. BLANK :: Color { 0, 0, 0, 0 }
  820. BLUE :: Color { 30, 116, 240, 255 }
  821. // These are from Raylib. They are here so you can easily port a Raylib program to Karl2D.
  822. RL_LIGHTGRAY :: Color { 200, 200, 200, 255 }
  823. RL_GRAY :: Color { 130, 130, 130, 255 }
  824. RL_DARKGRAY :: Color { 80, 80, 80, 255 }
  825. RL_YELLOW :: Color { 253, 249, 0, 255 }
  826. RL_GOLD :: Color { 255, 203, 0, 255 }
  827. RL_ORANGE :: Color { 255, 161, 0, 255 }
  828. RL_PINK :: Color { 255, 109, 194, 255 }
  829. RL_RED :: Color { 230, 41, 55, 255 }
  830. RL_MAROON :: Color { 190, 33, 55, 255 }
  831. RL_GREEN :: Color { 0, 228, 48, 255 }
  832. RL_LIME :: Color { 0, 158, 47, 255 }
  833. RL_DARKGREEN :: Color { 0, 117, 44, 255 }
  834. RL_SKYBLUE :: Color { 102, 191, 255, 255 }
  835. RL_BLUE :: Color { 0, 121, 241, 255 }
  836. RL_DARKBLUE :: Color { 0, 82, 172, 255 }
  837. RL_PURPLE :: Color { 200, 122, 255, 255 }
  838. RL_VIOLET :: Color { 135, 60, 190, 255 }
  839. RL_DARKPURPLE :: Color { 112, 31, 126, 255 }
  840. RL_BEIGE :: Color { 211, 176, 131, 255 }
  841. RL_BROWN :: Color { 127, 106, 79, 255 }
  842. RL_DARKBROWN :: Color { 76, 63, 47, 255 }
  843. RL_WHITE :: WHITE
  844. RL_BLACK :: BLACK
  845. RL_BLANK :: BLANK
  846. RL_MAGENTA :: Color { 255, 0, 255, 255 }
  847. RL_RAYWHITE :: Color { 245, 245, 245, 255 }
  848. Texture :: struct {
  849. handle: Texture_Handle,
  850. width: int,
  851. height: int,
  852. }
  853. Camera :: struct {
  854. target: Vec2,
  855. offset: Vec2,
  856. rotation: f32,
  857. zoom: f32,
  858. }
  859. Window_Flag :: enum {
  860. Resizable,
  861. }
  862. Window_Flags :: bit_set[Window_Flag]
  863. Shader_Handle :: distinct Handle
  864. SHADER_NONE :: Shader_Handle {}
  865. Shader :: struct {
  866. handle: Shader_Handle,
  867. constant_buffers: []Shader_Constant_Buffer,
  868. constant_lookup: map[string]Shader_Constant_Location,
  869. constant_builtin_locations: [Shader_Builtin_Constant]Maybe(Shader_Constant_Location),
  870. inputs: []Shader_Input,
  871. input_overrides: []Shader_Input_Value_Override,
  872. default_input_offsets: [Shader_Default_Inputs]int,
  873. vertex_size: int,
  874. }
  875. Shader_Constant_Buffer :: struct {
  876. cpu_data: []u8,
  877. }
  878. SHADER_INPUT_VALUE_MAX_SIZE :: 256
  879. Shader_Input_Value_Override :: struct {
  880. val: [SHADER_INPUT_VALUE_MAX_SIZE]u8,
  881. used: int,
  882. }
  883. Shader_Input_Type :: enum {
  884. F32,
  885. Vec2,
  886. Vec3,
  887. Vec4,
  888. }
  889. Shader_Builtin_Constant :: enum {
  890. MVP,
  891. }
  892. Shader_Default_Inputs :: enum {
  893. Unknown,
  894. Position,
  895. UV,
  896. Color,
  897. }
  898. Shader_Input :: struct {
  899. name: string,
  900. register: int,
  901. type: Shader_Input_Type,
  902. format: Pixel_Format,
  903. }
  904. Shader_Constant_Location :: struct {
  905. buffer_idx: u32,
  906. offset: u32,
  907. }
  908. Pixel_Format :: enum {
  909. Unknown,
  910. RGBA_32_Float,
  911. RGB_32_Float,
  912. RG_32_Float,
  913. R_32_Float,
  914. RGBA_8_Norm,
  915. RG_8_Norm,
  916. R_8_Norm,
  917. R_8_UInt,
  918. }
  919. Font :: struct {
  920. atlas: Texture,
  921. // internal
  922. fontstash_handle: int,
  923. }
  924. Handle :: hm.Handle
  925. Texture_Handle :: distinct Handle
  926. Font_Handle :: distinct int
  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: Maybe(Font),
  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(font: Font) {
  1235. if s.batch_font == font {
  1236. return
  1237. }
  1238. }
  1239. /*Load_Font_Error :: enum {
  1240. OK,
  1241. Load_File_Failed,
  1242. Bitmap_Bake_Failed,
  1243. Load_Texture_Failed,
  1244. }
  1245. // wip procedure
  1246. load_default_font :: proc() -> (Font, Load_Font_Error) {
  1247. font_data := ROBOTO_FONT_DATA
  1248. PW :: 2048
  1249. PH :: 2048
  1250. SIZE :: 64
  1251. pixels := make([]u8, PW*PH, frame_allocator)
  1252. baked_chars := make([]tt.bakedchar, FONT_MAX_CHARS, frame_allocator)
  1253. bake_res := tt.BakeFontBitmap(raw_data(font_data), 0, SIZE, raw_data(pixels), PW, PH, 0, FONT_MAX_CHARS, raw_data(baked_chars))
  1254. if bake_res == 0 {
  1255. return {}, .Bitmap_Bake_Failed
  1256. }
  1257. expanded_pixels := make([]Color, PW*PH, frame_allocator)
  1258. for p, i in pixels {
  1259. expanded_pixels[i] = {255,255,255,p}
  1260. }
  1261. tex := load_texture_from_bytes(slice.reinterpret([]u8, expanded_pixels), PW, PH, .RGBA_8_Norm)
  1262. if tex.handle == TEXTURE_NONE {
  1263. return {}, .Load_Texture_Failed
  1264. }
  1265. chars := make([]Font_Char, FONT_MAX_CHARS, s.allocator)
  1266. for i in 0..<FONT_MAX_CHARS {
  1267. b := baked_chars[i]
  1268. chars[i] = {
  1269. rect = {
  1270. x = f32(b.x0),
  1271. y = f32(b.y0),
  1272. w = f32(b.x1 - b.x0),
  1273. h = f32(b.y1 - b.y0),
  1274. },
  1275. offset = {
  1276. f32(b.xoff), f32(b.yoff),
  1277. },
  1278. xadvance = f32(b.xadvance),
  1279. r = rune(i),
  1280. }
  1281. }
  1282. return {
  1283. texture = tex,
  1284. chars = chars,
  1285. size = SIZE,
  1286. }, .OK
  1287. }*/
  1288. _ :: jpeg
  1289. _ :: bmp
  1290. _ :: png
  1291. _ :: tga