Initial commit
This commit is contained in:
commit
6e1613f73f
48 files changed
+13682
No files matched your search
+396
@@ -0,0 +1,396 @@
|
||||
use std::{
|
||||
fs,
|
||||
io::{Read, Write, stdout},
|
||||
path::PathBuf,
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use anyhow::anyhow;
|
||||
use directories::UserDirs;
|
||||
use flate2::{
|
||||
Compression,
|
||||
read::{ZlibDecoder, ZlibEncoder},
|
||||
};
|
||||
use glob::glob;
|
||||
use mlua::{
|
||||
Function, IntoLua, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, String as LuaString,
|
||||
Table, Value, Variadic,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
Game,
|
||||
api::{image_handle::ImageHandle, rendering::PoBString, search_handle::SearchHandle},
|
||||
context::CONTEXT,
|
||||
input::{str_as_keycode, str_as_mousebutton},
|
||||
util::{change_working_directory, get_executable_dir},
|
||||
};
|
||||
|
||||
mod image_handle;
|
||||
mod rendering;
|
||||
mod search_handle;
|
||||
|
||||
/// Register functions that can be called from lua
|
||||
pub fn register_globals(lua: &Lua) -> LuaResult<()> {
|
||||
let globals = lua.globals();
|
||||
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)?)?;
|
||||
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("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)?)?;
|
||||
globals.set("PCall", lua.create_function(protected_call)?)?;
|
||||
globals.set("GetTime", lua.create_function(get_time)?)?;
|
||||
globals.set("MakeDir", lua.create_function(make_dir)?)?;
|
||||
globals.set("StripEscapes", lua.create_function(strip_escapes)?)?;
|
||||
globals.set("Inflate", lua.create_function(inflate)?)?;
|
||||
globals.set("Deflate", lua.create_function(deflate)?)?;
|
||||
globals.set("NewFileSearch", lua.create_function(new_search_handle)?)?;
|
||||
globals.set("GetWorkDir", lua.create_function(get_work_dir)?)?;
|
||||
globals.set("SetWorkDir", lua.create_function(set_work_dir)?)?;
|
||||
globals.set("Copy", lua.create_function(copy)?)?;
|
||||
globals.set("Paste", lua.create_function(paste)?)?;
|
||||
globals.set("GetScreenSize", lua.create_function(get_screen_size)?)?;
|
||||
globals.set("GetScreenScale", lua.create_function(get_screen_scale)?)?;
|
||||
globals.set("GetCursorPos", lua.create_function(get_cursor_pos)?)?;
|
||||
globals.set("IsKeyDown", lua.create_function(is_key_down)?)?;
|
||||
globals.set("LoadModule", lua.create_function(load_module)?)?;
|
||||
globals.set("PLoadModule", lua.create_function(protected_load_module)?)?;
|
||||
globals.set("NewImageHandle", lua.create_function(new_image_handle)?)?;
|
||||
globals.set("SetWindowTitle", lua.create_function(set_window_title)?)?;
|
||||
globals.set("Restart", lua.create_function(restart)?)?;
|
||||
globals.set("OpenURL", lua.create_function(open_url)?)?;
|
||||
globals.set("RenderInit", lua.create_function(render_init)?)?;
|
||||
|
||||
// NOTE: not used by PoB
|
||||
let get_draw_layer = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
let set_blend_mode = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
let get_async_count = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
let set_cursor_pos = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
let show_cursor = |_: &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("SetCursorPos", lua.create_function(set_cursor_pos)?)?;
|
||||
globals.set("ShowCursor", lua.create_function(show_cursor)?)?;
|
||||
globals.set("SetClearColor", lua.create_function(set_clear_color)?)?;
|
||||
|
||||
rendering::register_globals(lua)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 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())
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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
|
||||
fn get_script_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
Ok(Game::script_dir())
|
||||
}
|
||||
|
||||
// parent directory of executable
|
||||
fn get_runtime_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
match get_executable_dir() {
|
||||
Ok(exe_path) => Ok(exe_path),
|
||||
Err(_) => Ok(PathBuf::new()),
|
||||
}
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
fn console_execute(_l: &Lua, _cmd: String) -> LuaResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn console_clear(_l: &Lua, _: ()) -> LuaResult<()> {
|
||||
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(())
|
||||
}
|
||||
|
||||
fn console_print_table(_l: &Lua, (table, no_recursive): (Table, Option<bool>)) -> LuaResult<()> {
|
||||
print_table(&table, 0, !no_recursive.unwrap_or(true))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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)?),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_time(_l: &Lua, _: ()) -> LuaResult<u128> {
|
||||
Ok(SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis())
|
||||
}
|
||||
|
||||
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)?),
|
||||
}
|
||||
}
|
||||
|
||||
fn strip_escapes(_: &Lua, text: String) -> LuaResult<String> {
|
||||
Ok(PoBString(&text).strip_escapes())
|
||||
}
|
||||
|
||||
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 = String::new();
|
||||
match decoder.read_to_string(&mut decompressed) {
|
||||
Ok(_) => Ok(decompressed.into_lua_multi(l).unwrap()),
|
||||
Err(e) => Ok((Value::Nil, e.to_string()).into_lua_multi(l).unwrap()),
|
||||
}
|
||||
}
|
||||
|
||||
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 = String::new();
|
||||
match encoder.read_to_string(&mut compressed) {
|
||||
Ok(_) => Ok(compressed.into_lua_multi(l).unwrap()),
|
||||
Err(e) => Ok((Value::Nil, e.to_string()).into_lua_multi(l).unwrap()),
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
fn get_work_dir(_: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
Ok(CONTEXT.with_borrow(|ctx| ctx.current_working_dir().to_path_buf()))
|
||||
}
|
||||
|
||||
// NOTE: unused
|
||||
fn set_work_dir(_: &Lua, path: String) -> LuaResult<()> {
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.set_current_working_dir(path.into()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn copy(_: &Lua, text: String) -> LuaResult<()> {
|
||||
CONTEXT.with_borrow_mut(|ctx| {
|
||||
ctx.clipboard
|
||||
.set_text(text)
|
||||
.map_err(|e| anyhow::anyhow!("{}", e))
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn paste(_: &Lua, _: ()) -> LuaResult<String> {
|
||||
let text = CONTEXT.with_borrow_mut(|ctx| {
|
||||
ctx.clipboard
|
||||
.get_text()
|
||||
.map_err(|e| anyhow::anyhow!("{}", e))
|
||||
})?;
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
// NOTE: needs to return physical size if this MR gets merged:
|
||||
// https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2/pull/1420
|
||||
fn get_screen_size(_: &Lua, _: ()) -> LuaResult<(u32, u32)> {
|
||||
let size = CONTEXT.with_borrow(|ctx| ctx.screen_size_logical());
|
||||
Ok((size.width, size.height))
|
||||
}
|
||||
|
||||
fn get_screen_scale(_: &Lua, _: ()) -> LuaResult<f32> {
|
||||
Ok(CONTEXT.with_borrow(|ctx| ctx.pixels_per_point() as f32))
|
||||
}
|
||||
|
||||
fn get_cursor_pos(_: &Lua, _: ()) -> LuaResult<(u32, u32)> {
|
||||
let pos = CONTEXT.with_borrow(|ctx| ctx.mouse_pos_logical());
|
||||
Ok((pos.x as u32, pos.y as u32))
|
||||
}
|
||||
|
||||
fn is_key_down(_: &Lua, key_name: String) -> LuaResult<bool> {
|
||||
if let Some(code) = str_as_keycode(&key_name) {
|
||||
Ok(CONTEXT.with_borrow(|ctx| ctx.input_state.key_pressed(code)))
|
||||
} else if let Some(button) = str_as_mousebutton(&key_name) {
|
||||
Ok(CONTEXT.with_borrow(|ctx| ctx.input_state.mouse_pressed(button)))
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
change_working_directory(Game::script_dir().as_path())?;
|
||||
let result = l.load(module_path).call::<MultiValue>(args);
|
||||
CONTEXT.with_borrow(|ctx| change_working_directory(ctx.current_working_dir()))?;
|
||||
result
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
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)?),
|
||||
};
|
||||
CONTEXT.with_borrow(|ctx| change_working_directory(ctx.current_working_dir()))?;
|
||||
result
|
||||
}
|
||||
|
||||
fn new_image_handle(_: &Lua, _: ()) -> LuaResult<ImageHandle> {
|
||||
Ok(ImageHandle::Unloaded)
|
||||
}
|
||||
|
||||
fn set_window_title(_: &Lua, title: String) -> LuaResult<()> {
|
||||
CONTEXT.with_borrow(|ctx| ctx.set_window_title(&title));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restart(_: &Lua, _: ()) -> LuaResult<()> {
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.needs_restart = true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_url(l: &Lua, url: String) -> LuaResult<MultiValue> {
|
||||
match open::that(url) {
|
||||
Ok(_) => Ok(().into_lua_multi(l)?),
|
||||
Err(_) => Ok("Unable to open url!".into_lua_multi(l)?),
|
||||
}
|
||||
}
|
||||
|
||||
fn render_init(_: &Lua, _features: Variadic<String>) -> LuaResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use mlua::{MultiValue, UserData};
|
||||
|
||||
use crate::{
|
||||
context::CONTEXT,
|
||||
renderer::textures::{TextureHandle, TextureOptions},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum ImageHandle {
|
||||
Loaded(TextureHandle),
|
||||
Unloaded,
|
||||
}
|
||||
|
||||
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("Unload", |_, this, ()| {
|
||||
match this {
|
||||
ImageHandle::Loaded(_) => {
|
||||
// dropping the handle frees the texture
|
||||
*this = ImageHandle::Unloaded;
|
||||
}
|
||||
ImageHandle::Unloaded => {}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
methods.add_method("IsValid", |_, this, ()| {
|
||||
Ok(matches!(this, ImageHandle::Loaded(_)))
|
||||
});
|
||||
|
||||
methods.add_method("IsLoading", |_, this, ()| match &this {
|
||||
ImageHandle::Loaded(texture_handle) => {
|
||||
let size = texture_handle.size();
|
||||
Ok(size[0] == 0)
|
||||
}
|
||||
ImageHandle::Unloaded => Ok(true),
|
||||
});
|
||||
|
||||
methods.add_method("ImageSize", |_, this, ()| match &this {
|
||||
ImageHandle::Loaded(texture_handle) => {
|
||||
let size = texture_handle.size();
|
||||
Ok((size[0], size[1]))
|
||||
}
|
||||
ImageHandle::Unloaded => Ok((0, 0)),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,621 @@
|
||||
use crate::{
|
||||
api::image_handle::ImageHandle,
|
||||
color::Srgba,
|
||||
context::CONTEXT,
|
||||
dpi::Uv,
|
||||
fonts::{Alignment, LayoutJob},
|
||||
math::{Point, Quad, Rect, Size},
|
||||
};
|
||||
use core::ffi::{c_int, c_void};
|
||||
use mlua::{
|
||||
LightUserData, Lua, Result as LuaResult, UserDataRefMut, Value,
|
||||
ffi::{self},
|
||||
};
|
||||
use regex::Regex;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
pub fn register_globals(lua: &Lua) -> LuaResult<()> {
|
||||
let globals = lua.globals();
|
||||
// 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("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)?,
|
||||
)?;
|
||||
|
||||
// NOTE: mlua wraps UserData in a special way to maintain safety guarantees.
|
||||
// This wrapper is not exposed by mlua, making it difficult to access the
|
||||
// underlying user data from within C functions.
|
||||
// This is a helper function that unwraps an ImageHandle and returns a pointer to it
|
||||
// See: https://github.com/mlua-rs/mlua/discussions/545#discussioncomment-12530475
|
||||
let get_img_handle = lua.create_function(|_, mut ud: UserDataRefMut<ImageHandle>| {
|
||||
let vec: *mut ImageHandle = &mut *ud;
|
||||
Ok(Value::LightUserData(LightUserData(vec as *mut c_void)))
|
||||
})?;
|
||||
lua.set_named_registry_value("get_img_handle", get_img_handle)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! img_handle_from_stack {
|
||||
($s:ident, $i:expr) => {
|
||||
unsafe {
|
||||
match ffi::lua_type($s, $i) {
|
||||
ffi::LUA_TNIL => None,
|
||||
ffi::LUA_TUSERDATA => {
|
||||
let img_handle = lua_toimghandle($s, $i);
|
||||
if !img_handle.is_null() {
|
||||
if let ImageHandle::Loaded(ref handle) = *img_handle {
|
||||
Some(handle.id())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
t => panic!("Expected Nil or ImageHandle, got {:?}", t),
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
unsafe extern "C" fn lua_toimghandle(state: *mut ffi::lua_State, idx: c_int) -> *mut ImageHandle {
|
||||
unsafe {
|
||||
let idx = ffi::lua_absindex(state, idx);
|
||||
ffi::lua_getfield(state, ffi::LUA_REGISTRYINDEX, c"get_img_handle".as_ptr());
|
||||
ffi::lua_pushvalue(state, idx);
|
||||
let img_handle = match ffi::lua_pcall(state, 1, 1, 0) {
|
||||
ffi::LUA_OK => ffi::lua_touserdata(state, -1) as *mut ImageHandle,
|
||||
_ => std::ptr::null_mut(),
|
||||
};
|
||||
ffi::lua_pop(state, 1);
|
||||
img_handle
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("set_draw_color");
|
||||
|
||||
let 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);
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.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);
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.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);
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_color(color));
|
||||
}
|
||||
_ => panic!("Unexpected number of arguments"),
|
||||
};
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("set_viewport");
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
match nargs {
|
||||
0 => CONTEXT.with_borrow_mut(|ctx| ctx.reset_viewport()),
|
||||
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));
|
||||
}
|
||||
_ => 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 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));
|
||||
}
|
||||
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 {
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.set_draw_layer(layer, sublayer));
|
||||
} else {
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.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 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 = img_handle_from_stack!(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;
|
||||
Rect::new(Point::new(u1, v1), Point::new(u2, v2))
|
||||
} else {
|
||||
Rect::default_uv()
|
||||
};
|
||||
|
||||
let layer_idx = if parse_layer_idx {
|
||||
let layer_idx = i32_from_stack!(state, -nargs + i);
|
||||
(layer_idx - 1) as u32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.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 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 = img_handle_from_stack!(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;
|
||||
Quad::new(
|
||||
Point::new(u1, v1),
|
||||
Point::new(u2, v2),
|
||||
Point::new(u3, v3),
|
||||
Point::new(u4, v4),
|
||||
)
|
||||
} else {
|
||||
Quad::default_uv()
|
||||
};
|
||||
|
||||
let layer_idx = if parse_layer_idx {
|
||||
let layer_idx = i32_from_stack!(state, -nargs + i);
|
||||
(layer_idx - 1) as u32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.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 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 alignment = match alignment.parse::<PoBTextAlignment>() {
|
||||
Ok(alignment) => alignment,
|
||||
Err(_) => panic!("Invalid alignment"),
|
||||
};
|
||||
let font_type = match font_type.parse::<PoBFontType>() {
|
||||
Ok(font_type) => font_type,
|
||||
Err(_) => panic!("Invalid font type"),
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
ctx.draw_text(position, job, 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 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 font_type = match font_type.parse::<PoBFontType>() {
|
||||
Ok(font_type) => font_type,
|
||||
Err(_) => panic!("Invalid font type"),
|
||||
};
|
||||
|
||||
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));
|
||||
|
||||
unsafe { ffi::lua_pushnumber(state, width as f64) };
|
||||
1
|
||||
}
|
||||
|
||||
fn get_index_at_cur(
|
||||
_: &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 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)));
|
||||
|
||||
// convert to lua's 1-based indexing
|
||||
Ok(index + 1)
|
||||
}
|
||||
|
||||
pub static ESCAPE_STR_REGEX: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"\^(?<idx>[0-9])|\^[x|X](?<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 font_family = match font_type {
|
||||
PoBFontType::Fixed => parley::GenericFamily::Monospace,
|
||||
PoBFontType::Var => parley::GenericFamily::SansSerif,
|
||||
PoBFontType::VarBold => {
|
||||
font_weight = Some(700.0);
|
||||
parley::GenericFamily::SansSerif
|
||||
}
|
||||
};
|
||||
|
||||
// TODO: check how PoB determines font size
|
||||
let font_size = (line_height - 2).clamp(11, 32) as f32;
|
||||
|
||||
let mut job = LayoutJob::new(
|
||||
font_family,
|
||||
font_size,
|
||||
line_height as f32,
|
||||
alignment,
|
||||
font_weight,
|
||||
);
|
||||
|
||||
for (color, segment) in PoBString(text).into_iter() {
|
||||
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!(
|
||||
"'{}' is not a valid TextFontType variant",
|
||||
s
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum PoBFontType {
|
||||
Fixed,
|
||||
Var,
|
||||
VarBold,
|
||||
}
|
||||
|
||||
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),
|
||||
_ => Err(anyhow::anyhow!(
|
||||
"'{}' is not a valid TextFontType variant",
|
||||
s
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Srgba {
|
||||
fn from_escape_code(escape_str: &str) -> Srgba {
|
||||
if let Some(caps) = ESCAPE_STR_REGEX.captures(escape_str) {
|
||||
if let Some(idx) = caps.name("idx") {
|
||||
return match idx.as_str() {
|
||||
"0" => Srgba::from_rgb(0, 0, 0), //black
|
||||
"1" => Srgba::from_rgb(255, 0, 0), //red
|
||||
"2" => Srgba::from_rgb(0, 255, 0), //green
|
||||
"3" => Srgba::from_rgb(0, 0, 255), //blue
|
||||
"4" => Srgba::from_rgb(255, 255, 0), //yellow
|
||||
"5" => Srgba::from_rgb(255, 0, 255), //purple
|
||||
"6" => Srgba::from_rgb(0, 255, 255), //aqua
|
||||
"7" => Srgba::from_rgb(255, 255, 255), //white
|
||||
"8" => Srgba::from_rgb(178, 178, 178), //gray
|
||||
"9" => Srgba::from_rgb(102, 102, 102), //dark gray
|
||||
_ => unreachable!(),
|
||||
};
|
||||
}
|
||||
if let Some(hex) = caps.name("hex")
|
||||
&& let Ok(hex_color) = Srgba::from_hex(hex.as_str())
|
||||
{
|
||||
return hex_color;
|
||||
}
|
||||
}
|
||||
Srgba::WHITE
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use glob::Paths;
|
||||
use mlua::{IntoLua, UserData};
|
||||
|
||||
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)
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Result;
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
dpi::PhysicalPosition,
|
||||
event::*,
|
||||
event_loop::ActiveEventLoop,
|
||||
keyboard::{ModifiersState, PhysicalKey},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
context::{CONTEXT, FrameOutput},
|
||||
gfx::GraphicsContext,
|
||||
input::{keycode_as_str, mousebutton_as_str},
|
||||
lua::LuaInstance,
|
||||
};
|
||||
|
||||
pub struct App {
|
||||
gfx_context: Option<GraphicsContext>,
|
||||
lua_instance: LuaInstance,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub fn new() -> Result<Self> {
|
||||
let lua_instance = LuaInstance::new()?;
|
||||
|
||||
Ok(Self {
|
||||
gfx_context: None,
|
||||
lua_instance,
|
||||
})
|
||||
}
|
||||
|
||||
fn frame(&mut self) -> FrameOutput {
|
||||
// Handle restart requests
|
||||
if CONTEXT.with_borrow(|ctx| ctx.needs_restart) {
|
||||
match self.lua_instance.restart() {
|
||||
Ok(_) => CONTEXT.with_borrow_mut(|ctx| ctx.needs_restart = false),
|
||||
Err(e) => panic!("Error occused while restarting lua instance: {}", e),
|
||||
}
|
||||
};
|
||||
|
||||
self.lua_instance.handle_subscripts();
|
||||
|
||||
// Clear data from previous frame and prepare for new one
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.begin_frame());
|
||||
|
||||
// Call back into lua and tell it to draw a frame
|
||||
self.lua_instance.on_frame().unwrap();
|
||||
|
||||
// End frame and get outupts
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.end_frame())
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler<GraphicsContext> for App {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
let window = match event_loop.create_window(Window::default_attributes()) {
|
||||
Ok(window) => Arc::new(window),
|
||||
Err(err) => {
|
||||
log::error!("{err}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.set_window(Arc::clone(&window)));
|
||||
|
||||
self.gfx_context = match pollster::block_on(GraphicsContext::new(window)) {
|
||||
Ok(gfx) => Some(gfx),
|
||||
Err(err) => {
|
||||
log::error!("{err}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
_window_id: winit::window::WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.on_window_event(&event));
|
||||
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
self.lua_instance.on_exit().unwrap();
|
||||
event_loop.exit()
|
||||
}
|
||||
WindowEvent::Resized(size) => {
|
||||
if let Some(ref mut gfx) = self.gfx_context {
|
||||
gfx.resize(size.width, size.height);
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.force_render = true)
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
profiling::scope!("RedrawRequested");
|
||||
|
||||
let FrameOutput { render_job } = self.frame();
|
||||
|
||||
if let Some(ref mut gfx) = self.gfx_context {
|
||||
match gfx.render(render_job) {
|
||||
Ok(_) => {}
|
||||
// Reconfigure the surface if it's lost or outdated
|
||||
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
|
||||
let size = gfx.window.inner_size();
|
||||
gfx.resize(size.width, size.height);
|
||||
CONTEXT.with_borrow_mut(|ctx| ctx.force_render = true)
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Unable to render: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
profiling::finish_frame!();
|
||||
}
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
physical_key: PhysicalKey::Code(code),
|
||||
state,
|
||||
text,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => {
|
||||
// Only call OnChar if no modifier key except SHIFT is pressed.
|
||||
// This prevents 'v' from getting inserted into a text field
|
||||
// when 'CTRL + v' is used to paste.
|
||||
if state.is_pressed()
|
||||
&& CONTEXT.with_borrow(|ctx| {
|
||||
ctx.input_state
|
||||
.modifiers()
|
||||
.difference(ModifiersState::SHIFT)
|
||||
.is_empty()
|
||||
})
|
||||
&& let Some(text) = text
|
||||
{
|
||||
self.lua_instance.on_char(&text).unwrap();
|
||||
}
|
||||
|
||||
if let Some(key_string) = keycode_as_str(code) {
|
||||
match state {
|
||||
ElementState::Pressed => {
|
||||
self.lua_instance.on_key_down(&key_string, false).unwrap();
|
||||
}
|
||||
ElementState::Released => {
|
||||
self.lua_instance.on_key_up(&key_string).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { state, button, .. } => {
|
||||
if let Some(button_string) = mousebutton_as_str(button) {
|
||||
match state {
|
||||
ElementState::Pressed => {
|
||||
let is_double_click = CONTEXT
|
||||
.with_borrow_mut(|ctx| ctx.input_state.is_double_click(button));
|
||||
self.lua_instance
|
||||
.on_key_down(&button_string, is_double_click)
|
||||
.unwrap();
|
||||
}
|
||||
ElementState::Released => {
|
||||
self.lua_instance.on_key_up(&button_string).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseWheel { delta, .. } => {
|
||||
let vertical_scroll_amount = match delta {
|
||||
MouseScrollDelta::LineDelta(_, y) => y as f64,
|
||||
MouseScrollDelta::PixelDelta(PhysicalPosition { y, .. }) => y,
|
||||
};
|
||||
|
||||
if vertical_scroll_amount > 0.0 {
|
||||
self.lua_instance.on_key_up("WHEELUP").unwrap();
|
||||
} else if vertical_scroll_amount < 0.0 {
|
||||
self.lua_instance.on_key_up("WHEELDOWN").unwrap();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
use clap::Parser;
|
||||
use clap::ValueEnum;
|
||||
use directories::BaseDirs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(version, about, long_about = None)]
|
||||
pub struct Args {
|
||||
#[arg(value_enum)]
|
||||
pub game: Game,
|
||||
|
||||
pub build_path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, ValueEnum)]
|
||||
pub enum Game {
|
||||
#[value(name = "poe1")]
|
||||
Poe1,
|
||||
#[value(name = "poe2")]
|
||||
Poe2,
|
||||
}
|
||||
|
||||
static GAME_CONFIG: std::sync::OnceLock<Game> = std::sync::OnceLock::new();
|
||||
|
||||
impl Game {
|
||||
pub fn init(game: Game) {
|
||||
GAME_CONFIG.set(game).expect("Game should be uninitialized");
|
||||
}
|
||||
|
||||
pub fn current() -> &'static Game {
|
||||
GAME_CONFIG.get().expect("Game should be initialized")
|
||||
}
|
||||
|
||||
pub fn script_dir() -> PathBuf {
|
||||
let directory_name = match Self::current() {
|
||||
Game::Poe1 => "PathOfBuilding1",
|
||||
Game::Poe2 => "PathOfBuilding2",
|
||||
};
|
||||
BaseDirs::new().unwrap().data_dir().join(directory_name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/// `sRGB` color with _unmultiplied alpha_.
|
||||
#[repr(C)]
|
||||
#[repr(align(4))]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct Srgba(pub [u8; 4]);
|
||||
|
||||
impl Srgba {
|
||||
pub const WHITE: Self = Self::from_rgb(255, 255, 255);
|
||||
pub const TRANSPARENT: Self = Self::new(0, 0, 0, 0);
|
||||
|
||||
#[inline]
|
||||
pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
|
||||
Self([r, g, b, a])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub const fn new_f32(r: f32, g: f32, b: f32, a: f32) -> Self {
|
||||
Self([f32_to_u8(r), f32_to_u8(g), f32_to_u8(b), f32_to_u8(a)])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub const fn from_rgb(r: u8, g: u8, b: u8) -> Self {
|
||||
Self([r, g, b, 255])
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn from_hex<T: AsRef<str>>(hex: T) -> anyhow::Result<Self> {
|
||||
let hex = hex.as_ref();
|
||||
let hex = hex.strip_prefix("#").unwrap_or(hex);
|
||||
|
||||
match hex.len() {
|
||||
// RGB shorthand form, e.g. #FC0 -> #FFCC00
|
||||
3 => {
|
||||
let [m, l] = u16::from_str_radix(hex, 16)?.to_be_bytes();
|
||||
let (r, g, b) = (m & 0x0F, (l & 0xF0) >> 4, l & 0x0F);
|
||||
Ok(Self::from_rgb((r << 4) | r, (g << 4) | g, (b << 4) | b))
|
||||
}
|
||||
// RGBA shorthand form, e.g. #FC0F -> #FFCC00FF
|
||||
4 => {
|
||||
let [m, l] = u16::from_str_radix(hex, 16)?.to_be_bytes();
|
||||
let (r, g, b, a) = ((m & 0xF0) >> 4, m & 0xF, (l & 0xF0) >> 4, l & 0x0F);
|
||||
Ok(Self::new(
|
||||
(r << 4) | r,
|
||||
(g << 4) | g,
|
||||
(b << 4) | b,
|
||||
(a << 4) | a,
|
||||
))
|
||||
}
|
||||
// RRGGBB
|
||||
6 => {
|
||||
let [_, r, g, b] = u32::from_str_radix(hex, 16)?.to_be_bytes();
|
||||
Ok(Self::from_rgb(r, g, b))
|
||||
}
|
||||
// RRGGBBAA
|
||||
8 => {
|
||||
let [r, g, b, a] = u32::from_str_radix(hex, 16)?.to_be_bytes();
|
||||
Ok(Self::new(r, g, b, a))
|
||||
}
|
||||
_ => Err(anyhow::anyhow!("Unexpected length of hex string")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Srgba> for image::Rgba<u8> {
|
||||
fn from(value: Srgba) -> Self {
|
||||
Self(value.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// f32 [0.0, 1.0] -> u8 [0, 255]
|
||||
#[inline(always)]
|
||||
const fn f32_to_u8(c: f32) -> u8 {
|
||||
((c * 255.0) + 0.5) as u8
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
use crate::{
|
||||
Game,
|
||||
color::Srgba,
|
||||
dpi::{
|
||||
ConvertToLogical, LogicalPoint, LogicalQuad, LogicalRect, LogicalSize, NormalizedQuad,
|
||||
NormalizedRect, PhysicalRect, PhysicalSize,
|
||||
},
|
||||
fonts::{Fonts, LayoutJob},
|
||||
input::InputState,
|
||||
layers::Layers,
|
||||
renderer::{
|
||||
mesh::ClippedMesh,
|
||||
primitives::{QuadPrimitive, QuadTexture, RectPrimitive, RectTexture, TextPrimitive},
|
||||
tessellator::Tessellator,
|
||||
textures::{TextureId, TexturesDelta, WrappedTextureManager},
|
||||
},
|
||||
util::{calculate_hash, change_working_directory},
|
||||
};
|
||||
use arboard::Clipboard;
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
use winit::{event::WindowEvent, window::Window};
|
||||
|
||||
// NOTE: This looks ugly but i haven't found a better way to do it yet.
|
||||
// The C functions used for rendering need a way to access the context.
|
||||
// They can't be defined as closures like all other lua callback functions
|
||||
// and we can't change their arguments. The only way for them to access
|
||||
// something outside their scope is to have some kind of static variable.
|
||||
thread_local! {
|
||||
pub static CONTEXT: RefCell<Context> = RefCell::new(Context::new());
|
||||
}
|
||||
|
||||
pub struct Context {
|
||||
window: Option<Arc<Window>>,
|
||||
screen_size: PhysicalSize<u32>,
|
||||
pixels_per_point: f32,
|
||||
pub input_state: InputState,
|
||||
pub clipboard: Clipboard,
|
||||
pub texture_manager: WrappedTextureManager,
|
||||
tessellator: Tessellator,
|
||||
fonts: Fonts,
|
||||
layers: Layers,
|
||||
current_draw_color: Srgba,
|
||||
previous_layers_hash: u64,
|
||||
current_working_dir: PathBuf,
|
||||
pub needs_restart: bool,
|
||||
pub force_render: bool,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
window: None,
|
||||
screen_size: PhysicalSize::new(0, 0),
|
||||
pixels_per_point: 1.0,
|
||||
input_state: InputState::default(),
|
||||
clipboard: Clipboard::new().unwrap(),
|
||||
texture_manager: WrappedTextureManager::new(),
|
||||
tessellator: Tessellator::default(),
|
||||
fonts: Fonts::new(),
|
||||
layers: Layers::new(),
|
||||
current_draw_color: Srgba::WHITE,
|
||||
previous_layers_hash: 0,
|
||||
current_working_dir: Game::script_dir().clone(),
|
||||
needs_restart: false,
|
||||
force_render: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn begin_frame(&mut self) {
|
||||
profiling::scope!("begin_frame");
|
||||
|
||||
self.fonts.begin_frame();
|
||||
self.layers.reset();
|
||||
self.reset_viewport();
|
||||
}
|
||||
|
||||
pub fn end_frame(&mut self) -> FrameOutput {
|
||||
profiling::scope!("end_frame");
|
||||
|
||||
let font_atlas_size = self.fonts.font_atlas().size();
|
||||
if let Some(font_image_delta) = self.fonts.font_atlas_delta() {
|
||||
self.texture_manager.update_font_texture(font_image_delta);
|
||||
}
|
||||
|
||||
let textures_delta = self.texture_manager.take_delta();
|
||||
|
||||
// Skip rendering this frame if identical to last one and no textures changed
|
||||
let layers_hash = calculate_hash(&self.layers);
|
||||
let elide_frame = layers_hash == self.previous_layers_hash && textures_delta.is_empty();
|
||||
|
||||
let render_job = if elide_frame && !self.force_render {
|
||||
RenderJob::Skip
|
||||
} else {
|
||||
self.force_render = false;
|
||||
self.previous_layers_hash = layers_hash;
|
||||
|
||||
let primitives = self.layers.consume_layers();
|
||||
let meshes = self
|
||||
.tessellator
|
||||
.convert_clipped_primitives(primitives, font_atlas_size);
|
||||
|
||||
RenderJob::Render {
|
||||
meshes,
|
||||
textures_delta,
|
||||
}
|
||||
};
|
||||
|
||||
FrameOutput { render_job }
|
||||
}
|
||||
|
||||
pub fn on_window_event(&mut self, event: &WindowEvent) {
|
||||
match event {
|
||||
WindowEvent::Resized(size) => {
|
||||
self.screen_size = PhysicalSize::new(size.width, size.height);
|
||||
}
|
||||
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
|
||||
self.pixels_per_point = *scale_factor as f32;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
self.input_state.on_window_event(event);
|
||||
}
|
||||
|
||||
pub fn screen_size_logical(&self) -> LogicalSize<u32> {
|
||||
self.screen_size.to_logical(self.pixels_per_point)
|
||||
}
|
||||
|
||||
pub fn mouse_pos_logical(&self) -> LogicalPoint<f32> {
|
||||
self.input_state
|
||||
.mouse_pos()
|
||||
.to_logical(self.pixels_per_point)
|
||||
}
|
||||
|
||||
pub fn pixels_per_point(&self) -> f32 {
|
||||
self.pixels_per_point
|
||||
}
|
||||
|
||||
pub fn current_working_dir(&self) -> &Path {
|
||||
&self.current_working_dir
|
||||
}
|
||||
|
||||
pub fn set_current_working_dir(&mut self, path: PathBuf) {
|
||||
if change_working_directory(&path).is_ok() {
|
||||
self.current_working_dir = path;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_window(&mut self, window: Arc<Window>) {
|
||||
self.window = Some(window);
|
||||
}
|
||||
|
||||
pub fn set_window_title(&self, title: &str) {
|
||||
if let Some(ref window) = self.window {
|
||||
window.set_title(title);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum RenderJob {
|
||||
Render {
|
||||
meshes: Vec<ClippedMesh>,
|
||||
textures_delta: TexturesDelta,
|
||||
},
|
||||
Skip,
|
||||
}
|
||||
|
||||
pub struct FrameOutput {
|
||||
pub render_job: RenderJob,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
pub fn set_draw_layer(&mut self, layer: i32, sublayer: i32) {
|
||||
self.layers.set_draw_layer(layer, sublayer);
|
||||
}
|
||||
|
||||
pub fn set_draw_sublayer(&mut self, sublayer: i32) {
|
||||
self.layers.set_draw_sublayer(sublayer);
|
||||
}
|
||||
|
||||
pub fn set_viewport(&mut self, viewport: LogicalRect<f32>) {
|
||||
self.layers.set_viewport(viewport);
|
||||
}
|
||||
|
||||
pub fn reset_viewport(&mut self) {
|
||||
let viewport = PhysicalRect::from_size(self.screen_size);
|
||||
self.layers
|
||||
.set_viewport(viewport.to_logical(self.pixels_per_point));
|
||||
}
|
||||
|
||||
pub fn set_draw_color(&mut self, color: Srgba) {
|
||||
self.current_draw_color = color;
|
||||
}
|
||||
|
||||
pub fn get_draw_color(&self) -> Srgba {
|
||||
self.current_draw_color
|
||||
}
|
||||
|
||||
pub fn draw_rect(
|
||||
&mut self,
|
||||
texture_id: Option<TextureId>,
|
||||
rect: LogicalRect<f32>,
|
||||
uv: NormalizedRect,
|
||||
layer_idx: u32,
|
||||
) {
|
||||
let texture = texture_id.map(|id| RectTexture::new(id, uv, layer_idx));
|
||||
let primitive = RectPrimitive::new(rect, self.current_draw_color, texture);
|
||||
self.layers.add_rect(primitive);
|
||||
}
|
||||
|
||||
pub fn draw_quad(
|
||||
&mut self,
|
||||
texture_id: Option<TextureId>,
|
||||
quad: LogicalQuad<f32>,
|
||||
uv: NormalizedQuad,
|
||||
layer_idx: u32,
|
||||
) {
|
||||
let texture = texture_id.map(|id| QuadTexture::new(id, uv, layer_idx));
|
||||
let primitive = QuadPrimitive::new(quad, self.current_draw_color, texture);
|
||||
self.layers.add_quad(primitive);
|
||||
}
|
||||
|
||||
pub fn draw_text(
|
||||
&mut self,
|
||||
position: LogicalPoint<f32>,
|
||||
job: LayoutJob,
|
||||
is_absolute_position: bool,
|
||||
) {
|
||||
let layout = self.fonts.layout(job, self.pixels_per_point as f32);
|
||||
let primitive = TextPrimitive::new(position, layout);
|
||||
self.layers.add_text(primitive, is_absolute_position);
|
||||
}
|
||||
|
||||
/// Width of laid out text
|
||||
pub fn get_text_width(&mut self, job: LayoutJob) -> i32 {
|
||||
let layout = self.fonts.layout(job, self.pixels_per_point as f32);
|
||||
layout.width() as i32
|
||||
}
|
||||
|
||||
/// Text index based on where cursor is positioned within text
|
||||
pub fn get_text_index_at_cursor(&mut self, job: LayoutJob, cursor: LogicalPoint<f32>) -> usize {
|
||||
let layout = self.fonts.layout(job, self.pixels_per_point as f32);
|
||||
layout.cursor_index(cursor)
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
use crate::math::{Point, Quad, Rect, Size, Vector};
|
||||
use core::f32;
|
||||
use num_traits::{Float, NumCast, ToPrimitive};
|
||||
|
||||
pub struct LogicalScreenSpace;
|
||||
pub struct PhysicalScreenSpace;
|
||||
pub struct Normalized;
|
||||
|
||||
pub type LogicalPoint<T> = Point<T, LogicalScreenSpace>;
|
||||
pub type LogicalVector<T> = Vector<T, LogicalScreenSpace>;
|
||||
pub type LogicalSize<T> = Size<T, LogicalScreenSpace>;
|
||||
pub type LogicalRect<T> = Rect<T, LogicalScreenSpace>;
|
||||
pub type LogicalQuad<T> = Quad<T, LogicalScreenSpace>;
|
||||
|
||||
pub type PhysicalPoint<T> = Point<T, PhysicalScreenSpace>;
|
||||
pub type PhysicalVector<T> = Vector<T, PhysicalScreenSpace>;
|
||||
pub type PhysicalSize<T> = Size<T, PhysicalScreenSpace>;
|
||||
pub type PhysicalRect<T> = Rect<T, PhysicalScreenSpace>;
|
||||
|
||||
pub type NormalizedPoint = Point<f32, Normalized>;
|
||||
pub type NormalizedRect = Rect<f32, Normalized>;
|
||||
pub type NormalizedQuad = Quad<f32, Normalized>;
|
||||
|
||||
pub trait Normalize<T, U> {
|
||||
type Output<F>;
|
||||
fn normalize<F: Float>(&self, size: Size<T, U>) -> Self::Output<F>;
|
||||
}
|
||||
|
||||
impl<T, U> Normalize<T, U> for Point<T, U>
|
||||
where
|
||||
T: Copy + std::ops::Div<Output = T> + ToPrimitive,
|
||||
{
|
||||
type Output<V> = Point<V, Normalized>;
|
||||
|
||||
#[inline]
|
||||
fn normalize<F: Float>(&self, size: Size<T, U>) -> Self::Output<F> {
|
||||
Point::new(
|
||||
F::from(self.x).unwrap() / F::from(size.width).unwrap(),
|
||||
F::from(self.y).unwrap() / F::from(size.height).unwrap(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> Normalize<T, U> for Rect<T, U>
|
||||
where
|
||||
T: Copy + std::ops::Div<Output = T> + ToPrimitive,
|
||||
{
|
||||
type Output<V> = Rect<V, Normalized>;
|
||||
|
||||
#[inline]
|
||||
fn normalize<F: Float>(&self, size: Size<T, U>) -> Self::Output<F> {
|
||||
Rect::new(self.min.normalize(size), self.max.normalize(size))
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ConvertToLogical {
|
||||
type Output<V>;
|
||||
fn to_logical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V>;
|
||||
}
|
||||
|
||||
pub trait ConvertToPhysical {
|
||||
type Output<V>;
|
||||
fn to_physical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V>;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn validate_scale_factor<F: Float>(scale_factor: F) -> bool {
|
||||
scale_factor.is_sign_positive() && scale_factor.is_normal()
|
||||
}
|
||||
|
||||
impl<T> ConvertToLogical for PhysicalPoint<T>
|
||||
where
|
||||
T: Copy + std::ops::Div<Output = T> + ToPrimitive,
|
||||
{
|
||||
type Output<V> = LogicalPoint<V>;
|
||||
|
||||
#[inline]
|
||||
fn to_logical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V> {
|
||||
assert!(validate_scale_factor(scale_factor));
|
||||
let x = F::from(self.x).unwrap() / scale_factor;
|
||||
let y = F::from(self.y).unwrap() / scale_factor;
|
||||
LogicalPoint::new(x, y).cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ConvertToLogical for PhysicalSize<T>
|
||||
where
|
||||
T: Copy + std::ops::Div<Output = T> + ToPrimitive,
|
||||
{
|
||||
type Output<V> = LogicalSize<V>;
|
||||
|
||||
#[inline]
|
||||
fn to_logical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V> {
|
||||
assert!(validate_scale_factor(scale_factor));
|
||||
let width = F::from(self.width).unwrap() / scale_factor;
|
||||
let height = F::from(self.height).unwrap() / scale_factor;
|
||||
LogicalSize::new(width, height).cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ConvertToLogical for PhysicalRect<T>
|
||||
where
|
||||
T: Copy + std::ops::Div<Output = T> + ToPrimitive,
|
||||
{
|
||||
type Output<V> = LogicalRect<V>;
|
||||
|
||||
#[inline]
|
||||
fn to_logical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V> {
|
||||
assert!(validate_scale_factor(scale_factor));
|
||||
let min = self.min.to_logical(scale_factor);
|
||||
let max = self.max.to_logical(scale_factor);
|
||||
LogicalRect::new(min, max)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ConvertToPhysical for LogicalPoint<T>
|
||||
where
|
||||
T: Copy + std::ops::Div<Output = T> + ToPrimitive,
|
||||
{
|
||||
type Output<V> = PhysicalPoint<V>;
|
||||
|
||||
#[inline]
|
||||
fn to_physical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V> {
|
||||
assert!(validate_scale_factor(scale_factor));
|
||||
let x = F::from(self.x).unwrap() * scale_factor;
|
||||
let y = F::from(self.y).unwrap() * scale_factor;
|
||||
PhysicalPoint::new(x, y).cast()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> ConvertToPhysical for LogicalRect<T>
|
||||
where
|
||||
T: Copy + std::ops::Div<Output = T> + ToPrimitive,
|
||||
{
|
||||
type Output<V> = PhysicalRect<V>;
|
||||
|
||||
#[inline]
|
||||
fn to_physical<V: NumCast, F: Float>(&self, scale_factor: F) -> Self::Output<V> {
|
||||
assert!(validate_scale_factor(scale_factor));
|
||||
let min = self.min.to_physical(scale_factor);
|
||||
let max = self.max.to_physical(scale_factor);
|
||||
PhysicalRect::new(min, max)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Uv {
|
||||
fn default_uv() -> Self;
|
||||
fn white_uv() -> Self;
|
||||
}
|
||||
|
||||
impl Uv for NormalizedPoint {
|
||||
#[inline]
|
||||
fn default_uv() -> Self {
|
||||
Self::zero()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn white_uv() -> Self {
|
||||
Self::zero()
|
||||
}
|
||||
}
|
||||
|
||||
impl Uv for NormalizedRect {
|
||||
#[inline]
|
||||
fn default_uv() -> Self {
|
||||
Self::from_size(Size::new(1.0, 1.0))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn white_uv() -> Self {
|
||||
Self::zero()
|
||||
}
|
||||
}
|
||||
|
||||
impl Uv for NormalizedQuad {
|
||||
#[inline]
|
||||
fn default_uv() -> Self {
|
||||
Self::from_size(Size::new(1.0, 1.0))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn white_uv() -> Self {
|
||||
Self::zero()
|
||||
}
|
||||
}
|
||||
+339
@@ -0,0 +1,339 @@
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::LogicalVector,
|
||||
fonts::{
|
||||
atlas::FontAtlas, glyph_key::SubpixelBin, layout::LayoutRow, rasterizer::GlyphRasterizer,
|
||||
},
|
||||
renderer::image::ImageDelta,
|
||||
util::calculate_hash,
|
||||
};
|
||||
use ordered_float::OrderedFloat;
|
||||
use parley::{
|
||||
FontContext, FontWeight, GenericFamily, LayoutContext, StyleProperty, TextStyle, fontique::Blob,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use atlas::FontAtlasSize;
|
||||
pub use layout::{Alignment, Layout, LayoutJob};
|
||||
|
||||
mod atlas;
|
||||
mod glyph_key;
|
||||
mod layout;
|
||||
mod rasterizer;
|
||||
|
||||
pub const BITSTREAM_VERA_SANS_MONO: &[u8] = include_bytes!("../fonts/VeraMono.ttf");
|
||||
pub const LIBERATION_SANS: &[u8] = include_bytes!("../fonts/LiberationSans-Regular.ttf");
|
||||
pub const LIBERATION_SANS_BOLD: &[u8] = include_bytes!("../fonts/LiberationSans-Bold.ttf");
|
||||
|
||||
pub struct FontData {
|
||||
data: std::borrow::Cow<'static, [u8]>,
|
||||
}
|
||||
|
||||
impl FontData {
|
||||
pub fn from_static(font_data: &'static [u8]) -> Self {
|
||||
Self {
|
||||
data: std::borrow::Cow::Borrowed(font_data),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<[u8]> for FontData {
|
||||
fn as_ref(&self) -> &[u8] {
|
||||
self.data.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FontDefinition {
|
||||
pub generic_families: Vec<GenericFamily>,
|
||||
pub data: Arc<FontData>,
|
||||
}
|
||||
|
||||
pub struct Fonts {
|
||||
font_definitions: Vec<FontDefinition>,
|
||||
font_context: FontContext,
|
||||
layout_context: LayoutContext<Srgba>,
|
||||
atlas: FontAtlas,
|
||||
glyph_rasterizer: GlyphRasterizer,
|
||||
layout_cache: LayoutCache,
|
||||
}
|
||||
|
||||
impl Fonts {
|
||||
pub fn new() -> Self {
|
||||
// add fonts used by PoB
|
||||
let font_definitions = vec![
|
||||
FontDefinition {
|
||||
generic_families: vec![GenericFamily::Monospace],
|
||||
data: Arc::new(FontData::from_static(BITSTREAM_VERA_SANS_MONO)),
|
||||
},
|
||||
FontDefinition {
|
||||
generic_families: vec![GenericFamily::SansSerif],
|
||||
data: Arc::new(FontData::from_static(LIBERATION_SANS)),
|
||||
},
|
||||
FontDefinition {
|
||||
generic_families: vec![GenericFamily::SansSerif],
|
||||
data: Arc::new(FontData::from_static(LIBERATION_SANS_BOLD)),
|
||||
},
|
||||
];
|
||||
|
||||
let mut fonts = Self {
|
||||
font_definitions,
|
||||
font_context: FontContext::new(),
|
||||
layout_context: LayoutContext::new(),
|
||||
atlas: FontAtlas::new(1024),
|
||||
glyph_rasterizer: GlyphRasterizer::new(),
|
||||
layout_cache: LayoutCache::default(),
|
||||
};
|
||||
|
||||
fonts.register_fonts();
|
||||
fonts.preload_common_characters(14.0);
|
||||
fonts.preload_common_characters(16.0);
|
||||
|
||||
fonts
|
||||
}
|
||||
|
||||
fn register_fonts(&mut self) {
|
||||
for definition in &self.font_definitions {
|
||||
let blob = Blob::new(Arc::new(definition.data.data.clone()));
|
||||
let registered_fonts = self.font_context.collection.register_fonts(blob, None);
|
||||
for generic_family in &definition.generic_families {
|
||||
self.font_context
|
||||
.collection
|
||||
.append_generic_families(*generic_family, registered_fonts.iter().map(|f| f.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Needs to be called at beginning of each frame.
|
||||
pub fn begin_frame(&mut self) {
|
||||
// recreate atlas when it becomes too full or overflowed
|
||||
if self.atlas.capacity() > 0.9 {
|
||||
self.clear_atlas();
|
||||
}
|
||||
self.layout_cache.flush();
|
||||
}
|
||||
|
||||
/// Gets changes to the font atlas texture since last call.
|
||||
pub fn font_atlas_delta(&mut self) -> Option<ImageDelta> {
|
||||
self.atlas.take_delta()
|
||||
}
|
||||
|
||||
pub fn preload_common_characters(&mut self, font_size: f32) {
|
||||
const ASCII_PRINTABLE_START: u8 = 32;
|
||||
const ASCII_PRINTABLE_END: u8 = 126;
|
||||
|
||||
let mut common_chars =
|
||||
String::with_capacity((ASCII_PRINTABLE_END - ASCII_PRINTABLE_START + 1) as usize);
|
||||
|
||||
for c in ASCII_PRINTABLE_START..=ASCII_PRINTABLE_END {
|
||||
common_chars.push(c as char);
|
||||
}
|
||||
|
||||
self.preload_text(&common_chars, font_size, GenericFamily::Monospace, None);
|
||||
self.preload_text(&common_chars, font_size, GenericFamily::SansSerif, None);
|
||||
self.preload_text(
|
||||
&common_chars,
|
||||
font_size,
|
||||
GenericFamily::SansSerif,
|
||||
Some(FontWeight::BOLD),
|
||||
);
|
||||
}
|
||||
|
||||
fn preload_text(
|
||||
&mut self,
|
||||
text: &str,
|
||||
font_size: f32,
|
||||
generic_family: GenericFamily,
|
||||
font_weight: Option<FontWeight>,
|
||||
) {
|
||||
profiling::scope!("preload_text");
|
||||
|
||||
let style = TextStyle {
|
||||
font_stack: parley::FontStack::Single(parley::FontFamily::Generic(generic_family)),
|
||||
font_weight: font_weight.unwrap_or(FontWeight::NORMAL),
|
||||
font_size,
|
||||
..Default::default()
|
||||
};
|
||||
let mut builder =
|
||||
self.layout_context
|
||||
.tree_builder(&mut self.font_context, 1.0, true, &style);
|
||||
builder.push_text(text);
|
||||
|
||||
let (mut layout, _) = builder.build();
|
||||
layout.break_all_lines(None);
|
||||
|
||||
for line in layout.lines() {
|
||||
for item in line.items() {
|
||||
let parley::PositionedLayoutItem::GlyphRun(run) = item else {
|
||||
continue;
|
||||
};
|
||||
|
||||
for horizontal_offset in SubpixelBin::<4>::BIN_OFFSETS {
|
||||
self.glyph_rasterizer
|
||||
.rasterize_glyph_run(
|
||||
&mut self.atlas,
|
||||
&run,
|
||||
LogicalVector::new(horizontal_offset, 0.0),
|
||||
1.0,
|
||||
)
|
||||
.for_each(|_| {});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn font_atlas(&self) -> &FontAtlas {
|
||||
&self.atlas
|
||||
}
|
||||
|
||||
pub fn layout(&mut self, job: LayoutJob, pixels_per_point: f32) -> Arc<Layout> {
|
||||
let hash = calculate_hash(&(&job, OrderedFloat(pixels_per_point)));
|
||||
|
||||
if let Some(cached_layout) = self.layout_cache.get(hash) {
|
||||
return cached_layout;
|
||||
}
|
||||
|
||||
let default_style = TextStyle::default();
|
||||
let style = TextStyle {
|
||||
font_stack: parley::FontStack::Single(parley::FontFamily::Generic(job.font_family)),
|
||||
font_size: job.font_size.into(),
|
||||
line_height: parley::LineHeight::Absolute(job.line_height.into()),
|
||||
font_weight: job
|
||||
.font_weight
|
||||
.map(|w| parley::FontWeight::new(w.into()))
|
||||
.unwrap_or(default_style.font_weight),
|
||||
..default_style
|
||||
};
|
||||
|
||||
let mut builder = self.layout_context.tree_builder(
|
||||
&mut self.font_context,
|
||||
1.0,
|
||||
// TODO: quantize true or false?
|
||||
true,
|
||||
&style,
|
||||
);
|
||||
|
||||
for segment in job.segments {
|
||||
let brush_style = StyleProperty::Brush(segment.color);
|
||||
builder.push_style_modification_span(&[brush_style]);
|
||||
builder.push_text(segment.text);
|
||||
builder.pop_style_span();
|
||||
}
|
||||
|
||||
let (mut parley_layout, _) = builder.build();
|
||||
parley_layout.break_all_lines(None);
|
||||
|
||||
// extra offset applied to each glyph to get position relative to layout origin
|
||||
let mut glyph_offset = LogicalVector::new(0.0, 0.0);
|
||||
if let Some(alignment) = job.alignment {
|
||||
let alignment = match alignment {
|
||||
Alignment::Min => parley::Alignment::Start,
|
||||
Alignment::Center => {
|
||||
glyph_offset.x += -parley_layout.full_width() * 0.5;
|
||||
parley::Alignment::Center
|
||||
}
|
||||
Alignment::Max => {
|
||||
glyph_offset.x += -parley_layout.full_width();
|
||||
parley::Alignment::End
|
||||
}
|
||||
};
|
||||
parley_layout.align(None, alignment, parley::AlignmentOptions::default());
|
||||
}
|
||||
|
||||
let mut layout_rows = Vec::new();
|
||||
let mut num_of_vertices = 0;
|
||||
let mut num_of_indices = 0;
|
||||
|
||||
for line in parley_layout.lines() {
|
||||
let mut layout_row = LayoutRow::default();
|
||||
|
||||
for item in line.items() {
|
||||
let parley::PositionedLayoutItem::GlyphRun(run) = item else {
|
||||
continue;
|
||||
};
|
||||
|
||||
for rasterized_glyph in self.glyph_rasterizer.rasterize_glyph_run(
|
||||
&mut self.atlas,
|
||||
&run,
|
||||
glyph_offset,
|
||||
pixels_per_point,
|
||||
) {
|
||||
let Some(glyph) = rasterized_glyph else {
|
||||
continue;
|
||||
};
|
||||
|
||||
layout_row.glyphs.push(glyph);
|
||||
num_of_vertices += 4;
|
||||
num_of_indices += 6;
|
||||
}
|
||||
}
|
||||
|
||||
if !layout_row.glyphs.is_empty() {
|
||||
layout_rows.push(layout_row);
|
||||
}
|
||||
}
|
||||
|
||||
let layout = Arc::new(Layout {
|
||||
job_hash: hash,
|
||||
parley_layout,
|
||||
rows: layout_rows,
|
||||
num_of_vertices,
|
||||
num_of_indices,
|
||||
});
|
||||
|
||||
self.layout_cache.insert(hash, Arc::clone(&layout));
|
||||
|
||||
layout
|
||||
}
|
||||
|
||||
/// Clear atlas and invalidate caches depend on atlas state
|
||||
fn clear_atlas(&mut self) {
|
||||
self.atlas.clear();
|
||||
self.glyph_rasterizer.clear();
|
||||
self.layout_cache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
struct CachedLayout {
|
||||
generation: u32,
|
||||
layout: Arc<Layout>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct LayoutCache {
|
||||
current_generation: u32,
|
||||
cache: nohash_hasher::IntMap<u64, CachedLayout>,
|
||||
}
|
||||
|
||||
impl LayoutCache {
|
||||
fn get(&mut self, hash: u64) -> Option<Arc<Layout>> {
|
||||
match self.cache.entry(hash) {
|
||||
std::collections::hash_map::Entry::Occupied(entry) => {
|
||||
let cached = entry.into_mut();
|
||||
cached.generation = self.current_generation;
|
||||
Some(Arc::clone(&cached.layout))
|
||||
}
|
||||
std::collections::hash_map::Entry::Vacant(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn insert(&mut self, hash: u64, layout: Arc<Layout>) {
|
||||
self.cache.insert(
|
||||
hash,
|
||||
CachedLayout {
|
||||
generation: self.current_generation,
|
||||
layout,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Removes unused layouts
|
||||
pub fn flush(&mut self) {
|
||||
self.cache
|
||||
.retain(|_key, cached| cached.generation == self.current_generation);
|
||||
self.current_generation = self.current_generation.wrapping_add(1);
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.cache.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
math::{Point, Rect, Size},
|
||||
renderer::{
|
||||
image::{ImageData, ImageDelta},
|
||||
textures::TextureOptions,
|
||||
},
|
||||
};
|
||||
use image::{GenericImage, RgbaImage, SubImage, imageops};
|
||||
|
||||
pub struct FontAtlasSpace;
|
||||
pub type FontAtlasPoint = Point<u32, FontAtlasSpace>;
|
||||
pub type FontAtlasSize = Size<u32, FontAtlasSpace>;
|
||||
pub type FontAtlasRect = Rect<u32, FontAtlasSpace>;
|
||||
|
||||
pub struct FontAtlas {
|
||||
// max width/height of atlas texture
|
||||
max_texture_side: u32,
|
||||
image: RgbaImage,
|
||||
// position of next allocation
|
||||
cursor: FontAtlasPoint,
|
||||
current_row_height: u32,
|
||||
// atlas has been altered and needs to be reuploaded to the GPU
|
||||
// TODO: only mark changed region as dirty and perform partial texture update
|
||||
dirty: bool,
|
||||
// atlas has overflowed and needs to be recreated
|
||||
overflowed: bool,
|
||||
}
|
||||
|
||||
impl FontAtlas {
|
||||
pub fn new(max_texture_side: u32) -> Self {
|
||||
// start out with maximum width and let height grow as needed
|
||||
let width = max_texture_side;
|
||||
let initial_height = 256;
|
||||
|
||||
let mut atlas = Self {
|
||||
max_texture_side,
|
||||
image: RgbaImage::new(width, initial_height),
|
||||
cursor: FontAtlasPoint::zero(),
|
||||
current_row_height: 0,
|
||||
dirty: false,
|
||||
overflowed: false,
|
||||
};
|
||||
|
||||
atlas.initialize();
|
||||
atlas
|
||||
}
|
||||
|
||||
fn initialize(&mut self) {
|
||||
// Puts white pixel at (0, 0).
|
||||
// NOTE: Rendering a solid color shape is done by setting the texture to
|
||||
// the font atlas and sampling the white pixel at (0, 0).
|
||||
let mut sub_image = self.allocate(FontAtlasSize::new(1, 1));
|
||||
sub_image.put_pixel(0, 0, Srgba::WHITE.into());
|
||||
}
|
||||
|
||||
// TODO: use an actual bin packing algorithm for tighter packing
|
||||
/// Returns a mutable view into the atlas of given size.
|
||||
pub fn allocate(&mut self, size: FontAtlasSize) -> SubImage<&mut RgbaImage> {
|
||||
const PADDING: u32 = 1;
|
||||
|
||||
if self.cursor.x + size.width > self.image.width() {
|
||||
self.cursor.x = 0;
|
||||
self.cursor.y += self.current_row_height + PADDING;
|
||||
self.current_row_height = 0;
|
||||
}
|
||||
|
||||
self.current_row_height = self.current_row_height.max(size.height);
|
||||
|
||||
let required_atlas_height = self.cursor.y + self.current_row_height;
|
||||
if required_atlas_height > self.max_texture_side {
|
||||
log::warn!("font atlas overflowed!");
|
||||
// start overwriting old glyphs
|
||||
self.cursor = Point::new(0, self.image.height() / 3);
|
||||
// setting this flag causes atlas to be recreated next frame
|
||||
self.overflowed = true;
|
||||
} else if required_atlas_height > self.image().height() {
|
||||
// increase height
|
||||
let mut new_height = self.image.height();
|
||||
while new_height < required_atlas_height {
|
||||
new_height *= 2;
|
||||
}
|
||||
self.image = extend_image_height(&self.image, new_height, Srgba::TRANSPARENT);
|
||||
}
|
||||
|
||||
let pos = self.cursor;
|
||||
self.cursor.x += size.width + PADDING;
|
||||
|
||||
self.dirty = true;
|
||||
|
||||
self.image.sub_image(pos.x, pos.y, size.width, size.height)
|
||||
}
|
||||
|
||||
pub fn take_delta(&mut self) -> Option<ImageDelta> {
|
||||
let dirty = std::mem::replace(&mut self.dirty, false);
|
||||
if dirty {
|
||||
Some(ImageDelta::new(
|
||||
ImageData::from(self.image.clone()),
|
||||
TextureOptions::LINEAR,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn capacity(&self) -> f32 {
|
||||
if self.overflowed {
|
||||
1.0
|
||||
} else {
|
||||
(self.cursor.y + self.current_row_height) as f32 / self.max_texture_side as f32
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.image.fill(0);
|
||||
self.cursor = FontAtlasPoint::zero();
|
||||
self.current_row_height = 0;
|
||||
self.dirty = false;
|
||||
self.overflowed = false;
|
||||
self.initialize();
|
||||
}
|
||||
|
||||
pub fn image(&self) -> &RgbaImage {
|
||||
&self.image
|
||||
}
|
||||
|
||||
pub fn size(&self) -> FontAtlasSize {
|
||||
FontAtlasSize::new(self.image.width(), self.image.height())
|
||||
}
|
||||
}
|
||||
|
||||
fn extend_image_height(image: &RgbaImage, new_height: u32, fill_color: Srgba) -> RgbaImage {
|
||||
let width = image.width();
|
||||
let mut extended_image = RgbaImage::from_pixel(width, new_height, fill_color.into());
|
||||
imageops::overlay(&mut extended_image, image, 0, 0);
|
||||
extended_image
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
use ordered_float::OrderedFloat;
|
||||
use parley::Glyph;
|
||||
|
||||
use crate::{dpi::PhysicalPoint, fonts::rasterizer::StyleId};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct GlyphKey {
|
||||
glyph_id: swash::GlyphId,
|
||||
style_id: StyleId,
|
||||
x_bin: SubpixelBin<4>,
|
||||
pixels_per_point: OrderedFloat<f32>,
|
||||
}
|
||||
|
||||
impl GlyphKey {
|
||||
pub fn from_glyph(
|
||||
glyph: &Glyph,
|
||||
style_id: StyleId,
|
||||
pixels_per_point: f32,
|
||||
) -> (Self, PhysicalPoint<i32>) {
|
||||
// Use subpixel binning for x coordinate
|
||||
let (x, x_bin) = SubpixelBin::<4>::new(glyph.x * pixels_per_point);
|
||||
// No binning for y coordinate, just rounding
|
||||
let y = (glyph.y * pixels_per_point).round() as i32;
|
||||
let glyph_pos = PhysicalPoint::new(x, y);
|
||||
|
||||
(
|
||||
Self {
|
||||
glyph_id: glyph.id as u16,
|
||||
style_id,
|
||||
x_bin,
|
||||
pixels_per_point: OrderedFloat(pixels_per_point),
|
||||
},
|
||||
glyph_pos,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn get_fractional_offset(&self) -> swash::zeno::Vector {
|
||||
swash::zeno::Vector::new(self.x_bin.as_float(), 0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Grouping of fractional offsets into discrete bins for cache optimization
|
||||
/// Bins have size 1/N and are centered around (1/N) * i with i in {0, 1, 2, ...}
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
pub struct SubpixelBin<const NUM_OF_BINS: usize>(usize);
|
||||
|
||||
impl<const NUM_OF_BINS: usize> SubpixelBin<NUM_OF_BINS> {
|
||||
pub const BIN_OFFSETS: [f32; NUM_OF_BINS] = {
|
||||
let mut out = [0.0; NUM_OF_BINS];
|
||||
let mut i = 0;
|
||||
while i < NUM_OF_BINS {
|
||||
out[i] = i as f32 * 1.0 / NUM_OF_BINS as f32;
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
};
|
||||
|
||||
pub fn new(position: f32) -> (i32, Self) {
|
||||
let half_bin_width = 1.0 / (NUM_OF_BINS as f32 * 2.0);
|
||||
let new_position = (position + half_bin_width).floor() as i32;
|
||||
|
||||
let scaled_pos = ((position - position.floor()) * NUM_OF_BINS as f32).round() as usize;
|
||||
let bin = scaled_pos.rem_euclid(NUM_OF_BINS);
|
||||
|
||||
(new_position, Self(bin))
|
||||
}
|
||||
|
||||
pub const fn as_float(&self) -> f32 {
|
||||
self.0 as f32 / NUM_OF_BINS as f32
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_subpixel_bins() {
|
||||
assert_eq!(SubpixelBin::<4>::new(3.14), (3, SubpixelBin(1)));
|
||||
assert_eq!(SubpixelBin::<4>::new(0.11), (0, SubpixelBin(0)));
|
||||
assert_eq!(SubpixelBin::<4>::new(-0.8), (-1, SubpixelBin(1)));
|
||||
assert_eq!(SubpixelBin::<2>::new(0.24), (0, SubpixelBin(0)));
|
||||
assert_eq!(SubpixelBin::<2>::new(0.26), (0, SubpixelBin(1)));
|
||||
assert_eq!(SubpixelBin::<2>::new(0.76), (1, SubpixelBin(0)));
|
||||
assert_eq!(SubpixelBin::<2>::new(-0.76), (-1, SubpixelBin(0)));
|
||||
assert_eq!(SubpixelBin::<2>::new(-0.25), (0, SubpixelBin(0)));
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
use crate::{color::Srgba, dpi::LogicalPoint, fonts::rasterizer::RasterizedGlyph};
|
||||
use ordered_float::OrderedFloat;
|
||||
use parley::GenericFamily;
|
||||
|
||||
#[derive(Copy, Clone, Debug, Hash)]
|
||||
pub enum Alignment {
|
||||
Min,
|
||||
Center,
|
||||
Max,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Hash)]
|
||||
pub struct LayoutSegment<'s> {
|
||||
pub text: &'s str,
|
||||
pub color: Srgba,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Hash)]
|
||||
pub struct LayoutJob<'s> {
|
||||
pub segments: Vec<LayoutSegment<'s>>,
|
||||
pub font_family: GenericFamily,
|
||||
pub font_size: OrderedFloat<f32>,
|
||||
pub line_height: OrderedFloat<f32>,
|
||||
pub alignment: Option<Alignment>,
|
||||
pub font_weight: Option<OrderedFloat<f32>>,
|
||||
}
|
||||
|
||||
impl<'s> LayoutJob<'s> {
|
||||
pub fn new(
|
||||
font_family: GenericFamily,
|
||||
font_size: f32,
|
||||
line_height: f32,
|
||||
alignment: Option<Alignment>,
|
||||
font_weight: Option<f32>,
|
||||
) -> Self {
|
||||
Self {
|
||||
segments: Vec::new(),
|
||||
font_family,
|
||||
font_size: font_size.into(),
|
||||
line_height: line_height.into(),
|
||||
alignment,
|
||||
font_weight: font_weight.map(OrderedFloat),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn append(&mut self, text: &'s str, color: Srgba) {
|
||||
self.segments.push(LayoutSegment { text, color });
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct LayoutRow {
|
||||
pub glyphs: Vec<RasterizedGlyph>,
|
||||
}
|
||||
|
||||
pub struct Layout {
|
||||
pub job_hash: u64,
|
||||
pub parley_layout: parley::Layout<Srgba>,
|
||||
pub rows: Vec<LayoutRow>,
|
||||
pub num_of_vertices: usize,
|
||||
pub num_of_indices: usize,
|
||||
}
|
||||
|
||||
impl Layout {
|
||||
pub fn width(&self) -> f32 {
|
||||
self.parley_layout.full_width()
|
||||
}
|
||||
|
||||
/// Returns text index at cursor position
|
||||
pub fn cursor_index(&self, cursor: LogicalPoint<f32>) -> usize {
|
||||
let cursor = parley::Cursor::from_point(&self.parley_layout, cursor.x, cursor.y);
|
||||
cursor.index()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::hash::Hash for Layout {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.job_hash.hash(state);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::{
|
||||
ConvertToLogical, LogicalRect, LogicalVector, PhysicalPoint, PhysicalRect, PhysicalVector,
|
||||
},
|
||||
fonts::{
|
||||
atlas::{FontAtlas, FontAtlasRect},
|
||||
glyph_key::GlyphKey,
|
||||
},
|
||||
math::{Point, Size},
|
||||
};
|
||||
use ahash::HashMap;
|
||||
use image::GenericImage;
|
||||
use ordered_float::OrderedFloat;
|
||||
use parley::{FontData, GlyphRun};
|
||||
use std::borrow::Cow;
|
||||
|
||||
type FontBlobId = u64;
|
||||
type FontIndex = u32;
|
||||
type SwashFontOffset = u32;
|
||||
pub type StyleId = u32;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
struct StyleKey<'a> {
|
||||
font_blob_id: FontBlobId,
|
||||
font_size: OrderedFloat<f32>,
|
||||
normalized_coords: Cow<'a, [i16]>,
|
||||
}
|
||||
|
||||
impl<'a> StyleKey<'a> {
|
||||
fn new(font_blob_id: FontBlobId, font_size: f32, normalized_coords: &'a [i16]) -> Self {
|
||||
Self {
|
||||
font_blob_id,
|
||||
font_size: font_size.into(),
|
||||
normalized_coords: Cow::Borrowed(normalized_coords),
|
||||
}
|
||||
}
|
||||
|
||||
fn to_static(&self) -> StyleKey<'static> {
|
||||
StyleKey {
|
||||
normalized_coords: self.normalized_coords.clone().into_owned().into(),
|
||||
..*self
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct CachedGlyph {
|
||||
// absolute uv rect within font atlas
|
||||
pub uv: FontAtlasRect,
|
||||
// offset from top/left to baseline
|
||||
pub baseline_offset: PhysicalVector<i32>,
|
||||
}
|
||||
|
||||
pub struct RasterizedGlyph {
|
||||
// NOTE: this is relative to the layout origin
|
||||
pub rect: LogicalRect<f32>,
|
||||
pub uv: FontAtlasRect,
|
||||
pub color: Srgba,
|
||||
}
|
||||
|
||||
impl RasterizedGlyph {
|
||||
fn from_cached(
|
||||
cached: CachedGlyph,
|
||||
position: PhysicalPoint<i32>,
|
||||
color: Srgba,
|
||||
pixels_per_point: f32,
|
||||
) -> Self {
|
||||
let glyph_rect = PhysicalRect::from_origin_and_size(
|
||||
position + cached.baseline_offset,
|
||||
cached.uv.cast_unit().cast().size(),
|
||||
);
|
||||
|
||||
RasterizedGlyph {
|
||||
rect: glyph_rect.to_logical(pixels_per_point),
|
||||
uv: cached.uv,
|
||||
color,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GlyphRasterizer {
|
||||
scale_context: swash::scale::ScaleContext,
|
||||
swash_keys: HashMap<(FontBlobId, FontIndex), (SwashFontOffset, swash::CacheKey)>,
|
||||
// Style properties (font, size, etc.) are the same for each glyph run and don't
|
||||
// need to be part of each glyph key. Instead, associate each style with its own
|
||||
// ID and include that in the glyph key.
|
||||
style_ids: HashMap<StyleKey<'static>, StyleId>,
|
||||
next_style_id: StyleId,
|
||||
cached_glyphs: HashMap<GlyphKey, Option<CachedGlyph>>,
|
||||
// scratch image buffer used to write bitmap data into
|
||||
scratch: swash::scale::image::Image,
|
||||
}
|
||||
|
||||
impl GlyphRasterizer {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
scale_context: swash::scale::ScaleContext::new(),
|
||||
swash_keys: Default::default(),
|
||||
style_ids: Default::default(),
|
||||
next_style_id: 0,
|
||||
cached_glyphs: Default::default(),
|
||||
scratch: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.swash_keys.clear();
|
||||
self.style_ids.clear();
|
||||
self.next_style_id = 0;
|
||||
self.cached_glyphs.clear();
|
||||
}
|
||||
|
||||
/// Gets a swash::FontRef from FontData
|
||||
fn get_font_ref<'a>(&mut self, font: &'a FontData) -> swash::FontRef<'a> {
|
||||
let font_blob_id = font.data.id();
|
||||
|
||||
let (swash_offset, swash_key) = *self
|
||||
.swash_keys
|
||||
.entry((font_blob_id, font.index))
|
||||
.or_insert_with(|| {
|
||||
let font_ref =
|
||||
swash::FontRef::from_index(font.data.data(), font.index as usize).unwrap();
|
||||
(font_ref.offset, font_ref.key)
|
||||
});
|
||||
|
||||
swash::FontRef {
|
||||
data: font.data.data(),
|
||||
offset: swash_offset,
|
||||
key: swash_key,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_style_id(
|
||||
&mut self,
|
||||
font_data: &FontData,
|
||||
font_size: f32,
|
||||
norm_coords: &[i16],
|
||||
) -> StyleId {
|
||||
let style_key = StyleKey::new(font_data.data.id(), font_size, norm_coords);
|
||||
match self.style_ids.get(&style_key) {
|
||||
Some(key) => *key,
|
||||
None => *self
|
||||
.style_ids
|
||||
.entry(style_key.to_static())
|
||||
.or_insert_with(|| {
|
||||
let id = self.next_style_id;
|
||||
self.next_style_id += 1;
|
||||
id
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rasterizes glyph run and returns the placement and UV for each glyph.
|
||||
/// Can return `None` if glyph doesn't take up any space (e.g. whitespace).
|
||||
pub fn rasterize_glyph_run<'slf: 'run, 'run, 'atlas>(
|
||||
&'slf mut self,
|
||||
atlas: &'atlas mut FontAtlas,
|
||||
glyph_run: &'run GlyphRun<'_, Srgba>,
|
||||
// additional offset relative to layout origin
|
||||
glyph_offset: LogicalVector<f32>,
|
||||
pixels_per_point: f32,
|
||||
) -> impl Iterator<Item = Option<RasterizedGlyph>> + use<'slf, 'run, 'atlas> {
|
||||
let run = glyph_run.run();
|
||||
let color = glyph_run.style().brush;
|
||||
let font_size = run.font_size() * pixels_per_point;
|
||||
let normalized_coords = run.normalized_coords();
|
||||
|
||||
let font_ref = self.get_font_ref(run.font());
|
||||
let style_id = self.get_style_id(run.font(), font_size, normalized_coords);
|
||||
|
||||
let mut scaler = self
|
||||
.scale_context
|
||||
.builder(font_ref)
|
||||
.size(font_size)
|
||||
.normalized_coords(normalized_coords)
|
||||
.hint(true)
|
||||
.build();
|
||||
|
||||
let image = &mut self.scratch;
|
||||
let cached_glyphs = &mut self.cached_glyphs;
|
||||
glyph_run.positioned_glyphs().map(move |mut glyph| {
|
||||
glyph.x += glyph_offset.x;
|
||||
glyph.y += glyph_offset.y;
|
||||
|
||||
let (glyph_key, glyph_pos) = GlyphKey::from_glyph(&glyph, style_id, pixels_per_point);
|
||||
|
||||
if let Some(cached_glyph) = cached_glyphs.get(&glyph_key) {
|
||||
return cached_glyph.map(|cached| {
|
||||
RasterizedGlyph::from_cached(cached, glyph_pos, color, pixels_per_point)
|
||||
});
|
||||
}
|
||||
|
||||
let fract_offset = glyph_key.get_fractional_offset();
|
||||
|
||||
image.clear();
|
||||
let did_render = swash::scale::Render::new(&[
|
||||
swash::scale::Source::ColorOutline(0),
|
||||
swash::scale::Source::ColorBitmap(swash::scale::StrikeWith::BestFit),
|
||||
swash::scale::Source::Outline,
|
||||
])
|
||||
.format(swash::zeno::Format::Alpha)
|
||||
.offset(fract_offset)
|
||||
.render_into(&mut scaler, glyph.id as u16, image);
|
||||
|
||||
if !did_render || image.placement.width == 0 || image.placement.height == 0 {
|
||||
cached_glyphs.insert(glyph_key, None);
|
||||
return None;
|
||||
};
|
||||
|
||||
let atlas_region = write_to_atlas(image, atlas);
|
||||
|
||||
let cached_glyph = CachedGlyph {
|
||||
uv: atlas_region,
|
||||
baseline_offset: PhysicalVector::new(image.placement.left, -image.placement.top),
|
||||
};
|
||||
cached_glyphs.insert(glyph_key, Some(cached_glyph));
|
||||
|
||||
Some(RasterizedGlyph::from_cached(
|
||||
cached_glyph,
|
||||
glyph_pos,
|
||||
color,
|
||||
pixels_per_point,
|
||||
))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes rasterized glyph to atlas and returns region it wrote into
|
||||
fn write_to_atlas(image: &swash::scale::image::Image, atlas: &mut FontAtlas) -> FontAtlasRect {
|
||||
let mut atlas_region = atlas.allocate(Size::new(image.placement.width, image.placement.height));
|
||||
|
||||
match image.content {
|
||||
swash::scale::image::Content::Mask => {
|
||||
let mut i = 0;
|
||||
for y in 0..image.placement.height {
|
||||
for x in 0..image.placement.width {
|
||||
let a = image.data[i];
|
||||
// SAFETY: allocated atlas region and swash image have the same size
|
||||
unsafe {
|
||||
atlas_region.unsafe_put_pixel(x, y, Srgba::new(255, 255, 255, a).into())
|
||||
};
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
FontAtlasRect::from_origin_and_size(
|
||||
Point::new(atlas_region.offsets().0, atlas_region.offsets().1),
|
||||
Size::new(image.placement.width, image.placement.height),
|
||||
)
|
||||
}
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
use crate::{context::RenderJob, dpi::PhysicalSize, renderer::Renderer};
|
||||
use std::sync::Arc;
|
||||
use wgpu::{Texture, TextureFormat, TextureView};
|
||||
use winit::window::Window;
|
||||
|
||||
pub struct GraphicsContext {
|
||||
surface: wgpu::Surface<'static>,
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
config: wgpu::SurfaceConfiguration,
|
||||
is_surface_configured: bool,
|
||||
renderer: Renderer,
|
||||
blit_texture: wgpu::Texture,
|
||||
blit_texture_view: wgpu::TextureView,
|
||||
texture_blitter: wgpu::util::TextureBlitter,
|
||||
pub window: Arc<Window>,
|
||||
}
|
||||
|
||||
impl GraphicsContext {
|
||||
pub async fn new(window: Arc<Window>) -> anyhow::Result<Self> {
|
||||
let size = window.inner_size();
|
||||
|
||||
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
|
||||
backends: wgpu::Backends::PRIMARY,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let surface = instance.create_surface(Arc::clone(&window)).unwrap();
|
||||
|
||||
let adapter = instance
|
||||
.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::default(),
|
||||
compatible_surface: Some(&surface),
|
||||
force_fallback_adapter: false,
|
||||
})
|
||||
.await?;
|
||||
|
||||
let required_features = wgpu::Features::TEXTURE_COMPRESSION_BC;
|
||||
let required_limits = wgpu::Limits {
|
||||
max_texture_array_layers: 512,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if !adapter.features().contains(required_features) {
|
||||
anyhow::bail!(
|
||||
"Unsupported features were requested: {}",
|
||||
required_features - adapter.features()
|
||||
);
|
||||
}
|
||||
|
||||
let mut failed_limit = Vec::new();
|
||||
|
||||
required_limits.check_limits_with_fail_fn(
|
||||
&adapter.limits(),
|
||||
false,
|
||||
|name, requested, allowed| {
|
||||
failed_limit.push((name, requested, allowed));
|
||||
},
|
||||
);
|
||||
|
||||
if let Some((name, requested, allowed)) = failed_limit.pop() {
|
||||
anyhow::bail!(
|
||||
"Requested limit '{name}' value {requested} is better than allowed {allowed}!"
|
||||
)
|
||||
}
|
||||
|
||||
let (device, queue) = adapter
|
||||
.request_device(&wgpu::DeviceDescriptor {
|
||||
label: None,
|
||||
required_features,
|
||||
required_limits,
|
||||
memory_hints: Default::default(),
|
||||
trace: wgpu::Trace::Off,
|
||||
experimental_features: Default::default(),
|
||||
})
|
||||
.await?;
|
||||
|
||||
let surface_caps = surface.get_capabilities(&adapter);
|
||||
|
||||
// NOTE: PoB incorrectly performs mixing and blending in sRGB space.
|
||||
// To get a similar visual outcome, we need to do the same.
|
||||
// Select a non-sRGB format so that no automatic linear -> sRGB conversion
|
||||
// is performed.
|
||||
let surface_format = surface_caps
|
||||
.formats
|
||||
.iter()
|
||||
.find(|f| !f.is_srgb())
|
||||
.copied()
|
||||
.unwrap_or(surface_caps.formats[0]);
|
||||
|
||||
let config = wgpu::SurfaceConfiguration {
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
format: surface_format,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
//present_mode: surface_caps.present_modes[0],
|
||||
present_mode: wgpu::PresentMode::Fifo,
|
||||
alpha_mode: surface_caps.alpha_modes[0],
|
||||
view_formats: vec![],
|
||||
desired_maximum_frame_latency: 2,
|
||||
};
|
||||
|
||||
let (blit_texture, blit_texture_view) =
|
||||
create_blit_texture(&device, config.width, config.height, config.format);
|
||||
|
||||
let texture_blitter = wgpu::util::TextureBlitter::new(&device, config.format);
|
||||
|
||||
let renderer = Renderer::new(&device, config.format, None);
|
||||
|
||||
Ok(Self {
|
||||
surface,
|
||||
device,
|
||||
queue,
|
||||
config,
|
||||
is_surface_configured: false,
|
||||
renderer,
|
||||
blit_texture,
|
||||
blit_texture_view,
|
||||
texture_blitter,
|
||||
window,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn resize(&mut self, width: u32, height: u32) {
|
||||
if width > 0 && height > 0 {
|
||||
self.config.width = width;
|
||||
self.config.height = height;
|
||||
self.surface.configure(&self.device, &self.config);
|
||||
self.is_surface_configured = true;
|
||||
|
||||
(self.blit_texture, self.blit_texture_view) =
|
||||
create_blit_texture(&self.device, width, height, self.config.format);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(&mut self, render_job: RenderJob) -> Result<(), wgpu::SurfaceError> {
|
||||
profiling::scope!("render");
|
||||
|
||||
self.window.request_redraw();
|
||||
|
||||
if !self.is_surface_configured {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let output = self.surface.get_current_texture()?;
|
||||
let suboptimal = output.suboptimal;
|
||||
|
||||
let surface_view = output
|
||||
.texture
|
||||
.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
let mut encoder = self
|
||||
.device
|
||||
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("Render Encoder"),
|
||||
});
|
||||
|
||||
// If render_job is [`RenderJob::Skip`], skip rendering and just
|
||||
// blit the texture of the previous frame onto the surface texture.
|
||||
if let RenderJob::Render {
|
||||
meshes,
|
||||
textures_delta,
|
||||
} = render_job
|
||||
{
|
||||
let screen_size = PhysicalSize::new(self.config.width, self.config.height);
|
||||
let pixels_per_point = self.window.as_ref().scale_factor() as f32;
|
||||
|
||||
// upload new textures
|
||||
self.renderer
|
||||
.update_textures(&self.device, &self.queue, &textures_delta);
|
||||
|
||||
// upload vertex, index, and uniform buffers
|
||||
self.renderer.update_buffers(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
&meshes,
|
||||
screen_size,
|
||||
pixels_per_point,
|
||||
);
|
||||
|
||||
let rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &self.blit_texture_view,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color {
|
||||
r: 0.0,
|
||||
g: 0.0,
|
||||
b: 0.0,
|
||||
a: 1.0,
|
||||
}),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
depth_slice: None,
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
label: Some("main render pass"),
|
||||
occlusion_query_set: None,
|
||||
});
|
||||
|
||||
self.renderer.render(
|
||||
&mut rpass.forget_lifetime(),
|
||||
&meshes,
|
||||
screen_size,
|
||||
pixels_per_point,
|
||||
);
|
||||
|
||||
self.renderer.free_textures(&textures_delta)
|
||||
}
|
||||
|
||||
{
|
||||
profiling::scope!("blit");
|
||||
self.texture_blitter.copy(
|
||||
&self.device,
|
||||
&mut encoder,
|
||||
&self.blit_texture_view,
|
||||
&surface_view,
|
||||
);
|
||||
}
|
||||
|
||||
self.queue.submit(std::iter::once(encoder.finish()));
|
||||
output.present();
|
||||
|
||||
if suboptimal {
|
||||
Err(wgpu::SurfaceError::Outdated)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn create_blit_texture(
|
||||
device: &wgpu::Device,
|
||||
width: u32,
|
||||
height: u32,
|
||||
format: TextureFormat,
|
||||
) -> (Texture, TextureView) {
|
||||
let blit_texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("Blit Texture"),
|
||||
size: wgpu::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
|
||||
view_formats: &[],
|
||||
});
|
||||
|
||||
let blit_texture_view = blit_texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
(blit_texture, blit_texture_view)
|
||||
}
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
use crate::dpi::PhysicalPoint;
|
||||
use ahash::{HashMap, HashSet};
|
||||
use std::time::{Duration, Instant};
|
||||
use winit::{
|
||||
event::{KeyEvent, MouseButton, WindowEvent},
|
||||
keyboard::{KeyCode, ModifiersState, PhysicalKey},
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct InputState {
|
||||
key_modifiers: ModifiersState,
|
||||
keys_pressed: HashSet<KeyCode>,
|
||||
mouse_pressed: HashSet<MouseButton>,
|
||||
mouse_last_pressed: HashMap<MouseButton, Instant>,
|
||||
cursor_pos: PhysicalPoint<f32>,
|
||||
}
|
||||
|
||||
impl InputState {
|
||||
pub fn key_pressed(&self, code: KeyCode) -> bool {
|
||||
self.keys_pressed.contains(&code)
|
||||
}
|
||||
|
||||
pub fn mouse_pressed(&self, button: MouseButton) -> bool {
|
||||
self.mouse_pressed.contains(&button)
|
||||
}
|
||||
|
||||
pub fn mouse_pos(&self) -> PhysicalPoint<f32> {
|
||||
self.cursor_pos
|
||||
}
|
||||
|
||||
pub fn modifiers(&self) -> ModifiersState {
|
||||
self.key_modifiers
|
||||
}
|
||||
|
||||
pub fn on_window_event(&mut self, event: &WindowEvent) {
|
||||
match event {
|
||||
WindowEvent::ModifiersChanged(modifiers) => {
|
||||
self.key_modifiers = modifiers.state();
|
||||
}
|
||||
WindowEvent::CursorMoved { position, .. } => {
|
||||
self.cursor_pos = PhysicalPoint::new(position.x as f32, position.y as f32);
|
||||
}
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
physical_key: PhysicalKey::Code(code),
|
||||
state,
|
||||
..
|
||||
},
|
||||
..
|
||||
} => {
|
||||
if state.is_pressed() {
|
||||
self.keys_pressed.insert(*code);
|
||||
} else {
|
||||
self.keys_pressed.remove(code);
|
||||
}
|
||||
}
|
||||
WindowEvent::MouseInput { state, button, .. } => {
|
||||
if state.is_pressed() {
|
||||
self.mouse_pressed.insert(*button);
|
||||
} else {
|
||||
self.mouse_pressed.remove(button);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_double_click(&mut self, button: MouseButton) -> bool {
|
||||
let now = Instant::now();
|
||||
let last = self.mouse_last_pressed.entry(button);
|
||||
|
||||
match last {
|
||||
std::collections::hash_map::Entry::Occupied(mut occupied_entry) => {
|
||||
let last = occupied_entry.insert(now);
|
||||
now.duration_since(last) < Duration::from_millis(400)
|
||||
}
|
||||
std::collections::hash_map::Entry::Vacant(vacant_entry) => {
|
||||
vacant_entry.insert(now);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn str_as_keycode(s: &str) -> Option<KeyCode> {
|
||||
Some(match s.to_uppercase().as_str() {
|
||||
// Letters
|
||||
"A" => KeyCode::KeyA,
|
||||
"B" => KeyCode::KeyB,
|
||||
"C" => KeyCode::KeyC,
|
||||
"D" => KeyCode::KeyD,
|
||||
"E" => KeyCode::KeyE,
|
||||
"F" => KeyCode::KeyF,
|
||||
"G" => KeyCode::KeyG,
|
||||
"H" => KeyCode::KeyH,
|
||||
"I" => KeyCode::KeyI,
|
||||
"J" => KeyCode::KeyJ,
|
||||
"K" => KeyCode::KeyK,
|
||||
"L" => KeyCode::KeyL,
|
||||
"M" => KeyCode::KeyM,
|
||||
"N" => KeyCode::KeyN,
|
||||
"O" => KeyCode::KeyO,
|
||||
"P" => KeyCode::KeyP,
|
||||
"Q" => KeyCode::KeyQ,
|
||||
"R" => KeyCode::KeyR,
|
||||
"S" => KeyCode::KeyS,
|
||||
"T" => KeyCode::KeyT,
|
||||
"U" => KeyCode::KeyU,
|
||||
"V" => KeyCode::KeyV,
|
||||
"W" => KeyCode::KeyW,
|
||||
"X" => KeyCode::KeyX,
|
||||
"Y" => KeyCode::KeyY,
|
||||
"Z" => KeyCode::KeyZ,
|
||||
|
||||
// Digits
|
||||
"0" => KeyCode::Digit0,
|
||||
"1" => KeyCode::Digit1,
|
||||
"2" => KeyCode::Digit2,
|
||||
"3" => KeyCode::Digit3,
|
||||
"4" => KeyCode::Digit4,
|
||||
"5" => KeyCode::Digit5,
|
||||
"6" => KeyCode::Digit6,
|
||||
"7" => KeyCode::Digit7,
|
||||
"8" => KeyCode::Digit8,
|
||||
"9" => KeyCode::Digit9,
|
||||
|
||||
// Modifiers
|
||||
"SHIFT" => KeyCode::ShiftLeft,
|
||||
"CTRL" => KeyCode::ControlLeft,
|
||||
"ALT" => KeyCode::AltLeft,
|
||||
|
||||
// F Keys
|
||||
"F1" => KeyCode::F1,
|
||||
"F2" => KeyCode::F2,
|
||||
"F3" => KeyCode::F3,
|
||||
"F4" => KeyCode::F4,
|
||||
"F5" => KeyCode::F5,
|
||||
"F6" => KeyCode::F6,
|
||||
"F7" => KeyCode::F7,
|
||||
"F8" => KeyCode::F8,
|
||||
"F9" => KeyCode::F9,
|
||||
"F10" => KeyCode::F10,
|
||||
"F11" => KeyCode::F11,
|
||||
"F12" => KeyCode::F12,
|
||||
|
||||
// Rest
|
||||
" " => KeyCode::Space,
|
||||
"BACK" => KeyCode::Backspace,
|
||||
"TAB" => KeyCode::Tab,
|
||||
"RETURN" => KeyCode::Enter,
|
||||
"ESCAPE" => KeyCode::Escape,
|
||||
"PAUSE" => KeyCode::Pause,
|
||||
"PAGEUP" => KeyCode::PageUp,
|
||||
"PAGEDOWN" => KeyCode::PageDown,
|
||||
"END" => KeyCode::End,
|
||||
"HOME" => KeyCode::Home,
|
||||
"PRINTSCREEN" => KeyCode::PrintScreen,
|
||||
"INSERT" => KeyCode::Insert,
|
||||
"DELETE" => KeyCode::Delete,
|
||||
"UP" => KeyCode::ArrowUp,
|
||||
"DOWN" => KeyCode::ArrowDown,
|
||||
"LEFT" => KeyCode::ArrowLeft,
|
||||
"RIGHT" => KeyCode::ArrowRight,
|
||||
"NUMLOCK" => KeyCode::NumLock,
|
||||
"SCROLL" => KeyCode::ScrollLock,
|
||||
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn keycode_as_str(code: KeyCode) -> Option<String> {
|
||||
Some(
|
||||
match code {
|
||||
// Letters
|
||||
KeyCode::KeyA => "a",
|
||||
KeyCode::KeyB => "b",
|
||||
KeyCode::KeyC => "c",
|
||||
KeyCode::KeyD => "d",
|
||||
KeyCode::KeyE => "e",
|
||||
KeyCode::KeyF => "f",
|
||||
KeyCode::KeyG => "g",
|
||||
KeyCode::KeyH => "h",
|
||||
KeyCode::KeyI => "i",
|
||||
KeyCode::KeyJ => "j",
|
||||
KeyCode::KeyK => "k",
|
||||
KeyCode::KeyL => "l",
|
||||
KeyCode::KeyM => "m",
|
||||
KeyCode::KeyN => "n",
|
||||
KeyCode::KeyO => "o",
|
||||
KeyCode::KeyP => "p",
|
||||
KeyCode::KeyQ => "q",
|
||||
KeyCode::KeyR => "r",
|
||||
KeyCode::KeyS => "s",
|
||||
KeyCode::KeyT => "t",
|
||||
KeyCode::KeyU => "u",
|
||||
KeyCode::KeyV => "v",
|
||||
KeyCode::KeyW => "w",
|
||||
KeyCode::KeyX => "x",
|
||||
KeyCode::KeyY => "y",
|
||||
KeyCode::KeyZ => "z",
|
||||
|
||||
// Digits
|
||||
KeyCode::Digit0 => "0",
|
||||
KeyCode::Digit1 => "1",
|
||||
KeyCode::Digit2 => "2",
|
||||
KeyCode::Digit3 => "3",
|
||||
KeyCode::Digit4 => "4",
|
||||
KeyCode::Digit5 => "5",
|
||||
KeyCode::Digit6 => "6",
|
||||
KeyCode::Digit7 => "7",
|
||||
KeyCode::Digit8 => "8",
|
||||
KeyCode::Digit9 => "9",
|
||||
|
||||
// Modifiers
|
||||
KeyCode::ShiftLeft => "SHIFT",
|
||||
KeyCode::ControlLeft => "CTRL",
|
||||
KeyCode::AltLeft => "ALT",
|
||||
|
||||
// F Keys
|
||||
KeyCode::F1 => "F1",
|
||||
KeyCode::F2 => "F2",
|
||||
KeyCode::F3 => "F3",
|
||||
KeyCode::F4 => "F4",
|
||||
KeyCode::F5 => "F5",
|
||||
KeyCode::F6 => "F6",
|
||||
KeyCode::F7 => "F7",
|
||||
KeyCode::F8 => "F8",
|
||||
KeyCode::F9 => "F9",
|
||||
KeyCode::F10 => "F10",
|
||||
KeyCode::F11 => "F11",
|
||||
KeyCode::F12 => "F12",
|
||||
|
||||
// Rest
|
||||
KeyCode::Space => " ",
|
||||
KeyCode::Backspace => "BACK",
|
||||
KeyCode::Tab => "TAB",
|
||||
KeyCode::Enter => "RETURN",
|
||||
KeyCode::Escape => "ESCAPE",
|
||||
KeyCode::Pause => "PAUSE",
|
||||
KeyCode::PageUp => "PAGEUP",
|
||||
KeyCode::PageDown => "PAGEDOWN",
|
||||
KeyCode::End => "END",
|
||||
KeyCode::Home => "HOME",
|
||||
KeyCode::PrintScreen => "PRINTSCREEN",
|
||||
KeyCode::Insert => "INSERT",
|
||||
KeyCode::Delete => "DELETE",
|
||||
KeyCode::ArrowUp => "UP",
|
||||
KeyCode::ArrowDown => "DOWN",
|
||||
KeyCode::ArrowLeft => "LEFT",
|
||||
KeyCode::ArrowRight => "RIGHT",
|
||||
KeyCode::NumLock => "NUMLOCK",
|
||||
KeyCode::ScrollLock => "SCROLL",
|
||||
|
||||
KeyCode::Equal => "+", // This is what PoB does
|
||||
KeyCode::Minus => "-",
|
||||
KeyCode::Comma => ",",
|
||||
KeyCode::Period => ".",
|
||||
KeyCode::Slash => "/",
|
||||
|
||||
KeyCode::NumpadAdd => "+",
|
||||
KeyCode::NumpadSubtract => "-",
|
||||
KeyCode::NumpadEnter => "RETURN",
|
||||
KeyCode::Numpad0 => "0",
|
||||
|
||||
_ => return None,
|
||||
}
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn str_as_mousebutton(s: &str) -> Option<MouseButton> {
|
||||
Some(match s.to_uppercase().as_str() {
|
||||
"LEFTBUTTON" => MouseButton::Left,
|
||||
"RIGHTBUTTON" => MouseButton::Right,
|
||||
"MIDDLEBUTTON" => MouseButton::Middle,
|
||||
"MOUSE4" => MouseButton::Back,
|
||||
"MOUSE5" => MouseButton::Forward,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn mousebutton_as_str(button: MouseButton) -> Option<String> {
|
||||
Some(
|
||||
match button {
|
||||
MouseButton::Left => "LEFTBUTTON",
|
||||
MouseButton::Right => "RIGHTBUTTON",
|
||||
MouseButton::Middle => "MIDDLEBUTTON",
|
||||
MouseButton::Back => "MOUSE4",
|
||||
MouseButton::Forward => "MOUSE5",
|
||||
_ => return None,
|
||||
}
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
use crate::args::Game;
|
||||
use anyhow::bail;
|
||||
use flate2::read::GzDecoder;
|
||||
use std::{
|
||||
fs::{self},
|
||||
io::copy,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
const REPO_NAME: &str = "meehl/RustyPathOfBuilding";
|
||||
|
||||
pub fn run_installer() -> anyhow::Result<()> {
|
||||
let script_dir = Game::script_dir();
|
||||
|
||||
// run installer iff Launch.lua doesn't exist, meaning this is likely the first run
|
||||
if script_dir.join("Launch.lua").exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
download_path_of_building(script_dir.as_path())?;
|
||||
replace_manifest(script_dir.as_path())?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Download latest release of Path of Building
|
||||
fn download_path_of_building<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
|
||||
log::info!("Downloading latest release of Path of Building...");
|
||||
|
||||
let repo = match Game::current() {
|
||||
Game::Poe1 => "PathOfBuildingCommunity/PathOfBuilding",
|
||||
Game::Poe2 => "PathOfBuildingCommunity/PathOfBuilding-PoE2",
|
||||
};
|
||||
let url = format!(
|
||||
"https://github.com/{}/archive/refs/heads/master.tar.gz",
|
||||
repo
|
||||
);
|
||||
|
||||
let response = ureq::get(url).call()?;
|
||||
|
||||
let body_reader = response.into_body().into_reader();
|
||||
let gz_decoder = GzDecoder::new(body_reader);
|
||||
let mut archive = tar::Archive::new(gz_decoder);
|
||||
|
||||
for file in archive.entries()? {
|
||||
let mut file = file?;
|
||||
let file_path = file.path()?;
|
||||
let components: Vec<_> = file_path.components().collect();
|
||||
|
||||
let target_path = match components.len() {
|
||||
0..=1 => None,
|
||||
// put these into target_dir/
|
||||
2 => {
|
||||
let filename = components[1].as_os_str();
|
||||
if filename == "manifest.xml"
|
||||
|| filename == "help.txt"
|
||||
|| filename == "changelog.txt"
|
||||
|| filename == "LICENSE.md"
|
||||
{
|
||||
Some(target_dir.as_ref().join(filename))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
// put lua runtime files into target_dir/lua/
|
||||
3.. => {
|
||||
if components[1].as_os_str() == "src"
|
||||
|| (components[1].as_os_str() == "runtime"
|
||||
&& components[2].as_os_str() == "lua")
|
||||
{
|
||||
Some(
|
||||
target_dir
|
||||
.as_ref()
|
||||
.join(components[2..].iter().collect::<PathBuf>()),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// create needed directories and extract
|
||||
if let Some(target_path) = target_path {
|
||||
if let Some(parent) = target_path.parent() {
|
||||
fs::create_dir_all(parent)?;
|
||||
}
|
||||
file.unpack(&target_path)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replace manifest and UpdateCheck with RustyPathOfBuilding's modified versions
|
||||
/// This is needed to make updating work without writing our own update system.
|
||||
fn replace_manifest<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
|
||||
log::info!("Replacing manifest...");
|
||||
|
||||
let game_path = match Game::current() {
|
||||
Game::Poe1 => "lua/poe1",
|
||||
Game::Poe2 => "lua/poe2",
|
||||
};
|
||||
|
||||
// Download on overwrite files
|
||||
download_file(
|
||||
&format!(
|
||||
"https://raw.githubusercontent.com/{REPO_NAME}/master/{}/{}",
|
||||
game_path, "manifest.xml"
|
||||
),
|
||||
target_dir.as_ref().join("manifest.xml"),
|
||||
)?;
|
||||
|
||||
download_file(
|
||||
&format!(
|
||||
"https://raw.githubusercontent.com/{REPO_NAME}/master/{}/{}",
|
||||
game_path, "UpdateCheck.lua"
|
||||
),
|
||||
target_dir.as_ref().join("UpdateCheck.lua"),
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn download_file<P: AsRef<Path>>(url: &str, file_path: P) -> anyhow::Result<()> {
|
||||
let response = ureq::get(url).call()?;
|
||||
|
||||
if response.status().is_success() {
|
||||
let body = response.into_body();
|
||||
let mut file = fs::File::create(file_path)?;
|
||||
copy(&mut body.into_reader(), &mut file)?;
|
||||
Ok(())
|
||||
} else {
|
||||
bail!("Unable to download: {}", url);
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::{
|
||||
dpi::LogicalRect,
|
||||
math::Rect,
|
||||
renderer::primitives::{
|
||||
ClippedPrimitive, DrawPrimitive, QuadPrimitive, RectPrimitive, TextPrimitive,
|
||||
},
|
||||
};
|
||||
|
||||
/// Holds the draw primitives for each layer.
|
||||
///
|
||||
/// Adding a primitive places it in currently set layer. Positions are interpreted as being relative to
|
||||
/// the current viewport. They are translated into absolute positions (screen positions) and
|
||||
/// clipped by the viewport.
|
||||
pub struct Layers {
|
||||
layers: BTreeMap<(i32, i32), Vec<ClippedPrimitive>>,
|
||||
current_layer: (i32, i32),
|
||||
viewport: LogicalRect<f32>,
|
||||
}
|
||||
|
||||
impl Layers {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
layers: Default::default(),
|
||||
current_layer: (0, 0),
|
||||
viewport: Rect::zero(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.current_layer = (0, 0);
|
||||
self.layers.clear();
|
||||
}
|
||||
|
||||
/// Consume primitives and return an iterator over them in drawing order.
|
||||
pub fn consume_layers(&mut self) -> impl Iterator<Item = ClippedPrimitive> {
|
||||
let layers = std::mem::take(&mut self.layers);
|
||||
layers.into_values().flatten()
|
||||
}
|
||||
|
||||
pub fn set_viewport(&mut self, viewport: LogicalRect<f32>) {
|
||||
self.viewport = viewport;
|
||||
}
|
||||
|
||||
pub fn set_draw_layer(&mut self, layer: i32, sublayer: i32) {
|
||||
self.current_layer = (layer, sublayer);
|
||||
}
|
||||
|
||||
pub fn set_draw_sublayer(&mut self, sublayer: i32) {
|
||||
self.set_draw_layer(self.current_layer.0, sublayer);
|
||||
}
|
||||
|
||||
pub fn add_rect(&mut self, mut rect: RectPrimitive) {
|
||||
rect.translate(self.viewport.min.to_vector());
|
||||
|
||||
let clipped_primitive = ClippedPrimitive {
|
||||
clip_rect: self.viewport,
|
||||
primitive: DrawPrimitive::Rect(rect),
|
||||
};
|
||||
|
||||
self.push(clipped_primitive);
|
||||
}
|
||||
|
||||
pub fn add_quad(&mut self, mut quad: QuadPrimitive) {
|
||||
quad.translate(self.viewport.min.to_vector());
|
||||
|
||||
let clipped_primitive = ClippedPrimitive {
|
||||
clip_rect: self.viewport,
|
||||
primitive: DrawPrimitive::Quad(quad),
|
||||
};
|
||||
|
||||
self.push(clipped_primitive);
|
||||
}
|
||||
|
||||
pub fn add_text(&mut self, mut text: TextPrimitive, is_absolute_position: bool) {
|
||||
if !is_absolute_position {
|
||||
text.translate(self.viewport.min.to_vector());
|
||||
};
|
||||
|
||||
let clipped_primitive = ClippedPrimitive {
|
||||
clip_rect: self.viewport,
|
||||
primitive: DrawPrimitive::Text(text),
|
||||
};
|
||||
|
||||
self.push(clipped_primitive);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn push(&mut self, clipped_primitive: ClippedPrimitive) {
|
||||
self.layers
|
||||
.entry(self.current_layer)
|
||||
.or_default()
|
||||
.push(clipped_primitive);
|
||||
}
|
||||
}
|
||||
|
||||
impl std::hash::Hash for Layers {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.layers.hash(state);
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
|
||||
use clap::Parser;
|
||||
use mlua::{Lua, Result as LuaResult, Table};
|
||||
|
||||
use crate::{
|
||||
Game,
|
||||
api::{self, get_callback},
|
||||
args::Args,
|
||||
subscript::{NativeMultiValue, SubscriptManager, SubscriptResult, register_subscript_globals},
|
||||
util::{change_working_directory, get_executable_dir},
|
||||
};
|
||||
|
||||
pub struct LuaInstance {
|
||||
lua: Lua,
|
||||
subscript_manager: Rc<RefCell<SubscriptManager>>,
|
||||
}
|
||||
|
||||
impl LuaInstance {
|
||||
pub fn new() -> anyhow::Result<Self> {
|
||||
let subscript_manager = Rc::new(RefCell::new(SubscriptManager::new()));
|
||||
|
||||
let lua = Self::create_lua_state()?;
|
||||
register_subscript_globals(&lua, &subscript_manager)?;
|
||||
|
||||
let instance = Self {
|
||||
lua,
|
||||
subscript_manager,
|
||||
};
|
||||
|
||||
instance.init()?;
|
||||
|
||||
Ok(instance)
|
||||
}
|
||||
|
||||
fn create_lua_state() -> LuaResult<Lua> {
|
||||
// SAFETY: use `unsafe_new` to allow loading of C modules
|
||||
let lua = unsafe { Lua::unsafe_new() };
|
||||
|
||||
// expose build arg to lua
|
||||
let args = Args::parse();
|
||||
let args_table = lua.create_sequence_from(std::iter::once(args.build_path))?;
|
||||
lua.globals().set("arg", args_table)?;
|
||||
|
||||
// add ./lua to package.path and package.cpath
|
||||
Self::register_package_paths(&lua)?;
|
||||
|
||||
// register callbacks
|
||||
api::register_globals(&lua)?;
|
||||
|
||||
Ok(lua)
|
||||
}
|
||||
|
||||
pub fn init(&self) -> LuaResult<()> {
|
||||
let script_dir = Game::script_dir();
|
||||
change_working_directory(script_dir.as_path())?;
|
||||
self.load(script_dir.join("Launch.lua")).exec()?;
|
||||
self.on_init()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn restart(&mut self) -> LuaResult<()> {
|
||||
self.lua = Self::create_lua_state()?;
|
||||
register_subscript_globals(&self.lua, &self.subscript_manager)?;
|
||||
self.init()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run functions for subscripts and handle their completion/failure.
|
||||
pub fn handle_subscripts(&self) {
|
||||
let subscript_events = self.subscript_manager.borrow_mut().process(self);
|
||||
|
||||
// Handle finished/errored subscripts.
|
||||
for event in subscript_events {
|
||||
match event {
|
||||
SubscriptResult::SubscriptFinished { id, return_values } => {
|
||||
self.on_sub_finished(id, return_values).unwrap();
|
||||
}
|
||||
SubscriptResult::SubscriptError { id, error } => {
|
||||
self.on_sub_error(id, &error).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_init(&self) -> LuaResult<()> {
|
||||
let on_init = get_callback(&self.lua, "OnInit")?;
|
||||
on_init.call::<()>(())
|
||||
}
|
||||
|
||||
pub fn on_frame(&self) -> LuaResult<()> {
|
||||
profiling::scope!("on_frame");
|
||||
|
||||
let on_frame = get_callback(&self.lua, "OnFrame")?;
|
||||
on_frame.call::<()>(())
|
||||
}
|
||||
|
||||
pub fn on_char(&self, ch: &str) -> LuaResult<()> {
|
||||
let on_char = get_callback(&self.lua, "OnChar")?;
|
||||
on_char.call::<()>(ch)
|
||||
}
|
||||
|
||||
pub fn on_key_down(&self, key: &str, is_double_click: bool) -> LuaResult<()> {
|
||||
let on_key_down = get_callback(&self.lua, "OnKeyDown")?;
|
||||
on_key_down.call::<()>((key, is_double_click))
|
||||
}
|
||||
|
||||
pub fn on_key_up(&self, key: &str) -> LuaResult<()> {
|
||||
let on_key_up = get_callback(&self.lua, "OnKeyUp")?;
|
||||
on_key_up.call::<()>(key)
|
||||
}
|
||||
|
||||
pub fn on_sub_finished(&self, id: u64, return_values: NativeMultiValue) -> LuaResult<()> {
|
||||
let on_sub_finished = get_callback(&self.lua, "OnSubFinished")?;
|
||||
on_sub_finished.call::<()>((id, return_values))
|
||||
}
|
||||
|
||||
pub fn on_sub_error(&self, id: u64, error: &str) -> LuaResult<()> {
|
||||
let on_sub_error = get_callback(&self.lua, "OnSubError")?;
|
||||
on_sub_error.call::<()>((id, error))
|
||||
}
|
||||
|
||||
pub fn on_exit(&self) -> LuaResult<()> {
|
||||
let on_exit = get_callback(&self.lua, "OnExit")?;
|
||||
on_exit.call::<()>(())
|
||||
}
|
||||
|
||||
pub fn register_package_paths(lua: &Lua) -> LuaResult<()> {
|
||||
let script_dir = Game::script_dir();
|
||||
let package: Table = lua.globals().get("package")?;
|
||||
let mut package_path: String = package.get("path")?;
|
||||
package_path.push(';');
|
||||
package_path.push_str(script_dir.join("lua/?.lua").to_str().unwrap());
|
||||
package_path.push(';');
|
||||
package_path.push_str(script_dir.join("lua/?/init.lua").to_str().unwrap());
|
||||
package.set("path", package_path)?;
|
||||
|
||||
let mut package_cpath: String = package.get("cpath")?;
|
||||
let exe_dir = get_executable_dir()?;
|
||||
package_cpath.push(';');
|
||||
#[cfg(target_os = "linux")]
|
||||
package_cpath.push_str(exe_dir.join("lua/?.so").to_str().unwrap());
|
||||
#[cfg(target_os = "windows")]
|
||||
package_cpath.push_str(exe_dir.join("lua/?.dll").to_str().unwrap());
|
||||
package.set("cpath", package_cpath)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for LuaInstance {
|
||||
type Target = Lua;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.lua
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
use crate::app::App;
|
||||
use crate::args::{Args, Game};
|
||||
use crate::installer::run_installer;
|
||||
use clap::Parser;
|
||||
use winit::event_loop::EventLoop;
|
||||
|
||||
mod api;
|
||||
mod app;
|
||||
mod args;
|
||||
mod color;
|
||||
mod context;
|
||||
mod dpi;
|
||||
mod fonts;
|
||||
mod gfx;
|
||||
mod input;
|
||||
mod installer;
|
||||
mod layers;
|
||||
mod lua;
|
||||
mod math;
|
||||
mod renderer;
|
||||
mod subscript;
|
||||
mod util;
|
||||
mod worker_pool;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
profiling::register_thread!("Main Thread");
|
||||
env_logger::init();
|
||||
|
||||
#[cfg(feature = "profile-with-puffin")]
|
||||
let _puffin_server = {
|
||||
let server_addr = format!("127.0.0.1:{}", puffin_http::DEFAULT_PORT);
|
||||
let server = puffin_http::Server::new(&server_addr).unwrap();
|
||||
eprintln!("Serving profiling data on {server_addr}. Run `puffin_viewer` to view it.");
|
||||
profiling::puffin::set_scopes_on(true);
|
||||
server
|
||||
};
|
||||
|
||||
let args = Args::parse();
|
||||
Game::init(args.game);
|
||||
|
||||
run_installer()?;
|
||||
|
||||
let mut app = App::new()?;
|
||||
|
||||
let event_loop = EventLoop::with_user_event().build()?;
|
||||
event_loop.run_app(&mut app)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
pub use euclid::Box2D as Rect;
|
||||
pub use euclid::Point2D as Point;
|
||||
pub use euclid::Size2D as Size;
|
||||
pub use euclid::Vector2D as Vector;
|
||||
pub use quad::Quad;
|
||||
|
||||
mod quad;
|
||||
|
||||
pub trait Corners<T, U> {
|
||||
fn top_left(&self) -> Point<T, U>;
|
||||
fn top_right(&self) -> Point<T, U>;
|
||||
fn bottom_left(&self) -> Point<T, U>;
|
||||
fn bottom_right(&self) -> Point<T, U>;
|
||||
}
|
||||
|
||||
impl<T, U> Corners<T, U> for Rect<T, U>
|
||||
where
|
||||
T: Copy,
|
||||
{
|
||||
#[inline]
|
||||
fn top_left(&self) -> Point<T, U> {
|
||||
self.min
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn top_right(&self) -> Point<T, U> {
|
||||
Point::new(self.max.x, self.min.y)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn bottom_left(&self) -> Point<T, U> {
|
||||
Point::new(self.min.x, self.max.y)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn bottom_right(&self) -> Point<T, U> {
|
||||
self.max
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
use crate::math::{Point, Size, Vector};
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use euclid::num::Zero;
|
||||
use std::fmt;
|
||||
use std::hash::Hash;
|
||||
use std::ops::Add;
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Quad<T, U> {
|
||||
pub p0: Point<T, U>,
|
||||
pub p1: Point<T, U>,
|
||||
pub p2: Point<T, U>,
|
||||
pub p3: Point<T, U>,
|
||||
}
|
||||
|
||||
impl<T: Copy, U> Copy for Quad<T, U> {}
|
||||
|
||||
impl<T: Clone, U> Clone for Quad<T, U> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
p0: self.p0.clone(),
|
||||
p1: self.p1.clone(),
|
||||
p2: self.p2.clone(),
|
||||
p3: self.p3.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> Eq for Quad<T, U> where T: Eq {}
|
||||
|
||||
impl<T, U> PartialEq for Quad<T, U>
|
||||
where
|
||||
T: PartialEq,
|
||||
{
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.p0 == other.p0 && self.p1 == other.p1 && self.p2 == other.p2 && self.p3 == other.p3
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Debug, U> fmt::Debug for Quad<T, U> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
f.debug_tuple("Quad")
|
||||
.field(&self.p0)
|
||||
.field(&self.p1)
|
||||
.field(&self.p2)
|
||||
.field(&self.p3)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Default, U> Default for Quad<T, U> {
|
||||
fn default() -> Self {
|
||||
Self::new(
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> Hash for Quad<T, U>
|
||||
where
|
||||
T: Hash,
|
||||
{
|
||||
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.p0.hash(state);
|
||||
self.p1.hash(state);
|
||||
self.p2.hash(state);
|
||||
self.p3.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: PhantomData in Point is zero-sized and repr(C) guarantees consistent layout
|
||||
unsafe impl<T: Zeroable, U> Zeroable for Quad<T, U> {}
|
||||
unsafe impl<T: Pod, U: 'static> Pod for Quad<T, U> {}
|
||||
|
||||
impl<T, U> Quad<T, U> {
|
||||
#[inline]
|
||||
pub const fn new(p0: Point<T, U>, p1: Point<T, U>, p2: Point<T, U>, p3: Point<T, U>) -> Self {
|
||||
Self { p0, p1, p2, p3 }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> Quad<T, U>
|
||||
where
|
||||
T: Copy,
|
||||
{
|
||||
/// Creates a `Quad` of the given size, at offset zero.
|
||||
#[inline]
|
||||
pub fn from_size(size: Size<T, U>) -> Self
|
||||
where
|
||||
T: Zero,
|
||||
{
|
||||
Quad {
|
||||
p0: Point::zero(),
|
||||
p1: Point::new(size.width, Zero::zero()),
|
||||
p2: Point::new(size.width, size.height),
|
||||
p3: Point::new(Zero::zero(), size.height),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> Quad<T, U>
|
||||
where
|
||||
T: Zero,
|
||||
{
|
||||
/// Constructor, setting all points to zero.
|
||||
pub fn zero() -> Self {
|
||||
Quad::new(Point::zero(), Point::zero(), Point::zero(), Point::zero())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> Quad<T, U>
|
||||
where
|
||||
T: Copy + Add<T, Output = T>,
|
||||
{
|
||||
/// Returns the same quad, translated by a vector.
|
||||
#[inline]
|
||||
pub fn translate(&self, by: Vector<T, U>) -> Self {
|
||||
Self::new(self.p0 + by, self.p1 + by, self.p2 + by, self.p3 + by)
|
||||
}
|
||||
}
|
||||
+635
@@ -0,0 +1,635 @@
|
||||
use crate::{
|
||||
dpi::{ConvertToLogical, ConvertToPhysical, LogicalSize, PhysicalRect, PhysicalSize},
|
||||
math::Point,
|
||||
renderer::{
|
||||
image::ImageData,
|
||||
mesh::{ClippedMesh, Vertex},
|
||||
textures::{TextureId, TextureOptions, TexturesDelta},
|
||||
},
|
||||
};
|
||||
use ahash::HashMap;
|
||||
use std::{borrow::Cow, num::NonZeroU64, ops::Range};
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
pub mod image;
|
||||
pub mod mesh;
|
||||
mod mipmap;
|
||||
pub mod primitives;
|
||||
pub mod tessellator;
|
||||
pub mod textures;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Texture {
|
||||
texture: wgpu::Texture,
|
||||
bind_group: wgpu::BindGroup,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct Globals {
|
||||
screen_size: LogicalSize<f32>,
|
||||
}
|
||||
|
||||
pub struct Renderer {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
|
||||
index_buffer: SlicedBuffer,
|
||||
vertex_buffer: SlicedBuffer,
|
||||
|
||||
globals_buffer: wgpu::Buffer,
|
||||
previous_globals: Globals,
|
||||
globals_bind_group: wgpu::BindGroup,
|
||||
texture_bind_group_layout: wgpu::BindGroupLayout,
|
||||
|
||||
textures: HashMap<TextureId, Texture>,
|
||||
samplers: HashMap<TextureOptions, wgpu::Sampler>,
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
output_color_format: wgpu::TextureFormat,
|
||||
output_depth_format: Option<wgpu::TextureFormat>,
|
||||
) -> Self {
|
||||
let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("main_shader_module"),
|
||||
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("renderer/main.wgsl"))),
|
||||
});
|
||||
|
||||
let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("globals_uniform_buffer"),
|
||||
contents: bytemuck::cast_slice(&[Globals {
|
||||
screen_size: LogicalSize::zero(),
|
||||
}]),
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
});
|
||||
|
||||
let globals_bind_group_layout =
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("globals_uniform_bind_group_layout"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX | wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: NonZeroU64::new(std::mem::size_of::<Globals>() as _),
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
});
|
||||
|
||||
let globals_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("globals_uniform_bind_group"),
|
||||
layout: &globals_bind_group_layout,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
|
||||
buffer: &uniform_buffer,
|
||||
offset: 0,
|
||||
size: None,
|
||||
}),
|
||||
}],
|
||||
});
|
||||
|
||||
let texture_bind_group_layout =
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("texture_bind_group_layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
multisampled: false,
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu::TextureViewDimension::D2Array,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("pipeline_layout"),
|
||||
bind_group_layouts: &[&globals_bind_group_layout, &texture_bind_group_layout],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
|
||||
let depth_stencil = output_depth_format.map(|format| wgpu::DepthStencilState {
|
||||
format,
|
||||
depth_write_enabled: false,
|
||||
depth_compare: wgpu::CompareFunction::Always,
|
||||
stencil: wgpu::StencilState::default(),
|
||||
bias: wgpu::DepthBiasState::default(),
|
||||
});
|
||||
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("render_pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
entry_point: Some("vs_main"),
|
||||
module: &shader_module,
|
||||
buffers: &[wgpu::VertexBufferLayout {
|
||||
// 4x f32, 2x u32 -> 6 * 4 bytes
|
||||
array_stride: 6 * 4,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
// 0: vec2 position
|
||||
// 1: vec2 texture coordinates
|
||||
// 2: uint color
|
||||
// 3: uint layer_idx
|
||||
attributes: &wgpu::vertex_attr_array![0 => Float32x2, 1 => Float32x2, 2 => Uint32, 3 => Uint32],
|
||||
}],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default()
|
||||
},
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
unclipped_depth: false,
|
||||
conservative: false,
|
||||
cull_mode: None,
|
||||
front_face: wgpu::FrontFace::default(),
|
||||
polygon_mode: wgpu::PolygonMode::default(),
|
||||
strip_index_format: None,
|
||||
},
|
||||
depth_stencil,
|
||||
multisample: wgpu::MultisampleState {
|
||||
alpha_to_coverage_enabled: false,
|
||||
count: 1,
|
||||
mask: !0,
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader_module,
|
||||
entry_point: Some("fs_main"),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: output_color_format,
|
||||
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default()
|
||||
}),
|
||||
multiview: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let vertex_buffer = SlicedBuffer::new(
|
||||
device,
|
||||
wgpu::BufferUsages::VERTEX,
|
||||
NonZeroU64::new(2048).expect("2048 is non-zero"),
|
||||
NonZeroU64::new(std::mem::size_of::<Vertex>() as u64)
|
||||
.expect("size of vertex is non-zero"),
|
||||
);
|
||||
let index_buffer = SlicedBuffer::new(
|
||||
device,
|
||||
wgpu::BufferUsages::INDEX,
|
||||
NonZeroU64::new(2048 * 3).expect("2048 * 3 is non-zero"),
|
||||
NonZeroU64::new(std::mem::size_of::<u32>() as u64).expect("size of u32 is non-zero"),
|
||||
);
|
||||
|
||||
Self {
|
||||
pipeline,
|
||||
vertex_buffer,
|
||||
index_buffer,
|
||||
globals_buffer: uniform_buffer,
|
||||
previous_globals: Globals {
|
||||
screen_size: LogicalSize::zero(),
|
||||
},
|
||||
globals_bind_group,
|
||||
texture_bind_group_layout,
|
||||
textures: HashMap::default(),
|
||||
samplers: HashMap::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(
|
||||
&self,
|
||||
render_pass: &mut wgpu::RenderPass<'static>,
|
||||
paint_jobs: &[ClippedMesh],
|
||||
screen_size: PhysicalSize<u32>,
|
||||
pixels_per_point: f32,
|
||||
) {
|
||||
profiling::scope!("render");
|
||||
|
||||
let screen_rect = PhysicalRect::from_origin_and_size(Point::zero(), screen_size);
|
||||
let mut index_buffer_slices = self.index_buffer.slices.iter();
|
||||
let mut vertex_buffer_slices = self.vertex_buffer.slices.iter();
|
||||
|
||||
render_pass.set_viewport(
|
||||
0.0,
|
||||
0.0,
|
||||
screen_size.width as f32,
|
||||
screen_size.height as f32,
|
||||
0.0,
|
||||
1.0,
|
||||
);
|
||||
render_pass.set_pipeline(&self.pipeline);
|
||||
render_pass.set_bind_group(0, &self.globals_bind_group, &[]);
|
||||
|
||||
for ClippedMesh { clip_rect, mesh } in paint_jobs {
|
||||
let phys_clip_rect = clip_rect.to_physical::<f32, _>(pixels_per_point).round();
|
||||
let scissor = phys_clip_rect
|
||||
// NOTE: can't cast to u32 directly because negative values cause a panic
|
||||
.cast::<i32>()
|
||||
.intersection(&screen_rect.to_i32())
|
||||
.map(|s| s.to_u32());
|
||||
|
||||
let Some(scissor) = scissor else {
|
||||
index_buffer_slices.next().unwrap();
|
||||
vertex_buffer_slices.next().unwrap();
|
||||
continue;
|
||||
};
|
||||
|
||||
render_pass.set_scissor_rect(
|
||||
scissor.min.x,
|
||||
scissor.min.y,
|
||||
scissor.width(),
|
||||
scissor.height(),
|
||||
);
|
||||
|
||||
let index_buffer_slice = index_buffer_slices.next().unwrap();
|
||||
let vertex_buffer_slice = vertex_buffer_slices.next().unwrap();
|
||||
|
||||
if let Some(Texture { bind_group, .. }) = self.textures.get(&mesh.texture_id) {
|
||||
render_pass.set_bind_group(1, bind_group, &[]);
|
||||
render_pass.set_index_buffer(
|
||||
self.index_buffer
|
||||
.buffer
|
||||
.slice(index_buffer_slice.start as u64..index_buffer_slice.end as u64),
|
||||
wgpu::IndexFormat::Uint32,
|
||||
);
|
||||
render_pass.set_vertex_buffer(
|
||||
0,
|
||||
self.vertex_buffer
|
||||
.buffer
|
||||
.slice(vertex_buffer_slice.start as u64..vertex_buffer_slice.end as u64),
|
||||
);
|
||||
render_pass.draw_indexed(0..mesh.indices.len() as u32, 0, 0..1);
|
||||
} else {
|
||||
log::warn!("Missing texture: {:?}", mesh.texture_id);
|
||||
}
|
||||
}
|
||||
|
||||
render_pass.set_scissor_rect(0, 0, screen_size.width, screen_size.height);
|
||||
}
|
||||
|
||||
/// Uploads texture data.
|
||||
/// Needs to be called before [`Self::render`].
|
||||
pub fn update_textures(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
textures_delta: &TexturesDelta,
|
||||
) {
|
||||
profiling::scope!("update_textures");
|
||||
|
||||
for (id, image_delta) in &textures_delta.update {
|
||||
let ImageData {
|
||||
format,
|
||||
width,
|
||||
height,
|
||||
array_layers,
|
||||
mipmap_count,
|
||||
data_order,
|
||||
ref bytes,
|
||||
} = image_delta.image;
|
||||
|
||||
let size = wgpu::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: array_layers,
|
||||
};
|
||||
|
||||
// only generate mipmaps for uncompressed images that don't already have mipmaps
|
||||
let gen_mipmaps = image_delta.options.generate_mipmaps
|
||||
&& mipmap_count.get() == 1
|
||||
&& !format.is_compressed();
|
||||
|
||||
let mip_level_count = if gen_mipmaps {
|
||||
size.max_mips(wgpu::TextureDimension::D2)
|
||||
} else {
|
||||
mipmap_count.get()
|
||||
};
|
||||
|
||||
let label_str = format!("texture_{id:?}");
|
||||
let label = Some(label_str.as_str());
|
||||
|
||||
let texture = create_texture_with_data(
|
||||
device,
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
label,
|
||||
size,
|
||||
mip_level_count,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[format.add_srgb_suffix()],
|
||||
},
|
||||
data_order.into(),
|
||||
bytes,
|
||||
gen_mipmaps,
|
||||
);
|
||||
|
||||
if gen_mipmaps {
|
||||
mipmap::generate_mipmap_chain(queue, &texture, bytes);
|
||||
}
|
||||
|
||||
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
dimension: Some(wgpu::TextureViewDimension::D2Array),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let sampler = self
|
||||
.samplers
|
||||
.entry(image_delta.options)
|
||||
.or_insert_with(|| create_sampler(image_delta.options, device));
|
||||
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label,
|
||||
layout: &self.texture_bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(&texture_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::Sampler(sampler),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
self.textures.insert(
|
||||
*id,
|
||||
Texture {
|
||||
texture,
|
||||
bind_group,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn free_textures(&mut self, textures_delta: &TexturesDelta) {
|
||||
profiling::scope!("free_textures");
|
||||
|
||||
for id in &textures_delta.free {
|
||||
if let Some(texture) = self.textures.remove(id) {
|
||||
texture.texture.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the vertex, index, and uniform buffers.
|
||||
/// Needs to be called before [`Self::render`].
|
||||
pub fn update_buffers(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
paint_jobs: &[ClippedMesh],
|
||||
screen_size: PhysicalSize<u32>,
|
||||
pixels_per_point: f32,
|
||||
) {
|
||||
profiling::scope!("update_buffers");
|
||||
|
||||
let uniform_buffer_content = Globals {
|
||||
screen_size: screen_size.to_logical(pixels_per_point),
|
||||
};
|
||||
|
||||
// update globals uniform buffer
|
||||
if uniform_buffer_content != self.previous_globals {
|
||||
queue.write_buffer(
|
||||
&self.globals_buffer,
|
||||
0,
|
||||
bytemuck::cast_slice(&[uniform_buffer_content]),
|
||||
);
|
||||
self.previous_globals = uniform_buffer_content;
|
||||
}
|
||||
|
||||
// count how many vertices & indices need to be rendered
|
||||
let (vertex_count, index_count) = {
|
||||
paint_jobs.iter().fold((0, 0), |acc, clipped_mesh| {
|
||||
(
|
||||
acc.0 + clipped_mesh.mesh.vertices.len(),
|
||||
acc.1 + clipped_mesh.mesh.indices.len(),
|
||||
)
|
||||
})
|
||||
};
|
||||
|
||||
// update index and vertex buffers
|
||||
if index_count > 0 && vertex_count > 0 {
|
||||
self.index_buffer.slices.clear();
|
||||
self.vertex_buffer.slices.clear();
|
||||
|
||||
let mut staging_index_buffer = self.index_buffer.create_staging_buffer(
|
||||
device,
|
||||
queue,
|
||||
NonZeroU64::new(index_count as u64).expect("index_count > 0"),
|
||||
);
|
||||
let mut staging_vertex_buffer = self.vertex_buffer.create_staging_buffer(
|
||||
device,
|
||||
queue,
|
||||
NonZeroU64::new(vertex_count as u64).expect("vertex_count > 0"),
|
||||
);
|
||||
|
||||
let mut index_offset = 0;
|
||||
let mut vertex_offset = 0;
|
||||
for ClippedMesh { mesh, .. } in paint_jobs {
|
||||
{
|
||||
let size = mesh.indices.len() * std::mem::size_of::<u32>();
|
||||
let slice = index_offset..(index_offset + size);
|
||||
staging_index_buffer[slice.clone()]
|
||||
.copy_from_slice(bytemuck::cast_slice(&mesh.indices));
|
||||
self.index_buffer.slices.push(slice);
|
||||
index_offset += size;
|
||||
}
|
||||
{
|
||||
let size = mesh.vertices.len() * std::mem::size_of::<Vertex>();
|
||||
let slice = vertex_offset..(vertex_offset + size);
|
||||
staging_vertex_buffer[slice.clone()]
|
||||
.copy_from_slice(bytemuck::cast_slice(&mesh.vertices));
|
||||
self.vertex_buffer.slices.push(slice);
|
||||
vertex_offset += size;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SlicedBuffer {
|
||||
buffer: wgpu::Buffer,
|
||||
slices: Vec<Range<usize>>,
|
||||
size: wgpu::BufferSize,
|
||||
usage: wgpu::BufferUsages,
|
||||
stride: NonZeroU64,
|
||||
}
|
||||
|
||||
impl SlicedBuffer {
|
||||
fn new(
|
||||
device: &wgpu::Device,
|
||||
usage: wgpu::BufferUsages,
|
||||
start_capacity: NonZeroU64,
|
||||
stride: NonZeroU64,
|
||||
) -> Self {
|
||||
let size = start_capacity.checked_mul(stride).unwrap();
|
||||
|
||||
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
usage: usage | wgpu::BufferUsages::COPY_DST,
|
||||
size: size.get(),
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
Self {
|
||||
buffer,
|
||||
slices: Vec::with_capacity(64),
|
||||
size,
|
||||
usage,
|
||||
stride,
|
||||
}
|
||||
}
|
||||
|
||||
fn create_staging_buffer(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
required_capacity: NonZeroU64,
|
||||
) -> wgpu::QueueWriteBufferView {
|
||||
let required_size = required_capacity.checked_mul(self.stride).unwrap();
|
||||
|
||||
// resize buffer to required size
|
||||
if self.size < required_size {
|
||||
self.buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: None,
|
||||
usage: self.usage | wgpu::BufferUsages::COPY_DST,
|
||||
size: required_size.get(),
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
self.size = required_size;
|
||||
}
|
||||
|
||||
let staging_buffer = queue.write_buffer_with(&self.buffer, 0, required_size);
|
||||
let Some(staging_buffer) = staging_buffer else {
|
||||
panic!("Failed to create staging buffer!");
|
||||
};
|
||||
staging_buffer
|
||||
}
|
||||
}
|
||||
|
||||
fn create_sampler(options: TextureOptions, device: &wgpu::Device) -> wgpu::Sampler {
|
||||
let TextureOptions {
|
||||
magnification,
|
||||
minification,
|
||||
wrap_mode,
|
||||
mipmap_mode,
|
||||
..
|
||||
} = options;
|
||||
device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some(&format!(
|
||||
"sampler (mag: {magnification:?}, min {minification:?})"
|
||||
)),
|
||||
mag_filter: magnification,
|
||||
min_filter: minification,
|
||||
address_mode_u: wrap_mode,
|
||||
address_mode_v: wrap_mode,
|
||||
mipmap_filter: mipmap_mode,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Adapted from `wgpu::Device::create_texture_with_data`.
|
||||
/// Doesn't upload any data for mip level > 0 if skip_mipmaps is true.
|
||||
fn create_texture_with_data(
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
desc: &wgpu::TextureDescriptor<'_>,
|
||||
order: wgpu::wgt::TextureDataOrder,
|
||||
data: &[u8],
|
||||
skip_mipmaps: bool,
|
||||
) -> wgpu::Texture {
|
||||
// Implicitly add the COPY_DST usage
|
||||
let mut desc = desc.to_owned();
|
||||
desc.usage |= wgpu::TextureUsages::COPY_DST;
|
||||
let texture = device.create_texture(&desc);
|
||||
|
||||
// Will return None only if it's a combined depth-stencil format
|
||||
// If so, default to 4, validation will fail later anyway since the depth or stencil
|
||||
// aspect needs to be written to individually
|
||||
let block_size = desc.format.block_copy_size(None).unwrap_or(4);
|
||||
let (block_width, block_height) = desc.format.block_dimensions();
|
||||
let layer_iterations = desc.array_layer_count();
|
||||
|
||||
let outer_iteration;
|
||||
let inner_iteration;
|
||||
match order {
|
||||
wgpu::wgt::TextureDataOrder::LayerMajor => {
|
||||
outer_iteration = layer_iterations;
|
||||
inner_iteration = desc.mip_level_count;
|
||||
}
|
||||
wgpu::wgt::TextureDataOrder::MipMajor => {
|
||||
outer_iteration = desc.mip_level_count;
|
||||
inner_iteration = layer_iterations;
|
||||
}
|
||||
}
|
||||
|
||||
let mut binary_offset = 0;
|
||||
for outer in 0..outer_iteration {
|
||||
for inner in 0..inner_iteration {
|
||||
let (layer, mip) = match order {
|
||||
wgpu::wgt::TextureDataOrder::LayerMajor => (outer, inner),
|
||||
wgpu::wgt::TextureDataOrder::MipMajor => (inner, outer),
|
||||
};
|
||||
|
||||
let mut mip_size = desc.mip_level_size(mip).unwrap();
|
||||
// copying layers separately
|
||||
if desc.dimension != wgpu::wgt::TextureDimension::D3 {
|
||||
mip_size.depth_or_array_layers = 1;
|
||||
}
|
||||
|
||||
// When uploading mips of compressed textures and the mip is supposed to be
|
||||
// a size that isn't a multiple of the block size, the mip needs to be uploaded
|
||||
// as its "physical size" which is the size rounded up to the nearest block size.
|
||||
let mip_physical = mip_size.physical_size(desc.format);
|
||||
|
||||
// All these calculations are performed on the physical size as that's the
|
||||
// data that exists in the buffer.
|
||||
let width_blocks = mip_physical.width / block_width;
|
||||
let height_blocks = mip_physical.height / block_height;
|
||||
|
||||
let bytes_per_row = width_blocks * block_size;
|
||||
let data_size = bytes_per_row * height_blocks * mip_size.depth_or_array_layers;
|
||||
|
||||
let end_offset = binary_offset + data_size as usize;
|
||||
|
||||
if mip == 0 || !skip_mipmaps {
|
||||
queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &texture,
|
||||
mip_level: mip,
|
||||
origin: wgpu::Origin3d {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: layer,
|
||||
},
|
||||
aspect: wgpu::wgt::TextureAspect::All,
|
||||
},
|
||||
&data[binary_offset..end_offset],
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(bytes_per_row),
|
||||
rows_per_image: Some(height_blocks),
|
||||
},
|
||||
mip_physical,
|
||||
);
|
||||
}
|
||||
|
||||
binary_offset = end_offset;
|
||||
}
|
||||
}
|
||||
|
||||
texture
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
use crate::{color::Srgba, renderer::textures::TextureOptions};
|
||||
use image::{DynamicImage, RgbaImage};
|
||||
use std::{io::Read, num::NonZeroU32, path::Path};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ImageDelta {
|
||||
pub image: ImageData,
|
||||
pub options: TextureOptions,
|
||||
}
|
||||
|
||||
impl ImageDelta {
|
||||
pub fn new<I: Into<ImageData>>(image: I, options: TextureOptions) -> Self {
|
||||
Self {
|
||||
image: image.into(),
|
||||
options,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Order in which data is laid out.
|
||||
/// Doesn't matter for data with a single layer and no mipmaps.
|
||||
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum DataOrder {
|
||||
/// Data is laid out as: `[Layer0Mip0, Layer0Mip1, Layer0Mip2, Layer1Mip0, Layer1Mip1, ...]`
|
||||
/// Used by dds files.
|
||||
#[default]
|
||||
LayerMajor,
|
||||
/// Data is laid out as: `[Layer0Mip0, Layer1Mip0, Layer2Mip0, Layer0Mip1, Layer1Mip1, ...]`
|
||||
/// Used by ktx and ktx2 files.
|
||||
#[allow(dead_code)]
|
||||
MipMajor,
|
||||
}
|
||||
|
||||
impl From<DataOrder> for wgpu::wgt::TextureDataOrder {
|
||||
fn from(value: DataOrder) -> Self {
|
||||
match value {
|
||||
DataOrder::LayerMajor => Self::LayerMajor,
|
||||
DataOrder::MipMajor => Self::MipMajor,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct ImageData {
|
||||
pub format: wgpu::TextureFormat,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub array_layers: u32,
|
||||
pub mipmap_count: NonZeroU32,
|
||||
pub data_order: DataOrder,
|
||||
pub bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
impl ImageData {
|
||||
pub fn from_solid_color(dimensions: [usize; 2], color: Srgba) -> Self {
|
||||
let width = dimensions[0] as u32;
|
||||
let height = dimensions[1] as u32;
|
||||
Self {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
width,
|
||||
height,
|
||||
array_layers: 1,
|
||||
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
|
||||
data_order: Default::default(),
|
||||
bytes: RgbaImage::from_pixel(width, height, color.0.into()).into_raw(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DynamicImage> for ImageData {
|
||||
fn from(image: DynamicImage) -> Self {
|
||||
Self {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
width: image.width(),
|
||||
height: image.height(),
|
||||
array_layers: 1,
|
||||
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
|
||||
data_order: Default::default(),
|
||||
bytes: image.to_rgba8().into_raw(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RgbaImage> for ImageData {
|
||||
fn from(image: RgbaImage) -> Self {
|
||||
Self {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
width: image.width(),
|
||||
height: image.height(),
|
||||
array_layers: 1,
|
||||
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
|
||||
data_order: Default::default(),
|
||||
bytes: image.into_raw(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ImageData {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ImageData")
|
||||
.field("format", &self.format)
|
||||
.field("width", &self.width)
|
||||
.field("height", &self.height)
|
||||
.field("array_layers", &self.array_layers)
|
||||
.field("mipmap_count", &self.mipmap_count)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: clean this up
|
||||
pub fn load_image_file<P: AsRef<Path>>(path: P) -> anyhow::Result<ImageData> {
|
||||
// PoB2 assumes a case insensitive filesystem is used. This can lead to some
|
||||
// files not being found on case sensitive systems.
|
||||
// As a workaround, try using a lower-cased path if the original path doesn't
|
||||
// exist.
|
||||
let path = if path.as_ref().exists() {
|
||||
path.as_ref().to_owned()
|
||||
} else {
|
||||
let mut path = path.as_ref().to_owned();
|
||||
let lowercase_filename = path.file_name().unwrap().to_ascii_lowercase();
|
||||
path.set_file_name(lowercase_filename);
|
||||
path
|
||||
};
|
||||
|
||||
// special handling for compressed dds files
|
||||
if path.extension().and_then(|s| s.to_str()) == Some("zst")
|
||||
&& path
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.map(|s| s.ends_with(".dds"))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
let f = std::fs::File::open(&path)?;
|
||||
let file_len = f.metadata().ok().map(|m| m.len());
|
||||
let mut zstd_decoder = zstd::Decoder::new(f)?;
|
||||
|
||||
let parse_option = dds::header::ParseOptions::new_permissive(file_len);
|
||||
let header = dds::header::Header::read(&mut zstd_decoder, &parse_option)?;
|
||||
let dxgi_format = dds::Format::from_header(&header)?;
|
||||
// zstd_decoder will now be at start of pixel data
|
||||
let non_data_len = dds::header::Header::MAGIC.len() + header.byte_len();
|
||||
let data_len = file_len.and_then(|l| (l as usize).checked_sub(non_data_len));
|
||||
let mut pixel_data = Vec::with_capacity(data_len.unwrap_or(0));
|
||||
zstd_decoder.read_to_end(&mut pixel_data)?;
|
||||
|
||||
let format = match dxgi_format {
|
||||
dds::Format::BC1_UNORM => wgpu::TextureFormat::Bc1RgbaUnorm,
|
||||
dds::Format::BC2_UNORM => wgpu::TextureFormat::Bc2RgbaUnorm,
|
||||
dds::Format::BC3_UNORM => wgpu::TextureFormat::Bc3RgbaUnorm,
|
||||
dds::Format::BC7_UNORM => wgpu::TextureFormat::Bc7RgbaUnorm,
|
||||
dds::Format::R8G8B8A8_UNORM => wgpu::TextureFormat::Rgba8Unorm,
|
||||
_ => anyhow::bail!("Unsupported dxgi format"),
|
||||
};
|
||||
|
||||
let image_data = ImageData {
|
||||
format,
|
||||
width: header.width(),
|
||||
height: header.height(),
|
||||
array_layers: header.array_size(),
|
||||
mipmap_count: header.mipmap_count(),
|
||||
data_order: DataOrder::LayerMajor,
|
||||
bytes: pixel_data,
|
||||
};
|
||||
|
||||
return Ok(image_data);
|
||||
}
|
||||
|
||||
// let image crate deal with other file types
|
||||
let image = image::ImageReader::open(&path)?.decode()?;
|
||||
Ok(image.into())
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
// Vertex shader bindings
|
||||
struct VertexOutput {
|
||||
@location(0) tex_coord: vec2<f32>,
|
||||
@location(1) color: vec4<f32>, // linear
|
||||
@location(2) layer_idx: u32,
|
||||
@builtin(position) position: vec4<f32>,
|
||||
};
|
||||
|
||||
struct Globals {
|
||||
screen_size: vec2<f32>,
|
||||
};
|
||||
|
||||
@group(0) @binding(0) var<uniform> r_globals: Globals;
|
||||
|
||||
// [u8; 4] as u32 -> [f32; 4]
|
||||
fn unpack_color(color: u32) -> vec4<f32> {
|
||||
return vec4<f32>(
|
||||
f32(color & 255u),
|
||||
f32((color >> 8u) & 255u),
|
||||
f32((color >> 16u) & 255u),
|
||||
f32((color >> 24u) & 255u),
|
||||
) / 255.0;
|
||||
}
|
||||
|
||||
fn position_from_screen(screen_pos: vec2<f32>) -> vec4<f32> {
|
||||
return vec4<f32>(
|
||||
2.0 * screen_pos.x / r_globals.screen_size.x - 1.0,
|
||||
1.0 - 2.0 * screen_pos.y / r_globals.screen_size.y,
|
||||
0.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_main(
|
||||
@location(0) a_pos: vec2<f32>,
|
||||
@location(1) a_tex_coord: vec2<f32>,
|
||||
@location(2) a_color: u32, // non-linear
|
||||
@location(3) a_layer_idx: u32,
|
||||
) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
out.tex_coord = a_tex_coord;
|
||||
out.layer_idx = a_layer_idx;
|
||||
out.color = unpack_color(a_color);
|
||||
out.position = position_from_screen(a_pos);
|
||||
return out;
|
||||
}
|
||||
|
||||
@group(1) @binding(0) var r_tex_color: texture_2d_array<f32>;
|
||||
@group(1) @binding(1) var r_tex_sampler: sampler;
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
// NOTE: PoB incorrectly performs mixing and blending in sRGB space.
|
||||
// To get a similar visual result, we need to do the same.
|
||||
// Vertex colors, texture samples, and the output color are all in sRGB.
|
||||
// Texture formats and output surface formats are selected such that no automatic
|
||||
// conversion between linear <-> sRGB is performed.
|
||||
let tex_color = textureSample(r_tex_color, r_tex_sampler, in.tex_coord, in.layer_idx);
|
||||
var out_color = in.color * tex_color;
|
||||
return out_color;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::{
|
||||
LogicalPoint, LogicalQuad, LogicalRect, NormalizedPoint, NormalizedQuad, NormalizedRect,
|
||||
},
|
||||
math::Corners,
|
||||
renderer::textures::TextureId,
|
||||
};
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct Vertex {
|
||||
pub pos: LogicalPoint<f32>,
|
||||
pub uv: NormalizedPoint,
|
||||
pub color: Srgba,
|
||||
// TODO: layer_idx is the same for all vertices. use a uniform buffer
|
||||
// and bind it along with the texture. move into Mesh or make part of
|
||||
// TextureId (change into tuple)
|
||||
pub layer_idx: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Mesh {
|
||||
pub vertices: Vec<Vertex>,
|
||||
pub indices: Vec<u32>,
|
||||
pub texture_id: TextureId,
|
||||
}
|
||||
|
||||
impl Mesh {
|
||||
#[inline]
|
||||
pub fn add_rect(
|
||||
&mut self,
|
||||
rect: LogicalRect<f32>,
|
||||
uv: NormalizedRect,
|
||||
color: Srgba,
|
||||
layer_idx: u32,
|
||||
) {
|
||||
let i = self.vertices.len() as u32;
|
||||
self.indices
|
||||
.extend_from_slice(&[i, i + 1, i + 3, i + 1, i + 2, i + 3]);
|
||||
|
||||
self.vertices.extend_from_slice(&[
|
||||
Vertex {
|
||||
pos: rect.top_left(),
|
||||
uv: uv.top_left(),
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: rect.top_right(),
|
||||
uv: uv.top_right(),
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: rect.bottom_right(),
|
||||
uv: uv.bottom_right(),
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: rect.bottom_left(),
|
||||
uv: uv.bottom_left(),
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn add_quad(
|
||||
&mut self,
|
||||
quad: LogicalQuad<f32>,
|
||||
uv: NormalizedQuad,
|
||||
color: Srgba,
|
||||
layer_idx: u32,
|
||||
) {
|
||||
let i = self.vertices.len() as u32;
|
||||
self.indices
|
||||
.extend_from_slice(&[i, i + 1, i + 3, i + 1, i + 2, i + 3]);
|
||||
|
||||
self.vertices.extend_from_slice(&[
|
||||
Vertex {
|
||||
pos: quad.p0,
|
||||
uv: uv.p0,
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: quad.p1,
|
||||
uv: uv.p1,
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: quad.p2,
|
||||
uv: uv.p2,
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: quad.p3,
|
||||
uv: uv.p3,
|
||||
color,
|
||||
layer_idx,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.vertices.is_empty() && self.indices.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ClippedMesh {
|
||||
// Only parts of the mesh that intersect with this will be rendered
|
||||
pub clip_rect: LogicalRect<f32>,
|
||||
pub mesh: Mesh,
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/// Generate entire mipmap chain for all layers starting from mip level 0 image data.
|
||||
/// Assumes data to contain one mip level 0 image for each layer in RGBA format.
|
||||
pub fn generate_mipmap_chain(queue: &wgpu::Queue, texture: &wgpu::Texture, data: &[u8]) {
|
||||
assert!(!texture.format().is_compressed());
|
||||
assert!(texture.format().components() == 4);
|
||||
|
||||
let size = texture.size();
|
||||
let block_size = texture.format().block_copy_size(None).unwrap_or(4);
|
||||
let data_size = (size.width * size.height * block_size) as usize;
|
||||
|
||||
let srgb_mapper = fast_image_resize::create_srgb_mapper();
|
||||
|
||||
let mut data_offset = 0;
|
||||
for layer in 0..texture.depth_or_array_layers() {
|
||||
let bytes = data[data_offset..data_size].to_owned();
|
||||
let mut src_image = fast_image_resize::images::Image::from_vec_u8(
|
||||
size.width,
|
||||
size.height,
|
||||
bytes,
|
||||
fast_image_resize::PixelType::U8x4,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
for mip in 1..texture.mip_level_count() {
|
||||
let mut target_size = size.mip_level_size(mip, wgpu::TextureDimension::D2);
|
||||
target_size.depth_or_array_layers = 1; // copying layers separately
|
||||
|
||||
// intermediate buffer that stores linear source image data in a higher
|
||||
// bit depth to avoid loss of information
|
||||
let mut linear_src_image = fast_image_resize::images::Image::new(
|
||||
src_image.width(),
|
||||
src_image.height(),
|
||||
fast_image_resize::PixelType::U16x4,
|
||||
);
|
||||
|
||||
// convert from sRGB space into linear space
|
||||
// resizing needs to be performed in linear space to get the correct visual result
|
||||
srgb_mapper
|
||||
.forward_map(&src_image, &mut linear_src_image)
|
||||
.unwrap();
|
||||
|
||||
let mut dst_image = fast_image_resize::images::Image::new(
|
||||
target_size.width,
|
||||
target_size.height,
|
||||
fast_image_resize::PixelType::U8x4,
|
||||
);
|
||||
|
||||
let mut linear_dst_image = fast_image_resize::images::Image::new(
|
||||
dst_image.width(),
|
||||
dst_image.height(),
|
||||
fast_image_resize::PixelType::U16x4,
|
||||
);
|
||||
|
||||
let mut resizer = fast_image_resize::Resizer::new();
|
||||
resizer
|
||||
.resize(
|
||||
&linear_src_image,
|
||||
&mut linear_dst_image,
|
||||
Some(&fast_image_resize::ResizeOptions {
|
||||
algorithm: fast_image_resize::ResizeAlg::Convolution(
|
||||
fast_image_resize::FilterType::Bilinear,
|
||||
),
|
||||
cropping: fast_image_resize::SrcCropping::None,
|
||||
mul_div_alpha: true,
|
||||
}),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// texture needs to be in sRGB, so map back from resized linear image
|
||||
srgb_mapper
|
||||
.backward_map(&linear_dst_image, &mut dst_image)
|
||||
.unwrap();
|
||||
|
||||
queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture,
|
||||
mip_level: mip,
|
||||
origin: wgpu::Origin3d {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: layer,
|
||||
},
|
||||
aspect: wgpu::wgt::TextureAspect::All,
|
||||
},
|
||||
dst_image.buffer(),
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(block_size * target_size.width),
|
||||
rows_per_image: None,
|
||||
},
|
||||
target_size,
|
||||
);
|
||||
|
||||
src_image = dst_image;
|
||||
}
|
||||
|
||||
data_offset += data_size;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::{LogicalPoint, LogicalQuad, LogicalRect, LogicalVector, NormalizedQuad, NormalizedRect},
|
||||
fonts::Layout,
|
||||
math::Point,
|
||||
renderer::textures::TextureId,
|
||||
};
|
||||
use ordered_float::OrderedFloat;
|
||||
use std::{
|
||||
hash::{Hash, Hasher},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ClippedPrimitive {
|
||||
pub clip_rect: LogicalRect<f32>,
|
||||
pub primitive: DrawPrimitive,
|
||||
}
|
||||
|
||||
impl Hash for ClippedPrimitive {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
hash_pos(&self.clip_rect.min, state);
|
||||
hash_pos(&self.clip_rect.max, state);
|
||||
self.primitive.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Hash)]
|
||||
pub enum DrawPrimitive {
|
||||
Rect(RectPrimitive),
|
||||
Quad(QuadPrimitive),
|
||||
Text(TextPrimitive),
|
||||
}
|
||||
|
||||
impl DrawPrimitive {
|
||||
pub fn texture_id(&self) -> TextureId {
|
||||
match self {
|
||||
DrawPrimitive::Rect(rect_primitive) => rect_primitive
|
||||
.texture
|
||||
.map_or_else(TextureId::default, |tex| tex.texture_id),
|
||||
DrawPrimitive::Quad(quad_primitive) => quad_primitive
|
||||
.texture
|
||||
.map_or_else(TextureId::default, |tex| tex.texture_id),
|
||||
_ => TextureId::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RectPrimitive {
|
||||
pub rect: LogicalRect<f32>,
|
||||
pub color: Srgba,
|
||||
pub texture: Option<RectTexture>,
|
||||
}
|
||||
|
||||
impl RectPrimitive {
|
||||
pub fn new(rect: LogicalRect<f32>, color: Srgba, texture: Option<RectTexture>) -> Self {
|
||||
Self {
|
||||
rect,
|
||||
color,
|
||||
texture,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn translate(&mut self, direction: LogicalVector<f32>) {
|
||||
self.rect = self.rect.translate(direction);
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for RectPrimitive {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
hash_pos(&self.rect.min, state);
|
||||
hash_pos(&self.rect.max, state);
|
||||
self.color.hash(state);
|
||||
self.texture.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RectTexture {
|
||||
pub texture_id: TextureId,
|
||||
pub uv: NormalizedRect,
|
||||
pub layer_idx: u32,
|
||||
}
|
||||
|
||||
impl RectTexture {
|
||||
pub fn new(texture_id: TextureId, uv: NormalizedRect, layer_idx: u32) -> Self {
|
||||
Self {
|
||||
texture_id,
|
||||
uv,
|
||||
layer_idx,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for RectTexture {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.texture_id.hash(state);
|
||||
hash_pos(&self.uv.min, state);
|
||||
hash_pos(&self.uv.max, state);
|
||||
self.layer_idx.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct QuadPrimitive {
|
||||
pub quad: LogicalQuad<f32>,
|
||||
pub color: Srgba,
|
||||
pub texture: Option<QuadTexture>,
|
||||
}
|
||||
|
||||
impl QuadPrimitive {
|
||||
pub fn new(quad: LogicalQuad<f32>, color: Srgba, texture: Option<QuadTexture>) -> Self {
|
||||
Self {
|
||||
quad,
|
||||
color,
|
||||
texture,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn translate(&mut self, direction: LogicalVector<f32>) {
|
||||
self.quad = self.quad.translate(direction);
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for QuadPrimitive {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
hash_pos(&self.quad.p0, state);
|
||||
hash_pos(&self.quad.p1, state);
|
||||
hash_pos(&self.quad.p2, state);
|
||||
hash_pos(&self.quad.p3, state);
|
||||
self.color.hash(state);
|
||||
self.texture.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct QuadTexture {
|
||||
pub texture_id: TextureId,
|
||||
pub uv: NormalizedQuad,
|
||||
pub layer_idx: u32,
|
||||
}
|
||||
|
||||
impl QuadTexture {
|
||||
pub fn new(texture_id: TextureId, uv: NormalizedQuad, layer_idx: u32) -> Self {
|
||||
Self {
|
||||
texture_id,
|
||||
uv,
|
||||
layer_idx,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for QuadTexture {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.texture_id.hash(state);
|
||||
hash_pos(&self.uv.p0, state);
|
||||
hash_pos(&self.uv.p1, state);
|
||||
hash_pos(&self.uv.p2, state);
|
||||
hash_pos(&self.uv.p3, state);
|
||||
self.layer_idx.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TextPrimitive {
|
||||
pub pos: LogicalPoint<f32>,
|
||||
pub layout: Arc<Layout>,
|
||||
}
|
||||
|
||||
impl TextPrimitive {
|
||||
pub fn new(pos: LogicalPoint<f32>, layout: Arc<Layout>) -> Self {
|
||||
Self { pos, layout }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn translate(&mut self, direction: LogicalVector<f32>) {
|
||||
self.pos += direction;
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for TextPrimitive {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
hash_pos(&self.pos, state);
|
||||
self.layout.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_pos<H: Hasher, U>(pos: &Point<f32, U>, state: &mut H) {
|
||||
OrderedFloat(pos.x).hash(state);
|
||||
OrderedFloat(pos.x).hash(state);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
use crate::{
|
||||
dpi::{Normalize, NormalizedQuad, NormalizedRect, Uv},
|
||||
fonts::FontAtlasSize,
|
||||
renderer::{
|
||||
mesh::{ClippedMesh, Mesh},
|
||||
primitives::{
|
||||
ClippedPrimitive, DrawPrimitive, QuadPrimitive, QuadTexture, RectPrimitive,
|
||||
RectTexture, TextPrimitive,
|
||||
},
|
||||
textures::TextureId,
|
||||
},
|
||||
};
|
||||
|
||||
/// Converts [`DrawPrimitive`]s into [`Mesh`]es.
|
||||
#[derive(Default)]
|
||||
pub struct Tessellator {
|
||||
last_clipped_meshes_size: usize,
|
||||
}
|
||||
|
||||
impl Tessellator {
|
||||
pub fn convert_clipped_primitives(
|
||||
&mut self,
|
||||
clipped_primitives: impl Iterator<Item = ClippedPrimitive>,
|
||||
font_atlas_size: FontAtlasSize,
|
||||
) -> Vec<ClippedMesh> {
|
||||
profiling::scope!("convert_primitives");
|
||||
|
||||
let mut clipped_meshes = Vec::with_capacity(self.last_clipped_meshes_size);
|
||||
|
||||
for clipped_primitive in clipped_primitives {
|
||||
self.convert_clipped_primitive(clipped_primitive, font_atlas_size, &mut clipped_meshes);
|
||||
}
|
||||
|
||||
self.last_clipped_meshes_size = clipped_meshes.len();
|
||||
clipped_meshes
|
||||
}
|
||||
|
||||
pub fn convert_clipped_primitive(
|
||||
&mut self,
|
||||
clipped_primitive: ClippedPrimitive,
|
||||
font_atlas_size: FontAtlasSize,
|
||||
out_clipped_meshes: &mut Vec<ClippedMesh>,
|
||||
) {
|
||||
let ClippedPrimitive {
|
||||
clip_rect,
|
||||
primitive,
|
||||
} = clipped_primitive;
|
||||
|
||||
if clip_rect.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let start_new_mesh = match out_clipped_meshes.last() {
|
||||
None => true,
|
||||
Some(last_clipped_mesh) => {
|
||||
// append to previous mesh if clip_rect and texture_id match.
|
||||
// otherwise, start a new mesh.
|
||||
!(last_clipped_mesh.clip_rect == clip_rect
|
||||
&& last_clipped_mesh.mesh.texture_id == primitive.texture_id())
|
||||
}
|
||||
};
|
||||
|
||||
if start_new_mesh {
|
||||
out_clipped_meshes.push(ClippedMesh {
|
||||
clip_rect,
|
||||
mesh: Mesh::default(),
|
||||
});
|
||||
}
|
||||
|
||||
let last_clipped_mesh = out_clipped_meshes.last_mut().unwrap();
|
||||
|
||||
match primitive {
|
||||
DrawPrimitive::Rect(rect_primitive) => {
|
||||
self.convert_rect_primitive(rect_primitive, &mut last_clipped_mesh.mesh)
|
||||
}
|
||||
DrawPrimitive::Quad(quad_primitive) => {
|
||||
self.convert_quad_primitive(quad_primitive, &mut last_clipped_mesh.mesh)
|
||||
}
|
||||
DrawPrimitive::Text(text_primitive) => self.convert_text_primitive(
|
||||
text_primitive,
|
||||
font_atlas_size,
|
||||
&mut last_clipped_mesh.mesh,
|
||||
),
|
||||
}
|
||||
|
||||
// This can be empty if a new mesh was started but the conversion from a text primitive
|
||||
// didn't add any vertices. Our renderer doesn't support empty meshes so remove it
|
||||
if last_clipped_mesh.mesh.is_empty() {
|
||||
out_clipped_meshes.pop();
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_rect_primitive(&self, rect_primitive: RectPrimitive, out: &mut Mesh) {
|
||||
let RectPrimitive {
|
||||
rect,
|
||||
color,
|
||||
texture,
|
||||
} = rect_primitive;
|
||||
|
||||
let (texture_id, uv, layer_idx) = match texture {
|
||||
Some(RectTexture {
|
||||
texture_id,
|
||||
uv,
|
||||
layer_idx,
|
||||
}) => (texture_id, uv, layer_idx),
|
||||
None => (TextureId::default(), NormalizedRect::white_uv(), 0),
|
||||
};
|
||||
|
||||
out.add_rect(rect, uv, color, layer_idx);
|
||||
out.texture_id = texture_id;
|
||||
}
|
||||
|
||||
fn convert_quad_primitive(&self, quad_primitive: QuadPrimitive, out: &mut Mesh) {
|
||||
let QuadPrimitive {
|
||||
quad,
|
||||
color,
|
||||
texture,
|
||||
} = quad_primitive;
|
||||
|
||||
let (texture_id, uv, layer_idx) = match texture {
|
||||
Some(QuadTexture {
|
||||
texture_id,
|
||||
uv,
|
||||
layer_idx,
|
||||
}) => (texture_id, uv, layer_idx),
|
||||
None => (TextureId::default(), NormalizedQuad::white_uv(), 0),
|
||||
};
|
||||
|
||||
out.add_quad(quad, uv, color, layer_idx);
|
||||
out.texture_id = texture_id;
|
||||
}
|
||||
|
||||
fn convert_text_primitive(
|
||||
&self,
|
||||
text_primitive: TextPrimitive,
|
||||
font_atlas_size: FontAtlasSize,
|
||||
out: &mut Mesh,
|
||||
) {
|
||||
let TextPrimitive {
|
||||
pos: layout_pos,
|
||||
layout,
|
||||
} = text_primitive;
|
||||
|
||||
if layout.rows.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
out.vertices.reserve(layout.num_of_vertices);
|
||||
out.indices.reserve(layout.num_of_indices);
|
||||
|
||||
// TODO: align to pixel grid?
|
||||
|
||||
for row in &layout.rows {
|
||||
for glyph in &row.glyphs {
|
||||
let rect = glyph.rect.translate(layout_pos.to_vector());
|
||||
let normalized_uv = glyph.uv.normalize(font_atlas_size);
|
||||
out.add_rect(rect, normalized_uv, glyph.color, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
use std::{
|
||||
collections::hash_map::Entry,
|
||||
path::Path,
|
||||
sync::{Arc, RwLock},
|
||||
};
|
||||
|
||||
use ahash::HashMap;
|
||||
use anyhow::bail;
|
||||
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
renderer::image::{ImageData, ImageDelta, load_image_file},
|
||||
worker_pool::WorkerPool,
|
||||
};
|
||||
|
||||
pub type TextureId = u64;
|
||||
|
||||
pub struct TextureHandle {
|
||||
tex_mngr: Arc<RwLock<TextureManager>>,
|
||||
id: TextureId,
|
||||
}
|
||||
|
||||
impl TextureHandle {
|
||||
pub fn new(tex_mngr: Arc<RwLock<TextureManager>>, id: TextureId) -> Self {
|
||||
Self { tex_mngr, id }
|
||||
}
|
||||
|
||||
pub fn id(&self) -> TextureId {
|
||||
self.id
|
||||
}
|
||||
|
||||
pub fn size(&self) -> [usize; 2] {
|
||||
self.tex_mngr
|
||||
.read()
|
||||
.unwrap()
|
||||
.get_meta_data(self.id)
|
||||
.map_or([0, 0], |tex| tex.size)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TextureHandle {
|
||||
fn drop(&mut self) {
|
||||
self.tex_mngr.write().unwrap().free(self.id);
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for TextureHandle {
|
||||
fn clone(&self) -> Self {
|
||||
self.tex_mngr.write().unwrap().retain(self.id);
|
||||
Self {
|
||||
tex_mngr: Arc::clone(&self.tex_mngr),
|
||||
id: self.id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct TexturesDelta {
|
||||
pub update: Vec<(TextureId, ImageDelta)>,
|
||||
pub free: Vec<TextureId>,
|
||||
}
|
||||
|
||||
impl TexturesDelta {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.update.is_empty() && self.free.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata about an allocated texture.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TextureMetaData {
|
||||
pub name: String,
|
||||
pub size: [usize; 2],
|
||||
/// Texture is freed when this reaches zero
|
||||
retain_count: usize,
|
||||
pub options: TextureOptions,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct TextureManager {
|
||||
next_id: u64,
|
||||
meta_data: HashMap<TextureId, TextureMetaData>,
|
||||
delta: TexturesDelta,
|
||||
}
|
||||
|
||||
impl TextureManager {
|
||||
/// Allocates a new Texture.
|
||||
pub fn alloc(&mut self, name: String, image: ImageData, options: TextureOptions) -> TextureId {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
|
||||
self.meta_data.entry(id).or_insert_with(|| TextureMetaData {
|
||||
name,
|
||||
size: [image.width as usize, image.height as usize],
|
||||
retain_count: 1,
|
||||
options,
|
||||
});
|
||||
|
||||
self.delta
|
||||
.update
|
||||
.push((id, ImageDelta::new(image, options)));
|
||||
|
||||
id
|
||||
}
|
||||
|
||||
/// Reserves a new TextureId for later assignment.
|
||||
pub fn reserve(&mut self, name: String, options: TextureOptions) -> TextureId {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
|
||||
self.meta_data.entry(id).or_insert_with(|| TextureMetaData {
|
||||
name,
|
||||
size: [0, 0],
|
||||
retain_count: 1,
|
||||
options,
|
||||
});
|
||||
|
||||
id
|
||||
}
|
||||
|
||||
/// Assigns a new image to an existing texture.
|
||||
pub fn set(&mut self, id: TextureId, delta: ImageDelta) {
|
||||
if let Some(meta_data) = self.meta_data.get_mut(&id) {
|
||||
meta_data.size = [delta.image.width as usize, delta.image.height as usize];
|
||||
// discard all old enqueued deltas
|
||||
self.delta.update.retain(|(x, _)| x != &id);
|
||||
self.delta.update.push((id, delta));
|
||||
} else {
|
||||
debug_assert!(false, "Tried setting texture {id:?} which is not allocated");
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees an existing texture.
|
||||
pub fn free(&mut self, id: TextureId) {
|
||||
if let Entry::Occupied(mut entry) = self.meta_data.entry(id) {
|
||||
let meta = entry.get_mut();
|
||||
meta.retain_count -= 1;
|
||||
if meta.retain_count == 0 {
|
||||
entry.remove();
|
||||
self.delta.free.push(id);
|
||||
}
|
||||
} else {
|
||||
debug_assert!(false, "Tried freeing texture {id:?} which is not allocated");
|
||||
}
|
||||
}
|
||||
|
||||
/// Increase the retain-count of the given texture.
|
||||
///
|
||||
/// [`Self::free`] must be called an additional time for each time [`Self::retain`] is called,
|
||||
pub fn retain(&mut self, id: TextureId) {
|
||||
if let Some(meta) = self.meta_data.get_mut(&id) {
|
||||
meta.retain_count += 1;
|
||||
} else {
|
||||
debug_assert!(
|
||||
false,
|
||||
"Tried retaining texture {id:?} which is not allocated",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get metadata about a specific texture.
|
||||
pub fn get_meta_data(&self, id: TextureId) -> Option<&TextureMetaData> {
|
||||
self.meta_data.get(&id)
|
||||
}
|
||||
|
||||
/// Take and reset changes since last frame.
|
||||
pub fn take_delta(&mut self) -> TexturesDelta {
|
||||
std::mem::take(&mut self.delta)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WrappedTextureManager {
|
||||
manager: Arc<RwLock<TextureManager>>,
|
||||
worker_pool: WorkerPool,
|
||||
}
|
||||
|
||||
impl WrappedTextureManager {
|
||||
pub fn new() -> Self {
|
||||
let manager = Arc::new(RwLock::new(TextureManager::default()));
|
||||
|
||||
// allocate default texture (id: 0) for font atlas
|
||||
manager.write().unwrap().alloc(
|
||||
"font_atlas_texture".into(),
|
||||
ImageData::from_solid_color([0, 0], Srgba::TRANSPARENT),
|
||||
TextureOptions::default(),
|
||||
);
|
||||
|
||||
Self {
|
||||
manager,
|
||||
worker_pool: WorkerPool::new(4),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn update_font_texture(&self, delta: ImageDelta) {
|
||||
self.manager
|
||||
.write()
|
||||
.unwrap()
|
||||
.set(TextureId::default(), delta);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn take_delta(&self) -> TexturesDelta {
|
||||
self.manager.write().unwrap().take_delta()
|
||||
}
|
||||
|
||||
pub fn load_texture(
|
||||
&self,
|
||||
image_path: String,
|
||||
options: TextureOptions,
|
||||
is_async: bool,
|
||||
) -> anyhow::Result<TextureHandle> {
|
||||
let manager = Arc::clone(&self.manager);
|
||||
|
||||
let handle = if is_async {
|
||||
let id = manager
|
||||
.write()
|
||||
.unwrap()
|
||||
.reserve(image_path.clone(), options);
|
||||
|
||||
// load image in background worker
|
||||
let mngr_clone = Arc::clone(&manager);
|
||||
self.worker_pool
|
||||
.execute(move || match load_image_file(Path::new(&image_path)) {
|
||||
Ok(image) => {
|
||||
mngr_clone
|
||||
.write()
|
||||
.unwrap()
|
||||
.set(id, ImageDelta::new(image, options));
|
||||
}
|
||||
Err(e) => log::warn!("Unable to load image fron {}: {}", &image_path, e),
|
||||
});
|
||||
|
||||
TextureHandle::new(manager, id)
|
||||
} else {
|
||||
match load_image_file(Path::new(&image_path)) {
|
||||
Ok(image) => {
|
||||
let id = manager.write().unwrap().alloc(image_path, image, options);
|
||||
TextureHandle::new(manager, id)
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("Unable to load image fron {}: {}", &image_path, e);
|
||||
bail!(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
pub fn update_texture(
|
||||
&self,
|
||||
texture_id: TextureId,
|
||||
image_path: String,
|
||||
options: TextureOptions,
|
||||
is_async: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
if is_async {
|
||||
let mngr_clone = Arc::clone(&self.manager);
|
||||
self.worker_pool
|
||||
.execute(move || match load_image_file(Path::new(&image_path)) {
|
||||
Ok(image) => {
|
||||
mngr_clone
|
||||
.write()
|
||||
.unwrap()
|
||||
.set(texture_id, ImageDelta::new(image, options));
|
||||
}
|
||||
Err(e) => log::warn!("Unable to load image fron {}: {}", &image_path, e),
|
||||
});
|
||||
} else {
|
||||
match load_image_file(Path::new(&image_path)) {
|
||||
Ok(image) => {
|
||||
self.manager
|
||||
.write()
|
||||
.unwrap()
|
||||
.set(texture_id, ImageDelta::new(image, options));
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("Unable to load image fron {}: {}", &image_path, e);
|
||||
bail!(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TextureOptions {
|
||||
pub magnification: wgpu::FilterMode,
|
||||
pub minification: wgpu::FilterMode,
|
||||
pub wrap_mode: wgpu::AddressMode,
|
||||
pub mipmap_mode: wgpu::FilterMode,
|
||||
pub generate_mipmaps: bool,
|
||||
}
|
||||
|
||||
impl TextureOptions {
|
||||
pub const LINEAR_REPEAT: Self = Self {
|
||||
magnification: wgpu::FilterMode::Linear,
|
||||
minification: wgpu::FilterMode::Linear,
|
||||
wrap_mode: wgpu::AddressMode::Repeat,
|
||||
mipmap_mode: wgpu::FilterMode::Linear,
|
||||
generate_mipmaps: false,
|
||||
};
|
||||
|
||||
pub const LINEAR: Self = Self {
|
||||
magnification: wgpu::FilterMode::Linear,
|
||||
minification: wgpu::FilterMode::Linear,
|
||||
wrap_mode: wgpu::AddressMode::ClampToEdge,
|
||||
mipmap_mode: wgpu::FilterMode::Linear,
|
||||
generate_mipmaps: false,
|
||||
};
|
||||
}
|
||||
|
||||
impl Default for TextureOptions {
|
||||
fn default() -> Self {
|
||||
Self::LINEAR
|
||||
}
|
||||
}
|
||||
|
||||
impl std::hash::Hash for TextureOptions {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.magnification.hash(state);
|
||||
self.minification.hash(state);
|
||||
self.wrap_mode.hash(state);
|
||||
self.mipmap_mode.hash(state);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::mpsc::{Receiver, Sender, TryRecvError};
|
||||
use std::{collections::VecDeque, sync::mpsc::channel, thread::JoinHandle};
|
||||
|
||||
use anyhow::{Result, anyhow};
|
||||
use mlua::{Function, IntoLuaMulti, Lua, Value};
|
||||
use mlua::{Integer, MultiValue, Number, Result as LuaResult};
|
||||
|
||||
use crate::api::get_callback;
|
||||
use crate::lua::LuaInstance;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SubscriptResult {
|
||||
SubscriptFinished {
|
||||
id: u64,
|
||||
return_values: NativeMultiValue,
|
||||
},
|
||||
SubscriptError {
|
||||
id: u64,
|
||||
error: String,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct SubscriptManager {
|
||||
current_id: u64,
|
||||
scripts: Vec<Subscript>,
|
||||
}
|
||||
|
||||
impl SubscriptManager {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
current_id: 0,
|
||||
scripts: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push(
|
||||
&mut self,
|
||||
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,
|
||||
);
|
||||
self.scripts.push(subscript);
|
||||
id
|
||||
}
|
||||
|
||||
pub fn process(&mut self, lua: &LuaInstance) -> Vec<SubscriptResult> {
|
||||
let mut results = vec![];
|
||||
|
||||
self.scripts.retain_mut(|subscript| {
|
||||
subscript.handle_calls(lua);
|
||||
|
||||
if let Some(event) = subscript.try_join() {
|
||||
results.push(event);
|
||||
// subscript has finished or errored, remove it
|
||||
false
|
||||
} else {
|
||||
// subscript has not finished yet, keep it
|
||||
true
|
||||
}
|
||||
});
|
||||
|
||||
results
|
||||
}
|
||||
}
|
||||
|
||||
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 main thread sends the return values of the function back to the subscript which is waiting on them.
|
||||
// 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,
|
||||
) -> 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
|
||||
LuaInstance::register_package_paths(&lua)?;
|
||||
|
||||
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()
|
||||
.map(|h| h.is_finished())
|
||||
.unwrap_or(false)
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register_subscript_globals(
|
||||
lua: &Lua,
|
||||
subscripts: &Rc<RefCell<SubscriptManager>>,
|
||||
) -> LuaResult<()> {
|
||||
let globals = lua.globals();
|
||||
|
||||
// ssID = LaunchSubScript("<scriptText>", "<funcList>", "<subList>"[, ...])
|
||||
let subscripts_clone = Rc::clone(subscripts);
|
||||
let launch_sub_script = move |_: &Lua,
|
||||
(script_text, func_list, sub_list, args): (
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
MultiValue,
|
||||
)| {
|
||||
let blocking_calls = func_list
|
||||
.split(',')
|
||||
.map(|s| s.trim())
|
||||
.filter(|&s| !s.is_empty())
|
||||
.map(String::from)
|
||||
.collect();
|
||||
|
||||
let nonblocking_calls = sub_list
|
||||
.split(',')
|
||||
.map(|s| s.trim())
|
||||
.filter(|&s| !s.is_empty())
|
||||
.map(String::from)
|
||||
.collect();
|
||||
|
||||
let arguments = args.try_into()?;
|
||||
let subscript_id = subscripts_clone.borrow_mut().push(
|
||||
script_text,
|
||||
blocking_calls,
|
||||
nonblocking_calls,
|
||||
arguments,
|
||||
);
|
||||
Ok(subscript_id)
|
||||
};
|
||||
|
||||
let subscripts_clone = Rc::clone(subscripts);
|
||||
let is_subscript_running = move |_: &Lua, subscript_id: u64| {
|
||||
Ok(subscripts_clone
|
||||
.borrow()
|
||||
.scripts
|
||||
.iter()
|
||||
.any(|ss| ss.id == subscript_id))
|
||||
};
|
||||
|
||||
let abort_subscript = |_: &Lua, _subscript_id: u64| -> LuaResult<()> { unimplemented!() };
|
||||
|
||||
globals.set(
|
||||
"LaunchSubScript",
|
||||
lua.create_function_mut(launch_sub_script)?,
|
||||
)?;
|
||||
globals.set(
|
||||
"IsSubScriptRunning",
|
||||
lua.create_function(is_subscript_running)?,
|
||||
)?;
|
||||
globals.set("IsSubScriptRunning", lua.create_function(abort_subscript)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 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(NativeMultiValue(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))
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
use std::{
|
||||
env,
|
||||
hash::{Hash, Hasher},
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use ahash::AHasher;
|
||||
|
||||
pub fn get_executable_dir() -> anyhow::Result<PathBuf> {
|
||||
let exe_path = env::current_exe()?;
|
||||
let exe_parent_dir = exe_path.parent().unwrap().canonicalize()?;
|
||||
Ok(exe_parent_dir)
|
||||
}
|
||||
|
||||
pub fn change_working_directory<P: AsRef<Path>>(path: P) -> anyhow::Result<()> {
|
||||
env::set_current_dir(path.as_ref()).map_err(|e| {
|
||||
anyhow::anyhow!(
|
||||
"Failed to change working directory {:?}: {}",
|
||||
path.as_ref(),
|
||||
e
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn calculate_hash<T: Hash>(t: &T) -> u64 {
|
||||
let mut state = AHasher::default();
|
||||
t.hash(&mut state);
|
||||
state.finish()
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
use std::{
|
||||
sync::{Arc, Mutex, mpsc},
|
||||
thread,
|
||||
};
|
||||
|
||||
type Job = Box<dyn FnOnce() + Send + 'static>;
|
||||
|
||||
pub struct WorkerPool {
|
||||
workers: Vec<Worker>,
|
||||
sender: Option<mpsc::Sender<Job>>,
|
||||
}
|
||||
|
||||
impl WorkerPool {
|
||||
pub fn new(size: usize) -> Self {
|
||||
assert!(size > 0);
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let rx = Arc::new(Mutex::new(rx));
|
||||
|
||||
let mut workers = Vec::with_capacity(size);
|
||||
|
||||
for id in 0..size {
|
||||
workers.push(Worker::new(id, rx.clone()));
|
||||
}
|
||||
|
||||
Self {
|
||||
workers,
|
||||
sender: Some(tx),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn execute<F>(&self, f: F)
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
let job = Box::new(f);
|
||||
self.sender.as_ref().unwrap().send(job).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WorkerPool {
|
||||
fn drop(&mut self) {
|
||||
drop(self.sender.take());
|
||||
|
||||
for worker in &mut self.workers {
|
||||
if let Some(thread) = worker.thread.take() {
|
||||
thread.join().unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Worker {
|
||||
_id: usize,
|
||||
thread: Option<thread::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Worker {
|
||||
fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>) -> Self {
|
||||
let thread = thread::spawn(move || {
|
||||
loop {
|
||||
let message = receiver.lock().unwrap().recv();
|
||||
|
||||
match message {
|
||||
Ok(job) => job(),
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
_id: id,
|
||||
thread: Some(thread),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user