yog_gfx/lib.rs
1//! Yog graphics — low-level GPU pipeline access for mods.
2//!
3//! Provides ergonomic wrappers around `YogGfxApi`, the stable C ABI table for
4//! GPU operations (VAO/VBO, GLSL shaders, textures, draw calls, render state).
5//!
6//! # Render contexts
7//!
8//! Mods receive a [`GfxContext`] in two places:
9//!
10//! - `on_hud_render(|ctx| { ... })` — called every frame after the HUD is drawn.
11//! `ctx.view_proj()` is zeroed; `ctx.draw2d()` works.
12//! - `on_world_render(|ctx| { ... })` — called after world geometry.
13//! `ctx.view_proj()` holds the camera view-projection matrix in camera-relative
14//! space; `ctx.camera_pos()` is the world-space camera position.
15//!
16//! # GPU resource lifetime
17//!
18//! GPU handles (`u32`) must be created and destroyed on the render thread.
19//! Store handles between frames; pass `ctx` on every render call.
20//!
21//! ```ignore
22//! use yog_gfx::{GfxContext, gl::{Buffer, ShaderProgram, VertexArray}};
23//!
24//! struct MyRenderer {
25//! vbo: Option<Buffer>,
26//! vao: Option<VertexArray>,
27//! prog: Option<ShaderProgram>,
28//! }
29//!
30//! impl MyRenderer {
31//! fn ensure_init(&mut self, ctx: &GfxContext) {
32//! if self.vbo.is_some() { return; }
33//! let vbo = ctx.create_buffer();
34//! vbo.upload(ctx, &MY_VERTICES, false);
35//! let prog = ctx.create_shader(VERT_SRC, FRAG_SRC).unwrap();
36//! let vao = ctx.create_vao();
37//! vao.attrib(ctx, &vbo, 0, 3, yog_gfx::core::DataType::F32, false, 24, 0);
38//! self.vbo = Some(vbo);
39//! self.vao = Some(vao);
40//! self.prog = Some(prog);
41//! }
42//!
43//! fn render(&mut self, ctx: &GfxContext) {
44//! self.ensure_init(ctx);
45//! let vao = self.vao.as_ref().unwrap();
46//! let prog = self.prog.as_ref().unwrap();
47//! prog.uniform_mat4(ctx, "uViewProj", &ctx.view_proj());
48//! ctx.draw_arrays(vao, prog, yog_gfx::core::DrawMode::Triangles, 0, 3);
49//! }
50//! }
51//! ```
52
53pub mod core;
54pub mod draw2d;
55pub mod gl;
56
57use yog_abi::YogGfxApi;
58
59/// Handle to the GPU and draw capabilities for a single render frame.
60///
61/// Valid only within an `on_hud_render` or `on_world_render` callback.
62/// Do **not** store across frames — store GPU resource handles (`u32`) instead.
63#[derive(Copy, Clone)]
64pub struct GfxContext(*const YogGfxApi);
65
66unsafe impl Send for GfxContext {}
67unsafe impl Sync for GfxContext {}
68
69impl GfxContext {
70 #[doc(hidden)]
71 pub unsafe fn from_raw(raw: *const YogGfxApi) -> Self {
72 Self(raw)
73 }
74
75 #[inline]
76 fn api(&self) -> &YogGfxApi {
77 unsafe { &*self.0 }
78 }
79
80 // ── Frame info ────────────────────────────────────────────────────────────
81
82 /// GUI pixel dimensions of the screen for this frame.
83 pub fn screen_size(&self) -> (i32, i32) {
84 let a = self.api();
85 (a.screen_w, a.screen_h)
86 }
87
88 /// Partial-tick interpolation factor (0.0–1.0).
89 pub fn delta_tick(&self) -> f32 {
90 self.api().delta_tick
91 }
92
93 /// View-projection matrix in camera-relative space (column-major, 16 × f32).
94 /// Zeros during `on_hud_render`; filled during `on_world_render`.
95 pub fn view_proj(&self) -> [f32; 16] {
96 self.api().view_proj
97 }
98
99 /// Camera world-space position. All zeros during `on_hud_render`.
100 pub fn camera_pos(&self) -> [f32; 3] {
101 self.api().camera_pos
102 }
103
104 /// Local player world-space position (eye height). All zeros during `on_hud_render`.
105 /// Use this to anchor geometry to the player; differs from `camera_pos` in third-person.
106 pub fn player_pos(&self) -> [f32; 3] {
107 self.api().player_pos
108 }
109
110 // ── GPU buffer ───────────────────────────────────────────────────────────
111
112 /// Allocate a new GPU buffer (VBO or EBO). Returns handle 0 on failure.
113 pub fn create_buffer(&self) -> gl::Buffer {
114 gl::Buffer {
115 handle: unsafe { (self.api().buf_create)() },
116 }
117 }
118
119 /// Delete a buffer allocated by `create_buffer`.
120 pub fn delete_buffer(&self, buf: gl::Buffer) {
121 unsafe { (self.api().buf_delete)(buf.handle) }
122 }
123
124 // ── Vertex array ─────────────────────────────────────────────────────────
125
126 /// Allocate a new vertex array object. Returns handle 0 on failure.
127 pub fn create_vao(&self) -> gl::VertexArray {
128 gl::VertexArray {
129 handle: unsafe { (self.api().vao_create)() },
130 }
131 }
132
133 /// Delete a vertex array allocated by `create_vao`.
134 pub fn delete_vao(&self, vao: gl::VertexArray) {
135 unsafe { (self.api().vao_delete)(vao.handle) }
136 }
137
138 // ── Shader program ────────────────────────────────────────────────────────
139
140 /// Compile and link a GLSL shader program.
141 /// Returns `Err(())` and logs on compile/link failure.
142 pub fn create_shader(&self, vert_src: &str, frag_src: &str) -> Result<gl::ShaderProgram, ()> {
143 use yog_abi::YogStr;
144 let mut handle = 0u32;
145 let ok = unsafe {
146 (self.api().prog_create)(
147 YogStr::from_str(vert_src),
148 YogStr::from_str(frag_src),
149 &mut handle,
150 )
151 };
152 if ok && handle != 0 {
153 Ok(gl::ShaderProgram { handle })
154 } else {
155 Err(())
156 }
157 }
158
159 /// Delete a shader program.
160 pub fn delete_shader(&self, prog: gl::ShaderProgram) {
161 unsafe { (self.api().prog_delete)(prog.handle) }
162 }
163
164 // ── Texture ───────────────────────────────────────────────────────────────
165
166 /// Upload RGBA8 pixel data as a new GPU texture.
167 /// `linear`: `true` = bilinear filter, `false` = nearest.
168 pub fn create_texture_rgba(&self, w: u32, h: u32, pixels: &[u8], linear: bool) -> gl::Texture {
169 gl::Texture {
170 handle: unsafe { (self.api().tex_create)(w, h, pixels.as_ptr(), linear) },
171 }
172 }
173
174 /// Get the GL texture handle that Minecraft uses for an identifier
175 /// (e.g. `"minecraft:textures/gui/icons.png"`). Returns handle 0 if not found.
176 pub fn texture_from_mc(&self, id: &str) -> gl::Texture {
177 use yog_abi::YogStr;
178 gl::Texture {
179 handle: unsafe { (self.api().tex_from_mc)(YogStr::from_str(id)) },
180 }
181 }
182
183 /// Delete a texture.
184 pub fn delete_texture(&self, tex: gl::Texture) {
185 unsafe { (self.api().tex_delete)(tex.handle) }
186 }
187
188 /// Bind a texture to the given sampler unit (0–7).
189 pub fn bind_texture(&self, unit: u32, tex: &gl::Texture) {
190 unsafe { (self.api().tex_bind)(unit, tex.handle) }
191 }
192
193 // ── Draw calls ────────────────────────────────────────────────────────────
194
195 /// Draw primitives using a vertex array (no index buffer).
196 pub fn draw_arrays(
197 &self,
198 vao: &gl::VertexArray,
199 prog: &gl::ShaderProgram,
200 mode: core::DrawMode,
201 first: u32,
202 count: u32,
203 ) {
204 unsafe { (self.api().draw_arrays)(vao.handle, prog.handle, mode as u8, first, count) }
205 }
206
207 /// Draw primitives via an index buffer.
208 /// `u32_indices`: `true` = `u32` indices, `false` = `u16` indices.
209 pub fn draw_elements(
210 &self,
211 vao: &gl::VertexArray,
212 ebo: &gl::Buffer,
213 prog: &gl::ShaderProgram,
214 mode: core::DrawMode,
215 count: u32,
216 u32_indices: bool,
217 ) {
218 unsafe {
219 (self.api().draw_elements)(
220 vao.handle,
221 ebo.handle,
222 prog.handle,
223 mode as u8,
224 count,
225 u32_indices,
226 )
227 }
228 }
229
230 // ── Render state ──────────────────────────────────────────────────────────
231
232 /// Enable or disable alpha blending.
233 /// `src`/`dst`: GL blend factor constants from [`core::blend`].
234 pub fn set_blend(&self, enabled: bool, src: u32, dst: u32) {
235 unsafe { (self.api().set_blend)(enabled, src, dst) }
236 }
237
238 /// Enable or disable depth testing and writing.
239 pub fn set_depth(&self, test: bool, write: bool) {
240 unsafe { (self.api().set_depth)(test, write) }
241 }
242
243 /// Enable scissor clipping to a GUI-pixel rectangle.
244 pub fn set_scissor(&self, x: i32, y: i32, w: i32, h: i32) {
245 unsafe { (self.api().set_scissor)(x, y, w, h) }
246 }
247
248 /// Disable scissor clipping.
249 pub fn clear_scissor(&self) {
250 unsafe { (self.api().clear_scissor)() }
251 }
252
253 /// Set the GL viewport in physical pixels (x, y, width, height).
254 pub fn set_viewport(&self, x: i32, y: i32, w: i32, h: i32) {
255 unsafe { (self.api().set_viewport)(x, y, w, h) }
256 }
257
258 // ── 2D convenience ────────────────────────────────────────────────────────
259
260 /// Access the 2D drawing helpers (text, rectangles, MC textures).
261 /// These only work during `on_hud_render`.
262 pub fn draw2d(&self) -> draw2d::Draw2D<'_> {
263 draw2d::Draw2D::new(self)
264 }
265}