karl2d.odin 32 KB

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