Refactor context handling and redraw requests
Remove unsafe pointer shenanigans and give Lua instance ownership over `Context`. Event handlers now directly mutate Context instead of using a shared app state which is then hooked up to Context via unsafe pointers. The removal of a shared state means stages (previously called "modes") are now responsible for keeping their own internal state. Additionally, clean up draw request handling and module hierarchy.
This commit is contained in:
1 parent
337e876571
commit
cc6de120f2
27 files changed
+803
-876
No files matched your search
+173
@@ -0,0 +1,173 @@
|
||||
pub use crate::pob::api::callback::{call_callback, get_callback};
|
||||
use crate::{
|
||||
pob::Context,
|
||||
pob::api::{
|
||||
callback::{get_custom_callback, set_custom_callback, set_main_object},
|
||||
clipboard::{copy, paste},
|
||||
compression::{deflate, inflate},
|
||||
console::{console_clear, console_execute, console_print_table, console_printf},
|
||||
image_handle::register_image_handle_api,
|
||||
input::{get_cursor_pos, is_key_down},
|
||||
lua::{load_module, protected_call, protected_load_module},
|
||||
paths::{
|
||||
get_runtime_path, get_script_path, get_user_path, get_work_dir, make_dir, remove_dir,
|
||||
set_work_dir,
|
||||
},
|
||||
rendering::PoBString,
|
||||
search_handle::new_search_handle,
|
||||
subscript::{abort_subscript, is_subscript_running, launch_subscript},
|
||||
window::{
|
||||
get_dpi_scale_override, get_screen_scale, get_screen_size, set_dpi_scale_override,
|
||||
set_foreground, set_window_title,
|
||||
},
|
||||
},
|
||||
};
|
||||
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Variadic};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
mod callback;
|
||||
mod clipboard;
|
||||
mod compression;
|
||||
mod console;
|
||||
mod image_handle;
|
||||
mod input;
|
||||
mod lua;
|
||||
mod paths;
|
||||
mod rendering;
|
||||
mod search_handle;
|
||||
mod subscript;
|
||||
mod window;
|
||||
|
||||
/// Register functions that can be called from lua
|
||||
pub fn register_globals(lua: &Lua) -> LuaResult<()> {
|
||||
let globals = lua.globals();
|
||||
|
||||
// callbacks
|
||||
globals.set("SetMainObject", lua.create_function(set_main_object)?)?;
|
||||
globals.set("SetCallback", lua.create_function(set_custom_callback)?)?;
|
||||
globals.set("GetCallback", lua.create_function(get_custom_callback)?)?;
|
||||
|
||||
// paths
|
||||
globals.set("GetUserPath", lua.create_function(get_user_path)?)?;
|
||||
globals.set("GetScriptPath", lua.create_function(get_script_path)?)?;
|
||||
globals.set("GetRuntimePath", lua.create_function(get_runtime_path)?)?;
|
||||
globals.set("GetWorkDir", lua.create_function(get_work_dir)?)?;
|
||||
globals.set("SetWorkDir", lua.create_function(set_work_dir)?)?;
|
||||
globals.set("MakeDir", lua.create_function(make_dir)?)?;
|
||||
globals.set("RemoveDir", lua.create_function(remove_dir)?)?;
|
||||
|
||||
// console
|
||||
globals.set("ConPrintf", lua.create_function(console_printf)?)?;
|
||||
globals.set("ConExecute", lua.create_function(console_execute)?)?;
|
||||
globals.set("ConClear", lua.create_function(console_clear)?)?;
|
||||
globals.set("ConPrintTable", lua.create_function(console_print_table)?)?;
|
||||
|
||||
// general
|
||||
globals.set("GetTime", lua.create_function(get_time)?)?;
|
||||
globals.set("StripEscapes", lua.create_function(strip_escapes)?)?;
|
||||
globals.set("Exit", lua.create_function(exit)?)?;
|
||||
globals.set("Restart", lua.create_function(restart)?)?;
|
||||
globals.set("OpenURL", lua.create_function(open_url)?)?;
|
||||
globals.set("RenderInit", lua.create_function(render_init)?)?;
|
||||
|
||||
let take_screenshot = |_: &Lua, ()| -> LuaResult<()> { Ok(()) }; // stub
|
||||
globals.set("TakeScreenshot", lua.create_function(take_screenshot)?)?;
|
||||
|
||||
// compression
|
||||
globals.set("Inflate", lua.create_function(inflate)?)?;
|
||||
globals.set("Deflate", lua.create_function(deflate)?)?;
|
||||
|
||||
// search handle
|
||||
globals.set("NewFileSearch", lua.create_function(new_search_handle)?)?;
|
||||
|
||||
// image handle
|
||||
register_image_handle_api(lua)?;
|
||||
|
||||
// clipboard
|
||||
globals.set("Copy", lua.create_function(copy)?)?;
|
||||
globals.set("Paste", lua.create_function(paste)?)?;
|
||||
|
||||
// input
|
||||
globals.set("GetCursorPos", lua.create_function(get_cursor_pos)?)?;
|
||||
globals.set("IsKeyDown", lua.create_function(is_key_down)?)?;
|
||||
|
||||
// window
|
||||
globals.set("GetScreenSize", lua.create_function(get_screen_size)?)?;
|
||||
globals.set("GetScreenScale", lua.create_function(get_screen_scale)?)?;
|
||||
globals.set("SetWindowTitle", lua.create_function(set_window_title)?)?;
|
||||
globals.set("SetForeground", lua.create_function(set_foreground)?)?;
|
||||
globals.set(
|
||||
"SetDPIScaleOverridePercent",
|
||||
lua.create_function(set_dpi_scale_override)?,
|
||||
)?;
|
||||
globals.set(
|
||||
"GetDPIScaleOverridePercent",
|
||||
lua.create_function(get_dpi_scale_override)?,
|
||||
)?;
|
||||
|
||||
// lua
|
||||
globals.set("PCall", lua.create_function(protected_call)?)?;
|
||||
globals.set("LoadModule", lua.create_function(load_module)?)?;
|
||||
globals.set("PLoadModule", lua.create_function(protected_load_module)?)?;
|
||||
|
||||
// subscripts
|
||||
globals.set(
|
||||
"LaunchSubScript",
|
||||
lua.create_function_mut(launch_subscript)?,
|
||||
)?;
|
||||
globals.set(
|
||||
"IsSubScriptRunning",
|
||||
lua.create_function(is_subscript_running)?,
|
||||
)?;
|
||||
globals.set("AbortSubScript", lua.create_function(abort_subscript)?)?;
|
||||
|
||||
// NOTE: not used by PoB
|
||||
let set_cursor_pos = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
let show_cursor = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
globals.set("SetCursorPos", lua.create_function(set_cursor_pos)?)?;
|
||||
globals.set("ShowCursor", lua.create_function(show_cursor)?)?;
|
||||
|
||||
// rendering
|
||||
rendering::register_globals(lua)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_time(_l: &Lua, _: ()) -> LuaResult<u128> {
|
||||
Ok(SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis())
|
||||
}
|
||||
|
||||
fn strip_escapes(_: &Lua, text: String) -> LuaResult<String> {
|
||||
Ok(PoBString(&text).strip_escapes())
|
||||
}
|
||||
|
||||
fn exit(l: &Lua, exit_msg: Option<String>) -> LuaResult<()> {
|
||||
if let Some(exit_msg) = exit_msg {
|
||||
println!("{exit_msg}");
|
||||
}
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
ctx.should_exit = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restart(l: &Lua, _: ()) -> LuaResult<()> {
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
ctx.needs_restart = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_url(l: &Lua, url: String) -> LuaResult<MultiValue> {
|
||||
match open::that(url) {
|
||||
Ok(_) => ().into_lua_multi(l),
|
||||
Err(_) => "Unable to open url!".into_lua_multi(l),
|
||||
}
|
||||
}
|
||||
|
||||
fn render_init(l: &Lua, features: Variadic<String>) -> LuaResult<()> {
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
ctx.is_dpi_aware = features.iter().any(|feat| feat == "DPI_AWARE");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
use mlua::{FromLuaMulti, Function, IntoLuaMulti, 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());
|
||||
}
|
||||
// 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 '{name}' not found").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)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn call_callback<A, R>(lua: &Lua, name: &str, args: A) -> LuaResult<R>
|
||||
where
|
||||
A: IntoLuaMulti,
|
||||
R: FromLuaMulti,
|
||||
{
|
||||
get_callback(lua, name)?.call(args)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use crate::pob::Context;
|
||||
use mlua::{Lua, Result as LuaResult};
|
||||
|
||||
pub fn copy(l: &Lua, text: String) -> LuaResult<()> {
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
ctx.window_state.set_clipboard_text(text);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn paste(l: &Lua, _: ()) -> LuaResult<Option<String>> {
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
Ok(ctx.window_state.get_clipboard_text())
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use flate2::{
|
||||
Compression,
|
||||
read::{ZlibDecoder, ZlibEncoder},
|
||||
};
|
||||
use mlua::{IntoLuaMulti, Lua, LuaString, MultiValue, Result as LuaResult, 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 (Value::Nil, "Input larger than 128 MiB").into_lua_multi(l);
|
||||
}
|
||||
|
||||
let mut decoder = ZlibDecoder::new(compressed_bytes);
|
||||
let mut decompressed = Vec::new();
|
||||
match decoder.read_to_end(&mut decompressed) {
|
||||
Ok(_) => l.create_string(&decompressed).unwrap().into_lua_multi(l),
|
||||
Err(e) => (Value::Nil, e.to_string()).into_lua_multi(l),
|
||||
}
|
||||
}
|
||||
|
||||
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 (Value::Nil, "Input larger than 128 MiB").into_lua_multi(l);
|
||||
}
|
||||
|
||||
let mut encoder = ZlibEncoder::new(uncompressed_bytes, Compression::fast());
|
||||
let mut compressed = Vec::new();
|
||||
match encoder.read_to_end(&mut compressed) {
|
||||
Ok(_) => l.create_string(&compressed).unwrap().into_lua_multi(l),
|
||||
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(())
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
use std::{
|
||||
ffi::{CStr, c_int},
|
||||
ptr,
|
||||
};
|
||||
|
||||
use mlua::{Lua, Result as LuaResult, ffi};
|
||||
|
||||
use crate::{
|
||||
pob::Context,
|
||||
renderer::textures::{TextureHandle, TextureId, TextureOptions},
|
||||
};
|
||||
|
||||
pub struct ImageHandle {
|
||||
texture: Option<TextureHandle>,
|
||||
}
|
||||
|
||||
impl ImageHandle {
|
||||
#[inline]
|
||||
pub const fn new() -> Self {
|
||||
Self { texture: None }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn texture_id(&self) -> Option<TextureId> {
|
||||
self.texture.as_ref().map(TextureHandle::id)
|
||||
}
|
||||
|
||||
#[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
|
||||
}
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn image_size(&self) -> [usize; 2] {
|
||||
match &self.texture {
|
||||
Some(texture) => texture.size(),
|
||||
None => [0, 0],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
/// Gets 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::<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;
|
||||
|
||||
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.borrow().update_texture(
|
||||
texture_handle.id(),
|
||||
path,
|
||||
options,
|
||||
is_async,
|
||||
);
|
||||
}
|
||||
None => {
|
||||
if let Ok(texture_handle) = ctx
|
||||
.texture_manager
|
||||
.borrow()
|
||||
.load_texture(path, options, is_async)
|
||||
{
|
||||
handle.texture = Some(texture_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(())
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
use crate::{
|
||||
input::{str_as_key, str_as_mousebutton},
|
||||
pob::Context,
|
||||
};
|
||||
use mlua::{Lua, Result as LuaResult};
|
||||
|
||||
pub fn get_cursor_pos(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
let pos = ctx.input_state.mouse_pos();
|
||||
Ok((pos.x as u32, pos.y as u32))
|
||||
}
|
||||
|
||||
pub fn is_key_down(l: &Lua, key_name: String) -> LuaResult<bool> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
|
||||
if let Some(key) = str_as_key(&key_name) {
|
||||
Ok(ctx.input_state.key_pressed(&key))
|
||||
} else if let Some(button) = str_as_mousebutton(&key_name) {
|
||||
Ok(ctx.input_state.mouse_pressed(button))
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use crate::{pob::Context, 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) => err.to_string().into_lua_multi(l),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
|
||||
let script_dir = {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
ctx.script_dir.to_owned()
|
||||
};
|
||||
let mut module_path = script_dir.join(name);
|
||||
if module_path.extension().is_none() {
|
||||
module_path.set_extension("lua");
|
||||
}
|
||||
|
||||
let current_dir = env::current_dir()?;
|
||||
change_working_directory(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 script_dir = {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
ctx.script_dir.to_owned()
|
||||
};
|
||||
let mut module_path = script_dir.join(name);
|
||||
if module_path.extension().is_none() {
|
||||
module_path.set_extension("lua");
|
||||
}
|
||||
|
||||
let current_dir = env::current_dir()?;
|
||||
change_working_directory(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) => err.to_string().into_lua_multi(l),
|
||||
};
|
||||
change_working_directory(current_dir)?;
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
use crate::{
|
||||
pob::Context,
|
||||
util::{change_working_directory, get_executable_dir},
|
||||
};
|
||||
|
||||
pub fn get_user_path(l: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
Ok(ctx.script_dir.join("userdata"))
|
||||
}
|
||||
|
||||
// parent directory of Launch.lua script
|
||||
pub fn get_script_path(l: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
Ok(ctx.script_dir.to_owned())
|
||||
}
|
||||
|
||||
// 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 ctx = l.app_data_ref::<Context>().unwrap();
|
||||
Ok(ctx.current_working_dir.to_owned())
|
||||
}
|
||||
|
||||
// NOTE: unused
|
||||
pub fn set_work_dir(l: &Lua, path: String) -> LuaResult<()> {
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
if change_working_directory(&path).is_ok() {
|
||||
ctx.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(_) => (true).into_lua_multi(l),
|
||||
// otherwise it is set to Nil and second return value is set to error msg
|
||||
Err(err) => (Value::Nil, err.to_string()).into_lua_multi(l),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove_dir(l: &Lua, (path, recursive): (String, Option<bool>)) -> LuaResult<MultiValue> {
|
||||
let result = if recursive.unwrap_or(false) {
|
||||
fs::remove_dir_all(&path)
|
||||
} else {
|
||||
fs::remove_dir(&path)
|
||||
};
|
||||
match result {
|
||||
Ok(_) => (true).into_lua_multi(l),
|
||||
Err(err) => (Value::Nil, err.to_string()).into_lua_multi(l),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,688 @@
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::{ConvertToLogical, ConvertToPhysical, LogicalPoint},
|
||||
fonts::{Alignment, FontStyle, LayoutJob},
|
||||
math::{Point, Quad, Rect, Size},
|
||||
pob::Context,
|
||||
pob::api::image_handle::image_handle_texture_id,
|
||||
};
|
||||
use core::ffi::c_int;
|
||||
use mlua::{
|
||||
Lua, Result as LuaResult,
|
||||
ffi::{self},
|
||||
};
|
||||
use parley::{FontFamily, FontFamilyName};
|
||||
use regex::Regex;
|
||||
use std::{borrow::Cow, 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
|
||||
// thousands of times per frame. C functions are used to get raw access to
|
||||
// the lua stack without the overhead.
|
||||
unsafe { globals.set("SetDrawColor", lua.create_c_function(set_draw_color)?)? };
|
||||
unsafe { globals.set("GetDrawColor", lua.create_c_function(get_draw_color)?)? };
|
||||
unsafe { globals.set("SetViewport", lua.create_c_function(set_viewport)?)? };
|
||||
unsafe {
|
||||
globals.set("SetDrawLayer", lua.create_c_function(set_draw_layer)?)?;
|
||||
}
|
||||
unsafe { globals.set("DrawImage", lua.create_c_function(draw_image)?)? };
|
||||
unsafe { globals.set("DrawImageQuad", lua.create_c_function(draw_image_quad)?)? };
|
||||
unsafe {
|
||||
globals.set("DrawString", lua.create_c_function(draw_string)?)?;
|
||||
}
|
||||
unsafe {
|
||||
globals.set("DrawStringWidth", lua.create_c_function(get_string_width)?)?;
|
||||
}
|
||||
globals.set(
|
||||
"DrawStringCursorIndex",
|
||||
lua.create_function_mut(get_index_at_cur)?,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
macro_rules! str_from_stack {
|
||||
($s:ident, $i:expr) => {
|
||||
unsafe {
|
||||
let mut size = 0;
|
||||
let data = ffi::luaL_checklstring($s, $i, &mut size);
|
||||
let bytes = std::slice::from_raw_parts(data as *const u8, size);
|
||||
std::str::from_utf8_unchecked(bytes)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! f32_from_stack {
|
||||
($s:ident, $i:expr) => {
|
||||
unsafe { ffi::luaL_checknumber($s, $i) } as f32
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! i32_from_stack {
|
||||
($s:ident, $i:expr) => {
|
||||
unsafe { ffi::luaL_checkinteger($s, $i) } as i32
|
||||
};
|
||||
}
|
||||
|
||||
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 mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
match nargs {
|
||||
// escape_code
|
||||
1 => {
|
||||
let esc_str = str_from_stack!(state, -nargs);
|
||||
let color = Srgba::from_escape_code(esc_str);
|
||||
ctx.recorder.set_draw_color(color);
|
||||
}
|
||||
// rgb
|
||||
3 => {
|
||||
let r = f32_from_stack!(state, -nargs);
|
||||
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);
|
||||
ctx.recorder.set_draw_color(color);
|
||||
}
|
||||
// rgba
|
||||
4 => {
|
||||
let r = f32_from_stack!(state, -nargs);
|
||||
let g = f32_from_stack!(state, -nargs + 1);
|
||||
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);
|
||||
ctx.recorder.set_draw_color(color);
|
||||
}
|
||||
_ => panic!("Unexpected number of arguments"),
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn get_draw_color(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("get_draw_color");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua_instance.app_data_ref::<Context>().unwrap();
|
||||
|
||||
let color: [f32; 4] = ctx.recorder.get_draw_color().into();
|
||||
unsafe { ffi::lua_pushnumber(state, color[0] as f64) };
|
||||
unsafe { ffi::lua_pushnumber(state, color[1] as f64) };
|
||||
unsafe { ffi::lua_pushnumber(state, color[2] as f64) };
|
||||
unsafe { ffi::lua_pushnumber(state, color[3] as f64) };
|
||||
|
||||
4
|
||||
}
|
||||
|
||||
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 mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
match nargs {
|
||||
0 => ctx.set_recorder_viewport_to_window_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));
|
||||
ctx.recorder.set_viewport(rect);
|
||||
}
|
||||
_ => panic!("Unexpected number of arguments"),
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
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 mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
match nargs {
|
||||
1 => {
|
||||
let layer = i32_from_stack!(state, -nargs);
|
||||
ctx.recorder.set_draw_layer(layer, 0);
|
||||
}
|
||||
2 => {
|
||||
let layer = match unsafe { ffi::lua_type(state, -nargs) } {
|
||||
ffi::LUA_TNIL => None,
|
||||
ffi::LUA_TNUMBER => {
|
||||
let layer = i32_from_stack!(state, -nargs);
|
||||
Some(layer)
|
||||
}
|
||||
t => panic!("Expected Nil or Number, got {:?}", t),
|
||||
};
|
||||
let sublayer = i32_from_stack!(state, -nargs + 1);
|
||||
if let Some(layer) = layer {
|
||||
ctx.recorder.set_draw_layer(layer, sublayer);
|
||||
} else {
|
||||
ctx.recorder.set_draw_sublayer(sublayer);
|
||||
}
|
||||
}
|
||||
_ => panic!("Unexpected number of arguments"),
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
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 mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
if !matches!(nargs, 5 | 6 | 7 | 9 | 10 | 11) {
|
||||
panic!("Unexpected number of arguments");
|
||||
}
|
||||
|
||||
#[allow(clippy::manual_range_patterns)]
|
||||
let parse_uv = matches!(nargs, 9 | 10 | 11);
|
||||
let parse_layer_idx = matches!(nargs, 6 | 7 | 10 | 11);
|
||||
|
||||
let texture_id = unsafe { image_handle_texture_id(state, -nargs) };
|
||||
|
||||
// left, top, width, height
|
||||
let x = f32_from_stack!(state, -nargs + 1);
|
||||
let y = f32_from_stack!(state, -nargs + 2);
|
||||
let w = f32_from_stack!(state, -nargs + 3);
|
||||
let h = f32_from_stack!(state, -nargs + 4);
|
||||
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
|
||||
|
||||
// u1, v1, u2, v2
|
||||
let mut i = 5;
|
||||
let uv = if parse_uv {
|
||||
let u1 = f32_from_stack!(state, -nargs + i);
|
||||
let v1 = f32_from_stack!(state, -nargs + i + 1);
|
||||
let u2 = f32_from_stack!(state, -nargs + i + 2);
|
||||
let v2 = f32_from_stack!(state, -nargs + i + 3);
|
||||
i += 4;
|
||||
Some(Rect::new(Point::new(u1, v1), Point::new(u2, v2)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let layer_idx = if parse_layer_idx {
|
||||
let layer_idx = i32_from_stack!(state, -nargs + i);
|
||||
(layer_idx - 1) as u32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
ctx.recorder.draw_image(rect, texture_id, uv, layer_idx);
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("draw_image_quad");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
if !matches!(nargs, 9 | 10 | 11 | 17 | 18 | 19) {
|
||||
panic!("Unexpected number of arguments");
|
||||
}
|
||||
|
||||
#[allow(clippy::manual_range_patterns)]
|
||||
let parse_uv = matches!(nargs, 17 | 18 | 19);
|
||||
let parse_layer_idx = matches!(nargs, 10 | 11 | 18 | 19);
|
||||
|
||||
let texture_id = unsafe { image_handle_texture_id(state, -nargs) };
|
||||
|
||||
// x1, y1, x2, y2, ...
|
||||
let x1 = f32_from_stack!(state, -nargs + 1);
|
||||
let y1 = f32_from_stack!(state, -nargs + 2);
|
||||
let x2 = f32_from_stack!(state, -nargs + 3);
|
||||
let y2 = f32_from_stack!(state, -nargs + 4);
|
||||
let x3 = f32_from_stack!(state, -nargs + 5);
|
||||
let y3 = f32_from_stack!(state, -nargs + 6);
|
||||
let x4 = f32_from_stack!(state, -nargs + 7);
|
||||
let y4 = f32_from_stack!(state, -nargs + 8);
|
||||
let quad = Quad::new(
|
||||
Point::new(x1, y1),
|
||||
Point::new(x2, y2),
|
||||
Point::new(x3, y3),
|
||||
Point::new(x4, y4),
|
||||
);
|
||||
|
||||
// u1, v1, u2, v2, ...
|
||||
let mut i = 9;
|
||||
let uv = if parse_uv {
|
||||
let u1 = f32_from_stack!(state, -nargs + i);
|
||||
let v1 = f32_from_stack!(state, -nargs + i + 1);
|
||||
let u2 = f32_from_stack!(state, -nargs + i + 2);
|
||||
let v2 = f32_from_stack!(state, -nargs + i + 3);
|
||||
let u3 = f32_from_stack!(state, -nargs + i + 4);
|
||||
let v3 = f32_from_stack!(state, -nargs + i + 5);
|
||||
let u4 = f32_from_stack!(state, -nargs + i + 6);
|
||||
let v4 = f32_from_stack!(state, -nargs + i + 7);
|
||||
i += 8;
|
||||
Some(Quad::new(
|
||||
Point::new(u1, v1),
|
||||
Point::new(u2, v2),
|
||||
Point::new(u3, v3),
|
||||
Point::new(u4, v4),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let layer_idx = if parse_layer_idx {
|
||||
let layer_idx = i32_from_stack!(state, -nargs + i);
|
||||
(layer_idx - 1) as u32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
ctx.recorder
|
||||
.draw_image_quad(quad, texture_id, 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 mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
let x = f32_from_stack!(state, -nargs);
|
||||
let y = f32_from_stack!(state, -nargs + 1);
|
||||
let alignment = str_from_stack!(state, -nargs + 2);
|
||||
let line_height = i32_from_stack!(state, -nargs + 3);
|
||||
let font_type = str_from_stack!(state, -nargs + 4);
|
||||
let text = str_from_stack!(state, -nargs + 5);
|
||||
|
||||
let Ok(alignment) = alignment.parse::<PoBTextAlignment>() else {
|
||||
panic!("Invalid alignment");
|
||||
};
|
||||
let Ok(font_type) = font_type.parse::<PoBFontType>() else {
|
||||
panic!("Invalid font type");
|
||||
};
|
||||
|
||||
let mut position = LogicalPoint::new(x, y);
|
||||
let mut is_absolute_position = false;
|
||||
// the position needs to be adjusted for some alignments to match PoBs behavior
|
||||
let screen_size = ctx.window_state.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,
|
||||
};
|
||||
|
||||
let current_draw_color = ctx.recorder.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.recorder.set_draw_color(last_segment.color);
|
||||
}
|
||||
|
||||
// Align layout origin with the physical pixel grid to reduce blurriness
|
||||
let pixels_per_point = ctx.window_state.scale_factor();
|
||||
let position = position
|
||||
.to_physical::<f32, _>(pixels_per_point)
|
||||
.round()
|
||||
.to_logical(pixels_per_point);
|
||||
|
||||
let layout = ctx.fonts.borrow_mut().layout(job, pixels_per_point);
|
||||
for glyph in &layout.glyphs {
|
||||
ctx.recorder.draw_glyph(
|
||||
glyph.rect.translate(position.to_vector()),
|
||||
glyph.uv,
|
||||
glyph.color,
|
||||
glyph.layer_idx,
|
||||
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 ctx = lua_instance.app_data_ref::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
let line_height = i32_from_stack!(state, -nargs);
|
||||
let font_type = str_from_stack!(state, -nargs + 1);
|
||||
let text = str_from_stack!(state, -nargs + 2);
|
||||
|
||||
let Ok(font_type) = font_type.parse::<PoBFontType>() else {
|
||||
panic!("Invalid font type");
|
||||
};
|
||||
|
||||
let job = build_layout_job(text, Srgba::WHITE, font_type, line_height, None);
|
||||
let layout = ctx
|
||||
.fonts
|
||||
.borrow_mut()
|
||||
.layout(job, ctx.window_state.scale_factor());
|
||||
let width = layout.width();
|
||||
|
||||
unsafe { ffi::lua_pushnumber(state, width as f64) };
|
||||
1
|
||||
}
|
||||
|
||||
fn get_index_at_cur(
|
||||
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 ctx = l.app_data_ref::<Context>().unwrap();
|
||||
|
||||
let font_type = font_type.parse::<PoBFontType>()?;
|
||||
|
||||
let job = build_layout_job(&text, Srgba::WHITE, font_type, line_height, None);
|
||||
let layout = ctx
|
||||
.fonts
|
||||
.borrow_mut()
|
||||
.layout(job, ctx.window_state.scale_factor());
|
||||
let index_stripped = layout.cursor_index_at(Point::new(cur_x, cur_y));
|
||||
|
||||
// build_layout_job() strips all color escape strings from the original string. The
|
||||
// resulting [`LayoutJob`] is then passed to get_text_index_at_cursor() which returns an
|
||||
// index into the **stripped* string.
|
||||
// But PoB expects an index into the **original, unstripped** text. Therefore we need to add
|
||||
// the length of all color escapes up until the cursor position to return the right value.
|
||||
//
|
||||
// TODO: avoid matching and iterating over string twice
|
||||
let mut color_escapes_total_length = 0;
|
||||
for capture in ESCAPE_STR_REGEX.find_iter(&text) {
|
||||
if capture.start() - color_escapes_total_length > index_stripped {
|
||||
break;
|
||||
}
|
||||
color_escapes_total_length += capture.len();
|
||||
}
|
||||
|
||||
// add length of color escapes and convert to lua's 1-based indexing
|
||||
Ok(index_stripped + color_escapes_total_length + 1)
|
||||
}
|
||||
|
||||
pub static ESCAPE_STR_REGEX: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"\^(?<idx>[0-9])|\^[xX](?<hex>[0-9A-Fa-f]{6})").unwrap());
|
||||
|
||||
fn build_layout_job<'a>(
|
||||
text: &'a str,
|
||||
current_color: Srgba,
|
||||
font_type: PoBFontType,
|
||||
line_height: i32,
|
||||
alignment: Option<Alignment>,
|
||||
) -> LayoutJob<'a> {
|
||||
let mut font_weight = None;
|
||||
let mut font_style = FontStyle::default();
|
||||
let font_family = match font_type {
|
||||
PoBFontType::Fixed => FontFamily::Single(FontFamilyName::Named(Cow::Borrowed(
|
||||
"Bitstream Vera Sans Mono",
|
||||
))),
|
||||
PoBFontType::Var => {
|
||||
FontFamily::Single(FontFamilyName::Named(Cow::Borrowed("Liberation Sans")))
|
||||
}
|
||||
PoBFontType::VarBold => {
|
||||
font_weight = Some(700.0);
|
||||
FontFamily::Single(FontFamilyName::Named(Cow::Borrowed("Liberation Sans")))
|
||||
}
|
||||
PoBFontType::Fontin => FontFamily::Single(FontFamilyName::Named(Cow::Borrowed("Fontin"))),
|
||||
PoBFontType::FontinItalic => {
|
||||
FontFamily::Single(FontFamilyName::Named(Cow::Borrowed("Fontin")))
|
||||
}
|
||||
PoBFontType::FontinSmallcaps => {
|
||||
FontFamily::Single(FontFamilyName::Named(Cow::Borrowed("Fontin SmallCaps")))
|
||||
}
|
||||
PoBFontType::FontinSmallcapsItalic => {
|
||||
font_style = FontStyle::Italic;
|
||||
// use regular Smallcaps with "faux italics"
|
||||
FontFamily::Single(FontFamilyName::Named(Cow::Borrowed("Fontin SmallCaps")))
|
||||
}
|
||||
};
|
||||
|
||||
// NOTE: This is just an approximation and was chosen based on how it looks.
|
||||
//
|
||||
// PoB uses pre-rendered font atlases of discrete sizes and selects the appropriate
|
||||
// atlas based on the provided height. Rusty-PoB dynamically renders fonts to a
|
||||
// cached font atlas to support the selection of arbitrary sizes.
|
||||
//
|
||||
// TODO: font size in some dropdowns is too small, e.g. socket group selection in
|
||||
// 'Calcs' tab
|
||||
let font_size = (line_height - 2).max(1) as f32;
|
||||
|
||||
let mut job = LayoutJob::new(
|
||||
font_family,
|
||||
font_size,
|
||||
line_height as f32,
|
||||
alignment,
|
||||
font_weight,
|
||||
font_style,
|
||||
);
|
||||
|
||||
for (color, segment) in PoBString(text) {
|
||||
job.append(segment, color.unwrap_or(current_color));
|
||||
}
|
||||
|
||||
job
|
||||
}
|
||||
|
||||
// PoB strings can contain escape codes that affect the color of subsequent text
|
||||
pub struct PoBString<'a>(pub &'a str);
|
||||
|
||||
impl<'a> PoBString<'a> {
|
||||
pub fn strip_escapes(&self) -> String {
|
||||
ESCAPE_STR_REGEX.replace_all(self.0, "").to_string()
|
||||
}
|
||||
}
|
||||
|
||||
type ColoredSegment<'a> = (Option<Srgba>, &'a str);
|
||||
|
||||
impl<'a> IntoIterator for PoBString<'a> {
|
||||
type Item = ColoredSegment<'a>;
|
||||
type IntoIter = PoBStringSegmentIterator<'a>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
PoBStringSegmentIterator::new(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
// Iterates over colored segments
|
||||
pub struct PoBStringSegmentIterator<'a> {
|
||||
haystack: &'a str,
|
||||
captures: std::iter::Peekable<regex::CaptureMatches<'static, 'a>>,
|
||||
is_first: bool,
|
||||
is_done: bool,
|
||||
}
|
||||
|
||||
impl<'a> PoBStringSegmentIterator<'a> {
|
||||
fn new(haystack: &'a str) -> Self {
|
||||
let captures = ESCAPE_STR_REGEX.captures_iter(haystack).peekable();
|
||||
Self {
|
||||
haystack,
|
||||
captures,
|
||||
is_first: true,
|
||||
is_done: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for PoBStringSegmentIterator<'a> {
|
||||
type Item = ColoredSegment<'a>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let is_first = core::mem::replace(&mut self.is_first, false);
|
||||
|
||||
match self.captures.peek() {
|
||||
Some(capture) => {
|
||||
let code_start = capture.get(0).unwrap().start();
|
||||
let code_end = capture.get(0).unwrap().end();
|
||||
|
||||
// string didn't start with an escape code.
|
||||
// return text up to first code without color.
|
||||
if is_first && code_start > 0 {
|
||||
return Some((None, &self.haystack[..code_start]));
|
||||
}
|
||||
|
||||
let escape_str = capture.get(0).unwrap().as_str();
|
||||
let color = Some(Srgba::from_escape_code(escape_str));
|
||||
|
||||
let _ = self.captures.next(); // pop current code to peek the next one
|
||||
match self.captures.peek() {
|
||||
Some(next_code) => {
|
||||
// found another escape code. return text up the next code
|
||||
let next_code_start = next_code.get(0).unwrap().start();
|
||||
Some((color, &self.haystack[code_end..next_code_start]))
|
||||
}
|
||||
None => {
|
||||
// no additional escape codes found. return rest of string
|
||||
self.is_done = true;
|
||||
Some((color, &self.haystack[code_end..]))
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if self.is_done {
|
||||
None
|
||||
} else {
|
||||
// string doesn't contain any escape codes.
|
||||
// return entire string without color
|
||||
self.is_done = true;
|
||||
Some((None, self.haystack))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PoB's text alignment is weird
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum PoBTextAlignment {
|
||||
// left-aligned, x coordinate describes top-left corner
|
||||
Left,
|
||||
// centered in screen space, x coordinate describes offset of text center
|
||||
// from screen center. positive values of x move text to right, negative to left.
|
||||
Center,
|
||||
// right-aligned in screen space, x coordinate describes distance from right edge
|
||||
// of text to right edge of screen. positive values move text further to left.
|
||||
Right,
|
||||
// makes text centered around position, i.e. position.x = horizontal center of text
|
||||
CenterX,
|
||||
// makes text right-aligned to position, i.e. position.x = right edge of text
|
||||
RightX,
|
||||
}
|
||||
|
||||
impl std::str::FromStr for PoBTextAlignment {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"LEFT" => Ok(Self::Left),
|
||||
"CENTER" => Ok(Self::Center),
|
||||
"RIGHT" => Ok(Self::Right),
|
||||
"CENTER_X" => Ok(Self::CenterX),
|
||||
"RIGHT_X" => Ok(Self::RightX),
|
||||
_ => Err(anyhow::anyhow!("'{s}' is not a valid TextFontType variant")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum PoBFontType {
|
||||
Fixed,
|
||||
Var,
|
||||
VarBold,
|
||||
FontinSmallcaps,
|
||||
FontinSmallcapsItalic,
|
||||
Fontin,
|
||||
FontinItalic,
|
||||
}
|
||||
|
||||
impl std::str::FromStr for PoBFontType {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"FIXED" => Ok(Self::Fixed),
|
||||
"VAR" => Ok(Self::Var),
|
||||
"VAR BOLD" => Ok(Self::VarBold),
|
||||
"FONTIN SC" => Ok(Self::FontinSmallcaps),
|
||||
"FONTIN SC ITALIC" => Ok(Self::FontinSmallcapsItalic),
|
||||
"FONTIN" => Ok(Self::Fontin),
|
||||
"FONTIN ITALIC" => Ok(Self::FontinItalic),
|
||||
_ => Err(anyhow::anyhow!("'{s}' is not a valid TextFontType variant")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn hex_byte(a: u8, b: u8) -> u8 {
|
||||
(hex_digit(a) << 4) | hex_digit(b)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn hex_digit(c: u8) -> u8 {
|
||||
match c {
|
||||
b'0'..=b'9' => c - b'0',
|
||||
b'a'..=b'f' => c - b'a' + 10,
|
||||
b'A'..=b'F' => c - b'A' + 10,
|
||||
_ => unreachable!("invalid hex digit"),
|
||||
}
|
||||
}
|
||||
|
||||
impl Srgba {
|
||||
fn from_escape_code(escape_str: &str) -> Srgba {
|
||||
let bytes = escape_str.as_bytes();
|
||||
|
||||
match bytes {
|
||||
[b'^', b'0'] => Self::from_rgb(0, 0, 0),
|
||||
[b'^', b'1'] => Self::from_rgb(255, 0, 0),
|
||||
[b'^', b'2'] => Self::from_rgb(0, 255, 0),
|
||||
[b'^', b'3'] => Self::from_rgb(0, 0, 255),
|
||||
[b'^', b'4'] => Self::from_rgb(255, 255, 0),
|
||||
[b'^', b'5'] => Self::from_rgb(255, 0, 255),
|
||||
[b'^', b'6'] => Self::from_rgb(0, 255, 255),
|
||||
[b'^', b'7'] => Self::from_rgb(255, 255, 255),
|
||||
[b'^', b'8'] => Self::from_rgb(178, 178, 178),
|
||||
[b'^', b'9'] => Self::from_rgb(102, 102, 102),
|
||||
|
||||
[b'^', b'x' | b'X', r1, r2, g1, g2, b1, b2] => {
|
||||
Self::from_rgb(hex_byte(*r1, *r2), hex_byte(*g1, *g2), hex_byte(*b1, *b2))
|
||||
}
|
||||
|
||||
_ => Self::WHITE,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
use glob::{Paths, glob};
|
||||
use mlua::{IntoLua, Lua, Result as LuaResult, UserData, Value};
|
||||
use std::{
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
time::SystemTime,
|
||||
};
|
||||
|
||||
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,
|
||||
// only yield directories if true, otherwise only files
|
||||
directories_only: bool,
|
||||
pub current: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl SearchHandle {
|
||||
pub fn new(paths: Paths, directories_only: bool) -> Self {
|
||||
Self {
|
||||
paths,
|
||||
directories_only,
|
||||
current: None,
|
||||
}
|
||||
}
|
||||
|
||||
// sets current to the next file/directory if it exists and doesn't cause errors,
|
||||
// otherwise None
|
||||
pub fn next(&mut self) {
|
||||
self.current = self
|
||||
.paths
|
||||
.find(|candidate| {
|
||||
candidate
|
||||
.as_ref()
|
||||
.is_ok_and(|c| c.is_dir() == self.directories_only)
|
||||
})
|
||||
.transpose()
|
||||
.ok()
|
||||
.flatten();
|
||||
}
|
||||
}
|
||||
|
||||
impl UserData for SearchHandle {
|
||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_method_mut("NextFile", |_, this, ()| {
|
||||
this.next();
|
||||
Ok(this.current.is_some())
|
||||
});
|
||||
methods.add_method_mut("GetFileName", |l, this, ()| {
|
||||
Ok(this.current.as_ref().unwrap().file_name().into_lua(l))
|
||||
});
|
||||
methods.add_method("GetFileSize", |_, this, ()| match &this.current {
|
||||
Some(path) => match fs::metadata(path) {
|
||||
Ok(metadata) => Ok(metadata.len()),
|
||||
Err(_) => Ok(0),
|
||||
},
|
||||
None => Ok(0),
|
||||
});
|
||||
methods.add_method("GetFileModifiedTime", |_, this, ()| match &this.current {
|
||||
Some(path) => get_time_modified(path).map_or(Ok(0), Ok),
|
||||
None => Ok(0),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn get_time_modified<P: AsRef<Path>>(path: P) -> anyhow::Result<u64> {
|
||||
let metadata = fs::metadata(path)?;
|
||||
let modified_time = metadata.modified()?;
|
||||
let duration_since_epoch = modified_time.duration_since(SystemTime::UNIX_EPOCH)?;
|
||||
let seconds_since_epoch = duration_since_epoch.as_secs();
|
||||
Ok(seconds_since_epoch)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use mlua::{Lua, MultiValue, Result as LuaResult};
|
||||
|
||||
use crate::pob::Context;
|
||||
|
||||
pub fn launch_subscript(
|
||||
l: &Lua,
|
||||
(script_text, func_list, sub_list, args): (String, String, String, MultiValue),
|
||||
) -> LuaResult<u64> {
|
||||
let blocking_calls = func_list
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|&s| !s.is_empty())
|
||||
.map(String::from)
|
||||
.collect();
|
||||
let nonblocking_calls = sub_list
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|&s| !s.is_empty())
|
||||
.map(String::from)
|
||||
.collect();
|
||||
let arguments = args.try_into()?;
|
||||
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
let script_dir = ctx.script_dir.to_owned();
|
||||
let subscript_id = ctx.subscript_manager.borrow_mut().push(
|
||||
script_dir,
|
||||
script_text,
|
||||
blocking_calls,
|
||||
nonblocking_calls,
|
||||
arguments,
|
||||
);
|
||||
|
||||
Ok(subscript_id)
|
||||
}
|
||||
|
||||
pub fn is_subscript_running(l: &Lua, subscript_id: u64) -> LuaResult<bool> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
Ok(ctx.subscript_manager.borrow().is_running(subscript_id))
|
||||
}
|
||||
|
||||
pub fn abort_subscript(_: &Lua, _subscript_id: u64) -> LuaResult<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use crate::{
|
||||
dpi::{LogicalSize, PhysicalSize},
|
||||
pob::Context,
|
||||
};
|
||||
use mlua::{Lua, Result as LuaResult};
|
||||
|
||||
pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
let size = if ctx.is_dpi_aware {
|
||||
let PhysicalSize { width, height, .. } = ctx.window_state.size;
|
||||
(width, height)
|
||||
} else {
|
||||
let LogicalSize { width, height, .. } = ctx.window_state.logical_size();
|
||||
(width, height)
|
||||
};
|
||||
Ok(size)
|
||||
}
|
||||
|
||||
pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult<f32> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
let scale_factor = ctx.window_state.scale_factor();
|
||||
Ok(scale_factor)
|
||||
}
|
||||
|
||||
pub fn set_window_title(l: &Lua, title: String) -> LuaResult<()> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
ctx.window_state.set_window_title(&title);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_foreground(l: &Lua, _: ()) -> LuaResult<()> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
ctx.window_state.focus();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_dpi_scale_override(l: &Lua, percent: i32) -> LuaResult<()> {
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
match percent {
|
||||
0 => ctx.window_state.scale_factor_override = None,
|
||||
p if p > 0 => ctx.window_state.scale_factor_override = Some(p as f32 / 100.0),
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_dpi_scale_override(l: &Lua, _: ()) -> LuaResult<i32> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
match ctx.window_state.scale_factor_override {
|
||||
Some(scale_factor) => Ok((scale_factor * 100.0) as i32),
|
||||
None => Ok(0),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
use crate::{pob::PathOfBuilding, pob::api::get_callback};
|
||||
use anyhow::{Result, anyhow};
|
||||
use mlua::{Function, Integer, IntoLuaMulti, Lua, MultiValue, Number, Value};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
path::PathBuf,
|
||||
sync::mpsc::{Receiver, Sender, TryRecvError, channel},
|
||||
thread::JoinHandle,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SubscriptResult {
|
||||
SubscriptFinished {
|
||||
id: u64,
|
||||
return_values: NativeMultiValue,
|
||||
},
|
||||
SubscriptError {
|
||||
id: u64,
|
||||
error: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct SubscriptManager {
|
||||
current_id: u64,
|
||||
scripts: Vec<Subscript>,
|
||||
}
|
||||
|
||||
impl SubscriptManager {
|
||||
pub fn push(
|
||||
&mut self,
|
||||
script_dir: PathBuf,
|
||||
script_text: String,
|
||||
blocking_calls: Vec<String>,
|
||||
nonblocking_calls: Vec<String>,
|
||||
arguments: NativeMultiValue,
|
||||
) -> u64 {
|
||||
let id = self.current_id;
|
||||
self.current_id += 1;
|
||||
|
||||
let subscript = Subscript::new(
|
||||
id,
|
||||
script_text,
|
||||
blocking_calls,
|
||||
nonblocking_calls,
|
||||
arguments,
|
||||
script_dir,
|
||||
);
|
||||
self.scripts.push(subscript);
|
||||
id
|
||||
}
|
||||
|
||||
pub fn process(&mut self, lua: &Lua) -> Vec<SubscriptResult> {
|
||||
let mut results = vec![];
|
||||
|
||||
self.scripts.retain_mut(|subscript| {
|
||||
subscript.handle_calls(lua);
|
||||
|
||||
subscript.try_join().is_none_or(|event| {
|
||||
results.push(event);
|
||||
// subscript has finished or errored, remove it
|
||||
false
|
||||
})
|
||||
});
|
||||
|
||||
results
|
||||
}
|
||||
|
||||
pub fn has_running_subscripts(&self) -> bool {
|
||||
!self.scripts.is_empty()
|
||||
}
|
||||
|
||||
pub fn is_running(&self, subscript_id: u64) -> bool {
|
||||
self.scripts.iter().any(|ss| ss.id == subscript_id)
|
||||
}
|
||||
}
|
||||
|
||||
enum SubscriptCall {
|
||||
Blocking {
|
||||
function_name: String,
|
||||
arguments: NativeMultiValue,
|
||||
// used to send return values of function back to thread
|
||||
return_values_sender: Sender<Result<NativeMultiValue>>,
|
||||
},
|
||||
NonBlocking {
|
||||
function_name: String,
|
||||
arguments: NativeMultiValue,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct Subscript {
|
||||
id: u64,
|
||||
handle: Option<JoinHandle<anyhow::Result<NativeMultiValue>>>,
|
||||
receiver: Receiver<SubscriptCall>,
|
||||
}
|
||||
|
||||
// Subscripts are lua scripts that are executed in their own instance on a separate
|
||||
// thread.
|
||||
//
|
||||
// When a subscript needs to call a function defined in the main instance, a
|
||||
// `SubscriptCall` message is send over a channel. At the beginning of each frame,
|
||||
// the main thread checks for messages and executes the requested function with the
|
||||
// provided arguments on behalf of the subscript.
|
||||
// For `BlockingCall`, the subscript waits for the main thread to send the return
|
||||
// values of the function back over another channel.
|
||||
// For `NonBlockingCall`, the subscript doesn't wait on any return values and keeps
|
||||
// executing the script after sending the message.
|
||||
// Subscripts are required to explicitly specify the names of all (non)-blocking
|
||||
// function calls that appear in the script.
|
||||
impl Subscript {
|
||||
pub fn new(
|
||||
id: u64,
|
||||
script_text: String,
|
||||
blocking_calls: Vec<String>,
|
||||
nonblocking_calls: Vec<String>,
|
||||
arguments: NativeMultiValue,
|
||||
script_dir: PathBuf,
|
||||
) -> Self {
|
||||
let (tx, rx) = channel();
|
||||
|
||||
let handle = std::thread::spawn(move || {
|
||||
profiling::register_thread!(format!("Subscript {} Thread", id));
|
||||
|
||||
// unsafe required to load C modules (curl)
|
||||
let lua = unsafe { Lua::unsafe_new() };
|
||||
|
||||
// add ./lua to package.path and package.cpath
|
||||
// TODO: this is awkward, move package path registration out of PoB?
|
||||
PathOfBuilding::register_package_paths(&lua, &script_dir)?;
|
||||
|
||||
for function_name in blocking_calls {
|
||||
let thread_tx = tx.clone();
|
||||
lua.globals().set(
|
||||
function_name.clone(),
|
||||
lua.create_function(move |_, args: MultiValue| {
|
||||
let (tx_return, rx_return) = channel();
|
||||
thread_tx
|
||||
.send(SubscriptCall::Blocking {
|
||||
function_name: function_name.clone(),
|
||||
arguments: args.try_into()?,
|
||||
return_values_sender: tx_return,
|
||||
})
|
||||
.unwrap();
|
||||
// this blocks until we receive return values
|
||||
let return_values = rx_return.recv().map_err(|e| anyhow!("{e}"))??;
|
||||
Ok(return_values)
|
||||
})?,
|
||||
)?;
|
||||
}
|
||||
|
||||
for function_name in nonblocking_calls {
|
||||
let thread_tx = tx.clone();
|
||||
lua.globals().set(
|
||||
function_name.clone(),
|
||||
lua.create_function(move |_, args: MultiValue| {
|
||||
thread_tx
|
||||
.send(SubscriptCall::NonBlocking {
|
||||
function_name: function_name.clone(),
|
||||
arguments: args.try_into()?,
|
||||
})
|
||||
.map_err(|e| anyhow!("{e}"))?;
|
||||
Ok(())
|
||||
})?,
|
||||
)?;
|
||||
}
|
||||
|
||||
let result = lua.load(script_text).call::<MultiValue>(arguments)?;
|
||||
result.try_into()
|
||||
});
|
||||
|
||||
Self {
|
||||
id,
|
||||
handle: Some(handle),
|
||||
receiver: rx,
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_calls(&mut self, lua: &Lua) {
|
||||
match self.receiver.try_recv() {
|
||||
Ok(SubscriptCall::Blocking {
|
||||
function_name,
|
||||
arguments,
|
||||
return_values_sender,
|
||||
}) => {
|
||||
let func: Result<Function, _> = get_callback(lua, "OnSubCall");
|
||||
match func {
|
||||
Ok(func) => {
|
||||
match func.call::<MultiValue>((function_name, arguments)) {
|
||||
Ok(return_values) => {
|
||||
// send return values back to thread
|
||||
let _ = return_values_sender.send(return_values.try_into());
|
||||
}
|
||||
// function returned error, forward it to thread
|
||||
Err(err) => {
|
||||
let _ = return_values_sender.send(Err(err.into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
// function not found
|
||||
Err(err) => {
|
||||
let _ = return_values_sender.send(Err(err.into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(SubscriptCall::NonBlocking {
|
||||
function_name,
|
||||
arguments,
|
||||
}) => {
|
||||
let func: Result<Function, _> = get_callback(lua, "OnSubCall");
|
||||
if let Ok(func) = func {
|
||||
// we can ignore return values for non-blocking calls
|
||||
let _ = func.call::<()>((function_name, arguments));
|
||||
}
|
||||
}
|
||||
// ignore disconnects. potential errors are handled during thread join
|
||||
Err(TryRecvError::Disconnected) => {}
|
||||
// no outstanding calls from thread
|
||||
Err(TryRecvError::Empty) => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn try_join(&mut self) -> Option<SubscriptResult> {
|
||||
if self.handle.as_ref().is_some_and(JoinHandle::is_finished) {
|
||||
let event = match self.handle.take().unwrap().join() {
|
||||
Ok(Ok(return_values)) => SubscriptResult::SubscriptFinished {
|
||||
id: self.id,
|
||||
return_values,
|
||||
},
|
||||
Ok(Err(err)) => SubscriptResult::SubscriptError {
|
||||
id: self.id,
|
||||
error: err.to_string(),
|
||||
},
|
||||
// the thread panicked
|
||||
Err(_) => SubscriptResult::SubscriptError {
|
||||
id: self.id,
|
||||
error: String::from("Subscript thread panicked!"),
|
||||
},
|
||||
};
|
||||
Some(event)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// used to move arguments and return values between lua instances
|
||||
// some lua values are associated with their instance and using them with another
|
||||
// instance is not allowed.
|
||||
#[derive(Debug)]
|
||||
pub struct NativeMultiValue(VecDeque<NativeValue>);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum NativeValue {
|
||||
Nil,
|
||||
Number(Number),
|
||||
Integer(Integer),
|
||||
Boolean(bool),
|
||||
// Lua strings may not be valid UTF-8, so store Vec<u8> instead
|
||||
String(Vec<u8>),
|
||||
}
|
||||
|
||||
impl TryFrom<MultiValue> for NativeMultiValue {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(values: MultiValue) -> Result<Self, Self::Error> {
|
||||
let native = values
|
||||
.iter()
|
||||
.map(|v| match v.type_name() {
|
||||
"nil" => Ok(NativeValue::Nil),
|
||||
"boolean" => Ok(NativeValue::Boolean(v.as_boolean().unwrap())),
|
||||
"number" => Ok(NativeValue::Number(v.as_number().unwrap())),
|
||||
"integer" => Ok(NativeValue::Integer(v.as_integer().unwrap())),
|
||||
"string" => Ok(NativeValue::String(
|
||||
v.as_string().unwrap().as_bytes().to_vec(),
|
||||
)),
|
||||
_ => Err(anyhow!("Unsupported value type")),
|
||||
})
|
||||
.collect::<Result<VecDeque<_>, _>>()?;
|
||||
|
||||
Ok(Self(native))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoLuaMulti for NativeMultiValue {
|
||||
fn into_lua_multi(self, lua: &Lua) -> mlua::Result<MultiValue> {
|
||||
let values = self
|
||||
.0
|
||||
.iter()
|
||||
.map(|v| match v {
|
||||
NativeValue::Nil => Ok(Value::Nil),
|
||||
NativeValue::Boolean(b) => Ok(Value::Boolean(*b)),
|
||||
NativeValue::Number(n) => Ok(Value::Number(*n)),
|
||||
NativeValue::Integer(n) => Ok(Value::Integer(*n)),
|
||||
NativeValue::String(s) => lua.create_string(s).map(Value::String),
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(MultiValue::from_vec(values))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user