karl2d.odin 29 KB

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