Compare commits

..
193 Commits
Author SHA1 Message Date
faumaray ebf33b62dc Let the CI Python distribution locate its packaging interpreter
CI / check (push) Successful in 1m28s
CI / windows (push) Successful in 3m27s
Native release / linux (push) Successful in 1m29s
Native release / windows (push) Successful in 3m1s
Native release / publish (push) Successful in 9s
2026-11-27 23:43:54 +03:00
faumaray 3ea497d38a Ship a self-contained Windows GUI with game shortcuts and application icons
CI / check (push) Successful in 1m30s
CI / windows (push) Failing after 4m27s
2026-11-27 23:34:01 +03:00
faumaray 329a1ad4df trying to fix release
Native release / linux (push) Successful in 1m42s
CI / check (push) Successful in 1m27s
Native release / windows (push) Successful in 3m51s
Native release / publish (push) Successful in 2m15s
Signed-off-by: faumaray <faumaray@gmail.com>
2026-11-27 22:53:32 +03:00
faumaray d5df8da8b9 trying to fix release
CI / check (push) Successful in 1m30s
Native release / linux (push) Successful in 1m34s
Native release / windows (push) Failing after 3m57s
Native release / publish (push) Skipped
Signed-off-by: faumaray <faumaray@gmail.com>
2026-11-27 22:45:08 +03:00
faumaray f9a3d8dbf1 trying to fix release
CI / check (push) Successful in 1m54s
Native release / linux (push) Successful in 2m2s
Native release / windows (push) Failing after 3m55s
Native release / publish (push) Skipped
Signed-off-by: faumaray <faumaray@gmail.com>
2026-11-27 22:38:44 +03:00
faumaray 67fba6c7e2 trying to fix release
CI / check (push) Successful in 1m23s
Native release / linux (push) Successful in 1m30s
Native release / windows (push) Failing after 3m10s
Native release / publish (push) Skipped
Signed-off-by: faumaray <faumaray@gmail.com>
2026-11-27 22:28:38 +03:00
Aleksey Selihov 35ef0c59e4 Обновить .gitea/workflows/release.yml
CI / check (push) Successful in 1m51s
Native release / windows (push) Failing after 4m7s
Native release / linux (push) Successful in 4m17s
Native release / publish (push) Skipped
2026-11-27 19:12:48 +00:00
faumaray 4118c3943f Release 0.3.6 with a game chooser and native installers
CI / check (push) Failing after 7s
Native release / linux (push) Successful in 1m33s
Native release / windows (push) Failing after 9s
Native release / publish (push) Skipped
2026-11-27 21:48:45 +03:00
meehl 67cc995f78 chore: Release rusty-path-of-building version 0.3.5
CI / check (push) Successful in 3m47s
Release / create-release (push) Successful in 6s
2026-11-20 10:13:44 +01:00
meehl 534788f027 Update CHANGELOG 2026-11-20 10:13:29 +01:00
meehl a57e0afda0 Use positive indices for API C-functions
This fixes the issue where error messages display the wrong index number
for the bad argument.
2026-11-20 10:04:40 +01:00
meehl 91ddf5696a Make alignment argument in draw_string API function optional 2026-11-20 09:54:28 +01:00
meehl 08260cabd2 chore: Release rusty-path-of-building version 0.3.4
Release / create-release (push) Successful in 6s
2026-11-13 16:44:49 +01:00
meehl 4316366f87 Apply texture deltas even when skipping frames
Since the renderer rework, texture updates and frees were dropped
whenever a frame was skipped. Apply deltas before acquiring the surface
texture and free textures on skipped or lost surfaces.
2026-11-13 16:34:37 +01:00
meehl 01697e32bd Move text layout positioning into DrawCommandRecorder 2026-11-10 22:55:18 +01:00
Dodomew 3e065a8838 Snap text to pixel grid after applying viewport offset
Text inside viewports was blurry with fractional scale factors because it was aligned to the pixel grid before the viewport offset was applied.
2026-11-10 22:33:55 +01:00
meehl 1aa0aa128f Update contribution guidelines 2026-10-26 11:12:47 +01:00
meehl 098c967206 chore: Release rusty-path-of-building version 0.3.3
Release / create-release (push) Successful in 7s
2026-10-23 16:23:29 +02:00
meehl 1bb0fdf056 Update CHANGELOG 2026-10-23 16:23:07 +02:00
meehl 9a341cfb39 Support passing userdata/tables to luacurl write/header callbacks 2026-10-23 16:16:00 +02:00
meehl 5465544eb2 chore: Release rusty-path-of-building version 0.3.2
Release / create-release (push) Successful in 5s
2026-10-22 12:35:01 +02:00
meehl 75c88af778 Update CHANGELOG 2026-10-22 12:33:53 +02:00
Archer Chang 4db36c1382 Render tab characters as 4 spaces (#62)
`parley` doesn't support tab characters, so tabs in PoB text (e.g. the
Notes tab) were drawn as missing-glyph boxes and broke alignment.
Replace each tab with 4 spaces before layout to match SimpleGraphic.

Fixes #53
2026-10-22 12:31:24 +02:00
meehl 9b925feb90 Refactor surface format selection 2026-10-22 11:12:24 +02:00
meehl 17bb3c6b39 chore: Release rusty-path-of-building version 0.3.1
Release / create-release (push) Successful in 7s
2026-10-21 17:50:12 +02:00
meehl ce62fe64e1 Update CHANGELOG 2026-10-21 17:49:55 +02:00
meehl 4b997447b5 Strip #@ script headers before loading Lua
LuaJIT now only treats a leading `#!` line as a shebang and interprets other
lines beginning with `#` as line number directives.

