karl2d.odin 32 KB

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