karl2d.odin 32 KB

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