https://github.com/LuaJIT/LuaJIT/commit/c41d727dbffa5ec4f346dd9be0f4c64740f124aa
2026-10-21 17:45:11 +02:00
meehl a1e92fa94e chore: Release rusty-path-of-building version 0.3.0
Release / create-release (push) Successful in 7s
2026-10-21 15:33:33 +02:00
meehl a24beac554 Update Cargo.lock 2026-10-21 14:59:41 +02:00
meehl 4affef3e62 Move fonts to assets directory 2026-10-21 14:53:08 +02:00
meehl e6ba149516 README formatting 2026-10-21 12:29:56 +02:00
meehl c2222c641b Update changelog 2026-10-21 12:28:58 +02:00
meehl 6427263f2d Update README 2026-10-21 11:52:56 +02:00
meehl f47a2657f6 Add vendored-lua feature for building LuaJIT from source 2026-10-21 11:21:09 +02:00
meehl 6cca05f2f5 Upgrade parley to v0.12 2026-10-21 11:11:02 +02:00
meehl f8a821d310 Upgrade zstd to v0.14 2026-10-21 10:49:40 +02:00
meehl 50e0af6cad cargo update 2026-10-21 10:45:45 +02:00
meehl 0886ad693a Register luazip module
This removes the runtime dependency on the external `lzip` C library.
2026-10-21 10:39:02 +02:00
meehl a4f7353ce6 Implement missing luasocket method 2026-10-17 17:05:13 +02:00
meehl f3c065debd Add feature for registering bundled Lua modules
Enabled by default.
2026-10-17 16:04:54 +02:00
meehl 9b98c65060 Register luacurl module
This removes the runtime dependency on the external `Lua-cURLv3` C library.
2026-10-17 15:04:50 +02:00
meehl b70d612a1d Remove unneeded return statement 2026-10-16 08:30:52 +02:00
meehl 36d2697754 Register luasocket module
This removes the runtime dependency on the external `luasocket` C library.
2026-10-15 23:31:23 +02:00
meehl 8ddcbf89f7 Fix re-entrant context borrow during subscript calls
Move `SubscriptManager` to its own app data slot and dispatch subscript
calls only after releasing the context and manager borrow.
2026-10-15 18:58:11 +02:00
meehl c6d5241b98 Expose luautf8 module through runtime
This removes the runtime dependency on the external `luautf8` C library.
2026-10-14 11:34:23 +02:00
vaisest ae9c59d132 Fix Windows canonical paths (#59) 2026-09-18 10:33:28 +02:00
meehl 41d9c9dbd7 Remove blend mode and mask index from API 2026-09-09 09:21:53 +02:00
meehl e72a271006 Add support for gzip compression 2026-09-08 08:36:23 +02:00
meehl d886f585f8 Adjust CI workflow 2026-09-06 09:02:11 +02:00
zakaluka bc2d245368 Add link to homebrew from README (#56) 2026-09-06 09:00:56 +02:00
meehl 51476da1d9 Make clippy happy 2026-09-02 18:46:37 +02:00
meehl 30bc02252b Add libluajit-5.1-dev as system dependency in CI workflow 2026-09-02 18:42:24 +02:00
meehl d5f9801d49 Add missing system dependency to CI workflow 2026-09-02 18:35:12 +02:00
meehl 0b608602d1 Disable the system feature for parley
System fonts are not needed since we provide our own custom fonts.
Disabling the system feature also removes the dependency on fontconfig
during compilation, which was previously undocumented.
2026-09-02 18:03:56 +02:00
meehl ef32139e14 Add CI workflow 2026-09-02 17:45:44 +02:00
meehl 20a1db073d Lint 2026-09-02 16:37:59 +02:00
meehl aa1bfb768e Add helpers for appending to Lua's package.path 2026-09-02 11:16:21 +02:00
meehl 29e2958dd3 Replace unwrap 2026-09-02 11:15:42 +02:00
meehl 5cbabed095 Simplify return value 2026-09-01 22:05:37 +02:00
meehl 5ba4100589 Small cleanup 2026-09-01 19:18:58 +02:00
meehl fc4d913930 Remove misleading comment 2026-09-01 17:47:37 +02:00
meehl dc9300bca2 Ensure compatibility of partial update with existing texture.
+ some improvements around querying texture loading status.
2026-09-01 14:47:00 +02:00
meehl e90396ff28 Add support for partial GPU texture updates
Mainly used for font atlas changes. Each glyph allocation now only
triggers a partial texture update instead of creating a full new
texture.
2026-09-01 10:17:34 +02:00
meehl e3288b96ac Implement get_draw_layer API function 2026-08-29 23:36:50 +02:00
meehl 749dd69589 Fix double regex matching and iteration in get_index_at_cur 2026-08-29 23:09:08 +02:00
meehl 1a6631c4ad Refactor PoBStringSegmentIterator 2026-08-29 21:46:51 +02:00
meehl 078269653e Restructure api functions 2026-08-29 19:08:49 +02:00
meehl fe96786aca Update comments about PoB alignment argument 2026-08-29 16:35:11 +02:00
meehl 4b344d15ae Refactor mouse and keyboard input handling 2026-08-29 16:12:45 +02:00
meehl c297eeaca6 Improve ergonomics of calling Lua callbacks 2026-08-29 11:28:30 +02:00
meehl 77e1d615e0 Lint 2026-08-28 20:12:42 +02:00
meehl 6f0d678790 Add better docs for subscripts 2026-08-28 20:11:25 +02:00
meehl 38f81cab3e Restructure Subscript::handle_calls 2026-08-28 19:37:18 +02:00
meehl a6c158424f Simply conversion to/from NativeMultiValue 2026-08-28 19:04:13 +02:00
meehl 8556ebf772 Lint 2026-08-28 18:19:16 +02:00
meehl 09f1a16071 Update README 2026-08-28 16:25:12 +02:00
meehl 6f0eef7cf8 Get rid of unwraps 2026-08-27 18:02:24 +02:00
meehl 8cfc82d668 Construct wgpu::VertexBufferLayout directly from Vertex 2026-08-27 17:48:17 +02:00
meehl 9d45b78d64 Use channel to handle async image load results in texture manager 2026-08-27 16:56:03 +02:00
meehl 692e530867 Add profiling scope for call to OnInit 2026-08-27 16:34:40 +02:00
meehl 4e67aa72c0 Acquire context reference after argument validation in image_handle_load
luaL_error can perform a long jump and never return. `drop` might not
get called on the AppDataRef, leaving it permanently borrowed.
2026-08-27 15:31:03 +02:00
meehl ac8cf3946e Remove TODO comment 2026-08-27 13:00:43 +02:00
meehl 49fab3c787 Use constant for number of texture slots in batch 2026-08-27 12:59:23 +02:00
meehl 93ce072d40 Remove unnecessary binding array size constant in shader 2026-08-27 12:43:29 +02:00
meehl 1f5e30ae5a Decouple anchor offset from parley alignment 2026-08-26 17:59:01 +02:00
meehl d217af94c3 Pass scale factor to layout builder.
This means `parley::Layout`'s internal coordinates are now in physical
space.
2026-08-26 17:34:11 +02:00
meehl fe9434e4f0 Warm glyph cache for correct scale factor 2026-08-26 16:16:14 +02:00
meehl f0be43cbdd Add helper for iterating glyph runs 2026-08-26 15:51:42 +02:00
meehl a678c8148d Clean up glyph rasterization 2026-08-26 14:41:32 +02:00
meehl 963a9ba1d1 Add comments about glyph baseline offset 2026-08-26 11:59:01 +02:00
meehl e6c5ec3d42 Move font style cache into separate file 2026-08-26 11:18:16 +02:00
meehl 8f98a9c8f1 Store size instead of rect for cached glyphs.
Their origin is always at (0.0, 0.0).
2026-08-26 10:24:13 +02:00
meehl a50ea4cdaf Introduce new coordinate space for glyph positions within a layout 2026-08-25 12:11:49 +02:00
meehl 7b925876a5 Cleanup of UV space handling 2026-08-25 10:46:12 +02:00
meehl 8d17f8e64f Use euclid::Scale to convert between physical and logical coord spaces 2026-08-24 23:57:19 +02:00
meehl 8ba72fd7df Cull draw command if shape does not intersect viewport. 2026-08-24 11:41:57 +02:00
meehl 2bbfd14c1b Add profileing scope around OnFrame and remove mut ref to context 2026-08-24 10:48:31 +02:00
meehl 99dd50de62 cargo update 2026-08-24 10:38:51 +02:00
meehl 6224a1b0a4 Lint 2026-08-24 10:24:51 +02:00
meehl 8cf5110eb2 Fix trailing whitespaces being ignored by string width query 2026-08-24 09:46:33 +02:00
meehl 493a2ba9cf Fix typo 2026-08-24 08:58:00 +02:00
meehl cc6de120f2 Refactor context handling and redraw requests
Remove unsafe pointer shenanigans and give Lua instance ownership over
`Context`. Event handlers now directly mutate Context instead of using a
shared app state which is then hooked up to Context via unsafe pointers.
The removal of a shared state means stages (previously called "modes")
are now responsible for keeping their own internal state.

Additionally, clean up draw request handling and module hierarchy.
2026-08-23 23:55:43 +02:00
meehl 337e876571 Fix off-by-one error in batcher 2026-08-23 15:24:14 +02:00
meehl d4ca16f07e Remove unnecessary Box around Context 2026-08-20 10:50:30 +02:00
meehl 6fe15c63fe DrawCommandRecorder::finish() doesn't need mutable reference 2026-08-18 11:06:38 +02:00
meehl 1cd62c2b1c Fix absolute positioning of text 2026-08-18 11:04:34 +02:00
meehl d43a1cf392 Hash draw commands directly from their byte representation 2026-08-18 10:58:06 +02:00
meehl e5bd0157d3 Update dependencies 2026-08-18 09:54:21 +02:00
meehl 43ef18c2e3 Align text with physical pixel grid to reduce blurriness 2026-08-16 11:08:45 +02:00
meehl 4d6c258932 Major renderer refactor
Replace old per-mesh bind group model with a better batching schema
built around wgpu's TEXTURE_BINDING_ARRAY support. Each batch now
holds multiple textures. Vertex and index buffers are now only set once
per frame. Massively improves rendering performance.
2026-08-16 01:25:22 +02:00
meehl 3fc87339ca Refactor draw command recording.
Remove distinct draw primitives and unify them into one shared form.
2026-08-15 19:19:55 +02:00
meehl a6d18a320c Fix comment 2026-08-15 19:19:34 +02:00
meehl e20a28fef7 Use layered font atlas.
Add layers instead of growing in height as more and more glyphs are
added. This allows us to return normalized UV coordinates since the
dimensions of each layer stay the same.
2026-08-15 15:49:25 +02:00
meehl b48edb72e1 Clean up return values of some API functions 2026-08-12 21:05:34 +02:00
meehl e43da1b9e8 Lint 2026-08-12 20:46:43 +02:00
meehl 99fc9f608e Improve performance of image handle access in API draw calls.
Use raw Lua C API to store image handles in Lua userdata instead
of using `mlua::UserData`. `mlua` wraps UserData in a special way
to maintain Rust safety guarantees which prevents direct access
of the underlying data from a raw Lua state.
The `DrawImage` and `DrawImageQuad` API calls used a workaround to
access the underlying image handle before which added significant
overhead. The overhead is eliminated by manually constructing the
userdata metatable for `ImageHandle` at the cost of weaker safety
guarantees.
2026-08-12 18:03:41 +02:00
meehl c1d91768bb Improve parsing of color escapes 2026-08-12 14:37:01 +02:00
meehl 4c581f92a8 Fix color escape regex 2026-08-12 14:10:00 +02:00
meehl a2afd2de54 Upgrade parley to v0.11 2026-08-11 23:17:58 +02:00
meehl a1cea10218 Upgrade wgpu to v30 2026-08-11 20:30:21 +02:00
meehl cee6f848ea Upgrade dds to v0.2 2026-08-11 19:26:24 +02:00
meehl 5c44328e16 Upgrade mlua to v0.12.0 2026-08-11 17:37:53 +02:00
meehl 6b6098d331 chore: Release rusty-path-of-building version 0.2.18
Release / create-release (push) Successful in 8s
2026-05-29 15:09:23 +02:00
meehl 69d70e4712 Update CHANGELOG 2026-05-29 15:08:27 +02:00
meehl 32fd954952 Raise max_texture_array_layers requirement to support new gem tooltips 2026-05-29 15:02:35 +02:00
Aleksandr Timofeev 40ea4445cd Fix doubleclick handling (#49) 2026-05-24 21:11:19 +02:00
meehl 3ca5f984de chore: Release rusty-path-of-building version 0.2.17
Release / create-release (push) Successful in 8s
2026-05-24 09:29:31 +02:00
meehl 6dbf6c0e3c Update CHANGELOG 2026-05-24 09:29:09 +02:00
meehl 6a05d86801 Adjust index to account for color escape sequences
get_text_index_at_cursor() returns an index into the stripped string,
but PoB expects an index into the original unstripped text. Accumulate
the total length of all escape sequences preceding the cursor position
and add it to the returned index.

Fixes #45
2026-05-14 10:42:26 +02:00
meehl 068dfce7ca Use correct font names to register generic font families
Fixes #48
2026-05-13 15:37:54 +02:00
Game Monster 28a9089443 Add macOS development setup guide to CONTRIBUTING 2026-04-08 15:23:38 +02:00
Game Monster e42776a2c8 Improve macOS compatibility
Enables wgpu's metal backend and restricts usage of smithay-clipboard, which provides access to the Wayland clipboard, to linux systems.
2026-04-08 14:48:21 +02:00
meehl c8bda4b76f chore: Release rusty-path-of-building version 0.2.16
Release / create-release (push) Successful in 4s
2026-03-23 08:54:23 +01:00
meehl fe10962c4b Update CHANGELOG 2026-03-23 08:53:54 +01:00
meehl 4dc8db6921 Fix tar extraction 2026-03-23 08:49:59 +01:00
meehl 716add6d76 chore: Release rusty-path-of-building version 0.2.15
Release / create-release (push) Successful in 7s
2026-03-22 22:53:27 +01:00
meehl 98af75c725 Update CHANGELOG 2026-03-22 22:52:54 +01:00
meehl 88bd3fa403 Installer refactor
Uses reqwest instead of ureq for better IPv6 handling.
2026-03-22 22:45:48 +01:00
meehl b16f7f528d chore: cargo update and bump fast_image_resize to v6.0.0 2026-03-22 10:22:45 +01:00
meehl e2c0f2fffc chore: Release rusty-path-of-building version 0.2.14
Release / create-release (push) Successful in 6s
2026-03-14 10:35:33 +01:00
meehl a6be413190 Update CHANGELOG 2026-03-14 10:35:21 +01:00
AiSatan 8034eef8c7 fix removing build directory 2026-03-11 16:48:11 +01:00
meehl 3b0d5295d3 installer: only install release versions
This prevents the installer from trying to download a beta version which
leads to a 404.
2026-03-10 16:07:54 +01:00
meehl ff46a570fc chore: Release rusty-path-of-building version 0.2.13
Release / create-release (push) Successful in 4s
2026-03-09 18:17:47 +01:00
meehl 7db64e337d Update CHANGELOG 2026-03-09 18:17:33 +01:00
meehl 522ab489cd Fix ascendancy flavour text size. 2026-03-09 18:13:58 +01:00
meehl 8217aca6f2 chore: Release rusty-path-of-building version 0.2.12
Release / create-release (push) Successful in 4s
2026-03-09 16:35:19 +01:00
meehl 249116af52 Update CHANGELOG 2026-03-09 16:35:06 +01:00
meehl c47bf48556 Add more fine-grained logging and UI feedback to installer 2026-03-09 16:30:00 +01:00
meehl 1f89e31f30 Set global timeout for ureq requests 2026-03-09 16:30:00 +01:00
AiSatan 913d2127d8 Fix to enable "Save changes" popup 2026-03-09 14:10:30 +01:00
meehl 1c99e9fabc chore: Release rusty-path-of-building version 0.2.11
Release / create-release (push) Successful in 4s
2026-03-05 08:50:53 +01:00
meehl 12fc773958 Update CHANGELOG 2026-03-05 08:50:34 +01:00
meehl ef4f86eac8 Track state and forward events for logical keys.
Using physical key codes leads to unexpected bevahior on different
keyboard layouts. Use logical keys like SimpleGraphic.

Closes #27
2026-03-05 08:30:56 +01:00
Ac5000 966363a859 Added method to InputState to clear pressed keys, mods, and mouse. Call method on window focus loss. 2026-02-28 10:23:56 +01:00
Ac5000 9d33a7704c Added documentation to src/input.rs 2026-02-28 10:23:56 +01:00
Ac5000 3a66f15b49 Added documentation. 2026-02-28 10:23:56 +01:00
meehl 7d02ca098c Use repology to display packaging status 2025-12-17 12:19:40 +01:00
meehl a858af2c38 chore: Release rusty-path-of-building version 0.2.10
Release / create-release (push) Successful in 4s
2025-12-15 23:20:27 +01:00
meehl 7fc3e340e7 Implement GetDrawColor 2025-12-15 17:56:52 +01:00
meehl dadf5c8804 Remove leftover dbg statement 2025-12-15 17:25:46 +01:00
meehl 031df6ed9c Store script directory in app context
This enables easier testing of the dev branch by providing a custom
script directory. Additionally, a Launch file is now searched for
in nearby locations and if found, used to determine a custom script
directory.
2025-12-15 17:18:56 +01:00
meehl e395e729e8 Add link to nixpkgs 2025-12-05 13:30:23 +01:00
meehl 76b5449bad installer: Write checksum of modified update script to manifest
This prevent having to perform a redundant update on first startup.
2025-12-05 13:03:11 +01:00
meehl f9f05aad08 Fix variable name 2025-12-03 23:09:03 +01:00
meehl 3eacd43837 chore: Release rusty-path-of-building version 0.2.9
Release / create-release (push) Successful in 6s
2025-12-03 16:10:25 +01:00
meehl 523d5ffe29 Update CHANGELOG 2025-12-03 16:09:53 +01:00
meehl e18623edb4 Update README 2025-11-30 11:22:18 +01:00
meehl 1812edcbe9 Implement UI scale overriding
Closes #16
2025-11-30 11:16:04 +01:00
meehl df06c8f9c6 installer: Download highest supported version instead of latest version
Closes #17
2025-11-30 10:05:43 +01:00
meehl ae6a24f82c Reduce CPU usage while window is unfocused and not hovered over
Only render if window is focused, hovered, subscript is running,
or coroutine is active.

Closes #18
2025-11-28 18:30:25 +01:00
meehl 0066a05e13 Register AbortSubscript function under right name 2025-11-27 10:54:43 +01:00
meehl 3d8143c4d1 Add help text to import url argument 2025-11-27 10:54:43 +01:00
meehl a3ef4b39d0 Remove unneeded 'return' statement 2025-11-27 10:54:43 +01:00
meehl f48ab50633 Create CONTRIBUTING.md 2025-11-23 20:51:17 +01:00
meehl b86486d5aa Move config.yml into right directory 2025-11-23 18:05:05 +01:00
meehl 1f1a331cc2 Create config.yml 2025-11-23 18:01:45 +01:00
meehl 27b93c4a9d Update issue templates 2025-11-23 17:48:35 +01:00
meehl c95514036f Fix compiler warning caused by uninitialized variable 2025-11-22 13:48:13 +01:00
meehl 37bc3c5dbb chore: Release rusty-path-of-building version 0.2.8
Release / create-release (push) Successful in 5s
2025-11-07 07:55:07 +01:00
meehl 56155d066a Remove note about clipboard support in known issues section of README 2025-11-07 01:00:06 +01:00
meehl f27e83b467 Use smithay-clipboard crate for clipboard support on Wayland
Fixes #8
2025-11-07 00:59:37 +01:00
meehl 50d4b4b09c Replace non-ASCII characters in text input with '?'
This matches `SimpleGraphics` behavior and prevents a crash that can
happen if PoB tries to delete a non-ASCII character.

Fixes #9.
2025-11-06 16:55:31 +01:00
meehl 51e6881cb0 Simplify input event handling 2025-11-06 16:30:24 +01:00
meehl 8a69d15b49 Set app_id only on platforms that support it.
This fixes a build error on windows.
2025-11-03 13:26:03 +01:00
meehl 3af5e3dccb chore: Release rusty-path-of-building version 0.2.7
Release / create-release (push) Successful in 5s
2025-11-02 17:52:39 +01:00
meehl 76a1b4691d Add missing icon 2025-11-02 17:06:21 +01:00
meehl e877b599c1 Fix UI scaling factor not being applied at startup on X11
On wayland an event it dispatched right after window creation.
 This is not the case on X11 so we need to set it manually.
2025-11-02 15:42:53 +01:00
meehl cc38e31dbb Update known issues section in README 2025-11-02 10:08:44 +01:00
meehl 2739c45181 Use better name for context 2025-11-02 09:53:37 +01:00
meehl 18b05338bf Tweak wording of README 2025-11-02 00:40:33 +01:00
meehl 73ebb1655a Add Flatpak to README
Close #7
2025-11-01 23:40:59 +01:00
meehl 87ff0968d8 Fix missing window title during installation step 2025-10-31 16:39:09 +01:00
108 changed files with 12221 additions and 6411 deletions

No files matched your search

+85
View File
@@ -0,0 +1,85 @@
# Gitea selects .gitea/workflows before .github/workflows. Keep the inherited
# push/PR checks active here; the existing GitHub workflows remain independent.
name: CI
on:
push:
branches: [main]
pull_request:
permissions:
code: read
env:
RUSTUP_TOOLCHAIN: nightly-2026-11-24
jobs:
check:
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- name: Install build dependencies
run: |
set -euo pipefail
sudo_cmd=()
if [ "$(id -u)" -ne 0 ]; then sudo_cmd=(sudo); fi
"${sudo_cmd[@]}" apt-get update
"${sudo_cmd[@]}" apt-get install -y ca-certificates curl build-essential cmake perl nasm pkg-config libcurl4-openssl-dev
- uses: https://github.com/dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc
with:
toolchain: ${{ env.RUSTUP_TOOLCHAIN }}
components: rustfmt, clippy
- name: Format
run: cargo fmt --check
- name: Clippy
run: cargo clippy --locked --all-targets --features vendored-lua -- -D warnings
- name: Test
run: cargo test --locked --features vendored-lua
windows:
if: gitea.event_name == 'push' && gitea.ref == 'refs/heads/main'
runs-on: windows-x64
defaults:
run:
shell: powershell
steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: https://github.com/dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc
with:
toolchain: ${{ env.RUSTUP_TOOLCHAIN }}
targets: x86_64-pc-windows-msvc
- name: Build and verify Windows packages
id: stage
run: |
$dist = Join-Path $env:RUNNER_TEMP ([IO.Path]::GetRandomFileName())
New-Item -ItemType Directory -Path $dist | Out-Null
[IO.File]::AppendAllText($env:GITHUB_OUTPUT, "dist=$dist" + [Environment]::NewLine)
& .\packaging\windows\build.ps1 -OutputDirectory $dist
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
with:
name: windows-packages
path: ${{ steps.stage.outputs.dist }}/*
if-no-files-found: error
compression-level: 0
retention-days: 1
- name: Remove temporary packages
if: always() && steps.stage.outputs.dist != ''
env:
DIST: ${{ steps.stage.outputs.dist }}
run: Remove-Item -LiteralPath $env:DIST -Recurse -Force
+161
View File
@@ -0,0 +1,161 @@
name: Native release
on:
push:
tags: ['v*'] # publish.py enforces exactly vX.Y.Z == Cargo.toml.
# Requires Gitea >=1.26.2; check it before any artifact transfer. Never cancel
# an in-flight publisher. Other publishers for this tag must use the same group.
concurrency:
group: release-${{ gitea.repository }}-${{ gitea.ref }}
cancel-in-progress: false
permissions:
code: read
env:
GITEA_API_URL: ${{ gitea.api_url }}
GITEA_REPOSITORY: ${{ gitea.repository }}
RELEASE_TAG: ${{ gitea.ref_name }}
RELEASE_COMMIT: ${{ gitea.sha }}
RUSTUP_TOOLCHAIN: nightly-2026-11-24
CARGO_INCREMENTAL: '0'
jobs:
linux:
# Host/image prerequisites: Git, Bash, Node 20, Python 3.11+,
# and root or passwordless sudo for the explicit apt packages below.
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
ref: ${{ gitea.sha }}
persist-credentials: false
- name: Check tag, checkout and Gitea prerequisite
run: python3 packaging/publish.py check
- name: Prepare native Linux build
id: stage
run: |
set -euo pipefail
. /etc/os-release
[[ "$ID" == ubuntu && "$VERSION_ID" == 24.04 ]]
test "$(uname -m)" = x86_64
sudo_cmd=()
if [ "$(id -u)" -ne 0 ]; then sudo_cmd=(sudo); fi
"${sudo_cmd[@]}" apt-get update
"${sudo_cmd[@]}" apt-get install -y ca-certificates curl build-essential cmake perl nasm pkg-config libcurl4-openssl-dev dpkg-dev
dist=$(mktemp -d "$RUNNER_TEMP/release-linux.XXXXXXXX")
build=$(mktemp -d "$RUNNER_TEMP/build-linux.XXXXXXXX")
echo "dist=$dist" >> "$GITHUB_OUTPUT"
echo "CARGO_TARGET_DIR=$build" >> "$GITHUB_ENV"
- uses: https://github.com/dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc
with:
toolchain: ${{ env.RUSTUP_TOOLCHAIN }}
targets: x86_64-unknown-linux-gnu
- name: Build and package Linux
env:
DIST: ${{ steps.stage.outputs.dist }}
run: |
set -euo pipefail
cargo build --locked --release --target x86_64-unknown-linux-gnu --features vendored-lua
binary="$CARGO_TARGET_DIR/x86_64-unknown-linux-gnu/release/rusty-path-of-building"
"$binary" --version
python3 packaging/package.py linux "$binary" --output "$DIST"
python3 packaging/publish.py check --assets "$DIST" --platform linux
# Gitea's v4 protocol needs these compatible forks (Gitea 1.22 release notes).
# Runtime artifact credentials are supplied by the runner, not GITEA_TOKEN.
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
with:
name: packages-linux
path: ${{ steps.stage.outputs.dist }}/*
if-no-files-found: error
compression-level: 0
overwrite: true
windows:
# Same MSVC build and packaged-executable checks as the Windows job on main.
runs-on: windows-x64
defaults:
run:
shell: powershell
steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
ref: ${{ gitea.sha }}
persist-credentials: false
- name: Check tag, checkout and Gitea prerequisite
run: |
python packaging/publish.py check
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- uses: https://github.com/dtolnay/rust-toolchain@df2a88e9fe4098bad09cb42c3dec7187f15861fc
with:
toolchain: ${{ env.RUSTUP_TOOLCHAIN }}
targets: x86_64-pc-windows-msvc
- name: Build and package Windows
id: stage
run: |
$ErrorActionPreference = 'Stop'
$dist = Join-Path $env:RUNNER_TEMP ('release-windows-' + [guid]::NewGuid())
New-Item -ItemType Directory -Path $dist | Out-Null
& .\packaging\windows\build.ps1 -OutputDirectory $dist
python packaging/publish.py check --assets $dist --platform windows
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
[IO.File]::AppendAllText($env:GITHUB_OUTPUT, "dist=$dist" + [Environment]::NewLine)
- uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
with:
name: packages-windows
path: ${{ steps.stage.outputs.dist }}/*
if-no-files-found: error
compression-level: 0
overwrite: true
publish:
needs: [linux, windows]
runs-on: ubuntu-latest
permissions:
code: read
releases: write
defaults:
run:
shell: bash
steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
ref: ${{ gitea.sha }}
persist-credentials: false
- name: Check prerequisites and prepare empty download directory
id: stage
run: |
set -euo pipefail
python3 packaging/publish.py check
dist=$(mktemp -d "$RUNNER_TEMP/release-publish.XXXXXXXX")
echo "dist=$dist" >> "$GITHUB_OUTPUT"
- uses: https://github.com/ChristopherHX/gitea-download-artifact@75635f32b4c1c41c4b3d64e8f85210112ed4c9c7 # v4
with:
name: packages-linux
path: ${{ steps.stage.outputs.dist }}
- uses: https://github.com/ChristopherHX/gitea-download-artifact@75635f32b4c1c41c4b3d64e8f85210112ed4c9c7 # v4
with:
name: packages-windows
path: ${{ steps.stage.outputs.dist }}
- name: Publish verified four-attachment release
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
DIST: ${{ steps.stage.outputs.dist }}
run: python3 packaging/publish.py publish --assets "$DIST"
+23
View File
@@ -0,0 +1,23 @@
# 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. Feel free to reach out through [Discussions](https://github.com/meehl/rusty-path-of-building/discussions) if you have any questions.
- Make sure the [API](https://github.com/meehl/rusty-path-of-building/blob/main/src/pob/api.rs) functions stay compatible with [SimpleGraphic](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic) (SG). A great place to ask questions about SG 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.
## Code Ownership and AI-Assisted Contributions
Contributors are responsible for every line of code they submit, regardless of how it was written. Make sure to:
- **Understand your code** - You must be able to explain how your contribution works and why it is implemented the way it is.
- **Review before submitting** - Carefully review all AI-generated code for correctness, security, maintainability, and consistency with the project's conventions.
- **Maintain quality** - AI assistance is not an excuse for untested code, unnecessary complexity, duplicated logic, or careless implementations.
If you cannot confidently explain and verify a piece of code, don't submit it.
+30
View File
@@ -0,0 +1,30 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A description of what you expected to happen.
**System information:**
- OS: [e.g. Linux, Windows, macOS]
- Desktop Environment/Compositor: [e.g. KDE, Gnome, sway, etc.] (only on Linux)
- Rusty Path of Building Version: [e.g. v0.2.8]
- Path of Building Version: [e.g. PoB1 v2.59.0 or PoB2 v0.12.2]
**Additional context**
Add any other context about the problem here. Feel free to add screenshots or any other info like PoB build codes if relevant.
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: yes
contact_links:
- name: GitHub Discussions
url: https://github.com/meehl/rusty-path-of-building/discussions
about: Please ask questions unrelated to actual bugs/issues here.
+31
View File
@@ -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
+2
View File
@@ -1 +1,3 @@
/target/
*.so
*.so.dSYM
+204 -1
View File
@@ -2,6 +2,189 @@
## [Unreleased] - ReleaseDate
## [0.3.7] - 2026-11-27
### Fixed
- The Windows application starts on systems without the Visual C++ Redistributable. Its installer and portable ZIP include any required app-local DLLs.
- Opening the Windows application displays the launcher without opening a console window.
### Added
- The Windows executable and installer use the project icon. Start Menu shortcuts can open Path of Exile 1 or 2 directly.
## [0.3.6] - 2026-11-27
### Added
- Choose Path of Exile 1 or 2 in the launcher when starting without arguments.
- Tagged Gitea releases include Windows x64 setup and ZIP downloads and Linux x64 Debian and tar.gz packages.
## [0.3.5] - 2026-11-20
### Fixed
- Fix a crash when filtering nodes in the Timeless Jewel Finder
## [0.3.4] - 2026-11-13
### Fixed
- Fix blurry text inside viewports with fractional scale factors
- Fix crash on macOS
## [0.3.3] - 2026-10-23
### Fixed
- Fix error in built-in updater with new `bundled-lua-modules` feature
## [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
- Replace `ureq` crate with `reqwest` for better IPv4/IPv6 dual stack support
- Refactor installer
- Bump dependencies
## [0.2.14] - 2026-03-14
### Fixed
- Fix deletion of character build directories
- Prevent installer from downloading beta versions
## [0.2.13] - 2026-03-09
### Fixed
- Fix size of ascendancy flavour texts
## [0.2.12] - 2026-03-09
### Changed
- Add better logging and UI feedback for initial install
- Set global timeout for network requests
### Fixed
- Fix confirmation dialog not showing on close with unsaved changes
## [0.2.11] - 2026-03-05
### Fixed
- Clear pressed keys on focus loss to avoid stuck keys
- Use logical keys for input handling to fix unexpected behavior with different keyboard layouts
## [0.2.10] - 2025-12-15
### Added
- Implement GetDrawColor
### Fixed
- Avoid redundant update after initial download
## [0.2.9] - 2025-12-03
### Added
- Implement UI scale overriding
### Changed
- Reduce CPU usage while window is unfocused and not hovered over
- Download highest compatible PoB version instead of latest version
### Fixed
- Register `AbortSubscript` function under right name
## [0.2.8] - 2025-11-07
### Changed
- Replace non-ASCII characters in text input with '?'
- Use `smithay-clipboard` crate for clipboard support on Wayland
## [0.2.7] - 2025-11-02
### Added
- Add missing window icon. Note for package maintainers: On Wayland, the name of the `.desktop` file entries needs to match RustyPoB's `app_id`. `app_id` is set to either `rusty-path-of-building-1` or `rusty-path-of-building-2`, depending on the game argument.
### Fixed
- Fix missing window title during installation step
- Fix UI scaling factor not being applied at startup on X11
## [0.2.6] - 2025-10-31
### Added
@@ -100,8 +283,28 @@
- First release
<!-- next-url -->
[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.6...HEAD
[Unreleased]: https://git.faumaray.com/faumaray/rusty-path-of-building/compare/v0.3.7...main
[0.3.7]: https://git.faumaray.com/faumaray/rusty-path-of-building/compare/v0.3.6...v0.3.7
[0.3.6]: https://git.faumaray.com/faumaray/rusty-path-of-building/compare/67cc995f786c12a9f81275f01412d2155debfd3e...v0.3.6
[0.3.5]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.4...v0.3.5
[0.3.4]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.3...v0.3.4
[0.3.3]: https://github.com/meehl/rusty-path-of-building/compare/v0.3.2...v0.3.3
[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
[0.2.12]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.11...v0.2.12
[0.2.11]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.10...v0.2.11
[0.2.10]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.9...v0.2.10
[0.2.9]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.8...v0.2.9
[0.2.8]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.7...v0.2.8
[0.2.7]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.6...v0.2.7
[0.2.6]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.5...v0.2.6
[0.2.5]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.4...v0.2.5
[0.2.4]: https://github.com/meehl/rusty-path-of-building/compare/v0.2.3...v0.2.4
Generated
+2316 -1064
View File
File diff suppressed because it is too large. Load diff
+31 -13
View File
@@ -2,43 +2,61 @@
name = "rusty-path-of-building"
authors = ["meehl"]
description = "Cross-platform runtime for Path of Building"
repository = "https://github.com/meehl/rusty-path-of-building"
repository = "https://git.faumaray.com/faumaray/rusty-path-of-building"
license = "MIT"
version = "0.2.6"
version = "0.3.7"
edition = "2024"
publish = false
[dependencies]
ahash = "0.8.12"
anyhow = "1.0"
arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] }
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 = "5.3.0", features = ["image"] }
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"
ureq = "3.1.2"
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(target_os = "linux")'.dependencies]
smithay-clipboard = "0.7.3"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_Console"] }
[build-dependencies]
embed-resource = "=3.0.12"
[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"]
+63 -11
View File
@@ -1,31 +1,80 @@
# Rusty Path of Building
Rusty Path of Building is a cross-platform runtime for [Path of Building](https://github.com/PathOfBuildingCommunity/PathOfBuilding) and [Path of Building 2](https://github.com/PathOfBuildingCommunity/PathOfBuilding-PoE2). Like the [official runtime](https://github.com/PathOfBuildingCommunity/PathOfBuilding-SimpleGraphic), it serves as a host environment for PoB by implementing the API used by the application's Lua logic, as well as rendering, window management, and input handling.
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.
This project was primarily created to allow Path of Building to run natively on Linux. It is written in Rust (in case you couldn't already tell from the unimaginative name) and should run on all platforms, though only Linux has been tested so far.
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
Open **Rusty Path of Building** from the applications menu, double-click the executable, or run it without arguments. Choose **Path of Exile 1** or **Path of Exile 2**. The first launch of each game downloads its Path of Building files into your user data directory.
To open a specific game directly or pass a build URL, use the command line.
```bash
rusty-path-of-building [poe1|poe2]
rusty-path-of-building
rusty-path-of-building poe1
rusty-path-of-building poe2 'pob://pobbin/<id>'
```
## Installation
### Arch (AUR)
Download the x64 package for your system from the [Gitea releases page](https://git.faumaray.com/faumaray/rusty-path-of-building/releases).
[![Stable version badge](https://img.shields.io/aur/version/rusty-path-of-building?style=flat&label=rusty-path-of-building)](https://aur.archlinux.org/packages/rusty-path-of-building)
| System | Installer | Archive |
| --- | --- | --- |
| Windows | Run the setup EXE. In Start, **Rusty Path of Building** opens the chooser. **Rusty Path of Building - PoE 1** and **Rusty Path of Building - PoE 2** open their game directly. | Extract the whole ZIP into one folder and run `rusty-path-of-building.exe`. |
| Linux | On a compatible Debian or Ubuntu system, run `sudo apt install ./rusty-path-of-building_<version>_amd64.deb`, substituting the downloaded filename. | Extract the tar.gz and run the included `rusty-path-of-building` executable. |
Please check [the Arch Wiki](https://wiki.archlinux.org/title/Arch_User_Repository) on how to install packages from the AUR.
Both games use the existing Vulkan renderer on Windows and Linux. You need a compatible graphics driver. Game downloads and saved builds live in separate per-game directories under your account.
The Linux release is built on Ubuntu 24.04. The tarball requires glibc 2.39 or newer, libcurl, Vulkan, and the X11 or Wayland client libraries. Installing the Debian package through APT resolves its library dependencies.
[![Packaging status](https://repology.org/badge/vertical-allrepos/rusty-path-of-building.svg)](https://repology.org/project/rusty-path-of-building/versions)
### Flathub
[![Stable version badge](https://img.shields.io/flathub/v/community.pathofbuilding.PathOfBuilding)](https://flathub.org/en/apps/community.pathofbuilding.PathOfBuilding)
### Homebrew
[Homebrew Tap](https://github.com/meehl/homebrew-rusty-path-of-building) (NOTE: This has been tested on macOS only)
### Building from source
`LuaJIT` needs to be installed on your system for the `mlua` crate to compile.
```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.
### Creating release packages
The packager reads the version from `Cargo.toml` and writes to `target/dist/`. It takes a built executable as input. Python 3.11 or newer is required on both platforms.
**Windows x64.** The Windows release links the Microsoft C runtime statically. Both the installer and portable ZIP include any additional DLLs the application needs alongside its executable.
For the build machine, install the Visual Studio C++ x64 build tools with the Windows SDK, Git, Rust via rustup, Python 3.11+ with pip, and NSIS 3. The Gitea runner also needs Node for its Actions. From the repository root in x64 PowerShell, use the same build script as CI.
```powershell
$env:RUSTUP_TOOLCHAIN = 'nightly-2026-11-24'
rustup toolchain install $env:RUSTUP_TOOLCHAIN --profile minimal --target x86_64-pc-windows-msvc
powershell -NoProfile -File .\packaging\windows\build.ps1
```
The script builds both packages in `target/dist/` and checks the extracted program's CLI output, GUI subsystem and icon. It resolves app-local DLLs alongside the input executable and in explicitly supplied directories. When packaging a custom build, pass its dependency folder with `-DllDirectory`. The installer uses the current user's account and uninstalling preserves saved builds.
**Linux x64.** On Ubuntu 24.04, install the C build tools, `pkg-config`, `libcurl4-openssl-dev`, and `dpkg-dev`. Build the executable and package it with the following commands.
```sh
cargo build --locked --release --target x86_64-unknown-linux-gnu --features vendored-lua
python3 packaging/package.py linux target/x86_64-unknown-linux-gnu/release/rusty-path-of-building
```
**Gitea releases.** A new `vX.Y.Z` tag matching the version in `Cargo.toml` triggers the release workflow. It builds on the `windows-x64` and `ubuntu-latest` runners, gathers the four packages and verifies their SHA-256 hashes before publishing. Use a native Windows x64 runner with the build tools above and an Ubuntu 24.04 x64 runner with APT access. Both runners need Git, a Node runtime for the checkout and artifact actions, and Python 3.11+. The repository's Actions job token needs read access to code and write access to releases.
## Runtime Dependencies
Path of Building's Lua code requires the following C libraries:
@@ -33,10 +82,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
- The clipboard doesn't work with Wayland compositors that don't support the data-control extension(s). It is recommended to fall back to `Xwayland` in these cases. This can be done by unsetting `WAYLAND_DISPLAY`. More info here: https://github.com/1Password/arboard?tab=readme-ov-file#backend-support
- 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.
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

+1
View File
@@ -0,0 +1 @@
1 ICON "assets/icon.ico"
+11
View File
@@ -0,0 +1,11 @@
fn main() {
println!("cargo:rerun-if-changed=assets/windows.rc");
println!("cargo:rerun-if-changed=assets/icon.ico");
// Check the target rather than the host so cross builds also receive the icon.
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
embed_resource::compile("assets/windows.rc", embed_resource::NONE)
.manifest_required()
.expect("failed to embed the Windows application icon");
}
}
-75
View File
@@ -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)
-735
View File
@@ -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;
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;
}
+53
View File
@@ -0,0 +1,53 @@
"""Check the packaged Windows executable on the native runner."""
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import tomllib
import zipfile
import pefile
from windows_deps import resolve_dependencies
def check_package(directory):
with (Path(__file__).resolve().parents[1] / "Cargo.toml").open("rb") as stream:
package = tomllib.load(stream)["package"]
name, version = package["name"], package["version"]
with tempfile.TemporaryDirectory() as temp:
unpacked = Path(temp) / "portable"
with zipfile.ZipFile(directory / f"{name}-{version}-windows-x86_64.zip") as archive:
archive.extractall(unpacked)
exe = unpacked / f"{name}.exe"
# Verify closure using only files that made it into the ZIP. A globally
# installed DLL on the build machine could otherwise mask an omission.
resolve_dependencies(exe, require_static_crt=True)
with pefile.PE(str(exe), fast_load=True) as pe:
if pe.OPTIONAL_HEADER.Subsystem != pefile.SUBSYSTEM_TYPE["IMAGE_SUBSYSTEM_WINDOWS_GUI"]:
raise ValueError("The packaged executable opens a console window")
pe.parse_data_directories([pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_RESOURCE"]])
resources = {entry.id for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries}
if not {pefile.RESOURCE_TYPE["RT_ICON"], pefile.RESOURCE_TYPE["RT_GROUP_ICON"]} <= resources:
raise ValueError("The packaged executable is missing its application icon")
windows = Path(os.environ["SystemRoot"])
env = {**os.environ, "PATH": os.pathsep.join(map(str, (windows / "System32", windows)))}
for argument, code, expected in [
("--version", 0, f"{name} {version}"),
("--help", 0, "poe2"),
("invalid-game", 2, "invalid-game"),
]:
# Exercise both pipes together and each redirected stream independently.
result = subprocess.run([exe, argument], cwd=temp, env=env, text=True, timeout=30,
stdout=subprocess.PIPE if not code else None,
stderr=subprocess.PIPE if argument != "--help" else None)
output = result.stderr if code else result.stdout
if result.returncode != code or expected not in output:
raise ValueError(f"{argument} returned {result.returncode:#x}: {output.strip()}")
print(f"Verified the packaged {name} {version}, its GUI subsystem, icon and CLI output.")
if __name__ == "__main__":
check_package(Path(sys.argv[1]))
@@ -0,0 +1,9 @@
[Desktop Entry]
Type=Application
Name=Rusty Path of Building
Comment=Plan characters for Path of Exile 1 and 2
Exec=rusty-path-of-building
Icon=rusty-path-of-building
Terminal=false
Categories=Game;RolePlaying;
StartupWMClass=rusty-path-of-building
+218
View File
@@ -0,0 +1,218 @@
"""Package a release binary built with the vendored-lua feature."""
import argparse
import os
from pathlib import Path
import shutil
import struct
import subprocess
import sys
import tarfile
import tempfile
import tomllib
import zipfile
ROOT = Path(__file__).resolve().parents[1]
PACKAGE = tomllib.loads((ROOT / "Cargo.toml").read_text(encoding="utf-8"))["package"]
NAME = PACKAGE["name"]
VERSION = PACKAGE["version"]
NOTICES = {
"LICENSE.txt": ROOT / "LICENSE",
"LiberationSans.txt": ROOT / "assets/fonts/LiberationSans License.txt",
"VeraMono.txt": ROOT / "assets/fonts/VeraMono License.txt",
}
def check_binary(binary, platform):
with binary.open("rb") as stream:
header = stream.read(64)
if platform == "linux":
# ELF64, little endian, EM_X86_64.
if header[:6] == b"\x7fELF\x02\x01" and header[18:20] == b"\x3e\x00":
return
elif len(header) == 64 and header[:2] == b"MZ":
stream.seek(struct.unpack_from("<I", header, 60)[0])
if stream.read(6) == b"PE\x00\x00\x64\x86":
return
raise ValueError(f"{binary} is not an x86_64 {platform} executable")
def windows_inventory(payload, include):
from windows_deps import safe_basename
paths = sorted(payload.rglob("*"), key=lambda p: p.relative_to(payload).as_posix().lower())
files, directories, seen = [], [], set()
for path in paths:
relative = path.relative_to(payload)
for part in relative.parts:
safe_basename(part)
key = relative.as_posix().lower()
if key in seen or key == "uninstall.exe":
raise ValueError(f"Conflicting Windows payload filename: {relative}")
seen.add(key)
if path.is_symlink():
raise ValueError(f"Symlink in Windows payload: {relative}")
if path.is_dir():
directories.append(relative)
elif path.is_file():
files.append(relative)
else:
raise ValueError(f"Not a regular payload file: {relative}")
install = ["!macro InstallPayload"]
previous = None
for path in files:
parent = "\\".join(path.parts[:-1])
destination = "$INSTDIR" + ("\\" + parent if parent else "")
if destination != previous:
install.append(f' SetOutPath "{destination}"')
previous = destination
source = "\\".join(path.parts)
install.append(f' File "payload\\{source}"')
install.extend([' SetOutPath "$INSTDIR"', "!macroend", "", "!macro UninstallPayload"])
for path in files:
name = "\\".join(path.parts)
install.append(f' Delete "$INSTDIR\\{name}"')
for path in sorted(directories, key=lambda p: (-len(p.parts), p.as_posix().lower())):
name = "\\".join(path.parts)
install.append(f' RMDir "$INSTDIR\\{name}"')
install.append("!macroend")
include.write_text("\n".join(install) + "\n", encoding="utf-8")
return files
def package_windows(binary, work, dll_dirs=(), require_static_crt=False):
from windows_deps import resolve_dependencies, safe_basename
safe_basename(NAME)
safe_basename(VERSION)
dependencies = resolve_dependencies(binary, dll_dirs, require_static_crt)
stem = f"{NAME}-{VERSION}-windows-x86_64"
payload = work / "payload"
(payload / "licenses").mkdir(parents=True)
shutil.copyfile(binary, payload / f"{NAME}.exe")
for name, source in dependencies.items():
shutil.copyfile(source, payload / name)
for name, source in NOTICES.items():
shutil.copyfile(source, payload / "licenses" / name)
# Freeze one validated inventory for the archive and both NSIS macros.
inventory = windows_inventory(payload, work / "payload-files.nsh")
archive = work / f"{stem}.zip"
with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as bundle:
for relative in inventory:
bundle.write(payload / relative, relative.as_posix())
makensis = shutil.which("makensis")
if not makensis and os.name == "nt":
for key in ("ProgramFiles(x86)", "ProgramFiles"):
if key in os.environ:
candidate = Path(os.environ[key]) / "NSIS" / "makensis.exe"
if candidate.is_file():
makensis = str(candidate)
break
if not makensis:
raise ValueError("Install NSIS 3 and make makensis available")
shutil.copyfile(ROOT / "packaging/windows/installer.nsi", work / "installer.nsi")
shutil.copyfile(ROOT / "assets/icon.ico", work / "app.ico")
define = "/D" if os.name == "nt" else "-D"
installer = work / f"{stem}-setup.exe"
subprocess.run(
[makensis, f"{define}VERSION={VERSION}", f"{define}OUTPUT={installer.name}", "installer.nsi"],
cwd=work, check=True,
)
return archive, installer
def package_linux(binary, work):
stem = f"{NAME}-{VERSION}-linux-x86_64"
package = work / "debian" / NAME
executable = package / "usr/bin" / NAME
executable.parent.mkdir(parents=True)
shutil.copyfile(binary, executable)
executable.chmod(0o755)
docs = package / "usr/share/doc" / NAME
docs.mkdir(parents=True)
for name, source in NOTICES.items():
shutil.copyfile(source, docs / ("copyright" if name == "LICENSE.txt" else name))
desktop = package / "usr/share/applications" / f"{NAME}.desktop"
desktop.parent.mkdir(parents=True)
shutil.copyfile(ROOT / "packaging/linux" / desktop.name, desktop)
icon = package / "usr/share/icons/hicolor/256x256/apps" / f"{NAME}.png"
icon.parent.mkdir(parents=True)
shutil.copyfile(ROOT / "assets/icon.png", icon)
# dpkg-shlibdeps reads the build system's package database and requires a source stanza.
(work / "debian/control").write_text(f"Source: {NAME}\n", encoding="utf-8")
control = package / "DEBIAN/control"
control.parent.mkdir()
linked = subprocess.check_output(
["dpkg-shlibdeps", "-O", executable.relative_to(work)], cwd=work, text=True
).strip().removeprefix("shlibs:Depends=")
# winit and wgpu load the window-system and Vulkan libraries at runtime.
extra = ("ca-certificates", "libvulkan1", "libx11-6", "libx11-xcb1", "libxcursor1",
"libxi6", "libxkbcommon0", "libxkbcommon-x11-0", "libwayland-client0",
"libwayland-cursor0")
control.write_text(
f"Package: {NAME}\nVersion: {VERSION}\nArchitecture: amd64\n"
"Section: games\nPriority: optional\n"
"Maintainer: Rusty Path of Building contributors <noreply@git.faumaray.com>\n"
f"Homepage: {PACKAGE['repository']}\n"
f"Depends: {', '.join((linked, *extra))}\n"
"Recommends: mesa-vulkan-drivers | vulkan-icd\n"
f"Description: {PACKAGE['description']}\n"
" Plan characters for Path of Exile 1 and 2.\n",
encoding="utf-8",
)
# The runner's umask must not give package files writable system permissions.
for path in [package, *package.rglob("*")]:
path.chmod(0o755 if path.is_dir() or path == executable else 0o644)
installer = work / f"{NAME}_{VERSION}_amd64.deb"
subprocess.run(["dpkg-deb", "--root-owner-group", "--build", package, installer], check=True)
archive = work / f"{stem}.tar.gz"
with tarfile.open(archive, "w:gz") as bundle:
members = {NAME: executable, **{f"licenses/{key}": value for key, value in NOTICES.items()}}
for name, source in members.items():
entry = bundle.gettarinfo(str(source), arcname=f"{stem}/{name}")
entry.uid = entry.gid = 0
entry.uname = entry.gname = "root"
entry.mode = 0o755 if name == NAME else 0o644
with source.open("rb") as stream:
bundle.addfile(entry, stream)
return archive, installer
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("platform", choices=("windows", "linux"))
parser.add_argument("binary", type=Path)
parser.add_argument("--output", type=Path, default=ROOT / "target/dist")
parser.add_argument("--dll-dir", type=Path, action="append", default=[], metavar="DIR",
help="Windows DLL source directory (repeatable; no PATH search)")
parser.add_argument("--require-static-crt", action="store_true",
help="Reject direct/delay CRT imports in the Windows executable")
args = parser.parse_args()
if args.platform != "windows" and (args.dll_dir or args.require_static_crt):
parser.error("--dll-dir and --require-static-crt apply only to Windows")
binary = args.binary.resolve()
output = args.output.resolve()
check_binary(binary, args.platform)
output.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(dir=output) as temp:
if args.platform == "windows":
artifacts = package_windows(binary, Path(temp), args.dll_dir, args.require_static_crt)
else:
artifacts = package_linux(binary, Path(temp))
for artifact in artifacts:
destination = output / artifact.name
artifact.replace(destination)
print(destination)
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, subprocess.CalledProcessError) as error:
sys.exit(str(error))
+344
View File
@@ -0,0 +1,344 @@
#!/usr/bin/env python3
"""Validate packages and publish a resumable, commit-bound Gitea draft.
Requires Python 3.11+, Git and Gitea >=1.26.2. Run from the tagged checkout.
`check` is read-only; `publish` requires GITEA_TOKEN. Arguments default to the
workflow's GITEA_API_URL, GITEA_REPOSITORY, RELEASE_TAG and RELEASE_COMMIT env.
Serialize invocations for the same repository/tag (the workflow does this).
HTTP is accepted only for loopback fixtures. API redirects are never followed;
attachment redirects receive credentials only while they stay on the API origin.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import tomllib
import urllib.error
import urllib.parse
import urllib.request
import uuid
NAME = "rusty-path-of-building"
VERSION = r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)"
CHUNK = 1024 * 1024
class ReleaseError(Exception):
"""A conflict or failed prerequisite; leave the release for inspection/retry."""
def require(condition, message):
if not condition:
raise ReleaseError(message)
def expected_names(version, platform="all"):
names = {
"windows": [f"{NAME}-{version}-windows-x86_64.zip",
f"{NAME}-{version}-windows-x86_64-setup.exe"],
"linux": [f"{NAME}-{version}-linux-x86_64.tar.gz",
f"{NAME}_{version}_amd64.deb"],
}
return names[platform] if platform != "all" else names["windows"] + names["linux"]
def fingerprint(stream, limit=None):
digest = hashlib.sha256()
size = 0
while chunk := stream.read(CHUNK):
size += len(chunk)
require(limit is None or size <= limit, "Attachment exceeds expected size")
digest.update(chunk)
return size, digest.hexdigest()
def local_assets(directory, names):
require(directory.is_dir() and not directory.is_symlink(), "Asset directory is missing or a symlink")
require({p.name for p in directory.iterdir()} == set(names),
"Asset directory must contain exactly the expected filenames: " + ", ".join(names))
result = {}
for name in names:
path = directory / name
require(path.is_file() and not path.is_symlink(), f"Not a regular asset: {name}")
with path.open("rb") as stream:
size, digest = fingerprint(stream)
require(size > 0, f"Empty asset: {name}")
result[name] = (path, size, digest)
return result
def local_identity(source, tag, revision):
require(re.fullmatch("v" + VERSION, tag or ""), "Tag must be exactly vX.Y.Z")
with (source / "Cargo.toml").open("rb") as stream:
package = tomllib.load(stream)["package"]
require(package["name"] == NAME, "Unexpected Cargo package name")
require(tag == "v" + package["version"], "Tag does not match Cargo.toml version")
require(re.fullmatch(r"(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})", revision or ""),
"Supply the full event commit/object SHA with --commit or RELEASE_COMMIT")
def resolve(ref):
completed = subprocess.run(["git", "-C", str(source), "rev-parse", "--verify", ref],
capture_output=True, text=True)
require(completed.returncode == 0, "Cannot resolve checkout/event commit")
return completed.stdout.strip().lower()
commit = resolve("HEAD^{commit}")
require(commit == resolve(revision + "^{commit}"), "Checkout differs from event commit")
return package["version"], commit
def checked_url(url):
parsed = urllib.parse.urlsplit(url)
require(parsed.scheme == "https" or
(parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"}),
"Use HTTPS (HTTP is allowed only for a loopback fixture)")
require(parsed.hostname and not parsed.username and not parsed.password and not parsed.fragment,
"Invalid URL or embedded URL credentials")
return parsed
def origin(url):
parsed = checked_url(url)
return parsed.scheme, parsed.hostname, parsed.port or (443 if parsed.scheme == "https" else 80)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
class Gitea:
def __init__(self, api_url, token=""):
self.api_url = api_url.rstrip("/")
parsed = checked_url(self.api_url)
require(parsed.path.endswith("/api/v1") and not parsed.query, "API URL must end in /api/v1")
self.token = token
self.opener = urllib.request.build_opener(NoRedirect())
def open(self, method, url, data=None, headers=None, authenticated=True):
checked_url(url)
headers = {"User-Agent": NAME + "-release", **(headers or {})}
if authenticated and self.token:
require(origin(url) == origin(self.api_url), "Refusing cross-origin credentials")
headers["Authorization"] = "token " + self.token
return self.opener.open(urllib.request.Request(url, data=data, headers=headers, method=method),
timeout=120)
def request(self, method, path, body=None, missing_ok=False, data=None, headers=None):
headers = {"Accept": "application/json", **(headers or {})}
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
try:
with self.open(method, self.api_url + path, data, headers) as response:
payload = response.read()
return json.loads(payload) if payload else None
except urllib.error.HTTPError as error:
error.close()
if error.code == 404 and missing_ok:
return None
# Never echo response bodies, signed redirect URLs or headers containing credentials.
raise ReleaseError(f"Gitea {method} request failed (HTTP {error.code})") from None
def check_version(self):
version = self.request("GET", "/version").get("version", "")
match = re.fullmatch(r"v?(\d+)\.(\d+)\.(\d+)(?:\+[0-9A-Za-z.-]+)?", version)
require(match and tuple(map(int, match.groups())) >= (1, 26, 2),
"Gitea >=1.26.2 stable is required for release concurrency/artifact safety")
return version
def download_fingerprint(self, url, size):
# A storage redirect may carry its own signed query, but never our token.
authenticated = origin(url) == origin(self.api_url)
for _ in range(6):
try:
with self.open("GET", url, authenticated=authenticated) as response:
return fingerprint(response, limit=size)
except urllib.error.HTTPError as error:
location = error.headers.get("Location")
code = error.code
error.close()
if code not in {301, 302, 303, 307, 308} or not location:
raise ReleaseError(f"Attachment download failed (HTTP {code})") from None
next_url = urllib.parse.urljoin(url, location)
require(not (checked_url(url).scheme == "https" and checked_url(next_url).scheme != "https"),
"Refusing attachment HTTPS downgrade")
authenticated = authenticated and origin(next_url) == origin(self.api_url)
url = next_url
raise ReleaseError("Too many attachment redirects")
def upload(self, path, asset):
filename, size, _ = asset
boundary = "release-" + uuid.uuid4().hex
prefix = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; '
f'filename="{filename.name}"\r\nContent-Type: application/octet-stream\r\n\r\n').encode()
suffix = f"\r\n--{boundary}--\r\n".encode()
def chunks():
yield prefix
with filename.open("rb") as stream:
while chunk := stream.read(CHUNK):
yield chunk
yield suffix
return self.request("POST", path, data=chunks(), headers={
"Content-Type": f"multipart/form-data; boundary={boundary}",
"Content-Length": str(len(prefix) + size + len(suffix)),
})
def release_notes(source, version):
changelog = source / "CHANGELOG.md"
if not changelog.is_file():
return f"Release v{version}"
text = changelog.read_text(encoding="utf-8")
match = re.search(r"^## \[" + re.escape(version) + r"\][^\n]*\n(.*?)(?=^## \[|\Z)",
text, re.MULTILINE | re.DOTALL)
return match.group(1).strip() if match else f"Release v{version}"
class Publisher:
def __init__(self, api, repository, tag, commit, assets):
require(re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository or ""),
"Repository must be owner/name")
require(all(part not in {".", ".."} for part in repository.split("/")), "Invalid repository")
self.api, self.tag, self.commit, self.assets = api, tag, commit, assets
self.base = "/repos/" + repository
self.marker = f"<!-- {NAME}:gitea-release:v1 commit={commit} -->"
def check_tag(self):
tag = self.api.request("GET", self.base + "/tags/" + self.tag)
require(tag.get("name") == self.tag and tag.get("commit", {}).get("sha") == self.commit,
"Live tag does not point to the checked-out commit")
def release(self):
return self.api.request("GET", self.base + "/releases/tags/" + self.tag, missing_ok=True)
def inspect(self, release):
require(release and release.get("tag_name") == self.tag and
release.get("target_commitish") == self.commit and
release.get("body", "").splitlines().count(self.marker) == 1 and
release.get("prerelease") is False and type(release.get("draft")) is bool,
"Release is not an owned, commit-matching stable release; refusing changes")
require(type(release.get("id")) is int and release["id"] > 0, "Invalid release ID")
attachments = self.api.request("GET", self.base + f'/releases/{release["id"]}/assets')
indexed = {}
for attachment in attachments:
name = attachment.get("name")
require(name in self.assets and name not in indexed, "Unexpected or duplicate release attachment")
require(type(attachment.get("id")) is int and attachment["id"] > 0 and
type(attachment.get("size")) is int and attachment["size"] >= 0,
"Invalid attachment metadata")
# Download counters change during our own hash verification.
indexed[name] = {key: attachment[key] for key in
("id", "name", "size", "browser_download_url")}
return indexed
def matches(self, attachment, asset):
_, size, digest = asset
if attachment["size"] != size:
return False
return self.api.download_fingerprint(attachment["browser_download_url"], size) == (size, digest)
def verify_complete(self, attachments):
require(set(attachments) == set(self.assets), "Release does not have exactly four expected attachments")
for name, asset in self.assets.items():
require(self.matches(attachments[name], asset), f"Release attachment differs: {name}")
def guard_draft(self, release_id):
release = self.release()
attachments = self.inspect(release)
require(release["id"] == release_id and release["draft"], "Draft changed or became public; refusing mutation")
self.check_tag()
return attachments
def publish(self, notes):
self.check_tag()
release = self.release()
if release is None:
self.check_tag()
release = self.api.request("POST", self.base + "/releases", {
"tag_name": self.tag, "target_commitish": self.commit,
"name": self.tag, "body": notes + "\n\n" + self.marker,
"draft": True, "prerelease": False,
})
attachments = self.inspect(release)
if not release["draft"]:
self.verify_complete(attachments)
self.check_tag()
print("Published release already matches all four assets; no changes made.")
return
release_id = release["id"]
path = self.base + f"/releases/{release_id}/assets"
# Plan all conflicts before changing anything. Unknown attachments always fail closed.
replace = [name for name, attachment in attachments.items()
if not self.matches(attachment, self.assets[name])]
for name, asset in self.assets.items():
if name in attachments and name not in replace:
continue
current = self.guard_draft(release_id)
if name in current:
require(name in replace and current[name]["id"] == attachments[name]["id"],
"Attachment changed concurrently; rerun after inspection")
self.api.request("DELETE", path + f'/{current[name]["id"]}')
self.guard_draft(release_id)
self.api.upload(path, asset)
current = self.guard_draft(release_id)
self.verify_complete(current)
# Hashing can take time: check draft status and the live tag again immediately before PATCH.
latest = self.guard_draft(release_id)
require(set(latest) == set(current) and all(
latest[name]["id"] == item["id"] and latest[name]["size"] == item["size"]
for name, item in current.items()
), "Attachments changed during verification")
self.api.request("PATCH", self.base + f"/releases/{release_id}", {"draft": False})
published = self.release()
require(published and published.get("draft") is False, "Publication was not confirmed; rerun safely")
self.verify_complete(self.inspect(published))
self.check_tag()
print("Published release verified: four attachments with matching sizes and SHA-256.")
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["check", "publish"])
parser.add_argument("--source", type=Path, default=Path.cwd(), help="Tagged Git checkout (default: cwd)")
parser.add_argument("--assets", type=Path, help="Directory containing only the expected packages")
parser.add_argument("--platform", choices=["all", "windows", "linux"], default="all", help="check only")
parser.add_argument("--tag", default=os.environ.get("RELEASE_TAG"))
parser.add_argument("--commit", default=os.environ.get("RELEASE_COMMIT"), help="Full event SHA; peeled before comparison")
parser.add_argument("--repository", default=os.environ.get("GITEA_REPOSITORY"))
parser.add_argument("--api-url", default=os.environ.get("GITEA_API_URL"), help="Gitea API base, ending /api/v1")
args = parser.parse_args(argv)
try:
version, commit = local_identity(args.source, args.tag, args.commit)
require(args.command != "publish" or (args.assets and args.platform == "all"),
"publish requires --assets with all four packages")
assets = local_assets(args.assets, expected_names(version, args.platform)) if args.assets else None
require(args.api_url, "Supply --api-url or GITEA_API_URL")
token = os.environ.get("GITEA_TOKEN", "") if args.command == "publish" else ""
require(args.command != "publish" or token, "publish requires GITEA_TOKEN")
api = Gitea(args.api_url, token)
server_version = api.check_version()
if args.command == "check":
print(f"Validated {args.tag} at {commit}; Gitea {server_version}; "
f"{len(assets) if assets else 0} assets checked.")
else:
Publisher(api, args.repository, args.tag, commit, assets).publish(release_notes(args.source, version))
return 0
except (ReleaseError, OSError, ValueError, KeyError, TypeError, urllib.error.URLError) as error:
# Network errors can embed signed URLs; report only their type.
message = str(error) if isinstance(error, ReleaseError) else type(error).__name__
print("Release failed: " + message, file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
+44
View File
@@ -0,0 +1,44 @@
param(
[string]$OutputDirectory = (Join-Path $PSScriptRoot '..\..\target\dist'),
[string[]]$DllDirectory = @()
)
$ErrorActionPreference = 'Stop'
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
$destination = [IO.Path]::GetFullPath($OutputDirectory)
$dllDirs = @($DllDirectory | ForEach-Object { (Resolve-Path -LiteralPath $_).Path })
if (-not [Environment]::Is64BitProcess) { throw 'Run this build in x64 PowerShell.' }
$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
$vs = & $vswhere -latest -products '*' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
if ($LASTEXITCODE -ne 0 -or -not $vs) { throw 'Install the Visual Studio C++ x64 build tools and Windows SDK.' }
Import-Module (Join-Path $vs 'Common7\Tools\Microsoft.VisualStudio.DevShell.dll')
Enter-VsDevShell -VsInstallPath $vs -SkipAutomaticLocation -DevCmdArguments '-arch=x64 -host_arch=x64'
# A short, fresh target path keeps link.exe below MAX_PATH on service-account runners.
$work = New-Item -ItemType Directory -Path (Join-Path ([IO.Path]::GetTempPath()) ([IO.Path]::GetRandomFileName()))
Push-Location $repo
try {
$env:CARGO_TARGET_DIR = Join-Path $work.FullName 'b'
# With --target, Cargo applies this to target crates only. The encoded setting
# takes precedence over inherited RUSTFLAGS, including on self-hosted runners.
$env:CARGO_ENCODED_RUSTFLAGS = '-Ctarget-feature=+crt-static'
$env:VCPKGRS_DISABLE = '1'
cargo build --locked --release --target x86_64-pc-windows-msvc --features vendored-lua,curl/static-curl
if ($LASTEXITCODE -ne 0) { throw "Windows build failed ($LASTEXITCODE)." }
$binary = Join-Path $env:CARGO_TARGET_DIR 'x86_64-pc-windows-msvc\release\rusty-path-of-building.exe'
# A third-party DLL can itself use the VC runtime. Use the selected toolset's
# app-local redistributables when needed, even on a host with a global redist.
if ($env:VCToolsRedistDir) {
$x64 = Join-Path $env:VCToolsRedistDir 'x64'
if (Test-Path -LiteralPath $x64) {
$dllDirs += @(Get-ChildItem -LiteralPath $x64 -Directory -Filter 'Microsoft.VC*.CRT' | ForEach-Object { $_.FullName })
}
}
python packaging/windows/package_release.py $work.FullName $binary $destination @dllDirs
if ($LASTEXITCODE -ne 0) { throw "Windows package creation or verification failed ($LASTEXITCODE)." }
} finally {
Pop-Location
Remove-Item -LiteralPath $work.FullName -Recurse -Force -ErrorAction Continue
}
+55
View File
@@ -0,0 +1,55 @@
Unicode true
!define MUI_ICON "app.ico"
!define MUI_UNICON "app.ico"
!include "MUI2.nsh"
!include "payload-files.nsh"
Name "Rusty Path of Building"
OutFile "${OUTPUT}"
RequestExecutionLevel user
InstallDir "$LOCALAPPDATA\Programs\Rusty Path of Building"
SetCompressor /SOLID lzma
!define APP "rusty-path-of-building.exe"
!define UNINSTALL_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\RustyPathOfBuilding"
!insertmacro MUI_PAGE_DIRECTORY
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_UNPAGE_CONFIRM
!insertmacro MUI_UNPAGE_INSTFILES
!insertmacro MUI_LANGUAGE "English"
Function .onInit
SetRegView 64
ReadRegStr $0 HKCU "${UNINSTALL_KEY}" "InstallLocation"
StrCmp $0 "" +2
StrCpy $INSTDIR $0
FunctionEnd
Section "Rusty Path of Building"
SetShellVarContext current
!insertmacro InstallPayload
SetOutPath "$INSTDIR"
WriteUninstaller "$INSTDIR\Uninstall.exe"
CreateShortcut "$SMPROGRAMS\Rusty Path of Building.lnk" "$INSTDIR\${APP}"
CreateShortcut "$SMPROGRAMS\Rusty Path of Building - PoE 1.lnk" "$INSTDIR\${APP}" "poe1"
CreateShortcut "$SMPROGRAMS\Rusty Path of Building - PoE 2.lnk" "$INSTDIR\${APP}" "poe2"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayName" "Rusty Path of Building"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayVersion" "${VERSION}"
WriteRegStr HKCU "${UNINSTALL_KEY}" "DisplayIcon" "$INSTDIR\${APP}"
WriteRegStr HKCU "${UNINSTALL_KEY}" "InstallLocation" "$INSTDIR"
WriteRegStr HKCU "${UNINSTALL_KEY}" "UninstallString" '"$INSTDIR\Uninstall.exe"'
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoModify" 1
WriteRegDWORD HKCU "${UNINSTALL_KEY}" "NoRepair" 1
SectionEnd
Section "Uninstall"
SetRegView 64
SetShellVarContext current
Delete "$SMPROGRAMS\Rusty Path of Building.lnk"
Delete "$SMPROGRAMS\Rusty Path of Building - PoE 1.lnk"
Delete "$SMPROGRAMS\Rusty Path of Building - PoE 2.lnk"
!insertmacro UninstallPayload
Delete "$INSTDIR\Uninstall.exe"
RMDir "$INSTDIR"
DeleteRegKey HKCU "${UNINSTALL_KEY}"
SectionEnd
+28
View File
@@ -0,0 +1,28 @@
"""Build and smoke-test the release packages with an isolated Python interpreter."""
from pathlib import Path
import subprocess
import sys
import venv
def main(work, binary, destination, dll_dirs):
root = Path(__file__).resolve().parents[2]
directory = str(Path(work).resolve() / "py")
builder = venv.EnvBuilder(with_pip=True)
builder.create(directory)
# CPython distributions use different executable names and venv layouts on Windows.
python = builder.ensure_directories(directory).env_exec_cmd
print(f"Packaging with {python} ({sys.platform})", flush=True)
subprocess.run([python, "-m", "pip", "install", "--disable-pip-version-check", "--no-input",
"--require-hashes", "-r", root / "packaging/windows/requirements.txt"], check=True)
args = [python, root / "packaging/package.py", "windows", binary,
"--output", destination, "--require-static-crt"]
for directory in dll_dirs:
args.extend(["--dll-dir", directory])
subprocess.run(args, check=True)
subprocess.run([python, root / "packaging/check_windows_release.py", destination], check=True)
if __name__ == "__main__":
main(*sys.argv[1:4], sys.argv[4:])
+3
View File
@@ -0,0 +1,3 @@
# Windows packaging only; the universal wheel digest is from PyPI.
--only-binary=:all:
pefile==2024.8.26 --hash=sha256:76f8b485dcd3b1bb8166f1128d395fa3d87af26360c2358fb75b80019b957c6f
+202
View File
@@ -0,0 +1,202 @@
"""Resolve the app-local PE dependency closure without consulting PATH or System32."""
from collections import deque
from dataclasses import dataclass
import hashlib
from pathlib import Path
import re
# Windows 10+ supplies these libraries. Redistributables and driver-provided
# libraries deliberately do not belong here. UCRT is an OS component on 10+.
SYSTEM_DLLS = frozenset("""
advapi32.dll avrt.dll bcrypt.dll bcryptprimitives.dll cabinet.dll cfgmgr32.dll
clbcatq.dll comctl32.dll comdlg32.dll combase.dll crypt32.dll cryptbase.dll
cryptnet.dll cryptsp.dll d2d1.dll d3d11.dll d3d12.dll d3d9.dll dcomp.dll
dbghelp.dll dnsapi.dll dwrite.dll dwmapi.dll dxgi.dll gdi32.dll
gdi32full.dll hid.dll imagehlp.dll imm32.dll iphlpapi.dll kernel32.dll
kernelbase.dll mpr.dll msimg32.dll msvcrt.dll mswsock.dll ncrypt.dll
netapi32.dll normaliz.dll nsi.dll ntdll.dll ole32.dll oleacc.dll oleaut32.dll
opengl32.dll powrprof.dll propsys.dll psapi.dll rpcrt4.dll sechost.dll
secur32.dll setupapi.dll shcore.dll shell32.dll shlwapi.dll sspicli.dll
ucrtbase.dll user32.dll userenv.dll usp10.dll uxtheme.dll version.dll
wer.dll windowscodecs.dll winhttp.dll wininet.dll winmm.dll winspool.drv
wintrust.dll wldap32.dll ws2_32.dll wtsapi32.dll
""".split())
API_SET = re.compile(r"(?:api|ext)-ms-[a-z0-9-]+-l\d+-\d+-\d+\.dll\Z")
VC_RUNTIME = re.compile(r"(?:vcruntime|msvcp|msvcr|msvcm|concrt|vcomp|vccorlib)\d[\w]*\.dll\Z")
DEBUG_RUNTIME = re.compile(
r"(?:(?:vcruntime|msvcp|msvcr|msvcm|concrt|vcomp|vccorlib)\d[\w]*d(?:_\w+)?"
r"|mfc(?:m)?\d+u?d|ucrtbased|msvcrtd)\.dll\Z"
)
DEVICE_NAME = re.compile(r"(?:con|prn|aux|nul|com[1-9]|lpt[1-9])\Z", re.I)
def safe_basename(name):
"""Use a portable subset of Windows filenames that is also literal NSIS text."""
if (not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.+ -]{0,254}", name)
or name.endswith((".", " "))
or DEVICE_NAME.fullmatch(name.split(".")[0].rstrip())):
raise ValueError(f"Unsafe Windows/NSIS filename: {name!r}")
return name
def dll_name(value):
name = safe_basename(value.decode("ascii")).lower()
if not name.endswith((".dll", ".drv")):
raise ValueError(f"Expected a DLL basename, got {name!r}")
return name
def dynamic_crt(name):
return (bool(VC_RUNTIME.fullmatch(name)) or name in {"msvcrt.dll", "ucrtbase.dll"}
or name.startswith(("api-ms-win-crt-", "ext-ms-win-crt-")))
@dataclass
class Imports:
libraries: dict[str, set[bytes | int]]
forwarders: dict[bytes | int, tuple[str, bytes | int]]
def descriptor_count(pe, directory, width):
"""pefile can skip unreadable DLL entries. Compare with the on-disk descriptors."""
if not (directory.VirtualAddress or directory.Size):
return 0
if not directory.VirtualAddress or directory.Size < width:
raise ValueError("Truncated PE import directory")
data = pe.get_data(directory.VirtualAddress, directory.Size)
if len(data) != directory.Size:
raise ValueError("Truncated PE import directory")
for offset in range(0, len(data) - width + 1, width):
if not any(data[offset:offset + width]):
return offset // width
raise ValueError("Unterminated PE import directory")
def inspect_pe(path, *, dll=False):
# Linux packaging never imports pefile or needs its wheel installed.
try:
import pefile
except ImportError as error:
raise ValueError("Windows packaging requires: python -m pip install --require-hashes "
"-r packaging/windows/requirements.txt") from error
try:
with pefile.PE(str(path), fast_load=True) as pe:
if pe.FILE_HEADER.Machine != 0x8664 or pe.OPTIONAL_HEADER.Magic != 0x20B:
raise ValueError("Expected an AMD64 PE32+ image")
if not pe.FILE_HEADER.Characteristics & 0x0002:
raise ValueError("PE is not an executable image")
if bool(pe.FILE_HEADER.Characteristics & 0x2000) != dll:
raise ValueError("Expected a DLL image" if dll else "Expected an executable, not a DLL")
directories = pe.OPTIONAL_HEADER.DATA_DIRECTORY
if pe.OPTIONAL_HEADER.NumberOfRvaAndSizes > len(directories):
raise ValueError("Truncated PE data directories")
before = len(pe.get_warnings())
pe.parse_data_directories([0, 1, 13])
# This heuristic says nothing about malformed data; real plugins may
# import only LoadLibrary/GetProcAddress. All parsing warnings fail.
warnings = [w for w in pe.get_warnings()[before:] if w !=
"Imported symbols contain entries typical of packed executables."]
if warnings:
raise ValueError("Malformed PE dependency data: " + "; ".join(warnings))
libraries = {}
for index, width, attr in ((1, 20, "DIRECTORY_ENTRY_IMPORT"),
(13, 32, "DIRECTORY_ENTRY_DELAY_IMPORT")):
if index >= len(directories):
continue
entries = getattr(pe, attr, [])
if len(entries) != descriptor_count(pe, directories[index], width):
raise ValueError(f"Incomplete PE directory {index}: parser skipped descriptors")
for entry in entries:
name = dll_name(entry.dll)
symbols = libraries.setdefault(name, set())
for symbol in entry.imports:
if symbol.import_by_ordinal:
symbols.add(symbol.ordinal)
else:
if not symbol.name or symbol.name == b"*invalid*":
raise ValueError(f"Malformed imported symbol in {name}")
symbols.add(symbol.name)
forwarders = {}
exports = getattr(pe, "DIRECTORY_ENTRY_EXPORT", None)
if directories and directories[0].VirtualAddress and exports is None:
raise ValueError("Unparsed PE export directory")
if exports is not None:
for symbol in exports.symbols:
if symbol.forwarder is None:
continue
forwarder = symbol.forwarder
library, separator, target = forwarder.rpartition(b".")
if not library or not separator or not target:
raise ValueError(f"Malformed forwarded export {forwarder!r}")
name = dll_name(library if library.lower().endswith(b".dll") else library + b".dll")
if target.startswith(b"#"):
if not target[1:].isdigit() or not 0 < int(target[1:]) <= 65535:
raise ValueError(f"Malformed forwarded ordinal {target!r}")
target = int(target[1:])
forwarders[symbol.ordinal] = (name, target)
if symbol.name is not None:
forwarders[symbol.name] = (name, target)
return Imports(libraries, forwarders)
except (pefile.PEFormatError, ValueError, OSError) as error:
raise ValueError(f"{path}: {error}") from error
def resolve_dependencies(binary, dll_dirs=(), require_static_crt=False):
"""Return {Windows basename: source path}, with only imported DLLs selected."""
binary = Path(binary).resolve()
directories = list(dict.fromkeys([binary.parent, *(Path(p).resolve() for p in dll_dirs)]))
candidates = {}
for directory in directories:
if not directory.is_dir():
raise ValueError(f"DLL source is not a directory: {directory}")
for path in sorted(directory.iterdir(), key=lambda p: p.name):
candidates.setdefault(path.name.lower(), []).append(path)
root = inspect_pe(binary)
if require_static_crt:
dynamic = sorted(name for name in root.libraries if dynamic_crt(name) or DEBUG_RUNTIME.fullmatch(name))
if dynamic:
raise ValueError(f"{binary.name}: --require-static-crt rejects dynamic CRT imports: "
+ ", ".join(dynamic))
pending = deque((name, symbols, (binary.name, name)) for name, symbols in sorted(root.libraries.items()))
selected, inspected, visited = {}, {}, {}
while pending:
name, symbols, chain = pending.popleft()
try:
if DEBUG_RUNTIME.fullmatch(name):
raise ValueError(f"Debug VC runtime cannot be redistributed: {name}")
if name in SYSTEM_DLLS or API_SET.fullmatch(name):
continue
if name not in inspected:
paths = candidates.get(name, [])
if not paths:
raise ValueError(f"Missing {name}; supply its redistributable directory with --dll-dir. "
f"Searched: {', '.join(map(str, directories))}")
for path in paths:
if path.is_symlink() or not path.is_file():
raise ValueError(f"DLL source must be a regular, non-symlink file: {path}")
safe_basename(path.name)
if len(paths) > 1:
digests = set()
for path in paths:
with path.open("rb") as stream:
digests.add(hashlib.file_digest(stream, "sha256").digest())
if len(digests) != 1:
raise ValueError(f"Ambiguous differing sources for {name}: {', '.join(map(str, paths))}")
selected[name] = paths[0]
inspected[name] = inspect_pe(paths[0], dll=True)
pending.extend((dependency, requested, (*chain, dependency)) for dependency, requested
in sorted(inspected[name].libraries.items()))
seen = visited.setdefault(name, set())
for symbol in symbols - seen:
forwarded = inspected[name].forwarders.get(symbol)
if forwarded:
dependency, target = forwarded
pending.append((dependency, {target}, (*chain, dependency)))
seen.update(symbols)
except (ValueError, OSError) as error:
raise ValueError(f"{' -> '.join(chain)}: {error}") from error
return dict(sorted(selected.items()))
+2 -2
View File
@@ -1,7 +1,7 @@
pre-release-replacements = [
{file="CHANGELOG.md", search="Unreleased", replace="{{version}}"},
{file="CHANGELOG.md", search="\\.\\.\\.HEAD", replace="...{{tag_name}}", exactly=1},
{file="CHANGELOG.md", search="\\.\\.\\.main", replace="...{{tag_name}}", exactly=1},
{file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}"},
{file="CHANGELOG.md", search="<!-- next-header -->", replace="<!-- next-header -->\n\n## [Unreleased] - ReleaseDate", exactly=1},
{file="CHANGELOG.md", search="<!-- next-url -->", replace="<!-- next-url -->\n[Unreleased]: https://github.com/meehl/rusty-path-of-building/compare/{{tag_name}}...HEAD", exactly=1},
{file="CHANGELOG.md", search="<!-- next-url -->", replace="<!-- next-url -->\n[Unreleased]: https://git.faumaray.com/faumaray/rusty-path-of-building/compare/{{tag_name}}...main", exactly=1},
]
-152
View File
@@ -1,152 +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, 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::ContextSocket,
};
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)?)?;
// 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("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 restart(l: &Lua, _: ()) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
*socket.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 socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
for feature in features {
if feature == "DPI_AWARE" {
*socket.is_dpi_aware() = true;
}
}
Ok(())
}
-44
View File
@@ -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)
}
-20
View File
@@ -1,20 +0,0 @@
use crate::lua::ContextSocket;
use mlua::{Lua, Result as LuaResult};
pub fn copy(l: &Lua, text: String) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
socket
.clipboard()
.set_text(text)
.map_err(|e| anyhow::anyhow!("{}", e))?;
Ok(())
}
pub fn paste(l: &Lua, _: ()) -> LuaResult<String> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
let text = socket
.clipboard()
.get_text()
.map_err(|e| anyhow::anyhow!("{}", e))?;
Ok(text)
}
-50
View File
@@ -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()),
}
}
-97
View File
@@ -1,97 +0,0 @@
use crate::{
lua::ContextSocket,
renderer::textures::{TextureHandle, TextureOptions},
};
use mlua::{Lua, MultiValue, Result as LuaResult, UserData};
pub fn new_image_handle(_: &Lua, _: ()) -> LuaResult<ImageHandle> {
Ok(ImageHandle::Unloaded)
}
#[derive(Clone)]
pub enum ImageHandle {
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 socket = lua.app_data_ref::<&'static ContextSocket>().unwrap();
let mut is_async = false;
let mut options = TextureOptions::LINEAR_REPEAT;
for flag in flags.iter() {
if let Some(flag) = flag.as_string() {
match flag.to_string_lossy().as_str() {
"CLAMP" => options.wrap_mode = wgpu::AddressMode::ClampToEdge,
"NEAREST" => options.magnification = wgpu::FilterMode::Nearest,
"ASYNC" => is_async = true,
"MIPMAP" => options.generate_mipmaps = true,
_ => {}
}
}
}
match handle {
// replace image data if already allocated
ImageHandle::Loaded(texture_handle) => {
// in case of error, stay loaded with current texture
let _ = socket.texture_manager().update_texture(
texture_handle.id(),
image_path,
options,
is_async,
);
}
// create new texture handle
ImageHandle::Unloaded => {
if let Ok(tex_handle) = socket
.texture_manager()
.load_texture(image_path, options, is_async)
{
*handle = ImageHandle::Loaded(tex_handle);
}
}
}
Ok(())
}
-23
View File
@@ -1,23 +0,0 @@
use crate::{
input::{str_as_keycode, str_as_mousebutton},
lua::ContextSocket,
};
use mlua::{Lua, Result as LuaResult};
pub fn get_cursor_pos(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
let pos = socket.input().mouse_pos();
Ok((pos.x as u32, pos.y as u32))
}
pub fn is_key_down(l: &Lua, key_name: String) -> LuaResult<bool> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
if let Some(code) = str_as_keycode(&key_name) {
Ok(socket.input().key_pressed(code))
} else if let Some(button) = str_as_mousebutton(&key_name) {
Ok(socket.input().mouse_pressed(button))
} else {
Ok(false)
}
}
-43
View File
@@ -1,43 +0,0 @@
use crate::{args::Game, util::change_working_directory};
use mlua::{Function, IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
use std::env;
pub fn protected_call(l: &Lua, (func, args): (Function, MultiValue)) -> LuaResult<MultiValue> {
match func.call::<MultiValue>(args) {
// callers expect first return value to be Nil on success
Ok(return_values) => Ok(std::iter::once(Value::Nil).chain(return_values).collect()),
// otherwise it is set to error message.
Err(err) => Ok(err.to_string().into_lua_multi(l)?),
}
}
pub fn load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
let mut module_path = Game::script_dir().join(name);
if module_path.extension().is_none() {
module_path.set_extension("lua");
}
let current_dir = env::current_dir()?;
change_working_directory(Game::script_dir().as_path())?;
let result = l.load(module_path).call::<MultiValue>(args);
change_working_directory(current_dir)?;
result
}
pub fn protected_load_module(l: &Lua, (name, args): (String, MultiValue)) -> LuaResult<MultiValue> {
let mut module_path = Game::script_dir().join(name);
if module_path.extension().is_none() {
module_path.set_extension("lua");
}
let current_dir = env::current_dir()?;
change_working_directory(Game::script_dir().as_path())?;
let result = match l.load(module_path).call::<MultiValue>(args) {
// on success, callers expect a Nil followed by return values
Ok(res) => Ok(std::iter::once(Value::Nil).chain(res).collect()),
// otherwise it is set to error message.
Err(err) => Ok(err.to_string().into_lua_multi(l)?),
};
change_working_directory(current_dir)?;
result
}
-48
View File
@@ -1,48 +0,0 @@
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
use std::{fs, path::PathBuf};
use crate::{
args::Game,
lua::ContextSocket,
util::{change_working_directory, get_executable_dir},
};
pub fn get_user_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
Ok(Game::user_data_dir())
}
// parent directory of Launch.lua script
pub fn get_script_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
Ok(Game::script_dir())
}
// parent directory of executable
pub fn get_runtime_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
match get_executable_dir() {
Ok(exe_path) => Ok(exe_path),
Err(_) => Ok(PathBuf::new()),
}
}
pub fn get_work_dir(l: &Lua, _: ()) -> LuaResult<PathBuf> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
Ok(socket.current_working_dir().to_path_buf())
}
// NOTE: unused
pub fn set_work_dir(l: &Lua, path: String) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
if change_working_directory(&path).is_ok() {
*socket.current_working_dir() = path.into();
}
Ok(())
}
pub fn make_dir(l: &Lua, path: String) -> LuaResult<MultiValue> {
match fs::create_dir_all(path) {
// callers expect first return value to be true on success
Ok(_) => Ok(Value::Boolean(true).into_lua_multi(l)?),
// otherwise it is set to Nil and second return value is set to error msg
Err(err) => Ok((Value::Nil, err.to_string()).into_lua_multi(l)?),
}
}
-688
View File
@@ -1,688 +0,0 @@
use crate::{
api::image_handle::ImageHandle,
color::Srgba,
dpi::Uv,
fonts::{Alignment, FontStyle, LayoutJob},
lua::ContextSocket,
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("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 socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.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);
socket.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);
socket.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);
socket.layers().set_draw_color(color);
}
_ => panic!("Unexpected number of arguments"),
};
0
}
unsafe extern "C-unwind" fn set_viewport(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("set_viewport");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
match nargs {
0 => socket
.layers()
.set_viewport_from_size(socket.window().logical_size()),
4 => {
let x = f32_from_stack!(state, -nargs);
let y = f32_from_stack!(state, -nargs + 1);
let w = f32_from_stack!(state, -nargs + 2);
let h = f32_from_stack!(state, -nargs + 3);
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
socket.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 socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
match nargs {
1 => {
let layer = i32_from_stack!(state, -nargs);
socket.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 {
socket.layers().set_draw_layer(layer, sublayer);
} else {
socket.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 socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
if !matches!(nargs, 5 | 6 | 7 | 9 | 10 | 11) {
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
};
socket.layers().draw_rect(texture_id, rect, uv, layer_idx);
0
}
unsafe extern "C-unwind" fn draw_image_quad(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("draw_image_quad", format!("args: {:?}", args));
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
if !matches!(nargs, 9 | 10 | 11 | 17 | 18 | 19) {
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
};
socket.layers().draw_quad(texture_id, quad, uv, layer_idx);
0
}
unsafe extern "C-unwind" fn draw_string(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("draw_string");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
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 = socket.window().logical_size();
let halign = match alignment {
PoBTextAlignment::Left => Alignment::Min,
PoBTextAlignment::Center => {
position.x += screen_size.width as f32 / 2.0;
is_absolute_position = true;
Alignment::Center
}
PoBTextAlignment::Right => {
position.x = screen_size.width as f32 - position.x;
is_absolute_position = true;
Alignment::Max
}
PoBTextAlignment::CenterX => Alignment::Center,
PoBTextAlignment::RightX => Alignment::Max,
};
let current_draw_color = socket.layers().get_draw_color();
let job = build_layout_job(
text,
current_draw_color,
font_type,
line_height,
Some(halign),
);
// NOTE: color escape codes modify the current draw color.
// set current draw color to color of last segment to match PoB's behavior
if let Some(last_segment) = job.segments.last() {
socket.layers().set_draw_color(last_segment.color);
}
let layout = socket.fonts().layout(job, socket.window().scale_factor);
socket
.layers()
.draw_text(position, layout, is_absolute_position);
0
}
unsafe extern "C-unwind" fn get_string_width(state: *mut ffi::lua_State) -> c_int {
//profiling::scope!("get_string_width");
let lua_instance = unsafe { Lua::get_or_init_from_ptr(state) };
let socket = lua_instance
.app_data_ref::<&'static ContextSocket>()
.unwrap();
let nargs = unsafe { ffi::lua_gettop(state) };
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 = socket
.fonts()
.get_text_width(job, socket.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 socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
let font_type = font_type.parse::<PoBFontType>()?;
let job = build_layout_job(&text, Srgba::WHITE, font_type, line_height, None);
let index = socket.fonts().get_text_index_at_cursor(
job,
Point::new(cur_x, cur_y),
socket.window().scale_factor,
);
// convert to lua's 1-based indexing
Ok(index + 1)
}
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"))
}
};
// TODO: check how PoB determines font size
let font_size = (line_height - 2).clamp(11, 32) as f32;
let mut job = LayoutJob::new(
font_family,
font_size,
line_height as f32,
alignment,
font_weight,
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
}
}
-44
View File
@@ -1,44 +0,0 @@
use crate::{
dpi::{LogicalSize, PhysicalSize},
lua::ContextSocket,
};
use mlua::{Lua, Result as LuaResult};
pub fn get_screen_size(l: &Lua, _: ()) -> LuaResult<(u32, u32)> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
let size = if *socket.is_dpi_aware() {
let PhysicalSize { width, height, .. } = socket.window().size;
(width, height)
} else {
let LogicalSize { width, height, .. } = socket.window().logical_size();
(width, height)
};
Ok(size)
}
pub fn get_screen_scale(l: &Lua, _: ()) -> LuaResult<f32> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
Ok(socket.window().scale_factor)
}
pub fn set_window_title(l: &Lua, title: String) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
socket.window().set_window_title(&title);
Ok(())
}
pub fn set_foreground(l: &Lua, _: ()) -> LuaResult<()> {
let socket = l.app_data_ref::<&'static ContextSocket>().unwrap();
socket.window().focus();
Ok(())
}
pub fn set_dpi_scale_override(_: &Lua, _percent: i32) -> LuaResult<()> {
// TODO:
Ok(())
}
pub fn get_dpi_scale_override(_: &Lua, _: ()) -> LuaResult<i32> {
// TODO:
Ok(0)
}
+342 -189
View File
@@ -1,146 +1,233 @@
use crate::{
dpi::{ConvertToLogical, PhysicalPoint, PhysicalSize},
args::{Args, Game},
batcher::build_render_job,
chooser::Chooser,
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 arboard::Clipboard;
use anyhow::{Context, Result};
use std::sync::Arc;
use std::{cell::RefCell, path::PathBuf, rc::Rc};
use winit::{
application::ApplicationHandler,
event::*,
event::{ElementState, MouseScrollDelta, WindowEvent},
event_loop::ActiveEventLoop,
keyboard::{ModifiersState, PhysicalKey},
platform::modifier_supplement::KeyEventExtModifierSupplement,
window::Window,
};
struct FrameOutput {
pub render_job: RenderJob,
pub render_job: Option<RenderJob>,
pub request_redraw: bool,
}
pub struct AppState {
pub window: WindowState,
pub input: InputState,
pub fonts: Fonts,
pub texture_manager: WrappedTextureManager,
pub clipboard: Clipboard,
}
impl AppState {
fn set_mouse_pos(&mut self, pos: PhysicalPoint<f32>) {
self.input
.set_mouse_pos(pos.to_logical(self.window.scale_factor));
}
struct GameLaunch {
game: Game,
script_dir: PathBuf,
}
pub struct App {
gfx_context: Option<GraphicsContext>,
state: AppState,
tessellator: Tessellator,
force_render: bool,
current_mode: AppMode,
fonts: Rc<RefCell<Fonts>>,
texture_manager: Rc<RefCell<TextureManager>>,
stage: ActiveStage,
launch: Option<GameLaunch>,
custom_script_dir: Option<PathBuf>,
import_url: Option<String>,
pending_transition: Option<StageTransition>,
needs_reconfigure: bool,
stage_changed: bool,
is_focused: bool,
is_hovered: bool,
}
impl App {
pub fn new() -> Result<Self> {
Ok(Self {
pub fn new(args: Args, custom_script_dir: Option<PathBuf>) -> Result<Self> {
let fonts = Rc::new(RefCell::new(Fonts::new(pob_font_definitions())));
let texture_manager = Rc::new(RefCell::new(TextureManager::new()));
let stage = ActiveStage::Chooser(Box::new(Chooser::new(Rc::clone(&fonts))));
let mut app = Self {
gfx_context: None,
state: AppState {
window: WindowState::default(),
input: InputState::default(),
fonts: Fonts::new(pob_font_definitions()),
texture_manager: WrappedTextureManager::new(),
clipboard: arboard::Clipboard::new()?,
},
tessellator: Tessellator::default(),
force_render: false,
current_mode: AppMode::Install(InstallMode::new()),
fonts,
texture_manager,
stage,
launch: None,
custom_script_dir,
import_url: args.import_url,
pending_transition: None,
needs_reconfigure: true,
stage_changed: true,
is_focused: true,
is_hovered: true,
};
if let Some(game) = args.game {
app.start_game(game)?;
}
Ok(app)
}
fn start_game(&mut self, game: Game) -> Result<()> {
anyhow::ensure!(self.launch.is_none(), "A game has already been started");
let launch = GameLaunch {
game,
script_dir: self
.custom_script_dir
.clone()
.unwrap_or_else(|| game.script_dir()),
};
let stage = if self.custom_script_dir.is_some() {
// Local scripts bypass installation, but only after a game is selected.
ActiveStage::Main(self.create_pob(&launch)?)
} else {
ActiveStage::Startup(Installer::new(game, Rc::clone(&self.fonts)))
};
self.launch = Some(launch);
self.set_stage(stage);
Ok(())
}
fn create_pob(&self, launch: &GameLaunch) -> Result<PathOfBuilding> {
PathOfBuilding::new(
&launch.script_dir,
Rc::clone(&self.fonts),
Rc::clone(&self.texture_manager),
self.import_url.clone(),
)
}
fn set_stage(&mut self, stage: ActiveStage) {
self.stage = stage;
if let Some(gfx) = &self.gfx_context {
gfx.window.set_title(self.window_identity().0);
self.stage.set_window(Arc::clone(&gfx.window));
}
self.handle_event(StageEvent::FocusChanged(self.is_focused));
self.handle_event(StageEvent::HoverChanged(self.is_hovered));
self.stage_changed = true;
self.request_redraw();
}
fn update(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> {
let transition = match self.pending_transition.take() {
Some(transition) => Some(transition),
None => self.stage.update()?,
};
if let Some(transition) = transition {
match transition {
StageTransition::StartGame(game) => self.start_game(game)?,
StageTransition::ToMain => {
let launch = self
.launch
.as_ref()
.context("No game selected for Lua startup")?;
let pob = self.create_pob(launch)?;
self.set_stage(ActiveStage::Main(pob));
}
StageTransition::ToShutdown => {
self.handle_event(StageEvent::Exit);
event_loop.exit();
}
}
}
Ok(())
}
fn frame(&mut self, inhibit_elision: bool) -> anyhow::Result<FrameOutput> {
self.fonts.borrow_mut().begin_frame();
let stage_output = self.stage.frame()?;
let font_image_delta = self.fonts.borrow_mut().font_atlas_delta();
self.texture_manager
.borrow()
.update_font_texture(font_image_delta);
let textures_delta = self.texture_manager.borrow().take_delta();
let render_job = if stage_output.can_elide && textures_delta.is_empty() && !inhibit_elision
{
None
} else {
Some(build_render_job(
&stage_output.draw_commands,
textures_delta,
stage_output.scale_factor,
))
};
Ok(FrameOutput {
render_job,
request_redraw: stage_output.request_redraw,
})
}
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 handle_event(&mut self, event: StageEvent) {
match self.stage.handle_event(event) {
Ok(Some(transition)) => {
self.pending_transition.get_or_insert(transition);
}
Ok(None) => {}
Err(err) => log::error!("{err}"),
}
// The chooser sleeps between events, including focus loss and cursor exit.
self.request_redraw();
}
fn window_identity(&self) -> (&'static str, &'static str) {
match self.launch.as_ref().map(|launch| launch.game) {
None => ("Rusty Path of Building", "rusty-path-of-building"),
Some(Game::Poe1) => ("Path of Building 1", "rusty-path-of-building-1"),
Some(Game::Poe2) => ("Path of Building 2", "rusty-path-of-building-2"),
}
}
fn create_window(&mut self, event_loop: &ActiveEventLoop) -> anyhow::Result<()> {
let (title, _app_id) = self.window_identity();
#[allow(unused_mut)]
let mut window_attributes = Window::default_attributes()
.with_title(title)
.with_window_icon(load_icon());
#[cfg(target_os = "linux")]
{
use winit::platform::wayland::ActiveEventLoopExtWayland;
use winit::platform::x11::ActiveEventLoopExtX11;
if event_loop.is_x11() {
use winit::platform::x11::WindowAttributesExtX11;
window_attributes = window_attributes.with_name(_app_id, _app_id);
} else if event_loop.is_wayland() {
use winit::platform::wayland::WindowAttributesExtWayland;
window_attributes = window_attributes.with_name(_app_id, _app_id);
}
}
let window = event_loop.create_window(window_attributes)?;
let window = Arc::new(window);
self.stage.set_window(Arc::clone(&window));
self.gfx_context = Some(pollster::block_on(GraphicsContext::new(window))?);
Ok(())
}
fn frame(&mut self) -> anyhow::Result<FrameOutput> {
self.state.fonts.begin_frame();
let mode_output = self.current_mode.frame(&mut self.state)?;
let font_atlas_size = self.state.fonts.font_atlas().size();
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.state.texture_manager.take_delta();
let render_job = if mode_output.can_elide && textures_delta.is_empty() && !self.force_render
{
RenderJob::Skip
} else {
self.force_render = false;
let meshes = self.tessellator.convert_clipped_primitives(
mode_output.primitives,
font_atlas_size,
self.state.window.scale_factor,
);
RenderJob::Render {
meshes,
textures_delta,
}
};
Ok(FrameOutput { render_job })
}
fn handle_event(&mut self, event: AppEvent) {
if let Err(err) = self.current_mode.handle_event(&mut self.state, event) {
log::error!("{err}");
fn request_redraw(&self) {
if let Some(gfx) = &self.gfx_context {
gfx.window.request_redraw();
}
}
}
impl ApplicationHandler<GraphicsContext> for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
let window = match event_loop.create_window(Window::default_attributes()) {
Ok(window) => Arc::new(window),
Err(err) => {
log::error!("{err}");
event_loop.exit();
return;
}
};
self.state.window.set_window(Arc::clone(&window));
self.gfx_context = match pollster::block_on(GraphicsContext::new(window)) {
Ok(gfx) => Some(gfx),
Err(err) => {
log::error!("{err}");
event_loop.exit();
return;
}
if let Err(err) = self.create_window(event_loop) {
log::error!("{err}");
event_loop.exit();
}
}
@@ -152,20 +239,43 @@ impl ApplicationHandler<GraphicsContext> for App {
) {
match event {
WindowEvent::CloseRequested => {
self.handle_event(AppEvent::Exit);
event_loop.exit();
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 event_loop.exiting() {
return;
}
if let Err(err) = self.update(event_loop) {
log::error!("{err}");
event_loop.exit();
return;
}
if event_loop.exiting() {
return;
}
let render_job = match self.frame() {
Ok(FrameOutput { render_job }) => render_job,
let mut inhibit_elision = std::mem::take(&mut self.stage_changed);
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;
}
let FrameOutput {
render_job,
request_redraw,
} = match self.frame(inhibit_elision) {
Ok(frame_output) => frame_output,
Err(err) => {
log::error!("{err}");
event_loop.exit();
@@ -175,93 +285,84 @@ impl ApplicationHandler<GraphicsContext> for App {
if let Some(ref mut gfx) = self.gfx_context {
match gfx.render(render_job) {
Ok(_) => {}
// Reconfigure the surface if it's lost or outdated
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
let size = gfx.window.inner_size();
gfx.resize(size.width, size.height);
self.force_render = true;
}
Ok(()) => {}
Err(err) => {
log::error!("Unable to render: {err}");
}
}
}
if request_redraw {
self.request_redraw();
}
profiling::finish_frame!();
}
WindowEvent::Resized(size) => {
if let Some(ref mut gfx) = self.gfx_context {
gfx.resize(size.width, size.height);
self.force_render = true;
self.needs_reconfigure = true;
self.handle_event(StageEvent::Resized(PhysicalSize::new(
size.width,
size.height,
)));
}
WindowEvent::Focused(focused) => {
self.is_focused = focused;
self.handle_event(StageEvent::FocusChanged(focused));
if !focused {
// Clear inputs on lost focus to avoid "stuck" keys on Wayland systems.
self.stage.clear_pressed();
}
self.state.window.size = PhysicalSize::new(size.width, size.height);
}
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
self.state.window.scale_factor = scale_factor as f32;
self.handle_event(StageEvent::ScaleFactorChanged(scale_factor));
}
WindowEvent::KeyboardInput {
event:
KeyEvent {
physical_key: PhysicalKey::Code(code),
logical_key,
state,
..
},
..
} => {
self.state.input.set_key_pressed(code, state.is_pressed());
WindowEvent::KeyboardInput { event, .. } => {
let state = event.state;
let event = match state {
ElementState::Pressed => AppEvent::KeyDown { code },
ElementState::Released => AppEvent::KeyUp { code },
// forward KeyUp/KeyDown events
let stage_event = match state {
ElementState::Pressed => StageEvent::KeyDown {
key: event.logical_key.clone(),
},
ElementState::Released => StageEvent::KeyUp {
key: event.logical_key.clone(),
},
};
self.handle_event(event);
self.handle_event(stage_event);
// handle text input
if state.is_pressed() {
match logical_key {
winit::keyboard::Key::Character(text) => {
// only emit event if no modifier except Shift is pressed.
let modifiers = self.state.input.key_modifiers;
if modifiers.difference(ModifiersState::SHIFT).is_empty() {
for ch in text.chars() {
let event = AppEvent::CharacterInput { ch };
self.handle_event(event);
}
}
}
winit::keyboard::Key::Named(named) => {
if named == winit::keyboard::NamedKey::Space {
let event = AppEvent::CharacterInput { ch: ' ' };
self.handle_event(event);
}
}
_ => {}
if let Some(text) = event.text_with_all_modifiers()
&& state.is_pressed()
{
for ch in text.chars() {
let event = StageEvent::CharacterInput { ch };
self.handle_event(event);
}
}
}
WindowEvent::ModifiersChanged(modifiers) => {
self.state.input.key_modifiers = modifiers.state();
self.handle_event(StageEvent::ModifiersChanged {
state: modifiers.state(),
});
}
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);
}
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 });
}
WindowEvent::CursorEntered { .. } => {
self.is_hovered = true;
self.handle_event(StageEvent::HoverChanged(true));
}
WindowEvent::CursorLeft { .. } => {
self.is_hovered = false;
self.handle_event(StageEvent::HoverChanged(false));
}
WindowEvent::MouseWheel { delta, .. } => {
let delta = match delta {
@@ -270,8 +371,7 @@ impl ApplicationHandler<GraphicsContext> for App {
y as f32
}
};
let event = AppEvent::MouseWheel { delta };
self.handle_event(event);
self.handle_event(StageEvent::MouseWheel { delta });
}
_ => {}
}
@@ -284,61 +384,114 @@ 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
}
fn load_icon() -> Option<winit::window::Icon> {
let image_data = include_bytes!("../assets/icon.png");
let image = image::load_from_memory(image_data).ok()?.into_rgba8();
let (width, height) = image.dimensions();
winit::window::Icon::from_rgba(image.into_raw(), width, height).ok()
}
#[cfg(test)]
mod tests {
use super::*;
use winit::keyboard::{Key, NamedKey};
#[test]
fn chooser_defers_custom_scripts_and_allows_cancellation() {
for script_dir in [None, Some(PathBuf::from("missing-launch-script"))] {
let mut app = App::new(
Args {
game: None,
import_url: None,
},
script_dir,
)
.unwrap();
assert!(matches!(app.stage, ActiveStage::Chooser(_)));
assert!(app.launch.is_none());
assert_eq!(
app.window_identity(),
("Rusty Path of Building", "rusty-path-of-building")
);
assert!(app.stage.can_exit());
app.handle_event(StageEvent::KeyDown {
key: Key::Named(NamedKey::Escape),
});
let transition = app
.pending_transition
.take()
.or_else(|| app.stage.update().unwrap());
assert!(matches!(transition, Some(StageTransition::ToShutdown)));
assert!(app.launch.is_none());
}
}
#[test]
fn explicit_games_bypass_selection_and_report_invalid_custom_scripts() {
for game in [Game::Poe1, Game::Poe2] {
assert!(
App::new(
Args {
game: Some(game),
import_url: None
},
Some(PathBuf::from("missing-launch-script")),
)
.is_err()
);
}
}
}
+70 -21
View File
@@ -3,47 +3,96 @@ use clap::ValueEnum;
use directories::BaseDirs;
use std::path::PathBuf;
/// CLI arguments passed to the application.
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
pub struct Args {
/// Which PoB to start. Opens the game chooser when omitted.
#[arg(value_enum)]
pub game: Game,
pub game: Option<Game>,
pub build_path: Option<String>,
/// Specify a build to load on start using a URL. (Optional)
#[arg(
help = "URL of build to import on startup. Needs to use custom protocol schema, e.g. `pob://pobbin/<id>`"
)]
pub import_url: Option<String>,
}
#[derive(Debug, Clone, ValueEnum)]
/// Enum representing the game version.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Game {
/// Path of Exile 1
#[value(name = "poe1")]
Poe1,
/// Path of Exile 2
#[value(name = "poe2")]
Poe2,
}
static GAME_CONFIG: std::sync::OnceLock<Game> = std::sync::OnceLock::new();
impl Game {
pub fn init(game: Game) {
GAME_CONFIG.set(game).expect("Game should be uninitialized");
}
pub fn current() -> &'static Game {
GAME_CONFIG.get().expect("Game should be initialized")
}
pub fn data_dir() -> PathBuf {
let directory_name = match Self::current() {
Game::Poe1 => "RustyPathOfBuilding1",
Game::Poe2 => "RustyPathOfBuilding2",
/// 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 {
Self::Poe1 => "RustyPathOfBuilding1",
Self::Poe2 => "RustyPathOfBuilding2",
};
BaseDirs::new().unwrap().data_dir().join(directory_name)
}
pub fn script_dir() -> PathBuf {
Game::data_dir()
/// Returns the path to the user's data directory.
pub fn script_dir(&self) -> PathBuf {
self.data_dir()
}
}
pub fn user_data_dir() -> PathBuf {
Game::data_dir().join("userdata")
#[cfg(test)]
mod tests {
use super::*;
use clap::error::ErrorKind;
#[test]
fn no_arguments_requests_game_selection() {
let args = Args::try_parse_from(["rpob"]).unwrap();
assert!(args.game.is_none());
assert!(args.import_url.is_none());
}
#[test]
fn explicit_games_accept_an_optional_import_url() {
for game in ["poe1", "poe2"] {
for import_url in [None, Some("pob://pobbin/example")] {
let args =
Args::try_parse_from(["rpob", game].into_iter().chain(import_url)).unwrap();
assert!(matches!(
(game, args.game),
("poe1", Some(Game::Poe1)) | ("poe2", Some(Game::Poe2))
));
assert_eq!(args.import_url.as_deref(), import_url);
}
}
}
#[test]
fn invalid_games_and_url_only_still_fail() {
for game in ["poe3", "pob://pobbin/example"] {
let error = Args::try_parse_from(["rpob", game]).unwrap_err();
assert_eq!(error.kind(), ErrorKind::InvalidValue);
assert_eq!(error.exit_code(), 2);
}
assert!(Args::try_parse_from(["rpob", "poe1", "url", "extra"]).is_err());
}
#[test]
fn help_and_version_keep_successful_cli_exit_codes() {
for (flag, kind) in [
("--help", ErrorKind::DisplayHelp),
("--version", ErrorKind::DisplayVersion),
] {
let error = Args::try_parse_from(["rpob", flag]).unwrap_err();
assert_eq!(error.kind(), kind);
assert_eq!(error.exit_code(), 0);
assert!(!error.use_stderr());
}
}
}
+169
View File
@@ -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,
}
}
+661
View File
@@ -0,0 +1,661 @@
use std::{cell::RefCell, rc::Rc, sync::Arc};
use parley::{FontFamily, FontFamilyName, GenericFamily};
use winit::{keyboard::NamedKey, window::Window};
use crate::{
args::Game,
color::Srgba,
dpi::{LogicalPoint, LogicalRect, LogicalSize, PhysicalPoint},
draw_commands::DrawCommandRecorder,
fonts::{FontStyle, Fonts, LayoutJob},
input::{InputState, Key, MouseButton},
stage::{StageEvent, StageFrameOutput, StageTransition},
window::WindowState,
};
impl Game {
const ALL: [Self; 2] = [Self::Poe1, Self::Poe2];
fn other(self) -> Self {
match self {
Self::Poe1 => Self::Poe2,
Self::Poe2 => Self::Poe1,
}
}
fn label(self) -> &'static str {
match self {
Self::Poe1 => "Path of Exile 1",
Self::Poe2 => "Path of Exile 2",
}
}
}
/// All drawing and hit testing share the same logical coordinates.
struct ChooserLayout {
center_x: f32,
top: f32,
scale: f32,
}
impl ChooserLayout {
fn new(size: LogicalSize<f32>) -> Self {
let scale = (size.width / 520.0).min(size.height / 380.0).min(1.0);
Self {
center_x: size.width / 2.0,
top: (size.height - 324.0 * scale) / 2.0,
scale,
}
}
fn button(&self, choice: Game) -> LogicalRect<f32> {
let offset = match choice {
Game::Poe1 => 96.0,
Game::Poe2 => 184.0,
};
LogicalRect::from_origin_and_size(
LogicalPoint::new(self.center_x - 220.0 * self.scale, self.y(offset)),
LogicalSize::new(440.0 * self.scale, 72.0 * self.scale),
)
}
fn hit_test(&self, pos: LogicalPoint<f32>) -> Option<Game> {
Game::ALL
.into_iter()
.find(|&choice| self.button(choice).contains(pos))
}
fn y(&self, offset: f32) -> f32 {
self.top + offset * self.scale
}
}
pub(crate) struct Chooser {
fonts: Rc<RefCell<Fonts>>,
window_state: WindowState,
input: InputState,
cursor: Option<PhysicalPoint<f32>>,
focused: Game,
hovered: Option<Game>,
mouse_armed: Option<Game>,
key_armed: Option<(Key, Game)>,
pending: Option<StageTransition>,
finished: bool,
previous_frame_hash: Option<u64>,
}
impl Chooser {
pub(crate) fn new(fonts: Rc<RefCell<Fonts>>) -> Self {
Self {
fonts,
window_state: WindowState::default(),
input: InputState::default(),
cursor: None,
focused: Game::Poe1,
hovered: None,
mouse_armed: None,
key_armed: None,
pending: None,
finished: false,
previous_frame_hash: None,
}
}
pub(crate) fn update(&mut self) -> anyhow::Result<Option<StageTransition>> {
Ok(self.pending.take())
}
pub(crate) fn frame(&mut self) -> anyhow::Result<StageFrameOutput> {
let size = self.window_state.logical_size();
let layout = ChooserLayout::new(size);
let mut recorder = DrawCommandRecorder::default();
recorder.reset();
recorder.set_viewport_from_size(size);
// A minimized/zero-sized surface has neither visible content nor hit targets.
if size.width > 0.0 && size.height > 0.0 {
recorder.set_draw_color(Srgba::from_rgb(18, 20, 25));
recorder.draw_image(LogicalRect::from_size(size), None, None, 0);
let gold = Srgba::from_rgb(218, 185, 119);
let muted = Srgba::from_rgb(180, 183, 191);
self.draw_text(
&mut recorder,
"Path of Building",
LogicalPoint::new(layout.center_x, layout.y(0.0)),
34.0 * layout.scale,
gold,
true,
);
self.draw_text(
&mut recorder,
"Choose your game",
LogicalPoint::new(layout.center_x, layout.y(48.0)),
20.0 * layout.scale,
muted,
false,
);
for choice in Game::ALL {
let rect = layout.button(choice);
let focused = self.window_state.is_focused && self.focused == choice;
let hovered = self.hovered == Some(choice);
let pressed = self.mouse_armed == Some(choice)
|| self.key_armed.as_ref().is_some_and(|(_, c)| *c == choice);
recorder.set_draw_color(if focused {
gold
} else if hovered {
Srgba::from_rgb(165, 172, 189)
} else {
Srgba::from_rgb(83, 86, 98)
});
recorder.draw_image(rect, None, None, 0);
recorder.set_draw_color(if pressed {
Srgba::from_rgb(88, 67, 36)
} else if hovered {
Srgba::from_rgb(47, 51, 62)
} else if focused {
Srgba::from_rgb(48, 43, 34)
} else {
Srgba::from_rgb(31, 34, 42)
});
recorder.draw_image(
rect.inflate(-2.0 * layout.scale, -2.0 * layout.scale),
None,
None,
0,
);
self.draw_text(
&mut recorder,
choice.label(),
LogicalPoint::new(layout.center_x, rect.center().y - 17.0 * layout.scale),
28.0 * layout.scale,
Srgba::WHITE,
true,
);
}
for (text, offset) in [
("Tab / arrows to choose Enter / Space to start", 280.0),
("Esc to quit", 304.0),
] {
self.draw_text(
&mut recorder,
text,
LogicalPoint::new(layout.center_x, layout.y(offset)),
15.0 * layout.scale,
muted,
false,
);
}
}
let (hash, layers) = recorder.finish();
let can_elide = self.previous_frame_hash == Some(hash);
self.previous_frame_hash = Some(hash);
Ok(StageFrameOutput {
draw_commands: layers.values().flatten().copied().collect(),
can_elide,
request_redraw: false,
scale_factor: self.window_state.scale_factor(),
})
}
pub(crate) fn handle_event(
&mut self,
event: StageEvent,
) -> anyhow::Result<Option<StageTransition>> {
match event {
StageEvent::Exit
| StageEvent::KeyDown {
key: Key::Named(NamedKey::Escape),
} => {
// Cancellation supersedes a selection not yet consumed by update.
if !self.finished || self.pending.is_some() {
self.pending = Some(StageTransition::ToShutdown);
self.finished = true;
self.clear_pressed();
}
}
StageEvent::Resized(size) => {
self.window_state.size = size;
self.disarm();
}
StageEvent::ScaleFactorChanged(factor) => {
let factor = factor as f32;
if factor.is_finite() && factor > 0.0 {
self.window_state.set_scale_factor(factor);
self.disarm();
}
}
StageEvent::FocusChanged(focused) => {
self.window_state.is_focused = focused;
if !focused {
self.clear_pressed();
}
}
StageEvent::HoverChanged(hovered) => {
self.window_state.is_hovered = hovered;
if !hovered {
self.disarm();
}
}
_ if self.finished || !self.window_state.is_focused => {}
StageEvent::KeyDown { key } => {
if !self.input.key_pressed(&key) {
self.input.set_key_pressed(&key, true);
match key {
Key::Named(
NamedKey::Tab
| NamedKey::ArrowLeft
| NamedKey::ArrowRight
| NamedKey::ArrowUp
| NamedKey::ArrowDown,
) => {
// With two choices, forward and reverse traversal both toggle.
self.focused = self.focused.other();
self.hovered = None;
self.mouse_armed = None;
self.key_armed = None;
}
Key::Named(NamedKey::Enter | NamedKey::Space)
if self.key_armed.is_none() =>
{
self.key_armed = Some((key, self.focused));
self.mouse_armed = None;
self.hovered = None;
}
_ => {}
}
}
}
StageEvent::KeyUp { key } => {
self.input.set_key_pressed(&key, false);
if self
.key_armed
.as_ref()
.is_some_and(|(armed, _)| *armed == key)
{
let (_, choice) = self.key_armed.take().unwrap();
self.select(choice);
}
}
StageEvent::MouseMoved { pos } => {
self.cursor = Some(pos);
self.hovered = self.pointer_target();
if self.mouse_armed != self.hovered {
self.mouse_armed = None;
}
}
StageEvent::MouseDown {
button: MouseButton::Left,
} => {
if !self.input.mouse_pressed(MouseButton::Left) {
self.input.set_mouse_pressed(MouseButton::Left, true);
self.mouse_armed = self.pointer_target();
self.key_armed = None;
self.hovered = self.mouse_armed;
if let Some(choice) = self.mouse_armed {
self.focused = choice;
}
}
}
StageEvent::MouseUp {
button: MouseButton::Left,
} => {
self.input.set_mouse_pressed(MouseButton::Left, false);
if let Some(choice) = self.mouse_armed.take()
&& self.pointer_target() == Some(choice)
{
self.select(choice);
}
}
_ => {}
}
// App advances the queued transition from update, outside event dispatch.
Ok(None)
}
pub(crate) fn set_window(&mut self, window: Arc<Window>) {
self.window_state.set_window(window);
self.previous_frame_hash = None;
self.clear_pressed();
}
pub(crate) fn clear_pressed(&mut self) {
self.input.clear_pressed();
self.disarm();
}
fn disarm(&mut self) {
// Keep held-key/button tracking across pointer exit or layout changes so
// repeats cannot rearm a cancelled press before its matching release.
self.mouse_armed = None;
self.key_armed = None;
self.hovered = None;
self.cursor = None;
}
fn select(&mut self, choice: Game) {
if !self.finished {
self.pending = Some(StageTransition::StartGame(choice));
self.finished = true;
self.clear_pressed();
}
}
fn pointer_target(&self) -> Option<Game> {
if !self.window_state.is_hovered || !self.window_state.is_focused {
return None;
}
let pos = self.cursor? / self.window_state.scale_factor();
ChooserLayout::new(self.window_state.logical_size()).hit_test(pos)
}
fn draw_text(
&self,
recorder: &mut DrawCommandRecorder,
text: &str,
center_top: LogicalPoint<f32>,
size: f32,
color: Srgba,
bold: bool,
) {
let mut job = LayoutJob::new(
FontFamily::Single(FontFamilyName::Generic(GenericFamily::SansSerif)),
size,
size * 1.2,
None,
Some(if bold { 700.0 } else { 400.0 }),
FontStyle::Normal,
);
job.append(text, color);
let scale = self.window_state.scale_factor();
let layout = self.fonts.borrow_mut().layout(job, scale);
let origin = LogicalPoint::new(center_top.x - layout.width() / 2.0, center_top.y);
recorder.draw_glyphs(&layout, origin, true, scale);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
dpi::PhysicalSize,
fonts::{FontData, FontDefinitions},
};
fn chooser() -> Chooser {
let mut definitions = FontDefinitions::default();
definitions.font_data.insert(
"liberation-sans".to_owned(),
Arc::new(FontData::from_static(include_bytes!(
"../assets/fonts/LiberationSans-Regular.ttf"
))),
);
definitions
.generic_families
.insert(GenericFamily::SansSerif, vec!["Liberation Sans".to_owned()]);
let mut chooser = Chooser::new(Rc::new(RefCell::new(Fonts::new(definitions))));
send(
&mut chooser,
StageEvent::Resized(PhysicalSize::new(800, 600)),
);
chooser
}
fn send(chooser: &mut Chooser, event: StageEvent) {
assert!(chooser.handle_event(event).unwrap().is_none());
}
fn key(chooser: &mut Chooser, key: NamedKey, down: bool) {
send(
chooser,
if down {
StageEvent::KeyDown {
key: Key::Named(key),
}
} else {
StageEvent::KeyUp {
key: Key::Named(key),
}
},
);
}
fn move_to(chooser: &mut Chooser, choice: Game) {
let pos = ChooserLayout::new(chooser.window_state.logical_size())
.button(choice)
.center()
* chooser.window_state.scale_factor();
send(chooser, StageEvent::MouseMoved { pos });
}
fn mouse(chooser: &mut Chooser, down: bool) {
send(
chooser,
if down {
StageEvent::MouseDown {
button: MouseButton::Left,
}
} else {
StageEvent::MouseUp {
button: MouseButton::Left,
}
},
);
}
#[test]
fn chooser_keyboard_selects_both_games_once_on_release() {
for (choice, activation) in [(Game::Poe1, NamedKey::Enter), (Game::Poe2, NamedKey::Space)] {
let mut chooser = chooser();
if choice == Game::Poe2 {
key(&mut chooser, NamedKey::Tab, true);
key(&mut chooser, NamedKey::Tab, true); // repeat does not cycle again
key(&mut chooser, NamedKey::Tab, false);
}
key(&mut chooser, activation, true);
key(&mut chooser, activation, true);
assert!(chooser.update().unwrap().is_none());
key(&mut chooser, activation, false);
assert!(matches!(
(choice, chooser.update().unwrap()),
(Game::Poe1, Some(StageTransition::StartGame(Game::Poe1)))
| (Game::Poe2, Some(StageTransition::StartGame(Game::Poe2)))
));
key(&mut chooser, activation, true);
key(&mut chooser, activation, false);
assert!(chooser.update().unwrap().is_none());
}
}
#[test]
fn chooser_arrow_navigation_works_after_hover_and_cursor_departure() {
let mut chooser = chooser();
move_to(&mut chooser, Game::Poe1);
for arrow in [
NamedKey::ArrowRight,
NamedKey::ArrowDown,
NamedKey::ArrowLeft,
NamedKey::ArrowUp,
] {
key(&mut chooser, arrow, true);
key(&mut chooser, arrow, false);
}
assert_eq!(chooser.focused, Game::Poe1);
send(&mut chooser, StageEvent::HoverChanged(false));
key(&mut chooser, NamedKey::Tab, true);
key(&mut chooser, NamedKey::Tab, false);
key(&mut chooser, NamedKey::Space, true);
key(&mut chooser, NamedKey::Space, false);
assert!(matches!(
chooser.update().unwrap(),
Some(StageTransition::StartGame(Game::Poe2))
));
}
#[test]
fn chooser_pointer_uses_display_scale_and_selects_each_game_once() {
for choice in Game::ALL {
let mut chooser = chooser();
send(&mut chooser, StageEvent::ScaleFactorChanged(2.0));
move_to(&mut chooser, choice);
mouse(&mut chooser, true);
mouse(&mut chooser, true);
assert!(chooser.update().unwrap().is_none());
mouse(&mut chooser, false);
assert!(matches!(
(choice, chooser.update().unwrap()),
(Game::Poe1, Some(StageTransition::StartGame(Game::Poe1)))
| (Game::Poe2, Some(StageTransition::StartGame(Game::Poe2)))
));
mouse(&mut chooser, false);
assert!(chooser.update().unwrap().is_none());
}
}
#[test]
fn chooser_rejects_unarmed_mismatched_and_departed_clicks() {
let mut chooser = chooser();
move_to(&mut chooser, Game::Poe1);
mouse(&mut chooser, false);
mouse(&mut chooser, true);
move_to(&mut chooser, Game::Poe2);
mouse(&mut chooser, false);
assert!(chooser.update().unwrap().is_none());
move_to(&mut chooser, Game::Poe1);
mouse(&mut chooser, true);
send(
&mut chooser,
StageEvent::MouseMoved {
pos: PhysicalPoint::new(0.0, 0.0),
},
);
move_to(&mut chooser, Game::Poe1);
mouse(&mut chooser, false);
assert!(chooser.update().unwrap().is_none());
mouse(&mut chooser, true);
send(&mut chooser, StageEvent::HoverChanged(false));
send(&mut chooser, StageEvent::HoverChanged(true));
move_to(&mut chooser, Game::Poe1);
mouse(&mut chooser, false);
assert!(chooser.update().unwrap().is_none());
}
#[test]
fn chooser_focus_loss_and_navigation_disarm_activation() {
let mut chooser = chooser();
key(&mut chooser, NamedKey::Enter, true);
send(&mut chooser, StageEvent::FocusChanged(false));
key(&mut chooser, NamedKey::Space, true);
send(&mut chooser, StageEvent::FocusChanged(true));
key(&mut chooser, NamedKey::Enter, false);
key(&mut chooser, NamedKey::Space, false);
assert!(chooser.update().unwrap().is_none());
key(&mut chooser, NamedKey::Enter, true);
key(&mut chooser, NamedKey::Tab, true);
key(&mut chooser, NamedKey::Enter, false);
assert!(chooser.update().unwrap().is_none());
move_to(&mut chooser, Game::Poe1);
mouse(&mut chooser, true);
send(&mut chooser, StageEvent::FocusChanged(false));
send(&mut chooser, StageEvent::FocusChanged(true));
move_to(&mut chooser, Game::Poe1);
mouse(&mut chooser, false);
assert!(chooser.update().unwrap().is_none());
}
#[test]
fn chooser_departure_and_resize_cannot_rearm_a_held_key() {
for event in [
StageEvent::HoverChanged(false),
StageEvent::Resized(PhysicalSize::new(640, 480)),
StageEvent::ScaleFactorChanged(1.5),
] {
let mut chooser = chooser();
key(&mut chooser, NamedKey::Enter, true);
send(&mut chooser, event);
key(&mut chooser, NamedKey::Enter, true);
key(&mut chooser, NamedKey::Enter, false);
assert!(chooser.update().unwrap().is_none());
key(&mut chooser, NamedKey::Enter, true);
key(&mut chooser, NamedKey::Enter, false);
assert!(matches!(
chooser.update().unwrap(),
Some(StageTransition::StartGame(Game::Poe1))
));
}
}
#[test]
fn chooser_escape_overrides_a_pending_game_and_stays_cancelled() {
let mut chooser = chooser();
key(&mut chooser, NamedKey::Enter, true);
key(&mut chooser, NamedKey::Enter, false);
key(&mut chooser, NamedKey::Escape, true);
assert!(matches!(
chooser.update().unwrap(),
Some(StageTransition::ToShutdown)
));
key(&mut chooser, NamedKey::Space, true);
key(&mut chooser, NamedKey::Space, false);
assert!(chooser.update().unwrap().is_none());
}
#[test]
fn chooser_layout_fits_small_windows_and_zero_surfaces_are_inert() {
for size in [
LogicalSize::new(320.0, 240.0),
LogicalSize::new(800.0, 600.0),
] {
let layout = ChooserLayout::new(size);
let screen = LogicalRect::from_size(size);
for choice in Game::ALL {
let button = layout.button(choice);
assert!(screen.contains_box(&button));
assert_eq!(layout.hit_test(button.center()), Some(choice));
}
}
let mut chooser = chooser();
move_to(&mut chooser, Game::Poe1);
mouse(&mut chooser, true);
send(&mut chooser, StageEvent::Resized(PhysicalSize::new(0, 0)));
mouse(&mut chooser, false);
assert!(chooser.update().unwrap().is_none());
let frame = chooser.frame().unwrap();
assert!(frame.draw_commands.is_empty());
assert!(!frame.request_redraw);
}
#[test]
fn chooser_initial_and_interaction_frames_render_then_idle() {
let mut chooser = chooser();
let initial = chooser.frame().unwrap();
assert!(!initial.can_elide);
assert!(!initial.request_redraw);
assert!(
initial
.draw_commands
.iter()
.filter(|cmd| cmd.color == Srgba::WHITE)
.count()
> 20,
"both game labels must produce visible glyphs"
);
assert!(chooser.frame().unwrap().can_elide);
move_to(&mut chooser, Game::Poe2);
assert!(!chooser.frame().unwrap().can_elide);
assert!(chooser.frame().unwrap().can_elide);
mouse(&mut chooser, true);
let pressed = chooser.frame().unwrap();
assert!(!pressed.can_elide);
assert!(!pressed.request_redraw);
}
}
+81
View File
@@ -0,0 +1,81 @@
use raw_window_handle::RawDisplayHandle;
/// Abstraction over clipboard crates
///
/// `smithay_clipboard`: Used on wayland
/// `arboard`: All other platforms (check arboard docs for platform support)
pub struct Clipboard {
#[cfg(target_os = "linux")]
smithay: Option<smithay_clipboard::Clipboard>,
arboard: Option<arboard::Clipboard>,
// fallback if everything else fails. only supports intra-application copy/paste
fallback: Option<String>,
}
impl Clipboard {
pub fn new(_raw_display_handle: Option<RawDisplayHandle>) -> Self {
Self {
#[cfg(target_os = "linux")]
smithay: create_smithay_clipboard(_raw_display_handle),
arboard: create_arboard_clipboard(),
fallback: None,
}
}
/// Sets the text content of clipboard
pub fn set_text(&mut self, text: String) {
#[cfg(target_os = "linux")]
if let Some(clipboard) = &mut self.smithay {
clipboard.store(text);
return;
}
if let Some(clipboard) = &mut self.arboard {
let _ = clipboard.set_text(text);
return;
}
self.fallback = Some(text);
}
/// Gets the text content of clipboard
pub fn get_text(&mut self) -> Option<String> {
#[cfg(target_os = "linux")]
if let Some(clipboard) = &mut self.smithay {
return clipboard.load().ok();
}
if let Some(clipboard) = &mut self.arboard {
return clipboard.get_text().ok();
}
if let Some(text) = &self.fallback {
return Some(text.clone());
}
None
}
}
#[cfg(target_os = "linux")]
fn create_smithay_clipboard(
raw_display_handle: Option<RawDisplayHandle>,
) -> Option<smithay_clipboard::Clipboard> {
if let Some(RawDisplayHandle::Wayland(handle)) = raw_display_handle {
log::debug!("Creating smithay clipboard...");
Some(unsafe { smithay_clipboard::Clipboard::new(handle.display.as_ptr()) })
} else {
None
}
}
fn create_arboard_clipboard() -> Option<arboard::Clipboard> {
log::debug!("Creating arboard clipboard...");
match arboard::Clipboard::new() {
Ok(clipboard) => Some(clipboard),
Err(err) => {
log::warn!("Failed to create arboard clipboard: {err}");
None
}
}
}
+12
View File
@@ -67,8 +67,20 @@ impl From<Srgba> for image::Rgba<u8> {
}
}
impl From<Srgba> for [f32; 4] {
fn from(value: Srgba) -> Self {
value.0.map(u8_to_f32)
}
}
/// f32 [0.0, 1.0] -> u8 [0, 255]
#[inline(always)]
const fn f32_to_u8(c: f32) -> u8 {
((c * 255.0) + 0.5) as u8
}
/// u8 [0, 255] -> f32 [0.0, 1.0]
#[inline(always)]
const fn u8_to_f32(c: u8) -> f32 {
c as f32 / 255.0
}
+2 -170
View File
@@ -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>;
+196
View File
@@ -0,0 +1,196 @@
use std::{collections::BTreeMap, hash::Hasher};
use ahash::AHasher;
use crate::{
color::Srgba,
dpi::{LogicalPoint, LogicalQuad, LogicalRect, LogicalSize, ScaleFactor},
fonts::{Layout, LayoutToLogical},
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,
});
}
/// Records a laid-out string whose top-left corner is at `layout_origin`.
pub fn draw_glyphs(
&mut self,
layout: &Layout,
layout_origin: LogicalPoint<f32>,
is_absolute_position: bool,
scale_factor: ScaleFactor<f32>,
) {
// resolve the layout origin to screen space
let origin = if is_absolute_position {
layout_origin
} else {
layout_origin + self.current_viewport.min.to_vector()
};
// align the layout origin with the physical pixel grid to reduce blurriness
let origin = (origin * scale_factor).round() / scale_factor;
for glyph in &layout.glyphs {
let rect = LayoutToLogical::new(origin.x, origin.y).transform_box(&glyph.rect);
self.draw_glyph(rect, glyph.uv, glyph.color, glyph.layer_idx);
}
}
fn draw_glyph(
&mut self,
positions: LogicalRect<f32>,
uv: UvRect,
color: Srgba,
layer_idx: u32,
) {
// 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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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()
}
}
+45
View File
@@ -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
View File
@@ -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),
})
}
+60
View File
@@ -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
}
}
+89 -49
View File
@@ -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,17 +171,42 @@ impl GraphicsContext {
}
}
pub fn render(&mut self, render_job: RenderJob) -> Result<(), wgpu::SurfaceError> {
pub fn render(&mut self, render_job: Option<RenderJob>) -> anyhow::Result<()> {
profiling::scope!("render");
self.window.request_redraw();
// apply textures delta
if let Some(render_job) = &render_job {
self.renderer
.update_textures(&self.device, &self.queue, &render_job.textures_delta);
}
if !self.is_surface_configured {
if let Some(render_job) = &render_job {
self.renderer.free_textures(&render_job.textures_delta);
}
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
if let Some(render_job) = &render_job {
self.renderer.free_textures(&render_job.textures_delta);
}
return Ok(());
}
wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
self.surface.configure(&self.device, &self.config);
if let Some(render_job) = &render_job {
self.renderer.free_textures(&render_job.textures_delta);
}
return Ok(());
}
};
let surface_view = output
.texture
@@ -166,27 +218,18 @@ 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);
let pixels_per_point = self.window.as_ref().scale_factor() as f32;
// upload new textures
self.renderer
.update_textures(&self.device, &self.queue, &textures_delta);
// upload vertex, index, and uniform buffers
self.renderer.update_buffers(
&self.device,
&self.queue,
&meshes,
&render_job,
screen_size,
pixels_per_point,
render_job.scale_factor,
);
let rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@@ -208,16 +251,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,
pixels_per_point,
render_job.scale_factor,
);
self.renderer.free_textures(&textures_delta)
self.renderer.free_textures(&render_job.textures_delta);
}
{
@@ -231,15 +276,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(())
}
}
+66 -227
View File
@@ -1,269 +1,108 @@
//! Module to handle user inputs like keyboard keys and mouse buttons.
use crate::dpi::LogicalPoint;
use ahash::{HashMap, HashSet};
use std::time::{Duration, Instant};
use winit::{
event::MouseButton,
keyboard::{KeyCode, ModifiersState},
};
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 {
/// Currently held modifier keys (Shift/Ctrl/Alt/Super).
pub key_modifiers: ModifiersState,
keys_pressed: HashSet<KeyCode>,
/// Keys currently held down.
keys_pressed: HashSet<Key>,
/// Mouse buttons currently held down.
mouse_pressed: HashSet<MouseButton>,
mouse_last_pressed: HashMap<MouseButton, Instant>,
/// 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 {
pub fn set_key_pressed(&mut self, code: KeyCode, 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(code);
self.keys_pressed.insert(key.clone());
} else {
self.keys_pressed.remove(&code);
self.keys_pressed.remove(key);
}
}
pub fn key_pressed(&self, code: KeyCode) -> bool {
self.keys_pressed.contains(&code)
/// Returns whether `key` is currently pressed.
pub fn key_pressed(&self, key: &Key) -> bool {
self.keys_pressed.contains(key)
}
/// 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 whether `button` is currently pressed.
pub fn mouse_pressed(&self, button: MouseButton) -> bool {
self.mouse_pressed.contains(&button)
}
/// Returns the last known cursor position.
pub fn mouse_pos(&self) -> LogicalPoint<f32> {
self.cursor_pos
}
/// Updates the cursor position.
pub fn set_mouse_pos(&mut self, pos: LogicalPoint<f32>) {
self.cursor_pos = pos;
}
}
pub fn str_as_keycode(s: &str) -> Option<KeyCode> {
Some(match s.to_uppercase().as_str() {
// Letters
"A" => KeyCode::KeyA,
"B" => KeyCode::KeyB,
"C" => KeyCode::KeyC,
"D" => KeyCode::KeyD,
"E" => KeyCode::KeyE,
"F" => KeyCode::KeyF,
"G" => KeyCode::KeyG,
"H" => KeyCode::KeyH,
"I" => KeyCode::KeyI,
"J" => KeyCode::KeyJ,
"K" => KeyCode::KeyK,
"L" => KeyCode::KeyL,
"M" => KeyCode::KeyM,
"N" => KeyCode::KeyN,
"O" => KeyCode::KeyO,
"P" => KeyCode::KeyP,
"Q" => KeyCode::KeyQ,
"R" => KeyCode::KeyR,
"S" => KeyCode::KeyS,
"T" => KeyCode::KeyT,
"U" => KeyCode::KeyU,
"V" => KeyCode::KeyV,
"W" => KeyCode::KeyW,
"X" => KeyCode::KeyX,
"Y" => KeyCode::KeyY,
"Z" => KeyCode::KeyZ,
// Digits
"0" => KeyCode::Digit0,
"1" => KeyCode::Digit1,
"2" => KeyCode::Digit2,
"3" => KeyCode::Digit3,
"4" => KeyCode::Digit4,
"5" => KeyCode::Digit5,
"6" => KeyCode::Digit6,
"7" => KeyCode::Digit7,
"8" => KeyCode::Digit8,
"9" => KeyCode::Digit9,
// Modifiers
"SHIFT" => KeyCode::ShiftLeft,
"CTRL" => KeyCode::ControlLeft,
"ALT" => KeyCode::AltLeft,
// F Keys
"F1" => KeyCode::F1,
"F2" => KeyCode::F2,
"F3" => KeyCode::F3,
"F4" => KeyCode::F4,
"F5" => KeyCode::F5,
"F6" => KeyCode::F6,
"F7" => KeyCode::F7,
"F8" => KeyCode::F8,
"F9" => KeyCode::F9,
"F10" => KeyCode::F10,
"F11" => KeyCode::F11,
"F12" => KeyCode::F12,
// Rest
" " => KeyCode::Space,
"BACK" => KeyCode::Backspace,
"TAB" => KeyCode::Tab,
"RETURN" => KeyCode::Enter,
"ESCAPE" => KeyCode::Escape,
"PAUSE" => KeyCode::Pause,
"PAGEUP" => KeyCode::PageUp,
"PAGEDOWN" => KeyCode::PageDown,
"END" => KeyCode::End,
"HOME" => KeyCode::Home,
"PRINTSCREEN" => KeyCode::PrintScreen,
"INSERT" => KeyCode::Insert,
"DELETE" => KeyCode::Delete,
"UP" => KeyCode::ArrowUp,
"DOWN" => KeyCode::ArrowDown,
"LEFT" => KeyCode::ArrowLeft,
"RIGHT" => KeyCode::ArrowRight,
"NUMLOCK" => KeyCode::NumLock,
"SCROLL" => KeyCode::ScrollLock,
_ => return None,
})
}
pub fn keycode_as_str(code: KeyCode) -> Option<&'static str> {
Some(match code {
// Letters
KeyCode::KeyA => "a",
KeyCode::KeyB => "b",
KeyCode::KeyC => "c",
KeyCode::KeyD => "d",
KeyCode::KeyE => "e",
KeyCode::KeyF => "f",
KeyCode::KeyG => "g",
KeyCode::KeyH => "h",
KeyCode::KeyI => "i",
KeyCode::KeyJ => "j",
KeyCode::KeyK => "k",
KeyCode::KeyL => "l",
KeyCode::KeyM => "m",
KeyCode::KeyN => "n",
KeyCode::KeyO => "o",
KeyCode::KeyP => "p",
KeyCode::KeyQ => "q",
KeyCode::KeyR => "r",
KeyCode::KeyS => "s",
KeyCode::KeyT => "t",
KeyCode::KeyU => "u",
KeyCode::KeyV => "v",
KeyCode::KeyW => "w",
KeyCode::KeyX => "x",
KeyCode::KeyY => "y",
KeyCode::KeyZ => "z",
// Digits
KeyCode::Digit0 => "0",
KeyCode::Digit1 => "1",
KeyCode::Digit2 => "2",
KeyCode::Digit3 => "3",
KeyCode::Digit4 => "4",
KeyCode::Digit5 => "5",
KeyCode::Digit6 => "6",
KeyCode::Digit7 => "7",
KeyCode::Digit8 => "8",
KeyCode::Digit9 => "9",
// Modifiers
KeyCode::ShiftLeft => "SHIFT",
KeyCode::ControlLeft => "CTRL",
KeyCode::AltLeft => "ALT",
// F Keys
KeyCode::F1 => "F1",
KeyCode::F2 => "F2",
KeyCode::F3 => "F3",
KeyCode::F4 => "F4",
KeyCode::F5 => "F5",
KeyCode::F6 => "F6",
KeyCode::F7 => "F7",
KeyCode::F8 => "F8",
KeyCode::F9 => "F9",
KeyCode::F10 => "F10",
KeyCode::F11 => "F11",
KeyCode::F12 => "F12",
// Rest
KeyCode::Space => " ",
KeyCode::Backspace => "BACK",
KeyCode::Tab => "TAB",
KeyCode::Enter => "RETURN",
KeyCode::Escape => "ESCAPE",
KeyCode::Pause => "PAUSE",
KeyCode::PageUp => "PAGEUP",
KeyCode::PageDown => "PAGEDOWN",
KeyCode::End => "END",
KeyCode::Home => "HOME",
KeyCode::PrintScreen => "PRINTSCREEN",
KeyCode::Insert => "INSERT",
KeyCode::Delete => "DELETE",
KeyCode::ArrowUp => "UP",
KeyCode::ArrowDown => "DOWN",
KeyCode::ArrowLeft => "LEFT",
KeyCode::ArrowRight => "RIGHT",
KeyCode::NumLock => "NUMLOCK",
KeyCode::ScrollLock => "SCROLL",
KeyCode::Equal => "+", // This is what PoB does
KeyCode::Minus => "-",
KeyCode::Comma => ",",
KeyCode::Period => ".",
KeyCode::Slash => "/",
KeyCode::NumpadAdd => "+",
KeyCode::NumpadSubtract => "-",
KeyCode::NumpadEnter => "RETURN",
KeyCode::Numpad0 => "0",
_ => return None,
})
}
pub fn str_as_mousebutton(s: &str) -> Option<MouseButton> {
Some(match s.to_uppercase().as_str() {
"LEFTBUTTON" => MouseButton::Left,
"RIGHTBUTTON" => MouseButton::Right,
"MIDDLEBUTTON" => MouseButton::Middle,
"MOUSE4" => MouseButton::Back,
"MOUSE5" => MouseButton::Forward,
_ => return None,
})
}
pub fn mousebutton_as_str(button: MouseButton) -> Option<&'static str> {
Some(match button {
MouseButton::Left => "LEFTBUTTON",
MouseButton::Right => "RIGHTBUTTON",
MouseButton::Middle => "MIDDLEBUTTON",
MouseButton::Back => "MOUSE4",
MouseButton::Forward => "MOUSE5",
_ => return None,
})
/// 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();
}
}
+389 -291
View File
@@ -1,96 +1,98 @@
use crate::{
app::AppState,
args::Game,
color::Srgba,
dpi::{LogicalPoint, LogicalRect},
fonts::{Alignment, FontStyle, LayoutJob},
mode::{AppEvent, ModeFrameOutput, ModeTransition},
renderer::primitives::{ClippedPrimitive, DrawPrimitive, TextPrimitive},
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,
},
renderer::textures::TextureId,
stage::{StageEvent, StageFrameOutput, StageTransition},
util::replace_in_matching_lines,
window::WindowState,
};
use anyhow::bail;
use flate2::read::GzDecoder;
use parley::{FontFamily, GenericFamily};
use parley::{FontFamily, FontFamilyName, GenericFamily};
use regex::Regex;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::{
fs::{self},
io::copy,
path::{Path, PathBuf},
sync::mpsc::{self, Receiver, TryRecvError},
cell::RefCell,
fs,
path::Path,
rc::Rc,
sync::{
Arc, LazyLock,
mpsc::{self, Receiver, TryRecvError},
},
thread,
};
use ureq::http::Response;
use winit::window::Window;
const REPO_NAME: &str = "meehl/rusty-pob-manifest";
mod download;
enum DownloadProgress {
Percentage(f32), // percentage of total size (between 0 and 1)
TotalBytes(u64), // amount of bytes downloaded
}
const COMPAT_REPO: &str = "meehl/rusty-pob-manifest";
static VERSION_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^(\d+)\.(\d+)\.(\d+)$").unwrap());
static MANIFEST_VERSION_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<Version").unwrap());
enum Progress {
Download(DownloadProgress),
Status(String),
Complete,
Error(anyhow::Error),
}
enum CurrentProgress {
Starting,
Download(DownloadProgress),
}
/// Execution mode in which PoB's assets are downloaded if they don't exist yet.
///
/// Immediately transitions into PoB mode if assets already exist. Otherwise,
/// it downloads them to the user directory and displays the download progress.
pub struct InstallMode {
pub struct Installer {
progress_rx: Option<Receiver<Progress>>,
current_progress: CurrentProgress,
status: String,
window_state: WindowState,
fonts: Rc<RefCell<Fonts>>,
}
impl InstallMode {
pub fn new() -> Self {
let script_dir = Game::script_dir();
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();
thread::spawn(move || {
if let Err(err) = install(script_dir.as_path(), &progress_tx) {
progress_tx.send(Progress::Error(err)).unwrap();
if let Err(err) = install(script_dir.as_path(), game, &progress_tx) {
let _ = progress_tx.send(Progress::Error(err));
return;
}
progress_tx.send(Progress::Complete).unwrap();
let _ = progress_tx.send(Progress::Complete);
});
Self {
progress_rx: Some(progress_rx),
current_progress: CurrentProgress::Starting,
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,
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::Download(progress)) => {
self.current_progress = CurrentProgress::Download(progress);
}
Ok(Progress::Complete) => {
return Ok(Some(ModeTransition::PoB));
}
Ok(Progress::Status(msg)) => self.status = msg,
Ok(Progress::Complete) => return Ok(Some(StageTransition::ToMain)),
Ok(Progress::Error(err)) => {
return Err(anyhow::anyhow!("Download failed: {}", err));
return Err(anyhow::anyhow!("Installation failed: {err}"));
}
Err(TryRecvError::Disconnected) => {
return Err(anyhow::anyhow!("Download thread disconnected!"));
return Err(anyhow::anyhow!("Install thread disconnected unexpectedly"));
}
Err(TryRecvError::Empty) => {
break;
@@ -102,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),
@@ -123,198 +135,263 @@ impl InstallMode {
FontStyle::Normal,
);
let progress_text = match &self.current_progress {
CurrentProgress::Starting => String::from("Starting download..."),
CurrentProgress::Download(progress) => match progress {
DownloadProgress::Percentage(progress) => {
let percent = (progress * 100.0) as u32;
format!("Downloading assets... ({})", percent)
}
DownloadProgress::TotalBytes(total_bytes) => {
format!("Downloading assets... ({})", format_bytes(*total_bytes))
}
},
};
job.append(&progress_text, Srgba::WHITE);
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),
});
}
// center text vertically and horizontally
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),
};
let primitives = vec![clipped_primitive];
Box::new(primitives.into_iter())
draw_commands
}
}
// Helper function for writing status to both the message channel and the log
fn report(tx: &mpsc::Sender<Progress>, msg: impl Into<String>) {
let msg = msg.into();
log::info!("{msg}");
let _ = tx.send(Progress::Status(msg));
}
/// Performs full installation of PoB assets into `target_dir`.
///
/// Skips installation if `rpob.version` already exists.
///
/// Steps:
/// 1. Fetch the compatibility table to determine which PoB version is
/// supported by the current Rusty PoB version.
/// 2. Download and extract the PoB release tarball into `target_dir`.
/// 3. Replace `UpdateCheck.lua` with a patched version and update its
/// checksum in `manifest.xml`. This is needed to support PoB native updater.
/// 4. Set the branch and platform fields in `manifest.xml`.
/// 5. Write `rpob.version` to mark the installation as complete.
fn install<P: AsRef<Path>>(
target_dir: P,
game: Game,
progress_tx: &mpsc::Sender<Progress>,
) -> anyhow::Result<()> {
// Skip installation if version file exists
let version_file_path = target_dir.as_ref().join("rpob.version");
if version_file_path.exists() {
let old_version = fs::read_to_string(&version_file_path).unwrap();
let current_version = env!("CARGO_PKG_VERSION");
let target_dir = target_dir.as_ref();
let client = build_client()?;
let version_file_path = target_dir.join("rpob.version");
let current_version = env!("CARGO_PKG_VERSION");
if version_file_path.exists() {
let old_version = fs::read_to_string(&version_file_path)?;
if old_version != current_version {
log::info!("New version detected: {old_version} -> {current_version}");
log::info!("Version changed: {old_version} -> {current_version}");
fs::write(&version_file_path, current_version).unwrap();
}
return Ok(());
}
download_path_of_building(&target_dir, progress_tx)?;
replace_updatecheck(&target_dir)?;
set_branch_and_platform(&target_dir)?;
report(progress_tx, "Fetching compatibility info...");
let compat_info = fetch_compatibility_info(&client, game)?;
let pob_version = highest_supported_pob_version(&compat_info, current_version)
.ok_or_else(|| anyhow::anyhow!("Unable to determine supported PoB version"))?;
log::info!("Using PoB version: {pob_version}");
// write version file
fs::write(&version_file_path, env!("CARGO_PKG_VERSION")).unwrap();
report(progress_tx, "Downloading assets...");
download_pob(&client, target_dir, game, pob_version, progress_tx)?;
report(progress_tx, "Finalizing installation...");
replace_updatecheck(&client, target_dir)?;
set_branch_and_platform(target_dir)?;
fs::write(&version_file_path, current_version)?;
log::info!("Installation complete.");
Ok(())
}
/// Downloads latest release of Path of Building
fn download_path_of_building<P: AsRef<Path>>(
#[derive(Debug)]
struct VersionReq {
pob_ver: String,
min_rpob_ver: String,
}
/// Fetches compatibility info
fn fetch_compatibility_info(
client: &reqwest::blocking::Client,
game: Game,
) -> anyhow::Result<Vec<VersionReq>> {
let file_name = match game {
Game::Poe1 => "Compatibility_pob1.lua",
Game::Poe2 => "Compatibility_pob2.lua",
};
let compatibility_info_file = fetch_file_contents(client, COMPAT_REPO, file_name)?;
// Load and evaluate compatibility file contents as Lua code
let lua = mlua::Lua::new();
let compatibility_table = lua.load(compatibility_info_file).eval::<mlua::Table>()?;
// Compatibility table maps PoB version to minimum required Rusty PoB version.
// Beta versions have a non-semver suffix and are filtered out by the regex.
Ok(compatibility_table
.pairs::<String, String>()
.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,
min_rpob_ver: min_req_rpob_ver,
})
.collect())
}
/// Determines the highest PoB version supported by the given Rusty PoB version.
fn highest_supported_pob_version<'a>(
compatibility_info: &'a [VersionReq],
rpob_version: &str,
) -> Option<&'a str> {
let mut highest: Option<&str> = None;
for VersionReq {
pob_ver,
min_rpob_ver,
} in compatibility_info
{
if is_higher_version(min_rpob_ver, rpob_version).unwrap_or(false) {
match highest {
Some(h) if !is_higher_version(h, pob_ver).unwrap_or(false) => {}
_ => highest = Some(pob_ver.as_str()),
}
}
}
highest
}
fn download_pob<P: AsRef<Path>>(
client: &reqwest::blocking::Client,
target_dir: P,
game: Game,
pob_version: &str,
progress_tx: &mpsc::Sender<Progress>,
) -> anyhow::Result<()> {
log::info!("Downloading Path of Building assets...");
let target_dir = target_dir.as_ref();
let repo = match Game::current() {
let pob_repo = match game {
Game::Poe1 => "PathOfBuildingCommunity/PathOfBuilding",
Game::Poe2 => "PathOfBuildingCommunity/PathOfBuilding-PoE2",
};
let url = format!(
"https://github.com/{}/archive/refs/heads/master.tar.gz",
repo
);
let mut response = http_get_with_backoff(&url)?;
let total_size = response
.headers()
.get("Content-Length")
.and_then(|s| s.to_str().ok()?.parse::<u64>().ok());
let rules = vec![
ExtractionRule::File {
tarball_path: "manifest.xml".into(),
dest_path: target_dir.join("manifest.xml"),
},
ExtractionRule::File {
tarball_path: "help.txt".into(),
dest_path: target_dir.join("help.txt"),
},
ExtractionRule::File {
tarball_path: "changelog.txt".into(),
dest_path: target_dir.join("changelog.txt"),
},
ExtractionRule::File {
tarball_path: "LICENSE.md".into(),
dest_path: target_dir.join("LICENSE.md"),
},
ExtractionRule::RewritePrefix {
prefix: "src/".into(),
dest_dir: target_dir.to_path_buf(),
},
ExtractionRule::RewritePrefix {
prefix: "runtime/lua/".into(),
dest_dir: target_dir.join("lua"),
},
];
let body_reader = response.body_mut().as_reader();
let mut archive = tar::Archive::new(GzDecoder::new(body_reader));
let mut downloaded = 0u64;
for file in archive.entries()? {
let mut file = file?;
let file_path = file.path()?;
let components: Vec<_> = file_path.components().collect();
let target_path = match components.len() {
0..=1 => None,
// put these into target_dir/
2 => {
let filename = components[1].as_os_str();
if filename == "manifest.xml"
|| filename == "help.txt"
|| filename == "changelog.txt"
|| filename == "LICENSE.md"
{
Some(target_dir.as_ref().join(filename))
} else {
None
download_and_extract_tarball(
client,
pob_repo,
&format!("v{pob_version}"),
&rules,
5,
&mut |event| {
let msg = match event {
DownloadEvent::Progress {
downloaded,
total: Some(total),
} => {
let pct = (downloaded as f32 / total as f32 * 100.0) as u32;
format!("Downloading assets... ({pct}%)")
}
}
// put lua runtime files into target_dir/lua/
3.. => {
if components[1].as_os_str() == "src"
|| (components[1].as_os_str() == "runtime"
&& components[2].as_os_str() == "lua")
{
Some(
target_dir
.as_ref()
.join(components[2..].iter().collect::<PathBuf>()),
)
} else {
None
DownloadEvent::Progress {
downloaded,
total: None,
} => {
format!("Downloading assets... ({})", format_bytes(downloaded))
}
}
};
// create needed directories and extract
if let Some(target_path) = target_path {
if let Some(parent) = target_path.parent() {
fs::create_dir_all(parent)?;
}
file.unpack(&target_path)?;
}
downloaded += file.size();
if let Some(total) = total_size {
let progress = downloaded as f32 / total as f32;
progress_tx.send(Progress::Download(DownloadProgress::Percentage(progress)))?;
} else {
progress_tx.send(Progress::Download(DownloadProgress::TotalBytes(downloaded)))?;
}
}
DownloadEvent::Retrying { attempt } => {
format!("Retrying... (Attempt {attempt})")
}
};
let _ = progress_tx.send(Progress::Status(msg));
},
)?;
Ok(())
}
/// Replaces UpdateCheck with rusty-path-of-building's custom version of it.
fn replace_updatecheck<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
log::info!("Downloading custom UpdateCheck.lua script...");
/// Replaces UpdateCheck.lua with rusty-path-of-building's modified version and
/// updates its checksum in manifest.xml.
fn replace_updatecheck<P: AsRef<Path>>(
client: &reqwest::blocking::Client,
target_dir: P,
) -> anyhow::Result<()> {
let target_dir = target_dir.as_ref();
let file_name = "UpdateCheck.lua";
download_file(
&format!(
"https://raw.githubusercontent.com/{REPO_NAME}/main/{}",
"UpdateCheck.lua"
),
target_dir.as_ref().join("UpdateCheck.lua"),
)?;
download_file_to_disk(client, COMPAT_REPO, file_name, target_dir.join(file_name))?;
// .sha1 file format: "<checksum> UpdateCheck.lua" - we only need the checksum.
let sha1_contents = fetch_file_contents(client, COMPAT_REPO, "UpdateCheck.lua.sha1")?;
let new_checksum = sha1_contents
.split_whitespace()
.next()
.ok_or_else(|| anyhow::anyhow!("Invalid checksum file format"))?;
let manifest_path = target_dir.join("manifest.xml");
let manifest = fs::read_to_string(&manifest_path)?;
let new_manifest = replace_in_matching_lines(
&manifest,
r#"name="UpdateCheck.lua""#,
r#"sha1="([0-9A-Za-z]+)""#,
&format!(r#"sha1="{new_checksum}""#),
);
fs::write(&manifest_path, &new_manifest)?;
Ok(())
}
/// Sets branch and platform in manifest.xml
fn set_branch_and_platform<P: AsRef<Path>>(target_dir: P) -> anyhow::Result<()> {
let filename = target_dir.as_ref().join("manifest.xml");
let manifest = fs::read_to_string(&filename)?;
let path = target_dir.as_ref().join("manifest.xml");
let manifest = fs::read_to_string(&path)?;
#[cfg(not(target_os = "windows"))]
let platform = std::env::consts::OS;
#[cfg(target_os = "windows")]
let platform = "win32";
#[cfg(not(target_os = "windows"))]
let platform = std::env::consts::OS;
let new_version = format!(r#"<Version branch="master" platform="{}""#, platform);
let version_regex = Regex::new(r"<Version").unwrap();
let new_manifest = version_regex.replace(&manifest, new_version);
fs::write(&filename, new_manifest.as_ref())?;
let replacement = format!(r#"<Version branch="master" platform="{platform}""#);
let new_manifest = MANIFEST_VERSION_RE.replace(&manifest, replacement);
fs::write(&path, new_manifest.as_ref())?;
Ok(())
}
fn download_file<P: AsRef<Path>>(url: &str, file_path: P) -> anyhow::Result<()> {
let mut response = http_get_with_backoff(url)?;
if response.status().is_success() {
let body = response.body_mut();
let mut file = fs::File::create(file_path)?;
copy(&mut body.as_reader(), &mut file)?;
Ok(())
} else {
bail!("Unable to download: {}", url);
}
}
fn format_bytes(size_in_bytes: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = KB * 1024;
@@ -327,108 +404,129 @@ fn format_bytes(size_in_bytes: u64) -> String {
} else if size_in_bytes >= KB {
format!("{:.2} KB", size_in_bytes as f64 / KB as f64)
} else {
format!("{} bytes", size_in_bytes)
format!("{size_in_bytes} bytes")
}
}
/// Calculates wait time based on rate limit headers or falls back to default backoff.
fn calculate_wait_time(resp: &Response<ureq::Body>, default_backoff: u64) -> u64 {
let headers = resp.headers();
/// Returns true if `v2` is greater than or equal to `v1`.
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}"))?;
// Wait for time specified in retry-after response header if present
if let Some(retry_after) = headers
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
{
return retry_after;
}
let major = caps[1].parse::<u32>().unwrap();
let minor = caps[2].parse::<u32>().unwrap();
let patch = caps[3].parse::<u32>().unwrap();
// The number of requests remaining in the current rate limit window
let remaining = headers
.get("x-ratelimit-remaining")
.and_then(|v| v.to_str().ok());
Ok((major, minor, patch))
};
if remaining == Some("0") {
// Calculate time until rate limit reset
if let Some(reset_epoch) = headers
.get("x-ratelimit-reset")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
{
let now_epoch = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let (major1, minor1, patch1) = parse_version(v1)?;
let (major2, minor2, patch2) = parse_version(v2)?;
if reset_epoch > now_epoch {
return reset_epoch - now_epoch;
}
}
}
default_backoff
Ok(major2 > major1
|| (major2 == major1 && minor2 > minor1)
|| (major2 == major1 && minor2 == minor1 && patch2 >= patch1))
}
/// Performs a GET request with exponential backoff aware of GitHub rate limit headers.
fn http_get_with_backoff(url: &str) -> anyhow::Result<Response<ureq::Body>> {
const MAX_ATTEMPTS: usize = 6;
const MAX_BACKOFF_SECS: u64 = 60;
let mut attempt = 0;
let mut backoff_secs: u64 = 2;
#[cfg(test)]
mod tests {
use super::*;
loop {
attempt += 1;
let resp_result = ureq::get(url)
.header("User-Agent", "rusty-path-of-building")
.call();
#[test]
fn test_major_version() {
assert!(is_higher_version("1.0.0", "2.0.0").unwrap());
assert!(!is_higher_version("2.0.0", "1.0.0").unwrap());
}
let resp = match resp_result {
Ok(r) => r,
Err(err) => {
log::warn!(
"Transport error: {} (attempt {}/{})",
err,
attempt,
MAX_ATTEMPTS
);
if attempt >= MAX_ATTEMPTS {
return Err(anyhow::Error::new(err));
}
thread::sleep(Duration::from_secs(backoff_secs));
backoff_secs = (backoff_secs * 2).min(MAX_BACKOFF_SECS);
continue;
}
};
#[test]
fn test_minor_version() {
assert!(is_higher_version("1.5.0", "1.6.0").unwrap());
assert!(!is_higher_version("1.10.0", "1.9.0").unwrap());
}
let status = resp.status();
if status == 403 || status == 429 {
let wait = calculate_wait_time(&resp, backoff_secs);
#[test]
fn test_patch_version() {
assert!(is_higher_version("1.0.3", "1.0.4").unwrap());
assert!(!is_higher_version("1.0.10", "1.0.9").unwrap());
}
log::warn!(
"Rate limited (status {}). Waiting {}s before retry (attempt {}/{})",
status,
wait,
attempt,
MAX_ATTEMPTS
);
if attempt >= MAX_ATTEMPTS {
return Err(anyhow::anyhow!(
"HTTP {} after {} attempts for {}",
status,
attempt,
url
));
}
thread::sleep(Duration::from_secs(wait));
backoff_secs = (backoff_secs * 2).min(MAX_BACKOFF_SECS);
continue;
}
#[test]
fn test_same_version() {
assert!(is_higher_version("1.5.3", "1.5.3").unwrap());
}
if status.is_client_error() || status.is_server_error() {
return Err(anyhow::anyhow!("http status: {} for {}", status, url));
}
#[test]
fn test_invalid_semver_format() {
assert!(is_higher_version("1.0", "2.0.0").is_err());
assert!(is_higher_version("1.0.0", "2.0").is_err());
assert!(is_higher_version("invalid", "2.0.0").is_err());
assert!(is_higher_version("1.0.0", "a.bb.ccc").is_err());
}
return Ok(resp);
#[test]
fn test_highest_supported_pob_ver() {
let compat_info = vec![
VersionReq {
pob_ver: "2.56.0".into(),
min_rpob_ver: "0.1.0".into(),
},
// compat info might not be sorted by pob_version
VersionReq {
pob_ver: "2.58.0".into(),
min_rpob_ver: "0.2.6".into(),
},
VersionReq {
pob_ver: "2.57.0".into(),
min_rpob_ver: "0.2.6".into(),
},
VersionReq {
pob_ver: "2.58.1".into(),
min_rpob_ver: "0.2.8".into(),
},
VersionReq {
pob_ver: "2.59.0".into(),
min_rpob_ver: "0.2.9".into(),
},
VersionReq {
pob_ver: "2.59.1".into(),
min_rpob_ver: "0.2.10".into(),
},
VersionReq {
pob_ver: "2.59.2".into(),
min_rpob_ver: "0.2.10".into(),
},
];
assert_eq!(highest_supported_pob_version(&compat_info, "0.0.2"), None);
assert_eq!(highest_supported_pob_version(&compat_info, "a.b.c"), None);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.1.0"),
Some("2.56.0")
);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.2.0"),
Some("2.56.0")
);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.2.6"),
Some("2.58.0")
);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.2.7"),
Some("2.58.0")
);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.2.8"),
Some("2.58.1")
);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.2.9"),
Some("2.59.0")
);
assert_eq!(
highest_supported_pob_version(&compat_info, "0.2.10"),
Some("2.59.2")
);
}
}
+266
View File
@@ -0,0 +1,266 @@
use std::{
fmt,
fs::{self, File},
io::{self, Read, Write},
path::{Path, PathBuf},
thread,
time::{Duration, Instant},
};
use flate2::read::GzDecoder;
use reqwest::blocking::{Client, Response};
use tar::Archive;
#[derive(Debug)]
pub enum DownloadEvent {
Progress { downloaded: u64, total: Option<u64> },
Retrying { attempt: u32 },
}
/// Build a reqwest blocking client
pub fn build_client() -> Result<Client, reqwest::Error> {
Client::builder().timeout(Duration::from_mins(1)).build()
}
// Rate-limit-aware GET.
//
// `raw.githubusercontent.com` doesn't seem to use `x-ratelimit-reset` and
// `x-ratelimit-remaining` headers like the API so only the status code is checked.
fn get_checked(client: &Client, url: &str) -> Result<Response, GithubError> {
let response = client.get(url).send()?;
let status = response.status();
if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
let retry_after_secs = response
.headers()
.get("retry-after")
.and_then(|v| v.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or(60);
return Err(GithubError::RateLimited {
retry_after_s: retry_after_secs,
});
}
if !status.is_success() {
return Err(GithubError::Http {
status: status.as_u16(),
url: url.to_string(),
});
}
Ok(response)
}
/// Wrapper to retry `f` up to `max_retries` times
pub fn with_retry<T, F>(max_retries: u32, base_delay: Duration, mut f: F) -> Result<T, GithubError>
where
F: FnMut(u32) -> Result<T, GithubError>,
{
let mut attempt = 0;
loop {
match f(attempt) {
Err(GithubError::RateLimited {
retry_after_s: retry_after_secs,
}) if attempt < max_retries => {
log::warn!("Rate limited – sleeping {retry_after_secs}s (attempt {attempt})");
thread::sleep(Duration::from_secs(retry_after_secs));
attempt += 1;
}
Err(GithubError::Network(e)) if attempt < max_retries => {
let delay = base_delay * (attempt + 1);
log::warn!("Network error on attempt {attempt}: {e}. Retrying in {delay:?}");
thread::sleep(delay);
attempt += 1;
}
other => return other,
}
}
}
/// Download file contents from raw.githubusercontent.com into a `String`.
pub fn fetch_file_contents(
client: &Client,
repo: &str,
file_name: &str,
) -> Result<String, GithubError> {
let url = format!("https://raw.githubusercontent.com/{repo}/main/{file_name}");
let response = get_checked(client, &url)?;
Ok(response.text()?)
}
/// Download a file from raw.githubusercontent.com and write it to `dest_path`.
pub fn download_file_to_disk<P: AsRef<Path>>(
client: &Client,
repo: &str,
file_name: &str,
dest_path: P,
) -> Result<(), GithubError> {
let dest_path = dest_path.as_ref();
let url = format!("https://raw.githubusercontent.com/{repo}/main/{file_name}");
let mut response = get_checked(client, &url)?;
if let Some(parent) = dest_path.parent() {
fs::create_dir_all(parent)?;
}
let mut file = File::create(dest_path)?;
io::copy(&mut response, &mut file)?;
Ok(())
}
/// A rule describing how to map tarball entries to destination paths.
///
/// The root prefix is automatically striped and doesn't need to be specified.
pub enum ExtractionRule {
/// Map a single file to an exact destination path.
File {
tarball_path: String,
dest_path: PathBuf,
},
/// Strip prefix from matching entries and place the remainder under `dest_dir`.
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,
repo_name: &str,
tag: &str,
rules: &[ExtractionRule],
max_retries: u32,
on_progress: &mut impl FnMut(DownloadEvent),
) -> Result<(), GithubError> {
let url = format!("https://github.com/{repo_name}/archive/refs/tags/{tag}.tar.gz");
let tmp_path =
std::env::temp_dir().join(format!("gh-{}-{}.tar.gz", repo_name.replace('/', "-"), tag));
// Download to temp file
with_retry(max_retries, Duration::from_secs(5), |attempt| {
if attempt > 0 {
on_progress(DownloadEvent::Retrying { attempt });
}
let response = get_checked(client, &url)?;
let content_length = response.content_length();
let mut tmp_file = File::create(&tmp_path)?;
let mut chunk = vec![0u8; CHUNK_SIZE];
let mut downloaded: u64 = 0;
let mut body = response;
let mut last_progress = Instant::now();
loop {
let n = body.read(&mut chunk)?;
if n == 0 {
break;
}
tmp_file.write_all(&chunk[..n])?;
downloaded += n as u64;
if last_progress.elapsed() >= PROGRESS_INTERVAL {
on_progress(DownloadEvent::Progress {
downloaded,
total: content_length,
});
last_progress = Instant::now();
}
}
on_progress(DownloadEvent::Progress {
downloaded,
total: content_length,
});
Ok(())
})?;
// Extract tarball to destination based on extract rules
let tmp_file = File::open(&tmp_path)?;
let gz = GzDecoder::new(io::BufReader::new(tmp_file));
let mut archive = Archive::new(gz);
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();
// Skip directory entries
if entry_str.ends_with('/') {
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 {
ExtractionRule::File {
tarball_path,
dest_path,
} => (tarball_path == relative).then(|| dest_path.clone()),
ExtractionRule::RewritePrefix { prefix, dest_dir } => relative
.strip_prefix(prefix)
.map(|tail| dest_dir.join(tail)),
});
if let Some(dest_path) = dest {
if let Some(parent) = dest_path.parent() {
fs::create_dir_all(parent)?;
}
let mut dest_file = File::create(&dest_path)?;
io::copy(&mut entry, &mut dest_file)?;
}
}
fs::remove_file(&tmp_path)?;
Ok(())
}
#[derive(Debug)]
pub enum GithubError {
Http { status: u16, url: String },
RateLimited { retry_after_s: u64 },
Network(reqwest::Error),
Io(io::Error),
}
impl fmt::Display for GithubError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Http { status, url } => write!(f, "HTTP error {status}: {url}"),
Self::RateLimited { retry_after_s } => {
write!(f, "Rate limited – retry after {retry_after_s}s")
}
Self::Network(e) => write!(f, "Network error: {e}"),
Self::Io(e) => write!(f, "I/O error: {e}"),
}
}
}
impl std::error::Error for GithubError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Network(e) => Some(e),
Self::Io(e) => Some(e),
_ => None,
}
}
}
impl From<reqwest::Error> for GithubError {
fn from(e: reqwest::Error) -> Self {
Self::Network(e)
}
}
impl From<io::Error> for GithubError {
fn from(e: io::Error) -> Self {
Self::Io(e)
}
}
-153
View File
@@ -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);
}
}
-288
View File
@@ -1,288 +0,0 @@
use crate::{
Game,
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 arboard::Clipboard;
use clap::Parser;
use mlua::{Lua, Result as LuaResult, Table};
use std::{
cell::{Cell, RefCell},
path::PathBuf,
rc::Rc,
};
macro_rules! socket_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 [`PoBContext`] into
/// the ContextSocket and "unplug" them afterwards.
pub struct ContextSocket {
window: Cell<*const WindowState>,
input: Cell<*const InputState>,
fonts: Cell<*mut Fonts>,
texture_manager: Cell<*mut WrappedTextureManager>,
clipboard: Cell<*mut Clipboard>,
current_working_dir: Cell<*mut PathBuf>,
layers: Cell<*mut Layers>,
needs_restart: Cell<*mut bool>,
is_dpi_aware: Cell<*mut bool>,
}
impl ContextSocket {
pub fn new() -> &'static Self {
Box::leak(Box::new(Self {
window: Cell::new(std::ptr::null()),
input: Cell::new(std::ptr::null()),
fonts: Cell::new(std::ptr::null_mut()),
texture_manager: Cell::new(std::ptr::null_mut()),
clipboard: Cell::new(std::ptr::null_mut()),
current_working_dir: Cell::new(std::ptr::null_mut()),
layers: Cell::new(std::ptr::null_mut()),
needs_restart: 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(&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.clipboard.set(&mut ctx.app.clipboard);
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.is_dpi_aware.set(&mut ctx.pob.is_dpi_aware);
}
pub fn clear(&self) {
self.window.set(std::ptr::null());
self.input.set(std::ptr::null());
self.fonts.set(std::ptr::null_mut());
self.texture_manager.set(std::ptr::null_mut());
self.clipboard.set(std::ptr::null_mut());
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.is_dpi_aware.set(std::ptr::null_mut());
}
socket_accessor!(window: &WindowState);
socket_accessor!(input: &InputState);
socket_accessor!(fonts: &mut Fonts);
socket_accessor!(texture_manager: &mut WrappedTextureManager);
socket_accessor!(clipboard: &mut Clipboard);
socket_accessor!(current_working_dir: &mut PathBuf);
socket_accessor!(layers: &mut Layers);
socket_accessor!(needs_restart: &mut bool);
socket_accessor!(is_dpi_aware: &mut bool);
}
pub enum PoBEvent {
Init,
Exit,
Frame,
KeyDown(&'static str, bool),
KeyUp(&'static str),
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() -> anyhow::Result<Self> {
let subscript_manager = Rc::new(RefCell::new(SubscriptManager::new()));
let lua = Self::create_lua_state()?;
register_subscript_globals(&lua, &subscript_manager)?;
Ok(Self {
lua,
subscript_manager,
})
}
fn create_lua_state() -> LuaResult<Lua> {
// SAFETY: use `unsafe_new` to allow loading of C modules
let lua = unsafe { Lua::unsafe_new() };
// expose build arg to lua
let args = Args::parse();
let args_table = lua.create_sequence_from(std::iter::once(args.build_path))?;
lua.globals().set("arg", args_table)?;
Self::register_package_paths(&lua)?;
// register "socket"
let socket = ContextSocket::new();
lua.set_app_data(socket);
// register callbacks
api::register_globals(&lua)?;
Ok(lua)
}
/// Loads and executes PoB's Launch.lua script
pub fn launch(&self, ctx: &mut PoBContext) -> LuaResult<()> {
let socket = self.lua.app_data_ref::<&'static ContextSocket>().unwrap();
socket.set(ctx);
let script_dir = Game::script_dir();
change_working_directory(script_dir.as_path())?;
self.load(script_dir.join("Launch.lua")).exec()?;
socket.clear();
Ok(())
}
pub fn restart(&mut self, ctx: &mut PoBContext) -> LuaResult<()> {
self.lua = Self::create_lua_state()?;
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, ctx: &mut PoBContext) {
profiling::scope!("handle_subscripts");
let subscript_events = self.subscript_manager.borrow_mut().process(self);
// Handle finished/errored subscripts.
for event in subscript_events {
match event {
SubscriptResult::SubscriptFinished { id, return_values } => {
self.handle_event(PoBEvent::SubFinished { id, return_values }, ctx)
.unwrap();
}
SubscriptResult::SubscriptError { id, error } => {
self.handle_event(PoBEvent::SubError { id, error }, ctx)
.unwrap();
}
}
}
}
pub fn handle_event(&self, event: PoBEvent, ctx: &mut PoBContext) -> LuaResult<()> {
profiling::scope!("handle_event", format!("{}", event));
// "Plug" references into "socket"
let socket = self.lua.app_data_ref::<&'static ContextSocket>().unwrap();
socket.set(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, double_click))
}
PoBEvent::KeyUp(key) => get_callback(&self.lua, "OnKeyUp")?.call::<()>(key),
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 "socket"
socket.clear();
handler_result
}
/// Adds "${script_dir}/lua" to package path
pub fn register_package_paths(lua: &Lua) -> LuaResult<()> {
let script_dir = Game::script_dir();
let package: Table = lua.globals().get("package")?;
let mut package_path: String = package.get("path")?;
package_path.push(';');
package_path.push_str(script_dir.join("lua/?.lua").to_str().unwrap());
package_path.push(';');
package_path.push_str(script_dir.join("lua/?/init.lua").to_str().unwrap());
package.set("path", package_path)?;
Ok(())
}
}
impl std::ops::Deref for LuaInstance {
type Target = Lua;
fn deref(&self) -> &Self::Target {
&self.lua
}
}
+79 -11
View File
@@ -1,31 +1,35 @@
use crate::{
app::App,
args::{Args, Game},
};
#![cfg_attr(windows, windows_subsystem = "windows")]
use crate::{app::App, args::Args};
use clap::Parser;
use std::path::{Path, PathBuf};
use winit::event_loop::EventLoop;
mod api;
mod app;
mod args;
mod batcher;
mod chooser;
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;
fn main() -> anyhow::Result<()> {
#[cfg(windows)]
attach_parent_console();
profiling::register_thread!("Main Thread");
env_logger::init();
@@ -39,12 +43,76 @@ fn main() -> anyhow::Result<()> {
};
let args = Args::parse();
Game::init(args.game);
let script_dir = find_nearby_launch_script();
let mut app = App::new()?;
let mut app = App::new(args, script_dir)?;
let event_loop = EventLoop::with_user_event().build()?;
event_loop.run_app(&mut app)?;
Ok(())
}
/// Reuse a terminal's console without opening one for Explorer or Start Menu launches.
#[cfg(windows)]
fn attach_parent_console() {
use windows_sys::Win32::{
Foundation::{GetHandleInformation, INVALID_HANDLE_VALUE},
System::Console::{
ATTACH_PARENT_PROCESS, AttachConsole, GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE,
STD_OUTPUT_HANDLE, SetStdHandle,
},
};
let inherited = [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE].map(|stream| {
// SAFETY: These calls only query process-owned handles; no ownership is transferred.
let handle = unsafe { GetStdHandle(stream) };
let mut flags = 0;
let valid = !handle.is_null()
&& handle != INVALID_HANDLE_VALUE
&& unsafe { GetHandleInformation(handle, &mut flags) } != 0;
(stream, handle, valid)
});
// SAFETY: Called before logging, argument parsing, or application threads start.
// Attaching can replace the standard handle table, so restore each valid inherited
// handle independently, including when only stdout or stderr was redirected.
unsafe {
if AttachConsole(ATTACH_PARENT_PROCESS) != 0 {
for (stream, handle, valid) in inherited {
if valid {
SetStdHandle(stream, handle);
}
}
}
}
}
/// Search for the Launch.lua file in nearby locations
fn find_nearby_launch_script() -> Option<PathBuf> {
let mut candidates = vec![Path::new("Launch.lua"), Path::new("src/Launch.lua")];
if let Ok(cwd) = std::env::current_dir()
&& cwd.ends_with("runtime")
{
candidates.push(Path::new("../src/Launch.lua"));
}
for candidate in candidates {
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
}
+2
View File
@@ -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
View File
@@ -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)
}
}
-65
View File
@@ -1,65 +0,0 @@
use crate::{
app::AppState, installer::InstallMode, pob::PoBMode, renderer::primitives::ClippedPrimitive,
};
use winit::{event::MouseButton, keyboard::KeyCode};
pub enum AppEvent {
KeyDown {
code: KeyCode,
},
KeyUp {
code: KeyCode,
},
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,
}
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),
}
}
}
+446 -118
View File
@@ -1,149 +1,477 @@
use crate::{
app::AppState,
dpi::{LogicalRect, LogicalSize},
input::{keycode_as_str, mousebutton_as_str},
layers::Layers,
lua::{LuaInstance, PoBContext, PoBEvent},
mode::{AppEvent, ModeFrameOutput, ModeTransition},
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::{
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,
import_url: Option<String>,
/// 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>>,
import_url: Option<String>,
) -> anyhow::Result<Self> {
let ctx = Context::new(script_dir, fonts, texture_manager);
let lua = Self::create_lua(ctx, SubscriptManager::default(), import_url.as_deref())?;
let lua_instance = LuaInstance::new()?;
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,
import_url,
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,
import_url: Option<&str>,
) -> 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_table = lua.create_sequence_from(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;
Ok(ModeFrameOutput {
primitives: self.state.layers.consume_layers(),
can_elide: identical,
})
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 { code } => {
if let Some(key_string) = keycode_as_str(code) {
let pob_event = PoBEvent::KeyDown(key_string, false);
self.lua_instance.handle_event(pob_event, &mut ctx)?;
}
}
AppEvent::KeyUp { code } => {
if let Some(key_string) = keycode_as_str(code) {
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", false), &mut ctx)?;
self.lua_instance
.handle_event(PoBEvent::KeyUp("WHEELUP"), &mut ctx)?;
} else if delta < 0.0 {
self.lua_instance
.handle_event(PoBEvent::KeyDown("WHEELDOWN", false), &mut ctx)?;
self.lua_instance
.handle_event(PoBEvent::KeyUp("WHEELDOWN"), &mut ctx)?;
}
}
AppEvent::CharacterInput { ch } => {
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(())
}
fn reset_viewport(&mut self, size: LogicalSize<u32>) {
self.state
.layers
.set_viewport(LogicalRect::from_size(size).cast());
/// 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.import_url.as_deref())?;
Self::launch(&self.lua, &script_dir)?;
Ok(())
}
/// 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()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fonts::FontDefinitions;
use std::{fs, process::Command};
#[test]
fn launch_and_restart_preserve_import_and_script_directory() {
const CHILD_ENV: &str = "RPOB_LUA_RESTART_TEST_CHILD";
// Launch changes the process CWD. Isolate it from concurrently running tests.
if std::env::var_os(CHILD_ENV).is_none() {
let output = Command::new(std::env::current_exe().unwrap())
.args([
"--exact",
"pob::tests::launch_and_restart_preserve_import_and_script_directory",
"--nocapture",
])
.env(CHILD_ENV, "1")
.output()
.unwrap();
assert!(
output.status.success(),
"Lua fixture failed:\n{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
return;
}
let original_dir = std::env::current_dir().unwrap();
let fixture_dir =
std::env::temp_dir().join(format!("rpob-lua-test-{}", std::process::id()));
fs::create_dir(&fixture_dir).unwrap();
let script_dir = fixture_dir.canonicalize().unwrap();
fs::write(script_dir.join("relative.txt"), "script directory").unwrap();
fs::write(
script_dir.join("Launch.lua"),
r#"
SetMainObject({
OnInit = function()
local file = assert(io.open("relative.txt", "r"))
assert(file:read("*a") == "script directory")
file:close()
initialized_arg = arg[1]
end,
CanExit = function() return allow_exit end,
})
allow_exit = true
"#,
)
.unwrap();
for import_url in [Some("pob://pobbin/restart-test"), None] {
let mut pob = PathOfBuilding::new(
&script_dir,
Rc::new(RefCell::new(Fonts::new(FontDefinitions::default()))),
Rc::new(RefCell::new(TextureManager::new())),
import_url.map(str::to_owned),
)
.unwrap();
assert_eq!(
pob.lua
.globals()
.get::<Option<String>>("initialized_arg")
.unwrap()
.as_deref(),
import_url
);
assert!(pob.can_exit());
pob.lua
.load("arg[1] = 'modified'; allow_exit = false; Restart()")
.exec()
.unwrap();
assert!(!pob.can_exit());
assert!(pob.update().unwrap().is_none());
assert_eq!(
pob.lua
.globals()
.get::<Option<String>>("initialized_arg")
.unwrap()
.as_deref(),
import_url
);
assert_eq!(std::env::current_dir().unwrap(), script_dir);
assert_eq!(pob.ctx().script_dir, script_dir);
assert!(!pob.ctx().needs_restart);
assert!(pob.can_exit());
}
std::env::set_current_dir(original_dir).unwrap();
fs::remove_dir_all(fixture_dir).unwrap();
}
}
+224
View File
@@ -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(),))
}
+56
View File
@@ -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)
}
+13
View File
@@ -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())
}
+41
View File
@@ -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,
}
}
}
+57
View File
@@ -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() {
+43
View File
@@ -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(())
}
+322
View File
@@ -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(())
}
+127
View File
@@ -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))
}
+55
View File
@@ -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
}
+58
View File
@@ -0,0 +1,58 @@
use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Value};
use std::{fs, path::PathBuf};
use crate::{
pob::Context,
util::{change_working_directory, get_executable_dir},
};
pub fn get_user_path(l: &Lua, _: ()) -> LuaResult<PathBuf> {
let ctx = l.app_data_ref::<Context>().unwrap();
Ok(ctx.script_dir.join("userdata"))
}
// parent directory of Launch.lua script
pub fn get_script_path(l: &Lua, _: ()) -> LuaResult<PathBuf> {
let ctx = l.app_data_ref::<Context>().unwrap();
Ok(ctx.script_dir.clone())
}
// parent directory of executable
pub fn get_runtime_path(_: &Lua, _: ()) -> LuaResult<PathBuf> {
Ok(get_executable_dir().unwrap_or_default())
}
pub fn get_work_dir(l: &Lua, _: ()) -> LuaResult<PathBuf> {
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 mut ctx = l.app_data_mut::<Context>().unwrap();
if change_working_directory(&path).is_ok() {
ctx.current_working_dir = path.into();
}
Ok(())
}
pub fn make_dir(l: &Lua, path: String) -> LuaResult<MultiValue> {
match fs::create_dir_all(path) {
// callers expect first return value to be true on success
Ok(()) => (true).into_lua_multi(l),
// otherwise it is set to Nil and second return value is set to error msg
Err(err) => (Value::Nil, err.to_string()).into_lua_multi(l),
}
}
pub fn remove_dir(l: &Lua, (path, recursive): (String, Option<bool>)) -> LuaResult<MultiValue> {
let result = if recursive.unwrap_or(false) {
fs::remove_dir_all(&path)
} else {
fs::remove_dir(&path)
};
match result {
Ok(()) => (true).into_lua_multi(l),
Err(err) => (Value::Nil, err.to_string()).into_lua_multi(l),
}
}
+270
View File
@@ -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, 1);
let color = Srgba::from_escape_code(esc_str);
ctx.recorder.set_draw_color(color);
}
// rgb
3 => {
let r = f32_from_stack!(state, 1);
let g = f32_from_stack!(state, 2);
let b = f32_from_stack!(state, 3);
let color = Srgba::new_f32(r, g, b, 1.0);
ctx.recorder.set_draw_color(color);
}
// rgba
4 => {
let r = f32_from_stack!(state, 1);
let g = f32_from_stack!(state, 2);
let b = f32_from_stack!(state, 3);
let a = f32_from_stack!(state, 4);
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, 1);
let y = f32_from_stack!(state, 2);
let w = f32_from_stack!(state, 3);
let h = f32_from_stack!(state, 4);
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, 1);
ctx.recorder.set_draw_layer(layer, 0);
}
2 => {
let layer = match unsafe { ffi::lua_type(state, 1) } {
ffi::LUA_TNIL => None,
ffi::LUA_TNUMBER => {
let layer = i32_from_stack!(state, 1);
Some(layer)
}
t => panic!("Expected Nil or Number, got {t:?}"),
};
let sublayer = i32_from_stack!(state, 2);
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, 1) };
// left, top, width, height
let x = f32_from_stack!(state, 2);
let y = f32_from_stack!(state, 3);
let w = f32_from_stack!(state, 4);
let h = f32_from_stack!(state, 5);
let rect = Rect::from_origin_and_size(Point::new(x, y), Size::new(w, h));
// u1, v1, u2, v2
let mut i = 6;
let uv = if parse_uv {
let u1 = f32_from_stack!(state, i);
let v1 = f32_from_stack!(state, i + 1);
let u2 = f32_from_stack!(state, i + 2);
let v2 = f32_from_stack!(state, 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, 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, 1) };
// x1, y1, x2, y2, ...
let x1 = f32_from_stack!(state, 2);
let y1 = f32_from_stack!(state, 3);
let x2 = f32_from_stack!(state, 4);
let y2 = f32_from_stack!(state, 5);
let x3 = f32_from_stack!(state, 6);
let y3 = f32_from_stack!(state, 7);
let x4 = f32_from_stack!(state, 8);
let y4 = f32_from_stack!(state, 9);
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 = 10;
let uv = if parse_uv {
let u1 = f32_from_stack!(state, i);
let v1 = f32_from_stack!(state, i + 1);
let u2 = f32_from_stack!(state, i + 2);
let v2 = f32_from_stack!(state, i + 3);
let u3 = f32_from_stack!(state, i + 4);
let v3 = f32_from_stack!(state, i + 5);
let u4 = f32_from_stack!(state, i + 6);
let v4 = f32_from_stack!(state, 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, 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))
});
}
}
+42
View File
@@ -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!()
}
+708
View File
@@ -0,0 +1,708 @@
use crate::{
color::Srgba,
dpi::LogicalPoint,
fonts::{Alignment, FontStyle, LayoutJob},
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 x = f32_from_stack!(state, 1);
let y = f32_from_stack!(state, 2);
let alignment = if unsafe { ffi::lua_isnil(state, 3) } != 0 {
"LEFT"
} else {
str_from_stack!(state, 3)
};
let line_height = i32_from_stack!(state, 4);
let font_type = str_from_stack!(state, 5);
let text = str_from_stack!(state, 6);
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 layout_origin = position + layout.anchor_offset(halign);
ctx.recorder
.draw_glyphs(&layout, layout_origin, is_absolute_position, scale_factor);
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 line_height = i32_from_stack!(state, 1);
let font_type = str_from_stack!(state, 2);
let text = str_from_stack!(state, 3);
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);
}
}
+55
View File
@@ -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),
}
}
+23
View File
@@ -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(())
}
+29
View File
@@ -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)
}
+25
View File
@@ -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;
+369
View File
@@ -0,0 +1,369 @@
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)),
}
}
/// A Lua callback set via `setopt_*function`.
///
/// `context` is set when an object is passed to the callback setter. In that case `function` is
/// the object's method and is invoked as `function(context, data)`.
struct Callback {
function: RegistryKey,
context: Option<RegistryKey>,
}
impl Callback {
fn resolve(&self, lua: &Lua) -> LuaResult<(mlua::Function, Option<mlua::Value>)> {
let function = lua.registry_value(&self.function)?;
let context = self
.context
.as_ref()
.map(|key| lua.registry_value::<mlua::Value>(key))
.transpose()?;
Ok((function, context))
}
fn remove(self, lua: &Lua) -> LuaResult<()> {
lua.remove_registry_value(self.function)?;
if let Some(key) = self.context {
lua.remove_registry_value(key)?;
}
Ok(())
}
}
/// Interprets write/header callback return values like Lua-cURL does.
fn callback_size(data_len: usize, results: &mlua::MultiValue) -> usize {
let Some(value) = results.front() else {
return data_len;
};
match value {
mlua::Value::Nil => 0,
mlua::Value::Integer(n) => (*n).max(0) as usize,
mlua::Value::Number(n) if *n >= 0.0 => *n as usize,
mlua::Value::Number(_) => 0,
mlua::Value::Boolean(false) => 0,
_ => data_len,
}
}
#[derive(Default)]
pub struct EasyHandle {
easy: Option<Easy>,
write_callback: Option<Callback>,
header_callback: Option<Callback>,
}
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(callback) = self.write_callback.take() {
callback.remove(lua)?;
}
if let Some(callback) = self.header_callback.take() {
callback.remove(lua)?;
}
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<Callback>,
value: mlua::Value,
method: &str,
) -> LuaResult<()> {
let new_callback = match value {
mlua::Value::Nil => None,
mlua::Value::Function(function) => Some(Callback {
function: lua.create_registry_value(function)?,
context: None,
}),
// Lua-cURL can also accept objects with a method of the given name,
// e.g. a file handle returned by `io.open` with a `write` method.
// looks a bit awkwards but it works...
value @ (mlua::Value::Table(_) | mlua::Value::UserData(_)) => {
let function: mlua::Function = lua
.load("local object, key = ...; return object[key]")
.call((value.clone(), method))?;
Some(Callback {
function: lua.create_registry_value(function)?,
context: Some(lua.create_registry_value(value)?),
})
}
_ => return Err(LuaError::runtime("invalid object type")),
};
if let Some(old_callback) = slot.take() {
old_callback.remove(lua)?;
}
*slot = new_callback;
Ok(())
}
fn perform(&mut self, lua: &Lua) -> LuaResult<()> {
let write_fn = self
.write_callback
.as_ref()
.map(|callback| callback.resolve(lua))
.transpose()?;
let header_fn = self
.header_callback
.as_ref()
.map(|callback| callback.resolve(lua))
.transpose()?;
let transfer_result = {
let mut transfer = self.curl()?.transfer();
if let Some((function, context)) = write_fn {
transfer
.write_function(move |data| {
let Ok(argument) = lua.create_string(data) else {
return Ok(0);
};
let result = match &context {
Some(context) => {
function.call::<mlua::MultiValue>((context.clone(), argument))
}
None => function.call::<mlua::MultiValue>(argument),
};
match result {
Ok(results) => Ok(callback_size(data.len(), &results)),
Err(_) => Ok(0),
}
})
.map_err(LuaError::external)?;
}
if let Some((function, context)) = header_fn {
transfer
.header_function(move |data| {
let Ok(argument) = lua.create_string(data) else {
return false;
};
match &context {
Some(context) => {
function.call::<mlua::MultiValue>((context.clone(), argument))
}
None => function.call::<mlua::MultiValue>(argument),
}
.map(|results| callback_size(data.len(), &results) == data.len())
.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, "write")
});
methods.add_method_mut("setopt_headerfunction", |lua, this, value: mlua::Value| {
Self::set_callback(lua, &mut this.header_callback, value, "header")
});
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)
});
}
}
+243
View File
@@ -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)),
}
},
);
}
}
+158
View File
@@ -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)
});
}
}
+716
View File
@@ -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)?,
})
}
+323
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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;
}
-119
View File
@@ -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,
}
+1 -1
View File
@@ -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);
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more