Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5465544eb2 | ||
|
|
75c88af778 | ||
|
|
4db36c1382 | ||
|
|
9b925feb90 | ||
|
|
17bb3c6b39 | ||
|
|
ce62fe64e1 | ||
|
|
4b997447b5 | ||
|
|
a1e92fa94e | ||
|
|
a24beac554 | ||
|
|
4affef3e62 | ||
|
|
e6ba149516 | ||
|
|
c2222c641b | ||
|
|
6427263f2d | ||
|
|
f47a2657f6 | ||
|
|
6cca05f2f5 | ||
|
|
f8a821d310 | ||
|
|
50e0af6cad | ||
|
|
0886ad693a | ||
|
|
a4f7353ce6 | ||
|
|
f3c065debd | ||
|
|
9b98c65060 | ||
|
|
b70d612a1d | ||
|
|
36d2697754 | ||
|
|
8ddcbf89f7 | ||
|
|
c6d5241b98 | ||
|
|
ae9c59d132 | ||
|
|
41d9c9dbd7 | ||
|
|
e72a271006 | ||
|
|
d886f585f8 | ||
|
|
bc2d245368 | ||
|
|
51476da1d9 | ||
|
|
30bc02252b | ||
|
|
d5f9801d49 | ||
|
|
0b608602d1 | ||
|
|
ef32139e14 | ||
|
|
20a1db073d | ||
|
|
aa1bfb768e | ||
|
|
29e2958dd3 | ||
|
|
5cbabed095 | ||
|
|
5ba4100589 | ||
|
|
fc4d913930 | ||
|
|
dc9300bca2 | ||
|
|
e90396ff28 | ||
|
|
e3288b96ac | ||
|
|
749dd69589 | ||
|
|
1a6631c4ad | ||
|
|
078269653e | ||
|
|
fe96786aca | ||
|
|
4b344d15ae | ||
|
|
c297eeaca6 | ||
|
|
77e1d615e0 | ||
|
|
6f0d678790 | ||
|
|
38f81cab3e | ||
|
|
a6c158424f | ||
|
|
8556ebf772 | ||
|
|
09f1a16071 | ||
|
|
6f0eef7cf8 | ||
|
|
8cfc82d668 | ||
|
|
9d45b78d64 | ||
|
|
692e530867 | ||
|
|
4e67aa72c0 | ||
|
|
ac8cf3946e | ||
|
|
49fab3c787 | ||
|
|
93ce072d40 | ||
|
|
1f5e30ae5a | ||
|
|
d217af94c3 | ||
|
|
fe9434e4f0 | ||
|
|
f0be43cbdd | ||
|
|
a678c8148d | ||
|
|
963a9ba1d1 | ||
|
|
e6c5ec3d42 | ||
|
|
8f98a9c8f1 | ||
|
|
a50ea4cdaf | ||
|
|
7b925876a5 | ||
|
|
8d17f8e64f | ||
|
|
8ba72fd7df | ||
|
|
2bbfd14c1b | ||
|
|
99dd50de62 | ||
|
|
6224a1b0a4 | ||
|
|
8cf5110eb2 | ||
|
|
493a2ba9cf | ||
|
|
cc6de120f2 | ||
|
|
337e876571 | ||
|
|
d4ca16f07e | ||
|
|
6fe15c63fe | ||
|
|
1cd62c2b1c | ||
|
|
d43a1cf392 | ||
|
|
e5bd0157d3 | ||
|
|
43ef18c2e3 | ||
|
|
4d6c258932 | ||
|
|
3fc87339ca | ||
|
|
a6d18a320c | ||
|
|
e20a28fef7 | ||
|
|
b48edb72e1 | ||
|
|
e43da1b9e8 | ||
|
|
99fc9f608e | ||
|
|
c1d91768bb | ||
|
|
4c581f92a8 | ||
|
|
a2afd2de54 | ||
|
|
a1cea10218 | ||
|
|
cee6f848ea | ||
|
|
5c44328e16 | ||
|
|
6b6098d331 | ||
|
|
69d70e4712 | ||
|
|
32fd954952 | ||
|
|
40ea4445cd | ||
|
|
3ca5f984de | ||
|
|
6dbf6c0e3c | ||
|
|
6a05d86801 | ||
|
|
068dfce7ca | ||
|
|
28a9089443 | ||
|
|
e42776a2c8 | ||
|
|
c8bda4b76f | ||
|
|
fe10962c4b | ||
|
|
4dc8db6921 |
No files matched your search
@@ -1,11 +1,64 @@
|
||||
# Contributing to Rusty Path Of Building
|
||||
|
||||
## Reporting bugs
|
||||
|
||||
- Ensure the bug was not already reported by searching through existing [issues](https://github.com/meehl/rusty-path-of-building/issues).
|
||||
- If the bug can also be reproduced with the official runtime (e.g. by running through wine), please open an issue in the [PoB1](https://github.com/PathOfBuildingCommunity/PathOfBuilding) or [PoB2](https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2) repo instead. If you're unsure, feel free to just open it here.
|
||||
- If possible, use the bug report template to create the issue and provide as much information as possible.
|
||||
|
||||
## Contributing code
|
||||
|
||||
- Get familiar with the code base before you start. I'll try to add more documentation providing a high-level overview of the architecture in the future. Until then, feel free to reach out through [Discussions](https://github.com/meehl/rusty-path-of-building/discussions) if you have any questions.
|
||||
- If you intend to work on the API functions, also check out the [SimpleGraphic](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) code base. A great place to ask questions about it is the PoB dev discord server. [Here](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) is more info on how to join.
|
||||
- Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.
|
||||
|
||||
## macOS Development Setup
|
||||
|
||||
### 1. Install Lua runtime dependencies
|
||||
|
||||
The application requires several Lua C libraries at runtime. Install them using LuaRocks with the LuaJIT backend:
|
||||
|
||||
```bash
|
||||
brew install luajit luarocks
|
||||
|
||||
luarocks --lua-version 5.1 install luasocket
|
||||
luarocks --lua-version 5.1 install luautf8
|
||||
luarocks --lua-version 5.1 install lua-curl
|
||||
```
|
||||
|
||||
Build and install `lzip` from the bundled source (requires zlib, which is pre-installed on macOS):
|
||||
|
||||
```bash
|
||||
cd lua/libs/lzip && make LUA_IMPL=luajit install
|
||||
```
|
||||
|
||||
### 2. Configure LUA_CPATH
|
||||
|
||||
Add the following to your shell profile (`~/.zshrc` or `~/.bash_profile`) so the runtime can locate the installed libraries:
|
||||
|
||||
```bash
|
||||
eval $(luarocks --lua-version 5.1 path)
|
||||
```
|
||||
|
||||
Then reload your shell or run `source ~/.bash_profile`.
|
||||
|
||||
### 3. Startup
|
||||
|
||||
```bash
|
||||
cargo run <poe1|poe2>
|
||||
```
|
||||
|
||||
Path of Building files are automatically downloaded to the following directories on first startup:
|
||||
|
||||
- poe1: `~/Library/Application Support/RustyPathOfBuilding1`
|
||||
- poe2: `~/Library/Application Support/RustyPathOfBuilding2`
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
**Build fails with `library 'luajit-5.1' not found`**
|
||||
|
||||
This usually means the build cache points to an old LuaJIT version after a Homebrew upgrade. Run:
|
||||
|
||||
```bash
|
||||
cargo clean && cargo run <poe1|poe2>
|
||||
```
|
||||
@@ -0,0 +1,31 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install system dependencies
|
||||
run: sudo apt-get update && sudo apt-get install -y luajit libluajit-5.1-dev
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: rustfmt, clippy
|
||||
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
|
||||
- name: Format
|
||||
run: cargo fmt --check
|
||||
|
||||
- name: Clippy
|
||||
run: cargo clippy --all-targets -- -D warnings
|
||||
|
||||
- name: Test
|
||||
run: cargo test
|
||||
@@ -1 +1,3 @@
|
||||
/target/
|
||||
*.so
|
||||
*.so.dSYM
|
||||
+71
-1
@@ -2,6 +2,70 @@
|
||||
|
||||
## [Unreleased] - ReleaseDate
|
||||
|
||||
## [0.3.2] - 2026-10-22
|
||||
|
||||
### Changed
|
||||
|
||||
- Refactor surface format selection
|
||||
|
||||
### Fixed
|
||||
|
||||
- Render tab characters as 4 spaces to match SimpleGraphic (#53)
|
||||
|
||||
## [0.3.1] - 2026-10-21
|
||||
|
||||
### Fixed
|
||||
|
||||
- Strip `#@` script headers before loading Lua files to fix syntax error with recent LuaJIT versions
|
||||
|
||||
## [0.3.0] - 2026-10-21
|
||||
|
||||
### Added
|
||||
|
||||
- Add `bundled-lua-modules` feature (enabled by default) for registering Rust implementations of required C libaries. Enabling this features removes the runtime dependencies on `Lua-cURLv3`, `luautf8`, `luasocket`, and `lzip`. Disable it use the original C libraries like before.
|
||||
- Add `vendored-lua` feature for building LuaJIT from source
|
||||
- Add support for gzip compression to `inflate`/`deflate` API functions
|
||||
|
||||
### Changed
|
||||
|
||||
- Rework renderer for significantly improved render performance
|
||||
- Rework context handling
|
||||
- Improve performance of image handle access in draw API
|
||||
- Remove blend mode and mask index from draw API
|
||||
- Bump dependencies
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix color escape regex
|
||||
- Fix Windows canonical path handling
|
||||
|
||||
## [0.2.18] - 2026-05-29
|
||||
|
||||
### Changed
|
||||
|
||||
- Raise `max_texture_array_layers` GPU requirement to support new gem tooltips
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix doubleclick handling
|
||||
|
||||
## [0.2.17] - 2026-05-24
|
||||
|
||||
### Changed
|
||||
|
||||
- Improve macOS compatibility
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix broken selection and display of colored text
|
||||
- Fix black screen during installation on nixOS
|
||||
|
||||
## [0.2.16] - 2026-03-23
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix bug that causes tarball extraction to fail
|
||||
|
||||
## [0.2.15] - 2026-03-22
|
||||
|
||||
### Changed
|
||||
@@ -182,8 +246,14 @@
|
||||
- First release
|
||||
|
||||
<!-- next-url -->
|
||||
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.15...HEAD
|
||||
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.2...HEAD
|
||||
|
||||
[0.3.2]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.1...v0.3.2
|
||||
[0.3.1]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.0...v0.3.1
|
||||
[0.3.0]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.18...v0.3.0
|
||||
[0.2.18]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.17...v0.2.18
|
||||
[0.2.17]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.16...v0.2.17
|
||||
[0.2.16]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.15...v0.2.16
|
||||
[0.2.15]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.14...v0.2.15
|
||||
[0.2.14]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.13...v0.2.14
|
||||
[0.2.13]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.12...v0.2.13
|
||||
|
||||
Generated
+1345
-986
File diff suppressed because it is too large.
Load diff
+18
-10
@@ -4,7 +4,7 @@ authors = ["meehl"]
|
||||
description = "Cross-platform runtime for Path of Building"
|
||||
repository = "https://github.com/meehl/rusty-path-of-building"
|
||||
license = "MIT"
|
||||
version = "0.2.15"
|
||||
version = "0.3.2"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
@@ -14,35 +14,43 @@ anyhow = "1.0"
|
||||
arboard = { version = "3.6.1", default-features = false }
|
||||
bytemuck = "1.23.2"
|
||||
clap = { version = "4.5.46", features = ["derive"] }
|
||||
dds = "0.1.0"
|
||||
curl = { version = "0.4.51", optional = true }
|
||||
dds = "0.2.0"
|
||||
directories = "6.0.0"
|
||||
env_logger = "0.10"
|
||||
env_logger = "0.11"
|
||||
euclid = { version = "0.22.11", features = ["bytemuck"] }
|
||||
fast_image_resize = { version = "6.0.0", features = ["image"] }
|
||||
flate2 = "1.1.2"
|
||||
glob = "0.3.3"
|
||||
image = { version = "0.25.8", default-features = false, features = ["rayon", "jpeg", "png", "webp"] }
|
||||
log = "0.4"
|
||||
mlua = { version = "0.11.2", features = ["luajit", "anyhow"] }
|
||||
luautf8-rs = { git = "https://github.com/meehl/luautf8-rs.git", rev = "dc74b734e5285108068cf2ffb674c1dc840073c1", features = ["luajit"], optional = true }
|
||||
mlua = { version = "0.12.0", features = ["luajit", "anyhow"] }
|
||||
nohash-hasher = "0.2.0"
|
||||
num-traits = "0.2.19"
|
||||
open = "5.3.2"
|
||||
ordered-float = "5.0.0"
|
||||
parley = "0.6.0"
|
||||
pollster = "0.3"
|
||||
parley = { version = "0.12.0", default-features = false, features = ["std"] }
|
||||
pollster = "1.0"
|
||||
profiling = "1.0"
|
||||
puffin_http = { version = "0.16", optional = true }
|
||||
puffin_http = { version = "0.17", optional = true }
|
||||
raw-window-handle = "0.6.2"
|
||||
regex = "1.11.2"
|
||||
reqwest = { version = "0.13.2", features = ["blocking"] }
|
||||
swash = "0.2.5"
|
||||
tar = "0.4.44"
|
||||
wgpu = { version = "27.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "wgsl"] }
|
||||
wgpu = { version = "30.0.0", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl"] }
|
||||
winit = "0.30"
|
||||
zstd = "0.13.3"
|
||||
zstd = "0.14"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
smithay-clipboard = "0.7.3"
|
||||
|
||||
[features]
|
||||
default = ["bundled-lua-modules"]
|
||||
# Register Rust implementations of the Lua modules required by PoB's Lua code.
|
||||
# Disable this to use the original C libraries.
|
||||
bundled-lua-modules = ["dep:curl", "dep:luautf8-rs"]
|
||||
# Build LuaJIT from source instead of linking against a system installation.
|
||||
vendored-lua = ["mlua/vendored"]
|
||||
profile-with-puffin = ["profiling/profile-with-puffin", "dep:puffin_http"]
|
||||
@@ -1,8 +1,8 @@
|
||||
# Rusty Path of Building
|
||||
|
||||
Rusty Path of Building is a cross-platform runtime environment for [Path of Building](https://github.com/PathOfBuildingCommunity/PathOfBuilding) and [Path of Building 2](https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2). Like [SimpleGraphic](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic), PoB's official runtime environment, it implements the API functions required by PoB's Lua code, handles window management and input, and renders the UI.
|
||||
Rusty Path of Building is a cross-platform runtime environment for [Path of Building](https://github.com/PathOfBuildingCommunity/PathOfBuilding) and [Path of Building 2](https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2). It serves as a replacement for [SimpleGraphic](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic), the official runtime environment for PoB.
|
||||
|
||||
The primary goal of this project is to provide native Linux support for Path of Building. It is written in Rust with cross-platform compatibility in mind and also runs on Windows, though testing there has been minimal.
|
||||
The main focus of this project is native Linux support for Path of Building. It also runs on Windows and macOS, though most of my testing and development is focused on Linux, with support for other platforms largely based on user reports. Contributions that improve support or fix bugs on other platforms are welcome.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -18,14 +18,21 @@ rusty-path-of-building [poe1|poe2]
|
||||
|
||||
[](https://flathub.org/en/apps/community.pathofbuilding.PathOfBuilding)
|
||||
|
||||
### Building from source
|
||||
### Homebrew
|
||||
|
||||
`LuaJIT` needs to be installed on your system for the `mlua` crate to compile.
|
||||
[Homebrew Tap](https://github.com/meehl/homebrew-rusty-path-of-building) (NOTE: This has been tested on macOS only)
|
||||
|
||||
### Building from source
|
||||
|
||||
```bash
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
#### Build Dependencies
|
||||
|
||||
- `LuaJIT` - Required by the `mlua` crate. Alternatively, enable the `vendored-lua` feature to build LuaJIT from source instead of using a system installation.
|
||||
- `libcurl` - Required when the `bundled-lua-modules` feature (enabled by default) is used.
|
||||
|
||||
## Runtime Dependencies
|
||||
|
||||
Path of Building's Lua code requires the following C libraries:
|
||||
@@ -33,10 +40,13 @@ Path of Building's Lua code requires the following C libraries:
|
||||
- [Lua-cURLv3](https://github.com/Lua-cURL/Lua-cURLv3)
|
||||
- [luautf8](https://github.com/starwing/luautf8)
|
||||
- [luasocket](https://github.com/lunarmodules/luasocket)
|
||||
- `lzip` - The source is included in this repo under `lua/libs/lzip` and requires [zlib](https://www.zlib.net/) to compile. Build it with `make LUA_IMPL=luajit`.
|
||||
- [lzip](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic/tree/master/libs/LZip)
|
||||
|
||||
Please refer to the [Lua documentation](https://www.lua.org/manual/5.1/manual.html#pdf-package.cpath) to see how it locates libraries.
|
||||
By default, the `bundled-lua-modules` feature is enabled and registers Rust implementations of these libraries with the Lua runtime. The original C libraries don't need to be installed if this feature is enabled.
|
||||
|
||||
To use the original C libraries instead, disable the feature and make sure Lua can locate them. Please refer to the [Lua documentation](https://www.lua.org/manual/5.1/manual.html#pdf-package.cpath) for details on that.
|
||||
|
||||
## Known Issues
|
||||
|
||||
- If automatic updates fail, navigate to `~/.local/share/RustyPathOfBuilding{1,2}/` and delete both the `rpob.version` file and the `Update` directory. This will force a complete re-download of PoB's latest assets and Lua code on the next startup. (Note: Third-party backends, like this project, face challenges supporting PoB's update mechanism. To make it work, fragile workarounds had to be implemented that can break unexpectedly)
|
||||
- If automatic updates fail, navigate to `~/.local/share/RustyPathOfBuilding{1,2}/` and delete the `rpob.version` file and the `Update` directory. This will force a complete re-download of PoB's latest assets and Lua code on the next startup.
|
||||
- Automatic updates for weekly beta builds are supported, but compatibility is not checked. If you run into problems with a beta version, please don't open an issue for it.
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,75 +0,0 @@
|
||||
T=lzip
|
||||
|
||||
UNAME ?= $(shell uname)
|
||||
DESTDIR ?= /
|
||||
PKG_CONFIG ?= pkg-config
|
||||
INSTALL ?= install
|
||||
RM ?= rm
|
||||
LUA_IMPL ?= luajit
|
||||
CC ?= $(MAC_ENV) g++
|
||||
|
||||
LUA_VERSION = $(shell $(PKG_CONFIG) --print-provides --silence-errors $(LUA_IMPL))
|
||||
ifeq ($(LUA_VERSION),)
|
||||
LUA_CMOD ?= /usr/lib/lua/5.1
|
||||
LUA_LMOD ?= /usr/share/lua/5.1
|
||||
LIBDIR ?= /usr/lib
|
||||
LUA_INC ?= /usr/include
|
||||
ZLIB_LIBS = -L/usr/lib -lz
|
||||
else
|
||||
LUA_CMOD ?= $(shell $(PKG_CONFIG) --variable INSTALL_CMOD $(LUA_IMPL))
|
||||
LUA_LMOD ?= $(shell $(PKG_CONFIG) --variable INSTALL_LMOD $(LUA_IMPL))
|
||||
LIBDIR ?= $(shell $(PKG_CONFIG) --variable libdir $(LUA_IMPL))
|
||||
LUA_INC ?= $(shell $(PKG_CONFIG) --variable includedir $(LUA_IMPL))
|
||||
LUA_LIBS = $(shell $(PKG_CONFIG) --libs $(LUA_IMPL))
|
||||
ZLIB_LIBS = $(shell $(PKG_CONFIG) --libs zlib)
|
||||
endif
|
||||
|
||||
ifeq ($(UNAME), Linux)
|
||||
OS_FLAGS ?= -shared
|
||||
endif
|
||||
ifeq ($(UNAME), Darwin)
|
||||
OS_FLAGS ?= -bundle -undefined dynamic_lookup
|
||||
MAC_ENV ?= env MACOSX_DEPLOYMENT_TARGET='10.3'
|
||||
endif
|
||||
|
||||
ifneq ($(DEBUG),)
|
||||
DBG = -ggdb
|
||||
endif
|
||||
|
||||
ifeq ($(DEV),)
|
||||
WARN = -Wall -Wno-unused-value
|
||||
else
|
||||
WARN = -Wall -W -Waggregate-return -Wcast-align -Wmissing-prototypes -Wnested-externs -Wshadow -Wwrite-strings -pedantic
|
||||
endif
|
||||
|
||||
INCLUDES = -I$(LUA_INC)
|
||||
DEFINES =
|
||||
LIBS = $(ZLIB_LIBS) -lstdc++
|
||||
|
||||
COMMONFLAGS = -O2 -g -pipe -fPIC $(OS_FLAGS) $(DBG)
|
||||
LF = $(LIBS) $(LDFLAGS)
|
||||
CF = $(INCLUDES) $(DEFINES) $(COMMONFLAGS) $(WARN) -DPTHREADS $(CFLAGS)
|
||||
|
||||
SRCS = src/*.cpp
|
||||
OBJS = $(subst src/,,$(subst .c,.o,$(SRCS)))
|
||||
|
||||
BIN = $(T).so
|
||||
STATIC_LIB = $(T).a
|
||||
|
||||
all: $(BIN)
|
||||
|
||||
$(BIN): $(SRCS)
|
||||
$(CC) $(CF) -o $@ $^ $(LF)
|
||||
|
||||
$(OBJS): $(SRCS)
|
||||
$(CC) $(CF) -c $^ $(LF)
|
||||
|
||||
$(STATIC_LIB): $(OBJS)
|
||||
ar rcs $@ $^
|
||||
|
||||
install: all
|
||||
$(INSTALL) -d $(DESTDIR)$(LUA_CMOD)
|
||||
$(INSTALL) $(BIN) $(DESTDIR)$(LUA_CMOD)
|
||||
|
||||
clean:
|
||||
$(RM) -f $(BIN) $(OBJS) $(STATIC_LIB)
|
||||
@@ -1,735 +0,0 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "zlib.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#define LZIP_EXPORT __declspec(dllexport)
|
||||
#else
|
||||
#define LZIP_EXPORT
|
||||
#endif
|
||||
|
||||
extern "C" {
|
||||
#include "lua.h"
|
||||
#include "lauxlib.h"
|
||||
#include "lualib.h"
|
||||
#include "luajit.h"
|
||||
}
|
||||
|
||||
typedef unsigned char byte;
|
||||
typedef unsigned int dword;
|
||||
typedef unsigned long lword;
|
||||
|
||||
char* AllocString(char* st)
|
||||
{
|
||||
if (st == NULL) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int aslen = strlen(st) + 1;
|
||||
char* al = new char[aslen];
|
||||
strcpy(al, st);
|
||||
return al;
|
||||
}
|
||||
|
||||
char* AllocStringLen(int len)
|
||||
{
|
||||
char* al = new char[len+1];
|
||||
al[len] = 0;
|
||||
return al;
|
||||
}
|
||||
|
||||
void FreeString(char* st)
|
||||
{
|
||||
if (st) delete st;
|
||||
}
|
||||
|
||||
// =============
|
||||
// Configuration
|
||||
// =============
|
||||
|
||||
static const int FS_INFLATE_BUFFER = 65536;
|
||||
|
||||
// ==========================
|
||||
// Zip File format structures
|
||||
// ==========================
|
||||
|
||||
#pragma pack(push, 1)
|
||||
|
||||
struct zf_cdHeader_s {
|
||||
int sig; // 0x02014b50 (50,4B,01,02)
|
||||
short ver_made;
|
||||
short ver_ext;
|
||||
short flag;
|
||||
short method;
|
||||
short ftime;
|
||||
short fdate;
|
||||
int crc32;
|
||||
lword szComp;
|
||||
lword szUcomp;
|
||||
short szName;
|
||||
short szExtra;
|
||||
short szComm;
|
||||
short nDisk;
|
||||
short attInt;
|
||||
int attExt;
|
||||
int hOffset;
|
||||
};
|
||||
|
||||
struct zf_localHeader_s {
|
||||
int sig; // 0x04034b50 (50,4B,03,04)
|
||||
short ver_ext;
|
||||
short flag;
|
||||
short method;
|
||||
short ftime;
|
||||
short fdate;
|
||||
int crc32;
|
||||
lword szComp;
|
||||
lword szUcomp;
|
||||
short szName;
|
||||
short szExtra;
|
||||
};
|
||||
|
||||
struct zf_dataDesc_s {
|
||||
int crc32;
|
||||
lword szComp;
|
||||
lword szUcomp;
|
||||
};
|
||||
|
||||
struct zf_cdEnd_s {
|
||||
int sig; // 0x06054b50 (50,4B,05,06)
|
||||
short nDisk;
|
||||
short stDisk;
|
||||
short noeDisk;
|
||||
short noeTotal;
|
||||
int szTotal;
|
||||
int cdOffset;
|
||||
short szComm;
|
||||
};
|
||||
|
||||
#pragma pack(pop)
|
||||
|
||||
// =========================
|
||||
// Zip File format constants
|
||||
// =========================
|
||||
|
||||
static const int ZF_MAXVER = 20;
|
||||
|
||||
static const int ZF_GPBF_ENC = 0x0001;
|
||||
static const int ZF_GPBF_DD = 0x0008;
|
||||
|
||||
static const int ZF_METHOD_STORE = 0;
|
||||
static const int ZF_METHOD_DEFLATE = 8;
|
||||
|
||||
static const int ZF_SIG_CDHEADER = 0x02014B50;
|
||||
static const int ZF_SIG_LOCALHEADER = 0x04034B50;
|
||||
static const int ZF_SIG_CDEND = 0x06054B50;
|
||||
|
||||
// ===============
|
||||
// ZLib Alloc/Free
|
||||
// ===============
|
||||
|
||||
static void* ZF_Alloc(void* unused, dword num, dword size)
|
||||
{
|
||||
return new byte[num*size];
|
||||
}
|
||||
|
||||
static void ZF_Free(void* unused, void* ptr)
|
||||
{
|
||||
delete (byte*)ptr;
|
||||
}
|
||||
|
||||
// =======
|
||||
// Classes
|
||||
// =======
|
||||
|
||||
struct fs_fileInfo_s {
|
||||
FILE* f; // Zip file
|
||||
char* name; // Filename
|
||||
int fo; // File offset
|
||||
int szU; // Uncompressed size
|
||||
int szC; // Compressed size, 0 if not compressed
|
||||
};
|
||||
|
||||
// ================
|
||||
// fsInflator class
|
||||
// ================
|
||||
|
||||
class fs_inflator_c {
|
||||
public:
|
||||
fs_inflator_c(fs_fileInfo_s* i);
|
||||
~fs_inflator_c();
|
||||
int Inflate(byte* buf, int len);// Inflate
|
||||
|
||||
private:
|
||||
int pC; // Read pointer
|
||||
byte* ibuf; // Input buffer
|
||||
int ibuflen; // Input buffer length
|
||||
fs_fileInfo_s* i; // Info structure
|
||||
z_stream* zst; // ZLib stream
|
||||
|
||||
void FillInput();// Fill decompression input
|
||||
};
|
||||
|
||||
fs_inflator_c::fs_inflator_c(fs_fileInfo_s* info)
|
||||
{
|
||||
i = info;
|
||||
|
||||
// Initialise stream
|
||||
zst = new z_stream;
|
||||
memset(zst, 0, sizeof(z_stream));
|
||||
zst->zalloc = ZF_Alloc;
|
||||
zst->zfree = ZF_Free;
|
||||
|
||||
// Initialise decompression input
|
||||
pC = 0;
|
||||
if (i->szC < FS_INFLATE_BUFFER) {
|
||||
ibuflen = i->szC;
|
||||
} else {
|
||||
ibuflen = FS_INFLATE_BUFFER;
|
||||
}
|
||||
ibuf = new byte[ibuflen];
|
||||
FillInput();
|
||||
|
||||
// Start decompressor
|
||||
inflateInit2(zst, -MAX_WBITS);
|
||||
}
|
||||
|
||||
fs_inflator_c::~fs_inflator_c()
|
||||
{
|
||||
// Stop decompressor
|
||||
inflateEnd(zst);
|
||||
|
||||
// Release stream and input buffer
|
||||
delete ibuf;
|
||||
delete zst;
|
||||
}
|
||||
|
||||
void fs_inflator_c::FillInput()
|
||||
{
|
||||
// Relocate any remaining input
|
||||
int remin = zst->avail_in;
|
||||
if (remin) {
|
||||
memcpy(ibuf, zst->next_in, remin);
|
||||
}
|
||||
|
||||
// Get reading amount
|
||||
int rdmax = ibuflen - remin;
|
||||
int rd = i->szC - pC;
|
||||
if (rd > rdmax) {
|
||||
rd = rdmax;
|
||||
}
|
||||
|
||||
// Read into buffer
|
||||
if (rd) {
|
||||
fseek(i->f, i->fo + pC, SEEK_SET);
|
||||
fread(ibuf + remin, rd, 1, i->f);
|
||||
}
|
||||
|
||||
// Update stream
|
||||
zst->next_in = ibuf;
|
||||
zst->avail_in+= rd;
|
||||
pC+= rd;
|
||||
}
|
||||
|
||||
int fs_inflator_c::Inflate(byte* out, int len)
|
||||
{
|
||||
// Prepare stream
|
||||
zst->next_out = out;
|
||||
zst->avail_out = len;
|
||||
|
||||
while (1) {
|
||||
// Decompress some data
|
||||
int r = inflate(zst, Z_SYNC_FLUSH);
|
||||
|
||||
switch (r) {
|
||||
case Z_OK:
|
||||
// Progress made, check if we're done
|
||||
if (zst->avail_out == 0) {
|
||||
return len;
|
||||
}
|
||||
break;
|
||||
case Z_BUF_ERROR:
|
||||
// No progress made, so give it more input
|
||||
FillInput();
|
||||
break;
|
||||
default:
|
||||
// We got an error
|
||||
case Z_STREAM_END:
|
||||
// Reached the end of the stream
|
||||
return len - zst->avail_out;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============
|
||||
// fsFile class
|
||||
// =============
|
||||
|
||||
enum vf_state_e {
|
||||
VF_OPEN =0x01, // Open
|
||||
VF_SEEK =0x04 // Seek enabled
|
||||
};
|
||||
|
||||
class fs_file_c {
|
||||
public:
|
||||
fs_file_c(fs_fileInfo_s* i);
|
||||
~fs_file_c();
|
||||
void Seek(int pos, int mode); // Seek
|
||||
int Read(byte* buf, int len); // Read data
|
||||
int Length(); // Return the file length
|
||||
int Tell(); // Return the read pointer
|
||||
|
||||
private:
|
||||
fs_fileInfo_s* i; // Info structure
|
||||
int pU; // Read pointer
|
||||
fs_inflator_c* inf; // Inflator
|
||||
};
|
||||
|
||||
fs_file_c::fs_file_c(fs_fileInfo_s* info)
|
||||
{
|
||||
i = info;
|
||||
|
||||
// Create inflator
|
||||
if (i->szC) {
|
||||
inf = new fs_inflator_c(i);
|
||||
} else {
|
||||
inf = NULL;
|
||||
}
|
||||
|
||||
// Set position
|
||||
pU = 0;
|
||||
}
|
||||
|
||||
fs_file_c::~fs_file_c()
|
||||
{
|
||||
delete inf;
|
||||
}
|
||||
|
||||
void fs_file_c::Seek(int pos, int mode)
|
||||
{
|
||||
int seekto;
|
||||
|
||||
switch (mode) {
|
||||
case SEEK_SET:
|
||||
seekto = pos;
|
||||
break;
|
||||
case SEEK_CUR:
|
||||
seekto = pU + pos;
|
||||
break;
|
||||
case SEEK_END:
|
||||
seekto = i->szU - pos;
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
|
||||
if (i->szC) {
|
||||
int diff = seekto - pU;
|
||||
if (diff > 0) {
|
||||
// Seek forward
|
||||
byte* sk = new byte[diff];
|
||||
Read(sk, diff);
|
||||
delete[] sk;
|
||||
} else if (diff < 0) {
|
||||
// Restart reading
|
||||
pU = 0;
|
||||
// Recreate inflator
|
||||
delete inf;
|
||||
inf = new fs_inflator_c(i);
|
||||
if (seekto) {
|
||||
// Seek forward
|
||||
byte* sk = new byte[seekto];
|
||||
Read(sk, seekto);
|
||||
delete[] sk;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
pU = seekto;
|
||||
if (pU < 0) {
|
||||
pU = 0;
|
||||
} else if (pU > i->szU) {
|
||||
pU = i->szU;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int fs_file_c::Read(byte* out, int len)
|
||||
{
|
||||
// Determine read length
|
||||
int rp = len + pU;
|
||||
if (rp > i->szU) len = i->szU - pU;
|
||||
if (len == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (i->szC) {
|
||||
// Decompress
|
||||
len = inf->Inflate(out, len);
|
||||
} else {
|
||||
// Raw read
|
||||
fseek(i->f, i->fo + pU, SEEK_SET);
|
||||
len = fread(out, 1, len, i->f);
|
||||
}
|
||||
|
||||
pU+= len;
|
||||
return len;
|
||||
}
|
||||
|
||||
int fs_file_c::Length()
|
||||
{
|
||||
return i->szU;
|
||||
}
|
||||
|
||||
int fs_file_c::Tell()
|
||||
{
|
||||
return pU;
|
||||
}
|
||||
|
||||
// =============
|
||||
// zipFile class
|
||||
// =============
|
||||
|
||||
class fs_zipFile_c {
|
||||
public:
|
||||
fs_zipFile_c(const char* zname);
|
||||
~fs_zipFile_c();
|
||||
|
||||
int numFiles;
|
||||
fs_fileInfo_s** files;
|
||||
private:
|
||||
FILE* zf; // File handle
|
||||
int filesSz;
|
||||
|
||||
int GetSignature(); // Get next signature
|
||||
};
|
||||
|
||||
int fs_zipFile_c::GetSignature()
|
||||
{
|
||||
int sig = 0;
|
||||
if (fread(&sig, 4, 1, zf) == 0) {
|
||||
return 0;
|
||||
}
|
||||
fseek(zf, -4, SEEK_CUR);
|
||||
return sig;
|
||||
}
|
||||
|
||||
fs_zipFile_c::fs_zipFile_c(const char* zname)
|
||||
{
|
||||
numFiles = 0;
|
||||
filesSz = 32;
|
||||
files = new fs_fileInfo_s*[filesSz];
|
||||
|
||||
int sig;
|
||||
|
||||
// Open and lock file
|
||||
zf = fopen(zname, "rb");
|
||||
if (zf == NULL) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check signature
|
||||
sig = GetSignature();
|
||||
if (strncmp((char*)&sig, "Rar", 3) == 0) {
|
||||
fclose(zf);
|
||||
return;
|
||||
}
|
||||
|
||||
// Read local headers
|
||||
while (sig == ZF_SIG_LOCALHEADER) {
|
||||
zf_localHeader_s lh;
|
||||
if (fread(&lh, sizeof(lh), 1, zf) == 0) {
|
||||
fclose(zf);
|
||||
return;
|
||||
}
|
||||
|
||||
if (lh.szName) {
|
||||
// Read filename
|
||||
char* fname = AllocStringLen(lh.szName);
|
||||
fread(fname, lh.szName, 1, zf);
|
||||
|
||||
// Add it in if it is a file
|
||||
if (fname[lh.szName-1] != '/') {
|
||||
// Fill in info
|
||||
fs_fileInfo_s* fi = new fs_fileInfo_s;
|
||||
fi->f = zf;
|
||||
fi->name = fname;
|
||||
fi->fo = ftell(zf) + lh.szExtra;
|
||||
fi->szU = lh.szUcomp;
|
||||
fi->szC = (lh.method == ZF_METHOD_DEFLATE)? lh.szComp : 0;
|
||||
|
||||
// Record file
|
||||
if (numFiles == filesSz) {
|
||||
filesSz<<= 1;
|
||||
files = (fs_fileInfo_s**)realloc(files, sizeof(fs_fileInfo_s*)*filesSz);
|
||||
}
|
||||
files[numFiles++] = fi;
|
||||
} else {
|
||||
FreeString(fname);
|
||||
}
|
||||
|
||||
// Skip the extra information and file data
|
||||
fseek(zf, lh.szExtra + lh.szComp, SEEK_CUR);
|
||||
}
|
||||
|
||||
sig = GetSignature();
|
||||
}
|
||||
}
|
||||
|
||||
fs_zipFile_c::~fs_zipFile_c()
|
||||
{
|
||||
fclose(zf);
|
||||
for (int f = 0; f < numFiles; f++) {
|
||||
delete files[f]->name;
|
||||
delete files[f];
|
||||
}
|
||||
delete files;
|
||||
}
|
||||
|
||||
// =============
|
||||
// Lua Interface
|
||||
// =============
|
||||
|
||||
static int IsUserData(lua_State* L, int index, const char* metaName)
|
||||
{
|
||||
if (lua_type(L, index) != LUA_TUSERDATA || lua_getmetatable(L, index) == 0) {
|
||||
return 0;
|
||||
}
|
||||
lua_getfield(L, lua_upvalueindex(1), metaName);
|
||||
int ret = lua_rawequal(L, -2, -1);
|
||||
lua_pop(L, 2);
|
||||
return ret;
|
||||
}
|
||||
|
||||
struct lzip_s {
|
||||
fs_zipFile_c* zipFile;
|
||||
};
|
||||
static lzip_s* GetZip(lua_State* L, const char* method, bool valid)
|
||||
{
|
||||
if ( !IsUserData(L, 1, "zipMeta") ) {
|
||||
luaL_error(L, "zip:%s() must be used on a zip handle", method);
|
||||
}
|
||||
lzip_s* lz = (lzip_s*)lua_touserdata(L, 1);
|
||||
lua_remove(L, 1);
|
||||
if (valid && lz->zipFile == NULL) {
|
||||
luaL_error(L, "zip:%s(): zip handle is closed");
|
||||
}
|
||||
return lz;
|
||||
}
|
||||
|
||||
struct lzipFile_s {
|
||||
fs_file_c* file;
|
||||
};
|
||||
static lzipFile_s* GetZipFile(lua_State* L, const char* method, bool valid)
|
||||
{
|
||||
if ( !IsUserData(L, 1, "zipFileMeta") ) {
|
||||
luaL_error(L, "zipFile:%s() must be used on a zip file handle", method);
|
||||
}
|
||||
lzipFile_s* lzf = (lzipFile_s*)lua_touserdata(L, 1);
|
||||
lua_remove(L, 1);
|
||||
if (valid && lzf->file == NULL) {
|
||||
luaL_error(L, "zipFile:%s(): zip file handle is closed");
|
||||
}
|
||||
return lzf;
|
||||
}
|
||||
|
||||
static int l_open(lua_State* L)
|
||||
{
|
||||
int n = lua_gettop(L);
|
||||
if (n < 1 || !lua_isstring(L, 1)) {
|
||||
luaL_error(L, "Usage: lzip.open(fileName)");
|
||||
}
|
||||
fs_zipFile_c* zipFile = new fs_zipFile_c(lua_tostring(L, 1));
|
||||
if (zipFile->numFiles == 0) {
|
||||
delete zipFile;
|
||||
return 0;
|
||||
}
|
||||
lzip_s* lz = (lzip_s*)lua_newuserdata(L, sizeof(lzip_s));
|
||||
lz->zipFile = zipFile;
|
||||
lua_pushvalue(L, lua_upvalueindex(2));
|
||||
lua_setmetatable(L, -2);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int l_zip_Close(lua_State* L)
|
||||
{
|
||||
lzip_s* lz = GetZip(L, "Closea", false);
|
||||
delete lz->zipFile;
|
||||
lz->zipFile = NULL;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int l_zip_GetNumFiles(lua_State* L)
|
||||
{
|
||||
lzip_s* lz = GetZip(L, "GetNumFiles", true);
|
||||
lua_pushinteger(L, lz->zipFile->numFiles);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int l_zip_GetFileName(lua_State* L)
|
||||
{
|
||||
lzip_s* lz = GetZip(L, "GetFileName", true);
|
||||
int n = lua_gettop(L);
|
||||
if (n < 1 || !lua_isnumber(L, 1)) {
|
||||
luaL_error(L, "Usage: zip:GetFileName(index)");
|
||||
}
|
||||
int index = lua_tointeger(L, 1);
|
||||
if (index < 1 || index > lz->zipFile->numFiles) {
|
||||
return 0;
|
||||
}
|
||||
lua_pushstring(L, lz->zipFile->files[index - 1]->name);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int l_zip_GetFileSize(lua_State* L)
|
||||
{
|
||||
lzip_s* lz = GetZip(L, "GetFileSize", true);
|
||||
int n = lua_gettop(L);
|
||||
if (n < 1 || !lua_isnumber(L, 1)) {
|
||||
luaL_error(L, "Usage: zip:GetFileSize(index)");
|
||||
}
|
||||
int index = lua_tointeger(L, 1);
|
||||
if (index < 1 || index > lz->zipFile->numFiles) {
|
||||
return 0;
|
||||
}
|
||||
lua_pushinteger(L, lz->zipFile->files[index - 1]->szU);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int l_zip_OpenFile(lua_State* L)
|
||||
{
|
||||
lzip_s* lz = GetZip(L, "OpenFile", true);
|
||||
int n = lua_gettop(L);
|
||||
if (n < 1 || !(lua_isnumber(L, 1) || lua_isstring(L, 1))) {
|
||||
luaL_error(L, "Usage: zip:OpenFile(index) or zip:OpenFile(fileName)");
|
||||
}
|
||||
fs_fileInfo_s* i = NULL;
|
||||
if (lua_isnumber(L, 1)) {
|
||||
int index = lua_tointeger(L, 1);
|
||||
if (index < 1 || index > lz->zipFile->numFiles) {
|
||||
luaL_error(L, "zip:OpenFile(): invalid index");
|
||||
}
|
||||
i = lz->zipFile->files[index - 1];
|
||||
} else {
|
||||
const char* name = lua_tostring(L, 1);
|
||||
for (int index = 0; index < lz->zipFile->numFiles; index++) {
|
||||
if ( !strcmp(name, lz->zipFile->files[index]->name) ) {
|
||||
i = lz->zipFile->files[index];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ( !i ) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
fs_file_c* file = new fs_file_c(i);
|
||||
lzipFile_s* lzf = (lzipFile_s*)lua_newuserdata(L, sizeof(lzipFile_s));
|
||||
lzf->file = file;
|
||||
lua_pushvalue(L, lua_upvalueindex(2));
|
||||
lua_setmetatable(L, -2);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int l_zipFile_Close(lua_State* L)
|
||||
{
|
||||
lzipFile_s* lzf = GetZipFile(L, "Close", false);
|
||||
delete lzf->file;
|
||||
lzf->file = NULL;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int l_zipFile_Read(lua_State* L)
|
||||
{
|
||||
lzipFile_s* lzf = GetZipFile(L, "Read", true);
|
||||
int n = lua_gettop(L);
|
||||
if (n < 1) {
|
||||
luaL_error(L, "Usage: zipFile:Read(count) or zipFile:read(\"*a\")");
|
||||
}
|
||||
int count = 0;
|
||||
if (lua_isnumber(L, 1)) {
|
||||
count = lua_tointeger(L, 1);
|
||||
} else {
|
||||
if ( !strcmp(lua_tostring(L, 1), "*a") ) {
|
||||
count = lzf->file->Length() - lzf->file->Tell();
|
||||
} else {
|
||||
luaL_error(L, "zipFile:Read(): unrecognised format: %s", lua_tostring(L, 1));
|
||||
}
|
||||
}
|
||||
if (count < 1) {
|
||||
lua_pushstring(L, "");
|
||||
return 1;
|
||||
}
|
||||
byte* buf = new byte[count];
|
||||
lzf->file->Read(buf, count);
|
||||
lua_pushlstring(L, (char*)buf, count);
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int l_zipFile_Length(lua_State* L)
|
||||
{
|
||||
lzipFile_s* lzf = GetZipFile(L, "Read", true);
|
||||
lua_pushinteger(L, lzf->file->Length());
|
||||
return 1;
|
||||
}
|
||||
|
||||
extern "C" LZIP_EXPORT int luaopen_lzip(lua_State* L)
|
||||
{
|
||||
lua_settop(L, 0);
|
||||
lua_newtable(L); // Library table
|
||||
lua_newtable(L); // Zip metatable
|
||||
lua_newtable(L); // Zip file metatable
|
||||
|
||||
lua_pushvalue(L, 2);
|
||||
lua_setfield(L, 1, "zipMeta");
|
||||
lua_pushvalue(L, 2);
|
||||
lua_setfield(L, 2, "__index");
|
||||
|
||||
lua_pushvalue(L, 3);
|
||||
lua_setfield(L, 1, "zipFileMeta");
|
||||
lua_pushvalue(L, 3);
|
||||
lua_setfield(L, 3, "__index");
|
||||
|
||||
lua_pushvalue(L, 1);
|
||||
lua_pushvalue(L, 2);
|
||||
lua_pushcclosure(L, l_open, 2);
|
||||
lua_setfield(L, 1, "open");
|
||||
|
||||
lua_pushvalue(L, 1);
|
||||
lua_pushcclosure(L, l_zip_Close, 1);
|
||||
lua_setfield(L, 2, "__gc");
|
||||
lua_pushvalue(L, 1);
|
||||
lua_pushcclosure(L, l_zip_Close, 1);
|
||||
lua_setfield(L, 2, "Close");
|
||||
lua_pushvalue(L, 1);
|
||||
lua_pushcclosure(L, l_zip_GetNumFiles, 1);
|
||||
lua_setfield(L, 2, "GetNumFiles");
|
||||
lua_pushvalue(L, 1);
|
||||
lua_pushcclosure(L, l_zip_GetFileName, 1);
|
||||
lua_setfield(L, 2, "GetFileName");
|
||||
lua_pushvalue(L, 1);
|
||||
lua_pushcclosure(L, l_zip_GetFileSize, 1);
|
||||
lua_setfield(L, 2, "GetFileSize");
|
||||
lua_pushvalue(L, 1);
|
||||
lua_pushvalue(L, 3);
|
||||
lua_pushcclosure(L, l_zip_OpenFile, 2);
|
||||
lua_setfield(L, 2, "OpenFile");
|
||||
|
||||
lua_pushvalue(L, 1);
|
||||
lua_pushcclosure(L, l_zipFile_Close, 1);
|
||||
lua_setfield(L, 3, "__gc");
|
||||
lua_pushvalue(L, 1);
|
||||
lua_pushcclosure(L, l_zipFile_Close, 1);
|
||||
lua_setfield(L, 3, "Close");
|
||||
lua_pushvalue(L, 1);
|
||||
lua_pushcclosure(L, l_zipFile_Read, 1);
|
||||
lua_setfield(L, 3, "Read");
|
||||
lua_pushvalue(L, 1);
|
||||
lua_pushcclosure(L, l_zipFile_Length, 1);
|
||||
lua_setfield(L, 3, "Length");
|
||||
|
||||
// Pop metatables
|
||||
lua_pop(L, 2);
|
||||
|
||||
return 1;
|
||||
}
|
||||
-164
@@ -1,164 +0,0 @@
|
||||
pub use crate::api::callback::get_callback;
|
||||
use crate::{
|
||||
api::{
|
||||
callback::{get_custom_callback, set_custom_callback, set_main_object},
|
||||
clipboard::{copy, paste},
|
||||
compression::{deflate, inflate},
|
||||
console::{console_clear, console_execute, console_print_table, console_printf},
|
||||
image_handle::new_image_handle,
|
||||
input::{get_cursor_pos, is_key_down},
|
||||
lua::{load_module, protected_call, protected_load_module},
|
||||
paths::{
|
||||
get_runtime_path, get_script_path, get_user_path, get_work_dir, make_dir, remove_dir,
|
||||
set_work_dir,
|
||||
},
|
||||
rendering::PoBString,
|
||||
search_handle::new_search_handle,
|
||||
window::{
|
||||
get_dpi_scale_override, get_screen_scale, get_screen_size, set_dpi_scale_override,
|
||||
set_foreground, set_window_title,
|
||||
},
|
||||
},
|
||||
lua::Context,
|
||||
};
|
||||
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Variadic};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
mod callback;
|
||||
mod clipboard;
|
||||
mod compression;
|
||||
mod console;
|
||||
mod image_handle;
|
||||
mod input;
|
||||
mod lua;
|
||||
mod paths;
|
||||
mod rendering;
|
||||
mod search_handle;
|
||||
mod window;
|
||||
|
||||
/// Register functions that can be called from lua
|
||||
pub fn register_globals(lua: &Lua) -> LuaResult<()> {
|
||||
let globals = lua.globals();
|
||||
|
||||
// callbacks
|
||||
globals.set("SetMainObject", lua.create_function(set_main_object)?)?;
|
||||
globals.set("SetCallback", lua.create_function(set_custom_callback)?)?;
|
||||
globals.set("GetCallback", lua.create_function(get_custom_callback)?)?;
|
||||
|
||||
// paths
|
||||
globals.set("GetUserPath", lua.create_function(get_user_path)?)?;
|
||||
globals.set("GetScriptPath", lua.create_function(get_script_path)?)?;
|
||||
globals.set("GetRuntimePath", lua.create_function(get_runtime_path)?)?;
|
||||
globals.set("GetWorkDir", lua.create_function(get_work_dir)?)?;
|
||||
globals.set("SetWorkDir", lua.create_function(set_work_dir)?)?;
|
||||
globals.set("MakeDir", lua.create_function(make_dir)?)?;
|
||||
globals.set("RemoveDir", lua.create_function(remove_dir)?)?;
|
||||
|
||||
// console
|
||||
globals.set("ConPrintf", lua.create_function(console_printf)?)?;
|
||||
globals.set("ConExecute", lua.create_function(console_execute)?)?;
|
||||
globals.set("ConClear", lua.create_function(console_clear)?)?;
|
||||
globals.set("ConPrintTable", lua.create_function(console_print_table)?)?;
|
||||
|
||||
// general
|
||||
globals.set("GetTime", lua.create_function(get_time)?)?;
|
||||
globals.set("StripEscapes", lua.create_function(strip_escapes)?)?;
|
||||
globals.set("Exit", lua.create_function(exit)?)?;
|
||||
globals.set("Restart", lua.create_function(restart)?)?;
|
||||
globals.set("OpenURL", lua.create_function(open_url)?)?;
|
||||
globals.set("RenderInit", lua.create_function(render_init)?)?;
|
||||
|
||||
let take_screenshot = |_: &Lua, ()| -> LuaResult<()> { Ok(()) }; // stub
|
||||
globals.set("TakeScreenshot", lua.create_function(take_screenshot)?)?;
|
||||
|
||||
// compression
|
||||
globals.set("Inflate", lua.create_function(inflate)?)?;
|
||||
globals.set("Deflate", lua.create_function(deflate)?)?;
|
||||
|
||||
// search handle
|
||||
globals.set("NewFileSearch", lua.create_function(new_search_handle)?)?;
|
||||
|
||||
// image handle
|
||||
globals.set("NewImageHandle", lua.create_function(new_image_handle)?)?;
|
||||
|
||||
// clipboard
|
||||
globals.set("Copy", lua.create_function(copy)?)?;
|
||||
globals.set("Paste", lua.create_function(paste)?)?;
|
||||
|
||||
// input
|
||||
globals.set("GetCursorPos", lua.create_function(get_cursor_pos)?)?;
|
||||
globals.set("IsKeyDown", lua.create_function(is_key_down)?)?;
|
||||
|
||||
// window
|
||||
globals.set("GetScreenSize", lua.create_function(get_screen_size)?)?;
|
||||
globals.set("GetScreenScale", lua.create_function(get_screen_scale)?)?;
|
||||
globals.set("SetWindowTitle", lua.create_function(set_window_title)?)?;
|
||||
globals.set("SetForeground", lua.create_function(set_foreground)?)?;
|
||||
globals.set(
|
||||
"SetDPIScaleOverridePercent",
|
||||
lua.create_function(set_dpi_scale_override)?,
|
||||
)?;
|
||||
globals.set(
|
||||
"GetDPIScaleOverridePercent",
|
||||
lua.create_function(get_dpi_scale_override)?,
|
||||
)?;
|
||||
|
||||
// lua
|
||||
globals.set("PCall", lua.create_function(protected_call)?)?;
|
||||
globals.set("LoadModule", lua.create_function(load_module)?)?;
|
||||
globals.set("PLoadModule", lua.create_function(protected_load_module)?)?;
|
||||
|
||||
// NOTE: not used by PoB
|
||||
let set_cursor_pos = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
let show_cursor = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
globals.set("SetCursorPos", lua.create_function(set_cursor_pos)?)?;
|
||||
globals.set("ShowCursor", lua.create_function(show_cursor)?)?;
|
||||
|
||||
// rendering
|
||||
rendering::register_globals(lua)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_time(_l: &Lua, _: ()) -> LuaResult<u128> {
|
||||
Ok(SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_millis())
|
||||
}
|
||||
|
||||
fn strip_escapes(_: &Lua, text: String) -> LuaResult<String> {
|
||||
Ok(PoBString(&text).strip_escapes())
|
||||
}
|
||||
|
||||
fn exit(l: &Lua, exit_msg: Option<String>) -> LuaResult<()> {
|
||||
if let Some(exit_msg) = exit_msg {
|
||||
println!("{exit_msg}");
|
||||
}
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
*ctx.should_exit() = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restart(l: &Lua, _: ()) -> LuaResult<()> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
*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(l: &Lua, features: Variadic<String>) -> LuaResult<()> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
for feature in features {
|
||||
if feature == "DPI_AWARE" {
|
||||
*ctx.is_dpi_aware() = true;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
use mlua::{Function, Lua, Result as LuaResult, Table, Value};
|
||||
|
||||
// During initialization, PoB calls `SetMainObject` with a callback table.
|
||||
// Functions defined in this table are used to call back into Lua from Rust.
|
||||
// Custom callback functions can be added with `SetCallback` and retrieved
|
||||
// with `GetCallback`.
|
||||
const CALLBACK_REGISTRY_NAME: &str = "uicallbacks";
|
||||
|
||||
pub fn get_callback(lua: &Lua, name: &str) -> LuaResult<Function> {
|
||||
let callback_table: Table = lua.named_registry_value(CALLBACK_REGISTRY_NAME)?;
|
||||
let callback_function: Value = callback_table.get(name)?;
|
||||
if callback_function.is_function() {
|
||||
// function defined through `SetCallback`
|
||||
return Ok(callback_function.as_function().unwrap().clone());
|
||||
} else {
|
||||
// look for function in `MainObject`
|
||||
let main_object: Table = callback_table.get("MainObject")?;
|
||||
let callback_function: Value = main_object.get(name)?;
|
||||
if callback_function.is_function() {
|
||||
// these functions expect `MainObject` as first argument so we bind it here
|
||||
return callback_function.as_function().unwrap().bind(main_object);
|
||||
}
|
||||
}
|
||||
Err(anyhow::anyhow!("Function '{}' not found", name).into())
|
||||
}
|
||||
|
||||
pub fn set_main_object(l: &Lua, main_object: Table) -> LuaResult<()> {
|
||||
let callback_table = l.create_table()?;
|
||||
callback_table.set("MainObject", main_object)?;
|
||||
l.set_named_registry_value(CALLBACK_REGISTRY_NAME, callback_table)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_custom_callback(l: &Lua, (name, func): (String, Function)) -> LuaResult<()> {
|
||||
let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?;
|
||||
callback_table.set(name, func)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_custom_callback(l: &Lua, name: String) -> LuaResult<Function> {
|
||||
let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?;
|
||||
let callback_function: Function = callback_table.get(name)?;
|
||||
Ok(callback_function)
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
use crate::lua::Context;
|
||||
use mlua::{Lua, Result as LuaResult};
|
||||
|
||||
pub fn copy(l: &Lua, text: String) -> LuaResult<()> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
ctx.window().set_clipboard_text(text);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn paste(l: &Lua, _: ()) -> LuaResult<Option<String>> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
Ok(ctx.window().get_clipboard_text())
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
use flate2::{
|
||||
Compression,
|
||||
read::{ZlibDecoder, ZlibEncoder},
|
||||
};
|
||||
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, String as LuaString, Value};
|
||||
use std::io::Read;
|
||||
|
||||
pub fn inflate(l: &Lua, compressed: LuaString) -> LuaResult<MultiValue> {
|
||||
let compressed_bytes = &compressed.as_bytes()[..];
|
||||
|
||||
// prevent decompression of input larger than 128MiB
|
||||
if compressed_bytes.len() > (128 << 20) {
|
||||
return Ok((Value::Nil, "Input larger than 128 MiB")
|
||||
.into_lua_multi(l)
|
||||
.unwrap());
|
||||
}
|
||||
|
||||
let mut decoder = ZlibDecoder::new(compressed_bytes);
|
||||
let mut decompressed = Vec::new();
|
||||
match decoder.read_to_end(&mut decompressed) {
|
||||
Ok(_) => Ok(l
|
||||
.create_string(&decompressed)
|
||||
.unwrap()
|
||||
.into_lua_multi(l)
|
||||
.unwrap()),
|
||||
Err(e) => Ok((Value::Nil, e.to_string()).into_lua_multi(l).unwrap()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deflate(l: &Lua, uncompressed: LuaString) -> LuaResult<MultiValue> {
|
||||
let uncompressed_bytes = &uncompressed.as_bytes()[..];
|
||||
|
||||
// prevent compression of input larger than 128MiB
|
||||
if uncompressed_bytes.len() > (128 << 20) {
|
||||
return Ok((Value::Nil, "Input larger than 128 MiB")
|
||||
.into_lua_multi(l)
|
||||
.unwrap());
|
||||
}
|
||||
|
||||
let mut encoder = ZlibEncoder::new(uncompressed_bytes, Compression::fast());
|
||||
let mut compressed = Vec::new();
|
||||
match encoder.read_to_end(&mut compressed) {
|
||||
Ok(_) => Ok(l
|
||||
.create_string(&compressed)
|
||||
.unwrap()
|
||||
.into_lua_multi(l)
|
||||
.unwrap()),
|
||||
Err(e) => Ok((Value::Nil, e.to_string()).into_lua_multi(l).unwrap()),
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
use crate::{
|
||||
lua::Context,
|
||||
renderer::textures::{TextureHandle, TextureOptions},
|
||||
};
|
||||
use mlua::{Lua, MultiValue, Result as LuaResult, UserData};
|
||||
|
||||
pub fn new_image_handle(_: &Lua, _: ()) -> LuaResult<ImageHandle> {
|
||||
Ok(ImageHandle::Unloaded)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum ImageHandle {
|
||||
Loaded(TextureHandle),
|
||||
Unloaded,
|
||||
}
|
||||
|
||||
impl UserData for ImageHandle {
|
||||
fn add_methods<M: mlua::UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_method_mut("Load", load);
|
||||
|
||||
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)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn load(
|
||||
lua: &Lua,
|
||||
handle: &mut ImageHandle,
|
||||
(image_path, flags): (String, MultiValue),
|
||||
) -> LuaResult<()> {
|
||||
let ctx = lua.app_data_ref::<&'static Context>().unwrap();
|
||||
let mut is_async = false;
|
||||
let mut options = TextureOptions::LINEAR_REPEAT;
|
||||
|
||||
for flag in flags.iter() {
|
||||
if let Some(flag) = flag.as_string() {
|
||||
match flag.to_string_lossy().as_str() {
|
||||
"CLAMP" => options.wrap_mode = wgpu::AddressMode::ClampToEdge,
|
||||
"NEAREST" => options.magnification = wgpu::FilterMode::Nearest,
|
||||
"ASYNC" => is_async = true,
|
||||
"MIPMAP" => options.generate_mipmaps = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match handle {
|
||||
// replace image data if already allocated
|
||||
ImageHandle::Loaded(texture_handle) => {
|
||||
// in case of error, stay loaded with current texture
|
||||
let _ = ctx.texture_manager().update_texture(
|
||||
texture_handle.id(),
|
||||
image_path,
|
||||
options,
|
||||
is_async,
|
||||
);
|
||||
}
|
||||
// create new texture handle
|
||||
ImageHandle::Unloaded => {
|
||||
if let Ok(tex_handle) = ctx
|
||||
.texture_manager()
|
||||
.load_texture(image_path, options, is_async)
|
||||
{
|
||||
*handle = ImageHandle::Loaded(tex_handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
use crate::{
|
||||
input::{str_as_key, str_as_mousebutton},
|
||||
lua::Context,
|
||||
};
|
||||
use mlua::{Lua, Result as LuaResult};
|
||||
|
||||
pub fn get_cursor_pos(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
let pos = ctx.input().mouse_pos();
|
||||
Ok((pos.x as u32, pos.y as u32))
|
||||
}
|
||||
|
||||
pub fn is_key_down(l: &Lua, key_name: String) -> LuaResult<bool> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
|
||||
if let Some(key) = str_as_key(&key_name) {
|
||||
Ok(ctx.input().key_pressed(key))
|
||||
} else if let Some(button) = str_as_mousebutton(&key_name) {
|
||||
Ok(ctx.input().mouse_pressed(button))
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
use crate::{lua::Context, util::change_working_directory};
|
||||
use mlua::{Function, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
|
||||
use std::env;
|
||||
|
||||
pub fn protected_call(l: &Lua, (func, args): (Function, MultiValue)) -> LuaResult<MultiValue> {
|
||||
match func.call::<MultiValue>(args) {
|
||||
// callers expect first return value to be Nil on success
|
||||
Ok(return_values) => Ok(std::iter::once(Value::Nil).chain(return_values).collect()),
|
||||
// otherwise it is set to error message.
|
||||
Err(err) => Ok(err.to_string().into_lua_multi(l)?),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
let mut module_path = ctx.script_dir().join(name);
|
||||
if module_path.extension().is_none() {
|
||||
module_path.set_extension("lua");
|
||||
}
|
||||
|
||||
let current_dir = env::current_dir()?;
|
||||
change_working_directory(ctx.script_dir().as_path())?;
|
||||
let result = l.load(module_path).call::<MultiValue>(args);
|
||||
change_working_directory(current_dir)?;
|
||||
result
|
||||
}
|
||||
|
||||
pub fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
let mut module_path = ctx.script_dir().join(name);
|
||||
if module_path.extension().is_none() {
|
||||
module_path.set_extension("lua");
|
||||
}
|
||||
|
||||
let current_dir = env::current_dir()?;
|
||||
change_working_directory(ctx.script_dir().as_path())?;
|
||||
let result = match l.load(module_path).call::<MultiValue>(args) {
|
||||
// on success, callers expect a Nil followed by return values
|
||||
Ok(res) => Ok(std::iter::once(Value::Nil).chain(res).collect()),
|
||||
// otherwise it is set to error message.
|
||||
Err(err) => Ok(err.to_string().into_lua_multi(l)?),
|
||||
};
|
||||
change_working_directory(current_dir)?;
|
||||
result
|
||||
}
|
||||
@@ -1,693 +0,0 @@
|
||||
use crate::{
|
||||
api::image_handle::ImageHandle,
|
||||
color::Srgba,
|
||||
dpi::Uv,
|
||||
fonts::{Alignment, FontStyle, LayoutJob},
|
||||
lua::Context,
|
||||
math::{Point, Quad, Rect, Size},
|
||||
};
|
||||
use core::ffi::{c_int, c_void};
|
||||
use mlua::{
|
||||
LightUserData, Lua, Result as LuaResult, UserDataRefMut, Value,
|
||||
ffi::{self},
|
||||
};
|
||||
use parley::FontFamily;
|
||||
use regex::Regex;
|
||||
use std::{borrow::Cow, sync::LazyLock};
|
||||
|
||||
pub fn register_globals(lua: &Lua) -> LuaResult<()> {
|
||||
let globals = lua.globals();
|
||||
|
||||
// unused functions
|
||||
let get_draw_layer = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
let set_blend_mode = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
let get_async_count = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
let set_clear_color = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() };
|
||||
globals.set("GetDrawLayer", lua.create_function(get_draw_layer)?)?;
|
||||
globals.set("SetBlendMode", lua.create_function(set_blend_mode)?)?;
|
||||
globals.set("GetAsyncCount", lua.create_function(get_async_count)?)?;
|
||||
globals.set("SetClearColor", lua.create_function(set_clear_color)?)?;
|
||||
|
||||
// rendering functions
|
||||
// NOTE: unfortunately, mlua's conversion of function arguments adds a lot of
|
||||
// overhead. this is very noticeable for the draw functions which can be called
|
||||
// thousands of times per frame. C functions are used to get raw access to
|
||||
// the lua stack without the overhead.
|
||||
unsafe { globals.set("SetDrawColor", lua.create_c_function(set_draw_color)?)? };
|
||||
unsafe { globals.set("GetDrawColor", lua.create_c_function(get_draw_color)?)? };
|
||||
unsafe { globals.set("SetViewport", lua.create_c_function(set_viewport)?)? };
|
||||
unsafe {
|
||||
globals.set("SetDrawLayer", lua.create_c_function(set_draw_layer)?)?;
|
||||
}
|
||||
unsafe { globals.set("DrawImage", lua.create_c_function(draw_image)?)? };
|
||||
unsafe { globals.set("DrawImageQuad", lua.create_c_function(draw_image_quad)?)? };
|
||||
unsafe {
|
||||
globals.set("DrawString", lua.create_c_function(draw_string)?)?;
|
||||
}
|
||||
unsafe {
|
||||
globals.set("DrawStringWidth", lua.create_c_function(get_string_width)?)?;
|
||||
}
|
||||
globals.set(
|
||||
"DrawStringCursorIndex",
|
||||
lua.create_function_mut(get_index_at_cur)?,
|
||||
)?;
|
||||
|
||||
// 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 lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
match nargs {
|
||||
// escape_code
|
||||
1 => {
|
||||
let esc_str = str_from_stack!(state, -nargs);
|
||||
let color = Srgba::from_escape_code(esc_str);
|
||||
ctx.layers().set_draw_color(color);
|
||||
}
|
||||
// rgb
|
||||
3 => {
|
||||
let r = f32_from_stack!(state, -nargs);
|
||||
let g = f32_from_stack!(state, -nargs + 1);
|
||||
let b = f32_from_stack!(state, -nargs + 2);
|
||||
let color = Srgba::new_f32(r, g, b, 1.0);
|
||||
ctx.layers().set_draw_color(color);
|
||||
}
|
||||
// rgba
|
||||
4 => {
|
||||
let r = f32_from_stack!(state, -nargs);
|
||||
let g = f32_from_stack!(state, -nargs + 1);
|
||||
let b = f32_from_stack!(state, -nargs + 2);
|
||||
let a = f32_from_stack!(state, -nargs + 3);
|
||||
let color = Srgba::new_f32(r, g, b, a);
|
||||
ctx.layers().set_draw_color(color);
|
||||
}
|
||||
_ => panic!("Unexpected number of arguments"),
|
||||
};
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn get_draw_color(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("get_draw_color");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
|
||||
|
||||
let color: [f32; 4] = ctx.layers().get_draw_color().into();
|
||||
unsafe { ffi::lua_pushnumber(state, color[0] as f64) };
|
||||
unsafe { ffi::lua_pushnumber(state, color[1] as f64) };
|
||||
unsafe { ffi::lua_pushnumber(state, color[2] as f64) };
|
||||
unsafe { ffi::lua_pushnumber(state, color[3] as f64) };
|
||||
|
||||
4
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("set_viewport");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
match nargs {
|
||||
0 => ctx
|
||||
.layers()
|
||||
.set_viewport_from_size(ctx.window().logical_size()),
|
||||
4 => {
|
||||
let x = f32_from_stack!(state, -nargs);
|
||||
let y = f32_from_stack!(state, -nargs + 1);
|
||||
let w = f32_from_stack!(state, -nargs + 2);
|
||||
let h = f32_from_stack!(state, -nargs + 3);
|
||||
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
|
||||
ctx.layers().set_viewport(rect);
|
||||
}
|
||||
_ => panic!("Unexpected number of arguments"),
|
||||
};
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("set_draw_layer");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
match nargs {
|
||||
1 => {
|
||||
let layer = i32_from_stack!(state, -nargs);
|
||||
ctx.layers().set_draw_layer(layer, 0);
|
||||
}
|
||||
2 => {
|
||||
let layer = match unsafe { ffi::lua_type(state, -nargs) } {
|
||||
ffi::LUA_TNIL => None,
|
||||
ffi::LUA_TNUMBER => {
|
||||
let layer = i32_from_stack!(state, -nargs);
|
||||
Some(layer)
|
||||
}
|
||||
t => panic!("Expected Nil or Number, got {:?}", t),
|
||||
};
|
||||
let sublayer = i32_from_stack!(state, -nargs + 1);
|
||||
if let Some(layer) = layer {
|
||||
ctx.layers().set_draw_layer(layer, sublayer);
|
||||
} else {
|
||||
ctx.layers().set_draw_sublayer(sublayer);
|
||||
}
|
||||
}
|
||||
_ => panic!("Unexpected number of arguments"),
|
||||
};
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("draw_image");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
if !matches!(nargs, 5 | 6 | 7 | 9 | 10 | 11) {
|
||||
panic!("Unexpected number of arguments");
|
||||
}
|
||||
|
||||
#[allow(clippy::manual_range_patterns)]
|
||||
let parse_uv = matches!(nargs, 9 | 10 | 11);
|
||||
let parse_layer_idx = matches!(nargs, 6 | 7 | 10 | 11);
|
||||
|
||||
let texture_id = 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
|
||||
};
|
||||
|
||||
ctx.layers().draw_rect(texture_id, rect, uv, layer_idx);
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("draw_image_quad", format!("args: {:?}", args));
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
if !matches!(nargs, 9 | 10 | 11 | 17 | 18 | 19) {
|
||||
panic!("Unexpected number of arguments");
|
||||
}
|
||||
|
||||
#[allow(clippy::manual_range_patterns)]
|
||||
let parse_uv = matches!(nargs, 17 | 18 | 19);
|
||||
let parse_layer_idx = matches!(nargs, 10 | 11 | 18 | 19);
|
||||
|
||||
let texture_id = 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
|
||||
};
|
||||
|
||||
ctx.layers().draw_quad(texture_id, quad, uv, layer_idx);
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("draw_string");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
let x = f32_from_stack!(state, -nargs);
|
||||
let y = f32_from_stack!(state, -nargs + 1);
|
||||
let alignment = str_from_stack!(state, -nargs + 2);
|
||||
let line_height = i32_from_stack!(state, -nargs + 3);
|
||||
let font_type = str_from_stack!(state, -nargs + 4);
|
||||
let text = str_from_stack!(state, -nargs + 5);
|
||||
|
||||
let 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;
|
||||
// the position needs to be adjusted for some alignments to match PoBs behavior
|
||||
let screen_size = ctx.window().logical_size();
|
||||
let halign = match alignment {
|
||||
PoBTextAlignment::Left => Alignment::Min,
|
||||
PoBTextAlignment::Center => {
|
||||
position.x += screen_size.width as f32 / 2.0;
|
||||
is_absolute_position = true;
|
||||
Alignment::Center
|
||||
}
|
||||
PoBTextAlignment::Right => {
|
||||
position.x = screen_size.width as f32 - position.x;
|
||||
is_absolute_position = true;
|
||||
Alignment::Max
|
||||
}
|
||||
PoBTextAlignment::CenterX => Alignment::Center,
|
||||
PoBTextAlignment::RightX => Alignment::Max,
|
||||
};
|
||||
|
||||
let current_draw_color = ctx.layers().get_draw_color();
|
||||
let job = build_layout_job(
|
||||
text,
|
||||
current_draw_color,
|
||||
font_type,
|
||||
line_height,
|
||||
Some(halign),
|
||||
);
|
||||
|
||||
// NOTE: color escape codes modify the current draw color.
|
||||
// set current draw color to color of last segment to match PoB's behavior
|
||||
if let Some(last_segment) = job.segments.last() {
|
||||
ctx.layers().set_draw_color(last_segment.color);
|
||||
}
|
||||
|
||||
let layout = ctx.fonts().layout(job, ctx.window().scale_factor());
|
||||
ctx.layers()
|
||||
.draw_text(position, layout, is_absolute_position);
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("get_string_width");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua_instance.app_data_ref::<&'static Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
let line_height = i32_from_stack!(state, -nargs);
|
||||
let font_type = str_from_stack!(state, -nargs + 1);
|
||||
let text = str_from_stack!(state, -nargs + 2);
|
||||
|
||||
let 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 = ctx.fonts().get_text_width(job, ctx.window().scale_factor());
|
||||
|
||||
unsafe { ffi::lua_pushnumber(state, width as f64) };
|
||||
1
|
||||
}
|
||||
|
||||
fn get_index_at_cur(
|
||||
l: &Lua,
|
||||
(line_height, font_type, text, cur_x, cur_y): (i32, String, String, f32, f32),
|
||||
) -> LuaResult<usize> {
|
||||
//profiling::scope!("get_char_index_at_cur");
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
|
||||
let font_type = font_type.parse::<PoBFontType>()?;
|
||||
|
||||
let job = build_layout_job(&text, Srgba::WHITE, font_type, line_height, None);
|
||||
let index = ctx.fonts().get_text_index_at_cursor(
|
||||
job,
|
||||
Point::new(cur_x, cur_y),
|
||||
ctx.window().scale_factor(),
|
||||
);
|
||||
|
||||
// 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 mut font_style = FontStyle::default();
|
||||
let font_family = match font_type {
|
||||
PoBFontType::Fixed => FontFamily::Named(Cow::Borrowed("Bitstream Vera Sans Mono")),
|
||||
PoBFontType::Var => FontFamily::Named(Cow::Borrowed("Liberation Sans")),
|
||||
PoBFontType::VarBold => {
|
||||
font_weight = Some(700.0);
|
||||
FontFamily::Named(Cow::Borrowed("Liberation Sans"))
|
||||
}
|
||||
PoBFontType::Fontin => FontFamily::Named(Cow::Borrowed("Fontin")),
|
||||
PoBFontType::FontinItalic => FontFamily::Named(Cow::Borrowed("Fontin")),
|
||||
PoBFontType::FontinSmallcaps => FontFamily::Named(Cow::Borrowed("Fontin SmallCaps")),
|
||||
PoBFontType::FontinSmallcapsItalic => {
|
||||
font_style = FontStyle::Italic;
|
||||
// use regular Smallcaps with "faux italics"
|
||||
FontFamily::Named(Cow::Borrowed("Fontin SmallCaps"))
|
||||
}
|
||||
};
|
||||
|
||||
// NOTE: This is just an approximation and was chosen based on how it looks.
|
||||
//
|
||||
// PoB uses pre-rendered font atlases of discrete sizes and selects the appropriate
|
||||
// atlas based on the provided height. Rusty-PoB dynamically renders fonts to a
|
||||
// cached font atlas to support the selection of arbitrary sizes.
|
||||
//
|
||||
// TODO: font size in some dropdowns is too small, e.g. socket group selection in
|
||||
// 'Calcs' tab
|
||||
let font_size = (line_height - 2).max(1) as f32;
|
||||
|
||||
let mut job = LayoutJob::new(
|
||||
font_family,
|
||||
font_size,
|
||||
line_height as f32,
|
||||
alignment,
|
||||
font_weight,
|
||||
font_style,
|
||||
);
|
||||
|
||||
for (color, segment) in PoBString(text).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,
|
||||
FontinSmallcaps,
|
||||
FontinSmallcapsItalic,
|
||||
Fontin,
|
||||
FontinItalic,
|
||||
}
|
||||
|
||||
impl std::str::FromStr for PoBFontType {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"FIXED" => Ok(Self::Fixed),
|
||||
"VAR" => Ok(Self::Var),
|
||||
"VAR BOLD" => Ok(Self::VarBold),
|
||||
"FONTIN SC" => Ok(Self::FontinSmallcaps),
|
||||
"FONTIN SC ITALIC" => Ok(Self::FontinSmallcapsItalic),
|
||||
"FONTIN" => Ok(Self::Fontin),
|
||||
"FONTIN ITALIC" => Ok(Self::FontinItalic),
|
||||
_ => Err(anyhow::anyhow!(
|
||||
"'{}' 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
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
use crate::{
|
||||
dpi::{LogicalSize, PhysicalSize},
|
||||
lua::Context,
|
||||
};
|
||||
use mlua::{Lua, Result as LuaResult};
|
||||
|
||||
pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
let size = if *ctx.is_dpi_aware() {
|
||||
let PhysicalSize { width, height, .. } = ctx.window().size;
|
||||
(width, height)
|
||||
} else {
|
||||
let LogicalSize { width, height, .. } = ctx.window().logical_size();
|
||||
(width, height)
|
||||
};
|
||||
Ok(size)
|
||||
}
|
||||
|
||||
pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult<f32> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
let scale_factor = ctx.window().scale_factor();
|
||||
Ok(scale_factor)
|
||||
}
|
||||
|
||||
pub fn set_window_title(l: &Lua, title: String) -> LuaResult<()> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
ctx.window().set_window_title(&title);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_foreground(l: &Lua, _: ()) -> LuaResult<()> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
ctx.window().focus();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_dpi_scale_override(l: &Lua, percent: i32) -> LuaResult<()> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
match percent {
|
||||
0 => ctx.window().scale_factor_override = None,
|
||||
p if p > 0 => ctx.window().scale_factor_override = Some(p as f32 / 100.0),
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_dpi_scale_override(l: &Lua, _: ()) -> LuaResult<i32> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
match ctx.window().scale_factor_override {
|
||||
Some(scale_factor) => Ok((scale_factor * 100.0) as i32),
|
||||
None => Ok(0),
|
||||
}
|
||||
}
|
||||
+140
-180
@@ -1,52 +1,38 @@
|
||||
use crate::{
|
||||
args::Game,
|
||||
dpi::{ConvertToLogical, PhysicalPoint, PhysicalSize},
|
||||
batcher::build_render_job,
|
||||
dpi::{PhysicalPoint, PhysicalSize},
|
||||
fonts::{FontData, FontDefinitions, Fonts},
|
||||
gfx::{GraphicsContext, RenderJob},
|
||||
input::InputState,
|
||||
installer::InstallMode,
|
||||
mode::{AppEvent, AppMode, ModeTransition},
|
||||
pob::PoBMode,
|
||||
renderer::{tessellator::Tessellator, textures::WrappedTextureManager},
|
||||
window::WindowState,
|
||||
gfx::GraphicsContext,
|
||||
installer::Installer,
|
||||
pob::PathOfBuilding,
|
||||
renderer::{RenderJob, textures::TextureManager},
|
||||
stage::{ActiveStage, StageEvent, StageTransition},
|
||||
};
|
||||
use anyhow::Result;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::{cell::RefCell, path::PathBuf, rc::Rc};
|
||||
use winit::{
|
||||
application::ApplicationHandler, event::*, event_loop::ActiveEventLoop,
|
||||
platform::modifier_supplement::KeyEventExtModifierSupplement, window::Window,
|
||||
application::ApplicationHandler,
|
||||
event::{ElementState, MouseScrollDelta, WindowEvent},
|
||||
event_loop::ActiveEventLoop,
|
||||
platform::modifier_supplement::KeyEventExtModifierSupplement,
|
||||
window::Window,
|
||||
};
|
||||
|
||||
struct FrameOutput {
|
||||
pub render_job: RenderJob,
|
||||
pub should_continue: bool,
|
||||
}
|
||||
|
||||
pub struct AppState {
|
||||
pub window: WindowState,
|
||||
pub input: InputState,
|
||||
pub fonts: Fonts,
|
||||
pub texture_manager: WrappedTextureManager,
|
||||
pub script_dir: PathBuf,
|
||||
pub should_exit: bool,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
fn set_mouse_pos(&mut self, pos: PhysicalPoint<f32>) {
|
||||
self.input
|
||||
.set_mouse_pos(pos.to_logical(self.window.scale_factor()));
|
||||
}
|
||||
pub render_job: Option<RenderJob>,
|
||||
pub request_redraw: bool,
|
||||
}
|
||||
|
||||
pub struct App {
|
||||
gfx_context: Option<GraphicsContext>,
|
||||
state: AppState,
|
||||
fonts: Rc<RefCell<Fonts>>,
|
||||
texture_manager: Rc<RefCell<TextureManager>>,
|
||||
stage: ActiveStage,
|
||||
game: Game,
|
||||
tessellator: Tessellator,
|
||||
script_dir: PathBuf,
|
||||
needs_reconfigure: bool,
|
||||
force_render: bool,
|
||||
current_mode: AppMode,
|
||||
}
|
||||
|
||||
impl App {
|
||||
@@ -54,88 +40,83 @@ impl App {
|
||||
let uses_custom_script_dir = custom_script_dir.is_some();
|
||||
let script_dir = custom_script_dir.unwrap_or_else(|| game.script_dir());
|
||||
|
||||
let mut state = AppState {
|
||||
window: WindowState::default(),
|
||||
input: InputState::default(),
|
||||
fonts: Fonts::new(pob_font_definitions()),
|
||||
texture_manager: WrappedTextureManager::new(),
|
||||
script_dir,
|
||||
should_exit: false,
|
||||
};
|
||||
let fonts = Rc::new(RefCell::new(Fonts::new(pob_font_definitions())));
|
||||
let texture_manager = Rc::new(RefCell::new(TextureManager::new()));
|
||||
|
||||
let current_mode = if uses_custom_script_dir {
|
||||
// Skip installer if custom script dir is provided.
|
||||
// Used for local testing
|
||||
let pob_mode = PoBMode::new(&mut state)?;
|
||||
AppMode::PoB(pob_mode)
|
||||
let stage = if uses_custom_script_dir {
|
||||
// skip installer if custom script dir is provided. used for local testing.
|
||||
let pob =
|
||||
PathOfBuilding::new(&script_dir, Rc::clone(&fonts), Rc::clone(&texture_manager))?;
|
||||
ActiveStage::Main(pob)
|
||||
} else {
|
||||
AppMode::Install(InstallMode::new(game))
|
||||
ActiveStage::Startup(Installer::new(game, Rc::clone(&fonts)))
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
gfx_context: None,
|
||||
state,
|
||||
fonts,
|
||||
texture_manager,
|
||||
stage,
|
||||
game,
|
||||
tessellator: Tessellator::default(),
|
||||
script_dir,
|
||||
needs_reconfigure: true,
|
||||
force_render: true,
|
||||
current_mode,
|
||||
})
|
||||
}
|
||||
|
||||
fn update(&mut self) -> anyhow::Result<()> {
|
||||
let transition = self.current_mode.update(&mut self.state)?;
|
||||
if let Some(transition) = transition {
|
||||
self.current_mode = match transition {
|
||||
ModeTransition::PoB => {
|
||||
let pob_mode = PoBMode::new(&mut self.state)?;
|
||||
AppMode::PoB(pob_mode)
|
||||
fn update(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> {
|
||||
let transition = self.stage.update();
|
||||
if let Some(transition) = transition? {
|
||||
match transition {
|
||||
StageTransition::ToMain => {
|
||||
self.stage = ActiveStage::Main(PathOfBuilding::new(
|
||||
&self.script_dir,
|
||||
Rc::clone(&self.fonts),
|
||||
Rc::clone(&self.texture_manager),
|
||||
)?);
|
||||
if let Some(gfx) = &self.gfx_context {
|
||||
self.stage.set_window(Arc::clone(&gfx.window));
|
||||
}
|
||||
}
|
||||
};
|
||||
StageTransition::ToShutdown => {
|
||||
self.handle_event(StageEvent::Exit);
|
||||
event_loop.exit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn frame(&mut self) -> anyhow::Result<FrameOutput> {
|
||||
self.state.fonts.begin_frame();
|
||||
fn frame(&mut self, inhibit_elision: bool) -> anyhow::Result<FrameOutput> {
|
||||
self.fonts.borrow_mut().begin_frame();
|
||||
|
||||
let mode_output = self.current_mode.frame(&mut self.state)?;
|
||||
let stage_output = self.stage.frame()?;
|
||||
|
||||
let font_atlas_size = self.state.fonts.font_atlas().size();
|
||||
let font_image_delta = self.fonts.borrow_mut().font_atlas_delta();
|
||||
self.texture_manager
|
||||
.borrow()
|
||||
.update_font_texture(font_image_delta);
|
||||
|
||||
if let Some(font_image_delta) = self.state.fonts.font_atlas_delta() {
|
||||
self.state
|
||||
.texture_manager
|
||||
.update_font_texture(font_image_delta);
|
||||
}
|
||||
let textures_delta = self.texture_manager.borrow().take_delta();
|
||||
|
||||
let textures_delta = self.state.texture_manager.take_delta();
|
||||
|
||||
let render_job = if mode_output.can_elide && textures_delta.is_empty() && !self.force_render
|
||||
let render_job = if stage_output.can_elide && textures_delta.is_empty() && !inhibit_elision
|
||||
{
|
||||
RenderJob::Skip
|
||||
None
|
||||
} else {
|
||||
let meshes = self.tessellator.convert_clipped_primitives(
|
||||
mode_output.primitives,
|
||||
font_atlas_size,
|
||||
self.state.window.scale_factor(),
|
||||
);
|
||||
|
||||
RenderJob::Render {
|
||||
meshes,
|
||||
Some(build_render_job(
|
||||
&stage_output.draw_commands,
|
||||
textures_delta,
|
||||
}
|
||||
stage_output.scale_factor,
|
||||
))
|
||||
};
|
||||
|
||||
Ok(FrameOutput {
|
||||
render_job,
|
||||
should_continue: mode_output.should_continue,
|
||||
request_redraw: stage_output.request_redraw,
|
||||
})
|
||||
}
|
||||
|
||||
fn handle_event(&mut self, event: AppEvent) {
|
||||
if let Err(err) = self.current_mode.handle_event(&mut self.state, event) {
|
||||
fn handle_event(&mut self, event: StageEvent) {
|
||||
if let Err(err) = self.stage.handle_event(event) {
|
||||
log::error!("{err}");
|
||||
}
|
||||
}
|
||||
@@ -167,11 +148,17 @@ impl App {
|
||||
|
||||
let window = event_loop.create_window(window_attributes)?;
|
||||
let window = Arc::new(window);
|
||||
self.state.window.set_window(Arc::clone(&window));
|
||||
self.stage.set_window(Arc::clone(&window));
|
||||
self.gfx_context = Some(pollster::block_on(GraphicsContext::new(window))?);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn request_redraw(&self) {
|
||||
if let Some(gfx) = &self.gfx_context {
|
||||
gfx.window.request_redraw();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler<GraphicsContext> for App {
|
||||
@@ -190,150 +177,130 @@ impl ApplicationHandler<GraphicsContext> for App {
|
||||
) {
|
||||
match event {
|
||||
WindowEvent::CloseRequested => {
|
||||
self.state.should_exit = self.current_mode.can_exit(&mut self.state);
|
||||
if !self.state.should_exit {
|
||||
self.state.window.request_redraw();
|
||||
if self.stage.can_exit() {
|
||||
self.handle_event(StageEvent::Exit);
|
||||
event_loop.exit();
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
profiling::scope!("RedrawRequested");
|
||||
|
||||
if let Err(err) = self.update() {
|
||||
if let Err(err) = self.update(event_loop) {
|
||||
log::error!("{err}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
|
||||
if self.state.should_exit {
|
||||
self.handle_event(AppEvent::Exit);
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
|
||||
let mut inhibit_elision = false;
|
||||
if self.needs_reconfigure {
|
||||
if let Some(ref mut gfx) = self.gfx_context {
|
||||
let size = gfx.window.inner_size();
|
||||
gfx.resize(size.width, size.height);
|
||||
// resizing recreates the blip texture (previous frame) thus elision needs to
|
||||
// be inhibited for at least one frame.
|
||||
inhibit_elision = true;
|
||||
}
|
||||
self.needs_reconfigure = false;
|
||||
// Render at least one frame after reconfigure
|
||||
self.force_render = true;
|
||||
}
|
||||
|
||||
let is_focused = self.state.window.is_focused;
|
||||
let is_hovered = self.state.window.is_hovered;
|
||||
let should_render = is_focused || is_hovered || self.force_render;
|
||||
let FrameOutput {
|
||||
render_job,
|
||||
request_redraw,
|
||||
} = match self.frame(inhibit_elision) {
|
||||
Ok(frame_output) => frame_output,
|
||||
Err(err) => {
|
||||
log::error!("{err}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if should_render {
|
||||
let FrameOutput {
|
||||
render_job,
|
||||
should_continue,
|
||||
} = match self.frame() {
|
||||
Ok(frame_output) => frame_output,
|
||||
if let Some(ref mut gfx) = self.gfx_context {
|
||||
match gfx.render(render_job) {
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
log::error!("{err}");
|
||||
event_loop.exit();
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(ref mut gfx) = self.gfx_context {
|
||||
match gfx.render(render_job, self.state.window.scale_factor()) {
|
||||
Ok(_) => {
|
||||
self.force_render = should_continue;
|
||||
|
||||
if is_focused || is_hovered || should_continue {
|
||||
self.state.window.request_redraw();
|
||||
}
|
||||
}
|
||||
// Reconfigure the surface if it's lost or outdated
|
||||
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
|
||||
self.needs_reconfigure = true;
|
||||
self.state.window.request_redraw();
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Unable to render: {err}");
|
||||
}
|
||||
log::error!("Unable to render: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if request_redraw {
|
||||
self.request_redraw();
|
||||
}
|
||||
|
||||
profiling::finish_frame!();
|
||||
}
|
||||
WindowEvent::Resized(size) => {
|
||||
self.state.window.size = PhysicalSize::new(size.width, size.height);
|
||||
self.needs_reconfigure = true;
|
||||
self.handle_event(StageEvent::Resized(PhysicalSize::new(
|
||||
size.width,
|
||||
size.height,
|
||||
)));
|
||||
self.request_redraw();
|
||||
}
|
||||
WindowEvent::Focused(focused) => {
|
||||
self.state.window.is_focused = focused;
|
||||
self.handle_event(StageEvent::FocusChanged(focused));
|
||||
if focused {
|
||||
self.state.window.request_redraw();
|
||||
self.request_redraw();
|
||||
} else {
|
||||
// Clear inputs on lost focus to avoid "stuck" keys on Wayland
|
||||
// systems.
|
||||
self.state.input.clear_pressed();
|
||||
// Clear inputs on lost focus to avoid "stuck" keys on Wayland systems.
|
||||
self.stage.clear_pressed();
|
||||
}
|
||||
}
|
||||
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
|
||||
self.state.window.set_scale_factor(scale_factor as f32);
|
||||
self.handle_event(StageEvent::ScaleFactorChanged(scale_factor));
|
||||
self.request_redraw();
|
||||
}
|
||||
WindowEvent::KeyboardInput { event, .. } => {
|
||||
let state = event.state;
|
||||
|
||||
// update input state
|
||||
self.state
|
||||
.input
|
||||
.set_key_pressed(event.logical_key.clone(), state.is_pressed());
|
||||
|
||||
// forward KeyUp/KeyDown events
|
||||
let app_event = match state {
|
||||
ElementState::Pressed => AppEvent::KeyDown {
|
||||
let stage_event = match state {
|
||||
ElementState::Pressed => StageEvent::KeyDown {
|
||||
key: event.logical_key.clone(),
|
||||
},
|
||||
ElementState::Released => AppEvent::KeyUp {
|
||||
ElementState::Released => StageEvent::KeyUp {
|
||||
key: event.logical_key.clone(),
|
||||
},
|
||||
};
|
||||
self.handle_event(app_event);
|
||||
self.handle_event(stage_event);
|
||||
|
||||
// handle text input
|
||||
if let Some(text) = event.text_with_all_modifiers()
|
||||
&& state.is_pressed()
|
||||
{
|
||||
for ch in text.chars() {
|
||||
let event = AppEvent::CharacterInput { ch };
|
||||
let event = StageEvent::CharacterInput { ch };
|
||||
self.handle_event(event);
|
||||
}
|
||||
}
|
||||
self.request_redraw();
|
||||
}
|
||||
WindowEvent::ModifiersChanged(modifiers) => {
|
||||
self.state.input.key_modifiers = modifiers.state();
|
||||
self.handle_event(StageEvent::ModifiersChanged {
|
||||
state: modifiers.state(),
|
||||
});
|
||||
self.request_redraw();
|
||||
}
|
||||
WindowEvent::MouseInput { state, button, .. } => {
|
||||
let is_double_click = self
|
||||
.state
|
||||
.input
|
||||
.set_mouse_pressed(button, state.is_pressed());
|
||||
|
||||
let event = match state {
|
||||
ElementState::Pressed => AppEvent::MouseDown {
|
||||
button,
|
||||
is_double_click,
|
||||
},
|
||||
ElementState::Released => AppEvent::MouseUp { button },
|
||||
ElementState::Pressed => StageEvent::MouseDown { button },
|
||||
ElementState::Released => StageEvent::MouseUp { button },
|
||||
};
|
||||
self.handle_event(event);
|
||||
self.request_redraw();
|
||||
}
|
||||
WindowEvent::CursorMoved { position, .. } => {
|
||||
let pos = PhysicalPoint::new(position.x as f32, position.y as f32);
|
||||
self.state.set_mouse_pos(pos);
|
||||
self.handle_event(StageEvent::MouseMoved { pos });
|
||||
self.request_redraw();
|
||||
}
|
||||
WindowEvent::CursorEntered { .. } => {
|
||||
self.state.window.is_hovered = true;
|
||||
self.state.window.request_redraw();
|
||||
self.handle_event(StageEvent::HoverChanged(true));
|
||||
self.request_redraw();
|
||||
}
|
||||
WindowEvent::CursorLeft { .. } => {
|
||||
self.state.window.is_hovered = false;
|
||||
self.handle_event(StageEvent::HoverChanged(false));
|
||||
}
|
||||
WindowEvent::MouseWheel { delta, .. } => {
|
||||
let delta = match delta {
|
||||
@@ -342,8 +309,8 @@ impl ApplicationHandler<GraphicsContext> for App {
|
||||
y as f32
|
||||
}
|
||||
};
|
||||
let event = AppEvent::MouseWheel { delta };
|
||||
self.handle_event(event);
|
||||
self.handle_event(StageEvent::MouseWheel { delta });
|
||||
self.request_redraw();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -356,60 +323,53 @@ fn pob_font_definitions() -> FontDefinitions {
|
||||
definitions.font_data.insert(
|
||||
"bitstream-vera-sans-mono".to_owned(),
|
||||
Arc::new(FontData::from_static(include_bytes!(
|
||||
"../fonts/VeraMono.ttf"
|
||||
"../assets/fonts/VeraMono.ttf"
|
||||
))),
|
||||
);
|
||||
definitions.font_data.insert(
|
||||
"liberation-sans".to_owned(),
|
||||
Arc::new(FontData::from_static(include_bytes!(
|
||||
"../fonts/LiberationSans-Regular.ttf"
|
||||
"../assets/fonts/LiberationSans-Regular.ttf"
|
||||
))),
|
||||
);
|
||||
definitions.font_data.insert(
|
||||
"liberation-sans-bold".to_owned(),
|
||||
Arc::new(FontData::from_static(include_bytes!(
|
||||
"../fonts/LiberationSans-Bold.ttf"
|
||||
"../assets/fonts/LiberationSans-Bold.ttf"
|
||||
))),
|
||||
);
|
||||
definitions.font_data.insert(
|
||||
"fontin-regular".to_owned(),
|
||||
Arc::new(FontData::from_static(include_bytes!(
|
||||
"../fonts/fontin-regular.ttf"
|
||||
"../assets/fonts/fontin-regular.ttf"
|
||||
))),
|
||||
);
|
||||
definitions.font_data.insert(
|
||||
"fontin-italic".to_owned(),
|
||||
Arc::new(FontData::from_static(include_bytes!(
|
||||
"../fonts/fontin-italic.ttf"
|
||||
"../assets/fonts/fontin-italic.ttf"
|
||||
))),
|
||||
);
|
||||
definitions.font_data.insert(
|
||||
"fontin-smallcaps".to_owned(),
|
||||
Arc::new(FontData::from_static(include_bytes!(
|
||||
"../fonts/fontin-smallcaps.ttf"
|
||||
"../assets/fonts/fontin-smallcaps.ttf"
|
||||
))),
|
||||
);
|
||||
|
||||
definitions.generic_families.insert(
|
||||
parley::GenericFamily::Monospace,
|
||||
vec!["bitstream-vera-sans-mono".to_owned()],
|
||||
vec!["Bitstream Vera Sans Mono".to_owned()],
|
||||
);
|
||||
|
||||
definitions.generic_families.insert(
|
||||
parley::GenericFamily::SansSerif,
|
||||
vec![
|
||||
"liberation-sans".to_owned(),
|
||||
"liberation-sans-bold".to_owned(),
|
||||
],
|
||||
vec!["Liberation Sans".to_owned()],
|
||||
);
|
||||
|
||||
definitions.generic_families.insert(
|
||||
parley::GenericFamily::Serif,
|
||||
vec![
|
||||
"fontin-regular".to_owned(),
|
||||
"fontin-italic".to_owned(),
|
||||
"fontin-smallcaps".to_owned(),
|
||||
],
|
||||
vec!["Fontin".to_owned(), "Fontin SmallCaps".to_owned()],
|
||||
);
|
||||
|
||||
definitions
|
||||
|
||||
+7
-12
@@ -1,14 +1,9 @@
|
||||
//! `args` is used to parse the arguments passed to the program on launch.
|
||||
//!
|
||||
//! Normally these are the arguments passed after the `rusty-path-of-building`
|
||||
//! command from a CLI.
|
||||
|
||||
use clap::Parser;
|
||||
use clap::ValueEnum;
|
||||
use directories::BaseDirs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// CLI arguments passed to the application on launch.
|
||||
/// CLI arguments passed to the application.
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(version, about, long_about = None)]
|
||||
pub struct Args {
|
||||
@@ -23,7 +18,7 @@ pub struct Args {
|
||||
pub import_url: Option<String>,
|
||||
}
|
||||
|
||||
/// Enum representing which game (PoE1 or PoE2) the application needs to launch.
|
||||
/// Enum representing the game version.
|
||||
#[derive(Debug, Clone, Copy, ValueEnum)]
|
||||
pub enum Game {
|
||||
/// Path of Exile 1
|
||||
@@ -35,17 +30,17 @@ pub enum Game {
|
||||
}
|
||||
|
||||
impl Game {
|
||||
/// Returns the path to the user’s data directory based on which `Game` option
|
||||
/// was used to start the application.
|
||||
/// Returns the path to the user’s data directory based on which `Game` option was used to
|
||||
/// start the application.
|
||||
pub fn data_dir(&self) -> PathBuf {
|
||||
let directory_name = match self {
|
||||
Game::Poe1 => "RustyPathOfBuilding1",
|
||||
Game::Poe2 => "RustyPathOfBuilding2",
|
||||
Self::Poe1 => "RustyPathOfBuilding1",
|
||||
Self::Poe2 => "RustyPathOfBuilding2",
|
||||
};
|
||||
BaseDirs::new().unwrap().data_dir().join(directory_name)
|
||||
}
|
||||
|
||||
/// Returns the path to the user's data directory. Calls [`Self::data_dir`].
|
||||
/// Returns the path to the user's data directory.
|
||||
pub fn script_dir(&self) -> PathBuf {
|
||||
self.data_dir()
|
||||
}
|
||||
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
use std::num::NonZeroU32;
|
||||
|
||||
use ahash::HashMap;
|
||||
|
||||
use crate::{
|
||||
dpi::{LogicalRect, ScaleFactor},
|
||||
draw_commands::DrawCommand,
|
||||
renderer::{
|
||||
BATCH_TEX_SLOTS, Batch, RenderJob, Vertex,
|
||||
textures::{TextureId, TexturesDelta},
|
||||
},
|
||||
};
|
||||
|
||||
struct BatchBuilder {
|
||||
textures: Vec<TextureId>,
|
||||
// maps TextureId to index into textures array
|
||||
texture_mapping: HashMap<TextureId, u32>,
|
||||
clip_rect: LogicalRect<f32>,
|
||||
// index into batch's indecies array
|
||||
start_index: u32,
|
||||
}
|
||||
|
||||
impl BatchBuilder {
|
||||
fn new(clip_rect: LogicalRect<f32>, start_index: u32) -> Self {
|
||||
// seed slot 0 with font atlas.
|
||||
// the font atlas texture is used for solid color and text
|
||||
// rendering so it needs to be present in almost every batch.
|
||||
let textures = vec![TextureId::default()];
|
||||
let texture_mapping = HashMap::from_iter([(TextureId::default(), 0)]);
|
||||
Self {
|
||||
textures,
|
||||
texture_mapping,
|
||||
clip_rect,
|
||||
start_index,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tries to assign a texture to the batch.
|
||||
///
|
||||
/// Returns `slot_index` into textures array if texture can be assigned.
|
||||
/// Returns `None` if maximum amount of texture slots is reached.
|
||||
fn try_assign(&mut self, id: TextureId, max_slots: NonZeroU32) -> Option<u32> {
|
||||
if let Some(&slot) = self.texture_mapping.get(&id) {
|
||||
return Some(slot);
|
||||
}
|
||||
|
||||
if self.textures.len() as u32 >= max_slots.get() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let slot = self.textures.len() as u32;
|
||||
self.textures.push(id);
|
||||
self.texture_mapping.insert(id, slot);
|
||||
Some(slot)
|
||||
}
|
||||
|
||||
fn finish(self, end_index: u32) -> Option<Batch> {
|
||||
if self.start_index < end_index {
|
||||
Some(Batch {
|
||||
clip_rect: self.clip_rect,
|
||||
textures: self.textures,
|
||||
index_range: self.start_index..end_index,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_render_job(
|
||||
commands: &[DrawCommand],
|
||||
textures_delta: TexturesDelta,
|
||||
scale_factor: ScaleFactor<f32>,
|
||||
) -> RenderJob {
|
||||
profiling::scope!("build_render_job");
|
||||
|
||||
let max_slots = BATCH_TEX_SLOTS;
|
||||
|
||||
let mut vertices = Vec::with_capacity(commands.len() * 4);
|
||||
let mut indices = Vec::with_capacity(commands.len() * 6);
|
||||
let mut batches = Vec::new();
|
||||
|
||||
let Some(first_cmd) = commands.first() else {
|
||||
// no draw commands, only texture updates
|
||||
return RenderJob {
|
||||
vertices,
|
||||
indices,
|
||||
batches,
|
||||
textures_delta,
|
||||
scale_factor,
|
||||
};
|
||||
};
|
||||
|
||||
let mut builder = BatchBuilder::new(first_cmd.clip_rect, 0);
|
||||
|
||||
for cmd in commands {
|
||||
// start new batch if clip_rects don't match
|
||||
if cmd.clip_rect != builder.clip_rect {
|
||||
let next_builder = BatchBuilder::new(cmd.clip_rect, indices.len() as u32);
|
||||
if let Some(batch) =
|
||||
std::mem::replace(&mut builder, next_builder).finish(indices.len() as u32)
|
||||
{
|
||||
batches.push(batch);
|
||||
}
|
||||
}
|
||||
|
||||
let slot = builder
|
||||
.try_assign(cmd.texture_id, max_slots)
|
||||
.unwrap_or_else(|| {
|
||||
let next_builder = BatchBuilder::new(cmd.clip_rect, indices.len() as u32);
|
||||
if let Some(batch) =
|
||||
std::mem::replace(&mut builder, next_builder).finish(indices.len() as u32)
|
||||
{
|
||||
batches.push(batch);
|
||||
}
|
||||
|
||||
builder
|
||||
.try_assign(cmd.texture_id, max_slots)
|
||||
.expect("new batch always has enough space")
|
||||
});
|
||||
|
||||
let i = vertices.len() as u32;
|
||||
|
||||
indices.extend_from_slice(&[i, i + 1, i + 3, i + 1, i + 2, i + 3]);
|
||||
|
||||
vertices.extend_from_slice(&[
|
||||
Vertex {
|
||||
pos: cmd.positions.p0,
|
||||
uv: cmd.uvs.p0,
|
||||
color: cmd.color,
|
||||
texture_slot: slot,
|
||||
layer_idx: cmd.texture_layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: cmd.positions.p1,
|
||||
uv: cmd.uvs.p1,
|
||||
color: cmd.color,
|
||||
texture_slot: slot,
|
||||
layer_idx: cmd.texture_layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: cmd.positions.p2,
|
||||
uv: cmd.uvs.p2,
|
||||
color: cmd.color,
|
||||
texture_slot: slot,
|
||||
layer_idx: cmd.texture_layer_idx,
|
||||
},
|
||||
Vertex {
|
||||
pos: cmd.positions.p3,
|
||||
uv: cmd.uvs.p3,
|
||||
color: cmd.color,
|
||||
texture_slot: slot,
|
||||
layer_idx: cmd.texture_layer_idx,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
if let Some(batch) = builder.finish(indices.len() as u32) {
|
||||
batches.push(batch);
|
||||
}
|
||||
|
||||
RenderJob {
|
||||
vertices,
|
||||
indices,
|
||||
batches,
|
||||
textures_delta,
|
||||
scale_factor,
|
||||
}
|
||||
}
|
||||
+5
-5
@@ -5,7 +5,7 @@ use raw_window_handle::RawDisplayHandle;
|
||||
/// `smithay_clipboard`: Used on wayland
|
||||
/// `arboard`: All other platforms (check arboard docs for platform support)
|
||||
pub struct Clipboard {
|
||||
#[cfg(target_family = "unix")]
|
||||
#[cfg(target_os = "linux")]
|
||||
smithay: Option<smithay_clipboard::Clipboard>,
|
||||
arboard: Option<arboard::Clipboard>,
|
||||
// fallback if everything else fails. only supports intra-application copy/paste
|
||||
@@ -15,7 +15,7 @@ pub struct Clipboard {
|
||||
impl Clipboard {
|
||||
pub fn new(_raw_display_handle: Option<RawDisplayHandle>) -> Self {
|
||||
Self {
|
||||
#[cfg(target_family = "unix")]
|
||||
#[cfg(target_os = "linux")]
|
||||
smithay: create_smithay_clipboard(_raw_display_handle),
|
||||
arboard: create_arboard_clipboard(),
|
||||
fallback: None,
|
||||
@@ -24,7 +24,7 @@ impl Clipboard {
|
||||
|
||||
/// Sets the text content of clipboard
|
||||
pub fn set_text(&mut self, text: String) {
|
||||
#[cfg(target_family = "unix")]
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Some(clipboard) = &mut self.smithay {
|
||||
clipboard.store(text);
|
||||
return;
|
||||
@@ -40,7 +40,7 @@ impl Clipboard {
|
||||
|
||||
/// Gets the text content of clipboard
|
||||
pub fn get_text(&mut self) -> Option<String> {
|
||||
#[cfg(target_family = "unix")]
|
||||
#[cfg(target_os = "linux")]
|
||||
if let Some(clipboard) = &mut self.smithay {
|
||||
return clipboard.load().ok();
|
||||
}
|
||||
@@ -57,7 +57,7 @@ impl Clipboard {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_family = "unix")]
|
||||
#[cfg(target_os = "linux")]
|
||||
fn create_smithay_clipboard(
|
||||
raw_display_handle: Option<RawDisplayHandle>,
|
||||
) -> Option<smithay_clipboard::Clipboard> {
|
||||
|
||||
+2
-170
@@ -1,10 +1,7 @@
|
||||
use crate::math::{Point, Quad, Rect, Size, Vector};
|
||||
use core::f32;
|
||||
use num_traits::{Float, NumCast, ToPrimitive};
|
||||
use crate::math::{Point, Quad, Rect, Scale, Size, Vector};
|
||||
|
||||
pub struct LogicalScreenSpace;
|
||||
pub struct PhysicalScreenSpace;
|
||||
pub struct Normalized;
|
||||
|
||||
pub type LogicalPoint<T> = Point<T, LogicalScreenSpace>;
|
||||
pub type LogicalVector<T> = Vector<T, LogicalScreenSpace>;
|
||||
@@ -17,169 +14,4 @@ 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()
|
||||
}
|
||||
}
|
||||
pub type ScaleFactor<F> = Scale<F, LogicalScreenSpace, PhysicalScreenSpace>;
|
||||
@@ -0,0 +1,179 @@
|
||||
use std::{collections::BTreeMap, hash::Hasher};
|
||||
|
||||
use ahash::AHasher;
|
||||
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::{LogicalQuad, LogicalRect, LogicalSize},
|
||||
math::Size,
|
||||
renderer::textures::TextureId,
|
||||
uv::{UvConstructors, UvQuad, UvRect},
|
||||
};
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct DrawCommand {
|
||||
pub positions: LogicalQuad<f32>,
|
||||
pub uvs: UvQuad,
|
||||
pub texture_id: TextureId,
|
||||
pub clip_rect: LogicalRect<f32>,
|
||||
pub texture_layer_idx: u32,
|
||||
pub color: Srgba,
|
||||
}
|
||||
|
||||
impl DrawCommand {
|
||||
#[inline(always)]
|
||||
fn hash_into<H: Hasher>(&self, state: &mut H) {
|
||||
state.write(bytemuck::bytes_of(self));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct DrawCommandRecorder {
|
||||
layers: BTreeMap<(i32, i32), Vec<DrawCommand>>,
|
||||
current_layer: (i32, i32),
|
||||
current_viewport: LogicalRect<f32>,
|
||||
current_draw_color: Srgba,
|
||||
hasher: AHasher,
|
||||
}
|
||||
|
||||
impl DrawCommandRecorder {
|
||||
fn push(&mut self, cmd: DrawCommand) {
|
||||
cmd.hash_into(&mut self.hasher);
|
||||
self.layers.entry(self.current_layer).or_default().push(cmd);
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
for layer in self.layers.values_mut() {
|
||||
layer.clear();
|
||||
}
|
||||
self.current_layer = (0, 0);
|
||||
self.current_viewport = LogicalRect::from_size(Size::new(f32::INFINITY, f32::INFINITY));
|
||||
self.current_draw_color = Srgba::WHITE;
|
||||
self.hasher = AHasher::default();
|
||||
}
|
||||
|
||||
pub fn set_viewport(&mut self, viewport: LogicalRect<f32>) {
|
||||
self.current_viewport = viewport;
|
||||
}
|
||||
|
||||
pub fn set_viewport_from_size(&mut self, size: LogicalSize<f32>) {
|
||||
self.set_viewport(LogicalRect::from_size(size));
|
||||
}
|
||||
|
||||
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 get_draw_layer(&self) -> (i32, i32) {
|
||||
self.current_layer
|
||||
}
|
||||
|
||||
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_image(
|
||||
&mut self,
|
||||
rect: LogicalRect<f32>,
|
||||
texture_id: Option<TextureId>,
|
||||
uv: Option<UvRect>,
|
||||
layer_idx: u32,
|
||||
) {
|
||||
let (texture_id, uvs, texture_layer_idx) = match texture_id {
|
||||
Some(texture_id) => (
|
||||
texture_id,
|
||||
uv.map_or_else(UvQuad::full_uv, |uv_rect| uv_rect.into()),
|
||||
layer_idx,
|
||||
),
|
||||
None => (TextureId::default(), UvQuad::white_uv(), 0),
|
||||
};
|
||||
|
||||
let positions = rect.translate(self.current_viewport.min.to_vector());
|
||||
|
||||
// cull if outside of viewport
|
||||
if !positions.intersects(&self.current_viewport) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.push(DrawCommand {
|
||||
positions: positions.into(),
|
||||
uvs,
|
||||
color: self.current_draw_color,
|
||||
texture_id,
|
||||
texture_layer_idx,
|
||||
clip_rect: self.current_viewport,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn draw_image_quad(
|
||||
&mut self,
|
||||
quad: LogicalQuad<f32>,
|
||||
texture_id: Option<TextureId>,
|
||||
uv: Option<UvQuad>,
|
||||
layer_idx: u32,
|
||||
) {
|
||||
let (texture_id, uvs, texture_layer_idx) = match texture_id {
|
||||
Some(texture_id) => (texture_id, uv.unwrap_or_else(UvQuad::full_uv), layer_idx),
|
||||
None => (TextureId::default(), UvQuad::white_uv(), 0),
|
||||
};
|
||||
|
||||
let positions = quad.translate(self.current_viewport.min.to_vector());
|
||||
|
||||
// cull if outside of viewport
|
||||
if !positions.aabb_intersects_rect(&self.current_viewport) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.push(DrawCommand {
|
||||
positions,
|
||||
uvs,
|
||||
color: self.current_draw_color,
|
||||
texture_id,
|
||||
texture_layer_idx,
|
||||
clip_rect: self.current_viewport,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn draw_glyph(
|
||||
&mut self,
|
||||
rect: LogicalRect<f32>,
|
||||
uv: UvRect,
|
||||
color: Srgba,
|
||||
layer_idx: u32,
|
||||
is_absolute_position: bool,
|
||||
) {
|
||||
let positions = if is_absolute_position {
|
||||
rect
|
||||
} else {
|
||||
rect.translate(self.current_viewport.min.to_vector())
|
||||
};
|
||||
|
||||
// cull if outside of viewport
|
||||
if !positions.intersects(&self.current_viewport) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.push(DrawCommand {
|
||||
positions: positions.into(),
|
||||
uvs: uv.into(),
|
||||
color,
|
||||
// font atlas always lives at default texture ID
|
||||
texture_id: TextureId::default(),
|
||||
texture_layer_idx: layer_idx,
|
||||
clip_rect: self.current_viewport,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn finish(&self) -> (u64, &BTreeMap<(i32, i32), Vec<DrawCommand>>) {
|
||||
(self.hasher.finish(), &self.layers)
|
||||
}
|
||||
}
|
||||
+97
-174
@@ -1,8 +1,9 @@
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::{LogicalPoint, LogicalVector},
|
||||
dpi::{PhysicalVector, ScaleFactor},
|
||||
fonts::{
|
||||
atlas::FontAtlas, glyph_key::SubpixelBin, layout::LayoutRow, rasterizer::GlyphRasterizer,
|
||||
atlas::FontAtlas, glyph_key::SubpixelBin, layout::PositionedGlyph,
|
||||
layout_cache::LayoutCache, rasterizer::GlyphRasterizer,
|
||||
},
|
||||
renderer::image::ImageDelta,
|
||||
util::calculate_hash,
|
||||
@@ -10,18 +11,19 @@ use crate::{
|
||||
use ahash::HashMap;
|
||||
use ordered_float::OrderedFloat;
|
||||
use parley::{
|
||||
FontContext, FontFamily, FontStack, FontWeight, GenericFamily, LayoutContext, StyleProperty,
|
||||
TextStyle, fontique::Blob,
|
||||
FontContext, FontFamily, FontFamilyName, FontWeight, GenericFamily, LayoutContext,
|
||||
StyleProperty, TextStyle, fontique::Blob,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use std::{rc::Rc, sync::Arc};
|
||||
|
||||
pub use atlas::FontAtlasSize;
|
||||
pub use layout::{Alignment, FontStyle, Layout, LayoutJob};
|
||||
pub use layout::{Alignment, FontStyle, Layout, LayoutJob, LayoutToLogical};
|
||||
|
||||
mod atlas;
|
||||
mod glyph_key;
|
||||
mod layout;
|
||||
mod layout_cache;
|
||||
mod rasterizer;
|
||||
mod style_cache;
|
||||
|
||||
/// Data of a .ttf or .otf file
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -64,14 +66,12 @@ impl Fonts {
|
||||
definitions,
|
||||
font_context: FontContext::new(),
|
||||
layout_context: LayoutContext::new(),
|
||||
atlas: FontAtlas::new(1024),
|
||||
atlas: FontAtlas::new(1024, 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
|
||||
}
|
||||
@@ -96,19 +96,16 @@ impl Fonts {
|
||||
|
||||
/// 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> {
|
||||
pub fn font_atlas_delta(&mut self) -> Vec<ImageDelta> {
|
||||
self.atlas.take_delta()
|
||||
}
|
||||
|
||||
pub fn preload_common_characters(&mut self, font_size: f32) {
|
||||
/// Warms the glyph cache for common ACSII characters
|
||||
pub fn preload_common_characters(&mut self, font_size: f32, scale_factor: ScaleFactor<f32>) {
|
||||
const ASCII_PRINTABLE_START: u8 = 32;
|
||||
const ASCII_PRINTABLE_END: u8 = 126;
|
||||
|
||||
@@ -122,23 +119,26 @@ impl Fonts {
|
||||
self.preload_text(
|
||||
&common_chars,
|
||||
font_size,
|
||||
FontFamily::Generic(GenericFamily::Monospace),
|
||||
FontFamily::Single(FontFamilyName::Generic(GenericFamily::Monospace)),
|
||||
None,
|
||||
parley::FontStyle::Normal,
|
||||
scale_factor,
|
||||
);
|
||||
self.preload_text(
|
||||
&common_chars,
|
||||
font_size,
|
||||
FontFamily::Generic(GenericFamily::SansSerif),
|
||||
FontFamily::Single(FontFamilyName::Generic(GenericFamily::SansSerif)),
|
||||
None,
|
||||
parley::FontStyle::Normal,
|
||||
scale_factor,
|
||||
);
|
||||
self.preload_text(
|
||||
&common_chars,
|
||||
font_size,
|
||||
FontFamily::Generic(GenericFamily::SansSerif),
|
||||
FontFamily::Single(FontFamilyName::Generic(GenericFamily::SansSerif)),
|
||||
Some(FontWeight::BOLD),
|
||||
parley::FontStyle::Normal,
|
||||
scale_factor,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -149,71 +149,76 @@ impl Fonts {
|
||||
font_family: FontFamily,
|
||||
font_weight: Option<FontWeight>,
|
||||
font_style: parley::FontStyle,
|
||||
scale_factor: ScaleFactor<f32>,
|
||||
) {
|
||||
profiling::scope!("preload_text");
|
||||
|
||||
let style = TextStyle {
|
||||
font_stack: FontStack::Single(font_family),
|
||||
font_family,
|
||||
font_weight: font_weight.unwrap_or(FontWeight::NORMAL),
|
||||
font_style,
|
||||
font_size,
|
||||
..Default::default()
|
||||
};
|
||||
let mut builder =
|
||||
self.layout_context
|
||||
.tree_builder(&mut self.font_context, 1.0, false, &style);
|
||||
let mut builder = self.layout_context.tree_builder(
|
||||
&mut self.font_context,
|
||||
scale_factor.get(),
|
||||
false,
|
||||
&style,
|
||||
);
|
||||
builder.push_text(text);
|
||||
|
||||
let (mut layout, _) = builder.build();
|
||||
layout.break_all_lines(None);
|
||||
let (mut parley_layout, _) = builder.build();
|
||||
parley_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(|_| {});
|
||||
}
|
||||
for_each_glyph_run(&parley_layout, |run| {
|
||||
for horizontal_offset in SubpixelBin::<4>::BIN_OFFSETS {
|
||||
self.glyph_rasterizer
|
||||
.rasterize_glyph_run(
|
||||
&mut self.atlas,
|
||||
run,
|
||||
PhysicalVector::new(horizontal_offset, 0.0),
|
||||
scale_factor,
|
||||
)
|
||||
.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)));
|
||||
pub fn layout(&mut self, job: LayoutJob, scale_factor: ScaleFactor<f32>) -> Rc<Layout> {
|
||||
let hash = calculate_hash(&(&job, OrderedFloat(scale_factor.get())));
|
||||
|
||||
if let Some(cached_layout) = self.layout_cache.get(hash) {
|
||||
return cached_layout;
|
||||
}
|
||||
|
||||
let layout = Rc::new(self.build_layout(job, scale_factor));
|
||||
|
||||
self.layout_cache.insert(hash, Rc::clone(&layout));
|
||||
|
||||
layout
|
||||
}
|
||||
|
||||
fn build_layout(&mut self, job: LayoutJob, scale_factor: ScaleFactor<f32>) -> Layout {
|
||||
let default_style = TextStyle::default();
|
||||
let style = TextStyle {
|
||||
font_stack: parley::FontStack::Single(job.font_family),
|
||||
font_family: 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),
|
||||
font_weight: job.font_weight.map_or(default_style.font_weight, |w| {
|
||||
parley::FontWeight::new(w.into())
|
||||
}),
|
||||
font_style: job.font_style.into(),
|
||||
..default_style
|
||||
};
|
||||
|
||||
let mut builder =
|
||||
self.layout_context
|
||||
.tree_builder(&mut self.font_context, 1.0, false, &style);
|
||||
// scale factor is passed to builder so coordinates in resulting layout will be physical
|
||||
let mut builder = self.layout_context.tree_builder(
|
||||
&mut self.font_context,
|
||||
scale_factor.get(),
|
||||
false,
|
||||
&style,
|
||||
);
|
||||
|
||||
for segment in job.segments {
|
||||
let brush_style = StyleProperty::Brush(segment.color);
|
||||
@@ -225,135 +230,53 @@ impl Fonts {
|
||||
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 {
|
||||
let parley_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
|
||||
}
|
||||
Alignment::Center => parley::Alignment::Center,
|
||||
Alignment::Max => parley::Alignment::End,
|
||||
};
|
||||
parley_layout.align(None, alignment, parley::AlignmentOptions::default());
|
||||
parley_layout.align(parley_alignment, parley::AlignmentOptions::default());
|
||||
}
|
||||
|
||||
let mut layout_rows = Vec::new();
|
||||
let mut num_of_vertices = 0;
|
||||
let mut num_of_indices = 0;
|
||||
let mut glyphs = Vec::new();
|
||||
|
||||
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;
|
||||
}
|
||||
for_each_glyph_run(&parley_layout, |run| {
|
||||
for rasterized in self.glyph_rasterizer.rasterize_glyph_run(
|
||||
&mut self.atlas,
|
||||
run,
|
||||
PhysicalVector::zero(),
|
||||
scale_factor,
|
||||
) {
|
||||
let Some(glyph) = rasterized else { continue };
|
||||
glyphs.push(PositionedGlyph {
|
||||
rect: glyph.rect,
|
||||
uv: glyph.uv,
|
||||
layer_idx: glyph.texture_layer_idx,
|
||||
color: glyph.color,
|
||||
});
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
/// Width of laid out text
|
||||
pub fn get_text_width(&mut self, job: LayoutJob, pixels_per_point: f32) -> i32 {
|
||||
let layout = self.layout(job, pixels_per_point);
|
||||
layout.width() as i32
|
||||
}
|
||||
|
||||
/// Text index at cursor location
|
||||
pub fn get_text_index_at_cursor(
|
||||
&mut self,
|
||||
job: LayoutJob,
|
||||
cursor: LogicalPoint<f32>,
|
||||
pixels_per_point: f32,
|
||||
) -> usize {
|
||||
let layout = self.layout(job, pixels_per_point);
|
||||
layout.cursor_index(cursor)
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
Layout {
|
||||
// full_width is physical so it needs to be converted back to logical
|
||||
width: parley_layout.full_width() / scale_factor.get(),
|
||||
glyphs,
|
||||
parley_layout,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
/// Applies a function to each glyph run in a `parley::Layout`
|
||||
fn for_each_glyph_run<'a>(
|
||||
layout: &'a parley::Layout<Srgba>,
|
||||
mut f: impl FnMut(&parley::GlyphRun<'a, Srgba>),
|
||||
) {
|
||||
for line in layout.lines() {
|
||||
for item in line.items() {
|
||||
if let parley::PositionedLayoutItem::GlyphRun(run) = item {
|
||||
f(&run);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+177
-89
@@ -1,137 +1,225 @@
|
||||
use std::num::NonZeroU32;
|
||||
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
math::{Point, Rect, Size},
|
||||
dpi::PhysicalSize,
|
||||
math::{Point, Rect, Scale, Size},
|
||||
renderer::{
|
||||
image::{ImageData, ImageDelta},
|
||||
image::{DataOrder, ImageData, ImageDelta, MipStrategy, PartialDeltaOrigin},
|
||||
textures::TextureOptions,
|
||||
},
|
||||
uv::{UvRect, UvSpace},
|
||||
};
|
||||
use image::{GenericImage, RgbaImage, SubImage, imageops};
|
||||
use image::{GenericImage, RgbaImage, SubImage};
|
||||
|
||||
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,
|
||||
pub struct AllocatedGlyph<'a> {
|
||||
pub sub_image: SubImage<&'a mut RgbaImage>,
|
||||
pub layer_idx: u32,
|
||||
pub uv: UvRect,
|
||||
}
|
||||
|
||||
struct Layer {
|
||||
image: RgbaImage,
|
||||
// position of next allocation
|
||||
/// 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,
|
||||
/// Dirty region
|
||||
dirty: FontAtlasRect,
|
||||
}
|
||||
|
||||
pub struct FontAtlas {
|
||||
layer_size: FontAtlasSize,
|
||||
// maximum amount of layers
|
||||
max_layers: u32,
|
||||
layers: Vec<Layer>,
|
||||
// used to convert to normalized UV coordinates
|
||||
to_uv: Scale<f32, FontAtlasSpace, UvSpace>,
|
||||
/// Set when a full texture upload is required
|
||||
needs_full_update: 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;
|
||||
|
||||
pub fn new(layer_size: u32, max_layers: u32) -> Self {
|
||||
let mut atlas = Self {
|
||||
max_texture_side,
|
||||
image: RgbaImage::new(width, initial_height),
|
||||
cursor: FontAtlasPoint::zero(),
|
||||
current_row_height: 0,
|
||||
dirty: false,
|
||||
overflowed: false,
|
||||
layer_size: Size::new(layer_size, layer_size),
|
||||
max_layers,
|
||||
layers: Vec::new(),
|
||||
to_uv: Scale::new(1.0 / layer_size as f32),
|
||||
needs_full_update: false,
|
||||
};
|
||||
|
||||
atlas.push_layer();
|
||||
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());
|
||||
/// Adds a new empty layer
|
||||
fn push_layer(&mut self) {
|
||||
self.layers.push(Layer {
|
||||
image: RgbaImage::new(self.layer_size.width, self.layer_size.height),
|
||||
cursor: FontAtlasPoint::zero(),
|
||||
current_row_height: 0,
|
||||
dirty: FontAtlasRect::zero(),
|
||||
});
|
||||
|
||||
// adding a new layer requires a full texture re-allocation
|
||||
self.needs_full_update = true;
|
||||
}
|
||||
|
||||
// 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> {
|
||||
/// Initializes the atlas.
|
||||
///
|
||||
/// Puts a white pixel at (0, 0) of layer 0 for solid color texturing.
|
||||
fn initialize(&mut self) {
|
||||
let mut allocation = self.allocate(FontAtlasSize::new(1, 1));
|
||||
allocation.sub_image.put_pixel(0, 0, Srgba::WHITE.into());
|
||||
}
|
||||
|
||||
/// Allocates a new glyph
|
||||
fn allocate(&mut self, requested_size: FontAtlasSize) -> AllocatedGlyph<'_> {
|
||||
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;
|
||||
}
|
||||
let mut idx = self.layers.len() - 1;
|
||||
|
||||
self.current_row_height = self.current_row_height.max(size.height);
|
||||
{
|
||||
let layer = &mut self.layers[idx];
|
||||
|
||||
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;
|
||||
// start new row if new allocation doesn't fit on current row
|
||||
if layer.cursor.x + requested_size.width > self.layer_size.width {
|
||||
layer.cursor.x = 0;
|
||||
layer.cursor.y += layer.current_row_height + PADDING;
|
||||
layer.current_row_height = 0;
|
||||
}
|
||||
|
||||
// add new layer if new allocation doesn't fit on current layer
|
||||
if layer.cursor.y + requested_size.height > self.layer_size.height {
|
||||
if (self.layers.len() as u32) < self.max_layers {
|
||||
self.push_layer();
|
||||
idx = self.layers.len() - 1;
|
||||
} else {
|
||||
// just choose a sufficiently large layer size and count to
|
||||
// avoid panic. a more sophisticated approach can be implemented
|
||||
// later if needed
|
||||
panic!("font atlas reached maximum size!");
|
||||
}
|
||||
}
|
||||
self.image = extend_image_height(&self.image, new_height, Srgba::TRANSPARENT);
|
||||
}
|
||||
|
||||
let pos = self.cursor;
|
||||
self.cursor.x += size.width + PADDING;
|
||||
let layer = &mut self.layers[idx];
|
||||
layer.current_row_height = layer.current_row_height.max(requested_size.height);
|
||||
let pos = layer.cursor;
|
||||
layer.cursor.x += requested_size.width + PADDING;
|
||||
|
||||
self.dirty = true;
|
||||
let glyph_rect = FontAtlasRect::from_origin_and_size(pos, requested_size);
|
||||
let uv = self.to_uv.transform_box2d(&glyph_rect.cast());
|
||||
|
||||
self.image.sub_image(pos.x, pos.y, size.width, size.height)
|
||||
// extend dirty region to include new glyph allocation
|
||||
layer.dirty = layer.dirty.union(&glyph_rect);
|
||||
|
||||
AllocatedGlyph {
|
||||
sub_image: layer.image.sub_image(
|
||||
pos.x,
|
||||
pos.y,
|
||||
requested_size.width,
|
||||
requested_size.height,
|
||||
),
|
||||
layer_idx: idx as u32,
|
||||
uv,
|
||||
}
|
||||
}
|
||||
|
||||
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()),
|
||||
pub fn take_delta(&mut self) -> Vec<ImageDelta> {
|
||||
// first check if full update is required
|
||||
if std::mem::replace(&mut self.needs_full_update, false) {
|
||||
let mut bytes = Vec::with_capacity(
|
||||
self.layers.len() * (self.layer_size.width * self.layer_size.height * 4) as usize,
|
||||
);
|
||||
|
||||
for layer in &mut self.layers {
|
||||
bytes.extend_from_slice(layer.image.as_raw());
|
||||
// reset layer's dirty region since we're doing a full update anyway
|
||||
layer.dirty = FontAtlasRect::zero();
|
||||
}
|
||||
|
||||
return vec![ImageDelta::full(
|
||||
ImageData {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
width: self.layer_size.width,
|
||||
height: self.layer_size.height,
|
||||
array_layers: self.layers.len() as u32,
|
||||
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
|
||||
data_order: DataOrder::default(),
|
||||
bytes,
|
||||
},
|
||||
TextureOptions::LINEAR,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
MipStrategy::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
|
||||
// add partial update for each dirty layer
|
||||
let mut partial_updates = Vec::new();
|
||||
for (i, layer) in self.layers.iter_mut().enumerate() {
|
||||
let dirty = std::mem::replace(&mut layer.dirty, FontAtlasRect::zero());
|
||||
if dirty.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let bytes = layer
|
||||
.image
|
||||
.sub_image(dirty.min.x, dirty.min.y, dirty.width(), dirty.height())
|
||||
.to_image()
|
||||
.into_vec();
|
||||
|
||||
partial_updates.push(ImageDelta::partial(
|
||||
ImageData {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
width: dirty.width(),
|
||||
height: dirty.height(),
|
||||
array_layers: 1,
|
||||
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
|
||||
data_order: DataOrder::default(),
|
||||
bytes,
|
||||
},
|
||||
PartialDeltaOrigin {
|
||||
x: dirty.min.x,
|
||||
y: dirty.min.y,
|
||||
layer: i as u32,
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
partial_updates
|
||||
}
|
||||
|
||||
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 write_mask(
|
||||
&mut self,
|
||||
image: &swash::scale::image::Image,
|
||||
) -> (PhysicalSize<u32>, UvRect, u32) {
|
||||
debug_assert!(matches!(image.content, swash::scale::image::Content::Mask));
|
||||
|
||||
pub fn image(&self) -> &RgbaImage {
|
||||
&self.image
|
||||
}
|
||||
let size = Size::new(image.placement.width, image.placement.height);
|
||||
let mut allocation = self.allocate(size);
|
||||
|
||||
pub fn size(&self) -> FontAtlasSize {
|
||||
FontAtlasSize::new(self.image.width(), self.image.height())
|
||||
let mut i = 0;
|
||||
for y in 0..size.height {
|
||||
for x in 0..size.width {
|
||||
let a = image.data[i];
|
||||
// SAFETY: allocated atlas region and swash image have the same size
|
||||
unsafe {
|
||||
allocation.sub_image.unsafe_put_pixel(
|
||||
x,
|
||||
y,
|
||||
Srgba::new(255, 255, 255, a).into(),
|
||||
);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
(size.cast_unit(), allocation.uv, allocation.layer_idx)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
+11
-17
@@ -1,36 +1,30 @@
|
||||
use ordered_float::OrderedFloat;
|
||||
use parley::Glyph;
|
||||
|
||||
use crate::{dpi::PhysicalPoint, fonts::rasterizer::StyleId};
|
||||
use crate::{dpi::PhysicalPoint, fonts::style_cache::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,
|
||||
pub fn from_position(
|
||||
position: PhysicalPoint<f32>,
|
||||
glyph_id: u32,
|
||||
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);
|
||||
// x: use subpixel binning so bitmap encodes sub-pixel position
|
||||
let (x, x_bin) = SubpixelBin::<4>::new(position.x);
|
||||
// y: just rounded. not much benefit from sub-pixel vertical positioning
|
||||
let y = position.y.round() as i32;
|
||||
|
||||
(
|
||||
Self {
|
||||
glyph_id: glyph.id as u16,
|
||||
glyph_id: glyph_id as u16,
|
||||
style_id,
|
||||
x_bin,
|
||||
pixels_per_point: OrderedFloat(pixels_per_point),
|
||||
},
|
||||
glyph_pos,
|
||||
PhysicalPoint::new(x, y),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -72,7 +66,7 @@ impl<const NUM_OF_BINS: usize> SubpixelBin<NUM_OF_BINS> {
|
||||
|
||||
#[test]
|
||||
fn test_subpixel_bins() {
|
||||
assert_eq!(SubpixelBin::<4>::new(3.14), (3, SubpixelBin(1)));
|
||||
assert_eq!(SubpixelBin::<4>::new(3.13), (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)));
|
||||
|
||||
+52
-24
@@ -1,8 +1,20 @@
|
||||
use crate::{color::Srgba, dpi::LogicalPoint, fonts::rasterizer::RasterizedGlyph};
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::{LogicalPoint, LogicalScreenSpace, LogicalVector},
|
||||
math::{Rect, Translation},
|
||||
uv::UvRect,
|
||||
};
|
||||
use ordered_float::OrderedFloat;
|
||||
use parley::FontFamily;
|
||||
use parley::{FontFamily, FontFamilyName};
|
||||
|
||||
#[derive(Copy, Clone, Default, Debug, Hash, PartialEq)]
|
||||
// All coordinates relative to layout origin
|
||||
pub struct LayoutSpace;
|
||||
|
||||
pub type LayoutRect<T> = Rect<T, LayoutSpace>;
|
||||
|
||||
pub type LayoutToLogical = Translation<f32, LayoutSpace, LogicalScreenSpace>;
|
||||
|
||||
#[derive(Copy, Clone, Default, Debug, Hash, Eq, PartialEq)]
|
||||
pub enum Alignment {
|
||||
#[default]
|
||||
Min,
|
||||
@@ -10,7 +22,7 @@ pub enum Alignment {
|
||||
Max,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Default, Debug, Hash, PartialEq)]
|
||||
#[derive(Copy, Clone, Default, Debug, Hash, Eq, PartialEq)]
|
||||
pub enum FontStyle {
|
||||
#[default]
|
||||
Normal,
|
||||
@@ -20,8 +32,8 @@ pub enum FontStyle {
|
||||
impl From<FontStyle> for parley::FontStyle {
|
||||
fn from(value: FontStyle) -> Self {
|
||||
match value {
|
||||
FontStyle::Normal => parley::FontStyle::Normal,
|
||||
FontStyle::Italic => parley::FontStyle::Italic,
|
||||
FontStyle::Normal => Self::Normal,
|
||||
FontStyle::Italic => Self::Italic,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,12 +84,24 @@ impl std::hash::Hash for LayoutJob<'_> {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.segments.hash(state);
|
||||
match &self.font_family {
|
||||
FontFamily::Named(cow) => {
|
||||
FontFamily::Single(FontFamilyName::Named(cow)) | FontFamily::Source(cow) => {
|
||||
cow.hash(state);
|
||||
}
|
||||
FontFamily::Generic(generic_family) => {
|
||||
FontFamily::Single(FontFamilyName::Generic(generic_family)) => {
|
||||
generic_family.hash(state);
|
||||
}
|
||||
FontFamily::List(cow) => {
|
||||
for name in cow.iter() {
|
||||
match name {
|
||||
FontFamilyName::Named(cow) => {
|
||||
cow.hash(state);
|
||||
}
|
||||
FontFamilyName::Generic(generic_family) => {
|
||||
generic_family.hash(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.font_size.hash(state);
|
||||
self.line_height.hash(state);
|
||||
@@ -87,33 +111,37 @@ impl std::hash::Hash for LayoutJob<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct LayoutRow {
|
||||
pub glyphs: Vec<RasterizedGlyph>,
|
||||
pub struct PositionedGlyph {
|
||||
pub rect: LayoutRect<f32>,
|
||||
pub uv: UvRect,
|
||||
pub layer_idx: u32,
|
||||
pub color: Srgba,
|
||||
}
|
||||
|
||||
pub struct Layout {
|
||||
pub job_hash: u64,
|
||||
pub glyphs: Vec<PositionedGlyph>,
|
||||
pub width: f32,
|
||||
// kept for parley's cursor helper.
|
||||
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()
|
||||
self.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()
|
||||
pub fn anchor_offset(&self, anchor: Alignment) -> LogicalVector<f32> {
|
||||
match anchor {
|
||||
Alignment::Min => LogicalVector::zero(),
|
||||
Alignment::Center => LogicalVector::new(-self.width * 0.5, 0.0),
|
||||
Alignment::Max => LogicalVector::new(-self.width, 0.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::hash::Hash for Layout {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.job_hash.hash(state);
|
||||
pub fn cursor_index_at(&self, point: LogicalPoint<f32>) -> usize {
|
||||
// `parley_layout` was built at the real display scale factor so its internal coordinates
|
||||
// are physical. Scale the query point to match.
|
||||
let scale = self.parley_layout.scale();
|
||||
parley::Cursor::from_point(&self.parley_layout, point.x * scale, point.y * scale).index()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::fonts::Layout;
|
||||
|
||||
struct CachedLayout {
|
||||
layout: Rc<Layout>,
|
||||
// used to identify unused layouts
|
||||
generation: u32,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct LayoutCache {
|
||||
cache: nohash_hasher::IntMap<u64, CachedLayout>,
|
||||
current_generation: u32,
|
||||
}
|
||||
|
||||
impl LayoutCache {
|
||||
pub fn get(&mut self, hash: u64) -> Option<Rc<Layout>> {
|
||||
match self.cache.entry(hash) {
|
||||
std::collections::hash_map::Entry::Occupied(entry) => {
|
||||
let cached = entry.into_mut();
|
||||
cached.generation = self.current_generation;
|
||||
Some(Rc::clone(&cached.layout))
|
||||
}
|
||||
std::collections::hash_map::Entry::Vacant(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, hash: u64, layout: Rc<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);
|
||||
}
|
||||
}
|
||||
+83
-182
@@ -1,101 +1,41 @@
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::{
|
||||
ConvertToLogical, LogicalRect, LogicalVector, PhysicalPoint, PhysicalRect, PhysicalVector,
|
||||
},
|
||||
fonts::{
|
||||
atlas::{FontAtlas, FontAtlasRect},
|
||||
glyph_key::GlyphKey,
|
||||
},
|
||||
math::{Point, Size},
|
||||
dpi::{PhysicalPoint, PhysicalRect, PhysicalSize, PhysicalVector, ScaleFactor},
|
||||
fonts::{atlas::FontAtlas, glyph_key::GlyphKey, layout::LayoutRect, style_cache::StyleCache},
|
||||
uv::UvRect,
|
||||
};
|
||||
use ahash::HashMap;
|
||||
use image::GenericImage;
|
||||
use ordered_float::OrderedFloat;
|
||||
use parley::{FontData, GlyphRun};
|
||||
use std::borrow::Cow;
|
||||
use swash::zeno;
|
||||
|
||||
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]>,
|
||||
skew: i8,
|
||||
}
|
||||
|
||||
impl<'a> StyleKey<'a> {
|
||||
fn new(
|
||||
font_blob_id: FontBlobId,
|
||||
font_size: f32,
|
||||
normalized_coords: &'a [i16],
|
||||
skew: i8,
|
||||
) -> Self {
|
||||
Self {
|
||||
font_blob_id,
|
||||
font_size: font_size.into(),
|
||||
normalized_coords: Cow::Borrowed(normalized_coords),
|
||||
skew,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_static(&self) -> StyleKey<'static> {
|
||||
StyleKey {
|
||||
normalized_coords: self.normalized_coords.clone().into_owned().into(),
|
||||
..*self
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct CachedGlyph {
|
||||
// absolute uv rect within font atlas
|
||||
pub uv: FontAtlasRect,
|
||||
// offset from top/left to baseline
|
||||
/// Size of the trimmed bitmap. Swash crops away transparant rows/columns so this is smaller
|
||||
/// than the glyph's full advance box.
|
||||
pub size: PhysicalSize<u32>,
|
||||
pub uv: UvRect,
|
||||
pub texture_layer_idx: u32,
|
||||
/// Offset from the glyph's origin (top-left) to the trimmed bitmap's top-left corner.
|
||||
pub baseline_offset: PhysicalVector<i32>,
|
||||
}
|
||||
|
||||
pub struct RasterizedGlyph {
|
||||
// NOTE: this is relative to the layout origin
|
||||
pub rect: LogicalRect<f32>,
|
||||
pub uv: FontAtlasRect,
|
||||
pub rect: LayoutRect<f32>,
|
||||
pub uv: UvRect,
|
||||
pub texture_layer_idx: u32,
|
||||
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,
|
||||
style_cache: StyleCache,
|
||||
cached_glyphs: HashMap<GlyphKey, Option<CachedGlyph>>,
|
||||
// scratch image buffer used to write bitmap data into
|
||||
/// Scratch image buffer used to temporarily write bitmap data into
|
||||
scratch: swash::scale::image::Image,
|
||||
}
|
||||
|
||||
@@ -103,22 +43,14 @@ 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(),
|
||||
swash_keys: HashMap::default(),
|
||||
style_cache: StyleCache::default(),
|
||||
cached_glyphs: HashMap::default(),
|
||||
scratch: swash::scale::image::Image::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
|
||||
/// 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();
|
||||
|
||||
@@ -138,46 +70,26 @@ impl GlyphRasterizer {
|
||||
}
|
||||
}
|
||||
|
||||
fn get_style_id(
|
||||
&mut self,
|
||||
font_data: &FontData,
|
||||
font_size: f32,
|
||||
norm_coords: &[i16],
|
||||
skew: i8,
|
||||
) -> StyleId {
|
||||
let style_key = StyleKey::new(font_data.data.id(), font_size, norm_coords, skew);
|
||||
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).
|
||||
/// Rasterizes a glyph run and returns the placement and UV for each glyph.
|
||||
/// Returns `None` for glyphs that doesn't take up visible 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,
|
||||
// additional offset applied to every glyph's raw parley position before quantization
|
||||
offset: PhysicalVector<f32>,
|
||||
scale_factor: ScaleFactor<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_size = run.font_size();
|
||||
let normalized_coords =
|
||||
&Vec::from_iter(run.normalized_coords().iter().map(|c| c.to_bits()));
|
||||
let skew = run.synthesis().skew(); // skew angle for faux italic
|
||||
|
||||
let font_ref = self.get_font_ref(run.font());
|
||||
let style_id = self.get_style_id(
|
||||
run.font(),
|
||||
let style_id = self.style_cache.get_or_insert(
|
||||
run.font().data.id(),
|
||||
font_size,
|
||||
normalized_coords,
|
||||
// parley stores skew as i8 internally so this conversion is ok
|
||||
@@ -194,79 +106,68 @@ impl GlyphRasterizer {
|
||||
|
||||
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);
|
||||
glyph_run.positioned_glyphs().map(move |glyph| {
|
||||
let glyph_position = PhysicalPoint::new(glyph.x, glyph.y) + offset;
|
||||
|
||||
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 (glyph_key, physical_position) =
|
||||
GlyphKey::from_position(glyph_position, glyph.id, style_id);
|
||||
|
||||
let fract_offset = glyph_key.get_fractional_offset();
|
||||
let cached = *cached_glyphs.entry(glyph_key).or_insert_with(|| {
|
||||
rasterize_glyph(&mut scaler, image, atlas, glyph.id, &glyph_key, skew)
|
||||
});
|
||||
|
||||
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(zeno::Format::Alpha)
|
||||
.transform(skew.map(|skew| {
|
||||
zeno::Transform::skew(zeno::Angle::from_degrees(skew), zeno::Angle::ZERO)
|
||||
}))
|
||||
.offset(fract_offset)
|
||||
.render_into(&mut scaler, glyph.id as u16, image);
|
||||
cached.map(|cached| {
|
||||
// apply the baseline offset to get the actual bitmap position
|
||||
let bitmap_top_left = physical_position + cached.baseline_offset;
|
||||
let physical_rect =
|
||||
PhysicalRect::from_origin_and_size(bitmap_top_left, cached.size.cast());
|
||||
|
||||
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,
|
||||
))
|
||||
RasterizedGlyph {
|
||||
rect: (physical_rect.cast() / scale_factor).cast_unit(),
|
||||
uv: cached.uv,
|
||||
texture_layer_idx: cached.texture_layer_idx,
|
||||
color,
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 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));
|
||||
/// Renders glyph's bitmap into the atlas
|
||||
fn rasterize_glyph(
|
||||
scaler: &mut swash::scale::Scaler,
|
||||
image: &mut swash::scale::image::Image,
|
||||
atlas: &mut FontAtlas,
|
||||
glyph_id: u32,
|
||||
glyph_key: &GlyphKey,
|
||||
skew: Option<f32>,
|
||||
) -> Option<CachedGlyph> {
|
||||
image.clear();
|
||||
|
||||
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),
|
||||
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(zeno::Format::Alpha)
|
||||
.transform(
|
||||
skew.map(|skew| zeno::Transform::skew(zeno::Angle::from_degrees(skew), zeno::Angle::ZERO)),
|
||||
)
|
||||
.offset(glyph_key.get_fractional_offset())
|
||||
.render_into(scaler, glyph_id as u16, image);
|
||||
|
||||
if !did_render || image.placement.width == 0 || image.placement.height == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (size, uv, layer_idx) = atlas.write_mask(image);
|
||||
|
||||
Some(CachedGlyph {
|
||||
size,
|
||||
uv,
|
||||
texture_layer_idx: layer_idx,
|
||||
// swash uses `Origin::BottomLeft` so we need to negate the vertical component
|
||||
baseline_offset: PhysicalVector::new(image.placement.left, -image.placement.top),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use ahash::HashMap;
|
||||
use ordered_float::OrderedFloat;
|
||||
use std::borrow::Cow;
|
||||
|
||||
pub type StyleId = u32;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
struct StyleKey<'a> {
|
||||
font_blob_id: u64,
|
||||
font_size: OrderedFloat<f32>,
|
||||
normalized_coords: Cow<'a, [i16]>,
|
||||
skew: i8,
|
||||
}
|
||||
|
||||
impl<'a> StyleKey<'a> {
|
||||
fn new(font_blob_id: u64, font_size: f32, normalized_coords: &'a [i16], skew: i8) -> Self {
|
||||
Self {
|
||||
font_blob_id,
|
||||
font_size: font_size.into(),
|
||||
normalized_coords: Cow::Borrowed(normalized_coords),
|
||||
skew,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_static(&self) -> StyleKey<'static> {
|
||||
StyleKey {
|
||||
normalized_coords: self.normalized_coords.clone().into_owned().into(),
|
||||
..*self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Associates font style combinations (font, size, norm coords, skew) with a small `StyleId`, so
|
||||
/// `GlyphKey` never has to compare full style data per glyph, just once per run.
|
||||
#[derive(Default)]
|
||||
pub struct StyleCache {
|
||||
ids: HashMap<StyleKey<'static>, StyleId>,
|
||||
next_id: StyleId,
|
||||
}
|
||||
|
||||
impl StyleCache {
|
||||
pub fn get_or_insert(
|
||||
&mut self,
|
||||
font_blob_id: u64,
|
||||
font_size: f32,
|
||||
normalized_coords: &[i16],
|
||||
skew: i8,
|
||||
) -> StyleId {
|
||||
let key = StyleKey::new(font_blob_id, font_size, normalized_coords, skew);
|
||||
|
||||
if let Some(id) = self.ids.get(&key) {
|
||||
return *id;
|
||||
}
|
||||
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
self.ids.insert(key.to_static(), id);
|
||||
id
|
||||
}
|
||||
}
|
||||
+76
-48
@@ -1,18 +1,13 @@
|
||||
use crate::{
|
||||
dpi::PhysicalSize,
|
||||
renderer::{Renderer, mesh::ClippedMesh, textures::TexturesDelta},
|
||||
renderer::{RenderJob, Renderer},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use wgpu::{Texture, TextureFormat, TextureView};
|
||||
use winit::window::Window;
|
||||
|
||||
pub enum RenderJob {
|
||||
Render {
|
||||
meshes: Vec<ClippedMesh>,
|
||||
textures_delta: TexturesDelta,
|
||||
},
|
||||
Skip,
|
||||
}
|
||||
const REQUIRED_TEXTURE_LAYERS: u32 = 1024;
|
||||
const REQUIRED_TEXTURE_ARRAY_SLOTS: u32 = 64;
|
||||
|
||||
pub struct GraphicsContext {
|
||||
surface: wgpu::Surface<'static>,
|
||||
@@ -31,9 +26,12 @@ impl GraphicsContext {
|
||||
pub async fn new(window: Arc<Window>) -> anyhow::Result<Self> {
|
||||
let size = window.inner_size();
|
||||
|
||||
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
|
||||
backends: wgpu::Backends::PRIMARY,
|
||||
..Default::default()
|
||||
flags: Default::default(),
|
||||
memory_budget_thresholds: Default::default(),
|
||||
backend_options: Default::default(),
|
||||
display: None,
|
||||
});
|
||||
|
||||
let surface = instance.create_surface(Arc::clone(&window)).unwrap();
|
||||
@@ -43,12 +41,17 @@ impl GraphicsContext {
|
||||
power_preference: wgpu::PowerPreference::default(),
|
||||
compatible_surface: Some(&surface),
|
||||
force_fallback_adapter: false,
|
||||
apply_limit_buckets: true,
|
||||
})
|
||||
.await?;
|
||||
|
||||
let required_features = wgpu::Features::TEXTURE_COMPRESSION_BC;
|
||||
let required_features = wgpu::Features::TEXTURE_COMPRESSION_BC
|
||||
| wgpu::Features::TEXTURE_BINDING_ARRAY
|
||||
| wgpu::Features::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING;
|
||||
let required_limits = wgpu::Limits {
|
||||
max_texture_array_layers: 512,
|
||||
max_texture_array_layers: REQUIRED_TEXTURE_LAYERS,
|
||||
max_binding_array_elements_per_shader_stage: REQUIRED_TEXTURE_ARRAY_SLOTS,
|
||||
max_binding_array_sampler_elements_per_shader_stage: REQUIRED_TEXTURE_ARRAY_SLOTS,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
@@ -88,27 +91,51 @@ impl GraphicsContext {
|
||||
|
||||
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
|
||||
log::debug!(
|
||||
"surface format capabilities: {:#?}",
|
||||
surface_caps.format_capabilities
|
||||
);
|
||||
|
||||
// NOTE: PoB blends in non-linear space, so we want a plain UNORM format with
|
||||
// no automatic linear -> non-linear conversion to get the same visual result.
|
||||
const PREFERRED: [wgpu::TextureFormat; 2] = [
|
||||
wgpu::TextureFormat::Bgra8Unorm,
|
||||
wgpu::TextureFormat::Rgba8Unorm,
|
||||
];
|
||||
|
||||
let surface_format = PREFERRED
|
||||
.iter()
|
||||
.find(|f| !f.is_srgb() && f.required_features().is_empty())
|
||||
.copied()
|
||||
.unwrap_or(surface_caps.formats[0]);
|
||||
.find(|f| surface_caps.formats.contains(f))
|
||||
.unwrap_or_else(|| {
|
||||
// fallback: any non-sRGB format that isn't floating point
|
||||
surface_caps
|
||||
.formats
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|f| {
|
||||
!f.is_srgb()
|
||||
&& !matches!(
|
||||
f,
|
||||
wgpu::TextureFormat::Rgba16Float | wgpu::TextureFormat::Rgba32Float
|
||||
)
|
||||
&& f.required_features().is_empty()
|
||||
})
|
||||
.unwrap_or(surface_caps.formats[0])
|
||||
});
|
||||
|
||||
log::debug!("selected format: {:?}", surface_format);
|
||||
|
||||
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,
|
||||
color_space: wgpu::SurfaceColorSpace::Srgb,
|
||||
};
|
||||
|
||||
let (blit_texture, blit_texture_view) =
|
||||
@@ -144,19 +171,27 @@ impl GraphicsContext {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(
|
||||
&mut self,
|
||||
render_job: RenderJob,
|
||||
scale_factor: f32,
|
||||
) -> Result<(), wgpu::SurfaceError> {
|
||||
pub fn render(&mut self, render_job: Option<RenderJob>) -> anyhow::Result<()> {
|
||||
profiling::scope!("render");
|
||||
|
||||
if !self.is_surface_configured {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let output = self.surface.get_current_texture()?;
|
||||
let suboptimal = output.suboptimal;
|
||||
let output = match self.surface.get_current_texture() {
|
||||
wgpu::CurrentSurfaceTexture::Success(surface_tex) => surface_tex,
|
||||
wgpu::CurrentSurfaceTexture::Suboptimal(surface_tex) => surface_tex,
|
||||
wgpu::CurrentSurfaceTexture::Timeout
|
||||
| wgpu::CurrentSurfaceTexture::Occluded
|
||||
| wgpu::CurrentSurfaceTexture::Validation => {
|
||||
// Skip frame
|
||||
return Ok(());
|
||||
}
|
||||
wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
|
||||
self.surface.configure(&self.device, &self.config);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
let surface_view = output
|
||||
.texture
|
||||
@@ -168,26 +203,22 @@ impl GraphicsContext {
|
||||
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
|
||||
{
|
||||
// If render_job is `None`, skip rendering and just blit the texture
|
||||
// of the previous frame onto the surface texture.
|
||||
if let Some(render_job) = render_job {
|
||||
let screen_size = PhysicalSize::new(self.config.width, self.config.height);
|
||||
|
||||
// upload new textures
|
||||
self.renderer
|
||||
.update_textures(&self.device, &self.queue, &textures_delta);
|
||||
.update_textures(&self.device, &self.queue, &render_job.textures_delta);
|
||||
|
||||
// upload vertex, index, and uniform buffers
|
||||
self.renderer.update_buffers(
|
||||
&self.device,
|
||||
&self.queue,
|
||||
&meshes,
|
||||
&render_job,
|
||||
screen_size,
|
||||
scale_factor,
|
||||
render_job.scale_factor,
|
||||
);
|
||||
|
||||
let rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
@@ -209,16 +240,18 @@ impl GraphicsContext {
|
||||
timestamp_writes: None,
|
||||
label: Some("main render pass"),
|
||||
occlusion_query_set: None,
|
||||
multiview_mask: None,
|
||||
});
|
||||
|
||||
self.renderer.render(
|
||||
&self.device,
|
||||
&mut rpass.forget_lifetime(),
|
||||
&meshes,
|
||||
&render_job,
|
||||
screen_size,
|
||||
scale_factor,
|
||||
render_job.scale_factor,
|
||||
);
|
||||
|
||||
self.renderer.free_textures(&textures_delta);
|
||||
self.renderer.free_textures(&render_job.textures_delta);
|
||||
}
|
||||
|
||||
{
|
||||
@@ -232,15 +265,10 @@ impl GraphicsContext {
|
||||
}
|
||||
|
||||
self.queue.submit(std::iter::once(encoder.finish()));
|
||||
|
||||
self.window.pre_present_notify();
|
||||
output.present();
|
||||
self.queue.present(output);
|
||||
|
||||
if suboptimal {
|
||||
Err(wgpu::SurfaceError::Outdated)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+57
-203
@@ -3,66 +3,87 @@
|
||||
use crate::dpi::LogicalPoint;
|
||||
use ahash::{HashMap, HashSet};
|
||||
use std::time::{Duration, Instant};
|
||||
use winit::{
|
||||
event::MouseButton,
|
||||
keyboard::{Key, ModifiersState, NamedKey, SmolStr},
|
||||
};
|
||||
|
||||
/// Current state of various keyboard and mouse inputs for the application.
|
||||
pub type Key = winit::keyboard::Key;
|
||||
pub type MouseButton = winit::event::MouseButton;
|
||||
pub type ModifiersState = winit::keyboard::ModifiersState;
|
||||
|
||||
/// Max gap between two clicks for them to count as a double-click.
|
||||
const DOUBLE_CLICK_DURATION: Duration = Duration::from_millis(500);
|
||||
/// Max cursor movement between two clicks for them to count as a double-click.
|
||||
const DOUBLE_CLICK_MOVE_THRESHOLD: f32 = 5.0;
|
||||
|
||||
/// When and where a mouse button was last pressed, for double-click detection.
|
||||
#[derive(Debug, Clone)]
|
||||
struct MousePressState {
|
||||
time: Instant,
|
||||
pos: LogicalPoint<f32>,
|
||||
}
|
||||
|
||||
/// Tracks currently-pressed keys/buttons and cursor position.
|
||||
#[derive(Default)]
|
||||
pub struct InputState {
|
||||
/// Current state(s) of modifier keys. (Shift, Control, Alt, Super)
|
||||
/// Currently held modifier keys (Shift/Ctrl/Alt/Super).
|
||||
pub key_modifiers: ModifiersState,
|
||||
/// HashSet of currently pressed keyboard keys.
|
||||
/// Keys currently held down.
|
||||
keys_pressed: HashSet<Key>,
|
||||
/// HashSet of currently pressed mouse buttons.
|
||||
/// Mouse buttons currently held down.
|
||||
mouse_pressed: HashSet<MouseButton>,
|
||||
/// HashMap of mouse buttons (keys) with the last time they were pressed.
|
||||
mouse_last_pressed: HashMap<MouseButton, Instant>,
|
||||
/// Current cursor position relative to the top-left corner of the window.
|
||||
/// Last press time/position per mouse button, for double-click detection.
|
||||
mouse_last_pressed: HashMap<MouseButton, MousePressState>,
|
||||
/// Current mouse cursor position.
|
||||
cursor_pos: LogicalPoint<f32>,
|
||||
}
|
||||
|
||||
impl InputState {
|
||||
/// Updates [`Self::keys_pressed`] based on `is_pressed`.
|
||||
pub fn set_key_pressed(&mut self, key: Key, is_pressed: bool) {
|
||||
/// Marks 'key' as pressed or released.
|
||||
pub fn set_key_pressed(&mut self, key: &Key, is_pressed: bool) {
|
||||
if is_pressed {
|
||||
self.keys_pressed.insert(key);
|
||||
self.keys_pressed.insert(key.clone());
|
||||
} else {
|
||||
self.keys_pressed.remove(&key);
|
||||
self.keys_pressed.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns if the key is pressed (`true`) or not pressed (`false`).
|
||||
pub fn key_pressed(&self, key: Key) -> bool {
|
||||
self.keys_pressed.contains(&key)
|
||||
/// Returns whether `key` is currently pressed.
|
||||
pub fn key_pressed(&self, key: &Key) -> bool {
|
||||
self.keys_pressed.contains(key)
|
||||
}
|
||||
|
||||
/// Updates [`Self::mouse_pressed`](field@Self::mouse_pressed) based on provided
|
||||
/// `button` and `is_pressed`.
|
||||
/// Marks `button` as pressed or released.
|
||||
/// Returns `true` if this press counts as a double-click (always `false` on release).
|
||||
pub fn set_mouse_pressed(&mut self, button: MouseButton, is_pressed: bool) -> bool {
|
||||
if is_pressed {
|
||||
self.mouse_pressed.insert(button);
|
||||
} else {
|
||||
if !is_pressed {
|
||||
self.mouse_pressed.remove(&button);
|
||||
return false;
|
||||
}
|
||||
|
||||
self.mouse_pressed.insert(button);
|
||||
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)
|
||||
let pos = self.cursor_pos;
|
||||
match self.mouse_last_pressed.entry(button) {
|
||||
std::collections::hash_map::Entry::Occupied(mut entry) => {
|
||||
let last = entry.get();
|
||||
let delta = (last.pos - pos).abs();
|
||||
let is_double = now.duration_since(last.time) < DOUBLE_CLICK_DURATION
|
||||
&& delta.x <= DOUBLE_CLICK_MOVE_THRESHOLD
|
||||
&& delta.y <= DOUBLE_CLICK_MOVE_THRESHOLD;
|
||||
if is_double {
|
||||
// Reset so that a triple-click is not treated as two consecutive
|
||||
// double-clicks; the next click starts a fresh timing window.
|
||||
entry.remove();
|
||||
} else {
|
||||
entry.insert(MousePressState { time: now, pos });
|
||||
}
|
||||
is_double
|
||||
}
|
||||
std::collections::hash_map::Entry::Vacant(vacant_entry) => {
|
||||
vacant_entry.insert(now);
|
||||
std::collections::hash_map::Entry::Vacant(entry) => {
|
||||
entry.insert(MousePressState { time: now, pos });
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if the `button` was pressed and no release has been seen.
|
||||
/// Returns whether `button` is currently pressed.
|
||||
pub fn mouse_pressed(&self, button: MouseButton) -> bool {
|
||||
self.mouse_pressed.contains(&button)
|
||||
}
|
||||
@@ -72,183 +93,16 @@ impl InputState {
|
||||
self.cursor_pos
|
||||
}
|
||||
|
||||
/// Sets [`Self::cursor_pos`] to the provided `pos`.
|
||||
/// Updates the cursor position.
|
||||
pub fn set_mouse_pos(&mut self, pos: LogicalPoint<f32>) {
|
||||
self.cursor_pos = pos;
|
||||
}
|
||||
|
||||
/// Clears all pressed keys, buttons, and modifier states. Used when the
|
||||
/// application loses focus to avoid keys being "stuck" on/pressed.
|
||||
/// Clears all pressed keys, buttons, and modifier states.
|
||||
pub fn clear_pressed(&mut self) {
|
||||
self.keys_pressed.clear();
|
||||
self.mouse_pressed.clear();
|
||||
self.mouse_last_pressed.clear();
|
||||
self.key_modifiers = ModifiersState::empty();
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempts to convert the provided string `s` to a [winit::keyboard::Key].
|
||||
/// Returns [None] if no matching Key found.
|
||||
pub fn str_as_key(s: &str) -> Option<Key> {
|
||||
Some(match s.to_uppercase().as_str() {
|
||||
"A" => Key::Character(SmolStr::new_static("A")),
|
||||
"B" => Key::Character(SmolStr::new_static("B")),
|
||||
"C" => Key::Character(SmolStr::new_static("C")),
|
||||
"D" => Key::Character(SmolStr::new_static("D")),
|
||||
"E" => Key::Character(SmolStr::new_static("E")),
|
||||
"F" => Key::Character(SmolStr::new_static("F")),
|
||||
"G" => Key::Character(SmolStr::new_static("G")),
|
||||
"H" => Key::Character(SmolStr::new_static("H")),
|
||||
"I" => Key::Character(SmolStr::new_static("I")),
|
||||
"J" => Key::Character(SmolStr::new_static("J")),
|
||||
"K" => Key::Character(SmolStr::new_static("K")),
|
||||
"L" => Key::Character(SmolStr::new_static("L")),
|
||||
"M" => Key::Character(SmolStr::new_static("M")),
|
||||
"N" => Key::Character(SmolStr::new_static("N")),
|
||||
"O" => Key::Character(SmolStr::new_static("O")),
|
||||
"P" => Key::Character(SmolStr::new_static("P")),
|
||||
"Q" => Key::Character(SmolStr::new_static("Q")),
|
||||
"R" => Key::Character(SmolStr::new_static("R")),
|
||||
"S" => Key::Character(SmolStr::new_static("S")),
|
||||
"T" => Key::Character(SmolStr::new_static("T")),
|
||||
"U" => Key::Character(SmolStr::new_static("U")),
|
||||
"V" => Key::Character(SmolStr::new_static("V")),
|
||||
"W" => Key::Character(SmolStr::new_static("W")),
|
||||
"X" => Key::Character(SmolStr::new_static("X")),
|
||||
"Y" => Key::Character(SmolStr::new_static("Y")),
|
||||
"Z" => Key::Character(SmolStr::new_static("Z")),
|
||||
|
||||
"0" => Key::Character(SmolStr::new_static("0")),
|
||||
"1" => Key::Character(SmolStr::new_static("1")),
|
||||
"2" => Key::Character(SmolStr::new_static("2")),
|
||||
"3" => Key::Character(SmolStr::new_static("3")),
|
||||
"4" => Key::Character(SmolStr::new_static("4")),
|
||||
"5" => Key::Character(SmolStr::new_static("5")),
|
||||
"6" => Key::Character(SmolStr::new_static("6")),
|
||||
"7" => Key::Character(SmolStr::new_static("7")),
|
||||
"8" => Key::Character(SmolStr::new_static("8")),
|
||||
"9" => Key::Character(SmolStr::new_static("9")),
|
||||
|
||||
"SHIFT" => Key::Named(NamedKey::Shift),
|
||||
"CTRL" => Key::Named(NamedKey::Control),
|
||||
"ALT" => Key::Named(NamedKey::Alt),
|
||||
|
||||
"F1" => Key::Named(NamedKey::F1),
|
||||
"F2" => Key::Named(NamedKey::F2),
|
||||
"F3" => Key::Named(NamedKey::F3),
|
||||
"F4" => Key::Named(NamedKey::F4),
|
||||
"F5" => Key::Named(NamedKey::F5),
|
||||
"F6" => Key::Named(NamedKey::F6),
|
||||
"F7" => Key::Named(NamedKey::F7),
|
||||
"F8" => Key::Named(NamedKey::F8),
|
||||
"F9" => Key::Named(NamedKey::F9),
|
||||
"F10" => Key::Named(NamedKey::F10),
|
||||
"F11" => Key::Named(NamedKey::F11),
|
||||
"F12" => Key::Named(NamedKey::F12),
|
||||
|
||||
" " => Key::Named(NamedKey::Space),
|
||||
"BACK" => Key::Named(NamedKey::Backspace),
|
||||
"TAB" => Key::Named(NamedKey::Tab),
|
||||
"RETURN" => Key::Named(NamedKey::Enter),
|
||||
"ESCAPE" => Key::Named(NamedKey::Escape),
|
||||
"PAUSE" => Key::Named(NamedKey::Pause),
|
||||
"PAGEUP" => Key::Named(NamedKey::PageUp),
|
||||
"PAGEDOWN" => Key::Named(NamedKey::PageDown),
|
||||
"END" => Key::Named(NamedKey::End),
|
||||
"HOME" => Key::Named(NamedKey::Home),
|
||||
"PRINTSCREEN" => Key::Named(NamedKey::PrintScreen),
|
||||
"INSERT" => Key::Named(NamedKey::Insert),
|
||||
"DELETE" => Key::Named(NamedKey::Delete),
|
||||
"UP" => Key::Named(NamedKey::ArrowUp),
|
||||
"DOWN" => Key::Named(NamedKey::ArrowDown),
|
||||
"LEFT" => Key::Named(NamedKey::ArrowLeft),
|
||||
"RIGHT" => Key::Named(NamedKey::ArrowRight),
|
||||
"NUMLOCK" => Key::Named(NamedKey::NumLock),
|
||||
"SCROLL" => Key::Named(NamedKey::ScrollLock),
|
||||
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Attempts to convert the provided [winit::keyboard::Key] `key` to a string
|
||||
/// representation that PoB recognizes.
|
||||
///
|
||||
/// Returns [None] if no matching string found.
|
||||
pub fn key_as_str(key: Key) -> Option<SmolStr> {
|
||||
Some(match key {
|
||||
Key::Character(ch) => {
|
||||
if ch == "=" {
|
||||
SmolStr::new("+") // This is what PoB does
|
||||
} else {
|
||||
ch
|
||||
}
|
||||
}
|
||||
Key::Named(named) => SmolStr::new(match named {
|
||||
NamedKey::Shift => "SHIFT",
|
||||
NamedKey::Control => "CTRL",
|
||||
NamedKey::Alt => "ALT",
|
||||
NamedKey::F1 => "F1",
|
||||
NamedKey::F2 => "F2",
|
||||
NamedKey::F3 => "F3",
|
||||
NamedKey::F4 => "F4",
|
||||
NamedKey::F5 => "F5",
|
||||
NamedKey::F6 => "F6",
|
||||
NamedKey::F7 => "F7",
|
||||
NamedKey::F8 => "F8",
|
||||
NamedKey::F9 => "F9",
|
||||
NamedKey::F10 => "F10",
|
||||
NamedKey::F11 => "F11",
|
||||
NamedKey::F12 => "F12",
|
||||
NamedKey::Space => " ",
|
||||
NamedKey::Backspace => "BACK",
|
||||
NamedKey::Tab => "TAB",
|
||||
NamedKey::Enter => "RETURN",
|
||||
NamedKey::Escape => "ESCAPE",
|
||||
NamedKey::Pause => "PAUSE",
|
||||
NamedKey::PageUp => "PAGEUP",
|
||||
NamedKey::PageDown => "PAGEDOWN",
|
||||
NamedKey::End => "END",
|
||||
NamedKey::Home => "HOME",
|
||||
NamedKey::PrintScreen => "PRINTSCREEN",
|
||||
NamedKey::Insert => "INSERT",
|
||||
NamedKey::Delete => "DELETE",
|
||||
NamedKey::ArrowUp => "UP",
|
||||
NamedKey::ArrowDown => "DOWN",
|
||||
NamedKey::ArrowLeft => "LEFT",
|
||||
NamedKey::ArrowRight => "RIGHT",
|
||||
NamedKey::NumLock => "NUMLOCK",
|
||||
NamedKey::ScrollLock => "SCROLL",
|
||||
_ => return None,
|
||||
}),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Attempts to convert the provided [&str] `s` from the PoB Lua Backend to a
|
||||
/// [MouseButton].
|
||||
///
|
||||
/// Returns [None] if no matching string found.
|
||||
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,
|
||||
})
|
||||
}
|
||||
|
||||
/// Attempts to convert the provided [MouseButton] to a [SmolStr] that the PoB Lua
|
||||
/// backend recognizes.
|
||||
///
|
||||
/// Returns [None] if no matching [MouseButton] was found.
|
||||
pub fn mousebutton_as_str(button: MouseButton) -> Option<SmolStr> {
|
||||
Some(match button {
|
||||
MouseButton::Left => SmolStr::new("LEFTBUTTON"),
|
||||
MouseButton::Right => SmolStr::new("RIGHTBUTTON"),
|
||||
MouseButton::Middle => SmolStr::new("MIDDLEBUTTON"),
|
||||
MouseButton::Back => SmolStr::new("MOUSE4"),
|
||||
MouseButton::Forward => SmolStr::new("MOUSE5"),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
+68
-46
@@ -1,28 +1,32 @@
|
||||
use crate::{
|
||||
app::AppState,
|
||||
args::Game,
|
||||
color::Srgba,
|
||||
dpi::{LogicalPoint, LogicalRect},
|
||||
fonts::{Alignment, FontStyle, LayoutJob},
|
||||
draw_commands::DrawCommand,
|
||||
fonts::{Alignment, FontStyle, Fonts, LayoutJob, LayoutToLogical},
|
||||
installer::download::{
|
||||
DownloadEvent, ExtractionRule, build_client, download_and_extract_tarball,
|
||||
download_file_to_disk, fetch_file_contents,
|
||||
},
|
||||
mode::{AppEvent, ModeFrameOutput, ModeTransition},
|
||||
renderer::primitives::{ClippedPrimitive, DrawPrimitive, TextPrimitive},
|
||||
renderer::textures::TextureId,
|
||||
stage::{StageEvent, StageFrameOutput, StageTransition},
|
||||
util::replace_in_matching_lines,
|
||||
window::WindowState,
|
||||
};
|
||||
use parley::{FontFamily, GenericFamily};
|
||||
use parley::{FontFamily, FontFamilyName, GenericFamily};
|
||||
use regex::Regex;
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
fs,
|
||||
path::Path,
|
||||
rc::Rc,
|
||||
sync::{
|
||||
LazyLock,
|
||||
Arc, LazyLock,
|
||||
mpsc::{self, Receiver, TryRecvError},
|
||||
},
|
||||
thread,
|
||||
};
|
||||
use winit::window::Window;
|
||||
|
||||
mod download;
|
||||
|
||||
@@ -39,16 +43,15 @@ enum Progress {
|
||||
Error(anyhow::Error),
|
||||
}
|
||||
|
||||
/// Execution mode in which initial installation of PoB is performed.
|
||||
///
|
||||
/// Immediately transitions into PoB mode if already installed.
|
||||
pub struct InstallMode {
|
||||
pub struct Installer {
|
||||
progress_rx: Option<Receiver<Progress>>,
|
||||
status: String,
|
||||
window_state: WindowState,
|
||||
fonts: Rc<RefCell<Fonts>>,
|
||||
}
|
||||
|
||||
impl InstallMode {
|
||||
pub fn new(game: Game) -> Self {
|
||||
impl Installer {
|
||||
pub fn new(game: Game, fonts: Rc<RefCell<Fonts>>) -> Self {
|
||||
let script_dir = game.script_dir();
|
||||
let (progress_tx, progress_rx) = mpsc::channel();
|
||||
|
||||
@@ -63,25 +66,28 @@ impl InstallMode {
|
||||
Self {
|
||||
progress_rx: Some(progress_rx),
|
||||
status: String::from("Starting installation..."),
|
||||
window_state: WindowState::default(),
|
||||
fonts,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn frame(&mut self, app_state: &mut AppState) -> anyhow::Result<ModeFrameOutput> {
|
||||
let primitives = self.draw_current_progress(app_state);
|
||||
pub fn frame(&self) -> anyhow::Result<StageFrameOutput> {
|
||||
let draw_commands = self.draw_current_progress();
|
||||
|
||||
Ok(ModeFrameOutput {
|
||||
primitives,
|
||||
Ok(StageFrameOutput {
|
||||
draw_commands,
|
||||
can_elide: false,
|
||||
should_continue: true,
|
||||
request_redraw: true,
|
||||
scale_factor: self.window_state.scale_factor(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn update(&mut self, _app_state: &mut AppState) -> anyhow::Result<Option<ModeTransition>> {
|
||||
pub fn update(&mut self) -> anyhow::Result<Option<StageTransition>> {
|
||||
if let Some(progress_rx) = &self.progress_rx {
|
||||
loop {
|
||||
match progress_rx.try_recv() {
|
||||
Ok(Progress::Status(msg)) => self.status = msg,
|
||||
Ok(Progress::Complete) => return Ok(Some(ModeTransition::PoB)),
|
||||
Ok(Progress::Complete) => return Ok(Some(StageTransition::ToMain)),
|
||||
Ok(Progress::Error(err)) => {
|
||||
return Err(anyhow::anyhow!("Installation failed: {err}"));
|
||||
}
|
||||
@@ -98,20 +104,30 @@ impl InstallMode {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub fn handle_event(
|
||||
&mut self,
|
||||
_app_state: &mut AppState,
|
||||
_event: AppEvent,
|
||||
) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
pub fn handle_event(&mut self, event: StageEvent) -> anyhow::Result<Option<StageTransition>> {
|
||||
match event {
|
||||
StageEvent::Resized(size) => self.window_state.size = size,
|
||||
StageEvent::ScaleFactorChanged(factor) => {
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
self.window_state.set_scale_factor(factor as f32);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn draw_current_progress(
|
||||
&self,
|
||||
app_state: &mut AppState,
|
||||
) -> Box<dyn Iterator<Item = ClippedPrimitive>> {
|
||||
pub fn set_window(&mut self, window: Arc<Window>) {
|
||||
self.window_state.set_window(window);
|
||||
}
|
||||
|
||||
fn draw_current_progress(&self) -> Vec<DrawCommand> {
|
||||
let mut draw_commands = Vec::new();
|
||||
|
||||
let screen_size = self.window_state.logical_size().cast::<f32>();
|
||||
let pos = LogicalPoint::new(screen_size.width / 2.0, screen_size.height / 2.0);
|
||||
|
||||
let mut job = LayoutJob::new(
|
||||
FontFamily::Generic(GenericFamily::SansSerif),
|
||||
FontFamily::Single(FontFamilyName::Generic(GenericFamily::SansSerif)),
|
||||
32.0,
|
||||
34.0,
|
||||
Some(Alignment::Center),
|
||||
@@ -121,19 +137,25 @@ impl InstallMode {
|
||||
|
||||
job.append(&self.status, Srgba::WHITE);
|
||||
|
||||
let layout = app_state.fonts.layout(job, app_state.window.scale_factor());
|
||||
let layout = self
|
||||
.fonts
|
||||
.borrow_mut()
|
||||
.layout(job, self.window_state.scale_factor());
|
||||
for glyph in &layout.glyphs {
|
||||
draw_commands.push(DrawCommand {
|
||||
positions: LayoutToLogical::new(pos.x, pos.y)
|
||||
.transform_box(&glyph.rect)
|
||||
.into(),
|
||||
uvs: glyph.uv.into(),
|
||||
color: glyph.color,
|
||||
// font atlas always lives at default texture ID
|
||||
texture_id: TextureId::default(),
|
||||
texture_layer_idx: glyph.layer_idx,
|
||||
clip_rect: LogicalRect::from_size(screen_size),
|
||||
});
|
||||
}
|
||||
|
||||
let screen_size = app_state.window.logical_size().cast::<f32>();
|
||||
let pos = LogicalPoint::new(screen_size.width / 2.0, screen_size.height / 2.0);
|
||||
|
||||
let primitive = TextPrimitive::new(pos, layout);
|
||||
|
||||
let clipped_primitive = ClippedPrimitive {
|
||||
clip_rect: LogicalRect::from_size(app_state.window.logical_size().cast()),
|
||||
primitive: DrawPrimitive::Text(primitive),
|
||||
};
|
||||
|
||||
Box::new(vec![clipped_primitive].into_iter())
|
||||
draw_commands
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,7 +242,7 @@ fn fetch_compatibility_info(
|
||||
// Beta versions have a non-semver suffix and are filtered out by the regex.
|
||||
Ok(compatibility_table
|
||||
.pairs::<String, String>()
|
||||
.filter_map(|p| p.ok())
|
||||
.filter_map(Result::ok)
|
||||
.filter(|(pob_version, _)| VERSION_RE.is_match(pob_version))
|
||||
.map(|(pob_version, min_req_rpob_ver)| VersionReq {
|
||||
pob_ver: pob_version,
|
||||
@@ -292,7 +314,7 @@ fn download_pob<P: AsRef<Path>>(
|
||||
];
|
||||
|
||||
download_and_extract_tarball(
|
||||
&client,
|
||||
client,
|
||||
pob_repo,
|
||||
&format!("v{pob_version}"),
|
||||
&rules,
|
||||
@@ -313,7 +335,7 @@ fn download_pob<P: AsRef<Path>>(
|
||||
format!("Downloading assets... ({})", format_bytes(downloaded))
|
||||
}
|
||||
DownloadEvent::Retrying { attempt } => {
|
||||
format!("Retrying... (Attempt {})", attempt)
|
||||
format!("Retrying... (Attempt {attempt})")
|
||||
}
|
||||
};
|
||||
let _ = progress_tx.send(Progress::Status(msg));
|
||||
@@ -391,7 +413,7 @@ fn is_higher_version(v1: &str, v2: &str) -> anyhow::Result<bool> {
|
||||
let parse_version = |v: &str| -> anyhow::Result<(u32, u32, u32)> {
|
||||
let caps = VERSION_RE
|
||||
.captures(v)
|
||||
.ok_or_else(|| anyhow::anyhow!("Invalid semver format: {}", v))?;
|
||||
.ok_or_else(|| anyhow::anyhow!("Invalid semver format: {v}"))?;
|
||||
|
||||
let major = caps[1].parse::<u32>().unwrap();
|
||||
let minor = caps[2].parse::<u32>().unwrap();
|
||||
|
||||
@@ -19,7 +19,7 @@ pub enum DownloadEvent {
|
||||
|
||||
/// Build a reqwest blocking client
|
||||
pub fn build_client() -> Result<Client, reqwest::Error> {
|
||||
Client::builder().timeout(Duration::from_secs(60)).build()
|
||||
Client::builder().timeout(Duration::from_mins(1)).build()
|
||||
}
|
||||
|
||||
// Rate-limit-aware GET.
|
||||
@@ -122,6 +122,9 @@ pub enum ExtractionRule {
|
||||
RewritePrefix { prefix: String, dest_dir: PathBuf },
|
||||
}
|
||||
|
||||
const CHUNK_SIZE: usize = 512 * 1024;
|
||||
const PROGRESS_INTERVAL: Duration = Duration::from_millis(50);
|
||||
|
||||
/// Download a GitHub release tarball and extract entries to specified destinations.
|
||||
pub fn download_and_extract_tarball(
|
||||
client: &Client,
|
||||
@@ -146,13 +149,11 @@ pub fn download_and_extract_tarball(
|
||||
let content_length = response.content_length();
|
||||
|
||||
let mut tmp_file = File::create(&tmp_path)?;
|
||||
const CHUNK_SIZE: usize = 512 * 1024;
|
||||
let mut chunk = vec![0u8; CHUNK_SIZE];
|
||||
let mut downloaded: u64 = 0;
|
||||
let mut body = response;
|
||||
|
||||
let mut last_progress = Instant::now();
|
||||
const PROGRESS_INTERVAL: Duration = Duration::from_millis(50);
|
||||
|
||||
loop {
|
||||
let n = body.read(&mut chunk)?;
|
||||
@@ -183,16 +184,7 @@ pub fn download_and_extract_tarball(
|
||||
let gz = GzDecoder::new(io::BufReader::new(tmp_file));
|
||||
let mut archive = Archive::new(gz);
|
||||
|
||||
let mut entries = archive.entries()?;
|
||||
|
||||
let root_prefix = {
|
||||
let first = entries
|
||||
.next()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "archive is empty"))??;
|
||||
first.path()?.to_string_lossy().into_owned()
|
||||
};
|
||||
|
||||
for entry_result in entries {
|
||||
for entry_result in archive.entries()? {
|
||||
let mut entry = entry_result?;
|
||||
let entry_path = entry.path()?.to_path_buf();
|
||||
let entry_str = entry_path.to_string_lossy();
|
||||
@@ -202,10 +194,9 @@ pub fn download_and_extract_tarball(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Strip root prefix before matching against rules
|
||||
let relative = match entry_str.strip_prefix(root_prefix.as_str()) {
|
||||
Some(r) => r,
|
||||
None => continue,
|
||||
// Strip root folder before matching against rules
|
||||
let Some((_, relative)) = entry_str.split_once('/') else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let dest: Option<PathBuf> = rules.iter().find_map(|rule| match rule {
|
||||
|
||||
-153
@@ -1,153 +0,0 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::{LogicalPoint, LogicalQuad, LogicalRect, LogicalSize, NormalizedQuad, NormalizedRect},
|
||||
fonts::Layout,
|
||||
renderer::{
|
||||
primitives::{
|
||||
ClippedPrimitive, DrawPrimitive, QuadPrimitive, QuadTexture, RectPrimitive,
|
||||
RectTexture, TextPrimitive,
|
||||
},
|
||||
textures::TextureId,
|
||||
},
|
||||
util::calculate_hash,
|
||||
};
|
||||
|
||||
/// 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.
|
||||
#[derive(Default)]
|
||||
pub struct Layers {
|
||||
layers: BTreeMap<(i32, i32), Vec<ClippedPrimitive>>,
|
||||
current_layer: (i32, i32),
|
||||
viewport: LogicalRect<f32>,
|
||||
current_draw_color: Srgba,
|
||||
}
|
||||
|
||||
impl Layers {
|
||||
pub fn reset(&mut self) {
|
||||
self.current_layer = (0, 0);
|
||||
self.layers.clear();
|
||||
self.current_draw_color = Srgba::TRANSPARENT;
|
||||
}
|
||||
|
||||
/// Consume primitives and return an iterator over them in drawing order.
|
||||
pub fn consume_layers(&mut self) -> Box<dyn Iterator<Item = ClippedPrimitive>> {
|
||||
let layers = std::mem::take(&mut self.layers);
|
||||
Box::new(layers.into_values().flatten())
|
||||
}
|
||||
|
||||
pub fn set_viewport(&mut self, viewport: LogicalRect<f32>) {
|
||||
self.viewport = viewport;
|
||||
}
|
||||
|
||||
pub fn set_viewport_from_size(&mut self, size: LogicalSize<u32>) {
|
||||
self.set_viewport(LogicalRect::from_size(size).cast());
|
||||
}
|
||||
|
||||
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 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.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.add_quad(primitive);
|
||||
}
|
||||
|
||||
pub fn draw_text(
|
||||
&mut self,
|
||||
position: LogicalPoint<f32>,
|
||||
layout: std::sync::Arc<Layout>,
|
||||
is_absolute_position: bool,
|
||||
) {
|
||||
let primitive = TextPrimitive::new(position, layout);
|
||||
self.add_text(primitive, is_absolute_position);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
pub fn get_hash(&self) -> u64 {
|
||||
calculate_hash(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::hash::Hash for Layers {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.layers.hash(state);
|
||||
}
|
||||
}
|
||||
-329
@@ -1,329 +0,0 @@
|
||||
use crate::{
|
||||
api::{self, get_callback},
|
||||
app::AppState,
|
||||
args::Args,
|
||||
fonts::Fonts,
|
||||
input::InputState,
|
||||
layers::Layers,
|
||||
pob::PoBState,
|
||||
renderer::textures::WrappedTextureManager,
|
||||
subscript::{NativeMultiValue, SubscriptManager, SubscriptResult, register_subscript_globals},
|
||||
util::change_working_directory,
|
||||
window::WindowState,
|
||||
};
|
||||
use clap::Parser;
|
||||
use mlua::{Function, Lua, Result as LuaResult, Table, ThreadStatus};
|
||||
use std::{
|
||||
cell::{Cell, RefCell},
|
||||
path::PathBuf,
|
||||
rc::Rc,
|
||||
};
|
||||
use winit::keyboard::SmolStr;
|
||||
|
||||
macro_rules! ctx_accessor {
|
||||
($field:ident: & $ty:ty) => {
|
||||
pub fn $field(&self) -> &$ty {
|
||||
let ptr = self.$field.get();
|
||||
assert!(!ptr.is_null());
|
||||
unsafe { &*ptr }
|
||||
}
|
||||
};
|
||||
|
||||
($field:ident: &mut $ty:ty) => {
|
||||
#[allow(clippy::mut_from_ref)]
|
||||
pub fn $field(&self) -> &mut $ty {
|
||||
let ptr = self.$field.get();
|
||||
assert!(!ptr.is_null());
|
||||
unsafe { &mut *ptr }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// A collection of pointers needed by the API funtions.
|
||||
///
|
||||
/// Before executing any lua code, we need to "plug" the references into
|
||||
/// the Context and "unplug" them afterwards.
|
||||
pub struct Context {
|
||||
window: Cell<*mut WindowState>,
|
||||
input: Cell<*const InputState>,
|
||||
fonts: Cell<*mut Fonts>,
|
||||
texture_manager: Cell<*mut WrappedTextureManager>,
|
||||
script_dir: Cell<*const PathBuf>,
|
||||
current_working_dir: Cell<*mut PathBuf>,
|
||||
layers: Cell<*mut Layers>,
|
||||
needs_restart: Cell<*mut bool>,
|
||||
should_exit: Cell<*mut bool>,
|
||||
is_dpi_aware: Cell<*mut bool>,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
pub fn new() -> &'static Self {
|
||||
Box::leak(Box::new(Self {
|
||||
window: Cell::new(std::ptr::null_mut()),
|
||||
input: Cell::new(std::ptr::null()),
|
||||
fonts: Cell::new(std::ptr::null_mut()),
|
||||
texture_manager: Cell::new(std::ptr::null_mut()),
|
||||
script_dir: Cell::new(std::ptr::null()),
|
||||
current_working_dir: Cell::new(std::ptr::null_mut()),
|
||||
layers: Cell::new(std::ptr::null_mut()),
|
||||
needs_restart: Cell::new(std::ptr::null_mut()),
|
||||
should_exit: Cell::new(std::ptr::null_mut()),
|
||||
is_dpi_aware: Cell::new(std::ptr::null_mut()),
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn set(&self, ctx: &mut PoBContext) {
|
||||
self.window.set(&mut ctx.app.window);
|
||||
self.input.set(&ctx.app.input);
|
||||
self.fonts.set(&mut ctx.app.fonts);
|
||||
self.texture_manager.set(&mut ctx.app.texture_manager);
|
||||
self.script_dir.set(&mut ctx.app.script_dir);
|
||||
self.current_working_dir
|
||||
.set(&mut ctx.pob.current_working_dir);
|
||||
self.layers.set(&mut ctx.pob.layers);
|
||||
self.needs_restart.set(&mut ctx.pob.needs_restart);
|
||||
self.should_exit.set(&mut ctx.app.should_exit);
|
||||
self.is_dpi_aware.set(&mut ctx.pob.is_dpi_aware);
|
||||
}
|
||||
|
||||
pub fn clear(&self) {
|
||||
self.window.set(std::ptr::null_mut());
|
||||
self.input.set(std::ptr::null());
|
||||
self.fonts.set(std::ptr::null_mut());
|
||||
self.texture_manager.set(std::ptr::null_mut());
|
||||
self.script_dir.set(std::ptr::null());
|
||||
self.current_working_dir.set(std::ptr::null_mut());
|
||||
self.layers.set(std::ptr::null_mut());
|
||||
self.needs_restart.set(std::ptr::null_mut());
|
||||
self.should_exit.set(std::ptr::null_mut());
|
||||
self.is_dpi_aware.set(std::ptr::null_mut());
|
||||
}
|
||||
|
||||
ctx_accessor!(window: &mut WindowState);
|
||||
ctx_accessor!(input: &InputState);
|
||||
ctx_accessor!(fonts: &mut Fonts);
|
||||
ctx_accessor!(texture_manager: &mut WrappedTextureManager);
|
||||
ctx_accessor!(script_dir: &PathBuf);
|
||||
ctx_accessor!(current_working_dir: &mut PathBuf);
|
||||
ctx_accessor!(layers: &mut Layers);
|
||||
ctx_accessor!(needs_restart: &mut bool);
|
||||
ctx_accessor!(should_exit: &mut bool);
|
||||
ctx_accessor!(is_dpi_aware: &mut bool);
|
||||
}
|
||||
|
||||
pub enum PoBEvent {
|
||||
Init,
|
||||
Exit,
|
||||
Frame,
|
||||
KeyDown(SmolStr, bool),
|
||||
KeyUp(SmolStr),
|
||||
Char(char),
|
||||
SubFinished {
|
||||
id: u64,
|
||||
return_values: NativeMultiValue,
|
||||
},
|
||||
SubError {
|
||||
id: u64,
|
||||
error: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Display for PoBEvent {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
PoBEvent::Init => write!(f, "Init"),
|
||||
PoBEvent::Exit => write!(f, "Exit"),
|
||||
PoBEvent::Frame => write!(f, "Frame"),
|
||||
PoBEvent::KeyDown(_, _) => write!(f, "KeyDown"),
|
||||
PoBEvent::KeyUp(_) => write!(f, "KeyUp"),
|
||||
PoBEvent::Char(_) => write!(f, "Char"),
|
||||
PoBEvent::SubFinished { .. } => write!(f, "SubFinished"),
|
||||
PoBEvent::SubError { .. } => write!(f, "SubError"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PoBContext<'a> {
|
||||
pub app: &'a mut AppState,
|
||||
pub pob: &'a mut PoBState,
|
||||
}
|
||||
|
||||
impl<'a> PoBContext<'a> {
|
||||
pub fn new(app_state: &'a mut AppState, pob_state: &'a mut PoBState) -> Self {
|
||||
Self {
|
||||
app: app_state,
|
||||
pob: pob_state,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lua instance that runs the PoB application code and manages subscripts.
|
||||
pub struct LuaInstance {
|
||||
lua: Lua,
|
||||
subscript_manager: Rc<RefCell<SubscriptManager>>,
|
||||
}
|
||||
|
||||
impl LuaInstance {
|
||||
pub fn new(script_dir: &PathBuf) -> anyhow::Result<Self> {
|
||||
let subscript_manager = Rc::new(RefCell::new(SubscriptManager::new(script_dir.to_owned())));
|
||||
|
||||
let lua = Self::create_lua_state(script_dir)?;
|
||||
register_subscript_globals(&lua, &subscript_manager)?;
|
||||
|
||||
Ok(Self {
|
||||
lua,
|
||||
subscript_manager,
|
||||
})
|
||||
}
|
||||
|
||||
fn create_lua_state(script_dir: &PathBuf) -> LuaResult<Lua> {
|
||||
// SAFETY: use `unsafe_new` to allow loading of C modules
|
||||
let lua = unsafe { Lua::unsafe_new() };
|
||||
|
||||
// expose import url to lua
|
||||
let args = Args::parse();
|
||||
let args_table = lua.create_sequence_from(std::iter::once(args.import_url))?;
|
||||
lua.globals().set("arg", args_table)?;
|
||||
|
||||
Self::register_package_paths(&lua, script_dir)?;
|
||||
|
||||
// register context
|
||||
let ctx = Context::new();
|
||||
lua.set_app_data(ctx);
|
||||
|
||||
// register callbacks
|
||||
api::register_globals(&lua)?;
|
||||
|
||||
Ok(lua)
|
||||
}
|
||||
|
||||
/// Loads and executes PoB's Launch.lua script
|
||||
pub fn launch(&self, pob_ctx: &mut PoBContext) -> LuaResult<()> {
|
||||
let ctx = self.lua.app_data_ref::<&'static Context>().unwrap();
|
||||
ctx.set(pob_ctx);
|
||||
|
||||
let script_dir = pob_ctx.app.script_dir.as_path();
|
||||
change_working_directory(script_dir)?;
|
||||
self.load(script_dir.join("Launch.lua")).exec()?;
|
||||
|
||||
ctx.clear();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn restart(&mut self, ctx: &mut PoBContext) -> LuaResult<()> {
|
||||
self.lua = Self::create_lua_state(&ctx.app.script_dir)?;
|
||||
register_subscript_globals(&self.lua, &self.subscript_manager)?;
|
||||
self.launch(ctx)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run functions for subscripts and handle their completion/failure.
|
||||
pub fn handle_subscripts(&self, pob_ctx: &mut PoBContext) {
|
||||
profiling::scope!("handle_subscripts");
|
||||
|
||||
let ctx = self.lua.app_data_ref::<&'static Context>().unwrap();
|
||||
ctx.set(pob_ctx);
|
||||
let subscript_events = self.subscript_manager.borrow_mut().process(self);
|
||||
ctx.clear();
|
||||
|
||||
// Handle finished/errored subscripts.
|
||||
for event in subscript_events {
|
||||
match event {
|
||||
SubscriptResult::SubscriptFinished { id, return_values } => {
|
||||
self.handle_event(PoBEvent::SubFinished { id, return_values }, pob_ctx)
|
||||
.unwrap();
|
||||
}
|
||||
SubscriptResult::SubscriptError { id, error } => {
|
||||
self.handle_event(PoBEvent::SubError { id, error }, pob_ctx)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_running_subscripts(&self) -> bool {
|
||||
self.subscript_manager.borrow().has_running_subscripts()
|
||||
}
|
||||
|
||||
pub fn has_active_coroutine(&self) -> bool {
|
||||
self.get_coroutines().is_ok_and(|coroutines| {
|
||||
coroutines.pairs::<mlua::Thread, bool>().any(|pair| {
|
||||
pair.is_ok_and(|(thread, _)| {
|
||||
matches!(
|
||||
thread.status(),
|
||||
ThreadStatus::Resumable | ThreadStatus::Running
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn get_coroutines(&self) -> LuaResult<Table> {
|
||||
let coroutine_module: Table = self.lua.globals().get("coroutine")?;
|
||||
let list_func: Function = coroutine_module.get("_list")?;
|
||||
list_func.call::<Table>(())
|
||||
}
|
||||
|
||||
pub fn can_exit(&self, pob_ctx: &mut PoBContext) -> bool {
|
||||
let ctx = self.lua.app_data_ref::<&'static Context>().unwrap();
|
||||
ctx.set(pob_ctx);
|
||||
|
||||
let can_exit = get_callback(&self.lua, "CanExit")
|
||||
.and_then(|f| f.call(()))
|
||||
.unwrap_or(true);
|
||||
|
||||
ctx.clear();
|
||||
can_exit
|
||||
}
|
||||
|
||||
pub fn handle_event(&self, event: PoBEvent, pob_ctx: &mut PoBContext) -> LuaResult<()> {
|
||||
profiling::scope!("handle_event", format!("{}", event));
|
||||
|
||||
// "Plug" references into context
|
||||
let ctx = self.lua.app_data_ref::<&'static Context>().unwrap();
|
||||
ctx.set(pob_ctx);
|
||||
|
||||
// Call event handler in PoB application code
|
||||
let handler_result = match event {
|
||||
PoBEvent::Init => get_callback(&self.lua, "OnInit")?.call::<()>(()),
|
||||
PoBEvent::Exit => get_callback(&self.lua, "OnExit")?.call::<()>(()),
|
||||
PoBEvent::Frame => get_callback(&self.lua, "OnFrame")?.call::<()>(()),
|
||||
PoBEvent::KeyDown(key, double_click) => {
|
||||
get_callback(&self.lua, "OnKeyDown")?.call::<()>((key.as_str(), double_click))
|
||||
}
|
||||
PoBEvent::KeyUp(key) => get_callback(&self.lua, "OnKeyUp")?.call::<()>(key.as_str()),
|
||||
PoBEvent::Char(ch) => get_callback(&self.lua, "OnChar")?.call::<()>(ch),
|
||||
PoBEvent::SubFinished { id, return_values } => {
|
||||
get_callback(&self.lua, "OnSubFinished")?.call::<()>((id, return_values))
|
||||
}
|
||||
PoBEvent::SubError { id, error } => {
|
||||
get_callback(&self.lua, "OnSubError")?.call::<()>((id, error))
|
||||
}
|
||||
};
|
||||
|
||||
// "Unplug" references from context
|
||||
ctx.clear();
|
||||
|
||||
handler_result
|
||||
}
|
||||
|
||||
/// Adds "${script_dir}/lua" to package path
|
||||
pub fn register_package_paths(lua: &Lua, script_dir: &PathBuf) -> LuaResult<()> {
|
||||
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)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for LuaInstance {
|
||||
type Target = Lua;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.lua
|
||||
}
|
||||
}
|
||||
+17
-10
@@ -3,24 +3,23 @@ use clap::Parser;
|
||||
use std::path::{Path, PathBuf};
|
||||
use winit::event_loop::EventLoop;
|
||||
|
||||
mod api;
|
||||
mod app;
|
||||
mod args;
|
||||
mod batcher;
|
||||
mod clipboard;
|
||||
mod color;
|
||||
mod dpi;
|
||||
mod draw_commands;
|
||||
mod fonts;
|
||||
mod gfx;
|
||||
mod input;
|
||||
mod installer;
|
||||
mod layers;
|
||||
mod lua;
|
||||
mod math;
|
||||
mod mode;
|
||||
mod pob;
|
||||
mod renderer;
|
||||
mod subscript;
|
||||
mod stage;
|
||||
mod util;
|
||||
mod uv;
|
||||
mod window;
|
||||
mod worker_pool;
|
||||
|
||||
@@ -59,11 +58,19 @@ fn find_nearby_launch_script() -> Option<PathBuf> {
|
||||
}
|
||||
|
||||
for candidate in candidates {
|
||||
if candidate.try_exists().is_ok_and(|exists| exists) {
|
||||
if let Some(Ok(candidate)) = candidate.parent().map(Path::canonicalize) {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
if candidate.try_exists().is_ok_and(|exists| exists)
|
||||
&& let Ok(candidate) = candidate.canonicalize()
|
||||
&& let Some(dir) = candidate.parent()
|
||||
{
|
||||
// remove the windows extended length path syntax as it contains a
|
||||
// question mark which will interfere with lua's require()
|
||||
const WINDOWS_PREFIX: &str = r#"\\?\"#;
|
||||
let path_str = dir.display().to_string();
|
||||
return match path_str.strip_prefix(WINDOWS_PREFIX) {
|
||||
Some(stripped) => Some(PathBuf::from(stripped)),
|
||||
None => Some(dir.to_path_buf()),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
None
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
pub use euclid::Box2D as Rect;
|
||||
pub use euclid::Point2D as Point;
|
||||
pub use euclid::Scale;
|
||||
pub use euclid::Size2D as Size;
|
||||
pub use euclid::Translation2D as Translation;
|
||||
pub use euclid::Vector2D as Vector;
|
||||
pub use quad::Quad;
|
||||
|
||||
|
||||
+44
-7
@@ -1,5 +1,6 @@
|
||||
use crate::math::{Point, Size, Vector};
|
||||
use crate::math::{Corners, Point, Rect, Size, Vector};
|
||||
use bytemuck::{Pod, Zeroable};
|
||||
use euclid::approxord::{max, min};
|
||||
use euclid::num::Zero;
|
||||
use std::fmt;
|
||||
use std::hash::Hash;
|
||||
@@ -51,10 +52,10 @@ impl<T: fmt::Debug, U> fmt::Debug for Quad<T, U> {
|
||||
impl<T: Default, U> Default for Quad<T, U> {
|
||||
fn default() -> Self {
|
||||
Self::new(
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
Point::default(),
|
||||
Point::default(),
|
||||
Point::default(),
|
||||
Point::default(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -92,7 +93,7 @@ where
|
||||
where
|
||||
T: Zero,
|
||||
{
|
||||
Quad {
|
||||
Self {
|
||||
p0: Point::zero(),
|
||||
p1: Point::new(size.width, Zero::zero()),
|
||||
p2: Point::new(size.width, size.height),
|
||||
@@ -107,7 +108,7 @@ where
|
||||
{
|
||||
/// Constructor, setting all points to zero.
|
||||
pub fn zero() -> Self {
|
||||
Quad::new(Point::zero(), Point::zero(), Point::zero(), Point::zero())
|
||||
Self::new(Point::zero(), Point::zero(), Point::zero(), Point::zero())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,3 +122,39 @@ where
|
||||
Self::new(self.p0 + by, self.p1 + by, self.p2 + by, self.p3 + by)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> From<Rect<T, U>> for Quad<T, U>
|
||||
where
|
||||
T: Copy,
|
||||
{
|
||||
fn from(value: Rect<T, U>) -> Self {
|
||||
Self::new(
|
||||
value.top_left(),
|
||||
value.top_right(),
|
||||
value.bottom_right(),
|
||||
value.bottom_left(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, U> Quad<T, U>
|
||||
where
|
||||
T: Copy + PartialOrd,
|
||||
{
|
||||
/// Returns the axis-aligned bounding box containing this quad.
|
||||
#[inline]
|
||||
pub fn aabb(&self) -> Rect<T, U> {
|
||||
let min_x = min(min(min(self.p0.x, self.p1.x), self.p2.x), self.p3.x);
|
||||
let max_x = max(max(max(self.p0.x, self.p1.x), self.p2.x), self.p3.x);
|
||||
let min_y = min(min(min(self.p0.y, self.p1.y), self.p2.y), self.p3.y);
|
||||
let max_y = max(max(max(self.p0.y, self.p1.y), self.p2.y), self.p3.y);
|
||||
|
||||
Rect::new(Point::new(min_x, min_y), Point::new(max_x, max_y))
|
||||
}
|
||||
|
||||
/// Tests intersection between this quad's AABB and a rectangle.
|
||||
#[inline]
|
||||
pub fn aabb_intersects_rect(&self, rect: &Rect<T, U>) -> bool {
|
||||
self.aabb().intersects(rect)
|
||||
}
|
||||
}
|
||||
-75
@@ -1,75 +0,0 @@
|
||||
use crate::{
|
||||
app::AppState, installer::InstallMode, pob::PoBMode, renderer::primitives::ClippedPrimitive,
|
||||
};
|
||||
use winit::{event::MouseButton, keyboard::Key};
|
||||
|
||||
pub enum AppEvent {
|
||||
KeyDown {
|
||||
key: Key,
|
||||
},
|
||||
KeyUp {
|
||||
key: Key,
|
||||
},
|
||||
MouseDown {
|
||||
button: MouseButton,
|
||||
is_double_click: bool,
|
||||
},
|
||||
MouseUp {
|
||||
button: MouseButton,
|
||||
},
|
||||
MouseWheel {
|
||||
delta: f32,
|
||||
},
|
||||
CharacterInput {
|
||||
ch: char,
|
||||
},
|
||||
Exit,
|
||||
}
|
||||
|
||||
/// Represents the transition to another mode
|
||||
pub enum ModeTransition {
|
||||
PoB,
|
||||
}
|
||||
|
||||
pub struct ModeFrameOutput {
|
||||
pub primitives: Box<dyn Iterator<Item = ClippedPrimitive>>,
|
||||
pub can_elide: bool,
|
||||
/// Indicates that this should be redrawn again next frame even if user is not interacting with
|
||||
/// window
|
||||
pub should_continue: bool,
|
||||
}
|
||||
|
||||
pub enum AppMode {
|
||||
Install(InstallMode),
|
||||
PoB(PoBMode),
|
||||
}
|
||||
|
||||
impl AppMode {
|
||||
pub fn frame(&mut self, state: &mut AppState) -> anyhow::Result<ModeFrameOutput> {
|
||||
match self {
|
||||
AppMode::Install(mode) => mode.frame(state),
|
||||
AppMode::PoB(mode) => mode.frame(state),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(&mut self, state: &mut AppState) -> anyhow::Result<Option<ModeTransition>> {
|
||||
match self {
|
||||
AppMode::Install(mode) => mode.update(state),
|
||||
AppMode::PoB(mode) => mode.update(state),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_event(&mut self, state: &mut AppState, event: AppEvent) -> anyhow::Result<()> {
|
||||
match self {
|
||||
AppMode::Install(mode) => mode.handle_event(state, event),
|
||||
AppMode::PoB(mode) => mode.handle_event(state, event),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_exit(&mut self, state: &mut AppState) -> bool {
|
||||
match self {
|
||||
AppMode::Install(_) => true,
|
||||
AppMode::PoB(mode) => mode.can_exit(state),
|
||||
}
|
||||
}
|
||||
}
|
||||
+346
-127
@@ -1,160 +1,379 @@
|
||||
use crate::{
|
||||
app::AppState,
|
||||
dpi::{LogicalRect, LogicalSize},
|
||||
input::{key_as_str, mousebutton_as_str},
|
||||
layers::Layers,
|
||||
lua::{LuaInstance, PoBContext, PoBEvent},
|
||||
mode::{AppEvent, ModeFrameOutput, ModeTransition},
|
||||
use clap::Parser;
|
||||
use mlua::{
|
||||
AppDataRef, AppDataRefMut, Function, Lua, Result as LuaResult, Table, thread::ThreadStatus,
|
||||
};
|
||||
use std::path::PathBuf;
|
||||
use winit::window::Window;
|
||||
|
||||
pub struct PoBState {
|
||||
pub layers: Layers,
|
||||
use crate::{
|
||||
args::Args,
|
||||
dpi::{PhysicalPoint, ScaleFactor},
|
||||
draw_commands::DrawCommandRecorder,
|
||||
fonts::Fonts,
|
||||
input::InputState,
|
||||
pob::subscript::{NativeMultiValue, SubscriptEvent, SubscriptManager},
|
||||
renderer::textures::TextureManager,
|
||||
stage::{StageEvent, StageFrameOutput, StageTransition},
|
||||
util::{append_lua_package_dir, change_working_directory, load_lua_file},
|
||||
window::WindowState,
|
||||
};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
path::{Path, PathBuf},
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
mod api;
|
||||
mod modules;
|
||||
mod subscript;
|
||||
|
||||
/// Holds all state shared between Rust and the API functions exposed to Lua.
|
||||
///
|
||||
/// Accessed via `lua.app_data_ref::<Context>()`/`app_data_mut::<Context>()`.
|
||||
pub struct Context {
|
||||
pub input_state: InputState,
|
||||
pub window_state: WindowState,
|
||||
/// Collects draw commands issued by API functions
|
||||
pub recorder: DrawCommandRecorder,
|
||||
pub fonts: Rc<RefCell<Fonts>>,
|
||||
pub texture_manager: Rc<RefCell<TextureManager>>,
|
||||
/// Directory containing the PoB Lua scripts
|
||||
pub script_dir: PathBuf,
|
||||
pub current_working_dir: PathBuf,
|
||||
/// Set by Lua to request a full Lua restart
|
||||
pub needs_restart: bool,
|
||||
/// Set by Lua to request application shutdown
|
||||
pub should_exit: bool,
|
||||
pub is_dpi_aware: bool,
|
||||
}
|
||||
|
||||
/// Execution mode in which PoB's application code is run.
|
||||
impl Context {
|
||||
pub fn new(
|
||||
script_dir: &Path,
|
||||
fonts: Rc<RefCell<Fonts>>,
|
||||
texture_manager: Rc<RefCell<TextureManager>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
input_state: InputState::default(),
|
||||
window_state: WindowState::default(),
|
||||
recorder: DrawCommandRecorder::default(),
|
||||
fonts,
|
||||
texture_manager,
|
||||
script_dir: script_dir.to_owned(),
|
||||
current_working_dir: PathBuf::default(),
|
||||
needs_restart: false,
|
||||
should_exit: false,
|
||||
is_dpi_aware: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resizes the recorder's viewport to match the current window size.
|
||||
/// Call at the start of every frame before any draw calls are recorded.
|
||||
pub fn set_recorder_viewport_to_window_size(&mut self) {
|
||||
self.recorder
|
||||
.set_viewport_from_size(self.window_state.logical_size());
|
||||
}
|
||||
|
||||
fn set_mouse_pos(&mut self, pos: PhysicalPoint<f32>) {
|
||||
self.input_state
|
||||
.set_mouse_pos(pos / self.window_state.scale_factor());
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the interface to Path of Building's Lua code.
|
||||
///
|
||||
/// It forwards app events to PoB's application event handlers and outputs
|
||||
/// the draw primitives created by PoB each frame.
|
||||
pub struct PoBMode {
|
||||
lua_instance: LuaInstance,
|
||||
state: PoBState,
|
||||
/// Exposes API, forwards events to Path of Building's event handlers, and manages subscripts.
|
||||
pub struct PathOfBuilding {
|
||||
lua: Lua,
|
||||
/// Hash of the previous frame's draw commands. Used to skip rerendering identical frames.
|
||||
previous_layers_hash: u64,
|
||||
}
|
||||
|
||||
impl PoBMode {
|
||||
pub fn new(app_state: &mut AppState) -> anyhow::Result<Self> {
|
||||
let mut state = PoBState {
|
||||
layers: Layers::default(),
|
||||
current_working_dir: PathBuf::default(),
|
||||
needs_restart: false,
|
||||
is_dpi_aware: false,
|
||||
};
|
||||
impl PathOfBuilding {
|
||||
pub fn new(
|
||||
script_dir: &Path,
|
||||
fonts: Rc<RefCell<Fonts>>,
|
||||
texture_manager: Rc<RefCell<TextureManager>>,
|
||||
) -> anyhow::Result<Self> {
|
||||
let ctx = Context::new(script_dir, fonts, texture_manager);
|
||||
let lua = Self::create_lua(ctx, SubscriptManager::default())?;
|
||||
|
||||
let lua_instance = LuaInstance::new(&app_state.script_dir)?;
|
||||
|
||||
let mut pob_ctx = PoBContext::new(app_state, &mut state);
|
||||
lua_instance.launch(&mut pob_ctx)?;
|
||||
lua_instance.handle_event(PoBEvent::Init, &mut pob_ctx)?;
|
||||
Self::launch(&lua, script_dir)?;
|
||||
|
||||
Ok(Self {
|
||||
lua_instance,
|
||||
state,
|
||||
lua,
|
||||
previous_layers_hash: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn frame(&mut self, app_state: &mut AppState) -> anyhow::Result<ModeFrameOutput> {
|
||||
profiling::scope!("frame");
|
||||
/// Builds a `Lua` state with package paths, context, and all API functions registered.
|
||||
fn create_lua(ctx: Context, subscript_manager: SubscriptManager) -> LuaResult<Lua> {
|
||||
// `unsafe_new` needed to allow loading of C modules
|
||||
let lua = unsafe { Lua::unsafe_new() };
|
||||
append_lua_package_dir(&lua, &ctx.script_dir.join("lua"))?;
|
||||
|
||||
// reset layers and viewport
|
||||
self.state.layers.reset();
|
||||
self.reset_viewport(app_state.window.logical_size());
|
||||
// expose import url to lua
|
||||
let args = Args::parse();
|
||||
let args_table = lua.create_sequence_from(std::iter::once(args.import_url))?;
|
||||
lua.globals().set("arg", args_table)?;
|
||||
|
||||
let mut ctx = PoBContext::new(app_state, &mut self.state);
|
||||
// make context and subscript manager accessible to API functions
|
||||
lua.set_app_data(ctx);
|
||||
lua.set_app_data(subscript_manager);
|
||||
|
||||
// handle subscripts
|
||||
self.lua_instance.handle_subscripts(&mut ctx);
|
||||
// register API functions
|
||||
api::register_globals(&lua)?;
|
||||
|
||||
// run PoB's draw code.
|
||||
// this will "fill up" up the layers with draw primitives
|
||||
self.lua_instance.handle_event(PoBEvent::Frame, &mut ctx)?;
|
||||
// register modules
|
||||
modules::register(&lua)?;
|
||||
|
||||
// check if draw prmitives are identical to primitives from last frame
|
||||
let layers_hash = self.state.layers.get_hash();
|
||||
let identical = layers_hash == self.previous_layers_hash;
|
||||
self.previous_layers_hash = layers_hash;
|
||||
|
||||
let has_active_subscript = self.lua_instance.has_running_subscripts();
|
||||
let has_active_coroutine = self.lua_instance.has_active_coroutine();
|
||||
let should_continue = has_active_subscript || has_active_coroutine;
|
||||
|
||||
Ok(ModeFrameOutput {
|
||||
primitives: self.state.layers.consume_layers(),
|
||||
can_elide: identical,
|
||||
should_continue,
|
||||
})
|
||||
Ok(lua)
|
||||
}
|
||||
|
||||
pub fn update(&mut self, app_state: &mut AppState) -> anyhow::Result<Option<ModeTransition>> {
|
||||
if self.state.needs_restart {
|
||||
let mut ctx = PoBContext::new(app_state, &mut self.state);
|
||||
self.lua_instance.restart(&mut ctx)?;
|
||||
self.lua_instance.handle_event(PoBEvent::Init, &mut ctx)?;
|
||||
self.state.needs_restart = false;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub fn handle_event(
|
||||
&mut self,
|
||||
app_state: &mut AppState,
|
||||
event: AppEvent,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut ctx = PoBContext::new(app_state, &mut self.state);
|
||||
|
||||
match event {
|
||||
AppEvent::KeyDown { key } => {
|
||||
if let Some(key_string) = key_as_str(key) {
|
||||
let pob_event = PoBEvent::KeyDown(key_string, false);
|
||||
self.lua_instance.handle_event(pob_event, &mut ctx)?;
|
||||
}
|
||||
}
|
||||
AppEvent::KeyUp { key } => {
|
||||
if let Some(key_string) = key_as_str(key) {
|
||||
let pob_event = PoBEvent::KeyUp(key_string);
|
||||
self.lua_instance.handle_event(pob_event, &mut ctx)?;
|
||||
}
|
||||
}
|
||||
AppEvent::MouseDown {
|
||||
button,
|
||||
is_double_click,
|
||||
} => {
|
||||
if let Some(button_string) = mousebutton_as_str(button) {
|
||||
let pob_event = PoBEvent::KeyDown(button_string, is_double_click);
|
||||
self.lua_instance.handle_event(pob_event, &mut ctx)?;
|
||||
}
|
||||
}
|
||||
AppEvent::MouseUp { button } => {
|
||||
if let Some(button_string) = mousebutton_as_str(button) {
|
||||
let pob_event = PoBEvent::KeyUp(button_string);
|
||||
self.lua_instance.handle_event(pob_event, &mut ctx)?;
|
||||
}
|
||||
}
|
||||
AppEvent::MouseWheel { delta } => {
|
||||
if delta > 0.0 {
|
||||
self.lua_instance
|
||||
.handle_event(PoBEvent::KeyDown("WHEELUP".into(), false), &mut ctx)?;
|
||||
self.lua_instance
|
||||
.handle_event(PoBEvent::KeyUp("WHEELUP".into()), &mut ctx)?;
|
||||
} else if delta < 0.0 {
|
||||
self.lua_instance
|
||||
.handle_event(PoBEvent::KeyDown("WHEELDOWN".into(), false), &mut ctx)?;
|
||||
self.lua_instance
|
||||
.handle_event(PoBEvent::KeyUp("WHEELDOWN".into()), &mut ctx)?;
|
||||
}
|
||||
}
|
||||
AppEvent::CharacterInput { ch } => {
|
||||
let ch = if ch.is_ascii() { ch } else { '?' };
|
||||
self.lua_instance
|
||||
.handle_event(PoBEvent::Char(ch), &mut ctx)?;
|
||||
}
|
||||
AppEvent::Exit => self.lua_instance.handle_event(PoBEvent::Exit, &mut ctx)?,
|
||||
/// Loads and runs `Launch.lua`, then calls PoB's `OnInit` handler.
|
||||
fn launch(lua: &Lua, script_dir: &Path) -> LuaResult<()> {
|
||||
change_working_directory(script_dir)?;
|
||||
load_lua_file(lua, &script_dir.join("Launch.lua"))?.exec()?;
|
||||
{
|
||||
profiling::scope!("OnInit");
|
||||
api::on_init(lua)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn can_exit(&mut self, app_state: &mut AppState) -> bool {
|
||||
let mut ctx = PoBContext::new(app_state, &mut self.state);
|
||||
self.lua_instance.can_exit(&mut ctx)
|
||||
/// Rebuilds the Lua instance from scratch. Preserves the current `Context`.
|
||||
fn restart(&mut self) -> LuaResult<()> {
|
||||
// move context and subscript manager out of current lua instance
|
||||
let mut ctx = self.lua.remove_app_data::<Context>().unwrap();
|
||||
let script_dir = ctx.script_dir.clone();
|
||||
ctx.needs_restart = false;
|
||||
|
||||
let subscript_manager = self
|
||||
.lua
|
||||
.remove_app_data::<SubscriptManager>()
|
||||
.unwrap_or_default();
|
||||
|
||||
// and move both into the new instance
|
||||
self.lua = Self::create_lua(ctx, subscript_manager)?;
|
||||
Self::launch(&self.lua, &script_dir)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reset_viewport(&mut self, size: LogicalSize<u32>) {
|
||||
self.state
|
||||
.layers
|
||||
.set_viewport(LogicalRect::from_size(size).cast());
|
||||
/// Handles events by updating context and forwarding them to PoB's event handlers.
|
||||
pub fn handle_event(&self, event: StageEvent) -> anyhow::Result<Option<StageTransition>> {
|
||||
match event {
|
||||
StageEvent::KeyDown { key } => {
|
||||
self.ctx_mut().input_state.set_key_pressed(&key, true);
|
||||
api::on_key_down(&self.lua, &api::Input::Keyboard(key), false)?;
|
||||
}
|
||||
StageEvent::KeyUp { key } => {
|
||||
self.ctx_mut().input_state.set_key_pressed(&key, false);
|
||||
api::on_key_up(&self.lua, &api::Input::Keyboard(key))?;
|
||||
}
|
||||
StageEvent::ModifiersChanged { state } => {
|
||||
self.ctx_mut().input_state.key_modifiers = state;
|
||||
}
|
||||
StageEvent::CharacterInput { ch } => {
|
||||
let ch = if ch.is_ascii() { ch } else { '?' };
|
||||
api::on_char(&self.lua, ch)?;
|
||||
}
|
||||
StageEvent::MouseDown { button } => {
|
||||
let is_double_click = self.ctx_mut().input_state.set_mouse_pressed(button, true);
|
||||
api::on_key_down(&self.lua, &api::Input::Mouse(button), is_double_click)?;
|
||||
}
|
||||
StageEvent::MouseUp { button } => {
|
||||
self.ctx_mut().input_state.set_mouse_pressed(button, false);
|
||||
api::on_key_up(&self.lua, &api::Input::Mouse(button))?;
|
||||
}
|
||||
StageEvent::MouseWheel { delta } => {
|
||||
if delta > 0.0 {
|
||||
api::on_key_down(&self.lua, &api::Input::WheelUp, false)?;
|
||||
api::on_key_up(&self.lua, &api::Input::WheelUp)?;
|
||||
} else if delta < 0.0 {
|
||||
api::on_key_down(&self.lua, &api::Input::WheelDown, false)?;
|
||||
api::on_key_up(&self.lua, &api::Input::WheelDown)?;
|
||||
}
|
||||
}
|
||||
StageEvent::Exit => api::on_exit(&self.lua)?,
|
||||
StageEvent::MouseMoved { pos } => {
|
||||
self.ctx_mut().set_mouse_pos(pos);
|
||||
}
|
||||
StageEvent::Resized(size) => {
|
||||
self.ctx_mut().window_state.size = size;
|
||||
}
|
||||
StageEvent::ScaleFactorChanged(scale_factor) => {
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
let mut ctx = self.ctx_mut();
|
||||
ctx.window_state.set_scale_factor(scale_factor as f32);
|
||||
ctx.fonts
|
||||
.borrow_mut()
|
||||
.preload_common_characters(16.0, ScaleFactor::new(scale_factor as f32));
|
||||
}
|
||||
StageEvent::FocusChanged(focused) => {
|
||||
self.ctx_mut().window_state.is_focused = focused;
|
||||
}
|
||||
StageEvent::HoverChanged(hovered) => {
|
||||
self.ctx_mut().window_state.is_hovered = hovered;
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Applies any pending restart/exit requests set by Lua via `Context`.
|
||||
/// Should be called once before `frame()`.
|
||||
pub fn update(&mut self) -> anyhow::Result<Option<StageTransition>> {
|
||||
let (needs_restart, should_exit) = {
|
||||
let ctx = self.ctx();
|
||||
(ctx.needs_restart, ctx.should_exit)
|
||||
};
|
||||
|
||||
if needs_restart {
|
||||
self.restart()?;
|
||||
}
|
||||
|
||||
if should_exit {
|
||||
return Ok(Some(StageTransition::ToShutdown));
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Runs one PoB frame.
|
||||
///
|
||||
/// Resets the draw command recorder, advances subscripts, calls `OnFrame` (which issues draw
|
||||
/// calls via the API), then collects the resulting draw commands.
|
||||
///
|
||||
/// Returns `can_elide: true` if the output is identical to the previous frame, letting the
|
||||
/// caller skip rerendering.
|
||||
pub fn frame(&mut self) -> anyhow::Result<StageFrameOutput> {
|
||||
profiling::scope!("frame");
|
||||
|
||||
{
|
||||
let mut ctx = self.ctx_mut();
|
||||
ctx.recorder.reset();
|
||||
ctx.set_recorder_viewport_to_window_size();
|
||||
}
|
||||
|
||||
self.handle_subscripts()?;
|
||||
|
||||
{
|
||||
profiling::scope!("lua_OnFrame");
|
||||
api::on_frame(&self.lua)?;
|
||||
}
|
||||
|
||||
let ctx = self.lua.app_data_ref::<Context>().unwrap();
|
||||
|
||||
let (layers_hash, layers) = ctx.recorder.finish();
|
||||
let identical = layers_hash == self.previous_layers_hash;
|
||||
self.previous_layers_hash = layers_hash;
|
||||
|
||||
// determine if another redraw needs to be requested after this frame.
|
||||
// this mirrors SimpleGraphic's behavior.
|
||||
let is_focused = ctx.window_state.is_focused;
|
||||
let is_hovered = ctx.window_state.is_hovered;
|
||||
let has_active_subscript = self.has_active_subscript();
|
||||
let has_active_coroutine = self.has_active_coroutine();
|
||||
let request_redraw =
|
||||
is_focused || is_hovered || has_active_subscript || has_active_coroutine;
|
||||
|
||||
Ok(StageFrameOutput {
|
||||
draw_commands: layers.values().flatten().copied().collect(),
|
||||
can_elide: identical,
|
||||
request_redraw,
|
||||
scale_factor: ctx.window_state.scale_factor(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Advances all running subscripts and forwards their results to Lua handlers.
|
||||
/// Call once per frame.
|
||||
fn handle_subscripts(&self) -> LuaResult<()> {
|
||||
profiling::scope!("handle_subscripts");
|
||||
|
||||
// advance the subscripts and collect the work they produced
|
||||
let subscript_events = self
|
||||
.lua
|
||||
.app_data_mut::<SubscriptManager>()
|
||||
.unwrap()
|
||||
.process();
|
||||
|
||||
for event in subscript_events {
|
||||
match event {
|
||||
SubscriptEvent::Call {
|
||||
function_name,
|
||||
arguments,
|
||||
reply_tx,
|
||||
} => {
|
||||
let result = api::on_sub_call(&self.lua, function_name, arguments)
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(NativeMultiValue::try_from);
|
||||
// non-blocking calls have no reply channel and discard their result
|
||||
if let Some(reply_tx) = reply_tx {
|
||||
// if the subscript's thread has already gone away, there's nowhere to send
|
||||
// the result, so ignore the error
|
||||
let _ = reply_tx.send(result);
|
||||
}
|
||||
}
|
||||
SubscriptEvent::Finished { id, return_values } => {
|
||||
api::on_sub_finished(&self.lua, id, return_values)?;
|
||||
}
|
||||
SubscriptEvent::Error { id, error } => {
|
||||
api::on_sub_error(&self.lua, id, error)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_active_subscript(&self) -> bool {
|
||||
self.lua
|
||||
.app_data_ref::<SubscriptManager>()
|
||||
.unwrap()
|
||||
.has_running_subscripts()
|
||||
}
|
||||
|
||||
fn has_active_coroutine(&self) -> bool {
|
||||
self.get_coroutines().is_ok_and(|coroutines| {
|
||||
coroutines.pairs::<mlua::Thread, bool>().any(|pair| {
|
||||
pair.is_ok_and(|(thread, _)| {
|
||||
matches!(
|
||||
thread.status(),
|
||||
ThreadStatus::Resumable | ThreadStatus::Running
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn get_coroutines(&self) -> LuaResult<Table> {
|
||||
let coroutine_module: Table = self.lua.globals().get("coroutine")?;
|
||||
let list_func: Function = coroutine_module.get("_list")?;
|
||||
list_func.call::<Table>(())
|
||||
}
|
||||
|
||||
pub fn clear_pressed(&self) {
|
||||
self.ctx_mut().input_state.clear_pressed();
|
||||
}
|
||||
|
||||
/// Calls PoB's `CanExit` handler. Used for unsaved changes prompt.
|
||||
pub fn can_exit(&self) -> bool {
|
||||
api::can_exit(&self.lua).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Attaches the render-target window to the context
|
||||
pub fn set_window(&self, window: Arc<Window>) {
|
||||
self.ctx_mut().window_state.set_window(window);
|
||||
}
|
||||
|
||||
/// Helper for accessing `Context`
|
||||
#[inline]
|
||||
fn ctx(&self) -> AppDataRef<'_, Context> {
|
||||
self.lua.app_data_ref().unwrap()
|
||||
}
|
||||
|
||||
/// Helper for getting mutable access to `Context`
|
||||
#[inline]
|
||||
fn ctx_mut(&self) -> AppDataRefMut<'_, Context> {
|
||||
self.lua.app_data_mut().unwrap()
|
||||
}
|
||||
}
|
||||
+224
@@ -0,0 +1,224 @@
|
||||
use crate::{
|
||||
input::{Key, MouseButton},
|
||||
pob::{
|
||||
api::{
|
||||
callback::{call_callback, get_custom_callback, set_custom_callback, set_main_object},
|
||||
clipboard::{copy, paste},
|
||||
compression::{deflate, inflate},
|
||||
console::{console_clear, console_execute, console_print_table, console_printf},
|
||||
general::{exit, get_time, open_url, render_init, restart, take_screenshot},
|
||||
image_handle::register_image_handle_api,
|
||||
input::{
|
||||
get_cursor_pos, is_key_down, key_as_str, mousebutton_as_str, set_cursor_pos,
|
||||
show_cursor,
|
||||
},
|
||||
lua::{load_module, protected_call, protected_load_module},
|
||||
paths::{
|
||||
get_runtime_path, get_script_path, get_user_path, get_work_dir, make_dir,
|
||||
remove_dir, set_work_dir,
|
||||
},
|
||||
rendering::{
|
||||
draw_image, draw_image_quad, get_async_count, get_draw_color, get_draw_layer,
|
||||
set_clear_color, set_draw_color, set_draw_layer, set_viewport,
|
||||
},
|
||||
search_handle::new_search_handle,
|
||||
subscript::{abort_subscript, is_subscript_running, launch_subscript},
|
||||
text::{draw_string, get_index_at_cur, get_string_width, strip_escapes},
|
||||
window::{
|
||||
get_dpi_scale_override, get_screen_scale, get_screen_size, set_dpi_scale_override,
|
||||
set_foreground, set_window_title,
|
||||
},
|
||||
},
|
||||
subscript::NativeMultiValue,
|
||||
},
|
||||
};
|
||||
use mlua::{Lua, MultiValue, Result as LuaResult};
|
||||
use winit::keyboard::SmolStr;
|
||||
|
||||
mod callback;
|
||||
mod clipboard;
|
||||
mod color;
|
||||
mod compression;
|
||||
mod console;
|
||||
mod general;
|
||||
mod image_handle;
|
||||
mod input;
|
||||
mod lua;
|
||||
mod paths;
|
||||
mod rendering;
|
||||
mod search_handle;
|
||||
mod subscript;
|
||||
mod text;
|
||||
mod window;
|
||||
|
||||
/// Register functions that can be called from Lua
|
||||
pub fn register_globals(lua: &Lua) -> LuaResult<()> {
|
||||
let globals = lua.globals();
|
||||
|
||||
// callbacks
|
||||
globals.set("SetMainObject", lua.create_function(set_main_object)?)?;
|
||||
globals.set("SetCallback", lua.create_function(set_custom_callback)?)?;
|
||||
globals.set("GetCallback", lua.create_function(get_custom_callback)?)?;
|
||||
|
||||
// paths
|
||||
globals.set("GetUserPath", lua.create_function(get_user_path)?)?;
|
||||
globals.set("GetScriptPath", lua.create_function(get_script_path)?)?;
|
||||
globals.set("GetRuntimePath", lua.create_function(get_runtime_path)?)?;
|
||||
globals.set("GetWorkDir", lua.create_function(get_work_dir)?)?;
|
||||
globals.set("SetWorkDir", lua.create_function(set_work_dir)?)?;
|
||||
globals.set("MakeDir", lua.create_function(make_dir)?)?;
|
||||
globals.set("RemoveDir", lua.create_function(remove_dir)?)?;
|
||||
|
||||
// console
|
||||
globals.set("ConPrintf", lua.create_function(console_printf)?)?;
|
||||
globals.set("ConExecute", lua.create_function(console_execute)?)?;
|
||||
globals.set("ConClear", lua.create_function(console_clear)?)?;
|
||||
globals.set("ConPrintTable", lua.create_function(console_print_table)?)?;
|
||||
|
||||
// general
|
||||
globals.set("GetTime", lua.create_function(get_time)?)?;
|
||||
globals.set("Exit", lua.create_function(exit)?)?;
|
||||
globals.set("Restart", lua.create_function(restart)?)?;
|
||||
globals.set("OpenURL", lua.create_function(open_url)?)?;
|
||||
globals.set("RenderInit", lua.create_function(render_init)?)?;
|
||||
globals.set("TakeScreenshot", lua.create_function(take_screenshot)?)?;
|
||||
|
||||
// compression
|
||||
globals.set("Inflate", lua.create_function(inflate)?)?;
|
||||
globals.set("Deflate", lua.create_function(deflate)?)?;
|
||||
|
||||
// search handle
|
||||
globals.set("NewFileSearch", lua.create_function(new_search_handle)?)?;
|
||||
|
||||
// image handle
|
||||
register_image_handle_api(lua)?;
|
||||
|
||||
// clipboard
|
||||
globals.set("Copy", lua.create_function(copy)?)?;
|
||||
globals.set("Paste", lua.create_function(paste)?)?;
|
||||
|
||||
// input
|
||||
globals.set("GetCursorPos", lua.create_function(get_cursor_pos)?)?;
|
||||
globals.set("SetCursorPos", lua.create_function(set_cursor_pos)?)?;
|
||||
globals.set("ShowCursor", lua.create_function(show_cursor)?)?;
|
||||
globals.set("IsKeyDown", lua.create_function(is_key_down)?)?;
|
||||
|
||||
// window
|
||||
globals.set("GetScreenSize", lua.create_function(get_screen_size)?)?;
|
||||
globals.set("GetScreenScale", lua.create_function(get_screen_scale)?)?;
|
||||
globals.set("SetWindowTitle", lua.create_function(set_window_title)?)?;
|
||||
globals.set("SetForeground", lua.create_function(set_foreground)?)?;
|
||||
globals.set(
|
||||
"SetDPIScaleOverridePercent",
|
||||
lua.create_function(set_dpi_scale_override)?,
|
||||
)?;
|
||||
globals.set(
|
||||
"GetDPIScaleOverridePercent",
|
||||
lua.create_function(get_dpi_scale_override)?,
|
||||
)?;
|
||||
|
||||
// lua
|
||||
globals.set("PCall", lua.create_function(protected_call)?)?;
|
||||
globals.set("LoadModule", lua.create_function(load_module)?)?;
|
||||
globals.set("PLoadModule", lua.create_function(protected_load_module)?)?;
|
||||
|
||||
// subscripts
|
||||
globals.set(
|
||||
"LaunchSubScript",
|
||||
lua.create_function_mut(launch_subscript)?,
|
||||
)?;
|
||||
globals.set(
|
||||
"IsSubScriptRunning",
|
||||
lua.create_function(is_subscript_running)?,
|
||||
)?;
|
||||
globals.set("AbortSubScript", lua.create_function(abort_subscript)?)?;
|
||||
|
||||
// rendering
|
||||
// NOTE: unfortunately, mlua's conversion of function arguments adds a lot of
|
||||
// overhead. this is very noticeable for the draw functions which can be called
|
||||
// thousands of times per frame. C functions are used to get raw access to
|
||||
// the lua stack without the overhead.
|
||||
unsafe { globals.set("SetDrawColor", lua.create_c_function(set_draw_color)?)? };
|
||||
unsafe { globals.set("GetDrawColor", lua.create_c_function(get_draw_color)?)? };
|
||||
unsafe { globals.set("SetViewport", lua.create_c_function(set_viewport)?)? };
|
||||
unsafe {
|
||||
globals.set("SetDrawLayer", lua.create_c_function(set_draw_layer)?)?;
|
||||
}
|
||||
unsafe { globals.set("DrawImage", lua.create_c_function(draw_image)?)? };
|
||||
unsafe { globals.set("DrawImageQuad", lua.create_c_function(draw_image_quad)?)? };
|
||||
globals.set("GetDrawLayer", lua.create_function(get_draw_layer)?)?;
|
||||
globals.set("GetAsyncCount", lua.create_function(get_async_count)?)?;
|
||||
globals.set("SetClearColor", lua.create_function(set_clear_color)?)?;
|
||||
|
||||
// text
|
||||
// see comment above about why C functions are used for these
|
||||
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)?,
|
||||
)?;
|
||||
globals.set("StripEscapes", lua.create_function(strip_escapes)?)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Registers Lua callback functions that can be called from Rust
|
||||
macro_rules! define_callbacks {
|
||||
($($fn_name:ident => $lua_name:literal ($($arg:ident : $arg_ty:ty),*) -> $ret_ty:ty;)*) => {
|
||||
$(
|
||||
pub fn $fn_name(lua: &Lua, $($arg: $arg_ty),*) -> LuaResult<$ret_ty> {
|
||||
call_callback(lua, $lua_name, ($($arg,)*))
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
define_callbacks! {
|
||||
on_init => "OnInit"() -> ();
|
||||
on_exit => "OnExit"() -> ();
|
||||
on_frame => "OnFrame"() -> ();
|
||||
can_exit => "CanExit"() -> bool;
|
||||
on_char => "OnChar"(ch: char) -> ();
|
||||
on_sub_call => "OnSubCall"(name: String, args: NativeMultiValue) -> MultiValue;
|
||||
on_sub_finished => "OnSubFinished"(id: u64, return_values: NativeMultiValue) -> ();
|
||||
on_sub_error => "OnSubError"(id: u64, error_msg: String) -> ();
|
||||
}
|
||||
|
||||
// `on_key_up` and `on_key_down` are manually defined because they require additional conversions
|
||||
// between key representations.
|
||||
pub enum Input {
|
||||
Keyboard(Key),
|
||||
Mouse(MouseButton),
|
||||
WheelUp,
|
||||
WheelDown,
|
||||
}
|
||||
|
||||
impl Input {
|
||||
fn as_pob_key_str(&self) -> Option<SmolStr> {
|
||||
match self {
|
||||
Self::Keyboard(key) => key_as_str(key.clone()),
|
||||
Self::Mouse(button) => mousebutton_as_str(*button),
|
||||
Self::WheelUp => Some("WHEELUP".into()),
|
||||
Self::WheelDown => Some("WHEELDOWN".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_key_down(lua: &Lua, key: &Input, double_click: bool) -> LuaResult<()> {
|
||||
let Some(key_str) = key.as_pob_key_str() else {
|
||||
return Ok(());
|
||||
};
|
||||
call_callback(lua, "OnKeyDown", (key_str.as_str(), double_click))
|
||||
}
|
||||
|
||||
pub fn on_key_up(lua: &Lua, key: &Input) -> LuaResult<()> {
|
||||
let Some(key_str) = key.as_pob_key_str() else {
|
||||
return Ok(());
|
||||
};
|
||||
call_callback(lua, "OnKeyUp", (key_str.as_str(),))
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
//! During initialization, PoB calls `set_main_object` 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 `set_custom_callback` and retrieved with
|
||||
//! `get_custom_callback`. Functions defined in the main object are shadowed by custom functions
|
||||
//! with the same name.
|
||||
use mlua::{FromLuaMulti, Function, IntoLuaMulti, Lua, Result as LuaResult, Table, Value};
|
||||
|
||||
const CALLBACK_REGISTRY_NAME: &str = "uicallbacks";
|
||||
|
||||
pub fn set_main_object(l: &Lua, main_object: Table) -> LuaResult<()> {
|
||||
let callback_table = l.create_table()?;
|
||||
callback_table.set("MainObject", main_object)?;
|
||||
l.set_named_registry_value(CALLBACK_REGISTRY_NAME, callback_table)
|
||||
}
|
||||
|
||||
pub fn set_custom_callback(l: &Lua, (name, func): (String, Function)) -> LuaResult<()> {
|
||||
let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?;
|
||||
callback_table.set(name, func)
|
||||
}
|
||||
|
||||
pub fn get_custom_callback(l: &Lua, name: String) -> LuaResult<Function> {
|
||||
let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?;
|
||||
callback_table.get(name)
|
||||
}
|
||||
|
||||
/// Looks up a callback by name.
|
||||
///
|
||||
/// Custom callbacks shadow callbacks defined in main object.
|
||||
fn get_callback(lua: &Lua, name: &str) -> LuaResult<Function> {
|
||||
let callback_table: Table = lua.named_registry_value(CALLBACK_REGISTRY_NAME)?;
|
||||
|
||||
// check for custom callbacks first
|
||||
if let Value::Function(f) = callback_table.get(name)? {
|
||||
return Ok(f);
|
||||
}
|
||||
|
||||
// then look look in main object
|
||||
if let Value::Table(main_object) = callback_table.get("MainObject")?
|
||||
&& let Value::Function(f) = main_object.get(name)?
|
||||
{
|
||||
// these functions expect the main object as first argument so we bind it here
|
||||
return f.bind(main_object);
|
||||
}
|
||||
|
||||
Err(anyhow::anyhow!("Callback '{name}' not found").into())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn call_callback<A, R>(lua: &Lua, name: &str, args: A) -> LuaResult<R>
|
||||
where
|
||||
A: IntoLuaMulti,
|
||||
R: FromLuaMulti,
|
||||
{
|
||||
get_callback(lua, name)?.call(args)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use crate::pob::Context;
|
||||
use mlua::{Lua, Result as LuaResult};
|
||||
|
||||
pub fn copy(l: &Lua, text: String) -> LuaResult<()> {
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
ctx.window_state.set_clipboard_text(text);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn paste(l: &Lua, _: ()) -> LuaResult<Option<String>> {
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
Ok(ctx.window_state.get_clipboard_text())
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
use crate::color::Srgba;
|
||||
|
||||
#[inline]
|
||||
fn hex_byte(a: u8, b: u8) -> u8 {
|
||||
(hex_digit(a) << 4) | hex_digit(b)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn hex_digit(c: u8) -> u8 {
|
||||
match c {
|
||||
b'0'..=b'9' => c - b'0',
|
||||
b'a'..=b'f' => c - b'a' + 10,
|
||||
b'A'..=b'F' => c - b'A' + 10,
|
||||
_ => unreachable!("invalid hex digit"),
|
||||
}
|
||||
}
|
||||
|
||||
impl Srgba {
|
||||
pub fn from_escape_code(escape_str: &str) -> Self {
|
||||
let bytes = escape_str.as_bytes();
|
||||
|
||||
match bytes {
|
||||
[b'^', b'0'] => Self::from_rgb(0, 0, 0),
|
||||
[b'^', b'1'] => Self::from_rgb(255, 0, 0),
|
||||
[b'^', b'2'] => Self::from_rgb(0, 255, 0),
|
||||
[b'^', b'3'] => Self::from_rgb(0, 0, 255),
|
||||
[b'^', b'4'] => Self::from_rgb(255, 255, 0),
|
||||
[b'^', b'5'] => Self::from_rgb(255, 0, 255),
|
||||
[b'^', b'6'] => Self::from_rgb(0, 255, 255),
|
||||
[b'^', b'7'] => Self::from_rgb(255, 255, 255),
|
||||
[b'^', b'8'] => Self::from_rgb(178, 178, 178),
|
||||
[b'^', b'9'] => Self::from_rgb(102, 102, 102),
|
||||
|
||||
[b'^', b'x' | b'X', r1, r2, g1, g2, b1, b2] => {
|
||||
Self::from_rgb(hex_byte(*r1, *r2), hex_byte(*g1, *g2), hex_byte(*b1, *b2))
|
||||
}
|
||||
|
||||
_ => Self::WHITE,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use flate2::{
|
||||
Compression,
|
||||
read::{GzDecoder, GzEncoder, ZlibDecoder, ZlibEncoder},
|
||||
};
|
||||
use mlua::{IntoLuaMulti, Lua, LuaString, MultiValue, Result as LuaResult, Value};
|
||||
use std::io::Read;
|
||||
|
||||
pub fn inflate(l: &Lua, compressed: LuaString) -> LuaResult<MultiValue> {
|
||||
let compressed_bytes = &compressed.as_bytes()[..];
|
||||
|
||||
// prevent decompression of input larger than 128MiB
|
||||
if compressed_bytes.len() > (128 << 20) {
|
||||
return (Value::Nil, "Input larger than 128 MiB").into_lua_multi(l);
|
||||
}
|
||||
|
||||
let mut decompressed = Vec::new();
|
||||
|
||||
let result = if is_gzip(compressed_bytes) {
|
||||
GzDecoder::new(compressed_bytes).read_to_end(&mut decompressed)
|
||||
} else {
|
||||
ZlibDecoder::new(compressed_bytes).read_to_end(&mut decompressed)
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(_) => l.create_string(&decompressed)?.into_lua_multi(l),
|
||||
Err(e) => (Value::Nil, e.to_string()).into_lua_multi(l),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_gzip(data: &[u8]) -> bool {
|
||||
data.len() >= 2 && data[0] == 0x1f && data[1] == 0x8b
|
||||
}
|
||||
|
||||
pub fn deflate(
|
||||
l: &Lua,
|
||||
(uncompressed, use_gzip): (LuaString, Option<bool>),
|
||||
) -> LuaResult<MultiValue> {
|
||||
let uncompressed_bytes = &uncompressed.as_bytes()[..];
|
||||
|
||||
// prevent compression of input larger than 128MiB
|
||||
if uncompressed_bytes.len() > (128 << 20) {
|
||||
return (Value::Nil, "Input larger than 128 MiB").into_lua_multi(l);
|
||||
}
|
||||
|
||||
let mut compressed = Vec::new();
|
||||
|
||||
let result = if use_gzip.unwrap_or(false) {
|
||||
GzEncoder::new(uncompressed_bytes, Compression::best()).read_to_end(&mut compressed)
|
||||
} else {
|
||||
ZlibEncoder::new(uncompressed_bytes, Compression::best()).read_to_end(&mut compressed)
|
||||
};
|
||||
|
||||
match result {
|
||||
Ok(_) => l.create_string(&compressed)?.into_lua_multi(l),
|
||||
Err(e) => (Value::Nil, e.to_string()).into_lua_multi(l),
|
||||
}
|
||||
}
|
||||
@@ -34,9 +34,9 @@ fn print_table(table: &Table, indent: usize, recursive: bool) -> LuaResult<()> {
|
||||
let (key, value) = pair?;
|
||||
|
||||
if key.is_string() {
|
||||
write!(lock, "{0:>1$}\"{2}\" = ", "", inner_ind, key.to_string()?,)?;
|
||||
write!(lock, "{0:>1$}\"{2}\" = ", "", inner_ind, key.to_string()?)?;
|
||||
} else {
|
||||
write!(lock, "{0:>1$}{2} = ", "", inner_ind, key.to_string()?,)?;
|
||||
write!(lock, "{0:>1$}{2} = ", "", inner_ind, key.to_string()?)?;
|
||||
}
|
||||
|
||||
if value.is_table() {
|
||||
@@ -0,0 +1,43 @@
|
||||
use crate::pob::Context;
|
||||
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Variadic};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub fn get_time(_l: &Lua, _: ()) -> LuaResult<u128> {
|
||||
Ok(SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("UNIX_EPOCH is before now")
|
||||
.as_millis())
|
||||
}
|
||||
|
||||
pub fn exit(l: &Lua, exit_msg: Option<String>) -> LuaResult<()> {
|
||||
if let Some(exit_msg) = exit_msg {
|
||||
println!("{exit_msg}");
|
||||
}
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
ctx.should_exit = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn restart(l: &Lua, _: ()) -> LuaResult<()> {
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
ctx.needs_restart = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn open_url(l: &Lua, url: String) -> LuaResult<MultiValue> {
|
||||
match open::that(url) {
|
||||
Ok(()) => ().into_lua_multi(l),
|
||||
Err(_) => "Unable to open url!".into_lua_multi(l),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render_init(l: &Lua, features: Variadic<String>) -> LuaResult<()> {
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
ctx.is_dpi_aware = features.iter().any(|feat| feat == "DPI_AWARE");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn take_screenshot(_l: &Lua, _: ()) -> LuaResult<()> {
|
||||
log::warn!("take_screenshot is not implemented!");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
use std::{
|
||||
ffi::{CStr, c_int},
|
||||
ptr,
|
||||
};
|
||||
|
||||
use mlua::{Lua, Result as LuaResult, ffi};
|
||||
|
||||
use crate::{
|
||||
dpi::PhysicalSize,
|
||||
pob::Context,
|
||||
renderer::textures::{TextureHandle, TextureId, TextureOptions},
|
||||
};
|
||||
|
||||
pub struct ImageHandle {
|
||||
texture: Option<TextureHandle>,
|
||||
}
|
||||
|
||||
impl ImageHandle {
|
||||
#[inline]
|
||||
pub const fn new() -> Self {
|
||||
Self { texture: None }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn texture_id(&self) -> Option<TextureId> {
|
||||
self.texture.as_ref().map(TextureHandle::id)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_valid(&self) -> bool {
|
||||
self.texture.is_some()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_loading(&self) -> bool {
|
||||
self.texture.as_ref().is_none_or(TextureHandle::is_loading)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn image_size(&self) -> PhysicalSize<u32> {
|
||||
self.texture
|
||||
.as_ref()
|
||||
.and_then(TextureHandle::size)
|
||||
.unwrap_or_else(PhysicalSize::zero)
|
||||
}
|
||||
}
|
||||
|
||||
// Lua userdata implementation for `ImageHandle`.
|
||||
//
|
||||
// `mlua::UserData` instances are wrapped in a special way to maintain Rust
|
||||
// safety guarantees which introduces additional overhead.
|
||||
// https://github.com/mlua-rs/mlua/discussions/545#discussioncomment-12518251
|
||||
//
|
||||
// To avoid this overhead, `ImageHandle` is stored directly in Lua userdata
|
||||
// using the raw Lua C API.
|
||||
|
||||
const IMAGE_HANDLE_METATABLE: &[u8] = b"runtime.ImageHandle\0";
|
||||
|
||||
#[inline]
|
||||
unsafe fn push_image_handle(state: *mut ffi::lua_State) -> *mut ImageHandle {
|
||||
let ptr = unsafe { ffi::lua_newuserdata(state, std::mem::size_of::<ImageHandle>()) }
|
||||
.cast::<ImageHandle>();
|
||||
|
||||
// Construct the Rust object directly in Lua-owned memory
|
||||
unsafe {
|
||||
ptr.write(ImageHandle::new());
|
||||
}
|
||||
|
||||
ptr
|
||||
}
|
||||
|
||||
/// Puts `ImageHandle` on the Lua stack
|
||||
unsafe extern "C-unwind" fn new_image_handle(state: *mut ffi::lua_State) -> c_int {
|
||||
unsafe {
|
||||
push_image_handle(state);
|
||||
|
||||
// The metatable must already have been registered.
|
||||
ffi::luaL_getmetatable(state, IMAGE_HANDLE_METATABLE.as_ptr().cast());
|
||||
ffi::lua_setmetatable(state, -2);
|
||||
}
|
||||
|
||||
1
|
||||
}
|
||||
|
||||
/// Gets an `ImageHandle` from the Lua stack.
|
||||
#[inline]
|
||||
unsafe fn get_image_handle(state: *mut ffi::lua_State, index: c_int) -> *mut ImageHandle {
|
||||
unsafe {
|
||||
ffi::luaL_checkudata(state, index, IMAGE_HANDLE_METATABLE.as_ptr().cast())
|
||||
.cast::<ImageHandle>()
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub unsafe fn image_handle_texture_id(
|
||||
state: *mut ffi::lua_State,
|
||||
index: c_int,
|
||||
) -> Option<TextureId> {
|
||||
if unsafe { ffi::lua_isnil(state, index) } != 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let ptr = unsafe { ffi::lua_touserdata(state, index) }.cast::<ImageHandle>();
|
||||
|
||||
if ptr.is_null() {
|
||||
return None;
|
||||
}
|
||||
|
||||
unsafe { (*ptr).texture_id() }
|
||||
}
|
||||
|
||||
// Drops the `ImageHandle`
|
||||
unsafe extern "C-unwind" fn image_handle_gc(state: *mut ffi::lua_State) -> c_int {
|
||||
let ptr = unsafe { ffi::lua_touserdata(state, 1) }.cast::<ImageHandle>();
|
||||
|
||||
if !ptr.is_null() {
|
||||
unsafe {
|
||||
ptr::drop_in_place(ptr);
|
||||
}
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn image_handle_is_valid(state: *mut ffi::lua_State) -> c_int {
|
||||
let handle = unsafe { get_image_handle(state, 1) };
|
||||
|
||||
let valid = unsafe { (*handle).is_valid() };
|
||||
|
||||
unsafe {
|
||||
ffi::lua_pushboolean(state, c_int::from(valid));
|
||||
}
|
||||
|
||||
1
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn image_handle_is_loading(state: *mut ffi::lua_State) -> c_int {
|
||||
let handle = unsafe { get_image_handle(state, 1) };
|
||||
|
||||
let loading = unsafe { (*handle).is_loading() };
|
||||
|
||||
unsafe {
|
||||
ffi::lua_pushboolean(state, c_int::from(loading));
|
||||
}
|
||||
|
||||
1
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn image_handle_image_size(state: *mut ffi::lua_State) -> c_int {
|
||||
let handle = unsafe { get_image_handle(state, 1) };
|
||||
|
||||
let size = unsafe { (*handle).image_size() };
|
||||
|
||||
unsafe {
|
||||
ffi::lua_pushinteger(state, size.width as ffi::lua_Integer);
|
||||
ffi::lua_pushinteger(state, size.height as ffi::lua_Integer);
|
||||
}
|
||||
|
||||
2
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn image_handle_unload(state: *mut ffi::lua_State) -> c_int {
|
||||
let handle = unsafe { get_image_handle(state, 1) };
|
||||
|
||||
unsafe {
|
||||
(*handle).texture = None;
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe extern "C-unwind" fn image_handle_load(state: *mut ffi::lua_State) -> c_int {
|
||||
let handle = unsafe { get_image_handle(state, 1) };
|
||||
|
||||
// Path
|
||||
let path_ptr = unsafe { ffi::luaL_checklstring(state, 2, ptr::null_mut()) };
|
||||
|
||||
if path_ptr.is_null() {
|
||||
unsafe {
|
||||
ffi::luaL_error(state, c"Invalid image path".as_ptr());
|
||||
}
|
||||
unreachable!();
|
||||
}
|
||||
|
||||
let path = unsafe { CStr::from_ptr(path_ptr) };
|
||||
|
||||
let path = match path.to_str() {
|
||||
Ok(path) => path.to_owned(),
|
||||
Err(_) => {
|
||||
unsafe {
|
||||
ffi::luaL_error(state, c"Image path is not valid UTF-8".as_ptr());
|
||||
}
|
||||
unreachable!();
|
||||
}
|
||||
};
|
||||
|
||||
// Flags
|
||||
let mut is_async = false;
|
||||
let mut generate_mipmaps = false;
|
||||
let mut options = TextureOptions::LINEAR_REPEAT;
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
for index in 3..=nargs {
|
||||
if unsafe { ffi::lua_type(state, index) } != ffi::LUA_TSTRING {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut len = 0;
|
||||
|
||||
let ptr = unsafe { ffi::lua_tolstring(state, index, &raw mut len) };
|
||||
if ptr.is_null() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let bytes = unsafe { std::slice::from_raw_parts(ptr.cast::<u8>(), len) };
|
||||
|
||||
match bytes {
|
||||
b"CLAMP" => {
|
||||
options.wrap_mode = wgpu::AddressMode::ClampToEdge;
|
||||
}
|
||||
b"NEAREST" => {
|
||||
options.magnification = wgpu::FilterMode::Nearest;
|
||||
}
|
||||
b"ASYNC" => {
|
||||
is_async = true;
|
||||
}
|
||||
b"MIPMAP" => {
|
||||
generate_mipmaps = true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Load / update
|
||||
let handle = unsafe { &mut *handle };
|
||||
|
||||
let lua = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua.app_data_ref::<Context>().unwrap();
|
||||
|
||||
match &mut handle.texture {
|
||||
Some(texture_handle) => {
|
||||
// Keep the existing TextureHandle and update underlying texture
|
||||
let _ = ctx.texture_manager.borrow().update_texture(
|
||||
texture_handle.id(),
|
||||
path,
|
||||
options,
|
||||
is_async,
|
||||
generate_mipmaps,
|
||||
);
|
||||
}
|
||||
None => {
|
||||
if let Ok(texture_handle) =
|
||||
ctx.texture_manager
|
||||
.borrow()
|
||||
.load_texture(path, options, is_async, generate_mipmaps)
|
||||
{
|
||||
handle.texture = Some(texture_handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
unsafe fn register_image_handle_metatable(state: *mut ffi::lua_State) {
|
||||
unsafe {
|
||||
let created = ffi::luaL_newmetatable(state, IMAGE_HANDLE_METATABLE.as_ptr().cast());
|
||||
|
||||
// Create metatable if it doesn't exist already
|
||||
if created != 0 {
|
||||
// metatable.__gc = image_handle_gc
|
||||
ffi::lua_pushcfunction(state, image_handle_gc);
|
||||
ffi::lua_setfield(state, -2, c"__gc".as_ptr());
|
||||
|
||||
// Create method table.
|
||||
ffi::lua_newtable(state);
|
||||
|
||||
// Load
|
||||
ffi::lua_pushcfunction(state, image_handle_load);
|
||||
ffi::lua_setfield(state, -2, c"Load".as_ptr());
|
||||
|
||||
// Unload
|
||||
ffi::lua_pushcfunction(state, image_handle_unload);
|
||||
ffi::lua_setfield(state, -2, c"Unload".as_ptr());
|
||||
|
||||
// IsValid
|
||||
ffi::lua_pushcfunction(state, image_handle_is_valid);
|
||||
ffi::lua_setfield(state, -2, c"IsValid".as_ptr());
|
||||
|
||||
// IsLoading
|
||||
ffi::lua_pushcfunction(state, image_handle_is_loading);
|
||||
ffi::lua_setfield(state, -2, c"IsLoading".as_ptr());
|
||||
|
||||
// ImageSize
|
||||
ffi::lua_pushcfunction(state, image_handle_image_size);
|
||||
ffi::lua_setfield(state, -2, c"ImageSize".as_ptr());
|
||||
|
||||
// metatable.__index = method table
|
||||
ffi::lua_setfield(state, -2, c"__index".as_ptr());
|
||||
}
|
||||
|
||||
// Pop metatable.
|
||||
ffi::lua_pop(state, 1);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register_image_handle_api(lua: &Lua) -> LuaResult<()> {
|
||||
let globals = lua.globals();
|
||||
|
||||
unsafe {
|
||||
lua.exec_raw::<()>((), |state| {
|
||||
register_image_handle_metatable(state);
|
||||
})
|
||||
}?;
|
||||
|
||||
globals.set("NewImageHandle", unsafe {
|
||||
lua.create_c_function(new_image_handle)
|
||||
}?)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
use crate::{
|
||||
input::{Key, MouseButton},
|
||||
pob::Context,
|
||||
};
|
||||
use mlua::{Lua, Result as LuaResult};
|
||||
use winit::keyboard::{NamedKey, SmolStr};
|
||||
|
||||
pub fn get_cursor_pos(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
let pos = ctx.input_state.mouse_pos();
|
||||
Ok((pos.x as u32, pos.y as u32))
|
||||
}
|
||||
|
||||
pub fn set_cursor_pos(_l: &Lua, _: ()) -> LuaResult<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn show_cursor(_l: &Lua, _: ()) -> LuaResult<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn is_key_down(l: &Lua, key_name: String) -> LuaResult<bool> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
|
||||
if let Some(key) = str_as_key(&key_name) {
|
||||
Ok(ctx.input_state.key_pressed(&key))
|
||||
} else if let Some(button) = str_as_mousebutton(&key_name) {
|
||||
Ok(ctx.input_state.mouse_pressed(button))
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
const NAMED_KEYS: &[(&str, NamedKey)] = &[
|
||||
("BACK", NamedKey::Backspace),
|
||||
("TAB", NamedKey::Tab),
|
||||
("RETURN", NamedKey::Enter),
|
||||
("ESCAPE", NamedKey::Escape),
|
||||
("SHIFT", NamedKey::Shift),
|
||||
("CTRL", NamedKey::Control),
|
||||
("ALT", NamedKey::Alt),
|
||||
("PAUSE", NamedKey::Pause),
|
||||
("PAGEUP", NamedKey::PageUp),
|
||||
("PAGEDOWN", NamedKey::PageDown),
|
||||
("END", NamedKey::End),
|
||||
("HOME", NamedKey::Home),
|
||||
("PRINTSCREEN", NamedKey::PrintScreen),
|
||||
("INSERT", NamedKey::Insert),
|
||||
("DELETE", NamedKey::Delete),
|
||||
("UP", NamedKey::ArrowUp),
|
||||
("DOWN", NamedKey::ArrowDown),
|
||||
("LEFT", NamedKey::ArrowLeft),
|
||||
("RIGHT", NamedKey::ArrowRight),
|
||||
("F1", NamedKey::F1),
|
||||
("F2", NamedKey::F2),
|
||||
("F3", NamedKey::F3),
|
||||
("F4", NamedKey::F4),
|
||||
("F5", NamedKey::F5),
|
||||
("F6", NamedKey::F6),
|
||||
("F7", NamedKey::F7),
|
||||
("F8", NamedKey::F8),
|
||||
("F9", NamedKey::F9),
|
||||
("F10", NamedKey::F10),
|
||||
("F11", NamedKey::F11),
|
||||
("F12", NamedKey::F12),
|
||||
("F13", NamedKey::F13),
|
||||
("F14", NamedKey::F14),
|
||||
("F15", NamedKey::F15),
|
||||
(" ", NamedKey::Space),
|
||||
("NUMLOCK", NamedKey::NumLock),
|
||||
("SCROLL", NamedKey::ScrollLock),
|
||||
];
|
||||
|
||||
/// Atempts to convert PoB's key representation into a `Key`.
|
||||
fn str_as_key(s: &str) -> Option<Key> {
|
||||
let upper = s.to_uppercase();
|
||||
|
||||
// named keys
|
||||
if let Some((_, named)) = NAMED_KEYS.iter().find(|(name, _)| *name == upper) {
|
||||
return Some(Key::Named(*named));
|
||||
}
|
||||
|
||||
// single-character keys
|
||||
let mut chars = upper.chars();
|
||||
let first = chars.next()?;
|
||||
chars
|
||||
.next()
|
||||
.is_none()
|
||||
.then(|| Key::Character(SmolStr::new(first.to_string())))
|
||||
}
|
||||
|
||||
/// Atempts to convert a `Key` into PoB's key representation
|
||||
pub fn key_as_str(key: Key) -> Option<SmolStr> {
|
||||
match key {
|
||||
Key::Character(ch) if ch == "=" => Some(SmolStr::new("+")), // matches PoB's behavior
|
||||
Key::Character(ch) => Some(ch),
|
||||
Key::Named(named) => NAMED_KEYS
|
||||
.iter()
|
||||
.find(|(_, n)| *n == named)
|
||||
.map(|(name, _)| SmolStr::new(*name)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
const MOUSE_BUTTONS: &[(&str, MouseButton)] = &[
|
||||
("LEFTBUTTON", MouseButton::Left),
|
||||
("RIGHTBUTTON", MouseButton::Right),
|
||||
("MIDDLEBUTTON", MouseButton::Middle),
|
||||
("MOUSE4", MouseButton::Back),
|
||||
("MOUSE5", MouseButton::Forward),
|
||||
];
|
||||
|
||||
/// Atempts to convert PoB's key representation into a `MouseButton`.
|
||||
fn str_as_mousebutton(s: &str) -> Option<MouseButton> {
|
||||
MOUSE_BUTTONS
|
||||
.iter()
|
||||
.find(|(name, _)| *name == s.to_uppercase())
|
||||
.map(|(_, button)| *button)
|
||||
}
|
||||
|
||||
/// Atempts to convert a `MouseButton` into PoB's key representation
|
||||
pub fn mousebutton_as_str(button: MouseButton) -> Option<SmolStr> {
|
||||
MOUSE_BUTTONS
|
||||
.iter()
|
||||
.find(|(_, b)| *b == button)
|
||||
.map(|(name, _)| SmolStr::new(*name))
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use crate::{
|
||||
pob::Context,
|
||||
util::{change_working_directory, load_lua_file},
|
||||
};
|
||||
use mlua::{Function, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
|
||||
use std::env;
|
||||
|
||||
pub fn protected_call(l: &Lua, (func, args): (Function, MultiValue)) -> LuaResult<MultiValue> {
|
||||
match func.call::<MultiValue>(args) {
|
||||
// callers expect first return value to be Nil on success
|
||||
Ok(return_values) => Ok(std::iter::once(Value::Nil).chain(return_values).collect()),
|
||||
// otherwise it is set to error message.
|
||||
Err(err) => err.to_string().into_lua_multi(l),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
|
||||
let script_dir = {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
ctx.script_dir.clone()
|
||||
};
|
||||
let mut module_path = script_dir.join(name);
|
||||
if module_path.extension().is_none() {
|
||||
module_path.set_extension("lua");
|
||||
}
|
||||
|
||||
let current_dir = env::current_dir()?;
|
||||
change_working_directory(script_dir.as_path())?;
|
||||
let result = load_lua_file(l, &module_path).and_then(|chunk| chunk.call::<MultiValue>(args));
|
||||
change_working_directory(current_dir)?;
|
||||
result
|
||||
}
|
||||
|
||||
pub fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
|
||||
let script_dir = {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
ctx.script_dir.clone()
|
||||
};
|
||||
let mut module_path = script_dir.join(name);
|
||||
if module_path.extension().is_none() {
|
||||
module_path.set_extension("lua");
|
||||
}
|
||||
|
||||
let current_dir = env::current_dir()?;
|
||||
change_working_directory(script_dir.as_path())?;
|
||||
let result =
|
||||
match load_lua_file(l, &module_path).and_then(|chunk| chunk.call::<MultiValue>(args)) {
|
||||
// on success, callers expect a Nil followed by return values
|
||||
Ok(res) => Ok(std::iter::once(Value::Nil).chain(res).collect()),
|
||||
// otherwise it is set to error message.
|
||||
Err(err) => err.to_string().into_lua_multi(l),
|
||||
};
|
||||
change_working_directory(current_dir)?;
|
||||
result
|
||||
}
|
||||
@@ -2,39 +2,36 @@ use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
|
||||
use std::{fs, path::PathBuf};
|
||||
|
||||
use crate::{
|
||||
lua::Context,
|
||||
pob::Context,
|
||||
util::{change_working_directory, get_executable_dir},
|
||||
};
|
||||
|
||||
pub fn get_user_path(l: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
Ok(ctx.script_dir().join("userdata"))
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
Ok(ctx.script_dir.join("userdata"))
|
||||
}
|
||||
|
||||
// parent directory of Launch.lua script
|
||||
pub fn get_script_path(l: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
Ok(ctx.script_dir().to_owned())
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
Ok(ctx.script_dir.clone())
|
||||
}
|
||||
|
||||
// parent directory of executable
|
||||
pub fn get_runtime_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
match get_executable_dir() {
|
||||
Ok(exe_path) => Ok(exe_path),
|
||||
Err(_) => Ok(PathBuf::new()),
|
||||
}
|
||||
Ok(get_executable_dir().unwrap_or_default())
|
||||
}
|
||||
|
||||
pub fn get_work_dir(l: &Lua, _: ()) -> LuaResult<PathBuf> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
Ok(ctx.current_working_dir().to_path_buf())
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
Ok(ctx.current_working_dir.clone())
|
||||
}
|
||||
|
||||
// NOTE: unused
|
||||
pub fn set_work_dir(l: &Lua, path: String) -> LuaResult<()> {
|
||||
let ctx = l.app_data_ref::<&'static Context>().unwrap();
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
if change_working_directory(&path).is_ok() {
|
||||
*ctx.current_working_dir() = path.into();
|
||||
ctx.current_working_dir = path.into();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -42,9 +39,9 @@ pub fn set_work_dir(l: &Lua, path: String) -> LuaResult<()> {
|
||||
pub fn make_dir(l: &Lua, path: String) -> LuaResult<MultiValue> {
|
||||
match fs::create_dir_all(path) {
|
||||
// callers expect first return value to be true on success
|
||||
Ok(_) => Ok(Value::Boolean(true).into_lua_multi(l)?),
|
||||
Ok(()) => (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)?),
|
||||
Err(err) => (Value::Nil, err.to_string()).into_lua_multi(l),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,7 +52,7 @@ pub fn remove_dir(l: &Lua, (path, recursive): (String, Option<bool>)) -> LuaResu
|
||||
fs::remove_dir(&path)
|
||||
};
|
||||
match result {
|
||||
Ok(_) => Ok(Value::Boolean(true).into_lua_multi(l)?),
|
||||
Err(err) => Ok((Value::Nil, err.to_string()).into_lua_multi(l)?),
|
||||
Ok(()) => (true).into_lua_multi(l),
|
||||
Err(err) => (Value::Nil, err.to_string()).into_lua_multi(l),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
math::{Point, Quad, Rect, Size},
|
||||
pob::{Context, api::image_handle::image_handle_texture_id},
|
||||
};
|
||||
use core::ffi::c_int;
|
||||
use mlua::{
|
||||
Lua, Result as LuaResult,
|
||||
ffi::{self},
|
||||
};
|
||||
|
||||
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.cast::<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
|
||||
};
|
||||
}
|
||||
|
||||
pub unsafe extern "C-unwind" fn set_draw_color(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("set_draw_color");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
match nargs {
|
||||
// escape_code
|
||||
1 => {
|
||||
let esc_str = str_from_stack!(state, -nargs);
|
||||
let color = Srgba::from_escape_code(esc_str);
|
||||
ctx.recorder.set_draw_color(color);
|
||||
}
|
||||
// rgb
|
||||
3 => {
|
||||
let r = f32_from_stack!(state, -nargs);
|
||||
let g = f32_from_stack!(state, -nargs + 1);
|
||||
let b = f32_from_stack!(state, -nargs + 2);
|
||||
let color = Srgba::new_f32(r, g, b, 1.0);
|
||||
ctx.recorder.set_draw_color(color);
|
||||
}
|
||||
// rgba
|
||||
4 => {
|
||||
let r = f32_from_stack!(state, -nargs);
|
||||
let g = f32_from_stack!(state, -nargs + 1);
|
||||
let b = f32_from_stack!(state, -nargs + 2);
|
||||
let a = f32_from_stack!(state, -nargs + 3);
|
||||
let color = Srgba::new_f32(r, g, b, a);
|
||||
ctx.recorder.set_draw_color(color);
|
||||
}
|
||||
_ => panic!("Unexpected number of arguments"),
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
pub unsafe extern "C-unwind" fn get_draw_color(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("get_draw_color");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua_instance.app_data_ref::<Context>().unwrap();
|
||||
|
||||
let color: [f32; 4] = ctx.recorder.get_draw_color().into();
|
||||
unsafe { ffi::lua_pushnumber(state, f64::from(color[0])) };
|
||||
unsafe { ffi::lua_pushnumber(state, f64::from(color[1])) };
|
||||
unsafe { ffi::lua_pushnumber(state, f64::from(color[2])) };
|
||||
unsafe { ffi::lua_pushnumber(state, f64::from(color[3])) };
|
||||
|
||||
4
|
||||
}
|
||||
|
||||
pub unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("set_viewport");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
match nargs {
|
||||
0 => ctx.set_recorder_viewport_to_window_size(),
|
||||
4 => {
|
||||
let x = f32_from_stack!(state, -nargs);
|
||||
let y = f32_from_stack!(state, -nargs + 1);
|
||||
let w = f32_from_stack!(state, -nargs + 2);
|
||||
let h = f32_from_stack!(state, -nargs + 3);
|
||||
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
|
||||
ctx.recorder.set_viewport(rect);
|
||||
}
|
||||
_ => panic!("Unexpected number of arguments"),
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
pub unsafe extern "C-unwind" fn set_draw_layer(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("set_draw_layer");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
match nargs {
|
||||
1 => {
|
||||
let layer = i32_from_stack!(state, -nargs);
|
||||
ctx.recorder.set_draw_layer(layer, 0);
|
||||
}
|
||||
2 => {
|
||||
let layer = match unsafe { ffi::lua_type(state, -nargs) } {
|
||||
ffi::LUA_TNIL => None,
|
||||
ffi::LUA_TNUMBER => {
|
||||
let layer = i32_from_stack!(state, -nargs);
|
||||
Some(layer)
|
||||
}
|
||||
t => panic!("Expected Nil or Number, got {t:?}"),
|
||||
};
|
||||
let sublayer = i32_from_stack!(state, -nargs + 1);
|
||||
if let Some(layer) = layer {
|
||||
ctx.recorder.set_draw_layer(layer, sublayer);
|
||||
} else {
|
||||
ctx.recorder.set_draw_sublayer(sublayer);
|
||||
}
|
||||
}
|
||||
_ => panic!("Unexpected number of arguments"),
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
pub unsafe extern "C-unwind" fn draw_image(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("draw_image");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
assert!(
|
||||
matches!(nargs, 5 | 6 | 9 | 10),
|
||||
"Unexpected number of arguments"
|
||||
);
|
||||
|
||||
#[allow(clippy::manual_range_patterns)]
|
||||
let parse_uv = matches!(nargs, 9 | 10);
|
||||
let parse_layer_idx = matches!(nargs, 6 | 10);
|
||||
|
||||
let texture_id = unsafe { image_handle_texture_id(state, -nargs) };
|
||||
|
||||
// left, top, width, height
|
||||
let x = f32_from_stack!(state, -nargs + 1);
|
||||
let y = f32_from_stack!(state, -nargs + 2);
|
||||
let w = f32_from_stack!(state, -nargs + 3);
|
||||
let h = f32_from_stack!(state, -nargs + 4);
|
||||
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
|
||||
|
||||
// u1, v1, u2, v2
|
||||
let mut i = 5;
|
||||
let uv = if parse_uv {
|
||||
let u1 = f32_from_stack!(state, -nargs + i);
|
||||
let v1 = f32_from_stack!(state, -nargs + i + 1);
|
||||
let u2 = f32_from_stack!(state, -nargs + i + 2);
|
||||
let v2 = f32_from_stack!(state, -nargs + i + 3);
|
||||
i += 4;
|
||||
Some(Rect::new(Point::new(u1, v1), Point::new(u2, v2)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let layer_idx = if parse_layer_idx {
|
||||
let layer_idx = i32_from_stack!(state, -nargs + i);
|
||||
(layer_idx - 1) as u32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
ctx.recorder.draw_image(rect, texture_id, uv, layer_idx);
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
pub unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("draw_image_quad");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
assert!(
|
||||
matches!(nargs, 9 | 10 | 17 | 18),
|
||||
"Unexpected number of arguments"
|
||||
);
|
||||
|
||||
#[allow(clippy::manual_range_patterns)]
|
||||
let parse_uv = matches!(nargs, 17 | 18);
|
||||
let parse_layer_idx = matches!(nargs, 10 | 18);
|
||||
|
||||
let texture_id = unsafe { image_handle_texture_id(state, -nargs) };
|
||||
|
||||
// x1, y1, x2, y2, ...
|
||||
let x1 = f32_from_stack!(state, -nargs + 1);
|
||||
let y1 = f32_from_stack!(state, -nargs + 2);
|
||||
let x2 = f32_from_stack!(state, -nargs + 3);
|
||||
let y2 = f32_from_stack!(state, -nargs + 4);
|
||||
let x3 = f32_from_stack!(state, -nargs + 5);
|
||||
let y3 = f32_from_stack!(state, -nargs + 6);
|
||||
let x4 = f32_from_stack!(state, -nargs + 7);
|
||||
let y4 = f32_from_stack!(state, -nargs + 8);
|
||||
let quad = Quad::new(
|
||||
Point::new(x1, y1),
|
||||
Point::new(x2, y2),
|
||||
Point::new(x3, y3),
|
||||
Point::new(x4, y4),
|
||||
);
|
||||
|
||||
// u1, v1, u2, v2, ...
|
||||
let mut i = 9;
|
||||
let uv = if parse_uv {
|
||||
let u1 = f32_from_stack!(state, -nargs + i);
|
||||
let v1 = f32_from_stack!(state, -nargs + i + 1);
|
||||
let u2 = f32_from_stack!(state, -nargs + i + 2);
|
||||
let v2 = f32_from_stack!(state, -nargs + i + 3);
|
||||
let u3 = f32_from_stack!(state, -nargs + i + 4);
|
||||
let v3 = f32_from_stack!(state, -nargs + i + 5);
|
||||
let u4 = f32_from_stack!(state, -nargs + i + 6);
|
||||
let v4 = f32_from_stack!(state, -nargs + i + 7);
|
||||
i += 8;
|
||||
Some(Quad::new(
|
||||
Point::new(u1, v1),
|
||||
Point::new(u2, v2),
|
||||
Point::new(u3, v3),
|
||||
Point::new(u4, v4),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let layer_idx = if parse_layer_idx {
|
||||
let layer_idx = i32_from_stack!(state, -nargs + i);
|
||||
(layer_idx - 1) as u32
|
||||
} else {
|
||||
0
|
||||
};
|
||||
|
||||
ctx.recorder
|
||||
.draw_image_quad(quad, texture_id, uv, layer_idx);
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
pub fn get_draw_layer(l: &Lua, _: ()) -> LuaResult<i32> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
// matching PoB's behavior where only the sublayer is returned
|
||||
Ok(ctx.recorder.get_draw_layer().1)
|
||||
}
|
||||
|
||||
pub fn get_async_count(_: &Lua, _: ()) -> LuaResult<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn set_clear_color(_: &Lua, _: ()) -> LuaResult<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
@@ -19,7 +19,7 @@ pub fn new_search_handle(
|
||||
if handle.current.is_some() {
|
||||
return handle.into_lua(l);
|
||||
}
|
||||
};
|
||||
}
|
||||
Ok(Value::Nil)
|
||||
}
|
||||
|
||||
@@ -64,16 +64,19 @@ impl UserData for SearchHandle {
|
||||
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("GetFileSize", |_, this, ()| {
|
||||
Ok(this
|
||||
.current
|
||||
.as_ref()
|
||||
.and_then(|path| fs::metadata(path).ok())
|
||||
.map_or(0, |metadata| metadata.len()))
|
||||
});
|
||||
methods.add_method("GetFileModifiedTime", |_, this, ()| match &this.current {
|
||||
Some(path) => get_time_modified(path).map_or(Ok(0), Ok),
|
||||
None => Ok(0),
|
||||
methods.add_method("GetFileModifiedTime", |_, this, ()| {
|
||||
Ok(this
|
||||
.current
|
||||
.as_ref()
|
||||
.and_then(|path| get_time_modified(path).ok())
|
||||
.unwrap_or(0))
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use mlua::{Lua, MultiValue, Result as LuaResult};
|
||||
|
||||
use crate::pob::{Context, subscript::SubscriptManager};
|
||||
|
||||
pub fn launch_subscript(
|
||||
l: &Lua,
|
||||
(script_text, func_list, sub_list, args): (String, String, String, MultiValue),
|
||||
) -> LuaResult<u64> {
|
||||
let blocking_calls = func_list
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|&s| !s.is_empty())
|
||||
.map(String::from)
|
||||
.collect();
|
||||
let nonblocking_calls = sub_list
|
||||
.split(',')
|
||||
.map(str::trim)
|
||||
.filter(|&s| !s.is_empty())
|
||||
.map(String::from)
|
||||
.collect();
|
||||
let arguments = args.try_into()?;
|
||||
|
||||
let script_dir = l.app_data_ref::<Context>().unwrap().script_dir.clone();
|
||||
let subscript_id = l.app_data_mut::<SubscriptManager>().unwrap().push(
|
||||
script_dir,
|
||||
script_text,
|
||||
blocking_calls,
|
||||
nonblocking_calls,
|
||||
arguments,
|
||||
);
|
||||
|
||||
Ok(subscript_id)
|
||||
}
|
||||
|
||||
pub fn is_subscript_running(l: &Lua, subscript_id: u64) -> LuaResult<bool> {
|
||||
let manager = l.app_data_ref::<SubscriptManager>().unwrap();
|
||||
Ok(manager.is_running(subscript_id))
|
||||
}
|
||||
|
||||
pub fn abort_subscript(_: &Lua, _subscript_id: u64) -> LuaResult<()> {
|
||||
unimplemented!()
|
||||
}
|
||||
@@ -0,0 +1,717 @@
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
dpi::LogicalPoint,
|
||||
fonts::{Alignment, FontStyle, LayoutJob, LayoutToLogical},
|
||||
math::Point,
|
||||
pob::Context,
|
||||
};
|
||||
use core::ffi::c_int;
|
||||
use mlua::{
|
||||
Lua, Result as LuaResult,
|
||||
ffi::{self},
|
||||
};
|
||||
use parley::{FontFamily, FontFamilyName};
|
||||
use regex::Regex;
|
||||
use std::{borrow::Cow, sync::LazyLock};
|
||||
|
||||
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.cast::<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
|
||||
};
|
||||
}
|
||||
|
||||
pub fn strip_escapes(_: &Lua, text: String) -> LuaResult<String> {
|
||||
Ok(PoBString(&text).strip_escapes())
|
||||
}
|
||||
|
||||
pub unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("draw_string");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let mut ctx = lua_instance.app_data_mut::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
let x = f32_from_stack!(state, -nargs);
|
||||
let y = f32_from_stack!(state, -nargs + 1);
|
||||
let alignment = str_from_stack!(state, -nargs + 2);
|
||||
let line_height = i32_from_stack!(state, -nargs + 3);
|
||||
let font_type = str_from_stack!(state, -nargs + 4);
|
||||
let text = str_from_stack!(state, -nargs + 5);
|
||||
|
||||
let Ok(alignment) = alignment.parse::<PoBTextAlignment>() else {
|
||||
panic!("Invalid alignment");
|
||||
};
|
||||
let Ok(font_type) = font_type.parse::<PoBFontType>() else {
|
||||
panic!("Invalid font type");
|
||||
};
|
||||
|
||||
let mut position = LogicalPoint::new(x, y);
|
||||
let mut is_absolute_position = false;
|
||||
// the position needs to be adjusted for some alignments to match PoBs behavior
|
||||
let screen_size = ctx.window_state.logical_size();
|
||||
let halign = match alignment {
|
||||
PoBTextAlignment::Left => Alignment::Min,
|
||||
PoBTextAlignment::Center => {
|
||||
position.x += screen_size.width / 2.0;
|
||||
is_absolute_position = true;
|
||||
Alignment::Center
|
||||
}
|
||||
PoBTextAlignment::Right => {
|
||||
position.x = screen_size.width - position.x;
|
||||
is_absolute_position = true;
|
||||
Alignment::Max
|
||||
}
|
||||
PoBTextAlignment::CenterX => Alignment::Center,
|
||||
PoBTextAlignment::RightX => Alignment::Max,
|
||||
};
|
||||
|
||||
let current_draw_color = ctx.recorder.get_draw_color();
|
||||
let job = build_layout_job(
|
||||
text,
|
||||
current_draw_color,
|
||||
font_type,
|
||||
line_height,
|
||||
Some(halign),
|
||||
);
|
||||
|
||||
// NOTE: color escape codes modify the current draw color.
|
||||
// set current draw color to color of last segment to match PoB's behavior
|
||||
if let Some(last_segment) = job.segments.last() {
|
||||
ctx.recorder.set_draw_color(last_segment.color);
|
||||
}
|
||||
|
||||
let scale_factor = ctx.window_state.scale_factor();
|
||||
let layout = ctx.fonts.borrow_mut().layout(job, scale_factor);
|
||||
|
||||
// apply offset to account for anchor position
|
||||
let position = position + layout.anchor_offset(halign);
|
||||
// align layout anchor with the physical pixel grid to reduce blurriness
|
||||
let position = (position * scale_factor).round() / scale_factor;
|
||||
|
||||
for glyph in &layout.glyphs {
|
||||
ctx.recorder.draw_glyph(
|
||||
LayoutToLogical::new(position.x, position.y).transform_box(&glyph.rect),
|
||||
glyph.uv,
|
||||
glyph.color,
|
||||
glyph.layer_idx,
|
||||
is_absolute_position,
|
||||
);
|
||||
}
|
||||
|
||||
0
|
||||
}
|
||||
|
||||
pub unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_int {
|
||||
//profiling::scope!("get_string_width");
|
||||
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
|
||||
let ctx = lua_instance.app_data_ref::<Context>().unwrap();
|
||||
|
||||
let nargs = unsafe { ffi::lua_gettop(state) };
|
||||
|
||||
let line_height = i32_from_stack!(state, -nargs);
|
||||
let font_type = str_from_stack!(state, -nargs + 1);
|
||||
let text = str_from_stack!(state, -nargs + 2);
|
||||
|
||||
let Ok(font_type) = font_type.parse::<PoBFontType>() else {
|
||||
panic!("Invalid font type");
|
||||
};
|
||||
|
||||
let job = build_layout_job(text, Srgba::WHITE, font_type, line_height, None);
|
||||
let layout = ctx
|
||||
.fonts
|
||||
.borrow_mut()
|
||||
.layout(job, ctx.window_state.scale_factor());
|
||||
let width = layout.width();
|
||||
|
||||
unsafe { ffi::lua_pushnumber(state, f64::from(width)) };
|
||||
1
|
||||
}
|
||||
|
||||
pub fn get_index_at_cur(
|
||||
l: &Lua,
|
||||
(line_height, font_type, text, cur_x, cur_y): (i32, String, String, f32, f32),
|
||||
) -> LuaResult<usize> {
|
||||
//profiling::scope!("get_char_index_at_cur");
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
|
||||
let font_type = font_type.parse::<PoBFontType>()?;
|
||||
|
||||
let (job, offset_map) =
|
||||
build_layout_job_with_offsets(&text, Srgba::WHITE, font_type, line_height, None);
|
||||
let layout = ctx
|
||||
.fonts
|
||||
.borrow_mut()
|
||||
.layout(job, ctx.window_state.scale_factor());
|
||||
|
||||
// `cursor_index_at` returns an offset into the layout text, but PoB expects an offset into
|
||||
// the original text. A `LayoutTextToOriginalOffsetMap` handles the conversion.
|
||||
let layout_text_index = layout.cursor_index_at(Point::new(cur_x, cur_y));
|
||||
let original_index = offset_map.to_original(layout_text_index);
|
||||
|
||||
// convert to lua's 1-based indexing
|
||||
Ok(original_index + 1)
|
||||
}
|
||||
|
||||
pub static ESCAPE_STR_REGEX: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"\^(?<idx>[0-9])|\^[xX](?<hex>[0-9A-Fa-f]{6})").unwrap());
|
||||
|
||||
fn new_layout_job<'a>(
|
||||
font_type: PoBFontType,
|
||||
line_height: i32,
|
||||
alignment: Option<Alignment>,
|
||||
) -> LayoutJob<'a> {
|
||||
let mut font_weight = None;
|
||||
let mut font_style = FontStyle::default();
|
||||
let font_family = match font_type {
|
||||
PoBFontType::Fixed => FontFamily::Single(FontFamilyName::Named(Cow::Borrowed(
|
||||
"Bitstream Vera Sans Mono",
|
||||
))),
|
||||
PoBFontType::Var => {
|
||||
FontFamily::Single(FontFamilyName::Named(Cow::Borrowed("Liberation Sans")))
|
||||
}
|
||||
PoBFontType::VarBold => {
|
||||
font_weight = Some(700.0);
|
||||
FontFamily::Single(FontFamilyName::Named(Cow::Borrowed("Liberation Sans")))
|
||||
}
|
||||
PoBFontType::Fontin => FontFamily::Single(FontFamilyName::Named(Cow::Borrowed("Fontin"))),
|
||||
PoBFontType::FontinItalic => {
|
||||
FontFamily::Single(FontFamilyName::Named(Cow::Borrowed("Fontin")))
|
||||
}
|
||||
PoBFontType::FontinSmallcaps => {
|
||||
FontFamily::Single(FontFamilyName::Named(Cow::Borrowed("Fontin SmallCaps")))
|
||||
}
|
||||
PoBFontType::FontinSmallcapsItalic => {
|
||||
font_style = FontStyle::Italic;
|
||||
// use regular Smallcaps with "faux italics"
|
||||
FontFamily::Single(FontFamilyName::Named(Cow::Borrowed("Fontin SmallCaps")))
|
||||
}
|
||||
};
|
||||
|
||||
// NOTE: This is just an approximation and was chosen based on how it looks.
|
||||
//
|
||||
// PoB uses pre-rendered font atlases of discrete sizes and selects the appropriate
|
||||
// atlas based on the provided height. Rusty-PoB dynamically renders fonts to a
|
||||
// cached font atlas to support the selection of arbitrary sizes.
|
||||
//
|
||||
// TODO: font size in some dropdowns is too small, e.g. socket group selection in
|
||||
// 'Calcs' tab
|
||||
let font_size = (line_height - 2).max(1) as f32;
|
||||
|
||||
LayoutJob::new(
|
||||
font_family,
|
||||
font_size,
|
||||
line_height as f32,
|
||||
alignment,
|
||||
font_weight,
|
||||
font_style,
|
||||
)
|
||||
}
|
||||
|
||||
fn build_layout_job<'a>(
|
||||
text: &'a str,
|
||||
current_color: Srgba,
|
||||
font_type: PoBFontType,
|
||||
line_height: i32,
|
||||
alignment: Option<Alignment>,
|
||||
) -> LayoutJob<'a> {
|
||||
let mut job = new_layout_job(font_type, line_height, alignment);
|
||||
|
||||
for ColoredSegment {
|
||||
color,
|
||||
text,
|
||||
original_start: _,
|
||||
} in PoBString(text)
|
||||
{
|
||||
let color = color.unwrap_or(current_color);
|
||||
for (_, piece) in split_tabs(text) {
|
||||
job.append(piece.layout_text(), color);
|
||||
}
|
||||
}
|
||||
|
||||
job
|
||||
}
|
||||
|
||||
/// Tabs are replaced with four spaces to match SimpleGraphic's behavior.
|
||||
const TAB_REPLACEMENT: &str = " ";
|
||||
|
||||
/// A piece of text with tabs split out.
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
|
||||
enum TextPiece<'a> {
|
||||
Text(&'a str),
|
||||
Tab,
|
||||
}
|
||||
|
||||
impl<'a> TextPiece<'a> {
|
||||
/// Returns the text that is passed to the layout
|
||||
fn layout_text(self) -> &'a str {
|
||||
match self {
|
||||
Self::Text(text) => text,
|
||||
Self::Tab => TAB_REPLACEMENT,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits `text` at tab characters. Yields each piece alongside its byte offset into `text`.
|
||||
fn split_tabs(text: &str) -> impl Iterator<Item = (usize, TextPiece<'_>)> {
|
||||
let mut offset = 0;
|
||||
text.split('\t').enumerate().flat_map(move |(i, piece)| {
|
||||
// every piece after the first one is preceded by a tab
|
||||
let tab = (i > 0).then(|| (offset - 1, TextPiece::Tab));
|
||||
let text_piece = (offset, TextPiece::Text(piece));
|
||||
offset += piece.len() + 1;
|
||||
tab.into_iter().chain(std::iter::once(text_piece))
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct OffsetSegment {
|
||||
layout_text_start: usize,
|
||||
original_start: usize,
|
||||
is_tab: bool,
|
||||
}
|
||||
|
||||
/// Maps a byte offset in the layout text back to an offset in the original text.
|
||||
///
|
||||
/// The layout text is the text passed to `parley`, i.e. without color escapes and with tabs
|
||||
/// replaced by spaces.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
struct LayoutTextToOriginalOffsetMap {
|
||||
segments: Vec<OffsetSegment>,
|
||||
}
|
||||
|
||||
impl LayoutTextToOriginalOffsetMap {
|
||||
fn push_segment(&mut self, layout_text_start: usize, original_start: usize) {
|
||||
self.segments.push(OffsetSegment {
|
||||
layout_text_start,
|
||||
original_start,
|
||||
is_tab: false,
|
||||
});
|
||||
}
|
||||
|
||||
fn push_tab(&mut self, layout_text_start: usize, original_start: usize) {
|
||||
self.segments.push(OffsetSegment {
|
||||
layout_text_start,
|
||||
original_start,
|
||||
is_tab: true,
|
||||
});
|
||||
}
|
||||
|
||||
fn to_original(&self, layout_text_index: usize) -> usize {
|
||||
assert!(!self.segments.is_empty());
|
||||
let i = self
|
||||
.segments
|
||||
.partition_point(|seg| seg.layout_text_start <= layout_text_index);
|
||||
let seg = self.segments[i - 1];
|
||||
if seg.is_tab {
|
||||
// map any cursor position within a tab to the start of it like SG
|
||||
seg.original_start
|
||||
} else {
|
||||
seg.original_start + (layout_text_index - seg.layout_text_start)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a `LayoutTextToOriginalOffsetMap` alongside the `LayoutJob`.
|
||||
fn build_layout_job_with_offsets<'a>(
|
||||
text: &'a str,
|
||||
current_color: Srgba,
|
||||
font_type: PoBFontType,
|
||||
line_height: i32,
|
||||
alignment: Option<Alignment>,
|
||||
) -> (LayoutJob<'a>, LayoutTextToOriginalOffsetMap) {
|
||||
let mut job = new_layout_job(font_type, line_height, alignment);
|
||||
let mut offset_map = LayoutTextToOriginalOffsetMap::default();
|
||||
let mut layout_text_offset = 0;
|
||||
|
||||
for ColoredSegment {
|
||||
color,
|
||||
text,
|
||||
original_start,
|
||||
} in PoBString(text)
|
||||
{
|
||||
let color = color.unwrap_or(current_color);
|
||||
for (offset, piece) in split_tabs(text) {
|
||||
match piece {
|
||||
TextPiece::Text(_) => {
|
||||
offset_map.push_segment(layout_text_offset, original_start + offset);
|
||||
}
|
||||
TextPiece::Tab => offset_map.push_tab(layout_text_offset, original_start + offset),
|
||||
}
|
||||
let layout_text = piece.layout_text();
|
||||
job.append(layout_text, color);
|
||||
layout_text_offset += layout_text.len();
|
||||
}
|
||||
}
|
||||
|
||||
(job, offset_map)
|
||||
}
|
||||
|
||||
/// A string constructed by Lua which may contain color escapes.
|
||||
pub struct PoBString<'a>(pub &'a str);
|
||||
|
||||
impl<'a> PoBString<'a> {
|
||||
/// Returns a copy of the string with all color escapes removed.
|
||||
pub fn strip_escapes(&self) -> String {
|
||||
ESCAPE_STR_REGEX.replace_all(self.0, "").to_string()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoIterator for PoBString<'a> {
|
||||
type Item = ColoredSegment<'a>;
|
||||
type IntoIter = PoBStringSegmentIterator<'a>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
PoBStringSegmentIterator::new(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// A segment of text that shares the same color.
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
|
||||
pub struct ColoredSegment<'a> {
|
||||
pub color: Option<Srgba>,
|
||||
pub text: &'a str,
|
||||
/// The byte offset of `text` within the **original** string.
|
||||
pub original_start: usize,
|
||||
}
|
||||
|
||||
/// Iterates over the [`ColoredSegment`]s of a [`PoBString`].
|
||||
pub struct PoBStringSegmentIterator<'a> {
|
||||
haystack: &'a str,
|
||||
captures: regex::CaptureMatches<'static, 'a>,
|
||||
/// Byte offset in `haystack` where the next segment's text begins.
|
||||
cursor: usize,
|
||||
/// Color of the next segment.
|
||||
color: Option<Srgba>,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
impl<'a> PoBStringSegmentIterator<'a> {
|
||||
fn new(haystack: &'a str) -> Self {
|
||||
Self {
|
||||
haystack,
|
||||
captures: ESCAPE_STR_REGEX.captures_iter(haystack),
|
||||
cursor: 0,
|
||||
color: None,
|
||||
done: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for PoBStringSegmentIterator<'a> {
|
||||
type Item = ColoredSegment<'a>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.done {
|
||||
return None;
|
||||
}
|
||||
|
||||
loop {
|
||||
if let Some(captures) = self.captures.next() {
|
||||
let m = &captures.get(0).expect("group 0 always matches");
|
||||
let start = self.cursor;
|
||||
let text = &self.haystack[start..m.start()];
|
||||
let color = self.color;
|
||||
|
||||
self.cursor = m.end();
|
||||
self.color = Some(Srgba::from_escape_code(m.as_str()));
|
||||
|
||||
// check for case where string starts with escape code
|
||||
if text.is_empty() && color.is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
return Some(ColoredSegment {
|
||||
color,
|
||||
text,
|
||||
original_start: start,
|
||||
});
|
||||
}
|
||||
|
||||
self.done = true;
|
||||
return Some(ColoredSegment {
|
||||
color: self.color,
|
||||
text: &self.haystack[self.cursor..],
|
||||
original_start: self.cursor,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PoB's alignment argument is weird!
|
||||
// It controls:
|
||||
// - the alignment within the text box
|
||||
// - the anchor point of the box
|
||||
// - the relative/absolute positioning of the box
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum PoBTextAlignment {
|
||||
// alignment: left | anchor: top-left corner | position: relative to viewport
|
||||
Left,
|
||||
// alignment: center | anchor: top-center | position: relative to center of screen
|
||||
Center,
|
||||
// alignment: right | anchor: top-right | position: relative to right edge of screen
|
||||
Right,
|
||||
// alignment: center | anchor: top-center | position: relative to viewport
|
||||
CenterX,
|
||||
// alignment: right | anchor: top-right corner | position: relative to viewport
|
||||
RightX,
|
||||
}
|
||||
|
||||
impl std::str::FromStr for PoBTextAlignment {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"LEFT" => Ok(Self::Left),
|
||||
"CENTER" => Ok(Self::Center),
|
||||
"RIGHT" => Ok(Self::Right),
|
||||
"CENTER_X" => Ok(Self::CenterX),
|
||||
"RIGHT_X" => Ok(Self::RightX),
|
||||
_ => Err(anyhow::anyhow!(
|
||||
"'{s}' is not a valid PoBTextAlignment variant"
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum PoBFontType {
|
||||
Fixed,
|
||||
Var,
|
||||
VarBold,
|
||||
FontinSmallcaps,
|
||||
FontinSmallcapsItalic,
|
||||
Fontin,
|
||||
FontinItalic,
|
||||
}
|
||||
|
||||
impl std::str::FromStr for PoBFontType {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s {
|
||||
"FIXED" => Ok(Self::Fixed),
|
||||
"VAR" => Ok(Self::Var),
|
||||
"VAR BOLD" => Ok(Self::VarBold),
|
||||
"FONTIN SC" => Ok(Self::FontinSmallcaps),
|
||||
"FONTIN SC ITALIC" => Ok(Self::FontinSmallcapsItalic),
|
||||
"FONTIN" => Ok(Self::Fontin),
|
||||
"FONTIN ITALIC" => Ok(Self::FontinItalic),
|
||||
_ => Err(anyhow::anyhow!("'{s}' is not a valid PoBFontType variant")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// helper for collecting segments
|
||||
fn segs(text: &str) -> Vec<(Option<Srgba>, &str, usize)> {
|
||||
PoBString(text)
|
||||
.into_iter()
|
||||
.map(|s| (s.color, s.text, s.original_start))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_segment() {
|
||||
assert_eq!(segs("Hello, world!"), vec![(None, "Hello, world!", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_string() {
|
||||
assert_eq!(segs(""), vec![(None, "", 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_at_start() {
|
||||
assert_eq!(
|
||||
segs("^3Hello, world!"),
|
||||
vec![(Some(Srgba::from_rgb(0, 0, 255)), "Hello, world!", 2)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_escape_at_start() {
|
||||
assert_eq!(
|
||||
segs("Hello, ^1world!"),
|
||||
vec![
|
||||
(None, "Hello, ", 0),
|
||||
(Some(Srgba::from_rgb(255, 0, 0)), "world!", 9)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_escapes() {
|
||||
assert_eq!(
|
||||
segs("Hello, ^1^2world!"),
|
||||
vec![
|
||||
(None, "Hello, ", 0),
|
||||
(Some(Srgba::from_rgb(255, 0, 0)), "", 9),
|
||||
(Some(Srgba::from_rgb(0, 255, 0)), "world!", 11)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_escape() {
|
||||
assert_eq!(
|
||||
segs("Hello, world!^3"),
|
||||
vec![
|
||||
(None, "Hello, world!", 0),
|
||||
(Some(Srgba::from_rgb(0, 0, 255)), "", 15),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_escape() {
|
||||
assert_eq!(
|
||||
segs("^xFF0000Hello, ^X00ff00world!"),
|
||||
vec![
|
||||
(Some(Srgba::from_rgb(255, 0, 0)), "Hello, ", 8),
|
||||
(Some(Srgba::from_rgb(0, 255, 0)), "world!", 23),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_offset_empty() {
|
||||
let mut offset_map = LayoutTextToOriginalOffsetMap::default();
|
||||
for seg in PoBString("") {
|
||||
offset_map.push_segment(0, seg.original_start);
|
||||
}
|
||||
assert_eq!(offset_map.to_original(0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_offset_no_escape() {
|
||||
let mut offset_map = LayoutTextToOriginalOffsetMap::default();
|
||||
let mut layout_text_offset = 0;
|
||||
for seg in PoBString("Hello, World!") {
|
||||
offset_map.push_segment(layout_text_offset, seg.original_start);
|
||||
layout_text_offset += seg.text.len();
|
||||
}
|
||||
assert_eq!(offset_map.to_original(0), 0);
|
||||
assert_eq!(offset_map.to_original(3), 3);
|
||||
assert_eq!(offset_map.to_original(6), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_offset() {
|
||||
let mut offset_map = LayoutTextToOriginalOffsetMap::default();
|
||||
let mut layout_text_offset = 0;
|
||||
for seg in PoBString("^1Hello^xFF0000World^3!") {
|
||||
offset_map.push_segment(layout_text_offset, seg.original_start);
|
||||
layout_text_offset += seg.text.len();
|
||||
}
|
||||
assert_eq!(offset_map.to_original(0), 2);
|
||||
assert_eq!(offset_map.to_original(3), 5);
|
||||
assert_eq!(offset_map.to_original(6), 16);
|
||||
assert_eq!(offset_map.to_original(11), 23);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_tabs_no_tabs() {
|
||||
assert_eq!(
|
||||
split_tabs("Hello").collect::<Vec<_>>(),
|
||||
vec![(0, TextPiece::Text("Hello"))]
|
||||
);
|
||||
assert_eq!(
|
||||
split_tabs("").collect::<Vec<_>>(),
|
||||
vec![(0, TextPiece::Text(""))]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_tabs_with_tabs() {
|
||||
assert_eq!(
|
||||
split_tabs("a\tbc\t\td\t").collect::<Vec<_>>(),
|
||||
vec![
|
||||
(0, TextPiece::Text("a")),
|
||||
(1, TextPiece::Tab),
|
||||
(2, TextPiece::Text("bc")),
|
||||
(4, TextPiece::Tab),
|
||||
(5, TextPiece::Text("")),
|
||||
(5, TextPiece::Tab),
|
||||
(6, TextPiece::Text("d")),
|
||||
(7, TextPiece::Tab),
|
||||
(8, TextPiece::Text("")),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
fn layout_text(job: &LayoutJob) -> String {
|
||||
job.segments.iter().map(|s| s.text).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_replaced_with_spaces() {
|
||||
let job = build_layout_job("^1a\tb^2\tc", Srgba::WHITE, PoBFontType::Var, 16, None);
|
||||
assert_eq!(layout_text(&job), "a b c");
|
||||
|
||||
// tabs keep the color of the segment they're in
|
||||
let red = Srgba::from_rgb(255, 0, 0);
|
||||
let green = Srgba::from_rgb(0, 255, 0);
|
||||
let colors: Vec<_> = job.segments.iter().map(|s| s.color).collect();
|
||||
assert_eq!(colors, vec![red, red, red, green, green, green]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_offset_with_tabs() {
|
||||
let (job, offset_map) =
|
||||
build_layout_job_with_offsets("^1a\tb\t", Srgba::WHITE, PoBFontType::Var, 16, None);
|
||||
assert_eq!(layout_text(&job), "a b ");
|
||||
|
||||
// 'a'
|
||||
assert_eq!(offset_map.to_original(0), 2);
|
||||
// first tab: any position within the tab maps to the tab start
|
||||
assert_eq!(offset_map.to_original(1), 3);
|
||||
assert_eq!(offset_map.to_original(2), 3);
|
||||
assert_eq!(offset_map.to_original(4), 3);
|
||||
// 'b'
|
||||
assert_eq!(offset_map.to_original(5), 4);
|
||||
// trailing tab: any position within the tab maps to the tab start
|
||||
assert_eq!(offset_map.to_original(6), 5);
|
||||
assert_eq!(offset_map.to_original(9), 5);
|
||||
// end of text is after the trailing tab
|
||||
assert_eq!(offset_map.to_original(10), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cursor_offset_with_consecutive_tabs() {
|
||||
let (job, offset_map) =
|
||||
build_layout_job_with_offsets("a\t\tb", Srgba::WHITE, PoBFontType::Var, 16, None);
|
||||
assert_eq!(layout_text(&job), "a b");
|
||||
assert_eq!(offset_map.to_original(0), 0);
|
||||
|
||||
// first tab
|
||||
for layout_text_index in 1..=4 {
|
||||
assert_eq!(offset_map.to_original(layout_text_index), 1);
|
||||
}
|
||||
|
||||
// second tab, which starts immediately after the first one
|
||||
for layout_text_index in 5..=8 {
|
||||
assert_eq!(offset_map.to_original(layout_text_index), 2);
|
||||
}
|
||||
assert_eq!(offset_map.to_original(9), 3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
use crate::{
|
||||
dpi::{LogicalSize, PhysicalSize},
|
||||
pob::Context,
|
||||
};
|
||||
use mlua::{Lua, Result as LuaResult};
|
||||
|
||||
pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
let size = if ctx.is_dpi_aware {
|
||||
let PhysicalSize { width, height, .. } = ctx.window_state.size;
|
||||
(width, height)
|
||||
} else {
|
||||
let LogicalSize { width, height, .. } = ctx.window_state.logical_size().cast();
|
||||
(width, height)
|
||||
};
|
||||
Ok(size)
|
||||
}
|
||||
|
||||
pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult<f32> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
let scale_factor = ctx.window_state.scale_factor();
|
||||
Ok(scale_factor.get())
|
||||
}
|
||||
|
||||
pub fn set_window_title(l: &Lua, title: String) -> LuaResult<()> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
ctx.window_state.set_window_title(&title);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_foreground(l: &Lua, _: ()) -> LuaResult<()> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
ctx.window_state.focus();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_dpi_scale_override(l: &Lua, percent: i32) -> LuaResult<()> {
|
||||
let mut ctx = l.app_data_mut::<Context>().unwrap();
|
||||
match percent {
|
||||
0 => ctx.window_state.set_scale_factor_override(None),
|
||||
p if p > 0 => ctx
|
||||
.window_state
|
||||
.set_scale_factor_override(Some(p as f32 / 100.0)),
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_dpi_scale_override(l: &Lua, _: ()) -> LuaResult<i32> {
|
||||
let ctx = l.app_data_ref::<Context>().unwrap();
|
||||
match ctx.window_state.scale_factor_override() {
|
||||
Some(scale_factor) => Ok((scale_factor * 100.0) as i32),
|
||||
None => Ok(0),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#[cfg(feature = "bundled-lua-modules")]
|
||||
pub mod luacurl;
|
||||
#[cfg(feature = "bundled-lua-modules")]
|
||||
pub mod luasocket;
|
||||
#[cfg(feature = "bundled-lua-modules")]
|
||||
pub mod luazip;
|
||||
|
||||
use mlua::{Lua, Result as LuaResult};
|
||||
|
||||
/// Registers Rust implementations of the Lua modules required by PoB's Lua code.
|
||||
pub fn register(lua: &Lua) -> LuaResult<()> {
|
||||
lua.register_module("lua-utf8", luautf8::create_module(lua)?)?;
|
||||
lua.register_module("socket", luasocket::create_module(lua)?)?;
|
||||
lua.register_module("lcurl.safe", luacurl::create_module(lua)?)?;
|
||||
lua.register_module("lzip", luazip::create_module(lua)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Nothing is registered so Lua resolves the required modules through `package.cpath`.
|
||||
#[cfg(not(feature = "bundled-lua-modules"))]
|
||||
pub fn register(_lua: &Lua) -> LuaResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use mlua::{Lua, Result as LuaResult, Table};
|
||||
|
||||
use crate::pob::modules::luacurl::easy::EasyHandle;
|
||||
|
||||
mod constants;
|
||||
mod easy;
|
||||
|
||||
pub fn create_module(lua: &Lua) -> LuaResult<Table> {
|
||||
let exports = lua.create_table()?;
|
||||
|
||||
exports.set("easy", lua.create_function(|_, ()| Ok(EasyHandle::new()))?)?;
|
||||
|
||||
exports.set("OPT_ACCEPT_ENCODING", constants::OPT_ACCEPT_ENCODING)?;
|
||||
exports.set("OPT_FOLLOWLOCATION", constants::OPT_FOLLOWLOCATION)?;
|
||||
exports.set("OPT_HTTPHEADER", constants::OPT_HTTPHEADER)?;
|
||||
exports.set("OPT_IPRESOLVE", constants::OPT_IPRESOLVE)?;
|
||||
exports.set("OPT_POST", constants::OPT_POST)?;
|
||||
exports.set("OPT_POSTFIELDS", constants::OPT_POSTFIELDS)?;
|
||||
exports.set("OPT_PROXY", constants::OPT_PROXY)?;
|
||||
exports.set("OPT_SSL_VERIFYHOST", constants::OPT_SSL_VERIFYHOST)?;
|
||||
exports.set("OPT_SSL_VERIFYPEER", constants::OPT_SSL_VERIFYPEER)?;
|
||||
exports.set("OPT_USERAGENT", constants::OPT_USERAGENT)?;
|
||||
|
||||
exports.set("INFO_RESPONSE_CODE", constants::INFO_RESPONSE_CODE)?;
|
||||
exports.set("INFO_SIZE_DOWNLOAD", constants::INFO_SIZE_DOWNLOAD)?;
|
||||
exports.set("INFO_REDIRECT_URL", constants::INFO_REDIRECT_URL)?;
|
||||
|
||||
Ok(exports)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
pub type CURLoption = i64;
|
||||
pub type CURLinfo = i64;
|
||||
|
||||
const CURLOPTTYPE_LONG: CURLoption = 0;
|
||||
const CURLOPTTYPE_OBJECTPOINT: CURLoption = 10_000;
|
||||
|
||||
pub const OPT_URL: CURLoption = CURLOPTTYPE_OBJECTPOINT + 2;
|
||||
pub const OPT_PROXY: CURLoption = CURLOPTTYPE_OBJECTPOINT + 4;
|
||||
pub const OPT_POSTFIELDS: CURLoption = CURLOPTTYPE_OBJECTPOINT + 15;
|
||||
pub const OPT_USERAGENT: CURLoption = CURLOPTTYPE_OBJECTPOINT + 18;
|
||||
pub const OPT_HTTPHEADER: CURLoption = CURLOPTTYPE_OBJECTPOINT + 23;
|
||||
pub const OPT_POST: CURLoption = CURLOPTTYPE_LONG + 47;
|
||||
pub const OPT_FOLLOWLOCATION: CURLoption = CURLOPTTYPE_LONG + 52;
|
||||
pub const OPT_SSL_VERIFYPEER: CURLoption = CURLOPTTYPE_LONG + 64;
|
||||
pub const OPT_SSL_VERIFYHOST: CURLoption = CURLOPTTYPE_LONG + 81;
|
||||
pub const OPT_ACCEPT_ENCODING: CURLoption = CURLOPTTYPE_OBJECTPOINT + 102;
|
||||
pub const OPT_IPRESOLVE: CURLoption = CURLOPTTYPE_LONG + 113;
|
||||
|
||||
const CURLINFO_STRING: CURLinfo = 0x100000;
|
||||
const CURLINFO_LONG: CURLinfo = 0x200000;
|
||||
const CURLINFO_DOUBLE: CURLinfo = 0x300000;
|
||||
|
||||
pub const INFO_RESPONSE_CODE: CURLinfo = CURLINFO_LONG + 2;
|
||||
pub const INFO_SIZE_DOWNLOAD: CURLinfo = CURLINFO_DOUBLE + 8;
|
||||
pub const INFO_REDIRECT_URL: CURLinfo = CURLINFO_STRING + 31;
|
||||
@@ -0,0 +1,290 @@
|
||||
use curl::easy::{Easy, IpResolve};
|
||||
use mlua::{
|
||||
Error as LuaError, IntoLua, Lua, LuaString, RegistryKey, Result as LuaResult, UserData,
|
||||
UserDataMethods,
|
||||
};
|
||||
|
||||
use crate::pob::modules::luacurl::constants;
|
||||
|
||||
/// Helper for constructing a `mlua::Error::BadArgument`
|
||||
fn bad_argument(to: impl Into<String>, pos: usize, cause: &'static str) -> LuaError {
|
||||
#[allow(clippy::arc_with_non_send_sync)]
|
||||
LuaError::BadArgument {
|
||||
to: Some(to.into()),
|
||||
pos: pos + 1,
|
||||
name: None,
|
||||
cause: std::sync::Arc::new(LuaError::runtime(cause)),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct EasyHandle {
|
||||
easy: Option<Easy>,
|
||||
write_callback: Option<RegistryKey>,
|
||||
header_callback: Option<RegistryKey>,
|
||||
}
|
||||
|
||||
impl EasyHandle {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
easy: Some(Easy::new()),
|
||||
write_callback: None,
|
||||
header_callback: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn curl(&mut self) -> LuaResult<&mut Easy> {
|
||||
self.easy
|
||||
.as_mut()
|
||||
.ok_or_else(|| LuaError::runtime("curl handle is closed"))
|
||||
}
|
||||
|
||||
pub fn close(&mut self, lua: &Lua) -> LuaResult<()> {
|
||||
if let Some(key) = self.write_callback.take() {
|
||||
lua.remove_registry_value(key)?;
|
||||
}
|
||||
|
||||
if let Some(key) = self.header_callback.take() {
|
||||
lua.remove_registry_value(key)?;
|
||||
}
|
||||
|
||||
self.easy = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// TODO: handling of `value` might not be 100% correct w.r.t. casting and mapping
|
||||
// of number values to arguments of `easy` methods. extract to helper functions.
|
||||
pub fn set_option(&mut self, option: i64, value: mlua::Value) -> LuaResult<()> {
|
||||
let easy = self.curl()?;
|
||||
|
||||
match option {
|
||||
constants::OPT_ACCEPT_ENCODING => {
|
||||
let encoding = match value {
|
||||
mlua::Value::String(s) => s.to_str(),
|
||||
_ => Err(bad_argument("setopt", 1, "string expected")),
|
||||
}?;
|
||||
easy.accept_encoding(&encoding)
|
||||
.map_err(LuaError::external)?;
|
||||
}
|
||||
constants::OPT_FOLLOWLOCATION => {
|
||||
let enable = match value {
|
||||
mlua::Value::Boolean(b) => Ok(b),
|
||||
mlua::Value::Integer(n) => Ok(n != 0),
|
||||
mlua::Value::Number(n) => Ok(n != 0.0),
|
||||
_ => Err(bad_argument("setopt", 1, "number or boolean expected")),
|
||||
}?;
|
||||
easy.follow_location(enable).map_err(LuaError::external)?;
|
||||
}
|
||||
constants::OPT_HTTPHEADER => {
|
||||
let headers = match value {
|
||||
mlua::Value::Table(t) => Ok(t),
|
||||
_ => Err(bad_argument("setopt", 1, "array expected")),
|
||||
}?;
|
||||
|
||||
let mut list = curl::easy::List::new();
|
||||
for header in headers.sequence_values::<String>() {
|
||||
list.append(&header?).map_err(LuaError::external)?;
|
||||
}
|
||||
|
||||
easy.http_headers(list).map_err(LuaError::external)?;
|
||||
}
|
||||
constants::OPT_IPRESOLVE => {
|
||||
let resolve = match value {
|
||||
mlua::Value::Integer(0) => Ok(IpResolve::Any),
|
||||
mlua::Value::Integer(1) => Ok(IpResolve::V4),
|
||||
mlua::Value::Integer(2) => Ok(IpResolve::V6),
|
||||
_ => Err(bad_argument("setopt", 1, "number or boolean expected")),
|
||||
}?;
|
||||
easy.ip_resolve(resolve).map_err(LuaError::external)?;
|
||||
}
|
||||
constants::OPT_POST => {
|
||||
let enable = match value {
|
||||
mlua::Value::Boolean(b) => Ok(b),
|
||||
mlua::Value::Integer(n) => Ok(n != 0),
|
||||
mlua::Value::Number(n) => Ok(n != 0.0),
|
||||
_ => Err(bad_argument("setopt", 1, "number or boolean expected")),
|
||||
}?;
|
||||
easy.post(enable).map_err(LuaError::external)?;
|
||||
}
|
||||
constants::OPT_POSTFIELDS => {
|
||||
let data = match value {
|
||||
mlua::Value::String(s) => Ok(s.as_bytes()),
|
||||
_ => Err(bad_argument("setopt", 1, "string expected")),
|
||||
}?;
|
||||
easy.post_fields_copy(&data).map_err(LuaError::external)?;
|
||||
}
|
||||
constants::OPT_PROXY => {
|
||||
let proxy = match value {
|
||||
mlua::Value::String(s) => s.to_str(),
|
||||
_ => Err(bad_argument("setopt", 1, "string expected")),
|
||||
}?;
|
||||
easy.proxy(&proxy).map_err(LuaError::external)?;
|
||||
}
|
||||
constants::OPT_SSL_VERIFYHOST => {
|
||||
let verify = match value {
|
||||
mlua::Value::Boolean(b) => Ok(b),
|
||||
mlua::Value::Integer(n) => Ok(n != 0),
|
||||
mlua::Value::Number(n) => Ok(n != 0.0),
|
||||
_ => Err(bad_argument("setopt", 1, "number or boolean expected")),
|
||||
}?;
|
||||
easy.ssl_verify_host(verify).map_err(LuaError::external)?;
|
||||
}
|
||||
constants::OPT_SSL_VERIFYPEER => {
|
||||
let verify = match value {
|
||||
mlua::Value::Boolean(b) => Ok(b),
|
||||
mlua::Value::Integer(n) => Ok(n != 0),
|
||||
mlua::Value::Number(n) => Ok(n != 0.0),
|
||||
_ => Err(bad_argument("setopt", 1, "number or boolean expected")),
|
||||
}?;
|
||||
easy.ssl_verify_peer(verify).map_err(LuaError::external)?;
|
||||
}
|
||||
constants::OPT_USERAGENT => {
|
||||
let useragent = match value {
|
||||
mlua::Value::String(s) => s.to_str(),
|
||||
_ => Err(bad_argument("setopt", 1, "string expected")),
|
||||
}?;
|
||||
easy.useragent(&useragent).map_err(LuaError::external)?;
|
||||
}
|
||||
constants::OPT_URL => {
|
||||
let url = match value {
|
||||
mlua::Value::String(s) => s.to_str(),
|
||||
_ => Err(bad_argument("setopt", 1, "string expected")),
|
||||
}?;
|
||||
easy.url(&url).map_err(LuaError::external)?;
|
||||
}
|
||||
_ => unimplemented!("Unsupported `setopt` option: {option}"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_callback(
|
||||
lua: &Lua,
|
||||
slot: &mut Option<RegistryKey>,
|
||||
value: mlua::Value,
|
||||
) -> LuaResult<()> {
|
||||
let new_key = match value {
|
||||
mlua::Value::Nil => None,
|
||||
mlua::Value::Function(f) => Some(lua.create_registry_value(f)?),
|
||||
_ => return Err(LuaError::runtime("invalid object type")),
|
||||
};
|
||||
|
||||
if let Some(old_key) = slot.take() {
|
||||
lua.remove_registry_value(old_key)?;
|
||||
}
|
||||
|
||||
*slot = new_key;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn perform(&mut self, lua: &Lua) -> LuaResult<()> {
|
||||
let write_fn = self
|
||||
.write_callback
|
||||
.as_ref()
|
||||
.map(|key| lua.registry_value::<mlua::Function>(key))
|
||||
.transpose()?;
|
||||
|
||||
let header_fn = self
|
||||
.header_callback
|
||||
.as_ref()
|
||||
.map(|key| lua.registry_value::<mlua::Function>(key))
|
||||
.transpose()?;
|
||||
|
||||
let transfer_result = {
|
||||
let mut transfer = self.curl()?.transfer();
|
||||
|
||||
if let Some(function) = write_fn {
|
||||
transfer
|
||||
.write_function(move |data| {
|
||||
let Ok(argument) = lua.create_string(data) else {
|
||||
return Ok(0);
|
||||
};
|
||||
|
||||
match function.call::<()>(argument) {
|
||||
Ok(()) => Ok(data.len()),
|
||||
Err(_) => Ok(0),
|
||||
}
|
||||
})
|
||||
.map_err(LuaError::external)?;
|
||||
}
|
||||
|
||||
if let Some(function) = header_fn {
|
||||
transfer
|
||||
.header_function(move |data| {
|
||||
let Ok(argument) = lua.create_string(data) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
function.call::<bool>(argument).unwrap_or(false)
|
||||
})
|
||||
.map_err(LuaError::external)?;
|
||||
}
|
||||
|
||||
transfer.perform()
|
||||
};
|
||||
|
||||
transfer_result.map_err(LuaError::external)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_info(&mut self, lua: &Lua, info: i64) -> LuaResult<mlua::Value> {
|
||||
let easy = self.curl()?;
|
||||
|
||||
match info {
|
||||
constants::INFO_REDIRECT_URL => {
|
||||
let url = easy.redirect_url().map_err(LuaError::external)?;
|
||||
url.into_lua(lua)
|
||||
}
|
||||
constants::INFO_RESPONSE_CODE => {
|
||||
let code = easy.response_code().map_err(LuaError::external)?;
|
||||
code.into_lua(lua)
|
||||
}
|
||||
constants::INFO_SIZE_DOWNLOAD => {
|
||||
let size = easy.download_size().map_err(LuaError::external)?;
|
||||
size.into_lua(lua)
|
||||
}
|
||||
_ => unimplemented!("Unsupported `getinfo` key: {info}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UserData for EasyHandle {
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_method("escape", |lua, _, value: LuaString| {
|
||||
let input = value.as_bytes();
|
||||
let mut easy = Easy::new();
|
||||
let escaped = easy.url_encode(input.as_ref());
|
||||
lua.create_string(escaped)
|
||||
});
|
||||
|
||||
methods.add_method_mut("close", |lua, this, ()| this.close(lua));
|
||||
|
||||
methods.add_method_mut("setopt", |_, this, (option, value): (i64, mlua::Value)| {
|
||||
this.set_option(option, value)
|
||||
});
|
||||
|
||||
methods.add_method_mut("setopt_url", |_, this, value: mlua::Value| {
|
||||
this.set_option(constants::OPT_URL, value)
|
||||
});
|
||||
methods.add_method_mut("setopt_useragent", |_, this, value: mlua::Value| {
|
||||
this.set_option(constants::OPT_USERAGENT, value)
|
||||
});
|
||||
|
||||
methods.add_method_mut("setopt_writefunction", |lua, this, value: mlua::Value| {
|
||||
Self::set_callback(lua, &mut this.write_callback, value)
|
||||
});
|
||||
|
||||
methods.add_method_mut("setopt_headerfunction", |lua, this, value: mlua::Value| {
|
||||
Self::set_callback(lua, &mut this.header_callback, value)
|
||||
});
|
||||
|
||||
methods.add_method_mut("perform", |lua, this, ()| this.perform(lua));
|
||||
|
||||
methods.add_method_mut("getinfo", |lua, this, info: i64| this.get_info(lua, info));
|
||||
|
||||
methods.add_method_mut("getinfo_response_code", |lua, this, ()| {
|
||||
this.get_info(lua, constants::INFO_RESPONSE_CODE)
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
//! Rust port of subset of [`luasocket`](https://github.com/lunarmodules/luasocket) API.
|
||||
|
||||
use std::{
|
||||
io::{self, BufRead, BufReader, Write},
|
||||
net::{TcpListener, TcpStream, ToSocketAddrs},
|
||||
thread,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use mlua::{Integer as LuaInteger, Lua, Result as LuaResult, Table, UserData, UserDataMethods};
|
||||
|
||||
pub fn create_module(lua: &Lua) -> LuaResult<Table> {
|
||||
let exports = lua.create_table()?;
|
||||
|
||||
exports.set(
|
||||
"tcp4",
|
||||
lua.create_function(|_, ()| {
|
||||
Ok(LuaTcpIp4Server {
|
||||
listener: None,
|
||||
timeout: None,
|
||||
})
|
||||
})?,
|
||||
)?;
|
||||
|
||||
Ok(exports)
|
||||
}
|
||||
|
||||
/// Helper for constructing a `mlua::Error::BadArgument`
|
||||
fn bad_argument(to: impl Into<String>, pos: usize, cause: mlua::Error) -> mlua::Error {
|
||||
#[allow(clippy::arc_with_non_send_sync)]
|
||||
mlua::Error::BadArgument {
|
||||
to: Some(to.into()),
|
||||
pos: pos + 1,
|
||||
name: None,
|
||||
cause: std::sync::Arc::new(cause),
|
||||
}
|
||||
}
|
||||
|
||||
struct LuaTcpIp4Server {
|
||||
listener: Option<TcpListener>,
|
||||
timeout: Option<Duration>,
|
||||
}
|
||||
|
||||
struct LuaTcpClient {
|
||||
reader: BufReader<TcpStream>,
|
||||
timeout: Option<Duration>,
|
||||
}
|
||||
|
||||
impl UserData for LuaTcpIp4Server {
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_method_mut("bind", |_, this, (host, port): (String, u16)| {
|
||||
let addr = (host.as_str(), port)
|
||||
.to_socket_addrs()?
|
||||
.find(|a| a.is_ipv4());
|
||||
|
||||
let Some(addr) = addr else {
|
||||
return Err(mlua::Error::external("no IPv4 address found"));
|
||||
};
|
||||
|
||||
match TcpListener::bind(addr) {
|
||||
Ok(listener) => {
|
||||
this.listener = Some(listener);
|
||||
Ok(1)
|
||||
}
|
||||
Err(e) => Err(mlua::Error::external(e)),
|
||||
}
|
||||
});
|
||||
|
||||
// `TcpListener::bind` handles the binding and immediately starts listening.
|
||||
// `listen` can therefore be a no-op if `bind` succeeded.
|
||||
methods.add_method("listen", |_, this, _backlog: u32| match &this.listener {
|
||||
Some(_) => Ok(1),
|
||||
None => Err(mlua::Error::external("socket is not bound")),
|
||||
});
|
||||
|
||||
methods.add_method_mut("close", |_, this, ()| {
|
||||
this.listener = None;
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
methods.add_method("getsockname", |_, this, ()| match &this.listener {
|
||||
Some(listener) => {
|
||||
let addr = listener.local_addr()?;
|
||||
Ok((addr.ip().to_string(), addr.port()))
|
||||
}
|
||||
None => Err(mlua::Error::external("socket is not bound")),
|
||||
});
|
||||
|
||||
methods.add_method_mut("settimeout", |_, this, seconds: f64| {
|
||||
this.timeout = if seconds < 0.0 {
|
||||
None
|
||||
} else {
|
||||
Some(Duration::from_secs_f64(seconds))
|
||||
};
|
||||
Ok(())
|
||||
});
|
||||
|
||||
methods.add_method_mut(
|
||||
"setoption",
|
||||
|_, _this, (name, _value): (String, mlua::Value)| {
|
||||
match name.as_str() {
|
||||
"reuseaddr" => {
|
||||
// NOTE: ignore for now. not sure why this is even set by PoB.
|
||||
// `TcpListener` doesn't give access to this options so if this
|
||||
// turns out to be important, switch to `socket2` crate which
|
||||
// offers more advanced configurations options.
|
||||
Ok(1)
|
||||
}
|
||||
_ => Err(mlua::Error::external(format!(
|
||||
"unsupported socket option `{name}`"
|
||||
))),
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
methods.add_method_mut("accept", |lua, this, ()| {
|
||||
let Some(listener) = &this.listener else {
|
||||
return Err(mlua::Error::external("socket is not bound"));
|
||||
};
|
||||
|
||||
// the listener blocks indefinitely until a connection is established.
|
||||
// in order to set a timeout, we move it into nonblocking mode and repeatedly call
|
||||
// `accept`. if it returns `WouldBlock`, return if the deadline is reached or try again
|
||||
// after a short sleep.
|
||||
listener.set_nonblocking(true)?;
|
||||
let deadline = this.timeout.map(|t| Instant::now() + t);
|
||||
|
||||
loop {
|
||||
match listener.accept() {
|
||||
Ok((stream, _addr)) => {
|
||||
let client = LuaTcpClient {
|
||||
reader: BufReader::new(stream),
|
||||
timeout: None,
|
||||
};
|
||||
|
||||
let userdata = lua.create_userdata(client)?;
|
||||
return Ok(userdata);
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
|
||||
if deadline.is_some_and(|d| Instant::now() >= d) {
|
||||
return Err(mlua::Error::external("timeout"));
|
||||
}
|
||||
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(e) => return Err(mlua::Error::external(e)),
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl UserData for LuaTcpClient {
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_method_mut("settimeout", |_, this, seconds: f64| {
|
||||
let timeout = if seconds < 0.0 {
|
||||
None
|
||||
} else {
|
||||
Some(Duration::from_secs_f64(seconds))
|
||||
};
|
||||
|
||||
this.timeout = timeout;
|
||||
this.reader.get_ref().set_read_timeout(timeout)?;
|
||||
this.reader.get_ref().set_write_timeout(timeout)?;
|
||||
Ok(())
|
||||
});
|
||||
|
||||
methods.add_method_mut("close", |_, this, ()| {
|
||||
let _ = this.reader.get_ref().shutdown(std::net::Shutdown::Both);
|
||||
Ok(())
|
||||
});
|
||||
|
||||
// TODO: map correct errors to `closed` and `timeout`
|
||||
methods.add_method_mut(
|
||||
"receive",
|
||||
|_, this, (pattern, prefix, maxsize): (Option<String>, Option<String>, Option<u64>)| {
|
||||
if prefix.is_some() || maxsize.is_some() {
|
||||
unimplemented!();
|
||||
}
|
||||
|
||||
match pattern.as_deref().unwrap_or("*l") {
|
||||
"*l" => {
|
||||
let mut line = Vec::new();
|
||||
|
||||
match this.reader.read_until(b'\n', &mut line) {
|
||||
Ok(0) => Err(mlua::Error::external("closed")),
|
||||
Ok(_) => {
|
||||
if line.last() == Some(&b'\n') {
|
||||
line.pop();
|
||||
}
|
||||
if line.last() == Some(&b'\r') {
|
||||
line.pop();
|
||||
}
|
||||
|
||||
Ok(String::from_utf8_lossy(&line).into_owned())
|
||||
}
|
||||
Err(e)
|
||||
if matches!(
|
||||
e.kind(),
|
||||
io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock
|
||||
) =>
|
||||
{
|
||||
Err(mlua::Error::external("timeout"))
|
||||
}
|
||||
Err(e) => Err(mlua::Error::external(e)),
|
||||
}
|
||||
}
|
||||
"*a" => {
|
||||
unimplemented!()
|
||||
}
|
||||
other => match other.parse::<u64>() {
|
||||
Ok(_) => {
|
||||
unimplemented!()
|
||||
}
|
||||
Err(_) => Err(bad_argument(
|
||||
"receive",
|
||||
1,
|
||||
mlua::Error::external("invalid receive pattern"),
|
||||
)),
|
||||
},
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// TODO: map correct errors to `closed` and `timeout`
|
||||
// TODO: handle i and j
|
||||
// TODO: on error, return index of the last byte (within [i, j]) sent
|
||||
methods.add_method_mut(
|
||||
"send",
|
||||
|_, this, (data, i, j): (String, Option<LuaInteger>, Option<LuaInteger>)| {
|
||||
if i.is_some() || j.is_some() {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
match this.reader.get_mut().write_all(data.as_bytes()) {
|
||||
Ok(()) => Ok(data.len()),
|
||||
Err(e) => Err(mlua::Error::external(e)),
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Rust port of SimpleGraphic's `lzip`, a library for reading zip files.
|
||||
//! <https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic/blob/master/libs/LZip/lzip.cpp>
|
||||
|
||||
use std::{fs::File, io::Read};
|
||||
|
||||
use mlua::{Integer as LuaInteger, Lua, Result as LuaResult, Table, UserData, UserDataMethods};
|
||||
|
||||
use crate::pob::modules::luazip::archive::{ZipArchive, ZipFile};
|
||||
|
||||
mod archive;
|
||||
|
||||
pub fn create_module(lua: &Lua) -> LuaResult<Table> {
|
||||
let exports = lua.create_table()?;
|
||||
|
||||
exports.set(
|
||||
"open",
|
||||
lua.create_function(|_, path: String| {
|
||||
let file = File::open(&path).map_err(mlua::Error::external)?;
|
||||
let archive = ZipArchive::new(file).map_err(mlua::Error::external)?;
|
||||
Ok(ZipArchiveHandle {
|
||||
archive: Some(archive),
|
||||
})
|
||||
})?,
|
||||
)?;
|
||||
|
||||
Ok(exports)
|
||||
}
|
||||
|
||||
fn to_index(i: LuaInteger, len: usize) -> Option<usize> {
|
||||
usize::try_from(i.checked_sub(1)?).ok().filter(|&i| i < len)
|
||||
}
|
||||
|
||||
struct ZipArchiveHandle {
|
||||
archive: Option<ZipArchive<File>>,
|
||||
}
|
||||
|
||||
impl ZipArchiveHandle {
|
||||
fn get(&self) -> LuaResult<&ZipArchive<File>> {
|
||||
self.archive
|
||||
.as_ref()
|
||||
.ok_or_else(|| mlua::Error::runtime("zip handle is closed"))
|
||||
}
|
||||
}
|
||||
|
||||
impl UserData for ZipArchiveHandle {
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_method_mut("Close", |_, this, ()| {
|
||||
this.archive = None;
|
||||
Ok(())
|
||||
});
|
||||
|
||||
methods.add_method("GetNumFiles", |_, this, ()| Ok(this.get()?.entries().len()));
|
||||
|
||||
methods.add_method("GetFileName", |lua, this, index: LuaInteger| {
|
||||
let entries = this.get()?.entries();
|
||||
let len = entries.len();
|
||||
match to_index(index, len) {
|
||||
Some(i) => Ok(Some(lua.create_string(entries[i].name())?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_method("GetFileSize", |_, this, index: LuaInteger| {
|
||||
let entries = this.get()?.entries();
|
||||
let len = entries.len();
|
||||
match to_index(index, len) {
|
||||
Some(i) => Ok(Some(entries[i].uncompressed_size())),
|
||||
None => Ok(None),
|
||||
}
|
||||
});
|
||||
|
||||
methods.add_method_mut("OpenFile", |_, this, index_or_name: mlua::Value| {
|
||||
let archive = this.get()?;
|
||||
let entries = archive.entries();
|
||||
|
||||
let index = match index_or_name {
|
||||
mlua::Value::Integer(i) => {
|
||||
let Some(index) = to_index(i, entries.len()) else {
|
||||
return Err(mlua::Error::runtime("zip:OpenFile(): invalid index"));
|
||||
};
|
||||
index
|
||||
}
|
||||
mlua::Value::String(s) => {
|
||||
let name = s.as_bytes();
|
||||
let Some(index) = entries.iter().position(|e| e.name()[..] == *name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
index
|
||||
}
|
||||
_ => {
|
||||
return Err(mlua::Error::runtime(
|
||||
"Usage: zip:OpenFile(index) or zip:OpenFile(fileName)",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let file = archive.by_index(index).map_err(mlua::Error::external)?;
|
||||
Ok(Some(ZipFileHandle { file: Some(file) }))
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
struct ZipFileHandle {
|
||||
file: Option<ZipFile<File>>,
|
||||
}
|
||||
|
||||
impl ZipFileHandle {
|
||||
fn get(&mut self) -> LuaResult<&ZipFile<File>> {
|
||||
self.file
|
||||
.as_ref()
|
||||
.ok_or_else(|| mlua::Error::runtime("zip file handle is closed"))
|
||||
}
|
||||
|
||||
fn get_mut(&mut self) -> LuaResult<&mut ZipFile<File>> {
|
||||
self.file
|
||||
.as_mut()
|
||||
.ok_or_else(|| mlua::Error::runtime("zip file handle is closed"))
|
||||
}
|
||||
}
|
||||
|
||||
impl UserData for ZipFileHandle {
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_method_mut("Close", |_, this, ()| {
|
||||
this.file = None;
|
||||
Ok(())
|
||||
});
|
||||
|
||||
methods.add_method_mut("Length", |_, this, ()| Ok(this.get()?.size()));
|
||||
|
||||
methods.add_method_mut("Read", |lua, this, arg: mlua::Value| {
|
||||
let file = this.get_mut()?;
|
||||
let mut buf = Vec::new();
|
||||
|
||||
match arg {
|
||||
mlua::Value::String(s) if s.as_bytes() == b"*a" => {
|
||||
file.read_to_end(&mut buf).map_err(mlua::Error::external)?;
|
||||
}
|
||||
mlua::Value::Integer(n) if n >= 0 => {
|
||||
if n == 0 {
|
||||
return lua.create_string("");
|
||||
}
|
||||
|
||||
file.take(n as u64)
|
||||
.read_to_end(&mut buf)
|
||||
.map_err(mlua::Error::external)?;
|
||||
}
|
||||
other => {
|
||||
return Err(mlua::Error::runtime(format!(
|
||||
"zipFile:Read(): unrecognised format: {}",
|
||||
other.to_string()?
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
lua.create_string(buf)
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,716 @@
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
io::{self, Read, Seek, SeekFrom, Take},
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
use flate2::read::DeflateDecoder;
|
||||
|
||||
const EOCD_LEN: usize = 22;
|
||||
const EOCD_MAGIC_BYTES: &[u8] = &[0x50, 0x4B, 0x05, 0x06];
|
||||
const EOCD_MAX_SIZE: usize = EOCD_LEN + u16::MAX as usize; // fixed fields + variable-sized comment
|
||||
|
||||
const EOCD64_LEN: usize = 56;
|
||||
const EOCD64_MAGIC_BYTES: &[u8] = &[0x50, 0x4B, 0x06, 0x06];
|
||||
|
||||
const EOCD64_LOCATOR_LEN: usize = 20;
|
||||
const EOCD64_LOCATOR_MAGIC_BYTES: &[u8] = &[0x50, 0x4B, 0x06, 0x07];
|
||||
|
||||
const CDFH_LEN: usize = 46;
|
||||
const CDFH_MAGIC_BYTES: &[u8] = &[0x50, 0x4B, 0x01, 0x02];
|
||||
|
||||
const LFH_LEN: usize = 30;
|
||||
const LFH_MAGIC_BYTES: &[u8] = &[0x50, 0x4B, 0x03, 0x04];
|
||||
|
||||
// 0 = encrypted | 6 = strong encryption | 13 = header masked
|
||||
const ENCRYPTED_FLAGS: u16 = (1 << 0) | (1 << 6) | (1 << 13);
|
||||
|
||||
#[inline]
|
||||
fn parse_u16(b: &[u8], at: usize) -> u16 {
|
||||
u16::from_le_bytes(b[at..at.saturating_add(2)].try_into().unwrap())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_u32(b: &[u8], at: usize) -> u32 {
|
||||
u32::from_le_bytes(b[at..at.saturating_add(4)].try_into().unwrap())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_u64(b: &[u8], at: usize) -> u64 {
|
||||
u64::from_le_bytes(b[at..at.saturating_add(8)].try_into().unwrap())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn read_u8_slice<R: Read>(reader: &mut R, size: usize) -> io::Result<Box<[u8]>> {
|
||||
let mut buf = vec![0; size];
|
||||
reader.read_exact(&mut buf)?;
|
||||
Ok(buf.into_boxed_slice())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn take_u32(data: &[u8], at: &mut usize) -> io::Result<u32> {
|
||||
let bytes = data
|
||||
.get(*at..at.saturating_add(4))
|
||||
.ok_or_else(|| invalid("truncated extra field"))?;
|
||||
|
||||
*at += 4;
|
||||
Ok(u32::from_le_bytes(bytes.try_into().unwrap()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn take_u64(data: &[u8], at: &mut usize) -> io::Result<u64> {
|
||||
let bytes = data
|
||||
.get(*at..at.saturating_add(8))
|
||||
.ok_or_else(|| invalid("truncated extra field"))?;
|
||||
|
||||
*at += 8;
|
||||
Ok(u64::from_le_bytes(bytes.try_into().unwrap()))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn invalid(msg: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, msg)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn unsupported(msg: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::Unsupported, msg)
|
||||
}
|
||||
|
||||
struct SharedReader<R> {
|
||||
inner: Rc<RefCell<R>>,
|
||||
pos: u64,
|
||||
}
|
||||
|
||||
impl<R: Read + Seek> Read for SharedReader<R> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
let mut r = self.inner.borrow_mut();
|
||||
r.seek(SeekFrom::Start(self.pos))?;
|
||||
let n = r.read(buf)?;
|
||||
self.pos += n as u64;
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
|
||||
enum CompressionMethod {
|
||||
Stored,
|
||||
Deflate,
|
||||
Other(u16),
|
||||
}
|
||||
|
||||
impl From<u16> for CompressionMethod {
|
||||
fn from(value: u16) -> Self {
|
||||
match value {
|
||||
0 => Self::Stored,
|
||||
8 => Self::Deflate,
|
||||
other => Self::Other(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ZipArchive<R> {
|
||||
reader: Rc<RefCell<R>>,
|
||||
entries: Vec<ZipEntry>,
|
||||
}
|
||||
|
||||
impl<R: Read + Seek> ZipArchive<R> {
|
||||
pub fn new(mut reader: R) -> io::Result<Self> {
|
||||
let cd_info = read_central_directory_info(&mut reader)?;
|
||||
let entries = parse_central_directory(
|
||||
&mut reader,
|
||||
cd_info.cd_offset,
|
||||
cd_info.cd_size,
|
||||
cd_info.cd_records_on_disk as usize,
|
||||
)?;
|
||||
|
||||
Ok(Self {
|
||||
reader: Rc::new(RefCell::new(reader)),
|
||||
entries,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn entries(&self) -> &[ZipEntry] {
|
||||
&self.entries
|
||||
}
|
||||
|
||||
pub fn by_index(&self, index: usize) -> io::Result<ZipFile<R>> {
|
||||
let entry = self
|
||||
.entries
|
||||
.get(index)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "entry not found"))?;
|
||||
|
||||
// reject unsupported entries
|
||||
if entry.flags & ENCRYPTED_FLAGS != 0 {
|
||||
return Err(unsupported("encrypted entries are not supported"));
|
||||
}
|
||||
let deflated = match entry.compression {
|
||||
CompressionMethod::Stored => {
|
||||
if entry.compressed_size != entry.uncompressed_size {
|
||||
return Err(invalid("uncompressed entry has mismatched sizes"));
|
||||
}
|
||||
false
|
||||
}
|
||||
CompressionMethod::Deflate => true,
|
||||
CompressionMethod::Other(method) => {
|
||||
return Err(unsupported(format!(
|
||||
"unsupported compression method {method}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
let start = data_start(&mut *self.reader.borrow_mut(), entry)?;
|
||||
let limited = SharedReader {
|
||||
inner: Rc::clone(&self.reader),
|
||||
pos: start,
|
||||
}
|
||||
.take(entry.compressed_size);
|
||||
|
||||
Ok(ZipFile {
|
||||
inner: if deflated {
|
||||
Inner::Deflate(DeflateDecoder::new(limited))
|
||||
} else {
|
||||
Inner::Stored(limited)
|
||||
},
|
||||
expected_size: entry.uncompressed_size,
|
||||
produced: 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Entry metadata
|
||||
#[derive(Debug)]
|
||||
pub struct ZipEntry {
|
||||
name: Box<[u8]>,
|
||||
flags: u16,
|
||||
compression: CompressionMethod,
|
||||
_crc32: u32,
|
||||
compressed_size: u64,
|
||||
uncompressed_size: u64,
|
||||
file_start_disk: u32,
|
||||
local_header_offset: u64,
|
||||
extra_fields: Box<[ExtraField]>,
|
||||
}
|
||||
|
||||
impl ZipEntry {
|
||||
pub fn name(&self) -> &[u8] {
|
||||
&self.name
|
||||
}
|
||||
|
||||
pub fn uncompressed_size(&self) -> u64 {
|
||||
self.uncompressed_size
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CDFH> for ZipEntry {
|
||||
fn from(cdfh: CDFH) -> Self {
|
||||
Self {
|
||||
name: cdfh.file_name,
|
||||
flags: cdfh.general_purpose_bit_flag,
|
||||
compression: CompressionMethod::from(cdfh.compression_method),
|
||||
_crc32: cdfh.crc32,
|
||||
compressed_size: u64::from(cdfh.compressed_size),
|
||||
uncompressed_size: u64::from(cdfh.uncompressed_size),
|
||||
local_header_offset: u64::from(cdfh.local_file_header_offset),
|
||||
file_start_disk: u32::from(cdfh.file_start_disk),
|
||||
extra_fields: cdfh.extra_fields,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Inner<R: Read + Seek> {
|
||||
Stored(Take<SharedReader<R>>),
|
||||
Deflate(DeflateDecoder<Take<SharedReader<R>>>),
|
||||
}
|
||||
|
||||
pub struct ZipFile<R: Read + Seek> {
|
||||
inner: Inner<R>,
|
||||
expected_size: u64,
|
||||
produced: u64,
|
||||
}
|
||||
|
||||
impl<R: Read + Seek> ZipFile<R> {
|
||||
pub fn size(&self) -> u64 {
|
||||
self.expected_size
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: Read + Seek> Read for ZipFile<R> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
if buf.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
// don't hand out more than one byte past the declared size to protect against malicious
|
||||
// archives
|
||||
let remaining = self.expected_size - self.produced.min(self.expected_size);
|
||||
let max = remaining.saturating_add(1).min(buf.len() as u64) as usize;
|
||||
let buf = &mut buf[..max];
|
||||
|
||||
let n = match &mut self.inner {
|
||||
Inner::Stored(r) => r.read(buf)?,
|
||||
Inner::Deflate(r) => r.read(buf)?,
|
||||
};
|
||||
|
||||
if n > 0 {
|
||||
self.produced += n as u64;
|
||||
if self.produced > self.expected_size {
|
||||
return Err(invalid("entry is larger than declared"));
|
||||
}
|
||||
} else {
|
||||
if self.produced != self.expected_size {
|
||||
return Err(invalid("entry is smaller than declared"));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the start position of an entrys payload.
|
||||
fn data_start<R: Read + Seek>(r: &mut R, entry: &ZipEntry) -> io::Result<u64> {
|
||||
r.seek(SeekFrom::Start(entry.local_header_offset))?;
|
||||
|
||||
let mut buf = [0u8; LFH_LEN];
|
||||
r.read_exact(&mut buf)?;
|
||||
|
||||
if [buf[0], buf[1], buf[2], buf[3]] != LFH_MAGIC_BYTES {
|
||||
return Err(invalid("Invalid LFH magic number"));
|
||||
}
|
||||
|
||||
let name_len = parse_u16(&buf, 26) as u64;
|
||||
let extra_len = parse_u16(&buf, 28) as u64;
|
||||
Ok(entry.local_header_offset + LFH_LEN as u64 + name_len + extra_len)
|
||||
}
|
||||
|
||||
fn parse_central_directory<R: Read + Seek>(
|
||||
reader: &mut R,
|
||||
start: u64,
|
||||
size: u64,
|
||||
num_of_entries: usize,
|
||||
) -> io::Result<Vec<ZipEntry>> {
|
||||
reader.seek(SeekFrom::Start(start))?;
|
||||
let end = start
|
||||
.checked_add(size)
|
||||
.ok_or_else(|| invalid("central directory too big"))?;
|
||||
let mut entries = Vec::new();
|
||||
|
||||
for _ in 0..num_of_entries {
|
||||
if reader.stream_position()? > end {
|
||||
return Err(invalid("invalid number of entries"));
|
||||
}
|
||||
|
||||
let cdfh = parse_cdfh(reader)?;
|
||||
|
||||
// check for ZIP64 sentinel values
|
||||
let need_uncompressed = cdfh.uncompressed_size == u32::MAX;
|
||||
let need_compressed = cdfh.compressed_size == u32::MAX;
|
||||
let need_offset = cdfh.local_file_header_offset == u32::MAX;
|
||||
let need_start_disk = cdfh.file_start_disk == u16::MAX;
|
||||
|
||||
let mut entry = ZipEntry::from(cdfh);
|
||||
|
||||
// update entry with info from ZIP64 extra field
|
||||
if need_compressed || need_uncompressed || need_offset || need_start_disk {
|
||||
let zip64_extra = entry
|
||||
.extra_fields
|
||||
.iter()
|
||||
.find(|extra| extra.header == 0x0001)
|
||||
.ok_or_else(|| invalid("ZIP64 extra field missing"))?;
|
||||
|
||||
let data = &zip64_extra.data[..];
|
||||
let mut at = 0;
|
||||
|
||||
if need_uncompressed {
|
||||
entry.uncompressed_size = take_u64(data, &mut at)?;
|
||||
}
|
||||
if need_compressed {
|
||||
entry.compressed_size = take_u64(data, &mut at)?;
|
||||
}
|
||||
if need_offset {
|
||||
entry.local_header_offset = take_u64(data, &mut at)?;
|
||||
}
|
||||
if need_start_disk {
|
||||
entry.file_start_disk = take_u32(data, &mut at)?;
|
||||
}
|
||||
}
|
||||
|
||||
if entry.file_start_disk != 0 {
|
||||
return Err(unsupported("split archives are not supported"));
|
||||
}
|
||||
|
||||
entries.push(entry);
|
||||
}
|
||||
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
/// Central Directory File Header (CDFH).
|
||||
#[derive(Debug)]
|
||||
#[allow(clippy::upper_case_acronyms)]
|
||||
struct CDFH {
|
||||
/// Version made by.
|
||||
_version_made_by: u16,
|
||||
/// Version needed to extract (minimum).
|
||||
_version_needed_to_extract: u16,
|
||||
/// General purpose bit flag.
|
||||
general_purpose_bit_flag: u16,
|
||||
/// Compression method.
|
||||
compression_method: u16,
|
||||
/// File last modification time.
|
||||
_last_modification_time: u16,
|
||||
/// File last modification date.
|
||||
_last_modification_date: u16,
|
||||
/// CRC-32 of uncompressed data.
|
||||
crc32: u32,
|
||||
/// Compressed size (or FF FF FF FF for ZIP64).
|
||||
compressed_size: u32,
|
||||
/// Uncompressed size (or FF FF FF FF for ZIP64).
|
||||
uncompressed_size: u32,
|
||||
/// Disk number where file starts (or FF FF for ZIP64).
|
||||
file_start_disk: u16,
|
||||
/// Internal file attributes.
|
||||
_internal_file_attributes: u16,
|
||||
/// External file attributes.
|
||||
_external_file_attributes: u32,
|
||||
/// Relative offset of local file header (or FF FF FF FF for ZIP64). This is the number of
|
||||
/// bytes between the start of the first disk on which the file occurs, and the start of the
|
||||
/// local file header. This allows software reading the central directory to locate the
|
||||
/// position of the file inside the ZIP file.
|
||||
local_file_header_offset: u32,
|
||||
/// File name.
|
||||
file_name: Box<[u8]>,
|
||||
/// Extra field.
|
||||
extra_fields: Box<[ExtraField]>,
|
||||
/// File comment.
|
||||
_file_comment: Box<[u8]>,
|
||||
}
|
||||
|
||||
/// Parses a CDFH. `reader` must be positioned at the start of a CDFH.
|
||||
fn parse_cdfh<R: Read>(reader: &mut R) -> io::Result<CDFH> {
|
||||
let mut buf = [0u8; CDFH_LEN];
|
||||
reader.read_exact(&mut buf)?;
|
||||
|
||||
if [buf[0], buf[1], buf[2], buf[3]] != CDFH_MAGIC_BYTES {
|
||||
return Err(invalid("Invalid CDFH magic number"));
|
||||
}
|
||||
|
||||
let file_name_length = parse_u16(&buf, 28) as usize;
|
||||
let extra_fields_length = parse_u16(&buf, 30);
|
||||
let file_comment_length = parse_u16(&buf, 32) as usize;
|
||||
|
||||
Ok(CDFH {
|
||||
_version_made_by: parse_u16(&buf, 4),
|
||||
_version_needed_to_extract: parse_u16(&buf, 6),
|
||||
general_purpose_bit_flag: parse_u16(&buf, 8),
|
||||
compression_method: parse_u16(&buf, 10),
|
||||
_last_modification_time: parse_u16(&buf, 12),
|
||||
_last_modification_date: parse_u16(&buf, 14),
|
||||
crc32: parse_u32(&buf, 16),
|
||||
compressed_size: parse_u32(&buf, 20),
|
||||
uncompressed_size: parse_u32(&buf, 24),
|
||||
file_start_disk: parse_u16(&buf, 34),
|
||||
_internal_file_attributes: parse_u16(&buf, 36),
|
||||
_external_file_attributes: parse_u32(&buf, 38),
|
||||
local_file_header_offset: parse_u32(&buf, 42),
|
||||
file_name: read_u8_slice(reader, file_name_length)?,
|
||||
extra_fields: read_extra_fields(reader, extra_fields_length)?,
|
||||
_file_comment: read_u8_slice(reader, file_comment_length)?,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ExtraField {
|
||||
pub header: u16,
|
||||
pub data: Box<[u8]>,
|
||||
}
|
||||
|
||||
fn read_extra_fields<R: Read>(reader: &mut R, size: u16) -> io::Result<Box<[ExtraField]>> {
|
||||
let mut remaining = usize::from(size);
|
||||
let mut fields = Vec::new();
|
||||
|
||||
while remaining > 0 {
|
||||
if remaining < 4 {
|
||||
return Err(invalid("truncated ZIP extra field"));
|
||||
}
|
||||
|
||||
let mut header = [0u8; 4];
|
||||
reader.read_exact(&mut header)?;
|
||||
|
||||
let id = parse_u16(&header, 0);
|
||||
let data_size = usize::from(parse_u16(&header, 2));
|
||||
|
||||
remaining -= 4;
|
||||
|
||||
if data_size > remaining {
|
||||
return Err(invalid("ZIP extra field data exceeds remaining length"));
|
||||
}
|
||||
|
||||
let mut data = vec![0u8; data_size];
|
||||
reader.read_exact(&mut data)?;
|
||||
|
||||
fields.push(ExtraField {
|
||||
header: id,
|
||||
data: data.into_boxed_slice(),
|
||||
});
|
||||
|
||||
remaining -= data_size;
|
||||
}
|
||||
|
||||
Ok(fields.into_boxed_slice())
|
||||
}
|
||||
|
||||
/// Central directory metadata.
|
||||
#[derive(Debug)]
|
||||
struct CentralDirectoryInfo {
|
||||
/// Number of this disk.
|
||||
disk_number: u32,
|
||||
/// Disk where central directory starts.
|
||||
cd_start_disk: u32,
|
||||
/// Number of central directory records on this disk.
|
||||
cd_records_on_disk: u64,
|
||||
/// Total number of central directory records.
|
||||
cd_records_total: u64,
|
||||
/// Size of central directory in bytes.
|
||||
cd_size: u64,
|
||||
/// Offset of start of central directory, relative to start of archive.
|
||||
cd_offset: u64,
|
||||
/// Comment
|
||||
_comment: Box<[u8]>,
|
||||
}
|
||||
|
||||
impl CentralDirectoryInfo {
|
||||
fn validate_single_disk(&self) -> io::Result<()> {
|
||||
if self.disk_number != 0
|
||||
|| self.cd_start_disk != 0
|
||||
|| self.cd_records_on_disk != self.cd_records_total
|
||||
{
|
||||
return Err(unsupported("split archives are not supported"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<EOCD> for CentralDirectoryInfo {
|
||||
fn from(eocd: EOCD) -> Self {
|
||||
Self {
|
||||
disk_number: u32::from(eocd.disk_number),
|
||||
cd_start_disk: u32::from(eocd.cd_start_disk),
|
||||
cd_records_on_disk: u64::from(eocd.cd_records_on_disk),
|
||||
cd_records_total: u64::from(eocd.cd_records_total),
|
||||
cd_size: u64::from(eocd.cd_size),
|
||||
cd_offset: u64::from(eocd.cd_offset),
|
||||
_comment: eocd.comment,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<EOCD64> for CentralDirectoryInfo {
|
||||
fn from(eocd: EOCD64) -> Self {
|
||||
Self {
|
||||
disk_number: eocd.disk_number,
|
||||
cd_start_disk: eocd.cd_start_disk,
|
||||
cd_records_on_disk: eocd.cd_records_on_disk,
|
||||
cd_records_total: eocd.cd_records_total,
|
||||
cd_size: eocd.cd_size,
|
||||
cd_offset: eocd.cd_offset,
|
||||
_comment: eocd.comment,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_central_directory_info<R: Read + Seek>(reader: &mut R) -> io::Result<CentralDirectoryInfo> {
|
||||
let eocd_start = find_eocd(reader)?;
|
||||
reader.seek(SeekFrom::Start(eocd_start))?;
|
||||
let eocd = parse_eocd(reader)?;
|
||||
|
||||
let needs_zip64 = eocd.has_zip64_sentinels();
|
||||
|
||||
// check for presence of EOCD64 Locator which sits right before the EOCD
|
||||
let locator_start = eocd_start.saturating_sub(EOCD64_LOCATOR_LEN as u64);
|
||||
reader.seek(SeekFrom::Start(locator_start))?;
|
||||
let eocd64_locator = parse_eocd64_locator(reader);
|
||||
|
||||
let info = match eocd64_locator {
|
||||
Ok(locator) => {
|
||||
if locator.cd_start_disk != 0 || locator.disks_total != 1 {
|
||||
return Err(unsupported("split archives are not supported"));
|
||||
}
|
||||
|
||||
// seek to and parse EOCD64
|
||||
reader.seek(SeekFrom::Start(locator.cd_offset))?;
|
||||
let eocd64 = parse_eocd64(reader)?;
|
||||
CentralDirectoryInfo::from(eocd64)
|
||||
}
|
||||
Err(_) if needs_zip64 => return Err(invalid("missing EOCD64")),
|
||||
Err(_) => CentralDirectoryInfo::from(eocd),
|
||||
};
|
||||
|
||||
info.validate_single_disk()?;
|
||||
Ok(info)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct EOCD64 {
|
||||
/// Version made by.
|
||||
_version_made_by: u16,
|
||||
/// Version needed to extract (minimum).
|
||||
_version_needed_to_extract: u16,
|
||||
/// Number of this disk.
|
||||
disk_number: u32,
|
||||
/// Disk where central directory starts.
|
||||
cd_start_disk: u32,
|
||||
/// Number of central directory records on this disk.
|
||||
cd_records_on_disk: u64,
|
||||
/// Total number of central directory records.
|
||||
cd_records_total: u64,
|
||||
/// Size of central directory in bytes.
|
||||
cd_size: u64,
|
||||
/// Offset of start of central directory, relative to start of archive.
|
||||
cd_offset: u64,
|
||||
/// Comment.
|
||||
comment: Box<[u8]>,
|
||||
}
|
||||
|
||||
/// Parses the EOCD64. `reader` must be positioned at the start of the EOCD64.
|
||||
fn parse_eocd64<R: Read>(reader: &mut R) -> io::Result<EOCD64> {
|
||||
let mut buf = [0u8; EOCD64_LEN];
|
||||
reader.read_exact(&mut buf)?;
|
||||
|
||||
if [buf[0], buf[1], buf[2], buf[3]] != EOCD64_MAGIC_BYTES {
|
||||
return Err(invalid("Invalid EOCD64 magic number"));
|
||||
}
|
||||
|
||||
let size_minus_12 = parse_u64(&buf, 4) + 12;
|
||||
let comment_length = size_minus_12 as usize - (EOCD64_LEN - 12);
|
||||
|
||||
Ok(EOCD64 {
|
||||
_version_made_by: parse_u16(&buf, 12),
|
||||
_version_needed_to_extract: parse_u16(&buf, 14),
|
||||
disk_number: parse_u32(&buf, 16),
|
||||
cd_start_disk: parse_u32(&buf, 20),
|
||||
cd_records_on_disk: parse_u64(&buf, 24),
|
||||
cd_records_total: parse_u64(&buf, 32),
|
||||
cd_size: parse_u64(&buf, 40),
|
||||
cd_offset: parse_u64(&buf, 48),
|
||||
comment: read_u8_slice(reader, comment_length)?,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct EOCD64Locator {
|
||||
/// Disk where EOCD64 starts.
|
||||
cd_start_disk: u32,
|
||||
/// Offset to start of EOCD64, relative to start of archive.
|
||||
cd_offset: u64,
|
||||
/// Total number of disks.
|
||||
disks_total: u32,
|
||||
}
|
||||
|
||||
/// Parses the EOCD64 Locator. `reader` must be positioned at the start of the EOCD64 Locator.
|
||||
fn parse_eocd64_locator<R: Read>(reader: &mut R) -> io::Result<EOCD64Locator> {
|
||||
let mut buf = [0u8; EOCD64_LOCATOR_LEN];
|
||||
reader.read_exact(&mut buf)?;
|
||||
|
||||
if [buf[0], buf[1], buf[2], buf[3]] != EOCD64_LOCATOR_MAGIC_BYTES {
|
||||
return Err(invalid("Invalid EOCD64 Locator magic number"));
|
||||
}
|
||||
|
||||
Ok(EOCD64Locator {
|
||||
cd_start_disk: parse_u32(&buf, 4),
|
||||
cd_offset: parse_u64(&buf, 8),
|
||||
disks_total: parse_u32(&buf, 16),
|
||||
})
|
||||
}
|
||||
|
||||
/// End Of Central Directory record (EOCD).
|
||||
#[derive(Debug)]
|
||||
#[allow(clippy::upper_case_acronyms)]
|
||||
struct EOCD {
|
||||
/// Number of this disk (or FF FF for ZIP64).
|
||||
disk_number: u16,
|
||||
/// Disk where central directory starts (or FF FF for ZIP64).
|
||||
cd_start_disk: u16,
|
||||
/// Number of central directory records on this disk (or FF FF for ZIP64).
|
||||
cd_records_on_disk: u16,
|
||||
/// Total number of central directory records (or FF FF for ZIP64).
|
||||
cd_records_total: u16,
|
||||
/// Size of central directory in bytes (or FF FF FF FF for ZIP64).
|
||||
cd_size: u32,
|
||||
/// Offset of start of central directory, relative to start of archive (or FF FF FF FF for ZIP64).
|
||||
cd_offset: u32,
|
||||
/// Comment.
|
||||
comment: Box<[u8]>,
|
||||
}
|
||||
|
||||
impl EOCD {
|
||||
fn has_zip64_sentinels(&self) -> bool {
|
||||
self.disk_number == u16::MAX
|
||||
|| self.cd_start_disk == u16::MAX
|
||||
|| self.cd_records_on_disk == u16::MAX
|
||||
|| self.cd_records_total == u16::MAX
|
||||
|| self.cd_size == u32::MAX
|
||||
|| self.cd_offset == u32::MAX
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the start byte position of the EOCD.
|
||||
fn find_eocd<R: Read + Seek>(reader: &mut R) -> io::Result<u64> {
|
||||
// the EOCD is located at the end of the file and is at most `EOCD_MAX_SIZE` bytes long so the
|
||||
// search is restricted to that region.
|
||||
let file_len = reader.seek(SeekFrom::End(0))?;
|
||||
let search_start = file_len.saturating_sub(EOCD_MAX_SIZE as u64);
|
||||
reader.seek(SeekFrom::Start(search_start))?;
|
||||
|
||||
let mut search_area = Vec::with_capacity((file_len - search_start) as usize);
|
||||
reader.read_to_end(&mut search_area)?;
|
||||
|
||||
let eocd_start_in_search_area = search_area
|
||||
.windows(EOCD_MAGIC_BYTES.len())
|
||||
.enumerate()
|
||||
.rev()
|
||||
.find_map(|(pos, window)| {
|
||||
if window != EOCD_MAGIC_BYTES {
|
||||
return None;
|
||||
}
|
||||
|
||||
// we found the magic bytes!
|
||||
// but they can theoretically appear in the comment so we need to verify that this
|
||||
// candidate header ends exactly at the end of the search area.
|
||||
let header_end = pos.checked_add(EOCD_LEN)?;
|
||||
let header = search_area.get(pos..header_end)?;
|
||||
let comment_length = u16::from_le_bytes([header[20], header[21]]) as usize;
|
||||
if header_end.checked_add(comment_length)? == search_area.len() {
|
||||
Some(pos)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| invalid("EOCD not found"))?;
|
||||
|
||||
let eocd_start = search_start + eocd_start_in_search_area as u64;
|
||||
Ok(eocd_start)
|
||||
}
|
||||
|
||||
/// Parses the EOCD. `reader` must be positioned at the start of the EOCD.
|
||||
fn parse_eocd<R: Read>(reader: &mut R) -> io::Result<EOCD> {
|
||||
let mut buf = [0u8; EOCD_LEN];
|
||||
reader.read_exact(&mut buf)?;
|
||||
|
||||
if [buf[0], buf[1], buf[2], buf[3]] != EOCD_MAGIC_BYTES {
|
||||
return Err(invalid("Invalid EOCD magic number"));
|
||||
}
|
||||
|
||||
let comment_length = parse_u16(&buf, 20) as usize;
|
||||
|
||||
Ok(EOCD {
|
||||
disk_number: parse_u16(&buf, 4),
|
||||
cd_start_disk: parse_u16(&buf, 6),
|
||||
cd_records_on_disk: parse_u16(&buf, 8),
|
||||
cd_records_total: parse_u16(&buf, 10),
|
||||
cd_size: parse_u32(&buf, 12),
|
||||
cd_offset: parse_u32(&buf, 16),
|
||||
comment: read_u8_slice(reader, comment_length)?,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
use crate::{
|
||||
pob::modules,
|
||||
util::{append_lua_package_dir, fix_script_header},
|
||||
};
|
||||
use anyhow::{Result, anyhow};
|
||||
use mlua::{Integer, IntoLuaMulti, Lua, MultiValue, Number, Value};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::mpsc::{Receiver, Sender, channel},
|
||||
thread::JoinHandle,
|
||||
};
|
||||
|
||||
/// A unit of work produced by advancing the running subscripts.
|
||||
pub enum SubscriptEvent {
|
||||
/// A subscript requested that a function in the main Lua instance be called on its behalf.
|
||||
Call {
|
||||
function_name: String,
|
||||
arguments: NativeMultiValue,
|
||||
/// Present for blocking calls. The return values of the callback must be sent back over it.
|
||||
reply_tx: Option<Sender<Result<NativeMultiValue>>>,
|
||||
},
|
||||
/// A subscript finished successfully.
|
||||
Finished {
|
||||
id: u64,
|
||||
return_values: NativeMultiValue,
|
||||
},
|
||||
/// A subscript errored or panicked.
|
||||
Error { id: u64, error: String },
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct SubscriptManager {
|
||||
next_id: u64,
|
||||
scripts: Vec<Subscript>,
|
||||
}
|
||||
|
||||
impl SubscriptManager {
|
||||
/// Starts a new subscript running `script_text` on its own thread and returns the id it was
|
||||
/// assigned.
|
||||
pub fn push(
|
||||
&mut self,
|
||||
script_dir: PathBuf,
|
||||
script_text: String,
|
||||
blocking_calls: Vec<String>,
|
||||
nonblocking_calls: Vec<String>,
|
||||
arguments: NativeMultiValue,
|
||||
) -> u64 {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
|
||||
let subscript = Subscript::new(
|
||||
id,
|
||||
script_text,
|
||||
blocking_calls,
|
||||
nonblocking_calls,
|
||||
arguments,
|
||||
script_dir,
|
||||
);
|
||||
self.scripts.push(subscript);
|
||||
id
|
||||
}
|
||||
|
||||
/// Advances all running subscripts by one step.
|
||||
pub fn process(&mut self) -> Vec<SubscriptEvent> {
|
||||
let mut events = vec![];
|
||||
|
||||
self.scripts.retain_mut(|subscript| {
|
||||
subscript.take_call(&mut events);
|
||||
|
||||
subscript.try_join().is_none_or(|event| {
|
||||
events.push(event);
|
||||
// subscript has finished or errored, remove it
|
||||
false
|
||||
})
|
||||
});
|
||||
|
||||
events
|
||||
}
|
||||
|
||||
/// Returns `true` if at least one subscript is running.
|
||||
pub fn has_running_subscripts(&self) -> bool {
|
||||
!self.scripts.is_empty()
|
||||
}
|
||||
|
||||
/// Returns `true` if the subscript with the given id is running.
|
||||
pub fn is_running(&self, subscript_id: u64) -> bool {
|
||||
self.scripts
|
||||
.iter()
|
||||
.any(|subscript| subscript.id == subscript_id)
|
||||
}
|
||||
}
|
||||
|
||||
/// A request sent from a subscript's thread to the main thread, asking it to invoke a function
|
||||
/// defined in the main Lua instance on the subscript's behalf.
|
||||
enum SubscriptCall {
|
||||
Blocking {
|
||||
function_name: String,
|
||||
arguments: NativeMultiValue,
|
||||
// used to send return values of function back to thread
|
||||
reply_tx: Sender<Result<NativeMultiValue>>,
|
||||
},
|
||||
NonBlocking {
|
||||
function_name: String,
|
||||
arguments: NativeMultiValue,
|
||||
},
|
||||
}
|
||||
|
||||
/// A Lua script running on its own thread, in a separate `Lua` instance.
|
||||
pub struct Subscript {
|
||||
id: u64,
|
||||
handle: Option<JoinHandle<anyhow::Result<NativeMultiValue>>>,
|
||||
/// Receives `SubscriptCall`s sent by the proxy functions running in the subscript's s thread.
|
||||
call_rx: Receiver<SubscriptCall>,
|
||||
}
|
||||
|
||||
// Subscripts are lua scripts that are executed in their own instance on a separate thread.
|
||||
//
|
||||
// When a subscript needs to call a function defined in the main instance, a `SubscriptCall`
|
||||
// message is send over a channel. At the beginning of each frame, the main thread checks for
|
||||
// messages and executes the requested function with the provided arguments on behalf of the
|
||||
// subscript. For `BlockingCall`, the subscript waits for the main thread to send the return
|
||||
// values of the function back over another channel. For `NonBlockingCall`, the subscript doesn't
|
||||
// wait on any return values and keeps executing the script after sending the message. Subscripts
|
||||
// are required to explicitly specify the names of all (non)-blocking function calls that appear in
|
||||
// the script.
|
||||
impl Subscript {
|
||||
/// Spawns a new thread, creates a fresh `Lua` instance on it, registers proxy functions for
|
||||
/// `blocking_calls` and `nonblocking_calls`, and starts running `script_text` with
|
||||
/// `arguments`.
|
||||
pub fn new(
|
||||
id: u64,
|
||||
script_text: String,
|
||||
blocking_calls: Vec<String>,
|
||||
nonblocking_calls: Vec<String>,
|
||||
arguments: NativeMultiValue,
|
||||
script_dir: PathBuf,
|
||||
) -> Self {
|
||||
let (call_tx, call_rx) = channel();
|
||||
|
||||
let handle = std::thread::spawn(move || {
|
||||
profiling::register_thread!(format!("Subscript {id} Thread"));
|
||||
|
||||
// unsafe required to load C modules (curl)
|
||||
let lua = unsafe { Lua::unsafe_new() };
|
||||
append_lua_package_dir(&lua, &script_dir.join("lua"))?;
|
||||
|
||||
// register modules
|
||||
modules::register(&lua)?;
|
||||
|
||||
// register a proxy for each allowed blocking call.
|
||||
// forwards the call to the main thread and blocks on `reply_rx` until the main thread
|
||||
// sends back the return values
|
||||
for function_name in blocking_calls {
|
||||
let call_tx = call_tx.clone();
|
||||
lua.globals().set(
|
||||
function_name.clone(),
|
||||
lua.create_function(move |_, args: MultiValue| {
|
||||
let (reply_tx, reply_rx) = channel();
|
||||
call_tx
|
||||
.send(SubscriptCall::Blocking {
|
||||
function_name: function_name.clone(),
|
||||
arguments: args.try_into()?,
|
||||
reply_tx,
|
||||
})
|
||||
.unwrap();
|
||||
let return_values = reply_rx.recv().map_err(|e| anyhow!("{e}"))??;
|
||||
Ok(return_values)
|
||||
})?,
|
||||
)?;
|
||||
}
|
||||
|
||||
// register a proxy for each allowed non-blocking call.
|
||||
// forwards the call to the main thread and returns immediately
|
||||
for function_name in nonblocking_calls {
|
||||
let call_tx = call_tx.clone();
|
||||
lua.globals().set(
|
||||
function_name.clone(),
|
||||
lua.create_function(move |_, args: MultiValue| {
|
||||
call_tx
|
||||
.send(SubscriptCall::NonBlocking {
|
||||
function_name: function_name.clone(),
|
||||
arguments: args.try_into()?,
|
||||
})
|
||||
.map_err(|e| anyhow!("{e}"))?;
|
||||
Ok(())
|
||||
})?,
|
||||
)?;
|
||||
}
|
||||
|
||||
let mut script_text = script_text.into_bytes();
|
||||
fix_script_header(&mut script_text);
|
||||
let result = lua.load(script_text).call::<MultiValue>(arguments)?;
|
||||
result.try_into()
|
||||
});
|
||||
|
||||
Self {
|
||||
id,
|
||||
handle: Some(handle),
|
||||
call_rx,
|
||||
}
|
||||
}
|
||||
|
||||
/// Collects a pending `SubscriptCall` into `events`.
|
||||
///
|
||||
/// Does nothing if there is no pending call.
|
||||
fn take_call(&self, events: &mut Vec<SubscriptEvent>) {
|
||||
let Ok(call) = self.call_rx.try_recv() else {
|
||||
// no pending call, or thread disconnected which is handled on join
|
||||
return;
|
||||
};
|
||||
|
||||
events.push(match call {
|
||||
SubscriptCall::Blocking {
|
||||
function_name,
|
||||
arguments,
|
||||
reply_tx,
|
||||
} => SubscriptEvent::Call {
|
||||
function_name,
|
||||
arguments,
|
||||
reply_tx: Some(reply_tx),
|
||||
},
|
||||
SubscriptCall::NonBlocking {
|
||||
function_name,
|
||||
arguments,
|
||||
} => SubscriptEvent::Call {
|
||||
function_name,
|
||||
arguments,
|
||||
reply_tx: None,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/// If the subscript's thread has finished, joins it and returns the resulting
|
||||
/// `SubscriptEvent`.
|
||||
fn try_join(&mut self) -> Option<SubscriptEvent> {
|
||||
if !self.handle.as_ref().is_some_and(JoinHandle::is_finished) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let event = match self.handle.take().unwrap().join() {
|
||||
Ok(Ok(return_values)) => SubscriptEvent::Finished {
|
||||
id: self.id,
|
||||
return_values,
|
||||
},
|
||||
Ok(Err(err)) => SubscriptEvent::Error {
|
||||
id: self.id,
|
||||
error: err.to_string(),
|
||||
},
|
||||
// the thread panicked
|
||||
Err(_) => SubscriptEvent::Error {
|
||||
id: self.id,
|
||||
error: String::from("Subscript thread panicked!"),
|
||||
},
|
||||
};
|
||||
Some(event)
|
||||
}
|
||||
}
|
||||
|
||||
/// Instance-independent stand-in for `mlua::Value`.
|
||||
///
|
||||
/// Values produced by one Lua instance (in particular strings) cannot be used directly with
|
||||
/// another Lua instance. `NativeValue` acts as a stand-in to freely move between the main instance
|
||||
/// and a subscript's instance. It only covers the types that are actually exchanged, namely `nil`,
|
||||
/// booleans, numbers, and string.
|
||||
#[derive(Debug)]
|
||||
pub enum NativeValue {
|
||||
Nil,
|
||||
Number(Number),
|
||||
Integer(Integer),
|
||||
Boolean(bool),
|
||||
// Lua strings may not be valid UTF-8, so store as raw bytes instead of String
|
||||
String(Vec<u8>),
|
||||
}
|
||||
|
||||
/// Instance-independent stand-in for `mlua::MultiValue`.
|
||||
///
|
||||
/// Used to pass function arguments and return values between the main Lua instance and a
|
||||
/// subscript's Lua instance.
|
||||
#[derive(Debug)]
|
||||
pub struct NativeMultiValue(Vec<NativeValue>);
|
||||
|
||||
impl TryFrom<Value> for NativeValue {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(value: Value) -> Result<Self, Self::Error> {
|
||||
match value {
|
||||
Value::Nil => Ok(Self::Nil),
|
||||
Value::Boolean(b) => Ok(Self::Boolean(b)),
|
||||
Value::Integer(i) => Ok(Self::Integer(i)),
|
||||
Value::Number(n) => Ok(Self::Number(n)),
|
||||
Value::String(s) => Ok(Self::String(s.as_bytes().to_vec())),
|
||||
other => Err(anyhow!("Unsupported value type: {}", other.type_name())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<MultiValue> for NativeMultiValue {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(values: MultiValue) -> Result<Self, Self::Error> {
|
||||
values
|
||||
.into_iter()
|
||||
.map(NativeValue::try_from)
|
||||
.collect::<Result<_, _>>()
|
||||
.map(Self)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoLuaMulti for NativeMultiValue {
|
||||
fn into_lua_multi(self, lua: &Lua) -> mlua::Result<MultiValue> {
|
||||
self.0
|
||||
.into_iter()
|
||||
.map(|v| match v {
|
||||
NativeValue::Nil => Ok(Value::Nil),
|
||||
NativeValue::Boolean(b) => Ok(Value::Boolean(b)),
|
||||
NativeValue::Integer(i) => Ok(Value::Integer(i)),
|
||||
NativeValue::Number(n) => Ok(Value::Number(n)),
|
||||
NativeValue::String(s) => lua.create_string(s).map(Value::String),
|
||||
})
|
||||
.collect::<mlua::Result<Vec<_>>>()
|
||||
.map(MultiValue::from_vec)
|
||||
}
|
||||
}
|
||||
+293
-221
@@ -1,27 +1,84 @@
|
||||
use crate::{
|
||||
dpi::{ConvertToLogical, ConvertToPhysical, LogicalSize, PhysicalRect, PhysicalSize},
|
||||
color::Srgba,
|
||||
dpi::{LogicalPoint, LogicalRect, LogicalSize, PhysicalRect, PhysicalSize, ScaleFactor},
|
||||
math::Point,
|
||||
renderer::{
|
||||
image::ImageData,
|
||||
mesh::{ClippedMesh, Vertex},
|
||||
image::MipStrategy,
|
||||
textures::{TextureId, TextureOptions, TexturesDelta},
|
||||
},
|
||||
util::calculate_hash,
|
||||
uv::UvPoint,
|
||||
};
|
||||
use ahash::HashMap;
|
||||
use std::{borrow::Cow, num::NonZeroU64, ops::Range};
|
||||
use wgpu::util::DeviceExt;
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
num::{NonZeroU32, NonZeroU64},
|
||||
ops::Range,
|
||||
};
|
||||
use wgpu::{Origin3d, util::DeviceExt};
|
||||
|
||||
pub mod image;
|
||||
pub mod mesh;
|
||||
mod mipmap;
|
||||
pub mod primitives;
|
||||
pub mod tessellator;
|
||||
pub mod textures;
|
||||
|
||||
pub const BATCH_TEX_SLOTS: NonZeroU32 = NonZeroU32::new(32).expect("32 is non-zero");
|
||||
const DUMMY_TEXTURE_ID: TextureId = 0;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct Vertex {
|
||||
pub pos: LogicalPoint<f32>,
|
||||
pub uv: UvPoint,
|
||||
pub color: Srgba,
|
||||
/// Index into batch's texture array
|
||||
pub texture_slot: u32,
|
||||
/// Index into texture array
|
||||
pub layer_idx: u32,
|
||||
}
|
||||
|
||||
impl Vertex {
|
||||
const ATTRIBS: [wgpu::VertexAttribute; 5] = wgpu::vertex_attr_array![
|
||||
// 0: vec2 position
|
||||
0 => Float32x2,
|
||||
// 1: vec2 uv
|
||||
1 => Float32x2,
|
||||
// 2: uint color
|
||||
2 => Uint32,
|
||||
// 3: uint texture_idx
|
||||
3 => Uint32,
|
||||
// 4: uint layer_idx
|
||||
4 => Uint32
|
||||
];
|
||||
|
||||
fn desc() -> wgpu::VertexBufferLayout<'static> {
|
||||
wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<Self>() as wgpu::BufferAddress,
|
||||
step_mode: wgpu::VertexStepMode::Vertex,
|
||||
attributes: &Self::ATTRIBS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Batch {
|
||||
pub clip_rect: LogicalRect<f32>,
|
||||
pub textures: Vec<TextureId>,
|
||||
/// Points into combined index buffer of `RenderJob`
|
||||
pub index_range: Range<u32>,
|
||||
}
|
||||
|
||||
pub struct RenderJob {
|
||||
pub vertices: Vec<Vertex>,
|
||||
pub indices: Vec<u32>,
|
||||
pub batches: Vec<Batch>,
|
||||
pub textures_delta: TexturesDelta,
|
||||
pub scale_factor: ScaleFactor<f32>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Texture {
|
||||
struct TextureEntry {
|
||||
texture: wgpu::Texture,
|
||||
bind_group: wgpu::BindGroup,
|
||||
view: wgpu::TextureView,
|
||||
options: TextureOptions,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
@@ -33,16 +90,17 @@ struct Globals {
|
||||
pub struct Renderer {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
|
||||
index_buffer: SlicedBuffer,
|
||||
vertex_buffer: SlicedBuffer,
|
||||
index_buffer: Buffer,
|
||||
vertex_buffer: Buffer,
|
||||
|
||||
globals_buffer: wgpu::Buffer,
|
||||
previous_globals: Globals,
|
||||
globals_bind_group: wgpu::BindGroup,
|
||||
texture_bind_group_layout: wgpu::BindGroupLayout,
|
||||
textures_bind_group_layout: wgpu::BindGroupLayout,
|
||||
|
||||
textures: HashMap<TextureId, Texture>,
|
||||
textures: HashMap<TextureId, TextureEntry>,
|
||||
samplers: HashMap<TextureOptions, wgpu::Sampler>,
|
||||
batch_bind_group_cache: HashMap<u64, wgpu::BindGroup>,
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
@@ -92,7 +150,7 @@ impl Renderer {
|
||||
}],
|
||||
});
|
||||
|
||||
let texture_bind_group_layout =
|
||||
let textures_bind_group_layout =
|
||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("texture_bind_group_layout"),
|
||||
entries: &[
|
||||
@@ -104,27 +162,30 @@ impl Renderer {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu::TextureViewDimension::D2Array,
|
||||
},
|
||||
count: None,
|
||||
count: Some(BATCH_TEX_SLOTS),
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
count: Some(BATCH_TEX_SLOTS),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
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: &[],
|
||||
bind_group_layouts: &[
|
||||
Some(&globals_bind_group_layout),
|
||||
Some(&textures_bind_group_layout),
|
||||
],
|
||||
immediate_size: 0,
|
||||
});
|
||||
|
||||
let depth_stencil = output_depth_format.map(|format| wgpu::DepthStencilState {
|
||||
format,
|
||||
depth_write_enabled: false,
|
||||
depth_compare: wgpu::CompareFunction::Always,
|
||||
depth_write_enabled: None,
|
||||
depth_compare: None,
|
||||
stencil: wgpu::StencilState::default(),
|
||||
bias: wgpu::DepthBiasState::default(),
|
||||
});
|
||||
@@ -135,17 +196,8 @@ impl Renderer {
|
||||
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()
|
||||
buffers: &[Some(Vertex::desc())],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
},
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
@@ -170,20 +222,20 @@ impl Renderer {
|
||||
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default()
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
}),
|
||||
multiview: None,
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let vertex_buffer = SlicedBuffer::new(
|
||||
let vertex_buffer = Buffer::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(
|
||||
let index_buffer = Buffer::new(
|
||||
device,
|
||||
wgpu::BufferUsages::INDEX,
|
||||
NonZeroU64::new(2048 * 3).expect("2048 * 3 is non-zero"),
|
||||
@@ -199,25 +251,24 @@ impl Renderer {
|
||||
screen_size: LogicalSize::zero(),
|
||||
},
|
||||
globals_bind_group,
|
||||
texture_bind_group_layout,
|
||||
textures_bind_group_layout,
|
||||
textures: HashMap::default(),
|
||||
samplers: HashMap::default(),
|
||||
batch_bind_group_cache: HashMap::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(
|
||||
&self,
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
render_pass: &mut wgpu::RenderPass<'static>,
|
||||
paint_jobs: &[ClippedMesh],
|
||||
render_job: &RenderJob,
|
||||
screen_size: PhysicalSize<u32>,
|
||||
pixels_per_point: f32,
|
||||
scale_factor: ScaleFactor<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,
|
||||
@@ -228,18 +279,25 @@ impl Renderer {
|
||||
);
|
||||
render_pass.set_pipeline(&self.pipeline);
|
||||
render_pass.set_bind_group(0, &self.globals_bind_group, &[]);
|
||||
render_pass.set_index_buffer(
|
||||
self.index_buffer.buffer.slice(..),
|
||||
wgpu::IndexFormat::Uint32,
|
||||
);
|
||||
render_pass.set_vertex_buffer(0, self.vertex_buffer.buffer.slice(..));
|
||||
|
||||
for ClippedMesh { clip_rect, mesh } in paint_jobs {
|
||||
let phys_clip_rect = clip_rect.to_physical::<f32, _>(pixels_per_point).round();
|
||||
for batch in &render_job.batches {
|
||||
// set textures array bind group
|
||||
let bind_group = self.get_or_build_batch_bind_group(device, batch);
|
||||
render_pass.set_bind_group(1, bind_group, &[]);
|
||||
|
||||
// scissor
|
||||
let phys_clip_rect = batch.clip_rect * scale_factor;
|
||||
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());
|
||||
.intersection(&screen_rect.cast())
|
||||
.map(|s| s.round().to_u32());
|
||||
|
||||
// skip batch if scissor doesn't intersect screen
|
||||
let Some(scissor) = scissor else {
|
||||
index_buffer_slices.next().unwrap();
|
||||
vertex_buffer_slices.next().unwrap();
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -250,27 +308,8 @@ impl Renderer {
|
||||
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);
|
||||
}
|
||||
// draw batch
|
||||
render_pass.draw_indexed(batch.index_range.clone(), 0, 0..1);
|
||||
}
|
||||
|
||||
render_pass.set_scissor_rect(0, 0, screen_size.width, screen_size.height);
|
||||
@@ -287,96 +326,113 @@ impl Renderer {
|
||||
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;
|
||||
match image_delta {
|
||||
image::ImageDelta::Full {
|
||||
image,
|
||||
options,
|
||||
mip_strategy,
|
||||
} => {
|
||||
let generate_mipmaps = matches!(mip_strategy, MipStrategy::GenerateOnUpload);
|
||||
let mip_level_count = mip_strategy.resolve_mip_level_count(image);
|
||||
|
||||
let size = wgpu::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: array_layers,
|
||||
};
|
||||
let size = wgpu::Extent3d {
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
depth_or_array_layers: image.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 label_str = format!("texture_{id:?}");
|
||||
let label = Some(label_str.as_str());
|
||||
|
||||
let mip_level_count = if gen_mipmaps {
|
||||
size.max_mips(wgpu::TextureDimension::D2)
|
||||
} else {
|
||||
mipmap_count.get()
|
||||
};
|
||||
let texture = create_texture_with_data(
|
||||
device,
|
||||
queue,
|
||||
&wgpu::TextureDescriptor {
|
||||
label,
|
||||
size,
|
||||
mip_level_count,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: image.format,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING
|
||||
| wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[image.format.add_srgb_suffix()],
|
||||
},
|
||||
image.data_order.into(),
|
||||
&image.bytes,
|
||||
generate_mipmaps,
|
||||
);
|
||||
|
||||
let label_str = format!("texture_{id:?}");
|
||||
let label = Some(label_str.as_str());
|
||||
if generate_mipmaps {
|
||||
mipmap::generate_mipmap_chain(queue, &texture, &image.bytes);
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
dimension: Some(wgpu::TextureViewDimension::D2Array),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
if gen_mipmaps {
|
||||
mipmap::generate_mipmap_chain(queue, &texture, bytes);
|
||||
self.samplers
|
||||
.entry(*options)
|
||||
.or_insert_with(|| create_sampler(*options, device));
|
||||
|
||||
self.textures.insert(
|
||||
*id,
|
||||
TextureEntry {
|
||||
texture,
|
||||
view,
|
||||
options: *options,
|
||||
},
|
||||
);
|
||||
|
||||
self.batch_bind_group_cache.clear();
|
||||
}
|
||||
image::ImageDelta::Partial {
|
||||
image: source,
|
||||
origin,
|
||||
} => {
|
||||
let destination = self.textures.get(id).expect("Texture is allocated");
|
||||
|
||||
let size = wgpu::Extent3d {
|
||||
width: source.width,
|
||||
height: source.height,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
|
||||
let origin = Origin3d {
|
||||
x: origin.x,
|
||||
y: origin.y,
|
||||
z: origin.layer,
|
||||
};
|
||||
|
||||
// NOTE: this doesn't handle mipmaps or formats other than RBGA
|
||||
queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &destination.texture,
|
||||
mip_level: 0,
|
||||
origin,
|
||||
aspect: wgpu::wgt::TextureAspect::All,
|
||||
},
|
||||
&source.bytes,
|
||||
wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(4 * source.width),
|
||||
rows_per_image: Some(source.height),
|
||||
},
|
||||
size,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
|
||||
if !textures_delta.free.is_empty() {
|
||||
self.batch_bind_group_cache.clear();
|
||||
}
|
||||
|
||||
for id in &textures_delta.free {
|
||||
if let Some(texture) = self.textures.remove(id) {
|
||||
texture.texture.destroy();
|
||||
@@ -390,14 +446,14 @@ impl Renderer {
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
paint_jobs: &[ClippedMesh],
|
||||
render_job: &RenderJob,
|
||||
screen_size: PhysicalSize<u32>,
|
||||
pixels_per_point: f32,
|
||||
scale_factor: ScaleFactor<f32>,
|
||||
) {
|
||||
profiling::scope!("update_buffers");
|
||||
|
||||
let uniform_buffer_content = Globals {
|
||||
screen_size: screen_size.to_logical(pixels_per_point),
|
||||
screen_size: screen_size.cast() / scale_factor,
|
||||
};
|
||||
|
||||
// update globals uniform buffer
|
||||
@@ -410,65 +466,90 @@ impl Renderer {
|
||||
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(),
|
||||
)
|
||||
})
|
||||
};
|
||||
let vertex_count = render_job.vertices.len();
|
||||
let index_count = render_job.indices.len();
|
||||
|
||||
if !(index_count > 0 && vertex_count > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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 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"),
|
||||
);
|
||||
staging_index_buffer
|
||||
.slice(..)
|
||||
.copy_from_slice(bytemuck::cast_slice(&render_job.indices));
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
staging_vertex_buffer
|
||||
.slice(..)
|
||||
.copy_from_slice(bytemuck::cast_slice(&render_job.vertices));
|
||||
}
|
||||
|
||||
fn get_or_build_batch_bind_group(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
batch: &Batch,
|
||||
) -> &wgpu::BindGroup {
|
||||
let key = calculate_hash(&batch.textures);
|
||||
|
||||
self.batch_bind_group_cache.entry(key).or_insert_with(|| {
|
||||
let mut views: Vec<_> = batch
|
||||
.textures
|
||||
.iter()
|
||||
.map(|id| &self.textures[id].view)
|
||||
.collect();
|
||||
let mut samplers: Vec<_> = batch
|
||||
.textures
|
||||
.iter()
|
||||
.map(|id| {
|
||||
self.samplers
|
||||
.get(&self.textures[id].options)
|
||||
.expect("sampler is present from update_textures")
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Metal doesn't support the PARTIALLY_BOUND_BINDING_ARRAY feature
|
||||
// so we pad to up MAX_SLOTS with a dummy view/sampler
|
||||
let dummy = &self.textures[&DUMMY_TEXTURE_ID];
|
||||
let dummy_sampler = self.samplers.get(&dummy.options).unwrap();
|
||||
views.resize(BATCH_TEX_SLOTS.get() as usize, &dummy.view);
|
||||
samplers.resize(BATCH_TEX_SLOTS.get() as usize, dummy_sampler);
|
||||
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("batch_textures_bind_group"),
|
||||
layout: &self.textures_bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureViewArray(&views),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::SamplerArray(&samplers),
|
||||
},
|
||||
],
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SlicedBuffer {
|
||||
struct Buffer {
|
||||
buffer: wgpu::Buffer,
|
||||
slices: Vec<Range<usize>>,
|
||||
size: wgpu::BufferSize,
|
||||
usage: wgpu::BufferUsages,
|
||||
stride: NonZeroU64,
|
||||
}
|
||||
|
||||
impl SlicedBuffer {
|
||||
impl Buffer {
|
||||
fn new(
|
||||
device: &wgpu::Device,
|
||||
usage: wgpu::BufferUsages,
|
||||
@@ -486,7 +567,6 @@ impl SlicedBuffer {
|
||||
|
||||
Self {
|
||||
buffer,
|
||||
slices: Vec::with_capacity(64),
|
||||
size,
|
||||
usage,
|
||||
stride,
|
||||
@@ -542,7 +622,7 @@ fn create_sampler(options: TextureOptions, device: &wgpu::Device) -> wgpu::Sampl
|
||||
}
|
||||
|
||||
/// Adapted from `wgpu::Device::create_texture_with_data`.
|
||||
/// Doesn't upload any data for mip level > 0 if skip_mipmaps is true.
|
||||
/// 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,
|
||||
@@ -551,30 +631,22 @@ fn create_texture_with_data(
|
||||
data: &[u8],
|
||||
skip_mipmaps: bool,
|
||||
) -> wgpu::Texture {
|
||||
// Implicitly add the COPY_DST usage
|
||||
// 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
|
||||
// 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 (outer_iteration, inner_iteration) = match order {
|
||||
wgpu::wgt::TextureDataOrder::LayerMajor => (layer_iterations, desc.mip_level_count),
|
||||
wgpu::wgt::TextureDataOrder::MipMajor => (desc.mip_level_count, layer_iterations),
|
||||
};
|
||||
|
||||
let mut binary_offset = 0;
|
||||
for outer in 0..outer_iteration {
|
||||
@@ -590,13 +662,13 @@ fn create_texture_with_data(
|
||||
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.
|
||||
// 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.
|
||||
// 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;
|
||||
|
||||
|
||||
+97
-17
@@ -2,17 +2,99 @@ use crate::{color::Srgba, renderer::textures::TextureOptions};
|
||||
use image::{DynamicImage, RgbaImage};
|
||||
use std::{io::Read, num::NonZeroU32, path::Path};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum MipStrategy {
|
||||
/// Single mip level.
|
||||
None,
|
||||
/// Generate mip chain from mip 0 on upload.
|
||||
GenerateOnUpload,
|
||||
/// Upload as is. Used when `ImageData` already contains a full mip chain (e.g. when loaded from DDS).
|
||||
Provided,
|
||||
}
|
||||
|
||||
impl MipStrategy {
|
||||
/// Resolves to a `MipStrategy` based on the actual `ImageData` and the callers request to
|
||||
/// generate a mip chain if possible.
|
||||
pub fn resolve(image: &ImageData, generate_if_possible: bool) -> Self {
|
||||
if image.mipmap_count.get() > 1 {
|
||||
Self::Provided
|
||||
} else if generate_if_possible && !image.format.is_compressed() {
|
||||
Self::GenerateOnUpload
|
||||
} else {
|
||||
Self::None
|
||||
}
|
||||
}
|
||||
|
||||
/// Determine mip level count of given `ImageData` after mip strategy has been applied
|
||||
pub fn resolve_mip_level_count(&self, image: &ImageData) -> u32 {
|
||||
match self {
|
||||
Self::None => 1,
|
||||
Self::Provided => image.mipmap_count.get(),
|
||||
Self::GenerateOnUpload => {
|
||||
let size = wgpu::Extent3d {
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
depth_or_array_layers: image.array_layers,
|
||||
};
|
||||
size.max_mips(wgpu::TextureDimension::D2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PartialDeltaOrigin {
|
||||
pub x: u32,
|
||||
pub y: u32,
|
||||
pub layer: u32,
|
||||
}
|
||||
|
||||
/// Represents the change to a GPU texture.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ImageDelta {
|
||||
pub image: ImageData,
|
||||
pub options: TextureOptions,
|
||||
pub enum ImageDelta {
|
||||
/// Creates a whole new texture.
|
||||
Full {
|
||||
image: ImageData,
|
||||
options: TextureOptions,
|
||||
mip_strategy: MipStrategy,
|
||||
},
|
||||
/// Updates a sub-region starting at `origin` of an existing texture.
|
||||
Partial {
|
||||
image: ImageData,
|
||||
origin: PartialDeltaOrigin,
|
||||
},
|
||||
}
|
||||
|
||||
impl ImageDelta {
|
||||
pub fn new<I: Into<ImageData>>(image: I, options: TextureOptions) -> Self {
|
||||
Self {
|
||||
image: image.into(),
|
||||
pub fn full<I: Into<ImageData>>(
|
||||
image: I,
|
||||
options: TextureOptions,
|
||||
mip_strategy: MipStrategy,
|
||||
) -> Self {
|
||||
let image = image.into();
|
||||
|
||||
debug_assert!(
|
||||
match mip_strategy {
|
||||
MipStrategy::None => true,
|
||||
MipStrategy::GenerateOnUpload => {
|
||||
image.mipmap_count.get() == 1 && !image.format.is_compressed()
|
||||
}
|
||||
MipStrategy::Provided => image.mipmap_count.get() > 1,
|
||||
},
|
||||
"MipStrategy inconsistent with image data"
|
||||
);
|
||||
|
||||
Self::Full {
|
||||
image,
|
||||
options,
|
||||
mip_strategy,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn partial<I: Into<ImageData>>(image: I, origin: PartialDeltaOrigin) -> Self {
|
||||
Self::Partial {
|
||||
image: image.into(),
|
||||
origin,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -61,7 +143,7 @@ impl ImageData {
|
||||
height,
|
||||
array_layers: 1,
|
||||
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
|
||||
data_order: Default::default(),
|
||||
data_order: DataOrder::default(),
|
||||
bytes: RgbaImage::from_pixel(width, height, color.0.into()).into_raw(),
|
||||
}
|
||||
}
|
||||
@@ -75,7 +157,7 @@ impl From<DynamicImage> for ImageData {
|
||||
height: image.height(),
|
||||
array_layers: 1,
|
||||
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
|
||||
data_order: Default::default(),
|
||||
data_order: DataOrder::default(),
|
||||
bytes: image.to_rgba8().into_raw(),
|
||||
}
|
||||
}
|
||||
@@ -89,7 +171,7 @@ impl From<RgbaImage> for ImageData {
|
||||
height: image.height(),
|
||||
array_layers: 1,
|
||||
mipmap_count: NonZeroU32::new(1).expect("1 is non-zero"),
|
||||
data_order: Default::default(),
|
||||
data_order: DataOrder::default(),
|
||||
bytes: image.into_raw(),
|
||||
}
|
||||
}
|
||||
@@ -103,7 +185,7 @@ impl std::fmt::Debug for ImageData {
|
||||
.field("height", &self.height)
|
||||
.field("array_layers", &self.array_layers)
|
||||
.field("mipmap_count", &self.mipmap_count)
|
||||
.finish()
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,12 +220,10 @@ fn resolve_path<P: AsRef<Path>>(path: P) -> std::path::PathBuf {
|
||||
|
||||
/// Checks if file is a compressed DDS file (.dds.zst)
|
||||
fn is_compressed_dds<P: AsRef<Path>>(path: P) -> bool {
|
||||
let path = path.as_ref();
|
||||
path.extension().and_then(|s| s.to_str()) == Some("zst")
|
||||
&& path
|
||||
.file_stem()
|
||||
.and_then(|s| s.to_str())
|
||||
.is_some_and(|s| s.ends_with(".dds"))
|
||||
path.as_ref()
|
||||
.to_string_lossy()
|
||||
.to_ascii_lowercase()
|
||||
.ends_with(".dds.zst")
|
||||
}
|
||||
|
||||
fn dds_format_to_wgpu(format: dds::Format) -> anyhow::Result<wgpu::TextureFormat> {
|
||||
@@ -153,7 +233,7 @@ fn dds_format_to_wgpu(format: dds::Format) -> anyhow::Result<wgpu::TextureFormat
|
||||
dds::Format::BC3_UNORM => wgpu::TextureFormat::Bc3RgbaUnorm,
|
||||
dds::Format::BC7_UNORM => wgpu::TextureFormat::Bc7RgbaUnorm,
|
||||
dds::Format::R8G8B8A8_UNORM => wgpu::TextureFormat::Rgba8Unorm,
|
||||
_ => anyhow::bail!("Unsupported DDS format: {:?}", format),
|
||||
_ => anyhow::bail!("Unsupported DDS format: {format:?}"),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+11
-6
@@ -1,8 +1,11 @@
|
||||
enable wgpu_binding_array;
|
||||
|
||||
// Vertex shader bindings
|
||||
struct VertexOutput {
|
||||
@location(0) tex_coord: vec2<f32>,
|
||||
@location(1) color: vec4<f32>, // linear
|
||||
@location(2) layer_idx: u32,
|
||||
@location(1) color: vec4<f32>,
|
||||
@location(2) @interpolate(flat) texture_idx: u32,
|
||||
@location(3) @interpolate(flat) layer_idx: u32,
|
||||
@builtin(position) position: vec4<f32>,
|
||||
};
|
||||
|
||||
@@ -36,18 +39,20 @@ 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,
|
||||
@location(3) a_texture_idx: u32,
|
||||
@location(4) a_layer_idx: u32,
|
||||
) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
out.tex_coord = a_tex_coord;
|
||||
out.texture_idx = a_texture_idx;
|
||||
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;
|
||||
@group(1) @binding(0) var textures: binding_array<texture_2d_array<f32>>;
|
||||
@group(1) @binding(1) var samplers: binding_array<sampler>;
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
@@ -56,7 +61,7 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
// 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);
|
||||
let tex_color = textureSample(textures[in.texture_idx], samplers[in.texture_idx], in.tex_coord, in.layer_idx);
|
||||
var out_color = in.color * tex_color;
|
||||
return out_color;
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
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,
|
||||
/// Index into texture array
|
||||
/// TODO: Remove from Vertex and put into Mesh. Use push constant to set index
|
||||
/// before each draw call. Not sure if actually faster, profiling needed.
|
||||
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,
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
/// 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);
|
||||
assert_eq!(texture.format().components(), 4);
|
||||
|
||||
let size = texture.size();
|
||||
let block_size = texture.format().block_copy_size(None).unwrap_or(4);
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
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.y).hash(state);
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
use crate::{
|
||||
dpi::{ConvertToLogical, ConvertToPhysical, 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,
|
||||
pixels_per_point: f32,
|
||||
) -> 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,
|
||||
pixels_per_point,
|
||||
&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,
|
||||
pixels_per_point: f32,
|
||||
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,
|
||||
pixels_per_point,
|
||||
&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,
|
||||
pixels_per_point: f32,
|
||||
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);
|
||||
|
||||
// Make sure the layout origin aligns with the physical pixel grid so
|
||||
// that each glyph aligns correctly. Glyphs are positioned relative
|
||||
// to the layout origin and assume that it ends up on the start of
|
||||
// a physical pixel.
|
||||
let layout_pos = layout_pos
|
||||
.to_physical::<f32, _>(pixels_per_point)
|
||||
.round()
|
||||
.to_logical(pixels_per_point);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+215
-103
@@ -1,27 +1,24 @@
|
||||
use std::{
|
||||
collections::hash_map::Entry,
|
||||
path::Path,
|
||||
sync::{Arc, RwLock},
|
||||
};
|
||||
use std::{cell::RefCell, collections::hash_map::Entry, path::Path, rc::Rc, sync::mpsc};
|
||||
|
||||
use ahash::HashMap;
|
||||
use anyhow::bail;
|
||||
|
||||
use crate::{
|
||||
color::Srgba,
|
||||
renderer::image::{ImageData, ImageDelta, load_image_file},
|
||||
dpi::PhysicalSize,
|
||||
renderer::image::{ImageData, ImageDelta, MipStrategy, load_image_file},
|
||||
worker_pool::WorkerPool,
|
||||
};
|
||||
|
||||
pub type TextureId = u64;
|
||||
|
||||
pub struct TextureHandle {
|
||||
tex_mngr: Arc<RwLock<TextureManager>>,
|
||||
tex_mngr: Rc<RefCell<TextureRegistry>>,
|
||||
id: TextureId,
|
||||
}
|
||||
|
||||
impl TextureHandle {
|
||||
pub fn new(tex_mngr: Arc<RwLock<TextureManager>>, id: TextureId) -> Self {
|
||||
fn new(tex_mngr: Rc<RefCell<TextureRegistry>>, id: TextureId) -> Self {
|
||||
Self { tex_mngr, id }
|
||||
}
|
||||
|
||||
@@ -29,26 +26,44 @@ impl TextureHandle {
|
||||
self.id
|
||||
}
|
||||
|
||||
pub fn size(&self) -> [usize; 2] {
|
||||
self.tex_mngr
|
||||
.read()
|
||||
.unwrap()
|
||||
pub fn size(&self) -> Option<PhysicalSize<u32>> {
|
||||
match self
|
||||
.tex_mngr
|
||||
.borrow()
|
||||
.get_meta_data(self.id)
|
||||
.map_or([0, 0], |tex| tex.size)
|
||||
.expect("Texture exists because we hold a handle")
|
||||
.state
|
||||
{
|
||||
TextureState::AsyncLoading => None,
|
||||
TextureState::Loaded(shape) => Some(shape.size),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_loading(&self) -> bool {
|
||||
match self
|
||||
.tex_mngr
|
||||
.borrow()
|
||||
.get_meta_data(self.id)
|
||||
.expect("Texture exists because we hold a handle")
|
||||
.state
|
||||
{
|
||||
TextureState::AsyncLoading => true,
|
||||
TextureState::Loaded(_) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TextureHandle {
|
||||
fn drop(&mut self) {
|
||||
self.tex_mngr.write().unwrap().free(self.id);
|
||||
self.tex_mngr.borrow_mut().free(self.id);
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for TextureHandle {
|
||||
fn clone(&self) -> Self {
|
||||
self.tex_mngr.write().unwrap().retain(self.id);
|
||||
self.tex_mngr.borrow_mut().retain(self.id);
|
||||
Self {
|
||||
tex_mngr: Arc::clone(&self.tex_mngr),
|
||||
tex_mngr: Rc::clone(&self.tex_mngr),
|
||||
id: self.id,
|
||||
}
|
||||
}
|
||||
@@ -66,75 +81,144 @@ impl TexturesDelta {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct TextureShape {
|
||||
size: PhysicalSize<u32>,
|
||||
format: wgpu::TextureFormat,
|
||||
array_layers: u32,
|
||||
mip_level_count: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum TextureState {
|
||||
/// Texture is being loaded asynchronously
|
||||
AsyncLoading,
|
||||
Loaded(TextureShape),
|
||||
}
|
||||
|
||||
/// Metadata about an allocated texture.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TextureMetaData {
|
||||
pub name: String,
|
||||
pub size: [usize; 2],
|
||||
name: String,
|
||||
options: TextureOptions,
|
||||
state: TextureState,
|
||||
/// Texture is freed when this reaches zero
|
||||
retain_count: usize,
|
||||
pub options: TextureOptions,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct TextureManager {
|
||||
struct TextureRegistry {
|
||||
next_id: u64,
|
||||
meta_data: HashMap<TextureId, TextureMetaData>,
|
||||
delta: TexturesDelta,
|
||||
}
|
||||
|
||||
impl TextureManager {
|
||||
impl TextureRegistry {
|
||||
/// Allocates a new Texture.
|
||||
pub fn alloc(&mut self, name: String, image: ImageData, options: TextureOptions) -> TextureId {
|
||||
pub fn alloc(
|
||||
&mut self,
|
||||
name: String,
|
||||
image: ImageData,
|
||||
options: TextureOptions,
|
||||
generate_mipmaps: bool,
|
||||
) -> 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,
|
||||
});
|
||||
let mip_strategy = MipStrategy::resolve(&image, generate_mipmaps);
|
||||
|
||||
self.meta_data.insert(
|
||||
id,
|
||||
TextureMetaData {
|
||||
name,
|
||||
retain_count: 1,
|
||||
options,
|
||||
state: TextureState::Loaded(TextureShape {
|
||||
size: PhysicalSize::new(image.width, image.height),
|
||||
format: image.format,
|
||||
array_layers: image.array_layers,
|
||||
mip_level_count: mip_strategy.resolve_mip_level_count(&image),
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
self.delta
|
||||
.update
|
||||
.push((id, ImageDelta::new(image, options)));
|
||||
.push((id, ImageDelta::full(image, options, mip_strategy)));
|
||||
|
||||
id
|
||||
}
|
||||
|
||||
/// Reserves a new TextureId for later assignment.
|
||||
/// 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,
|
||||
});
|
||||
self.meta_data.insert(
|
||||
id,
|
||||
TextureMetaData {
|
||||
name,
|
||||
retain_count: 1,
|
||||
options,
|
||||
state: TextureState::AsyncLoading,
|
||||
},
|
||||
);
|
||||
|
||||
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");
|
||||
let Some(meta_data) = self.meta_data.get_mut(&id) else {
|
||||
// the handle may have been dropped while the async load was in flight.
|
||||
// just discard the result.
|
||||
log::debug!("Discarding load result for freed texture {id:?}");
|
||||
return;
|
||||
};
|
||||
|
||||
match &delta {
|
||||
ImageDelta::Full {
|
||||
image,
|
||||
mip_strategy,
|
||||
..
|
||||
} => {
|
||||
meta_data.state = TextureState::Loaded(TextureShape {
|
||||
size: PhysicalSize::new(image.width, image.height),
|
||||
format: image.format,
|
||||
array_layers: image.array_layers,
|
||||
mip_level_count: mip_strategy.resolve_mip_level_count(image),
|
||||
});
|
||||
// discard all old enqueued deltas since we're doing a full update
|
||||
self.delta.update.retain(|(x, _)| x != &id);
|
||||
}
|
||||
ImageDelta::Partial { image, .. } => {
|
||||
let TextureState::Loaded(shape) = &meta_data.state else {
|
||||
panic!("partial update for texture {id:?} which hasn't finished loading!");
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
shape.format, image.format,
|
||||
"format of partial update must match format of existing texture {id:?}"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
shape.mip_level_count, 1,
|
||||
"partial updates are not supported for textures with mipmaps (texture {id:?})"
|
||||
);
|
||||
}
|
||||
}
|
||||
self.delta.update.push((id, delta));
|
||||
}
|
||||
|
||||
/// 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;
|
||||
debug_assert!(
|
||||
meta.retain_count > 0,
|
||||
"Tried freeing texture {id:?} with retain_count == 0"
|
||||
);
|
||||
meta.retain_count = meta.retain_count.saturating_sub(1);
|
||||
if meta.retain_count == 0 {
|
||||
entry.remove();
|
||||
self.delta.free.push(id);
|
||||
@@ -169,39 +253,56 @@ impl TextureManager {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WrappedTextureManager {
|
||||
manager: Arc<RwLock<TextureManager>>,
|
||||
worker_pool: WorkerPool,
|
||||
enum LoadResult {
|
||||
Loaded {
|
||||
id: TextureId,
|
||||
image: ImageData,
|
||||
options: TextureOptions,
|
||||
generate_mipmaps: bool,
|
||||
},
|
||||
}
|
||||
|
||||
impl WrappedTextureManager {
|
||||
pub struct TextureManager {
|
||||
manager: Rc<RefCell<TextureRegistry>>,
|
||||
worker_pool: WorkerPool,
|
||||
// channel for handling async image loads
|
||||
results_tx: mpsc::Sender<LoadResult>,
|
||||
results_rx: mpsc::Receiver<LoadResult>,
|
||||
}
|
||||
|
||||
impl TextureManager {
|
||||
pub fn new() -> Self {
|
||||
let manager = Arc::new(RwLock::new(TextureManager::default()));
|
||||
let mut manager = TextureRegistry::default();
|
||||
|
||||
// allocate default texture (id: 0) for font atlas
|
||||
manager.write().unwrap().alloc(
|
||||
manager.alloc(
|
||||
"font_atlas_texture".into(),
|
||||
ImageData::from_solid_color([0, 0], Srgba::TRANSPARENT),
|
||||
ImageData::from_solid_color([1, 1], Srgba::WHITE),
|
||||
TextureOptions::default(),
|
||||
false,
|
||||
);
|
||||
|
||||
let (tx, rx) = mpsc::channel();
|
||||
|
||||
Self {
|
||||
manager,
|
||||
manager: Rc::new(RefCell::new(manager)),
|
||||
worker_pool: WorkerPool::new(4),
|
||||
results_tx: tx,
|
||||
results_rx: rx,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn update_font_texture(&self, delta: ImageDelta) {
|
||||
self.manager
|
||||
.write()
|
||||
.unwrap()
|
||||
.set(TextureId::default(), delta);
|
||||
pub fn update_font_texture(&self, delta: Vec<ImageDelta>) {
|
||||
for d in delta {
|
||||
self.manager.borrow_mut().set(TextureId::default(), d);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn take_delta(&self) -> TexturesDelta {
|
||||
self.manager.write().unwrap().take_delta()
|
||||
self.apply_pending_loads();
|
||||
self.manager.borrow_mut().take_delta()
|
||||
}
|
||||
|
||||
pub fn load_texture(
|
||||
@@ -209,43 +310,48 @@ impl WrappedTextureManager {
|
||||
image_path: String,
|
||||
options: TextureOptions,
|
||||
is_async: bool,
|
||||
generate_mipmaps: bool,
|
||||
) -> anyhow::Result<TextureHandle> {
|
||||
let manager = Arc::clone(&self.manager);
|
||||
profiling::scope!("load_texture");
|
||||
|
||||
let handle = if is_async {
|
||||
let id = manager
|
||||
.write()
|
||||
.unwrap()
|
||||
if is_async {
|
||||
let id = self
|
||||
.manager
|
||||
.borrow_mut()
|
||||
.reserve(image_path.clone(), options);
|
||||
|
||||
// load image in background worker
|
||||
let mngr_clone = Arc::clone(&manager);
|
||||
let tx = self.results_tx.clone();
|
||||
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));
|
||||
let _ = tx.send(LoadResult::Loaded {
|
||||
id,
|
||||
image,
|
||||
options,
|
||||
generate_mipmaps,
|
||||
});
|
||||
}
|
||||
Err(e) => log::warn!("Unable to load image fron {}: {}", &image_path, e),
|
||||
Err(e) => log::warn!("Unable to load image from {image_path}: {e}"),
|
||||
});
|
||||
|
||||
TextureHandle::new(manager, id)
|
||||
Ok(TextureHandle::new(Rc::clone(&self.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)
|
||||
let id = self.manager.borrow_mut().alloc(
|
||||
image_path,
|
||||
image,
|
||||
options,
|
||||
generate_mipmaps,
|
||||
);
|
||||
Ok(TextureHandle::new(Rc::clone(&self.manager), id))
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("Unable to load image fron {}: {}", &image_path, e);
|
||||
log::warn!("Unable to load image from {image_path}: {e}");
|
||||
bail!(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok(handle)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_texture(
|
||||
@@ -254,29 +360,32 @@ impl WrappedTextureManager {
|
||||
image_path: String,
|
||||
options: TextureOptions,
|
||||
is_async: bool,
|
||||
generate_mipmaps: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
if is_async {
|
||||
let mngr_clone = Arc::clone(&self.manager);
|
||||
let tx = self.results_tx.clone();
|
||||
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));
|
||||
let _ = tx.send(LoadResult::Loaded {
|
||||
id: texture_id,
|
||||
image,
|
||||
options,
|
||||
generate_mipmaps,
|
||||
});
|
||||
}
|
||||
Err(e) => log::warn!("Unable to load image fron {}: {}", &image_path, e),
|
||||
Err(e) => log::warn!("Unable to load image from {image_path}: {e}"),
|
||||
});
|
||||
} else {
|
||||
match load_image_file(Path::new(&image_path)) {
|
||||
Ok(image) => {
|
||||
let mip_strategy = MipStrategy::resolve(&image, generate_mipmaps);
|
||||
self.manager
|
||||
.write()
|
||||
.unwrap()
|
||||
.set(texture_id, ImageDelta::new(image, options));
|
||||
.borrow_mut()
|
||||
.set(texture_id, ImageDelta::full(image, options, mip_strategy));
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("Unable to load image fron {}: {}", &image_path, e);
|
||||
log::warn!("Unable to load image from {image_path}: {e}");
|
||||
bail!(e);
|
||||
}
|
||||
}
|
||||
@@ -284,15 +393,29 @@ impl WrappedTextureManager {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drains completed async image loads and assigns them to textures
|
||||
fn apply_pending_loads(&self) {
|
||||
let mut manager = self.manager.borrow_mut();
|
||||
while let Ok(LoadResult::Loaded {
|
||||
id,
|
||||
image,
|
||||
options,
|
||||
generate_mipmaps,
|
||||
}) = self.results_rx.try_recv()
|
||||
{
|
||||
let mip_strategy = MipStrategy::resolve(&image, generate_mipmaps);
|
||||
manager.set(id, ImageDelta::full(image, options, mip_strategy));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
|
||||
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,
|
||||
pub mipmap_mode: wgpu::MipmapFilterMode,
|
||||
}
|
||||
|
||||
impl TextureOptions {
|
||||
@@ -300,16 +423,14 @@ impl TextureOptions {
|
||||
magnification: wgpu::FilterMode::Linear,
|
||||
minification: wgpu::FilterMode::Linear,
|
||||
wrap_mode: wgpu::AddressMode::Repeat,
|
||||
mipmap_mode: wgpu::FilterMode::Linear,
|
||||
generate_mipmaps: false,
|
||||
mipmap_mode: wgpu::MipmapFilterMode::Linear,
|
||||
};
|
||||
|
||||
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,
|
||||
mipmap_mode: wgpu::MipmapFilterMode::Linear,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -318,12 +439,3 @@ impl Default for TextureOptions {
|
||||
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,88 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use winit::window::Window;
|
||||
|
||||
use crate::{
|
||||
dpi::{PhysicalPoint, PhysicalSize, ScaleFactor},
|
||||
draw_commands::DrawCommand,
|
||||
input::{Key, ModifiersState, MouseButton},
|
||||
installer::Installer,
|
||||
pob::PathOfBuilding,
|
||||
};
|
||||
|
||||
pub enum StageEvent {
|
||||
KeyDown { key: Key },
|
||||
KeyUp { key: Key },
|
||||
CharacterInput { ch: char },
|
||||
ModifiersChanged { state: ModifiersState },
|
||||
MouseDown { button: MouseButton },
|
||||
MouseUp { button: MouseButton },
|
||||
MouseWheel { delta: f32 },
|
||||
MouseMoved { pos: PhysicalPoint<f32> },
|
||||
Exit,
|
||||
Resized(PhysicalSize<u32>),
|
||||
ScaleFactorChanged(f64),
|
||||
FocusChanged(bool),
|
||||
HoverChanged(bool),
|
||||
}
|
||||
|
||||
pub enum StageTransition {
|
||||
ToMain,
|
||||
ToShutdown,
|
||||
}
|
||||
|
||||
pub struct StageFrameOutput {
|
||||
pub draw_commands: Vec<DrawCommand>,
|
||||
pub can_elide: bool,
|
||||
pub request_redraw: bool,
|
||||
pub scale_factor: ScaleFactor<f32>,
|
||||
}
|
||||
|
||||
pub enum ActiveStage {
|
||||
Startup(Installer),
|
||||
Main(PathOfBuilding),
|
||||
}
|
||||
|
||||
impl ActiveStage {
|
||||
pub fn update(&mut self) -> anyhow::Result<Option<StageTransition>> {
|
||||
match self {
|
||||
Self::Startup(s) => s.update(),
|
||||
Self::Main(s) => s.update(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn frame(&mut self) -> anyhow::Result<StageFrameOutput> {
|
||||
match self {
|
||||
Self::Startup(s) => s.frame(),
|
||||
Self::Main(s) => s.frame(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_event(&mut self, event: StageEvent) -> anyhow::Result<Option<StageTransition>> {
|
||||
match self {
|
||||
Self::Startup(s) => s.handle_event(event),
|
||||
Self::Main(s) => s.handle_event(event),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_window(&mut self, window: Arc<Window>) {
|
||||
match self {
|
||||
Self::Startup(s) => s.set_window(window),
|
||||
Self::Main(s) => s.set_window(window),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_exit(&mut self) -> bool {
|
||||
match self {
|
||||
Self::Startup(_) => true,
|
||||
Self::Main(s) => s.can_exit(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_pressed(&mut self) {
|
||||
match self {
|
||||
Self::Startup(_) => {}
|
||||
Self::Main(s) => s.clear_pressed(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,373 +0,0 @@
|
||||
use crate::{api::get_callback, lua::LuaInstance};
|
||||
use anyhow::{Result, anyhow};
|
||||
use mlua::{Function, Integer, IntoLuaMulti, Lua, MultiValue, Number, Result as LuaResult, Value};
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::VecDeque,
|
||||
path::PathBuf,
|
||||
rc::Rc,
|
||||
sync::mpsc::{Receiver, Sender, TryRecvError, channel},
|
||||
thread::JoinHandle,
|
||||
};
|
||||
|
||||
#[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>,
|
||||
script_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl SubscriptManager {
|
||||
pub fn new(script_dir: PathBuf) -> Self {
|
||||
Self {
|
||||
current_id: 0,
|
||||
scripts: Vec::new(),
|
||||
script_dir,
|
||||
}
|
||||
}
|
||||
|
||||
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.script_dir.clone(),
|
||||
);
|
||||
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
|
||||
}
|
||||
|
||||
pub fn has_running_subscripts(&self) -> bool {
|
||||
!self.scripts.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
enum SubscriptCall {
|
||||
Blocking {
|
||||
function_name: String,
|
||||
arguments: NativeMultiValue,
|
||||
// used to send return values of function back to thread
|
||||
return_values_sender: Sender<Result<NativeMultiValue>>,
|
||||
},
|
||||
NonBlocking {
|
||||
function_name: String,
|
||||
arguments: NativeMultiValue,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct Subscript {
|
||||
id: u64,
|
||||
handle: Option<JoinHandle<anyhow::Result<NativeMultiValue>>>,
|
||||
receiver: Receiver<SubscriptCall>,
|
||||
}
|
||||
|
||||
// Subscripts are lua scripts that are executed in their own instance on a separate
|
||||
// thread.
|
||||
//
|
||||
// When a subscript needs to call a function defined in the main instance, a
|
||||
// `SubscriptCall` message is send over a channel. At the beginning of each frame,
|
||||
// the main thread checks for messages and executes the requested function with the
|
||||
// provided arguments on behalf of the subscript.
|
||||
// For `BlockingCall`, the subscript waits for the main thread to send the return
|
||||
// values of the function back over another channel.
|
||||
// For `NonBlockingCall`, the subscript doesn't wait on any return values and keeps
|
||||
// executing the script after sending the message.
|
||||
// Subscripts are required to explicitly specify the names of all (non)-blocking
|
||||
// function calls that appear in the script.
|
||||
impl Subscript {
|
||||
pub fn new(
|
||||
id: u64,
|
||||
script_text: String,
|
||||
blocking_calls: Vec<String>,
|
||||
nonblocking_calls: Vec<String>,
|
||||
arguments: NativeMultiValue,
|
||||
script_dir: PathBuf,
|
||||
) -> Self {
|
||||
let (tx, rx) = channel();
|
||||
|
||||
let handle = std::thread::spawn(move || {
|
||||
profiling::register_thread!(format!("Subscript {} Thread", id));
|
||||
|
||||
// unsafe required to load C modules (curl)
|
||||
let lua = unsafe { Lua::unsafe_new() };
|
||||
|
||||
// add ./lua to package.path and package.cpath
|
||||
LuaInstance::register_package_paths(&lua, &script_dir)?;
|
||||
|
||||
for function_name in blocking_calls {
|
||||
let thread_tx = tx.clone();
|
||||
lua.globals().set(
|
||||
function_name.clone(),
|
||||
lua.create_function(move |_, args: MultiValue| {
|
||||
let (tx_return, rx_return) = channel();
|
||||
thread_tx
|
||||
.send(SubscriptCall::Blocking {
|
||||
function_name: function_name.clone(),
|
||||
arguments: args.try_into()?,
|
||||
return_values_sender: tx_return,
|
||||
})
|
||||
.unwrap();
|
||||
// this blocks until we receive return values
|
||||
let return_values = rx_return.recv().map_err(|e| anyhow!("{}", e))??;
|
||||
Ok(return_values)
|
||||
})?,
|
||||
)?;
|
||||
}
|
||||
|
||||
for function_name in nonblocking_calls {
|
||||
let thread_tx = tx.clone();
|
||||
lua.globals().set(
|
||||
function_name.clone(),
|
||||
lua.create_function(move |_, args: MultiValue| {
|
||||
thread_tx
|
||||
.send(SubscriptCall::NonBlocking {
|
||||
function_name: function_name.clone(),
|
||||
arguments: args.try_into()?,
|
||||
})
|
||||
.map_err(|e| anyhow!("{}", e))?;
|
||||
Ok(())
|
||||
})?,
|
||||
)?;
|
||||
}
|
||||
|
||||
let result = lua.load(script_text).call::<MultiValue>(arguments)?;
|
||||
result.try_into()
|
||||
});
|
||||
|
||||
Self {
|
||||
id,
|
||||
handle: Some(handle),
|
||||
receiver: rx,
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_calls(&mut self, lua: &Lua) {
|
||||
match self.receiver.try_recv() {
|
||||
Ok(SubscriptCall::Blocking {
|
||||
function_name,
|
||||
arguments,
|
||||
return_values_sender,
|
||||
}) => {
|
||||
let func: Result<Function, _> = get_callback(lua, "OnSubCall");
|
||||
match func {
|
||||
Ok(func) => {
|
||||
match func.call::<MultiValue>((function_name, arguments)) {
|
||||
Ok(return_values) => {
|
||||
// send return values back to thread
|
||||
let _ = return_values_sender.send(return_values.try_into());
|
||||
}
|
||||
// function returned error, forward it to thread
|
||||
Err(err) => {
|
||||
let _ = return_values_sender.send(Err(err.into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
// function not found
|
||||
Err(err) => {
|
||||
let _ = return_values_sender.send(Err(err.into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(SubscriptCall::NonBlocking {
|
||||
function_name,
|
||||
arguments,
|
||||
}) => {
|
||||
let func: Result<Function, _> = get_callback(lua, "OnSubCall");
|
||||
if let Ok(func) = func {
|
||||
// we can ignore return values for non-blocking calls
|
||||
let _ = func.call::<()>((function_name, arguments));
|
||||
}
|
||||
}
|
||||
// ignore disconnects. potential errors are handled during thread join
|
||||
Err(TryRecvError::Disconnected) => {}
|
||||
// no outstanding calls from thread
|
||||
Err(TryRecvError::Empty) => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn try_join(&mut self) -> Option<SubscriptResult> {
|
||||
if self
|
||||
.handle
|
||||
.as_ref()
|
||||
.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("AbortSubScript", 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))
|
||||
}
|
||||
}
|
||||
+62
-5
@@ -1,11 +1,11 @@
|
||||
use ahash::AHasher;
|
||||
use mlua::{Lua, Result as LuaResult, Table, chunk::Chunk};
|
||||
use std::{
|
||||
env,
|
||||
env, fs,
|
||||
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()?;
|
||||
@@ -15,8 +15,8 @@ pub fn get_executable_dir() -> anyhow::Result<PathBuf> {
|
||||
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(),
|
||||
"Failed to change working directory {}: {}",
|
||||
path.as_ref().display(),
|
||||
e
|
||||
)
|
||||
})
|
||||
@@ -52,3 +52,60 @@ pub fn replace_in_matching_lines(
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
/// Appends a search pattern to Lua's `package.path`.
|
||||
pub fn append_lua_package_path(lua: &Lua, pattern: &str) -> LuaResult<()> {
|
||||
let package: Table = lua.globals().get("package")?;
|
||||
let mut package_path: String = package.get("path")?;
|
||||
|
||||
if !package_path.is_empty() {
|
||||
package_path.push(';');
|
||||
}
|
||||
|
||||
package_path.push_str(pattern);
|
||||
package.set("path", package_path)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds a directory to Lua's `package.path`.
|
||||
///
|
||||
/// This adds the following patterns:
|
||||
/// - `<path>/?.lua`
|
||||
/// - `<path>/?/init.lua`
|
||||
pub fn append_lua_package_dir(lua: &Lua, path: &Path) -> LuaResult<()> {
|
||||
let path = path.to_string_lossy();
|
||||
append_lua_package_path(lua, &format!("{path}/?.lua"))?;
|
||||
append_lua_package_path(lua, &format!("{path}/?/init.lua"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rewrites PoB's `#@ <label>` script header into a Lua comment.
|
||||
///
|
||||
/// Some Path of Building scripts start with a line such as `#@ <optional_text>`. Recent LuaJIT
|
||||
/// versions interpret a leading `#` as a line number directive and reject this header so we
|
||||
/// replace them with a comment.
|
||||
///
|
||||
/// commit that introduced changes to the lexer to enable parsing of line number directives:
|
||||
/// <https://github.com/LuaJIT/LuaJIT/commit/c41d727dbffa5ec4f346dd9be0f4c64740f124aa>
|
||||
pub fn fix_script_header(source: &mut [u8]) {
|
||||
// skip utf8-bom
|
||||
let start = if source.starts_with(b"\xEF\xBB\xBF") {
|
||||
3
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if source[start..].starts_with(b"#@") {
|
||||
source[start..start + 2].copy_from_slice(b"--");
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads a Lua script from `path` and applies `fix_script_header`.
|
||||
///
|
||||
/// The chunk name is set to `@<path>` to match `Lua::load`'s behavior for paths, so error messages
|
||||
/// keep referring to the file.
|
||||
pub fn load_lua_file<'lua>(lua: &'lua Lua, path: &Path) -> LuaResult<Chunk<'lua>> {
|
||||
let mut source = fs::read(path)?;
|
||||
fix_script_header(&mut source);
|
||||
Ok(lua.load(source).set_name(format!("@{}", path.display())))
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
use crate::math::{Point, Quad, Rect, Size};
|
||||
|
||||
pub struct UvSpace;
|
||||
|
||||
pub type UvPoint = Point<f32, UvSpace>;
|
||||
pub type UvRect = Rect<f32, UvSpace>;
|
||||
pub type UvQuad = Quad<f32, UvSpace>;
|
||||
|
||||
pub trait UvConstructors {
|
||||
fn full_uv() -> Self;
|
||||
fn white_uv() -> Self;
|
||||
}
|
||||
|
||||
impl UvConstructors for UvRect {
|
||||
#[inline]
|
||||
fn full_uv() -> Self {
|
||||
Self::from_size(Size::new(1.0, 1.0))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn white_uv() -> Self {
|
||||
Self::zero()
|
||||
}
|
||||
}
|
||||
|
||||
impl UvConstructors for UvQuad {
|
||||
#[inline]
|
||||
fn full_uv() -> Self {
|
||||
Self::from_size(Size::new(1.0, 1.0))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn white_uv() -> Self {
|
||||
Self::zero()
|
||||
}
|
||||
}
|
||||
+19
-21
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
clipboard::Clipboard,
|
||||
dpi::{ConvertToLogical, LogicalSize, PhysicalSize},
|
||||
dpi::{LogicalSize, PhysicalSize, ScaleFactor},
|
||||
};
|
||||
use raw_window_handle::HasDisplayHandle;
|
||||
use std::sync::Arc;
|
||||
@@ -11,8 +11,8 @@ pub struct WindowState {
|
||||
clipboard: Option<Clipboard>,
|
||||
pub window: Option<Arc<Window>>,
|
||||
pub size: PhysicalSize<u32>,
|
||||
scale_factor: f32,
|
||||
pub scale_factor_override: Option<f32>,
|
||||
scale_factor: ScaleFactor<f32>,
|
||||
scale_factor_override: Option<ScaleFactor<f32>>,
|
||||
pending_window_title: std::cell::Cell<Option<String>>,
|
||||
pub is_hovered: bool,
|
||||
pub is_focused: bool,
|
||||
@@ -22,8 +22,8 @@ impl Default for WindowState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
window: None,
|
||||
size: Default::default(),
|
||||
scale_factor: 1.0,
|
||||
size: PhysicalSize::default(),
|
||||
scale_factor: ScaleFactor::identity(),
|
||||
scale_factor_override: None,
|
||||
pending_window_title: std::cell::Cell::new(None),
|
||||
clipboard: None,
|
||||
@@ -41,7 +41,7 @@ impl WindowState {
|
||||
|
||||
let winit::dpi::PhysicalSize { width, height } = window.inner_size();
|
||||
self.size = PhysicalSize::new(width, height);
|
||||
self.scale_factor = window.scale_factor() as f32;
|
||||
self.scale_factor = ScaleFactor::new(window.scale_factor() as f32);
|
||||
|
||||
let raw_display_handle = window.display_handle().ok().map(|h| h.as_raw());
|
||||
self.clipboard = Some(Clipboard::new(raw_display_handle));
|
||||
@@ -56,16 +56,24 @@ impl WindowState {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn logical_size(&self) -> LogicalSize<u32> {
|
||||
self.size.to_logical(self.scale_factor())
|
||||
pub fn logical_size(&self) -> LogicalSize<f32> {
|
||||
self.size.cast() / self.scale_factor()
|
||||
}
|
||||
|
||||
pub fn scale_factor(&self) -> f32 {
|
||||
pub fn scale_factor(&self) -> ScaleFactor<f32> {
|
||||
self.scale_factor_override.unwrap_or(self.scale_factor)
|
||||
}
|
||||
|
||||
pub fn set_scale_factor(&mut self, scale_factor: f32) {
|
||||
self.scale_factor = scale_factor;
|
||||
self.scale_factor = ScaleFactor::new(scale_factor);
|
||||
}
|
||||
|
||||
pub fn scale_factor_override(&self) -> Option<f32> {
|
||||
self.scale_factor_override.map(ScaleFactor::get)
|
||||
}
|
||||
|
||||
pub fn set_scale_factor_override(&mut self, scale_factor: Option<f32>) {
|
||||
self.scale_factor_override = scale_factor.map(ScaleFactor::new);
|
||||
}
|
||||
|
||||
pub fn focus(&self) {
|
||||
@@ -81,16 +89,6 @@ impl WindowState {
|
||||
}
|
||||
|
||||
pub fn get_clipboard_text(&mut self) -> Option<String> {
|
||||
if let Some(clipboard) = &mut self.clipboard {
|
||||
clipboard.get_text()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn request_redraw(&self) {
|
||||
if let Some(ref window) = self.window {
|
||||
window.request_redraw();
|
||||
}
|
||||
self.clipboard.as_mut().and_then(Clipboard::get_text)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user