karl2d.odin 35 KB

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