karl2d.odin 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  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.batch_scissor, 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. draw_current_batch()
  609. s.batch_scissor = scissor_rect
  610. }
  611. // Restore the internal state using the pointer returned by `init`. Useful after reloading the
  612. // library (for example, when doing code hot reload).
  613. set_internal_state :: proc(state: ^State) {
  614. s = state
  615. rb = s.rb
  616. win = s.win
  617. rb.set_internal_state(s.rb_state)
  618. win.set_internal_state(s.window_state)
  619. }
  620. //---------------------//
  621. // TYPES AND CONSTANTS //
  622. //---------------------//
  623. Vec2 :: [2]f32
  624. Vec3 :: [3]f32
  625. Vec4 :: [4]f32
  626. Mat4 :: matrix[4,4]f32
  627. // A two dimensional vector of integer numeric type.
  628. Vec2i :: [2]int
  629. // A rectangle that sits at position (x, y) and has size (w, h).
  630. Rect :: struct {
  631. x, y: f32,
  632. w, h: f32,
  633. }
  634. // An RGBA (Red, Green, Blue, Alpha) color. Each channel can have a value between 0 and 255.
  635. Color :: [4]u8
  636. WHITE :: Color { 255, 255, 255, 255 }
  637. BLACK :: Color { 0, 0, 0, 255 }
  638. BLANK :: Color { 0, 0, 0, 0 }
  639. BLUE :: Color { 30, 116, 240, 255 }
  640. // These are from Raylib. They are here so you can easily port a Raylib program to Karl2D.
  641. RL_LIGHTGRAY :: Color { 200, 200, 200, 255 }
  642. RL_GRAY :: Color { 130, 130, 130, 255 }
  643. RL_DARKGRAY :: Color { 80, 80, 80, 255 }
  644. RL_YELLOW :: Color { 253, 249, 0, 255 }
  645. RL_GOLD :: Color { 255, 203, 0, 255 }
  646. RL_ORANGE :: Color { 255, 161, 0, 255 }
  647. RL_PINK :: Color { 255, 109, 194, 255 }
  648. RL_RED :: Color { 230, 41, 55, 255 }
  649. RL_MAROON :: Color { 190, 33, 55, 255 }
  650. RL_GREEN :: Color { 0, 228, 48, 255 }
  651. RL_LIME :: Color { 0, 158, 47, 255 }
  652. RL_DARKGREEN :: Color { 0, 117, 44, 255 }
  653. RL_SKYBLUE :: Color { 102, 191, 255, 255 }
  654. RL_BLUE :: Color { 0, 121, 241, 255 }
  655. RL_DARKBLUE :: Color { 0, 82, 172, 255 }
  656. RL_PURPLE :: Color { 200, 122, 255, 255 }
  657. RL_VIOLET :: Color { 135, 60, 190, 255 }
  658. RL_DARKPURPLE :: Color { 112, 31, 126, 255 }
  659. RL_BEIGE :: Color { 211, 176, 131, 255 }
  660. RL_BROWN :: Color { 127, 106, 79, 255 }
  661. RL_DARKBROWN :: Color { 76, 63, 47, 255 }
  662. RL_WHITE :: WHITE
  663. RL_BLACK :: BLACK
  664. RL_BLANK :: BLANK
  665. RL_MAGENTA :: Color { 255, 0, 255, 255 }
  666. RL_RAYWHITE :: Color { 245, 245, 245, 255 }
  667. Texture :: struct {
  668. handle: Texture_Handle,
  669. width: int,
  670. height: int,
  671. }
  672. Camera :: struct {
  673. target: Vec2,
  674. offset: Vec2,
  675. rotation: f32,
  676. zoom: f32,
  677. }
  678. Shader_Handle :: distinct Handle
  679. SHADER_NONE :: Shader_Handle {}
  680. Shader :: struct {
  681. handle: Shader_Handle,
  682. constant_buffers: []Shader_Constant_Buffer,
  683. constant_lookup: map[string]Shader_Constant_Location,
  684. constant_builtin_locations: [Shader_Builtin_Constant]Maybe(Shader_Constant_Location),
  685. inputs: []Shader_Input,
  686. input_overrides: []Shader_Input_Value_Override,
  687. default_input_offsets: [Shader_Default_Inputs]int,
  688. vertex_size: int,
  689. }
  690. Shader_Constant_Buffer :: struct {
  691. cpu_data: []u8,
  692. }
  693. SHADER_INPUT_VALUE_MAX_SIZE :: 256
  694. Shader_Input_Value_Override :: struct {
  695. val: [SHADER_INPUT_VALUE_MAX_SIZE]u8,
  696. used: int,
  697. }
  698. Shader_Input_Type :: enum {
  699. F32,
  700. Vec2,
  701. Vec3,
  702. Vec4,
  703. }
  704. Shader_Builtin_Constant :: enum {
  705. MVP,
  706. }
  707. Shader_Default_Inputs :: enum {
  708. Unknown,
  709. Position,
  710. UV,
  711. Color,
  712. }
  713. Shader_Input :: struct {
  714. name: string,
  715. register: int,
  716. type: Shader_Input_Type,
  717. format: Shader_Input_Format,
  718. }
  719. Shader_Constant_Location :: struct {
  720. buffer_idx: u32,
  721. offset: u32,
  722. }
  723. Shader_Input_Format :: enum {
  724. Unknown,
  725. RGBA32_Float,
  726. RGBA8_Norm,
  727. RGBA8_Norm_SRGB,
  728. RGB32_Float,
  729. RG32_Float,
  730. R32_Float,
  731. }
  732. Handle :: hm.Handle
  733. Texture_Handle :: distinct Handle
  734. TEXTURE_NONE :: Texture_Handle {}
  735. // This keeps track of the internal state of the library. Usually, you do not need to poke at it.
  736. // It is created and kept as a global variable when 'init' is called. However, 'init' also returns
  737. // the pointer to it, so you can later use 'set_internal_state' to restore it (after for example hot
  738. // reload).
  739. State :: struct {
  740. allocator: runtime.Allocator,
  741. custom_context: runtime.Context,
  742. win: Window_Interface,
  743. window_state: rawptr,
  744. rb: Render_Backend_Interface,
  745. rb_state: rawptr,
  746. shutdown_wanted: bool,
  747. mouse_position: Vec2,
  748. mouse_delta: Vec2,
  749. mouse_wheel_delta: f32,
  750. keys_went_down: #sparse [Keyboard_Key]bool,
  751. keys_went_up: #sparse [Keyboard_Key]bool,
  752. keys_is_held: #sparse [Keyboard_Key]bool,
  753. mouse_button_went_down: #sparse [Mouse_Button]bool,
  754. mouse_button_went_up: #sparse [Mouse_Button]bool,
  755. mouse_button_is_held: #sparse [Mouse_Button]bool,
  756. window: Window_Handle,
  757. width: int,
  758. height: int,
  759. shape_drawing_texture: Texture_Handle,
  760. batch_camera: Maybe(Camera),
  761. batch_shader: Maybe(Shader),
  762. batch_scissor: Maybe(Rect),
  763. batch_texture: Texture_Handle,
  764. view_matrix: Mat4,
  765. proj_matrix: Mat4,
  766. vertex_buffer_cpu: []u8,
  767. vertex_buffer_cpu_used: int,
  768. default_shader: Shader,
  769. }
  770. // Support for up to 255 mouse buttons. Cast an int to type `Mouse_Button` to use things outside the
  771. // options presented here.
  772. Mouse_Button :: enum {
  773. Left,
  774. Right,
  775. Middle,
  776. Max = 255,
  777. }
  778. // Based on Raylib / GLFW
  779. Keyboard_Key :: enum {
  780. None = 0,
  781. // Alphanumeric keys
  782. Apostrophe = 39,
  783. Comma = 44,
  784. Minus = 45,
  785. Period = 46,
  786. Slash = 47,
  787. Zero = 48,
  788. One = 49,
  789. Two = 50,
  790. Three = 51,
  791. Four = 52,
  792. Five = 53,
  793. Six = 54,
  794. Seven = 55,
  795. Eight = 56,
  796. Nine = 57,
  797. Semicolon = 59,
  798. Equal = 61,
  799. A = 65,
  800. B = 66,
  801. C = 67,
  802. D = 68,
  803. E = 69,
  804. F = 70,
  805. G = 71,
  806. H = 72,
  807. I = 73,
  808. J = 74,
  809. K = 75,
  810. L = 76,
  811. M = 77,
  812. N = 78,
  813. O = 79,
  814. P = 80,
  815. Q = 81,
  816. R = 82,
  817. S = 83,
  818. T = 84,
  819. U = 85,
  820. V = 86,
  821. W = 87,
  822. X = 88,
  823. Y = 89,
  824. Z = 90,
  825. Left_Bracket = 91,
  826. Backslash = 92,
  827. Right_Bracket = 93,
  828. Grave = 96,
  829. // Function keys
  830. Space = 32,
  831. Escape = 256,
  832. Enter = 257,
  833. Tab = 258,
  834. Backspace = 259,
  835. Insert = 260,
  836. Delete = 261,
  837. Right = 262,
  838. Left = 263,
  839. Down = 264,
  840. Up = 265,
  841. Page_Up = 266,
  842. Page_Down = 267,
  843. Home = 268,
  844. End = 269,
  845. Caps_Lock = 280,
  846. Scroll_Lock = 281,
  847. Num_Lock = 282,
  848. Print_Screen = 283,
  849. Pause = 284,
  850. F1 = 290,
  851. F2 = 291,
  852. F3 = 292,
  853. F4 = 293,
  854. F5 = 294,
  855. F6 = 295,
  856. F7 = 296,
  857. F8 = 297,
  858. F9 = 298,
  859. F10 = 299,
  860. F11 = 300,
  861. F12 = 301,
  862. Left_Shift = 340,
  863. Left_Control = 341,
  864. Left_Alt = 342,
  865. Left_Super = 343,
  866. Right_Shift = 344,
  867. Right_Control = 345,
  868. Right_Alt = 346,
  869. Right_Super = 347,
  870. Menu = 348,
  871. // Keypad keys
  872. KP_0 = 320,
  873. KP_1 = 321,
  874. KP_2 = 322,
  875. KP_3 = 323,
  876. KP_4 = 324,
  877. KP_5 = 325,
  878. KP_6 = 326,
  879. KP_7 = 327,
  880. KP_8 = 328,
  881. KP_9 = 329,
  882. KP_Decimal = 330,
  883. KP_Divide = 331,
  884. KP_Multiply = 332,
  885. KP_Subtract = 333,
  886. KP_Add = 334,
  887. KP_Enter = 335,
  888. KP_Equal = 336,
  889. }
  890. // Used by API builder. Everything after this constant will not be in karl2d.doc.odin
  891. API_END :: true
  892. batch_vertex :: proc(v: Vec2, uv: Vec2, color: Color) {
  893. v := v
  894. if s.vertex_buffer_cpu_used == len(s.vertex_buffer_cpu) {
  895. panic("Must dispatch here")
  896. }
  897. shd := s.batch_shader.? or_else s.default_shader
  898. base_offset := s.vertex_buffer_cpu_used
  899. pos_offset := shd.default_input_offsets[.Position]
  900. uv_offset := shd.default_input_offsets[.UV]
  901. color_offset := shd.default_input_offsets[.Color]
  902. mem.set(&s.vertex_buffer_cpu[base_offset], 0, shd.vertex_size)
  903. if pos_offset != -1 {
  904. (^Vec2)(&s.vertex_buffer_cpu[base_offset + pos_offset])^ = {v.x, v.y}
  905. }
  906. if uv_offset != -1 {
  907. (^Vec2)(&s.vertex_buffer_cpu[base_offset + uv_offset])^ = uv
  908. }
  909. if color_offset != -1 {
  910. (^Color)(&s.vertex_buffer_cpu[base_offset + color_offset])^ = color
  911. }
  912. override_offset: int
  913. for &o, idx in shd.input_overrides {
  914. input := &shd.inputs[idx]
  915. sz := shader_input_format_size(input.format)
  916. if o.used != 0 {
  917. mem.copy(&s.vertex_buffer_cpu[base_offset + override_offset], raw_data(&o.val), o.used)
  918. }
  919. override_offset += sz
  920. }
  921. s.vertex_buffer_cpu_used += shd.vertex_size
  922. }
  923. VERTEX_BUFFER_MAX :: 1000000
  924. DEFAULT_SHADER_SOURCE :: #load("shader.hlsl")
  925. @(private="file")
  926. s: ^State
  927. win: Window_Interface
  928. rb: Render_Backend_Interface
  929. maybe_handle_equal :: proc(m1: Maybe($T), m2: Maybe(T)) -> bool {
  930. if m1 == nil && m2 == nil {
  931. return true
  932. }
  933. m1v, m1v_ok := m1.?
  934. m2v, m2v_ok := m2.?
  935. if !m1v_ok || !m2v_ok {
  936. return false
  937. }
  938. return m1v.handle == m2v.handle
  939. }
  940. get_shader_input_default_type :: proc(name: string, type: Shader_Input_Type) -> Shader_Default_Inputs {
  941. if name == "POS" && type == .Vec2 {
  942. return .Position
  943. } else if name == "UV" && type == .Vec2 {
  944. return .UV
  945. } else if name == "COL" && type == .Vec4 {
  946. return .Color
  947. }
  948. return .Unknown
  949. }
  950. get_shader_input_format :: proc(name: string, type: Shader_Input_Type) -> Shader_Input_Format {
  951. default_type := get_shader_input_default_type(name, type)
  952. if default_type != .Unknown {
  953. switch default_type {
  954. case .Position: return .RG32_Float
  955. case .UV: return .RG32_Float
  956. case .Color: return .RGBA8_Norm
  957. case .Unknown: unreachable()
  958. }
  959. }
  960. switch type {
  961. case .F32: return .R32_Float
  962. case .Vec2: return .RG32_Float
  963. case .Vec3: return .RGB32_Float
  964. case .Vec4: return .RGBA32_Float
  965. }
  966. return .Unknown
  967. }
  968. vec3_from_vec2 :: proc(v: Vec2) -> Vec3 {
  969. return {
  970. v.x, v.y, 0,
  971. }
  972. }
  973. temp_cstring :: proc(str: string, loc := #caller_location) -> cstring {
  974. return strings.clone_to_cstring(str, context.temp_allocator, loc)
  975. }
  976. make_default_projection :: proc(w, h: int) -> matrix[4,4]f32 {
  977. return linalg.matrix_ortho3d_f32(0, f32(w), f32(h), 0, 0.001, 2)
  978. }
  979. _ :: bmp
  980. _ :: png
  981. _ :: tga