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
69/// See [`GfxContext::text_width_fn`]: `(text, font) -> width` in GUI pixels.
70pub type TextWidthFn = unsafe extern "C" fn(text: yog_abi::YogStr, font: yog_abi::YogStr) -> f32;
71
72impl GfxContext {
73 #[doc(hidden)]
74 pub unsafe fn from_raw(raw: *const YogGfxApi) -> Self {
75 Self(raw)
76 }
77
78 #[inline]
79 fn api(&self) -> &YogGfxApi {
80 unsafe { &*self.0 }
81 }
82
83 // ── Frame info ────────────────────────────────────────────────────────────
84
85 /// GUI pixel dimensions of the screen for this frame.
86 pub fn screen_size(&self) -> (i32, i32) {
87 let a = self.api();
88 (a.screen_w, a.screen_h)
89 }
90
91 /// Partial-tick interpolation factor (0.0–1.0).
92 pub fn delta_tick(&self) -> f32 {
93 self.api().delta_tick
94 }
95
96 /// View-projection matrix in camera-relative space (column-major, 16 × f32).
97 /// Zeros during `on_hud_render`; filled during `on_world_render`.
98 pub fn view_proj(&self) -> [f32; 16] {
99 self.api().view_proj
100 }
101
102 /// Camera world-space position. All zeros during `on_hud_render`.
103 pub fn camera_pos(&self) -> [f32; 3] {
104 self.api().camera_pos
105 }
106
107 /// Local player world-space position (eye height). All zeros during `on_hud_render`.
108 /// Use this to anchor geometry to the player; differs from `camera_pos` in third-person.
109 pub fn player_pos(&self) -> [f32; 3] {
110 self.api().player_pos
111 }
112
113 // ── GPU buffer ───────────────────────────────────────────────────────────
114
115 /// Allocate a new GPU buffer (VBO or EBO). Returns handle 0 on failure.
116 pub fn create_buffer(&self) -> gl::Buffer {
117 gl::Buffer {
118 handle: unsafe { (self.api().buf_create)() },
119 }
120 }
121
122 /// Delete a buffer allocated by `create_buffer`.
123 pub fn delete_buffer(&self, buf: gl::Buffer) {
124 unsafe { (self.api().buf_delete)(buf.handle) }
125 }
126
127 // ── Vertex array ─────────────────────────────────────────────────────────
128
129 /// Allocate a new vertex array object. Returns handle 0 on failure.
130 pub fn create_vao(&self) -> gl::VertexArray {
131 gl::VertexArray {
132 handle: unsafe { (self.api().vao_create)() },
133 }
134 }
135
136 /// Delete a vertex array allocated by `create_vao`.
137 pub fn delete_vao(&self, vao: gl::VertexArray) {
138 unsafe { (self.api().vao_delete)(vao.handle) }
139 }
140
141 // ── Shader program ────────────────────────────────────────────────────────
142
143 /// Compile and link a GLSL shader program.
144 /// Returns `Err(())` and logs on compile/link failure.
145 #[allow(clippy::result_unit_err)] // public API; the log carries the details
146 pub fn create_shader(&self, vert_src: &str, frag_src: &str) -> Result<gl::ShaderProgram, ()> {
147 use yog_abi::YogStr;
148 let mut handle = 0u32;
149 let ok = unsafe {
150 (self.api().prog_create)(
151 YogStr::from_str(vert_src),
152 YogStr::from_str(frag_src),
153 &mut handle,
154 )
155 };
156 if ok && handle != 0 {
157 Ok(gl::ShaderProgram { handle })
158 } else {
159 Err(())
160 }
161 }
162
163 /// Delete a shader program.
164 pub fn delete_shader(&self, prog: gl::ShaderProgram) {
165 unsafe { (self.api().prog_delete)(prog.handle) }
166 }
167
168 // ── Texture ───────────────────────────────────────────────────────────────
169
170 /// Upload RGBA8 pixel data as a new GPU texture.
171 /// `linear`: `true` = bilinear filter, `false` = nearest.
172 pub fn create_texture_rgba(&self, w: u32, h: u32, pixels: &[u8], linear: bool) -> gl::Texture {
173 gl::Texture {
174 handle: unsafe { (self.api().tex_create)(w, h, pixels.as_ptr(), linear) },
175 }
176 }
177
178 /// Get the GL texture handle that Minecraft uses for an identifier
179 /// (e.g. `"minecraft:textures/gui/icons.png"`). Returns handle 0 if not found.
180 pub fn texture_from_mc(&self, id: &str) -> gl::Texture {
181 use yog_abi::YogStr;
182 gl::Texture {
183 handle: unsafe { (self.api().tex_from_mc)(YogStr::from_str(id)) },
184 }
185 }
186
187 /// Delete a texture.
188 pub fn delete_texture(&self, tex: gl::Texture) {
189 unsafe { (self.api().tex_delete)(tex.handle) }
190 }
191
192 /// Bind a texture to the given sampler unit (0–7).
193 pub fn bind_texture(&self, unit: u32, tex: &gl::Texture) {
194 unsafe { (self.api().tex_bind)(unit, tex.handle) }
195 }
196
197 // ── Draw calls ────────────────────────────────────────────────────────────
198
199 /// Draw primitives using a vertex array (no index buffer).
200 pub fn draw_arrays(
201 &self,
202 vao: &gl::VertexArray,
203 prog: &gl::ShaderProgram,
204 mode: core::DrawMode,
205 first: u32,
206 count: u32,
207 ) {
208 unsafe { (self.api().draw_arrays)(vao.handle, prog.handle, mode as u8, first, count) }
209 }
210
211 /// Draw primitives via an index buffer.
212 /// `u32_indices`: `true` = `u32` indices, `false` = `u16` indices.
213 pub fn draw_elements(
214 &self,
215 vao: &gl::VertexArray,
216 ebo: &gl::Buffer,
217 prog: &gl::ShaderProgram,
218 mode: core::DrawMode,
219 count: u32,
220 u32_indices: bool,
221 ) {
222 unsafe {
223 (self.api().draw_elements)(
224 vao.handle,
225 ebo.handle,
226 prog.handle,
227 mode as u8,
228 count,
229 u32_indices,
230 )
231 }
232 }
233
234 // ── Render state ──────────────────────────────────────────────────────────
235
236 /// Enable or disable alpha blending.
237 /// `src`/`dst`: GL blend factor constants from [`core::blend`].
238 pub fn set_blend(&self, enabled: bool, src: u32, dst: u32) {
239 unsafe { (self.api().set_blend)(enabled, src, dst) }
240 }
241
242 /// Enable or disable depth testing and writing.
243 pub fn set_depth(&self, test: bool, write: bool) {
244 unsafe { (self.api().set_depth)(test, write) }
245 }
246
247 /// Enable scissor clipping to a GUI-pixel rectangle.
248 pub fn set_scissor(&self, x: i32, y: i32, w: i32, h: i32) {
249 unsafe { (self.api().set_scissor)(x, y, w, h) }
250 }
251
252 /// Disable scissor clipping.
253 pub fn clear_scissor(&self) {
254 unsafe { (self.api().clear_scissor)() }
255 }
256
257 /// Set the GL viewport in physical pixels (x, y, width, height).
258 pub fn set_viewport(&self, x: i32, y: i32, w: i32, h: i32) {
259 unsafe { (self.api().set_viewport)(x, y, w, h) }
260 }
261
262 // ── 2D convenience ────────────────────────────────────────────────────────
263
264 /// Access the 2D drawing helpers (text, rectangles, MC textures).
265 /// These only work during `on_hud_render`.
266 /// The host's text-width function (see [`draw2d::Draw2D::text_width`]) as
267 /// a plain function pointer — valid for the life of the process, so it
268 /// can be kept for measuring outside render callbacks (on the render
269 /// thread), e.g. by a layout engine.
270 pub fn text_width_fn(&self) -> TextWidthFn {
271 self.api().text_width
272 }
273
274 pub fn draw2d(&self) -> draw2d::Draw2D<'_> {
275 draw2d::Draw2D::new(self)
276 }
277}