karl2d.odin 27 KB

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