Remove global context
This commit is contained in:
1 parent
f3d2f73925
commit
d8e52218f8
25 files changed
+1607
-1036
No files matched your search
@@ -0,0 +1,44 @@
|
||||
use mlua::{Function, Lua, Result as LuaResult, Table, Value};
|
||||
|
||||
// During initialization, PoB calls `SetMainObject` with a callback table.
|
||||
// Functions defined in this table are used to call back into Lua from Rust.
|
||||
// Custom callback functions can be added with `SetCallback` and retrieved
|
||||
// with `GetCallback`.
|
||||
const CALLBACK_REGISTRY_NAME: &str = "uicallbacks";
|
||||
|
||||
pub fn get_callback(lua: &Lua, name: &str) -> LuaResult<Function> {
|
||||
let callback_table: Table = lua.named_registry_value(CALLBACK_REGISTRY_NAME)?;
|
||||
let callback_function: Value = callback_table.get(name)?;
|
||||
if callback_function.is_function() {
|
||||
// function defined through `SetCallback`
|
||||
return Ok(callback_function.as_function().unwrap().clone());
|
||||
} else {
|
||||
// look for function in `MainObject`
|
||||
let main_object: Table = callback_table.get("MainObject")?;
|
||||
let callback_function: Value = main_object.get(name)?;
|
||||
if callback_function.is_function() {
|
||||
// these functions expect `MainObject` as first argument so we bind it here
|
||||
return callback_function.as_function().unwrap().bind(main_object);
|
||||
}
|
||||
}
|
||||
Err(anyhow::anyhow!("Function '{}' not found", name).into())
|
||||
}
|
||||
|
||||
pub fn set_main_object(l: &Lua, main_object: Table) -> LuaResult<()> {
|
||||
let callback_table = l.create_table()?;
|
||||
callback_table.set("MainObject", main_object)?;
|
||||
l.set_named_registry_value(CALLBACK_REGISTRY_NAME, callback_table)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_custom_callback(l: &Lua, (name, func): (String, Function)) -> LuaResult<()> {
|
||||
let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?;
|
||||
callback_table.set(name, func)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_custom_callback(l: &Lua, name: String) -> LuaResult<Function> {
|
||||
let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?;
|
||||
let callback_function: Function = callback_table.get(name)?;
|
||||
Ok(callback_function)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
use crate::lua::ContextSocket;
|
||||
use mlua::{Lua, Result as LuaResult};
|
||||
|
||||
pub fn copy(l: &Lua, text: String) -> LuaResult<()> {
|
||||
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
|
||||
socket
|
||||
.clipboard()
|
||||
.set_text(text)
|
||||
.map_err(|e| anyhow::anyhow!("{}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn paste(l: &Lua, _: ()) -> LuaResult<String> {
|
||||
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
|
||||
let text = socket
|
||||
.clipboard()
|
||||
.get_text()
|
||||
.map_err(|e| anyhow::anyhow!("{}", e))?;
|
||||
Ok(text)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use flate2::{
|
||||
Compression,
|
||||
read::{ZlibDecoder, ZlibEncoder},
|
||||
};
|
||||
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, String as LuaString, Value};
|
||||
use std::io::Read;
|
||||
|
||||
pub fn inflate(l: &Lua, compressed: LuaString) -> LuaResult<MultiValue> {
|
||||
let compressed_bytes = &compressed.as_bytes()[..];
|
||||
|
||||
// prevent decompression of input larger than 128MiB
|
||||
if compressed_bytes.len() > (128 << 20) {
|
||||
return Ok((Value::Nil, "Input larger than 128 MiB")
|
||||
.into_lua_multi(l)
|
||||
.unwrap());
|
||||
}
|
||||
|
||||
let mut decoder = ZlibDecoder::new(compressed_bytes);
|
||||
let mut decompressed = Vec::new();
|
||||
match decoder.read_to_end(&mut decompressed) {
|
||||
Ok(_) => Ok(l
|
||||
.create_string(&decompressed)
|
||||
.unwrap()
|
||||
.into_lua_multi(l)
|
||||
.unwrap()),
|
||||
Err(e) => Ok((Value::Nil, e.to_string()).into_lua_multi(l).unwrap()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deflate(l: &Lua, uncompressed: LuaString) -> LuaResult<MultiValue> {
|
||||
let uncompressed_bytes = &uncompressed.as_bytes()[..];
|
||||
|
||||
// prevent compression of input larger than 128MiB
|
||||
if uncompressed_bytes.len() > (128 << 20) {
|
||||
return Ok((Value::Nil, "Input larger than 128 MiB")
|
||||
.into_lua_multi(l)
|
||||
.unwrap());
|
||||
}
|
||||
|
||||
let mut encoder = ZlibEncoder::new(uncompressed_bytes, Compression::fast());
|
||||
let mut compressed = Vec::new();
|
||||
match encoder.read_to_end(&mut compressed) {
|
||||
Ok(_) => Ok(l
|
||||
.create_string(&compressed)
|
||||
.unwrap()
|
||||
.into_lua_multi(l)
|
||||
.unwrap()),
|
||||
Err(e) => Ok((Value::Nil, e.to_string()).into_lua_multi(l).unwrap()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
use mlua::{Function, Lua, MultiValue, Result as LuaResult, Table, Value};
|
||||
use std::io::{Write, stdout};
|
||||
|
||||
pub fn console_printf(l: &Lua, (fmt, args): (String, MultiValue)) -> LuaResult<()> {
|
||||
// uses lua's builtin string.format function
|
||||
let string_module: Table = l.globals().get("string")?;
|
||||
let format_func: Function = string_module.get("format")?;
|
||||
let formatted_string = format_func.call::<String>((fmt, args))?;
|
||||
println!("{formatted_string}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn console_execute(_l: &Lua, _cmd: String) -> LuaResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn console_clear(_l: &Lua, _: ()) -> LuaResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn console_print_table(
|
||||
_l: &Lua,
|
||||
(table, no_recursive): (Table, Option<bool>),
|
||||
) -> LuaResult<()> {
|
||||
print_table(&table, 0, !no_recursive.unwrap_or(true))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn print_table(table: &Table, indent: usize, recursive: bool) -> LuaResult<()> {
|
||||
let mut lock = stdout().lock();
|
||||
writeln!(lock, "{{")?;
|
||||
for pair in table.pairs::<Value, Value>() {
|
||||
let inner_ind = indent + 2;
|
||||
let (key, value) = pair?;
|
||||
|
||||
if key.is_string() {
|
||||
write!(lock, "{0:>1$}\"{2}\" = ", "", inner_ind, key.to_string()?,)?;
|
||||
} else {
|
||||
write!(lock, "{0:>1$}{2} = ", "", inner_ind, key.to_string()?,)?;
|
||||
}
|
||||
|
||||
if value.is_table() {
|
||||
if recursive {
|
||||
print_table(value.as_table().unwrap(), indent + 2, recursive)?;
|
||||
} else {
|
||||
writeln!(lock, "{}", value.to_string()?)?;
|
||||
}
|
||||
} else if value.is_string() {
|
||||
writeln!(lock, "\"{}\"", value.to_string()?)?;
|
||||
} else {
|
||||
writeln!(lock, "{}", value.to_string()?)?;
|
||||
}
|
||||
}
|
||||
writeln!(lock, "{0:>1$}}}", "", indent)?;
|
||||
Ok(())
|
||||
}
|
||||
+52
-49
@@ -1,9 +1,12 @@
|
||||
use mlua::{MultiValue, UserData};
|
||||
|
||||
use crate::{
|
||||
context::CONTEXT,
|
||||
lua::ContextSocket,
|
||||
renderer::textures::{TextureHandle, TextureOptions},
|
||||
};
|
||||
use mlua::{Lua, MultiValue, Result as LuaResult, UserData};
|
||||
|
||||
pub fn new_image_handle(_: &Lua, _: ()) -> LuaResult<ImageHandle> {
|
||||
Ok(ImageHandle::Unloaded)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum ImageHandle {
|
||||
@@ -13,52 +16,7 @@ pub enum ImageHandle {
|
||||
|
||||
impl UserData for ImageHandle {
|
||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_method_mut(
|
||||
"Load",
|
||||
|_, this, (image_path, flags): (String, MultiValue)| {
|
||||
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,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match this {
|
||||
// replace image data if already allocated
|
||||
ImageHandle::Loaded(texture_handle) => {
|
||||
CONTEXT.with_borrow(|ctx| {
|
||||
// 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 => {
|
||||
CONTEXT.with_borrow(|ctx| {
|
||||
if let Ok(handle) = ctx
|
||||
.texture_manager
|
||||
.load_texture(image_path, options, is_async)
|
||||
{
|
||||
*this = ImageHandle::Loaded(handle);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
methods.add_method_mut("Load", load);
|
||||
|
||||
methods.add_method_mut("Unload", |_, this, ()| {
|
||||
match this {
|
||||
@@ -92,3 +50,48 @@ impl UserData for ImageHandle {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn load(
|
||||
lua: &Lua,
|
||||
handle: &mut ImageHandle,
|
||||
(image_path, flags): (String, MultiValue),
|
||||
) -> LuaResult<()> {
|
||||
let socket = lua.app_data_ref::<&'static ContextSocket>().unwrap();
|
||||
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,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match handle {
|
||||
// replace image data if already allocated
|
||||
ImageHandle::Loaded(texture_handle) => {
|
||||
// in case of error, stay loaded with current texture
|
||||
let _ = socket.texture_manager().update_texture(
|
||||
texture_handle.id(),
|
||||
image_path,
|
||||
options,
|
||||
is_async,
|
||||
);
|
||||
}
|
||||
// create new texture handle
|
||||
ImageHandle::Unloaded => {
|
||||
if let Ok(tex_handle) = socket
|
||||
.texture_manager()
|
||||
.load_texture(image_path, options, is_async)
|
||||
{
|
||||
*handle = ImageHandle::Loaded(tex_handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use crate::{
|
||||
input::{str_as_keycode, str_as_mousebutton},
|
||||
lua::ContextSocket,
|
||||
};
|
||||
use mlua::{Lua, Result as LuaResult};
|
||||
|
||||
pub fn get_cursor_pos(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
|
||||
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
|
||||
let pos = socket.input().mouse_pos();
|
||||
Ok((pos.x as u32, pos.y as u32))
|
||||
}
|
||||
|
||||
pub fn is_key_down(l: &Lua, key_name: String) -> LuaResult<bool> {
|
||||
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
|
||||
|
||||
if let Some(code) = str_as_keycode(&key_name) {
|
||||
Ok(socket.input().key_pressed(code))
|
||||
} else if let Some(button) = str_as_mousebutton(&key_name) {
|
||||
Ok(socket.input().mouse_pressed(button))
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use crate::{args::Game, util::change_working_directory};
|
||||
use mlua::{Function, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
|
||||
use std::env;
|
||||
|
||||
pub fn protected_call(l: &Lua, (func, args): (Function, MultiValue)) -> LuaResult<MultiValue> {
|
||||
match func.call::<MultiValue>(args) {
|
||||
// callers expect first return value to be Nil on success
|
||||
Ok(return_values) => Ok(std::iter::once(Value::Nil).chain(return_values).collect()),
|
||||
// otherwise it is set to error message.
|
||||
Err(err) => Ok(err.to_string().into_lua_multi(l)?),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
|
||||
let mut module_path = Game::script_dir().join(name);
|
||||
if module_path.extension().is_none() {
|
||||
module_path.set_extension("lua");
|
||||
}
|
||||
|
||||
let current_dir = env::current_dir()?;
|
||||
change_working_directory(Game::script_dir().as_path())?;
|
||||
let result = l.load(module_path).call::<MultiValue>(args);
|
||||
change_working_directory(current_dir)?;
|
||||
result
|
||||
}
|
||||
|
||||
pub fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
|
||||
let mut module_path = Game::script_dir().join(name);
|
||||
if module_path.extension().is_none() {
|
||||
module_path.set_extension("lua");
|
||||
}
|
||||
|
||||
let current_dir = env::current_dir()?;
|
||||
change_working_directory(Game::script_dir().as_path())?;
|
||||
let result = match l.load(module_path).call::<MultiValue>(args) {
|
||||
// on success, callers expect a Nil followed by return values
|
||||
Ok(res) => Ok(std::iter::once(Value::Nil).chain(res).collect()),
|
||||
// otherwise it is set to error message.
|
||||
Err(err) => Ok(err.to_string().into_lua_multi(l)?),
|
||||
};
|
||||
change_working_directory(current_dir)?;
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use anyhow::anyhow;
|
||||
use directories::UserDirs;
|
||||
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
use crate::{
|
||||
args::Game,
|
||||
lua::ContextSocket,
|
||||
util::{change_working_directory, get_executable_dir},
|
||||
};
|
||||
|
||||
pub fn get_user_path(_: &Lua, _: ()) -> LuaResult<anyhow::Result<PathBuf>> {
|
||||
let user_dirs = match UserDirs::new() {
|
||||
Some(user_dirs) => user_dirs,
|
||||
None => return Ok(Err(anyhow!("Failed to retrieve user's home directory"))),
|
||||
};
|
||||
|
||||
match user_dirs.document_dir() {
|
||||
Some(docs_dir) => Ok(Ok(docs_dir.canonicalize().unwrap())),
|
||||
None => Ok(Err(anyhow!(
|
||||
"Failed to retrieve user's documents directory"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
// parent directory of Launch.lua script
|
||||
pub fn get_script_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
Ok(Game::script_dir())
|
||||
}
|
||||
|
||||
// parent directory of executable
|
||||
pub fn get_runtime_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
match get_executable_dir() {
|
||||
Ok(exe_path) => Ok(exe_path),
|
||||
Err(_) => Ok(PathBuf::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_work_dir(l: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
|
||||
Ok(socket.current_working_dir().to_path_buf())
|
||||
}
|
||||
|
||||
// NOTE: unused
|
||||
pub fn set_work_dir(l: &Lua, path: String) -> LuaResult<()> {
|
||||
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
|
||||
if change_working_directory(&path).is_ok() {
|
||||
*socket.current_working_dir() = path.into();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn make_dir(l: &Lua, path: String) -> LuaResult<MultiValue> {
|
||||
match fs::create_dir_all(path) {
|
||||
// callers expect first return value to be true on success
|
||||
Ok(_) => Ok(Value::Boolean(true).into_lua_multi(l)?),
|
||||
// otherwise it is set to Nil and second return value is set to error msg
|
||||
Err(err) => Ok((Value::Nil, err.to_string()).into_lua_multi(l)?),
|
||||
}
|
||||
}
|
||||
+97
-49
@@ -1,9 +1,9 @@
|
||||
use crate::{
|
||||
api::image_handle::ImageHandle,
|
||||
color::Srgba,
|
||||
context::CONTEXT,
|
||||
dpi::Uv,
|
||||
fonts::{Alignment, LayoutJob},
|
||||
lua::ContextSocket,
|
||||
math::{Point, Quad, Rect, Size},
|
||||
};
|
||||
use core::ffi::{c_int, c_void};
|
||||
@@ -16,6 +16,17 @@ use std::sync::LazyLock;
|
||||
|
||||
pub fn register_globals(lua: &Lua) -> LuaResult<()> {
|
||||
let globals = lua.globals();
|
||||
|
||||
// unused functions
|
||||
let get_draw_layer = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
let set_blend_mode = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
let get_async_count = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
let set_clear_color = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
globals.set("GetDrawLayer", lua.create_function(get_draw_layer)?)?;
|
||||
globals.set("SetBlendMode", lua.create_function(set_blend_mode)?)?;
|
||||
globals.set("GetAsyncCount", lua.create_function(get_async_count)?)?;
|
||||
globals.set("SetClearColor", lua.create_function(set_clear_color)?)?;
|
||||
|
||||
// rendering functions
|
||||
// NOTE: unfortunately, mlua's conversion of function arguments adds a lot of
|
||||
// overhead. this is very noticeable for the draw functions which can be called
|
||||
@@ -114,6 +125,10 @@ unsafe extern "C" fn lua_toimghandle(state: *mut ffi::lua_State, idx: c_int) ->
|
||||
|
||||
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) };
|
||||
let socket = lua_instance
|
||||
.app_data_ref::<&'static ContextSocket>()
|
||||
.unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
match nargs {
|
||||
@@ -121,7 +136,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
|
||||
1 => {
|
||||
let esc_str = str_from_stack!(state, -nargs);
|
||||
let color = Srgba::from_escape_code(esc_str);
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_color(color));
|
||||
socket.layers().set_draw_color(color);
|
||||
}
|
||||
// rgb
|
||||
3 => {
|
||||
@@ -129,7 +144,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
|
||||
let g = f32_from_stack!(state, -nargs + 1);
|
||||
let b = f32_from_stack!(state, -nargs + 2);
|
||||
let color = Srgba::new_f32(r, g, b, 1.0);
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_color(color));
|
||||
socket.layers().set_draw_color(color);
|
||||
}
|
||||
// rgba
|
||||
4 => {
|
||||
@@ -138,7 +153,7 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
|
||||
let b = f32_from_stack!(state, -nargs + 2);
|
||||
let a = f32_from_stack!(state, -nargs + 3);
|
||||
let color = Srgba::new_f32(r, g, b, a);
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_color(color));
|
||||
socket.layers().set_draw_color(color);
|
||||
}
|
||||
_ => panic!("Unexpected number of arguments"),
|
||||
};
|
||||
@@ -148,17 +163,23 @@ unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int
|
||||
|
||||
unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("set_viewport");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let socket = lua_instance
|
||||
.app_data_ref::<&'static ContextSocket>()
|
||||
.unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
match nargs {
|
||||
0 => CONTEXT.with_borrow_mut(|ctx| ctx.reset_viewport()),
|
||||
0 => socket
|
||||
.layers()
|
||||
.set_viewport_from_size(socket.window().logical_size()),
|
||||
4 => {
|
||||
let x = f32_from_stack!(state, -nargs);
|
||||
let y = f32_from_stack!(state, -nargs + 1);
|
||||
let w = f32_from_stack!(state, -nargs + 2);
|
||||
let h = f32_from_stack!(state, -nargs + 3);
|
||||
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.set_viewport(rect));
|
||||
socket.layers().set_viewport(rect);
|
||||
}
|
||||
_ => panic!("Unexpected number of arguments"),
|
||||
};
|
||||
@@ -168,13 +189,17 @@ unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int {
|
||||
|
||||
unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("set_draw_layer");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let socket = lua_instance
|
||||
.app_data_ref::<&'static ContextSocket>()
|
||||
.unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
match nargs {
|
||||
1 => {
|
||||
let layer = i32_from_stack!(state, -nargs);
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_layer(layer, 0));
|
||||
socket.layers().set_draw_layer(layer, 0);
|
||||
}
|
||||
2 => {
|
||||
let layer = match unsafe { ffi::lua_type(state, -nargs) } {
|
||||
@@ -187,9 +212,9 @@ unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int
|
||||
};
|
||||
let sublayer = i32_from_stack!(state, -nargs + 1);
|
||||
if let Some(layer) = layer {
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_layer(layer, sublayer));
|
||||
socket.layers().set_draw_layer(layer, sublayer);
|
||||
} else {
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_sublayer(sublayer));
|
||||
socket.layers().set_draw_sublayer(sublayer);
|
||||
}
|
||||
}
|
||||
_ => panic!("Unexpected number of arguments"),
|
||||
@@ -200,6 +225,10 @@ unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int
|
||||
|
||||
unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("draw_image");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let socket = lua_instance
|
||||
.app_data_ref::<&'static ContextSocket>()
|
||||
.unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
if !matches!(nargs, 5 | 6 | 7 | 9 | 10 | 11) {
|
||||
@@ -239,13 +268,17 @@ unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int {
|
||||
0
|
||||
};
|
||||
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.draw_rect(texture_id, rect, uv, layer_idx));
|
||||
socket.layers().draw_rect(texture_id, rect, uv, layer_idx);
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("draw_image_quad", format!("args: {:?}", args));
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let socket = lua_instance
|
||||
.app_data_ref::<&'static ContextSocket>()
|
||||
.unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
if !matches!(nargs, 9 | 10 | 11 | 17 | 18 | 19) {
|
||||
@@ -303,13 +336,17 @@ unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int
|
||||
0
|
||||
};
|
||||
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.draw_quad(texture_id, quad, uv, layer_idx));
|
||||
socket.layers().draw_quad(texture_id, quad, uv, layer_idx);
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("draw_string");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let socket = lua_instance
|
||||
.app_data_ref::<&'static ContextSocket>()
|
||||
.unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
@@ -331,48 +368,53 @@ unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
|
||||
|
||||
let mut position = Point::new(x, y);
|
||||
let mut is_absolute_position = false;
|
||||
CONTEXT.with_borrow_mut(|ctx| {
|
||||
// the position needs to be adjusted for some alignments to match PoBs behavior
|
||||
let screen_size = ctx.screen_size_logical();
|
||||
let halign = match alignment {
|
||||
PoBTextAlignment::Left => Alignment::Min,
|
||||
PoBTextAlignment::Center => {
|
||||
position.x += screen_size.width as f32 / 2.0;
|
||||
is_absolute_position = true;
|
||||
Alignment::Center
|
||||
}
|
||||
PoBTextAlignment::Right => {
|
||||
position.x = screen_size.width as f32 - position.x;
|
||||
is_absolute_position = true;
|
||||
Alignment::Max
|
||||
}
|
||||
PoBTextAlignment::CenterX => Alignment::Center,
|
||||
PoBTextAlignment::RightX => Alignment::Max,
|
||||
};
|
||||
|
||||
let current_draw_color = ctx.get_draw_color();
|
||||
let job = build_layout_job(
|
||||
text,
|
||||
current_draw_color,
|
||||
font_type,
|
||||
line_height,
|
||||
Some(halign),
|
||||
);
|
||||
|
||||
// NOTE: color escape codes modify the current draw color.
|
||||
// set current draw color to color of last segment to match PoB's behavior
|
||||
if let Some(last_segment) = job.segments.last() {
|
||||
ctx.set_draw_color(last_segment.color);
|
||||
// the position needs to be adjusted for some alignments to match PoBs behavior
|
||||
let screen_size = socket.window().logical_size();
|
||||
let halign = match alignment {
|
||||
PoBTextAlignment::Left => Alignment::Min,
|
||||
PoBTextAlignment::Center => {
|
||||
position.x += screen_size.width as f32 / 2.0;
|
||||
is_absolute_position = true;
|
||||
Alignment::Center
|
||||
}
|
||||
PoBTextAlignment::Right => {
|
||||
position.x = screen_size.width as f32 - position.x;
|
||||
is_absolute_position = true;
|
||||
Alignment::Max
|
||||
}
|
||||
PoBTextAlignment::CenterX => Alignment::Center,
|
||||
PoBTextAlignment::RightX => Alignment::Max,
|
||||
};
|
||||
|
||||
ctx.draw_text(position, job, is_absolute_position);
|
||||
});
|
||||
let current_draw_color = socket.layers().get_draw_color();
|
||||
let job = build_layout_job(
|
||||
text,
|
||||
current_draw_color,
|
||||
font_type,
|
||||
line_height,
|
||||
Some(halign),
|
||||
);
|
||||
|
||||
// NOTE: color escape codes modify the current draw color.
|
||||
// set current draw color to color of last segment to match PoB's behavior
|
||||
if let Some(last_segment) = job.segments.last() {
|
||||
socket.layers().set_draw_color(last_segment.color);
|
||||
}
|
||||
|
||||
let layout = socket.fonts().layout(job, socket.window().scale_factor);
|
||||
socket
|
||||
.layers()
|
||||
.draw_text(position, layout, is_absolute_position);
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("get_string_width");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let socket = lua_instance
|
||||
.app_data_ref::<&'static ContextSocket>()
|
||||
.unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
@@ -386,23 +428,29 @@ unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_in
|
||||
};
|
||||
|
||||
let job = build_layout_job(text, Srgba::WHITE, font_type, line_height, None);
|
||||
let width = CONTEXT.with_borrow_mut(|ctx| ctx.get_text_width(job));
|
||||
let width = socket
|
||||
.fonts()
|
||||
.get_text_width(job, socket.window().scale_factor);
|
||||
|
||||
unsafe { ffi::lua_pushnumber(state, width as f64) };
|
||||
1
|
||||
}
|
||||
|
||||
fn get_index_at_cur(
|
||||
_: &Lua,
|
||||
l: &Lua,
|
||||
(line_height, font_type, text, cur_x, cur_y): (i32, String, String, f32, f32),
|
||||
) -> LuaResult<usize> {
|
||||
//profiling::scope!("get_char_index_at_cur");
|
||||
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
|
||||
|
||||
let font_type = font_type.parse::<PoBFontType>()?;
|
||||
|
||||
let job = build_layout_job(&text, Srgba::WHITE, font_type, line_height, None);
|
||||
let index =
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.get_text_index_at_cursor(job, Point::new(cur_x, cur_y)));
|
||||
let index = socket.fonts().get_text_index_at_cursor(
|
||||
job,
|
||||
Point::new(cur_x, cur_y),
|
||||
socket.window().scale_factor,
|
||||
);
|
||||
|
||||
// convert to lua's 1-based indexing
|
||||
Ok(index + 1)
|
||||
|
||||
@@ -1,9 +1,27 @@
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
use glob::{Paths, glob};
|
||||
use mlua::{IntoLua, Lua, Result as LuaResult, UserData, Value};
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
time::SystemTime,
|
||||
};
|
||||
|
||||
use glob::Paths;
|
||||
use mlua::{IntoLua, UserData};
|
||||
pub fn new_search_handle(
|
||||
l: &Lua,
|
||||
(pattern, find_directories): (String, Option<bool>),
|
||||
) -> LuaResult<Value> {
|
||||
if let Ok(paths) = glob(&pattern) {
|
||||
let directories_only = find_directories.is_some_and(|x| x);
|
||||
let mut handle = SearchHandle::new(paths, directories_only);
|
||||
// try to get the first result
|
||||
handle.next();
|
||||
// only return a handle if at least one file/directory is found
|
||||
if handle.current.is_some() {
|
||||
return handle.into_lua(l);
|
||||
}
|
||||
};
|
||||
Ok(Value::Nil)
|
||||
}
|
||||
|
||||
pub struct SearchHandle {
|
||||
paths: Paths,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
use crate::lua::ContextSocket;
|
||||
use mlua::{Lua, Result as LuaResult};
|
||||
|
||||
// NOTE: needs to return physical size if this MR gets merged:
|
||||
// https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2/pull/1420
|
||||
pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
|
||||
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
|
||||
let size = socket.window().logical_size();
|
||||
Ok((size.width, size.height))
|
||||
}
|
||||
|
||||
pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult<f32> {
|
||||
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
|
||||
Ok(socket.window().scale_factor)
|
||||
}
|
||||
|
||||
pub fn set_window_title(l: &Lua, title: String) -> LuaResult<()> {
|
||||
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
|
||||
socket.window().set_window_title(&title);
|
||||
Ok(())
|
||||
}
|
||||
Reference in new issue
Block a user