karl2d.odin 27 KB

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