Improve performance of image handle access in API draw calls.

Use raw Lua C API to store image handles in Lua userdata instead
of using `mlua::UserData`. `mlua` wraps UserData in a special way
to maintain Rust safety guarantees which prevents direct access
of the underlying data from a raw Lua state.
The `DrawImage` and `DrawImageQuad` API calls used a workaround to
access the underlying image handle before which added significant
overhead. The overhead is eliminated by manually constructing the
userdata metatable for `ImageHandle` at the cost of weaker safety
guarantees.
This commit is contained in:
meehl committed 2026-08-12 18:03:41 +02:00
1 parent c1d91768bb
commit 99fc9f608e
3 files changed
+302 -128

No files matched your search

+2 -2
View File
@@ -5,7 +5,7 @@ use crate::{
clipboard::{copy, paste},
compression::{deflate, inflate},
console::{console_clear, console_execute, console_print_table, console_printf},
image_handle::new_image_handle,
image_handle::register_image_handle_api,
input::{get_cursor_pos, is_key_down},
lua::{load_module, protected_call, protected_load_module},
paths::{
@@ -79,7 +79,7 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> {
globals.set("NewFileSearch", lua.create_function(new_search_handle)?)?;
// image handle
globals.set("NewImageHandle", lua.create_function(new_image_handle)?)?;
register_image_handle_api(&lua)?;
// clipboard
globals.set("Copy", lua.create_function(copy)?)?;
+294 -72
View File
@@ -1,97 +1,319 @@
use std::{
ffi::{CStr, c_int},
ptr,
};
use mlua::{Lua, Result as LuaResult, ffi};
use crate::{
lua::Context,
renderer::textures::{TextureHandle, TextureOptions},
renderer::textures::{TextureHandle, TextureId, TextureOptions},
};
use mlua::{Lua, MultiValue, Result as LuaResult, UserData};
pub fn new_image_handle(_: &Lua, _: ()) -> LuaResult<ImageHandle> {
Ok(ImageHandle::Unloaded)
pub struct ImageHandle {
texture: Option<TextureHandle>,
}
#[derive(Clone)]
pub enum ImageHandle {
Loaded(TextureHandle),
Unloaded,
}
impl ImageHandle {
#[inline]
pub const fn new() -> Self {
Self { texture: None }
}
impl UserData for ImageHandle {
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
methods.add_method_mut("Load", load);
#[inline(always)]
pub fn texture_id(&self) -> Option<TextureId> {
self.texture.as_ref().map(TextureHandle::id)
}
methods.add_method_mut("Unload", |_, this, ()| {
match this {
ImageHandle::Loaded(_) => {
// dropping the handle frees the texture
*this = ImageHandle::Unloaded;
}
ImageHandle::Unloaded => {}
#[inline]
pub fn is_valid(&self) -> bool {
self.texture.is_some()
}
#[inline]
pub fn is_loading(&self) -> bool {
match &self.texture {
Some(texture) => {
let size = texture.size();
size[0] == 0
}
Ok(())
});
None => true,
}
}
methods.add_method("IsValid", |_, this, ()| {
Ok(matches!(this, ImageHandle::Loaded(_)))
});
methods.add_method("IsLoading", |_, this, ()| match &this {
ImageHandle::Loaded(texture_handle) => {
let size = texture_handle.size();
Ok(size[0] == 0)
}
ImageHandle::Unloaded => Ok(true),
});
methods.add_method("ImageSize", |_, this, ()| match &this {
ImageHandle::Loaded(texture_handle) => {
let size = texture_handle.size();
Ok((size[0], size[1]))
}
ImageHandle::Unloaded => Ok((0, 0)),
});
#[inline]
pub fn image_size(&self) -> [usize; 2] {
match &self.texture {
Some(texture) => texture.size(),
None => [0, 0],
}
}
}
fn load(
lua: &Lua,
handle: &mut ImageHandle,
(image_path, flags): (String, MultiValue),
) -> LuaResult<()> {
// Lua userdata implementation for `ImageHandle`.
//
// `mlua::UserData` instances are wrapped in a special way to maintain Rust
// safety guarantees which introduces additional overhead.
// https://github.com/mlua-rs/mlua/discussions/545#discussioncomment-12518251
//
// To avoid this overhead, `ImageHandle` is stored directly in Lua userdata
// using the raw Lua C API.
const IMAGE_HANDLE_METATABLE: &[u8] = b"runtime.ImageHandle\0";
#[inline]
unsafe fn push_image_handle(state: *mut ffi::lua_State) -> *mut ImageHandle {
let ptr = unsafe { ffi::lua_newuserdata(state, std::mem::size_of::<ImageHandle>()) }
as *mut ImageHandle;
// Construct the Rust object directly in Lua-owned memory
unsafe {
ptr.write(ImageHandle::new());
}
ptr
}
/// Puts ImageHandle on the Lua stack
unsafe extern "C-unwind" fn new_image_handle(state: *mut ffi::lua_State) -> c_int {
unsafe {
push_image_handle(state);
// The metatable must already have been registered.
ffi::luaL_getmetatable(state, IMAGE_HANDLE_METATABLE.as_ptr() as *const _);
ffi::lua_setmetatable(state, -2);
}
1
}
/// Get an ImageHandle from the Lua stack.
#[inline]
unsafe fn get_image_handle(state: *mut ffi::lua_State, index: c_int) -> *mut ImageHandle {
unsafe {
ffi::luaL_checkudata(state, index, IMAGE_HANDLE_METATABLE.as_ptr() as *const _)
as *mut ImageHandle
}
}
#[inline(always)]
pub unsafe fn image_handle_texture_id(
state: *mut ffi::lua_State,
index: c_int,
) -> Option<TextureId> {
if unsafe { ffi::lua_isnil(state, index) } != 0 {
return None;
}
let ptr = unsafe { ffi::lua_touserdata(state, index) } as *const ImageHandle;
if ptr.is_null() {
return None;
}
unsafe { (*ptr).texture_id() }
}
// Drops the ImageHandle
unsafe extern "C-unwind" fn image_handle_gc(state: *mut ffi::lua_State) -> c_int {
let ptr = unsafe { ffi::lua_touserdata(state, 1) } as *mut ImageHandle;
if !ptr.is_null() {
unsafe {
ptr::drop_in_place(ptr);
}
}
0
}
unsafe extern "C-unwind" fn image_handle_is_valid(state: *mut ffi::lua_State) -> c_int {
let handle = unsafe { get_image_handle(state, 1) };
let valid = unsafe { (*handle).is_valid() };
unsafe {
ffi::lua_pushboolean(state, valid as c_int);
}
1
}
unsafe extern "C-unwind" fn image_handle_is_loading(state: *mut ffi::lua_State) -> c_int {
let handle = unsafe { get_image_handle(state, 1) };
let loading = unsafe { (*handle).is_loading() };
unsafe {
ffi::lua_pushboolean(state, loading as c_int);
}
1
}
unsafe extern "C-unwind" fn image_handle_image_size(state: *mut ffi::lua_State) -> c_int {
let handle = unsafe { get_image_handle(state, 1) };
let [width, height] = unsafe { (*handle).image_size() };
unsafe {
ffi::lua_pushinteger(state, width as ffi::lua_Integer);
ffi::lua_pushinteger(state, height as ffi::lua_Integer);
}
2
}
unsafe extern "C-unwind" fn image_handle_unload(state: *mut ffi::lua_State) -> c_int {
let handle = unsafe { get_image_handle(state, 1) };
unsafe {
(*handle).texture = None;
}
0
}
unsafe extern "C-unwind" fn image_handle_load(state: *mut ffi::lua_State) -> c_int {
let handle = unsafe { get_image_handle(state, 1) };
let lua = unsafe { Lua::get_or_init_from_ptr(state) };
let ctx = lua.app_data_ref::<&'static Context>().unwrap();
// Path
let path_ptr = unsafe { ffi::luaL_checklstring(state, 2, ptr::null_mut()) };
if path_ptr.is_null() {
unsafe {
ffi::luaL_error(state, c"Invalid image path".as_ptr());
}
unreachable!();
}
let path = unsafe { CStr::from_ptr(path_ptr) };
let path = match path.to_str() {
Ok(path) => path.to_owned(),
Err(_) => {
unsafe {
ffi::luaL_error(state, c"Image path is not valid UTF-8".as_ptr());
}
unreachable!();
}
};
// Flags
let mut is_async = false;
let mut options = TextureOptions::LINEAR_REPEAT;
for flag in flags.iter() {
if let Some(flag) = flag.as_string() {
match flag.to_string_lossy().as_str() {
"CLAMP" => options.wrap_mode = wgpu::AddressMode::ClampToEdge,
"NEAREST" => options.magnification = wgpu::FilterMode::Nearest,
"ASYNC" => is_async = true,
"MIPMAP" => options.generate_mipmaps = true,
_ => {}
let nargs = unsafe { ffi::lua_gettop(state) };
for index in 3..=nargs {
if unsafe { ffi::lua_type(state, index) } != ffi::LUA_TSTRING {
continue;
}
let mut len = 0;
let ptr = unsafe { ffi::lua_tolstring(state, index, &mut len) };
if ptr.is_null() {
continue;
}
let bytes = unsafe { std::slice::from_raw_parts(ptr as *const u8, len) };
match bytes {
b"CLAMP" => {
options.wrap_mode = wgpu::AddressMode::ClampToEdge;
}
b"NEAREST" => {
options.magnification = wgpu::FilterMode::Nearest;
}
b"ASYNC" => {
is_async = true;
}
b"MIPMAP" => {
options.generate_mipmaps = true;
}
_ => {}
}
}
// Load / update
let handle = unsafe { &mut *handle };
match &mut handle.texture {
Some(texture_handle) => {
// Keep the existing TextureHandle and update underlying texture
let _ =
ctx.texture_manager()
.update_texture(texture_handle.id(), path, options, is_async);
}
None => {
if let Ok(texture_handle) = ctx.texture_manager().load_texture(path, options, is_async)
{
handle.texture = Some(texture_handle);
}
}
}
match handle {
// replace image data if already allocated
ImageHandle::Loaded(texture_handle) => {
// in case of error, stay loaded with current texture
let _ = ctx.texture_manager().update_texture(
texture_handle.id(),
image_path,
options,
is_async,
);
}
// create new texture handle
ImageHandle::Unloaded => {
if let Ok(tex_handle) = ctx
.texture_manager()
.load_texture(image_path, options, is_async)
{
*handle = ImageHandle::Loaded(tex_handle);
}
0
}
unsafe fn register_image_handle_metatable(state: *mut ffi::lua_State) {
unsafe {
let created = ffi::luaL_newmetatable(state, IMAGE_HANDLE_METATABLE.as_ptr() as *const _);
// Create metatable if it doesn't exist already
if created != 0 {
// metatable.__gc = image_handle_gc
ffi::lua_pushcfunction(state, image_handle_gc);
ffi::lua_setfield(state, -2, c"__gc".as_ptr());
// Create method table.
ffi::lua_newtable(state);
// Load
ffi::lua_pushcfunction(state, image_handle_load);
ffi::lua_setfield(state, -2, c"Load".as_ptr());
// Unload
ffi::lua_pushcfunction(state, image_handle_unload);
ffi::lua_setfield(state, -2, c"Unload".as_ptr());
// IsValid
ffi::lua_pushcfunction(state, image_handle_is_valid);
ffi::lua_setfield(state, -2, c"IsValid".as_ptr());
// IsLoading
ffi::lua_pushcfunction(state, image_handle_is_loading);
ffi::lua_setfield(state, -2, c"IsLoading".as_ptr());
// ImageSize
ffi::lua_pushcfunction(state, image_handle_image_size);
ffi::lua_setfield(state, -2, c"ImageSize".as_ptr());
// metatable.__index = method table
ffi::lua_setfield(state, -2, c"__index".as_ptr());
}
// Pop metatable.
ffi::lua_pop(state, 1);
}
}
pub fn register_image_handle_api(lua: &Lua) -> LuaResult<()> {
let globals = lua.globals();
unsafe {
lua.exec_raw::<()>((), |state| {
register_image_handle_metatable(state);
})
}?;
globals.set("NewImageHandle", unsafe {
lua.create_c_function(new_image_handle)
}?)?;
Ok(())
}
+6 -54
View File
@@ -1,14 +1,14 @@
use crate::{
api::image_handle::ImageHandle,
api::image_handle::image_handle_texture_id,
color::Srgba,
dpi::Uv,
fonts::{Alignment, FontStyle, LayoutJob},
lua::Context,
math::{Point, Quad, Rect, Size},
};
use core::ffi::{c_int, c_void};
use core::ffi::c_int;
use mlua::{
LightUserData, Lua, Result as LuaResult, UserDataRefMut, Value,
Lua, Result as LuaResult,
ffi::{self},
};
use parley::{FontFamily, FontFamilyName};
@@ -51,17 +51,6 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> {
"DrawStringCursorIndex",
lua.create_function_mut(get_index_at_cur)?,
)?;
// NOTE: mlua wraps UserData in a special way to maintain safety guarantees.
// This wrapper is not exposed by mlua, making it difficult to access the
// underlying user data from within C functions.
// This is a helper function that unwraps an ImageHandle and returns a pointer to it
// See: https://github.com/mlua-rs/mlua/discussions/545#discussioncomment-12530475
let get_img_handle = lua.create_function(|_, mut ud: UserDataRefMut<ImageHandle>| {
let vec: *mut ImageHandle = &mut *ud;
Ok(Value::LightUserData(LightUserData(vec as *mut c_void)))
})?;
lua.set_named_registry_value("get_img_handle", get_img_handle)?;
Ok(())
}
@@ -88,43 +77,6 @@ macro_rules! i32_from_stack {
};
}
macro_rules! img_handle_from_stack {
($s:ident, $i:expr) => {
unsafe {
match ffi::lua_type($s, $i) {
ffi::LUA_TNIL => None,
ffi::LUA_TUSERDATA => {
let img_handle = lua_toimghandle($s, $i);
if !img_handle.is_null() {
if let ImageHandle::Loaded(ref handle) = *img_handle {
Some(handle.id())
} else {
None
}
} else {
None
}
}
t => panic!("Expected Nil or ImageHandle, got {:?}", t),
}
}
};
}
unsafe extern "C" fn lua_toimghandle(state: *mut ffi::lua_State, idx: c_int) -> *mut ImageHandle {
unsafe {
let idx = ffi::lua_absindex(state, idx);
ffi::lua_getfield(state, ffi::LUA_REGISTRYINDEX, c"get_img_handle".as_ptr());
ffi::lua_pushvalue(state, idx);
let img_handle = match ffi::lua_pcall(state, 1, 1, 0) {
ffi::LUA_OK => ffi::lua_touserdata(state, -1) as *mut ImageHandle,
_ => std::ptr::null_mut(),
};
ffi::lua_pop(state, 1);
img_handle
}
}
unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("set_draw_color");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
@@ -247,7 +199,7 @@ unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int {
let parse_uv = matches!(nargs, 9 | 10 | 11);
let parse_layer_idx = matches!(nargs, 6 | 7 | 10 | 11);
let texture_id = img_handle_from_stack!(state, -nargs);
let texture_id = unsafe { image_handle_texture_id(state, -nargs) };
// left, top, width, height
let x = f32_from_stack!(state, -nargs + 1);
@@ -282,7 +234,7 @@ unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int {
}
unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("draw_image_quad", format!("args: {:?}", args));
//profiling::scope!("draw_image_quad");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
@@ -295,7 +247,7 @@ unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int
let parse_uv = matches!(nargs, 17 | 18 | 19);
let parse_layer_idx = matches!(nargs, 10 | 11 | 18 | 19);
let texture_id = img_handle_from_stack!(state, -nargs);
let texture_id = unsafe { image_handle_texture_id(state, -nargs) };
// x1, y1, x2, y2, ...
let x1 = f32_from_stack!(state, -nargs + 1);