karl2d.odin 37 KB

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