Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fac1ec00da | ||
|
|
b173d75e98 | ||
|
|
6ca825990d | ||
|
|
b1cde7e783 | ||
|
|
1d7f87f71d | ||
|
|
9f6a047867 | ||
|
|
70e896b3cb | ||
|
|
6a604fe4d8 | ||
|
|
18a952d4c1 | ||
|
|
94cbdcf0b1 | ||
|
|
297118cfc1 | ||
|
|
20303d5ddc | ||
|
|
72a6da0ca3 | ||
|
|
61862ef792 | ||
|
|
74b35b0120 | ||
|
|
0c7e80d896 | ||
|
|
409be9d31a | ||
|
|
5ab3161bf5 | ||
|
|
673cddfff6 | ||
|
|
eabc3780c9 | ||
|
|
4f2ee4256a | ||
|
|
4aac0ac70b | ||
|
|
f6ccbf59bc | ||
|
|
ac9faba229 | ||
|
|
1e7e9dfc41 | ||
|
|
543b489b11 | ||
|
|
2e463dab3a | ||
|
|
6584b2f92f | ||
|
|
4efc2f3968 | ||
|
|
365e4ad732 | ||
|
|
9f5f1f669d | ||
|
|
2953ab1ee3 | ||
|
|
976fcdc354 | ||
|
|
c7fee5beeb | ||
|
|
3dfef1961d | ||
|
|
b82225ce08 | ||
|
|
227aecb8f6 | ||
|
|
3d0cad3312 | ||
|
|
560f08cfb9 | ||
|
|
17c73925bf | ||
|
|
e7a36c3129 | ||
|
|
01a92f1edf | ||
|
|
744aa20496 | ||
|
|
e351ee588a | ||
|
|
b06ec4be7b | ||
|
|
8883e93d2b | ||
|
|
0377141e4f | ||
|
|
d712c4ea85 | ||
|
|
ffe3523f26 | ||
|
|
2e98159083 | ||
|
|
4f9f84446d | ||
|
|
7468bdf5de | ||
|
|
cfb49218f7 | ||
|
|
953a920a23 | ||
|
|
146d7a5fb9 |
No files matched your search
@@ -13,10 +13,10 @@ env:
|
||||
RUST_BACKTRACE: 1
|
||||
|
||||
jobs:
|
||||
# Make sure that the program correctly builds,
|
||||
# passes format and lints, as well as tests
|
||||
build-test:
|
||||
name: Build, check and test
|
||||
# Type-checks the daemon on Linux: formatting, and clippy over every target, which compiles
|
||||
# the cfg(target_os = "linux") paths without linking them. Linking is the Windows job's.
|
||||
check:
|
||||
name: Check and lint (Linux)
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
@@ -34,21 +34,56 @@ jobs:
|
||||
run: cargo fmt --check
|
||||
|
||||
- name: Install system build dependencies
|
||||
# pkg-config finds libobs for its build script; nothing is linked here, so the distro's
|
||||
# version is enough even though the Windows build links a newer obs.lib.
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y pkg-config libglib2.0-dev libobs-dev libc6-dev clang libwayland-client0 libwayland-dev
|
||||
|
||||
- name: Build
|
||||
run: cargo build
|
||||
env:
|
||||
RUSTFLAGS: -Dwarnings
|
||||
sudo apt-get install -y pkg-config libglib2.0-dev libobs-dev libc6-dev clang libwayland-dev
|
||||
|
||||
- name: Lint
|
||||
run: cargo clippy --all-targets --all-features
|
||||
|
||||
- name: Run tests with verbose logging (timeout 30min)
|
||||
run: timeout 30m cargo test -- --nocapture
|
||||
env:
|
||||
RUST_LOG: debug
|
||||
# The daemon ships on Windows and links Windows' obs.lib, so that is the build worth checking.
|
||||
# It cross-compiles from the Linux runner: obs.lib rides with the libobs crate, and cargo-xwin
|
||||
# brings the MSVC runtime and the Windows SDK. Tests need a machine that can run the exe, so
|
||||
# they stay local: `cargo test` in record-daemon on Windows.
|
||||
build:
|
||||
name: Build (Windows x64)
|
||||
runs-on: ubuntu-latest
|
||||
defaults:
|
||||
run:
|
||||
working-directory: record-daemon
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v6
|
||||
|
||||
# TODO: Add windows native builds
|
||||
- name: Install Rust toolchain
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: x86_64-pc-windows-msvc
|
||||
|
||||
- name: Install the cross linker
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y clang lld llvm
|
||||
|
||||
- name: Install cargo-xwin
|
||||
run: cargo install cargo-xwin --locked
|
||||
|
||||
- name: Build
|
||||
# libobs-wrapper's build script asks for X11 and Wayland through #[cfg], which it
|
||||
# resolves against the machine running the script rather than the target: a Linux
|
||||
# host cross-building for Windows asks the linker for two libraries that cannot
|
||||
# exist there. Empty archives on the search path answer it without adding anything
|
||||
# to the exe.
|
||||
env:
|
||||
RUSTFLAGS: -Dwarnings -L native=/tmp/xwin-stubs
|
||||
run: |
|
||||
mkdir -p /tmp/xwin-stubs
|
||||
printf 'void stub(void) {}\n' > /tmp/xwin-stub.c
|
||||
clang --target=x86_64-pc-windows-msvc -c /tmp/xwin-stub.c -o /tmp/xwin-stub.obj
|
||||
libtool=$(command -v llvm-lib || ls /usr/lib/llvm-*/bin/llvm-lib | head -1)
|
||||
for lib in X11 wayland-client; do
|
||||
"$libtool" /out:/tmp/xwin-stubs/$lib.lib /tmp/xwin-stub.obj
|
||||
done
|
||||
cargo xwin build --target x86_64-pc-windows-msvc
|
||||
@@ -0,0 +1 @@
|
||||
/.rhema/
|
||||
@@ -0,0 +1,37 @@
|
||||
# Working in this repository
|
||||
|
||||
The repository holds two Rust programs: `record-daemon/` (the recorder) and `app/` (the rune
|
||||
front end). `tauri-app/` is the old front end, kept for reference.
|
||||
|
||||
## Before every commit
|
||||
|
||||
In `app/` and in `record-daemon/`, all of these must pass:
|
||||
|
||||
```sh
|
||||
cargo fmt
|
||||
cargo clippy --all-targets -- -D warnings
|
||||
cargo test
|
||||
```
|
||||
|
||||
`cargo build` must print no warning for these crates. The vendored crates under `app/vendor/`
|
||||
and the rune checkout can print their own; they are silenced at their crate root, so do not add
|
||||
allows in our own code to hide a warning that is ours to fix.
|
||||
|
||||
For UI work, check the screen without a window and look at the PNG:
|
||||
|
||||
```sh
|
||||
cd app
|
||||
cargo run -- --snap /tmp/screen.png --scene history
|
||||
cargo run -- --snap /tmp/live.png --live --at 40 # real daemon and recordings
|
||||
```
|
||||
|
||||
## Commit messages
|
||||
|
||||
History uses `<area>: <imperative summary>`, for example `app: open the review screen from a
|
||||
card` or `record-daemon: stop writing a log per game`. Lowercase after the colon, no trailing
|
||||
period, subject at most 72 characters. The body says why, wrapped at 80 columns.
|
||||
|
||||
## Rune gaps
|
||||
|
||||
`docs/rune-upstream.md` lists the faults we work around in rune, with the file to change and how
|
||||
to check a fix.
|
||||
@@ -0,0 +1,3 @@
|
||||
/target
|
||||
/dist
|
||||
/.rhema
|
||||
Generated
+5009
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,50 @@
|
||||
[package]
|
||||
name = "leaguerecorder"
|
||||
version = "0.3.1"
|
||||
edition = "2024"
|
||||
description = "Native League Recorder desktop app (rune)"
|
||||
license = "MIT"
|
||||
|
||||
[[bin]]
|
||||
name = "leaguerecorder"
|
||||
path = "src/main.rs"
|
||||
|
||||
[build-dependencies]
|
||||
# Bakes icons/icon.ico into the exe's resources (build.rs), for Explorer and shortcuts.
|
||||
winresource = "0.1"
|
||||
|
||||
[dependencies]
|
||||
rune = { git = "https://github.com/anomalyco/rune", rev = "4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1" }
|
||||
rune-kit = { git = "https://github.com/anomalyco/rune", rev = "4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1" }
|
||||
rune-notify = { git = "https://github.com/anomalyco/rune", rev = "4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1" }
|
||||
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
directories = "6"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "std", "serde"] }
|
||||
tokio = { version = "1", features = ["rt", "net", "io-util", "time", "sync"] }
|
||||
uuid = { version = "1", features = ["v4", "serde"] }
|
||||
ffmpeg-sidecar = "2.7"
|
||||
ureq = "3.5"
|
||||
# PNG decode of the bundled tray icon; the same crate and features rune itself uses.
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winreg = "0.56"
|
||||
windows = { version = "0.62", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Console",
|
||||
"Win32_System_Diagnostics_ToolHelp",
|
||||
"Win32_System_Threading",
|
||||
] }
|
||||
|
||||
# Rune is patched in the workspace that builds it. A dependency's `[patch]` doesn't apply to
|
||||
# the app that depends on it, so these three copies (from rune's own vendor/) are repeated here.
|
||||
[patch.crates-io]
|
||||
wgpu-hal = { path = "vendor/wgpu-hal" }
|
||||
winit = { path = "vendor/winit" }
|
||||
parley_engine = { path = "vendor/parley_engine" }
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
strip = true
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
# League Recorder (rune app)
|
||||
|
||||
The native replacement for `tauri-app`. It talks to `record-daemon` over the daemon's existing
|
||||
named-pipe protocol and draws with [rune](https://github.com/anomalyco/rune).
|
||||
|
||||
## Run it
|
||||
|
||||
```sh
|
||||
cargo run
|
||||
```
|
||||
|
||||
The binary is a windowed app on Windows (`windows_subsystem = "windows"` in `main.rs`), so
|
||||
launching it from Explorer, the Run key or the login item never opens a console. The printing
|
||||
modes still work from a shell: `attach_console` borrows the console of whatever started the app,
|
||||
and nothing happens when nothing did.
|
||||
|
||||
The app starts the daemon if it isn't running, then reads its settings and status. `cargo run --
|
||||
--probe` does the same without a window and prints the daemon's answers; `cargo run -- --games`
|
||||
prints how many timelines load from disk.
|
||||
|
||||
Headless renders, for looking at a screen without a window:
|
||||
|
||||
```sh
|
||||
cargo run -- --snap history.png --scene history
|
||||
cargo run -- --snap settings.png --scene settings
|
||||
cargo run -- --snap recording.png --scene recording
|
||||
cargo run -- --snap audio.png --scene audio
|
||||
cargo run -- --snap review.png --scene review
|
||||
cargo run -- --snap many.png --scene many --at 1 # 60 sample games, to see the scrollbar
|
||||
```
|
||||
|
||||
Pass `--at 1` when the screenshot depends on a laid-out size (the scrollbar does): layout callbacks
|
||||
run after the first frame.
|
||||
|
||||
`--live` renders without sample data: the app talks to the daemon and reads the real timelines
|
||||
from disk. Loading them takes a few seconds with a large history, so give it time before `--at`.
|
||||
|
||||
```sh
|
||||
cargo run -- --snap live.png --live --at 40
|
||||
```
|
||||
|
||||
Without `--live`, a headless run never starts the daemon and reads no recording: `App::new` loads
|
||||
the sample recordings from `history::sample` when it sees rune's tooling flags. Portraits still
|
||||
come from the Data Dragon cache (or download into it) so the PNGs show real champion faces.
|
||||
|
||||
## Test
|
||||
|
||||
```sh
|
||||
cargo test
|
||||
```
|
||||
|
||||
The tests pin the wire format the daemon parses (`ipc::tests`, `settings::tests`), timeline
|
||||
reading (`history::tests`), highlight clipping (`highlight::tests`) and formatting.
|
||||
|
||||
## Layout
|
||||
|
||||
| File | What it holds |
|
||||
| --- | --- |
|
||||
| `src/main.rs` | Entry point, single instance, notifications, app spec, `--probe` |
|
||||
| `src/app.rs` | App state, `poll` (daemon answers, tray events, status), screen dispatch |
|
||||
| `src/ipc.rs` | Protocol types and the named-pipe client, on a worker thread |
|
||||
| `src/daemon.rs` | Finding, starting and logging the daemon |
|
||||
| `src/settings.rs` | The daemon's settings model, field for field |
|
||||
| `src/history.rs` | Timelines from disk and the values the cards show |
|
||||
| `src/portraits.rs` | Champion portraits: the Data Dragon cache and its downloads |
|
||||
| `src/highlight.rs` | Highlight clips from kill events |
|
||||
| `src/export.rs` | ffmpeg clip export |
|
||||
| `src/os.rs` | Run key, toasts, tray icon and menu |
|
||||
| `src/ui.rs` | Colours, cards, switches, sliders, buttons |
|
||||
| `src/screens/` | Settings, match history, game review |
|
||||
|
||||
## Where this stands against TODO.txt
|
||||
|
||||
1. Skeleton: done. Rune is pinned to `4ddf696b0f13ec618fdeb80b4c9ea1a6246547f1`; the window
|
||||
opens and `--snap` writes PNGs.
|
||||
2. Pipe client: done and checked against the running daemon here: `--probe` prints status,
|
||||
settings, encoders and audio devices, and parses the settings reply with the app's model.
|
||||
Requests are typed (`Command`), the worker thread keeps the UI off tokio, and the same types
|
||||
are tested against the daemon's serde names.
|
||||
3. Settings: done. General, recording, audio and daemon tabs; device and encoder lists come from
|
||||
`getAudioDevices` and `getEncoders`; changes go out through `updateSettings`, and each
|
||||
application volume slider sends `updateAudioSource` as it moves.
|
||||
4. Match history: done. Cards read `GameHistory.vue`'s fields (result, champion portrait,
|
||||
queue, KDA, CS/m, gold/m, LP change) from the raw API responses in each timeline, with the
|
||||
queue filters. Portraits come from Data Dragon and are cached on disk (`src/portraits.rs`).
|
||||
The list holds rows, not timelines: `history::summaries` parses each file, keeps a
|
||||
`Summary`, and drops the timeline with its events and raw responses, 20 rows at a time as
|
||||
the list scrolls. Opening a row reads that one timeline again, on a thread, and the review
|
||||
screen fills in when it arrives. Peak over 313 recordings: 165 MB, down from 2.1 GB.
|
||||
5. Video: not libmpv. Rune ships a `Player` with a native surface and frame seeking
|
||||
(`Player::file`, `seek`, `duration`), which removes the OpenGL and wgpu interop question the
|
||||
TODO opened. The review screen uses it. If clip-accurate seeking turns out to be worse than
|
||||
mpv's, the three options in TODO.txt still apply; `Player` is confined to `screens/review.rs`.
|
||||
6. Game review: done. The clip fills the window at 16:9, with play/pause, +/-10 s, and a
|
||||
scrubber that marks every event; highlights (play, export) and the timeline sit in a side
|
||||
panel, one press away. ffmpeg exports each highlight.
|
||||
7. Audio channels: the recorder writes one audio stream per source, and the review screen opens
|
||||
one player per stream (`export::extract_tracks` copies each into the audio cache). Toggles
|
||||
under the transport mute a channel for listening, and clip and highlight exports mix only
|
||||
the channels left on. Recordings made before the split play as one mixed track.
|
||||
8. OS integration: tray icon with open/hide/record/quit, launch at login through the Run key,
|
||||
single instance, and toasts on recording start and stop.
|
||||
9. Installer: `packager.toml` targets NSIS and copies the daemon, its OBS files and the VC++
|
||||
runtime beside the exe. `cargo install cargo-packager --locked && cargo packager --release`.
|
||||
On the first run the app downloads ffmpeg (`--fetch-ffmpeg` does it from a shell), so clip
|
||||
export is ready before the first clip. The installer has not been run on a clean VM yet.
|
||||
10. Parity: `tauri-app` is still in the tree. Delete it once the items above are verified on a
|
||||
machine with a live League Client.
|
||||
|
||||
### Known gaps
|
||||
|
||||
- Item images are not drawn. Champion portraits download from Data Dragon on first sight and are
|
||||
cached under the user's cache directory; offline, a card falls back to initials on the
|
||||
champion's colour.
|
||||
- The installer has not been run on a clean VM, and it is unsigned: SmartScreen will warn on
|
||||
every download until it is signed. The VC++ runtime travels with it (`vendor/vcruntime`),
|
||||
because Windows ships the UCRT but not `VCRUNTIME140.dll`, `VCRUNTIME140_1.dll` or
|
||||
`MSVCP140.dll`, and the app, the daemon and every OBS plugin import them.
|
||||
|
||||
## The vendored crates
|
||||
|
||||
`vendor/` also holds `vcruntime/`: the three redistributable DLLs the installer puts beside
|
||||
the exes, copied from a machine with Visual Studio's runtime installed.
|
||||
|
||||
`vendor/` holds three crates copied from rune's own `vendor/`: `wgpu-hal`, `winit` and
|
||||
`parley_engine`. Rune builds against patched copies of these, and a dependency's
|
||||
`[patch.crates-io]` does not apply to the app that depends on it, so `Cargo.toml` repeats the
|
||||
patches here. They match the rune rev above; when the rev moves, refresh them from that checkout:
|
||||
|
||||
```sh
|
||||
cp -r ../rune/vendor/{wgpu-hal,winit,parley_engine} vendor/
|
||||
```
|
||||
@@ -0,0 +1,75 @@
|
||||
Rune app (replaces tauri-app)
|
||||
|
||||
Decided
|
||||
- UI framework: rune (github.com/anomalyco/rune, pin a dev rev). gpui is the
|
||||
fallback if rune fights back. Decide via a time-boxed spike on the Settings
|
||||
screen; it exercises switches, dropdowns, tables and text input.
|
||||
- Video: libmpv2 crate (repo kohsine/libmpv-rs, v7.0.1, render feature on by
|
||||
default). Requires libmpv >= 2.0 (mpv 0.35+); bundle libmpv-2.dll from the
|
||||
shinchiro mpv-winbuild mpv-dev archive, same as we bundle obs.dll.
|
||||
- Installers: cargo-packager (CrabNebula), NSIS target. Replaces what the
|
||||
Tauri bundler gave us. Revisit plain NSIS or Inno in CI if cargo-packager
|
||||
lags.
|
||||
|
||||
Open question before the spike commits to a render path
|
||||
- libmpv2's render API is OpenGL-based (anlumo's example renders to an SDL2
|
||||
GL window) and rune/gpui render with wgpu. Options, in order:
|
||||
1. software render into an RGBA buffer, upload as a texture each frame;
|
||||
need to verify libmpv2 exposes MPV_RENDER_PARAM_SW (its docs only show
|
||||
the GL path)
|
||||
2. share the GL texture with wgpu (external texture interop, painful)
|
||||
3. embed a native child window with --wid and drive mpv over JSON IPC
|
||||
(mpvipc crate); this is FFI-free but mpv then owns the video surface
|
||||
Spike 1 first, fall back to 3. All recordings are H.264 today
|
||||
(jim_nvenc, amd_amf_h264, qsv, x264) so every path can decode them.
|
||||
|
||||
Initial plan
|
||||
Each phase ends with something that runs. Phase 1 doubles as the
|
||||
rune-vs-gpui decision: if the Settings screen keeps fighting the
|
||||
framework, stop and switch to gpui before writing anything else.
|
||||
|
||||
1. Skeleton: new app/ crate, rune pinned to one dev rev, window opens
|
||||
on Windows and renders headlessly to PNG.
|
||||
2. Pipe client: port daemon_ipc.rs, keep the serde types identical to
|
||||
record-daemon/src/ipc/protocol.rs. Done when the app reads settings
|
||||
and status from a running daemon.
|
||||
3. Settings screen: general, recording and audio source tabs; device
|
||||
dropdowns from getAudioDevices; volume sliders. Done when changes
|
||||
save through updateSettings and survive a daemon restart.
|
||||
4. Game history: port get_game_history, list games from the timeline
|
||||
JSON in the recordings dir. Done when it matches GameHistory.vue.
|
||||
5. Video spike: libmpv2 in a standalone example first, software render
|
||||
to RGBA and upload as a texture. Done when a clip plays and
|
||||
frame-seeks to a timestamp. Fall back to --wid plus mpvipc if the
|
||||
software path is not exposed.
|
||||
6. Game review: timeline scrubber with event markers over the video.
|
||||
Done when clicking an event seeks the video to that timestamp.
|
||||
7. OS integration: tray icon, autostart via the registry Run key,
|
||||
single instance, notifications for recording start and end.
|
||||
8. Installer: cargo-packager NSIS target with the bundle list below.
|
||||
Done when the installer works on a clean Windows VM and the app
|
||||
records a real game end to end.
|
||||
9. Parity check against tauri-app, then delete it.
|
||||
|
||||
Stable contracts
|
||||
- record-daemon does not change. The IPC protocol (IpcCommand serde types
|
||||
over named pipes) is the versioned interface between app and daemon.
|
||||
- Port tauri-app/src-tauri/src/daemon_ipc.rs (645 lines, pipe client) into
|
||||
app/ nearly as-is; it is plain Rust + tokio.
|
||||
- Port the disk-side helpers from src-tauri/src/lib.rs: get_game_history,
|
||||
export_clip, find_video_file and the ffmpeg_sidecar download logic.
|
||||
- Keep tauri-app/ working until the native app reaches feature parity.
|
||||
Build app/ as a separate crate; do not mutate tauri-app in place.
|
||||
|
||||
Installer contents
|
||||
- app exe, record-daemon.exe, obs.dll, ffmpeg sidecar, libmpv-2.dll.
|
||||
- NSIS fits our layout (small install, OBS and ffmpeg downloaded at first
|
||||
run). MSI would want a self-contained package; skip unless we need AD
|
||||
deployment.
|
||||
- Code signing: unsigned exes that hook games and open named pipes hit
|
||||
SmartScreen. Budget for an EV cert or Azure Trusted Signing before
|
||||
shipping installers.
|
||||
|
||||
OS integration to reimplement (was Tauri plugins)
|
||||
- tray icon, launch at Windows startup (registry Run key or Startup folder
|
||||
shortcut), single instance, notifications for recording start/end.
|
||||
@@ -0,0 +1,11 @@
|
||||
//! Bakes `icons/icon.ico` into the exe as its resource, so Explorer, shortcuts and the
|
||||
//! installer show the medallion the window and the tray also draw.
|
||||
|
||||
fn main() {
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
|
||||
return;
|
||||
}
|
||||
let mut resource = winresource::WindowsResource::new();
|
||||
resource.set_icon("icons/icon.ico");
|
||||
resource.compile().expect("the icon resource compiles");
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 37 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 66 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 797 KiB |
@@ -0,0 +1,42 @@
|
||||
# cargo-packager configuration for the NSIS installer (`cargo packager --release`).
|
||||
#
|
||||
# The app exe is the cargo binary. Everything the daemon needs at run time sits beside it in the
|
||||
# install root: the daemon, OBS and its data are built into record-daemon/target/release by the
|
||||
# daemon's own build and copied from there. The app downloads ffmpeg itself on the first export.
|
||||
"$schema" = "https://raw.githubusercontent.com/crabnebula-dev/cargo-packager/main/crates/packager/schema.json"
|
||||
|
||||
name = "leaguerecorder"
|
||||
product-name = "League Recorder"
|
||||
identifier = "v.leaguerecorder"
|
||||
version = "0.3.1"
|
||||
description = "Records League of Legends games through the record-daemon."
|
||||
out-dir = "dist"
|
||||
# A config file is not read from Cargo.toml, so the binary has to be named. The app crate
|
||||
# builds one.
|
||||
binaries-dir = "target/release"
|
||||
binaries = [{ path = "leaguerecorder", main = true }]
|
||||
before-packaging-command = "cargo build --release && cargo build --release --manifest-path ../record-daemon/Cargo.toml"
|
||||
formats = ["nsis"]
|
||||
icons = ["icons/icon.ico"]
|
||||
|
||||
# Everything the daemon loads from beside its exe: the binary, obs.dll and the DLLs it pulls in
|
||||
# (ffmpeg, x264, curl, srt, …), the module data and the plugins with their data. Shipping the
|
||||
# whole set keeps a first run offline; the daemon can also fetch OBS when a piece is missing.
|
||||
resources = [
|
||||
{ src = "../record-daemon/target/release/record-daemon.exe", target = "record-daemon.exe" },
|
||||
{ src = "../record-daemon/target/release/*.dll", target = "." },
|
||||
{ src = "../record-daemon/target/release/obs-*.exe", target = "." },
|
||||
{ src = "../record-daemon/target/release/data", target = "data" },
|
||||
{ src = "../record-daemon/target/release/obs-plugins", target = "obs-plugins" },
|
||||
{ src = "../record-daemon/target/release/win-capture", target = "win-capture" },
|
||||
{ src = "../record-daemon/target/release/rtmp-services", target = "rtmp-services" },
|
||||
{ src = "../record-daemon/target/release/iconengines", target = "iconengines" },
|
||||
{ src = "../record-daemon/target/release/styles", target = "styles" },
|
||||
# The C++ runtime the exes and every OBS plugin import. Windows ships the UCRT but not these,
|
||||
# so a machine without the VC++ redistributable would not start the app.
|
||||
{ src = "vendor/vcruntime/*.dll", target = "." },
|
||||
]
|
||||
|
||||
[nsis]
|
||||
compression = "lzma"
|
||||
installer-mode = "currentUser"
|
||||
+1158
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,174 @@
|
||||
//! Finding, starting and logging the record-daemon process.
|
||||
//!
|
||||
//! Ported from `tauri-app/src-tauri/src/daemon_ipc.rs`. The daemon binary ships next to the
|
||||
//! app; inside a checkout it is found in `record-daemon/target/{release,debug}`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::ipc::Client;
|
||||
|
||||
/// Set this to point the app and the daemon at a scratch directory, as scripts do.
|
||||
pub const HOME_ENV: &str = "RECORD_DAEMON_HOME";
|
||||
|
||||
/// Where the review screen keeps one audio file per track of a clip.
|
||||
pub fn audio_cache_dir() -> PathBuf {
|
||||
data_dir()
|
||||
.map(|p| p.join("audio-cache"))
|
||||
.unwrap_or_else(|| PathBuf::from("./audio-cache"))
|
||||
}
|
||||
|
||||
/// The daemon's data directory, shared with the daemon itself.
|
||||
pub fn data_dir() -> Option<PathBuf> {
|
||||
if let Some(home) = std::env::var_os(HOME_ENV).filter(|value| !value.is_empty()) {
|
||||
return Some(PathBuf::from(home).join("data"));
|
||||
}
|
||||
directories::ProjectDirs::from("com", "leaguerecorder", "record-daemon")
|
||||
.map(|dirs| dirs.data_dir().to_path_buf())
|
||||
}
|
||||
|
||||
/// Where recordings and timelines live.
|
||||
pub fn recordings_dir() -> PathBuf {
|
||||
data_dir()
|
||||
.map(|p| p.join("recordings"))
|
||||
.unwrap_or_else(|| PathBuf::from("./recordings"))
|
||||
}
|
||||
|
||||
/// Where the daemon writes its log.
|
||||
pub fn log_file() -> Option<PathBuf> {
|
||||
let dir = data_dir()?.join("logs");
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
Some(dir.join("daemon.log"))
|
||||
}
|
||||
|
||||
/// Find the record-daemon binary next to the app, in an installed `resources` folder, or in a
|
||||
/// development checkout.
|
||||
///
|
||||
/// A checkout can hold both `target/debug` and `target/release`, one of them stale; the newest
|
||||
/// build wins, so the app talks to the daemon that was built last ("cargo build" then "cargo
|
||||
/// run", rather than a release build from another week).
|
||||
pub fn find_binary() -> Option<PathBuf> {
|
||||
let name = if cfg!(windows) {
|
||||
"record-daemon.exe"
|
||||
} else {
|
||||
"record-daemon"
|
||||
};
|
||||
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
let exe_dir = exe.parent()?;
|
||||
let beside = exe_dir.join(name);
|
||||
if beside.exists() {
|
||||
return Some(beside);
|
||||
}
|
||||
if let Some(parent) = exe_dir.parent() {
|
||||
let resources = parent.join("resources").join(name);
|
||||
if resources.exists() {
|
||||
return Some(resources);
|
||||
}
|
||||
}
|
||||
if let Some(found) = newest_build(exe_dir, name) {
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
|
||||
newest_build(&std::env::current_dir().ok()?, name)
|
||||
}
|
||||
|
||||
/// The most recently built daemon in a checkout, walking up from `start`.
|
||||
fn newest_build(start: &Path, name: &str) -> Option<PathBuf> {
|
||||
let mut dir = start.to_path_buf();
|
||||
for _ in 0..6 {
|
||||
let candidates = [
|
||||
dir.join("record-daemon/target/release").join(name),
|
||||
dir.join("record-daemon/target/debug").join(name),
|
||||
];
|
||||
if let Some(found) = candidates
|
||||
.into_iter()
|
||||
.filter_map(|path| {
|
||||
let modified = std::fs::metadata(&path).ok()?.modified().ok()?;
|
||||
Some((modified, path))
|
||||
})
|
||||
.max_by_key(|(modified, _)| *modified)
|
||||
.map(|(_, path)| path)
|
||||
{
|
||||
return Some(found);
|
||||
}
|
||||
if !dir.pop() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
/// Start the daemon detached, so it outlives the app.
|
||||
pub fn spawn() -> Result<PathBuf, String> {
|
||||
let binary = find_binary().ok_or_else(|| {
|
||||
"record-daemon was not found next to the app or in record-daemon/target".to_string()
|
||||
})?;
|
||||
let log = log_file().ok_or_else(|| "no data directory for the daemon log".to_string())?;
|
||||
|
||||
let mut command = std::process::Command::new(&binary);
|
||||
command.arg("--foreground").arg("--log-file").arg(&log);
|
||||
if let Some(dir) = binary.parent() {
|
||||
// The daemon finds its bundled OBS plugin data relative to itself.
|
||||
command.current_dir(dir);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
// CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
|
||||
command.creation_flags(0x0000_0200 | 0x0000_0008);
|
||||
}
|
||||
command
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null());
|
||||
command
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start record-daemon: {e}"))?;
|
||||
Ok(binary)
|
||||
}
|
||||
|
||||
/// Wait up to `timeout` for the daemon to answer, starting it if it isn't running yet.
|
||||
pub async fn ensure_running() -> Result<(), String> {
|
||||
let client = Client::new();
|
||||
if client.is_running().await {
|
||||
return Ok(());
|
||||
}
|
||||
spawn()?;
|
||||
let deadline = std::time::Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
if client.is_running().await {
|
||||
return Ok(());
|
||||
}
|
||||
if std::time::Instant::now() >= deadline {
|
||||
return Err("record-daemon did not answer within 30 s".to_string());
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The last `n` lines of the daemon log.
|
||||
pub fn read_logs(n: usize) -> Result<String, String> {
|
||||
let path = log_file().ok_or_else(|| "no data directory for the daemon log".to_string())?;
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.map_err(|e| format!("cannot read {}: {e}", path.display()))?;
|
||||
let lines: Vec<&str> = text.lines().rev().take(n).collect();
|
||||
Ok(lines.into_iter().rev().collect::<Vec<_>>().join("\n"))
|
||||
}
|
||||
|
||||
/// The log path as text, for the About tab.
|
||||
pub fn log_path() -> String {
|
||||
log_file()
|
||||
.map(|p| p.display().to_string())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Open a folder.
|
||||
pub fn open_folder(path: &Path) {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = std::process::Command::new("explorer").arg(path).spawn();
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = path;
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
//! Clip export with ffmpeg, ported from `export_clip` and `export_clip_precise` in
|
||||
//! `tauri-app/src-tauri/src/lib.rs`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
use ffmpeg_sidecar::command::{FfmpegCommand, ffmpeg_is_installed};
|
||||
use ffmpeg_sidecar::download::{
|
||||
FfmpegDownloadProgressEvent, download_ffmpeg_package_with_progress, ffmpeg_download_url,
|
||||
unpack_ffmpeg_without_extras,
|
||||
};
|
||||
use ffmpeg_sidecar::event::{FfmpegEvent, LogLevel};
|
||||
use ffmpeg_sidecar::paths::{sidecar_dir, sidecar_path};
|
||||
|
||||
use crate::daemon;
|
||||
|
||||
/// The clips folder beside the recordings.
|
||||
pub fn clips_dir() -> PathBuf {
|
||||
let dir = daemon::recordings_dir().join("clips");
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
/// Set while `fetch` runs, so an export during the download does not start a second one that
|
||||
/// unpacks over the first.
|
||||
static FETCHING: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// One cut at a time. Reopening a row while its tracks are still being cut would otherwise
|
||||
/// have two ffmpeg processes writing the same cache file.
|
||||
static CUTTING: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// What `fetch` reports while it runs.
|
||||
pub enum FetchEvent {
|
||||
/// Bytes of the download so far, of the total the server announced.
|
||||
Bytes { done: u64, total: u64 },
|
||||
/// The archive is complete and being unpacked beside the exe.
|
||||
Unpacking,
|
||||
/// The work is over, with its outcome.
|
||||
Finished(Result<(), String>),
|
||||
}
|
||||
|
||||
/// Whether ffmpeg still has to be downloaded: it lives beside the exe. The presence of the file
|
||||
/// is enough here; `ffmpeg -version` is left to the export that needs it.
|
||||
pub fn missing() -> bool {
|
||||
sidecar_path().map(|path| !path.exists()).unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Whether a download is running right now.
|
||||
pub fn fetching() -> bool {
|
||||
FETCHING.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Download ffmpeg beside the exe, reporting progress. Blocks: call it on a thread.
|
||||
///
|
||||
/// Only `ffmpeg.exe` is unpacked. The archive carries `ffplay` and `ffprobe` too, and the
|
||||
/// export paths call neither; unpacking all three would add 200 MB to every install.
|
||||
pub fn fetch(report: impl Fn(FetchEvent)) -> Result<(), String> {
|
||||
if ffmpeg_is_installed() {
|
||||
return Ok(());
|
||||
}
|
||||
FETCHING.store(true, Ordering::SeqCst);
|
||||
let result = download(&report);
|
||||
FETCHING.store(false, Ordering::SeqCst);
|
||||
report(FetchEvent::Finished(result.clone()));
|
||||
result
|
||||
}
|
||||
|
||||
fn download(report: &impl Fn(FetchEvent)) -> Result<(), String> {
|
||||
let url = ffmpeg_download_url().map_err(|e| format!("cannot find a build to download: {e}"))?;
|
||||
let dir = sidecar_dir().map_err(|e| format!("cannot find where to put ffmpeg: {e}"))?;
|
||||
let archive = download_ffmpeg_package_with_progress(url, &dir, |event| {
|
||||
if let FfmpegDownloadProgressEvent::Downloading {
|
||||
total_bytes,
|
||||
downloaded_bytes,
|
||||
} = event
|
||||
{
|
||||
report(FetchEvent::Bytes {
|
||||
done: downloaded_bytes,
|
||||
total: total_bytes,
|
||||
});
|
||||
}
|
||||
})
|
||||
.map_err(|e| format!("cannot download ffmpeg: {e}"))?;
|
||||
report(FetchEvent::Unpacking);
|
||||
unpack_ffmpeg_without_extras(&archive, &dir)
|
||||
.map_err(|e| format!("cannot unpack ffmpeg: {e}"))?;
|
||||
if !ffmpeg_is_installed() {
|
||||
return Err("ffmpeg did not end up beside the app".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Download the ffmpeg sidecar on first use.
|
||||
pub fn ensure_ffmpeg() -> Result<(), String> {
|
||||
if ffmpeg_is_installed() {
|
||||
return Ok(());
|
||||
}
|
||||
if fetching() {
|
||||
return Err("ffmpeg is still downloading; try the export again in a moment".to_string());
|
||||
}
|
||||
fetch(|_| {})
|
||||
}
|
||||
|
||||
/// Export `start..end` of `video`. Stream copy is fast and keyframe-aligned; `precise` re-encodes
|
||||
/// with x264 for exact cuts. `audio` names the audio streams the clip keeps, empty for all of
|
||||
/// them as they are.
|
||||
pub fn export_clip(
|
||||
video: &str,
|
||||
start: f64,
|
||||
end: f64,
|
||||
output_name: &str,
|
||||
precise: bool,
|
||||
quality: &str,
|
||||
audio: &[usize],
|
||||
) -> Result<String, String> {
|
||||
ensure_ffmpeg()?;
|
||||
if !PathBuf::from(video).exists() {
|
||||
return Err(format!("video file not found: {video}"));
|
||||
}
|
||||
let output = clips_dir().join(format!("{}.mp4", sanitize(output_name)));
|
||||
let duration = (end - start).max(0.0);
|
||||
if duration <= 0.0 {
|
||||
return Err("the clip has no length".into());
|
||||
}
|
||||
|
||||
let mut command = FfmpegCommand::new();
|
||||
command
|
||||
.arg("-y")
|
||||
.arg("-ss")
|
||||
.arg(format!("{start:.3}"))
|
||||
.arg("-i")
|
||||
.arg(video)
|
||||
.arg("-t")
|
||||
.arg(format!("{duration:.3}"));
|
||||
|
||||
// Which tracks the clip keeps. One track is mapped whole; several are mixed into a single
|
||||
// stereo track, because a clip is meant to be played, not to carry a track picker.
|
||||
let kept: Vec<String> = audio
|
||||
.iter()
|
||||
.map(|stream| format!("[0:a:{stream}]"))
|
||||
.collect();
|
||||
if kept.len() > 1 {
|
||||
command
|
||||
.arg("-filter_complex")
|
||||
.arg(format!(
|
||||
"{}amix=inputs={}:normalize=0[out]",
|
||||
kept.concat(),
|
||||
kept.len()
|
||||
))
|
||||
.arg("-map")
|
||||
.arg("0:v")
|
||||
.arg("-map")
|
||||
.arg("[out]")
|
||||
.arg("-c:a")
|
||||
.arg("aac")
|
||||
.arg("-b:a")
|
||||
.arg("160k");
|
||||
} else if let Some(stream) = audio.first() {
|
||||
command
|
||||
.arg("-map")
|
||||
.arg("0:v")
|
||||
.arg("-map")
|
||||
.arg(format!("0:a:{stream}"));
|
||||
}
|
||||
|
||||
if precise || kept.len() > 1 {
|
||||
let crf = match quality {
|
||||
"low" => "28",
|
||||
"high" => "18",
|
||||
_ => "23",
|
||||
};
|
||||
command
|
||||
.arg("-c:v")
|
||||
.arg("libx264")
|
||||
.arg("-crf")
|
||||
.arg(crf)
|
||||
.arg("-preset")
|
||||
.arg("fast")
|
||||
.arg("-c:a")
|
||||
.arg("aac")
|
||||
.arg("-b:a")
|
||||
.arg("128k");
|
||||
} else {
|
||||
command
|
||||
.arg("-c")
|
||||
.arg("copy")
|
||||
.arg("-avoid_negative_ts")
|
||||
.arg("make_zero");
|
||||
}
|
||||
let iter = command
|
||||
.arg(output.to_string_lossy().to_string())
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start ffmpeg: {e}"))?
|
||||
.iter()
|
||||
.map_err(|e| format!("cannot read ffmpeg output: {e}"))?;
|
||||
|
||||
let mut errors = Vec::new();
|
||||
for event in iter {
|
||||
match event {
|
||||
FfmpegEvent::Error(e) => errors.push(e),
|
||||
FfmpegEvent::Log(LogLevel::Error, msg) => errors.push(msg),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let size = std::fs::metadata(&output).map(|m| m.len()).unwrap_or(0);
|
||||
if size == 0 {
|
||||
return Err(if errors.is_empty() {
|
||||
"ffmpeg produced no output".to_string()
|
||||
} else {
|
||||
errors.join("; ")
|
||||
});
|
||||
}
|
||||
Ok(output.display().to_string())
|
||||
}
|
||||
|
||||
/// Copy each audio track of `video` into a file of its own, so a player can be opened per
|
||||
/// track. Files are kept between sessions; a track older than the clip is cut again.
|
||||
pub fn extract_tracks(video: &str, stem: &str, count: usize) -> Result<Vec<PathBuf>, String> {
|
||||
ensure_ffmpeg()?;
|
||||
let _cutting = CUTTING.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let dir = crate::daemon::audio_cache_dir().join(sanitize(stem));
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
||||
let clip_time = std::fs::metadata(video)
|
||||
.and_then(|m| m.modified())
|
||||
.map_err(|e| format!("cannot read {video}: {e}"))?;
|
||||
|
||||
let mut paths = Vec::new();
|
||||
for track in 0..count {
|
||||
let path = dir.join(format!("track-{track}.m4a"));
|
||||
let fresh = std::fs::metadata(&path)
|
||||
.and_then(|m| m.modified())
|
||||
.map(|time| time >= clip_time)
|
||||
.unwrap_or(false);
|
||||
if !fresh {
|
||||
// The stream copy takes seconds where re-encoding takes minutes; a track whose
|
||||
// codec an m4a cannot hold is cut again as AAC.
|
||||
cut_track(video, track, &path, true)
|
||||
.or_else(|_| cut_track(video, track, &path, false))?;
|
||||
}
|
||||
paths.push(path);
|
||||
}
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
/// Cut `track` out of `video` into `path`, keeping the stream as it is (`copy`) or re-encoding
|
||||
/// it as AAC.
|
||||
fn cut_track(video: &str, track: usize, path: &Path, copy: bool) -> Result<(), String> {
|
||||
let mut command = FfmpegCommand::new();
|
||||
command
|
||||
.arg("-y")
|
||||
.arg("-i")
|
||||
.arg(video)
|
||||
.arg("-map")
|
||||
.arg(format!("0:a:{track}"))
|
||||
.arg("-vn");
|
||||
if copy {
|
||||
command.arg("-c:a").arg("copy");
|
||||
} else {
|
||||
command.arg("-c:a").arg("aac").arg("-b:a").arg("160k");
|
||||
}
|
||||
command.arg(path.to_string_lossy().to_string());
|
||||
|
||||
let mut errors = Vec::new();
|
||||
for event in command
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start ffmpeg: {e}"))?
|
||||
.iter()
|
||||
.map_err(|e| format!("cannot read ffmpeg output: {e}"))?
|
||||
{
|
||||
match event {
|
||||
FfmpegEvent::Error(e) => errors.push(e),
|
||||
FfmpegEvent::Log(LogLevel::Error, msg) => errors.push(msg),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
|
||||
if size == 0 {
|
||||
return Err(if errors.is_empty() {
|
||||
format!("audio track {track} came out empty")
|
||||
} else {
|
||||
errors.join("; ")
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sanitize(name: &str) -> String {
|
||||
name.chars()
|
||||
.map(|c| {
|
||||
if c.is_alphanumeric() || matches!(c, '-' | '_' | '.') {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Text formatting shared by the screens, matching `tauri-app/src/types/timeline.ts`.
|
||||
|
||||
use chrono::{DateTime, Local, Utc};
|
||||
|
||||
pub fn duration(secs: f64) -> String {
|
||||
let total = secs.max(0.0).round() as u64;
|
||||
format!("{}:{:02}", total / 60, total % 60)
|
||||
}
|
||||
|
||||
pub fn clock(secs: f64) -> String {
|
||||
let total = secs.max(0.0) as u64;
|
||||
format!("{}:{:02}", total / 60, total % 60)
|
||||
}
|
||||
|
||||
pub fn relative_time(when: DateTime<Utc>) -> String {
|
||||
let now = Utc::now();
|
||||
let delta = now.signed_duration_since(when);
|
||||
let days = delta.num_days();
|
||||
let local = when.with_timezone(&Local);
|
||||
if days > 7 {
|
||||
return local.format("%b %e, %Y, %H:%M").to_string();
|
||||
}
|
||||
if days > 0 {
|
||||
return format!("{days} day{} ago", plural(days));
|
||||
}
|
||||
let hours = delta.num_hours();
|
||||
if hours > 0 {
|
||||
return format!("{hours} hour{} ago", plural(hours));
|
||||
}
|
||||
let minutes = delta.num_minutes();
|
||||
if minutes > 0 {
|
||||
return format!("{minutes} minute{} ago", plural(minutes));
|
||||
}
|
||||
"Just now".into()
|
||||
}
|
||||
|
||||
pub fn game_start(when: DateTime<Utc>) -> String {
|
||||
let local = when.with_timezone(&Local);
|
||||
let now = Local::now();
|
||||
let day = local.date_naive();
|
||||
let time = local.format("%H:%M").to_string();
|
||||
if day == now.date_naive() {
|
||||
format!("Today at {time}")
|
||||
} else if day == now.date_naive() - chrono::Days::new(1) {
|
||||
format!("Yesterday at {time}")
|
||||
} else {
|
||||
format!("{} at {time}", local.format("%b %e"))
|
||||
}
|
||||
}
|
||||
|
||||
fn plural(n: i64) -> &'static str {
|
||||
if n == 1 { "" } else { "s" }
|
||||
}
|
||||
|
||||
pub fn kda_ratio(kills: u32, deaths: u32, assists: u32) -> String {
|
||||
let value = if deaths == 0 {
|
||||
(kills + assists) as f64
|
||||
} else {
|
||||
(kills + assists) as f64 / deaths as f64
|
||||
};
|
||||
format!("{value:.1}")
|
||||
}
|
||||
|
||||
pub fn cs_per_min(stats: &crate::history::Stats) -> String {
|
||||
if stats.game_duration == 0 {
|
||||
return "0.0".into();
|
||||
}
|
||||
format!(
|
||||
"{:.1}",
|
||||
stats.creep_score as f64 / (stats.game_duration as f64 / 60.0)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn gold_per_min(stats: &crate::history::Stats) -> String {
|
||||
if stats.game_duration == 0 {
|
||||
return "0".into();
|
||||
}
|
||||
let value = stats.gold_earned as f64 / (stats.game_duration as f64 / 60.0);
|
||||
number(value.round() as u64)
|
||||
}
|
||||
|
||||
pub fn number(n: u64) -> String {
|
||||
if n >= 1_000_000 {
|
||||
format!("{:.1}M", n as f64 / 1_000_000.0)
|
||||
} else if n >= 1_000 {
|
||||
format!("{:.1}K", n as f64 / 1_000.0)
|
||||
} else {
|
||||
n.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rank(tier: &str, division: &str) -> String {
|
||||
if tier.is_empty() || tier == "UNRANKED" {
|
||||
return "Unranked".into();
|
||||
}
|
||||
let mut chars = tier.chars();
|
||||
let tidy = match chars.next() {
|
||||
Some(first) => first.to_uppercase().collect::<String>() + &chars.as_str().to_lowercase(),
|
||||
None => String::new(),
|
||||
};
|
||||
if division.is_empty() {
|
||||
tidy
|
||||
} else {
|
||||
format!("{tidy} {division}")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lp_delta(delta: i64) -> String {
|
||||
if delta > 0 {
|
||||
format!("+{delta}")
|
||||
} else {
|
||||
delta.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::history::Stats;
|
||||
|
||||
#[test]
|
||||
fn durations_read_as_minutes_and_seconds() {
|
||||
assert_eq!(duration(1830.0), "30:30");
|
||||
assert_eq!(duration(65.4), "1:05");
|
||||
assert_eq!(duration(-3.0), "0:00");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kda_ratio_survives_zero_deaths() {
|
||||
assert_eq!(kda_ratio(9, 3, 7), "5.3");
|
||||
assert_eq!(kda_ratio(9, 0, 7), "16.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranks_are_tidied_for_people() {
|
||||
assert_eq!(rank("EMERALD", "II"), "Emerald II");
|
||||
assert_eq!(rank("UNRANKED", ""), "Unranked");
|
||||
assert_eq!(rank("GOLD", ""), "Gold");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn per_minute_stats_use_the_game_length() {
|
||||
let stats = Stats {
|
||||
creep_score: 200,
|
||||
gold_earned: 12_000,
|
||||
game_duration: 1200,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(cs_per_min(&stats), "10.0");
|
||||
assert_eq!(gold_per_min(&stats), "600");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
//! Highlight clips from timeline events, ported from `computeHighlights` in
|
||||
//! `tauri-app/src/types/timeline.ts`.
|
||||
|
||||
use crate::history::{Timeline, TimelineEvent};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
Kill,
|
||||
Death,
|
||||
Assist,
|
||||
MultiKill,
|
||||
TradeKill,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Kind::Kill => "Kill",
|
||||
Kind::Death => "Death",
|
||||
Kind::Assist => "Assist",
|
||||
Kind::MultiKill => "Multi kill",
|
||||
Kind::TradeKill => "Trade kill",
|
||||
}
|
||||
}
|
||||
|
||||
fn priority(self) -> u8 {
|
||||
match self {
|
||||
Kind::MultiKill => 0,
|
||||
Kind::TradeKill => 1,
|
||||
Kind::Kill => 2,
|
||||
Kind::Death => 3,
|
||||
Kind::Assist => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Highlight {
|
||||
pub start: f64,
|
||||
pub end: f64,
|
||||
pub kind: Kind,
|
||||
pub title: String,
|
||||
pub subtitle: String,
|
||||
/// Timestamps of the events inside the clip, for markers.
|
||||
pub events: Vec<f64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Options {
|
||||
pub before: f64,
|
||||
pub after: f64,
|
||||
pub min_duration: f64,
|
||||
pub merge_overlapping: bool,
|
||||
pub merge_gap: f64,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
before: 10.0,
|
||||
after: 3.0,
|
||||
min_duration: 5.0,
|
||||
merge_overlapping: true,
|
||||
merge_gap: 5.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn string_at<'a>(event: &'a TimelineEvent, key: &str) -> Option<&'a str> {
|
||||
event.raw_data.get(key).and_then(|v| v.as_str())
|
||||
}
|
||||
|
||||
/// Whether a name from the live client data is the player. The timeline's summoner carries a
|
||||
/// `#TAG` (`Kai'Sa#EUW`) that the live client data's `KillerName` does not, so the tag is
|
||||
/// dropped before comparing.
|
||||
fn same_player(name: &str, player: &str) -> bool {
|
||||
fn base(n: &str) -> &str {
|
||||
n.split('#').next().unwrap_or(n).trim()
|
||||
}
|
||||
base(name).eq_ignore_ascii_case(base(player))
|
||||
}
|
||||
|
||||
/// How the player took part in a kill event, if at all.
|
||||
pub fn involvement(event: &TimelineEvent, player: &str) -> Option<Kind> {
|
||||
if string_at(event, "KillerName").is_some_and(|name| same_player(name, player)) {
|
||||
return Some(Kind::Kill);
|
||||
}
|
||||
if string_at(event, "VictimName").is_some_and(|name| same_player(name, player)) {
|
||||
return Some(Kind::Death);
|
||||
}
|
||||
let assist = event
|
||||
.raw_data
|
||||
.get("Assisters")
|
||||
.and_then(|v| v.as_array())
|
||||
.is_some_and(|names| {
|
||||
names
|
||||
.iter()
|
||||
.filter_map(|name| name.as_str())
|
||||
.any(|name| same_player(name, player))
|
||||
});
|
||||
if assist {
|
||||
return Some(Kind::Assist);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// One clip per involvement, then multi-kills, then a merge pass.
|
||||
pub fn compute(timeline: &Timeline, player: Option<&str>, options: Options) -> Vec<Highlight> {
|
||||
let Some(player) = player else {
|
||||
return Vec::new();
|
||||
};
|
||||
let duration = timeline.duration_secs.max(0) as f64;
|
||||
let kills = timeline.events.iter().filter(|e| e.event_type == "kill");
|
||||
|
||||
let mut clips: Vec<Highlight> = Vec::new();
|
||||
let mut player_kills: Vec<f64> = Vec::new();
|
||||
let mut player_deaths: Vec<f64> = Vec::new();
|
||||
|
||||
for event in kills {
|
||||
let Some(kind) = involvement(event, player) else {
|
||||
continue;
|
||||
};
|
||||
let at = event.time();
|
||||
let (title, subtitle) = match kind {
|
||||
Kind::Kill => (
|
||||
"Kill".to_string(),
|
||||
format!(
|
||||
"Killed {}",
|
||||
string_at(event, "VictimName").unwrap_or("an enemy")
|
||||
),
|
||||
),
|
||||
Kind::Death => (
|
||||
"Death".to_string(),
|
||||
format!(
|
||||
"Killed by {}",
|
||||
string_at(event, "KillerName").unwrap_or("an enemy")
|
||||
),
|
||||
),
|
||||
_ => (
|
||||
"Assist".to_string(),
|
||||
format!(
|
||||
"Assisted {} against {}",
|
||||
string_at(event, "KillerName").unwrap_or("an ally"),
|
||||
string_at(event, "VictimName").unwrap_or("an enemy")
|
||||
),
|
||||
),
|
||||
};
|
||||
match kind {
|
||||
Kind::Kill => player_kills.push(at),
|
||||
Kind::Death => player_deaths.push(at),
|
||||
_ => {}
|
||||
}
|
||||
clips.push(Highlight {
|
||||
start: (at - options.before).max(0.0),
|
||||
end: (at + options.after).min(if duration > 0.0 { duration } else { f64::MAX }),
|
||||
kind,
|
||||
title,
|
||||
subtitle,
|
||||
events: vec![at],
|
||||
});
|
||||
}
|
||||
|
||||
// Multi-kills: two or more of the player's kills within 12 s.
|
||||
player_kills.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||
let mut i = 0;
|
||||
while i < player_kills.len() {
|
||||
let mut j = i;
|
||||
while j + 1 < player_kills.len() && player_kills[j + 1] - player_kills[j] <= 12.0 {
|
||||
j += 1;
|
||||
}
|
||||
let count = j - i + 1;
|
||||
if count >= 2 {
|
||||
let first = player_kills[i];
|
||||
let last = player_kills[j];
|
||||
let died = player_deaths
|
||||
.iter()
|
||||
.any(|d| *d >= first && *d <= last + 12.0);
|
||||
let (kind, title) = if died {
|
||||
(Kind::TradeKill, "Trade kill".to_string())
|
||||
} else {
|
||||
(Kind::MultiKill, multi_kill_label(count))
|
||||
};
|
||||
let subtitle = if died {
|
||||
format!("{count} kills but died in the trade")
|
||||
} else {
|
||||
format!("{count} kills in quick succession")
|
||||
};
|
||||
let mut events: Vec<f64> = player_kills[i..=j].to_vec();
|
||||
if died {
|
||||
events.extend(
|
||||
player_deaths
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|d| *d >= first && *d <= last + 12.0),
|
||||
);
|
||||
}
|
||||
let end = events.iter().cloned().fold(last, f64::max) + options.after;
|
||||
clips.push(Highlight {
|
||||
start: (first - options.before).max(0.0),
|
||||
end: end.min(if duration > 0.0 { duration } else { f64::MAX }),
|
||||
kind,
|
||||
title,
|
||||
subtitle,
|
||||
events,
|
||||
});
|
||||
}
|
||||
i = j + 1;
|
||||
}
|
||||
|
||||
clips.sort_by(|a, b| a.start.partial_cmp(&b.start).unwrap());
|
||||
|
||||
let mut merged: Vec<Highlight> = Vec::new();
|
||||
let mut iter = clips.into_iter();
|
||||
let Some(mut current) = iter.next() else {
|
||||
return Vec::new();
|
||||
};
|
||||
for next in iter {
|
||||
let joins = options.merge_overlapping && next.start <= current.end + options.merge_gap;
|
||||
if joins {
|
||||
current.end = current.end.max(next.end);
|
||||
current.events.extend(next.events.iter().copied());
|
||||
if next.kind.priority() < current.kind.priority() {
|
||||
current.kind = next.kind;
|
||||
current.title = next.title;
|
||||
current.subtitle = next.subtitle;
|
||||
}
|
||||
} else {
|
||||
merged.push(current);
|
||||
current = next;
|
||||
}
|
||||
}
|
||||
merged.push(current);
|
||||
|
||||
merged.retain(|c| c.end - c.start >= options.min_duration);
|
||||
merged
|
||||
}
|
||||
|
||||
fn multi_kill_label(count: usize) -> String {
|
||||
match count {
|
||||
2 => "Double kill".into(),
|
||||
3 => "Triple kill".into(),
|
||||
4 => "Quadra kill".into(),
|
||||
5 => "Penta kill".into(),
|
||||
n => format!("{n}x kill"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_sample_game_has_a_clip_for_each_involvement() {
|
||||
let game = &crate::history::sample()[0];
|
||||
let clips = compute(game, Some("Demo#EUW"), Options::default());
|
||||
assert_eq!(clips.len(), 3, "{clips:#?}");
|
||||
assert!(clips.iter().any(|c| c.kind == Kind::Death));
|
||||
assert!(clips.iter().all(|c| c.end > c.start));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tag_in_the_summoner_does_not_hide_the_player() {
|
||||
let game = &crate::history::sample()[0];
|
||||
let clips = compute(game, Some("Demo"), Options::default());
|
||||
assert_eq!(
|
||||
clips.len(),
|
||||
3,
|
||||
"the live client names carry no tag: {clips:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nobody_named_means_no_clips() {
|
||||
let game = &crate::history::sample()[0];
|
||||
assert!(compute(game, None, Options::default()).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,733 @@
|
||||
//! Reading the daemon's timelines from disk and the values the screens show.
|
||||
//!
|
||||
//! Ported from `tauri-app/src-tauri/src/lib.rs` (`get_game_history`, `get_timeline`,
|
||||
//! `find_video_file`) and the extractors in `tauri-app/src/types/timeline.ts`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::daemon;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[allow(dead_code)] // every field mirrors the daemon's timeline JSON
|
||||
pub struct Timeline {
|
||||
pub recording_id: String,
|
||||
pub start_time: DateTime<Utc>,
|
||||
#[serde(default)]
|
||||
pub end_time: Option<DateTime<Utc>>,
|
||||
#[serde(default)]
|
||||
pub duration_secs: i64,
|
||||
#[serde(default)]
|
||||
pub events: Vec<TimelineEvent>,
|
||||
#[serde(default)]
|
||||
pub game_id: Option<u64>,
|
||||
#[serde(default)]
|
||||
pub raw_session: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub raw_summoner: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub raw_champion_select: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub raw_rune_page: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub raw_live_client_data: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub raw_end_game_stats: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub video_file: Option<String>,
|
||||
/// What each audio track of the video carries, in file order. Empty for recordings made
|
||||
/// before the recorder wrote one track per source.
|
||||
#[serde(default)]
|
||||
pub audio_tracks: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[allow(dead_code)]
|
||||
pub struct TimelineEvent {
|
||||
/// `(seconds, nanos)` since the recording started.
|
||||
#[serde(default)]
|
||||
pub video_timestamp: (i64, i32),
|
||||
#[serde(default)]
|
||||
pub game_timestamp: Option<(i64, i32)>,
|
||||
#[serde(default)]
|
||||
pub timestamp: Option<DateTime<Utc>>,
|
||||
#[serde(default)]
|
||||
pub event_type: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub raw_data: Value,
|
||||
#[serde(default)]
|
||||
pub uri: String,
|
||||
}
|
||||
|
||||
impl TimelineEvent {
|
||||
pub fn time(&self) -> f64 {
|
||||
self.video_timestamp.0 as f64 + self.video_timestamp.1 as f64 / 1e9
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
Victory,
|
||||
Defeat,
|
||||
Terminated,
|
||||
}
|
||||
|
||||
impl Outcome {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Outcome::Victory => "Victory",
|
||||
Outcome::Defeat => "Defeat",
|
||||
Outcome::Terminated => "Terminated",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct Stats {
|
||||
pub kills: u32,
|
||||
pub deaths: u32,
|
||||
pub assists: u32,
|
||||
pub creep_score: u32,
|
||||
pub gold_earned: u64,
|
||||
pub damage_dealt: u64,
|
||||
pub vision_score: u32,
|
||||
pub game_duration: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct LpChange {
|
||||
pub delta: i64,
|
||||
pub league_points: u32,
|
||||
pub tier: String,
|
||||
pub division: String,
|
||||
pub in_promos: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum QueueCategory {
|
||||
RankedSolo,
|
||||
RankedFlex,
|
||||
Normals,
|
||||
Aram,
|
||||
Custom,
|
||||
}
|
||||
|
||||
impl QueueCategory {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
QueueCategory::RankedSolo => "Ranked Solo",
|
||||
QueueCategory::RankedFlex => "Ranked Flex",
|
||||
QueueCategory::Normals => "Normals",
|
||||
QueueCategory::Aram => "ARAM",
|
||||
QueueCategory::Custom => "Custom",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The timeline folder the daemon writes.
|
||||
pub fn timeline_dir() -> PathBuf {
|
||||
daemon::recordings_dir().join("timelines")
|
||||
}
|
||||
|
||||
/// Timeline files on disk, most recently written first.
|
||||
///
|
||||
/// The name is a recording id, so the write time is the only cheap order there is. A
|
||||
/// recording is written when its game ends, which matches when it started closely enough for
|
||||
/// a list that gets re-sorted by `start_time` as pages arrive.
|
||||
pub fn timeline_paths() -> Vec<PathBuf> {
|
||||
let dir = timeline_dir();
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut found: Vec<(std::time::SystemTime, PathBuf)> = entries
|
||||
.flatten()
|
||||
.map(|entry| entry.path())
|
||||
.filter(|path| path.extension().and_then(|e| e.to_str()) == Some("json"))
|
||||
.filter_map(|path| {
|
||||
let written = std::fs::metadata(&path).ok()?.modified().ok()?;
|
||||
Some((written, path))
|
||||
})
|
||||
.collect();
|
||||
found.sort_by_key(|(written, _)| std::cmp::Reverse(*written));
|
||||
found.into_iter().map(|(_, path)| path).collect()
|
||||
}
|
||||
|
||||
/// The rows for a page of timelines.
|
||||
///
|
||||
/// Each file is parsed whole, because the champion, the scoreline and the queue only exist
|
||||
/// inside the raw responses, and the [`Timeline`] is dropped as soon as its [`Summary`] is
|
||||
/// built. Only the summaries are kept, so the events and the raw JSON do not pile up.
|
||||
pub fn summaries(paths: &[PathBuf]) -> Vec<Summary> {
|
||||
paths.iter().filter_map(|path| summary_of(path)).collect()
|
||||
}
|
||||
|
||||
fn summary_of(path: &Path) -> Option<Summary> {
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
match serde_json::from_str::<Timeline>(&text) {
|
||||
Ok(timeline) => Some(timeline.summary()),
|
||||
Err(e) => {
|
||||
eprintln!("skipping {}: {e}", path.display());
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the match history list needs from a recording.
|
||||
///
|
||||
/// The list shows 309 rows of this at a time and the events and raw responses of the timeline
|
||||
/// stay on disk until a row is opened, so this carries only the values they were read for.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Summary {
|
||||
pub recording_id: String,
|
||||
pub start_time: DateTime<Utc>,
|
||||
pub duration_secs: i64,
|
||||
/// The video file the row names, kept so deleting a row does not re-read its timeline.
|
||||
pub video_file: Option<String>,
|
||||
champion: Option<String>,
|
||||
summoner: Option<String>,
|
||||
queue_label: String,
|
||||
category: QueueCategory,
|
||||
outcome: Outcome,
|
||||
stats: Option<Stats>,
|
||||
lp: Option<LpChange>,
|
||||
pub event_count: usize,
|
||||
}
|
||||
|
||||
impl Summary {
|
||||
pub fn champion(&self) -> Option<String> {
|
||||
self.champion.clone()
|
||||
}
|
||||
|
||||
pub fn summoner(&self) -> Option<String> {
|
||||
self.summoner.clone()
|
||||
}
|
||||
|
||||
pub fn queue_label(&self) -> &str {
|
||||
&self.queue_label
|
||||
}
|
||||
|
||||
pub fn category(&self) -> QueueCategory {
|
||||
self.category
|
||||
}
|
||||
|
||||
pub fn outcome(&self) -> Outcome {
|
||||
self.outcome
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> Option<Stats> {
|
||||
self.stats
|
||||
}
|
||||
|
||||
pub fn lp_change(&self) -> Option<LpChange> {
|
||||
self.lp.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Timeline {
|
||||
/// The list row for this recording, computed before the timeline is dropped.
|
||||
pub fn summary(&self) -> Summary {
|
||||
Summary {
|
||||
recording_id: self.recording_id.clone(),
|
||||
start_time: self.start_time,
|
||||
duration_secs: self.duration_secs,
|
||||
video_file: self.video_file.clone(),
|
||||
champion: self.champion(),
|
||||
summoner: self.summoner(),
|
||||
queue_label: self.queue_label(),
|
||||
category: self.category(),
|
||||
outcome: self.outcome(),
|
||||
stats: self.stats(),
|
||||
lp: self.lp_change(),
|
||||
event_count: self.events.len(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load(recording_id: &str) -> Option<Timeline> {
|
||||
let path = timeline_dir().join(format!("{recording_id}.json"));
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
serde_json::from_str(&text).ok()
|
||||
}
|
||||
|
||||
/// Remove a recording: its timeline JSON and its video file.
|
||||
///
|
||||
/// The video is found the way review finds it, so a clip renamed but keeping the timestamp
|
||||
/// prefix goes too. A file that is already gone is fine: the list shows what was read
|
||||
/// earlier, and a tidy-up elsewhere should not turn into an error here.
|
||||
pub fn delete(recording_id: &str, video_file: Option<&str>) -> Result<(), String> {
|
||||
delete_in(recording_id, video_file, &daemon::recordings_dir())
|
||||
}
|
||||
|
||||
/// [`delete`] inside one recordings folder, so a test can point it at a temporary one.
|
||||
fn delete_in(
|
||||
recording_id: &str,
|
||||
video_file: Option<&str>,
|
||||
recordings: &Path,
|
||||
) -> Result<(), String> {
|
||||
let json = recordings
|
||||
.join("timelines")
|
||||
.join(format!("{recording_id}.json"));
|
||||
if json.exists() {
|
||||
std::fs::remove_file(&json)
|
||||
.map_err(|e| format!("could not delete {}: {e}", json.display()))?;
|
||||
}
|
||||
if let Some(video) = video_file.and_then(|name| find_video_file(recordings, name)) {
|
||||
std::fs::remove_file(&video)
|
||||
.map_err(|e| format!("could not delete {}: {e}", video.display()))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Timeline {
|
||||
fn end_stats(&self) -> Option<&Value> {
|
||||
self.raw_end_game_stats.as_ref()
|
||||
}
|
||||
|
||||
pub fn outcome(&self) -> Outcome {
|
||||
let stats = self
|
||||
.end_stats()
|
||||
.and_then(|s| s.get("localPlayer"))
|
||||
.and_then(|p| p.get("stats"));
|
||||
if stats.and_then(|s| s.get("WIN")).and_then(|v| v.as_u64()) == Some(1) {
|
||||
Outcome::Victory
|
||||
} else if stats.and_then(|s| s.get("LOSE")).and_then(|v| v.as_u64()) == Some(1) {
|
||||
Outcome::Defeat
|
||||
} else {
|
||||
Outcome::Terminated
|
||||
}
|
||||
}
|
||||
|
||||
pub fn champion(&self) -> Option<String> {
|
||||
if let Some(name) = self
|
||||
.end_stats()
|
||||
.and_then(|s| s.pointer("/localPlayer/championName"))
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
return Some(name.to_string());
|
||||
}
|
||||
self.raw_live_client_data
|
||||
.as_ref()
|
||||
.and_then(|s| s.pointer("/activePlayer/championName"))
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
pub fn summoner(&self) -> Option<String> {
|
||||
if let Some(game_name) = self
|
||||
.end_stats()
|
||||
.and_then(|s| s.pointer("/localPlayer/riotIdGameName"))
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
let tag = self
|
||||
.end_stats()
|
||||
.and_then(|s| s.pointer("/localPlayer/riotIdTagLine"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
return Some(if tag.is_empty() {
|
||||
game_name.to_string()
|
||||
} else {
|
||||
format!("{game_name}#{tag}")
|
||||
});
|
||||
}
|
||||
let summoner = self.raw_summoner.as_ref()?;
|
||||
if let Some(name) = summoner.get("gameName").and_then(|v| v.as_str()) {
|
||||
let tag = summoner
|
||||
.get("tagLine")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
return Some(if tag.is_empty() {
|
||||
name.to_string()
|
||||
} else {
|
||||
format!("{name}#{tag}")
|
||||
});
|
||||
}
|
||||
summoner
|
||||
.get("displayName")
|
||||
.or_else(|| summoner.get("name"))
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
pub fn queue_name(&self) -> Option<String> {
|
||||
self.raw_session
|
||||
.as_ref()
|
||||
.and_then(|s| s.pointer("/gameData/queue/name"))
|
||||
.and_then(|v| v.as_str())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
pub fn queue_id(&self) -> Option<u64> {
|
||||
self.raw_session
|
||||
.as_ref()
|
||||
.and_then(|s| s.pointer("/gameData/queue/id"))
|
||||
.and_then(|v| v.as_u64())
|
||||
}
|
||||
|
||||
/// A display name for the queue, falling back to the queue id table.
|
||||
pub fn queue_label(&self) -> String {
|
||||
if let Some(name) = self.queue_name() {
|
||||
if name.contains("Practice") {
|
||||
return "Practice Tool".into();
|
||||
}
|
||||
if name.contains("Ranked Solo") {
|
||||
return "Ranked Solo".into();
|
||||
}
|
||||
if name.contains("Ranked Flex") {
|
||||
return "Ranked Flex".into();
|
||||
}
|
||||
if name.contains("ARAM") {
|
||||
return "ARAM".into();
|
||||
}
|
||||
if name.contains("Normal") {
|
||||
return "Normal".into();
|
||||
}
|
||||
if name.contains("Co-op") {
|
||||
return "Co-op vs AI".into();
|
||||
}
|
||||
return name;
|
||||
}
|
||||
match self.queue_id() {
|
||||
Some(420) => "Ranked Solo".into(),
|
||||
Some(440) => "Ranked Flex".into(),
|
||||
Some(450) => "ARAM".into(),
|
||||
Some(400) => "Normal Draft".into(),
|
||||
Some(430) => "Normal Blind".into(),
|
||||
Some(800..=850) => "Co-op vs AI".into(),
|
||||
Some(3140) => "Practice Tool".into(),
|
||||
Some(_) => "Custom Game".into(),
|
||||
None => "Custom Game".into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn category(&self) -> QueueCategory {
|
||||
if let Some(name) = self.queue_name() {
|
||||
if name.contains("Ranked Solo") {
|
||||
return QueueCategory::RankedSolo;
|
||||
}
|
||||
if name.contains("Ranked Flex") {
|
||||
return QueueCategory::RankedFlex;
|
||||
}
|
||||
if name.contains("ARAM") {
|
||||
return QueueCategory::Aram;
|
||||
}
|
||||
if name.contains("Normal") || name.contains("Draft") || name.contains("Blind") {
|
||||
return QueueCategory::Normals;
|
||||
}
|
||||
if name.contains("Custom") || name.contains("Practice") {
|
||||
return QueueCategory::Custom;
|
||||
}
|
||||
}
|
||||
match self.queue_id() {
|
||||
Some(420) => QueueCategory::RankedSolo,
|
||||
Some(440) => QueueCategory::RankedFlex,
|
||||
Some(400 | 430) => QueueCategory::Normals,
|
||||
Some(450) => QueueCategory::Aram,
|
||||
_ => QueueCategory::Custom,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stats(&self) -> Option<Stats> {
|
||||
let player = self.end_stats()?.get("localPlayer")?;
|
||||
let s = player.get("stats")?;
|
||||
let n = |k: &str| s.get(k).and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
Some(Stats {
|
||||
kills: n("CHAMPIONS_KILLED") as u32,
|
||||
deaths: n("NUM_DEATHS") as u32,
|
||||
assists: n("ASSISTS") as u32,
|
||||
creep_score: n("MINIONS_KILLED") as u32,
|
||||
gold_earned: n("GOLD_EARNED"),
|
||||
damage_dealt: n("TOTAL_DAMAGE_DEALT_TO_CHAMPIONS"),
|
||||
vision_score: n("VISION_SCORE") as u32,
|
||||
game_duration: self
|
||||
.end_stats()
|
||||
.and_then(|s| s.get("gameLength"))
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(self.duration_secs.max(0) as u64),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn lp_change(&self) -> Option<LpChange> {
|
||||
let lp_events: Vec<&TimelineEvent> = self
|
||||
.events
|
||||
.iter()
|
||||
.filter(|e| e.event_type == "lp_change")
|
||||
.collect();
|
||||
let ranked = lp_events.iter().find(|e| {
|
||||
e.raw_data
|
||||
.get("tier")
|
||||
.and_then(|v| v.as_str())
|
||||
.is_some_and(|t| t != "UNRANKED")
|
||||
});
|
||||
let event = ranked
|
||||
.or_else(|| {
|
||||
lp_events.iter().find(|e| {
|
||||
e.raw_data.get("leaguePointsDelta").and_then(|v| v.as_i64()) != Some(0)
|
||||
})
|
||||
})
|
||||
.or_else(|| lp_events.first())?;
|
||||
let raw = &event.raw_data;
|
||||
let delta = raw.get("leaguePointsDelta").and_then(|v| v.as_i64())?;
|
||||
Some(LpChange {
|
||||
delta,
|
||||
league_points: raw
|
||||
.get("leaguePoints")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(0) as u32,
|
||||
tier: raw
|
||||
.get("tier")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("UNRANKED")
|
||||
.to_string(),
|
||||
division: raw
|
||||
.get("division")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string(),
|
||||
in_promos: raw
|
||||
.get("miniseriesProgress")
|
||||
.and_then(|v| v.as_str())
|
||||
.is_some_and(|s| !s.is_empty()),
|
||||
})
|
||||
}
|
||||
|
||||
/// The recording's video file, by name or by the timestamp prefix.
|
||||
pub fn video_path(&self) -> Option<PathBuf> {
|
||||
let dir = daemon::recordings_dir();
|
||||
find_video_file(&dir, self.video_file.as_deref()?)
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact name first, then a file sharing the timestamp prefix.
|
||||
pub fn find_video_file(dir: &Path, filename: &str) -> Option<PathBuf> {
|
||||
let exact = dir.join(filename);
|
||||
if exact.exists() {
|
||||
return Some(exact);
|
||||
}
|
||||
let prefix = filename.replace("_unknown.mp4", "");
|
||||
let entries = std::fs::read_dir(dir).ok()?;
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let video = matches!(
|
||||
path.extension().and_then(|e| e.to_str()),
|
||||
Some("mp4" | "mkv" | "mov")
|
||||
);
|
||||
if !video {
|
||||
continue;
|
||||
}
|
||||
let name = path.file_name()?.to_string_lossy().to_string();
|
||||
if name.starts_with(&prefix) {
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Two made-up recordings for `--scene` snapshots and for checking layout without a daemon.
|
||||
pub fn sample() -> Vec<Timeline> {
|
||||
let now = Utc::now();
|
||||
let game = |id: &str,
|
||||
hours_ago: i64,
|
||||
champion: &str,
|
||||
win: bool,
|
||||
kills: u64,
|
||||
deaths: u64,
|
||||
assists: u64,
|
||||
cs: u64| {
|
||||
let start = now - chrono::Duration::hours(hours_ago);
|
||||
let event = |at: f64, kind: &str, description: &str, raw: Value| TimelineEvent {
|
||||
video_timestamp: (at as i64, ((at.fract()) * 1e9) as i32),
|
||||
game_timestamp: None,
|
||||
timestamp: None,
|
||||
event_type: kind.to_string(),
|
||||
description: description.to_string(),
|
||||
raw_data: raw,
|
||||
uri: String::new(),
|
||||
};
|
||||
let events = vec![
|
||||
event(12.0, "game_start", "Game start", Value::Null),
|
||||
event(
|
||||
212.0,
|
||||
"kill",
|
||||
"Killed Ahri",
|
||||
serde_json::json!({"KillerName": "Demo#EUW", "VictimName": "Ahri", "Assisters": ["Thresh"]}),
|
||||
),
|
||||
event(
|
||||
368.0,
|
||||
"kill",
|
||||
"Killed Lee Sin",
|
||||
serde_json::json!({"KillerName": "Demo#EUW", "VictimName": "Lee Sin", "Assisters": []}),
|
||||
),
|
||||
event(
|
||||
402.0,
|
||||
"kill",
|
||||
"Killed by Zed",
|
||||
serde_json::json!({"KillerName": "Zed", "VictimName": "Demo#EUW", "Assisters": []}),
|
||||
),
|
||||
event(744.0, "objective", "Dragon", Value::Null),
|
||||
event(1500.0, "game_end", "Game end", Value::Null),
|
||||
event(
|
||||
1510.0,
|
||||
"lp_change",
|
||||
if win { "+21 LP" } else { "-19 LP" },
|
||||
serde_json::json!({
|
||||
"leaguePointsDelta": if win { 21 } else { -19 },
|
||||
"leaguePoints": if win { 74 } else { 54 },
|
||||
"tier": "EMERALD",
|
||||
"division": "II",
|
||||
"queueType": "RANKED_SOLO_5x5"
|
||||
}),
|
||||
),
|
||||
];
|
||||
Timeline {
|
||||
recording_id: id.to_string(),
|
||||
start_time: start,
|
||||
end_time: Some(start + chrono::Duration::seconds(1830)),
|
||||
duration_secs: 1830,
|
||||
events,
|
||||
game_id: Some(7_000_000),
|
||||
raw_session: Some(
|
||||
serde_json::json!({"gameData": {"queue": {"name": "Ranked Solo", "id": 420}}}),
|
||||
),
|
||||
raw_summoner: Some(serde_json::json!({"gameName": "Demo", "tagLine": "EUW"})),
|
||||
raw_champion_select: None,
|
||||
raw_rune_page: None,
|
||||
raw_live_client_data: None,
|
||||
raw_end_game_stats: Some(serde_json::json!({
|
||||
"gameLength": 1830,
|
||||
"localPlayer": {
|
||||
"championName": champion,
|
||||
"riotIdGameName": "Demo",
|
||||
"riotIdTagLine": "EUW",
|
||||
"stats": {
|
||||
"CHAMPIONS_KILLED": kills,
|
||||
"NUM_DEATHS": deaths,
|
||||
"ASSISTS": assists,
|
||||
"MINIONS_KILLED": cs,
|
||||
"GOLD_EARNED": 13_450,
|
||||
"TOTAL_DAMAGE_DEALT_TO_CHAMPIONS": 24_800,
|
||||
"VISION_SCORE": 32,
|
||||
"WIN": if win { 1 } else { 0 },
|
||||
"LOSE": if win { 0 } else { 1 }
|
||||
}
|
||||
}
|
||||
})),
|
||||
video_file: None,
|
||||
audio_tracks: Vec::new(),
|
||||
}
|
||||
};
|
||||
vec![
|
||||
game("demo-1", 3, "Kai'Sa", true, 9, 3, 7, 214),
|
||||
game("demo-2", 27, "Jinx", false, 4, 8, 5, 188),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const TIMELINE: &str = r#"{
|
||||
"recording_id": "0b7d3f6e-2f4a-4b83-9f0e-0d5c9f1a2b3c",
|
||||
"start_time": "2026-03-27T16:42:52Z",
|
||||
"end_time": "2026-03-27T17:13:22Z",
|
||||
"duration_secs": 1830,
|
||||
"events": [
|
||||
{"video_timestamp": [212, 0], "game_timestamp": null, "timestamp": "2026-03-27T16:46:24Z",
|
||||
"event_type": "kill", "description": "Killed Ahri", "uri": "",
|
||||
"raw_data": {"KillerName": "Me#EUW", "VictimName": "Ahri", "Assisters": []}},
|
||||
{"video_timestamp": [1500, 500000000], "event_type": "lp_change", "description": "",
|
||||
"raw_data": {"leaguePointsDelta": 21, "leaguePoints": 74, "tier": "EMERALD", "division": "II"}}
|
||||
],
|
||||
"raw_session": {"gameData": {"queue": {"name": "Ranked Solo", "id": 420}}},
|
||||
"raw_end_game_stats": {"gameLength": 1830, "localPlayer": {"championName": "Kai'Sa",
|
||||
"riotIdGameName": "Demo", "riotIdTagLine": "EUW",
|
||||
"stats": {"CHAMPIONS_KILLED": 9, "NUM_DEATHS": 3, "ASSISTS": 7, "MINIONS_KILLED": 214,
|
||||
"GOLD_EARNED": 13450, "VISION_SCORE": 32, "WIN": 1, "LOSE": 0}}},
|
||||
"video_file": "2026-03-27_16-42-52_unknown.mp4"
|
||||
}"#;
|
||||
|
||||
fn parsed() -> Timeline {
|
||||
serde_json::from_str(TIMELINE).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timeline_parses_with_duration_tuples() {
|
||||
let timeline = parsed();
|
||||
assert_eq!(timeline.duration_secs, 1830);
|
||||
assert!((timeline.events[0].time() - 212.0).abs() < 1e-9);
|
||||
assert!((timeline.events[1].time() - 1500.5).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_game_values_come_out_of_the_raw_responses() {
|
||||
let timeline = parsed();
|
||||
assert_eq!(timeline.champion().as_deref(), Some("Kai'Sa"));
|
||||
assert_eq!(timeline.summoner().as_deref(), Some("Demo#EUW"));
|
||||
assert_eq!(timeline.outcome(), Outcome::Victory);
|
||||
assert_eq!(timeline.queue_label(), "Ranked Solo");
|
||||
assert_eq!(timeline.category(), QueueCategory::RankedSolo);
|
||||
let stats = timeline.stats().unwrap();
|
||||
assert_eq!((stats.kills, stats.deaths, stats.assists), (9, 3, 7));
|
||||
assert_eq!(stats.creep_score, 214);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lp_event_is_the_ranked_one() {
|
||||
let lp = parsed().lp_change().unwrap();
|
||||
assert_eq!(lp.delta, 21);
|
||||
assert_eq!(lp.tier, "EMERALD");
|
||||
assert_eq!(lp.league_points, 74);
|
||||
}
|
||||
#[test]
|
||||
fn a_summary_keeps_what_the_row_shows() {
|
||||
let summary = parsed().summary();
|
||||
assert_eq!(summary.recording_id, "0b7d3f6e-2f4a-4b83-9f0e-0d5c9f1a2b3c");
|
||||
assert_eq!(summary.champion().as_deref(), Some("Kai'Sa"));
|
||||
assert_eq!(summary.queue_label(), "Ranked Solo");
|
||||
assert_eq!(summary.outcome(), Outcome::Victory);
|
||||
assert_eq!(summary.event_count, 2);
|
||||
assert_eq!(summary.stats().unwrap().kills, 9);
|
||||
assert_eq!(summary.lp_change().unwrap().delta, 21);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_read_summaries_from_disk() {
|
||||
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("game.json");
|
||||
std::fs::write(&path, TIMELINE).unwrap();
|
||||
let rows = summaries(&[path, dir.join("missing.json")]);
|
||||
assert_eq!(rows.len(), 1, "a file that cannot be read is skipped");
|
||||
assert_eq!(rows[0].champion().as_deref(), Some("Kai'Sa"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
#[test]
|
||||
fn a_video_is_found_by_its_timestamp_prefix() {
|
||||
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("2026-03-27_16-42-52_kai_sa.mp4"), b"x").unwrap();
|
||||
let found = find_video_file(&dir, "2026-03-27_16-42-52_unknown.mp4").unwrap();
|
||||
assert!(found.ends_with("2026-03-27_16-42-52_kai_sa.mp4"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_recording_removes_its_timeline_and_its_clip() {
|
||||
let dir = std::env::temp_dir().join(format!("leaguerecorder-{}", uuid::Uuid::new_v4()));
|
||||
std::fs::create_dir_all(dir.join("timelines")).unwrap();
|
||||
std::fs::write(dir.join("timelines").join("game.json"), TIMELINE).unwrap();
|
||||
std::fs::write(dir.join("2026-03-27_16-42-52_kai_sa.mp4"), b"x").unwrap();
|
||||
|
||||
delete_in("game", Some("2026-03-27_16-42-52_unknown.mp4"), &dir).unwrap();
|
||||
assert!(!dir.join("timelines").join("game.json").exists());
|
||||
assert!(!dir.join("2026-03-27_16-42-52_kai_sa.mp4").exists());
|
||||
|
||||
// What is already gone is not an error.
|
||||
delete_in("game", Some("2026-03-27_16-42-52_unknown.mp4"), &dir).unwrap();
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! The few shapes the app draws itself: transport arrows, a play triangle and pause bars.
|
||||
//!
|
||||
//! Rune renders an [`Icon`] from SVG paths tinted with the element's colour, so these are plain
|
||||
//! geometry at a 16 point box and need no font behind them.
|
||||
|
||||
use rune::Icon;
|
||||
|
||||
pub static PLAY: Icon = Icon {
|
||||
name: "app-play",
|
||||
view: 16.0,
|
||||
body: r#"<path d="M5.4 3.4 12.6 8 5.4 12.6Z" fill="currentColor"/>"#,
|
||||
};
|
||||
|
||||
pub static PAUSE: Icon = Icon {
|
||||
name: "app-pause",
|
||||
view: 16.0,
|
||||
body: r#"<rect x="5" y="3.6" width="2.4" height="8.8" rx="0.6" fill="currentColor"/><rect x="8.6" y="3.6" width="2.4" height="8.8" rx="0.6" fill="currentColor"/>"#,
|
||||
};
|
||||
|
||||
/// Two triangles pointing back: a step of ten seconds, as the button says.
|
||||
pub static BACK: Icon = Icon {
|
||||
name: "app-back",
|
||||
view: 16.0,
|
||||
body: r#"<path d="M2.8 8 7.2 4.6v6.8Z" fill="currentColor"/><path d="M7.6 8 12 4.6v6.8Z" fill="currentColor"/>"#,
|
||||
};
|
||||
|
||||
pub static FORWARD: Icon = Icon {
|
||||
name: "app-forward",
|
||||
view: 16.0,
|
||||
body: r#"<path d="M13.2 8 8.8 4.6v6.8Z" fill="currentColor"/><path d="M8.4 8 4 4.6v6.8Z" fill="currentColor"/>"#,
|
||||
};
|
||||
|
||||
/// One end of the clip: a single chevron, drawn on the scrubber over the knob.
|
||||
pub static CHEVRON_LEFT: Icon = Icon {
|
||||
name: "app-chevron-left",
|
||||
view: 16.0,
|
||||
body: r#"<path d="M10 3.6 5.4 8 10 12.4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>"#,
|
||||
};
|
||||
|
||||
pub static CHEVRON_RIGHT: Icon = Icon {
|
||||
name: "app-chevron-right",
|
||||
view: 16.0,
|
||||
body: r#"<path d="M6 3.6 10.6 8 6 12.4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>"#,
|
||||
};
|
||||
|
||||
/// Three vertical dots: the button that opens a card's menu of actions.
|
||||
pub static DOTS: Icon = Icon {
|
||||
name: "app-dots",
|
||||
view: 16.0,
|
||||
body: r#"<circle cx="8" cy="3.6" r="1.7" fill="currentColor"/><circle cx="8" cy="8" r="1.7" fill="currentColor"/><circle cx="8" cy="12.4" r="1.7" fill="currentColor"/>"#,
|
||||
};
|
||||
+498
@@ -0,0 +1,498 @@
|
||||
//! Client for the record-daemon's IPC protocol.
|
||||
//!
|
||||
//! Ported from `tauri-app/src-tauri/src/daemon_ipc.rs`. The wire format is the daemon's
|
||||
//! (`record-daemon/src/ipc/protocol.rs`): one JSON object per line over a named pipe, a
|
||||
//! `request` answered by one `response` with the same id.
|
||||
//!
|
||||
//! Requests are async (tokio). The UI runs on rune's thread and never blocks, so a worker thread
|
||||
//! owns a current-thread runtime, executes one request at a time and pushes results into a queue
|
||||
//! that `poll` drains.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Protocol
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Message type, as the daemon's `MessageType`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum MessageType {
|
||||
Request,
|
||||
Response,
|
||||
Notification,
|
||||
}
|
||||
|
||||
/// Commands the daemon accepts (`IpcCommand`, camelCase).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Command {
|
||||
GetSettings,
|
||||
UpdateSettings,
|
||||
ResetSettings,
|
||||
GetStatus,
|
||||
GetEncoders,
|
||||
GetAudioDevices,
|
||||
AddAudioSource,
|
||||
RemoveAudioSource { id: String },
|
||||
UpdateAudioSource,
|
||||
StartRecording,
|
||||
StopRecording,
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
/// Request envelope.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct IpcMessage {
|
||||
#[serde(rename = "type")]
|
||||
pub message_type: MessageType,
|
||||
pub id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub command: Option<Command>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub payload: Option<Value>,
|
||||
}
|
||||
|
||||
/// Response envelope.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct IpcResponse {
|
||||
pub request_id: String,
|
||||
pub success: bool,
|
||||
#[serde(default)]
|
||||
pub data: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// The pipe the daemon listens on. A scratch home, as scripts set, gets a pipe of its own.
|
||||
pub fn default_socket_path() -> PathBuf {
|
||||
let scratch = std::env::var_os(crate::daemon::HOME_ENV).is_some_and(|value| !value.is_empty());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
if scratch {
|
||||
return PathBuf::from(r"\\.\pipe\record-daemon-scratch");
|
||||
}
|
||||
PathBuf::from(r"\\.\pipe\record-daemon")
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let name = if scratch {
|
||||
"record-daemon-scratch.sock"
|
||||
} else {
|
||||
"record-daemon.sock"
|
||||
};
|
||||
let dir = std::env::var("XDG_RUNTIME_DIR").unwrap_or_else(|_| "/tmp".into());
|
||||
Path::new(&dir).join(name)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Client
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pub struct Client {
|
||||
path: PathBuf,
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
path: default_socket_path(),
|
||||
timeout: Duration::from_secs(5),
|
||||
}
|
||||
}
|
||||
|
||||
/// Send one command and wait for its answer.
|
||||
pub async fn call(&self, command: Command, payload: Option<Value>) -> Result<Value, String> {
|
||||
let message = IpcMessage {
|
||||
message_type: MessageType::Request,
|
||||
id: uuid::Uuid::new_v4().to_string(),
|
||||
command: Some(command),
|
||||
payload,
|
||||
};
|
||||
let json = serde_json::to_string(&message).map_err(|e| format!("serialize: {e}"))?;
|
||||
let line = self.round_trip(&json).await?;
|
||||
let response: IpcResponse =
|
||||
serde_json::from_str(&line).map_err(|e| format!("parse response: {e}"))?;
|
||||
if response.success {
|
||||
Ok(response.data.unwrap_or(Value::Null))
|
||||
} else {
|
||||
Err(response
|
||||
.error
|
||||
.unwrap_or_else(|| "daemon returned an error".into()))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn is_running(&self) -> bool {
|
||||
self.call(Command::GetStatus, None).await.is_ok()
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
async fn round_trip(&self, message: &str) -> Result<String, String> {
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::windows::named_pipe::ClientOptions;
|
||||
|
||||
let pipe = self.path.to_string_lossy().to_string();
|
||||
let client = tokio::time::timeout(self.timeout, async {
|
||||
let mut attempts = 0;
|
||||
loop {
|
||||
match ClientOptions::new().open(&pipe) {
|
||||
Ok(client) => return Ok(client),
|
||||
// ERROR_PIPE_BUSY: every instance is serving another client.
|
||||
Err(e) if e.raw_os_error() == Some(231) => {
|
||||
attempts += 1;
|
||||
if attempts > 5 {
|
||||
return Err(format!("daemon pipe busy: {e}"));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
Err(e) => return Err(format!("cannot connect to daemon: {e}")),
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| "connecting to the daemon timed out".to_string())??;
|
||||
|
||||
let (reader, mut writer) = tokio::io::split(client);
|
||||
writer
|
||||
.write_all(message.as_bytes())
|
||||
.await
|
||||
.map_err(|e| format!("write: {e}"))?;
|
||||
writer
|
||||
.write_all(b"\n")
|
||||
.await
|
||||
.map_err(|e| format!("write: {e}"))?;
|
||||
writer.flush().await.map_err(|e| format!("flush: {e}"))?;
|
||||
|
||||
let mut lines = BufReader::new(reader).lines();
|
||||
let line = tokio::time::timeout(self.timeout, lines.next_line())
|
||||
.await
|
||||
.map_err(|_| "the daemon did not answer in time".to_string())?
|
||||
.map_err(|e| format!("read: {e}"))?;
|
||||
line.ok_or_else(|| "the daemon closed the pipe without answering".to_string())
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
async fn round_trip(&self, message: &str) -> Result<String, String> {
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
let stream = tokio::time::timeout(self.timeout, UnixStream::connect(&self.path))
|
||||
.await
|
||||
.map_err(|_| "connecting to the daemon timed out".to_string())?
|
||||
.map_err(|e| format!("cannot connect to daemon: {e}"))?;
|
||||
let (reader, mut writer) = stream.into_split();
|
||||
writer
|
||||
.write_all(message.as_bytes())
|
||||
.await
|
||||
.map_err(|e| format!("write: {e}"))?;
|
||||
writer
|
||||
.write_all(b"\n")
|
||||
.await
|
||||
.map_err(|e| format!("write: {e}"))?;
|
||||
writer.flush().await.map_err(|e| format!("flush: {e}"))?;
|
||||
let mut lines = BufReader::new(reader).lines();
|
||||
let line = tokio::time::timeout(self.timeout, lines.next_line())
|
||||
.await
|
||||
.map_err(|_| "the daemon did not answer in time".to_string())?
|
||||
.map_err(|e| format!("read: {e}"))?;
|
||||
line.ok_or_else(|| "the daemon closed the socket without answering".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Background worker
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// What a queued request is for, so `poll` can route its answer.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Request {
|
||||
EnsureRunning,
|
||||
Settings,
|
||||
SaveSettings,
|
||||
ResetSettings,
|
||||
Status,
|
||||
Encoders,
|
||||
AudioDevices,
|
||||
AddAudioSource,
|
||||
RemoveAudioSource,
|
||||
UpdateAudioSource,
|
||||
StartRecording,
|
||||
StopRecording,
|
||||
Shutdown,
|
||||
Logs,
|
||||
}
|
||||
|
||||
struct Job {
|
||||
request: Request,
|
||||
command: Command,
|
||||
payload: Option<Value>,
|
||||
}
|
||||
|
||||
/// An answer from the worker thread.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Event {
|
||||
pub request: Request,
|
||||
pub result: Result<Value, String>,
|
||||
}
|
||||
|
||||
/// A cloneable handle to the worker thread.
|
||||
#[derive(Clone)]
|
||||
pub struct Daemon {
|
||||
jobs: Sender<Job>,
|
||||
events: Arc<Mutex<Receiver<Event>>>,
|
||||
waker: Arc<Mutex<Option<rune::Waker>>>,
|
||||
/// Headless runs keep no worker and send nothing.
|
||||
off: bool,
|
||||
}
|
||||
|
||||
impl Daemon {
|
||||
/// Start the worker. It also brings the daemon process up on first use.
|
||||
/// A headless run (`--snap` and friends) starts nothing and talks to nobody.
|
||||
pub fn start(headless: bool) -> Self {
|
||||
let (job_tx, job_rx) = channel::<Job>();
|
||||
let (event_tx, event_rx) = channel::<Event>();
|
||||
let waker: Arc<Mutex<Option<rune::Waker>>> = Arc::new(Mutex::new(None));
|
||||
let worker_waker = waker.clone();
|
||||
if headless {
|
||||
return Self {
|
||||
jobs: job_tx,
|
||||
events: Arc::new(Mutex::new(event_rx)),
|
||||
waker,
|
||||
off: true,
|
||||
};
|
||||
}
|
||||
|
||||
std::thread::Builder::new()
|
||||
.name("daemon-ipc".into())
|
||||
.spawn(move || {
|
||||
let runtime = match tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
{
|
||||
Ok(rt) => rt,
|
||||
Err(e) => {
|
||||
let _ = event_tx.send(Event {
|
||||
request: Request::EnsureRunning,
|
||||
result: Err(format!("no async runtime: {e}")),
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
let client = Client::new();
|
||||
// Bring the daemon up before the first request. It takes a few seconds to
|
||||
// initialise OBS, so this must not run on the UI thread.
|
||||
let started = runtime
|
||||
.block_on(crate::daemon::ensure_running())
|
||||
.map(|_| Value::Null);
|
||||
let _ = event_tx.send(Event {
|
||||
request: Request::EnsureRunning,
|
||||
result: started,
|
||||
});
|
||||
wake(&worker_waker);
|
||||
|
||||
while let Ok(job) = job_rx.recv() {
|
||||
let result = match job.request {
|
||||
Request::EnsureRunning => runtime
|
||||
.block_on(crate::daemon::ensure_running())
|
||||
.map(|_| Value::Null),
|
||||
Request::Logs => crate::daemon::read_logs(200).map(Value::String),
|
||||
_ => runtime.block_on(client.call(job.command, job.payload)),
|
||||
};
|
||||
let _ = event_tx.send(Event {
|
||||
request: job.request,
|
||||
result,
|
||||
});
|
||||
wake(&worker_waker);
|
||||
}
|
||||
})
|
||||
.expect("spawn daemon worker");
|
||||
|
||||
Self {
|
||||
jobs: job_tx,
|
||||
events: Arc::new(Mutex::new(event_rx)),
|
||||
waker,
|
||||
off: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The waker rune hands to `AppSpec::setup`.
|
||||
pub fn set_waker(&self, waker: rune::Waker) {
|
||||
*self.waker.lock().unwrap() = Some(waker);
|
||||
}
|
||||
|
||||
fn send(&self, request: Request, command: Command, payload: Option<Value>) {
|
||||
if self.off {
|
||||
return;
|
||||
}
|
||||
let _ = self.jobs.send(Job {
|
||||
request,
|
||||
command,
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn get_settings(&self) {
|
||||
self.send(Request::Settings, Command::GetSettings, None);
|
||||
}
|
||||
|
||||
pub fn save_settings(&self, settings: Value) {
|
||||
self.send(
|
||||
Request::SaveSettings,
|
||||
Command::UpdateSettings,
|
||||
Some(settings),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn reset_settings(&self) {
|
||||
self.send(Request::ResetSettings, Command::ResetSettings, None);
|
||||
}
|
||||
|
||||
pub fn get_status(&self) {
|
||||
self.send(Request::Status, Command::GetStatus, None);
|
||||
}
|
||||
|
||||
pub fn get_encoders(&self) {
|
||||
self.send(Request::Encoders, Command::GetEncoders, None);
|
||||
}
|
||||
|
||||
pub fn get_audio_devices(&self) {
|
||||
self.send(Request::AudioDevices, Command::GetAudioDevices, None);
|
||||
}
|
||||
|
||||
pub fn add_audio_source(&self, source: Value) {
|
||||
self.send(
|
||||
Request::AddAudioSource,
|
||||
Command::AddAudioSource,
|
||||
Some(source),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn remove_audio_source(&self, id: &str) {
|
||||
self.send(
|
||||
Request::RemoveAudioSource,
|
||||
Command::RemoveAudioSource { id: id.to_string() },
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn update_audio_source(&self, source: Value) {
|
||||
self.send(
|
||||
Request::UpdateAudioSource,
|
||||
Command::UpdateAudioSource,
|
||||
Some(source),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn start_recording(&self) {
|
||||
self.send(Request::StartRecording, Command::StartRecording, None);
|
||||
}
|
||||
|
||||
pub fn stop_recording(&self) {
|
||||
self.send(Request::StopRecording, Command::StopRecording, None);
|
||||
}
|
||||
|
||||
pub fn shutdown(&self) {
|
||||
self.send(Request::Shutdown, Command::Shutdown, None);
|
||||
}
|
||||
|
||||
pub fn ensure_running(&self) {
|
||||
self.send(Request::EnsureRunning, Command::GetStatus, None);
|
||||
}
|
||||
|
||||
pub fn logs(&self) {
|
||||
self.send(Request::Logs, Command::GetStatus, None);
|
||||
}
|
||||
|
||||
/// Answers that arrived since the last frame, without blocking.
|
||||
pub fn drain(&self) -> Vec<Event> {
|
||||
let rx = self.events.lock().unwrap();
|
||||
let mut out = Vec::new();
|
||||
while let Ok(event) = rx.try_recv() {
|
||||
out.push(event);
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
fn wake(waker: &Mutex<Option<rune::Waker>>) {
|
||||
if let Some(w) = waker.lock().unwrap().as_ref() {
|
||||
w();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn request(command: Command, payload: Option<Value>) -> Value {
|
||||
let message = IpcMessage {
|
||||
message_type: MessageType::Request,
|
||||
id: "00000000-0000-4000-8000-000000000000".into(),
|
||||
command: Some(command),
|
||||
payload,
|
||||
};
|
||||
serde_json::to_value(message).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_unit_command_is_a_plain_string() {
|
||||
assert_eq!(
|
||||
request(Command::GetSettings, None),
|
||||
json!({
|
||||
"type": "request",
|
||||
"id": "00000000-0000-4000-8000-000000000000",
|
||||
"command": "getSettings"
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_command_with_a_field_is_an_object() {
|
||||
assert_eq!(
|
||||
request(Command::RemoveAudioSource { id: "abc".into() }, None),
|
||||
json!({
|
||||
"type": "request",
|
||||
"id": "00000000-0000-4000-8000-000000000000",
|
||||
"command": {"removeAudioSource": {"id": "abc"}}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_go_in_the_payload_untouched() {
|
||||
let payload = json!({"video": {"frame_rate": 60}});
|
||||
assert_eq!(
|
||||
request(Command::UpdateSettings, Some(payload.clone()))["payload"],
|
||||
payload
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn responses_parse_with_and_without_data() {
|
||||
let ok: IpcResponse =
|
||||
serde_json::from_str(r#"{"request_id":"x","success":true,"data":{"a":1}}"#).unwrap();
|
||||
assert!(ok.success);
|
||||
assert_eq!(ok.data.unwrap()["a"], 1);
|
||||
|
||||
let err: IpcResponse =
|
||||
serde_json::from_str(r#"{"request_id":"x","success":false,"error":"nope"}"#).unwrap();
|
||||
assert!(!err.success);
|
||||
assert_eq!(err.error.as_deref(), Some("nope"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pipe_name_matches_the_daemon() {
|
||||
assert_eq!(
|
||||
default_socket_path().to_string_lossy(),
|
||||
r"\\.\pipe\record-daemon"
|
||||
);
|
||||
}
|
||||
}
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
//! League Recorder: a native desktop app for the record-daemon.
|
||||
//!
|
||||
//! Replaces `tauri-app`. The daemon keeps its IPC protocol; this app is a client of it.
|
||||
//! `cargo run` opens the window; `cargo run -- --snap out.png` renders it headless.
|
||||
//!
|
||||
//! The binary is a windowed app on Windows, so launching it from Explorer, the Run key or the
|
||||
//! login item never opens a console. The printing modes (`--games`, `--probe`, `--snap`) borrow
|
||||
//! the console of the shell that started them (`attach_console`).
|
||||
#![cfg_attr(target_os = "windows", windows_subsystem = "windows")]
|
||||
|
||||
mod app;
|
||||
mod daemon;
|
||||
mod export;
|
||||
mod format;
|
||||
mod highlight;
|
||||
mod history;
|
||||
mod icons;
|
||||
mod ipc;
|
||||
mod os;
|
||||
mod portraits;
|
||||
mod process;
|
||||
mod screens;
|
||||
mod settings;
|
||||
mod theme;
|
||||
mod ui;
|
||||
|
||||
/// Print to the shell that started this app, when there is one.
|
||||
///
|
||||
/// A windowed process has no console of its own, so `println!` from `--probe` or `--snap` would
|
||||
/// go nowhere under `cmd`. The shell's console is still there to attach to; when the app is
|
||||
/// started from Explorer or the login item there is none and this does nothing.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn attach_console() {
|
||||
use windows::Win32::System::Console::{ATTACH_PARENT_PROCESS, AttachConsole};
|
||||
unsafe {
|
||||
let _ = AttachConsole(ATTACH_PARENT_PROCESS);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
fn attach_console() {}
|
||||
|
||||
use rune::AppSpec;
|
||||
|
||||
fn main() {
|
||||
attach_console();
|
||||
if std::env::args().any(|arg| arg == "--games") {
|
||||
println!("{} timelines", crate::history::timeline_paths().len());
|
||||
return;
|
||||
}
|
||||
if std::env::args().any(|arg| arg == "--probe") {
|
||||
probe();
|
||||
return;
|
||||
}
|
||||
// `--fetch-ffmpeg`: download ffmpeg beside the exe and exit, 0 when it is ready. The app
|
||||
// does this itself on the first run; this is the same fetch, for a shortcut or a script.
|
||||
if std::env::args().any(|arg| arg == "--fetch-ffmpeg") {
|
||||
fetch_ffmpeg();
|
||||
return;
|
||||
}
|
||||
// A second launch hands its arguments to the first and exits; the tooling modes
|
||||
// (`--snap`, `--tree`, that sort of thing) render or print and exit, so they never forward.
|
||||
if !app::headless() && !rune::single_instance(os::APP_ID) {
|
||||
return;
|
||||
}
|
||||
os::set_app_icon();
|
||||
os::register_notifications();
|
||||
rune_notify::on_click(|_| rune_notify::bring_to_front());
|
||||
|
||||
let mut hidden = false;
|
||||
let args: Vec<String> = std::env::args()
|
||||
.filter(|arg| {
|
||||
if arg == "--hidden" {
|
||||
hidden = true;
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
rune::App::new(AppSpec {
|
||||
scenes: &[
|
||||
("history", |_app: &mut app::App| {}),
|
||||
("settings", |app| app.screen = app::Screen::Settings),
|
||||
("recording", |app| {
|
||||
app.screen = app::Screen::Settings;
|
||||
app.settings_tab = app::SettingsTab::Recording;
|
||||
}),
|
||||
("audio", |app| {
|
||||
app.screen = app::Screen::Settings;
|
||||
app.settings_tab = app::SettingsTab::Audio;
|
||||
}),
|
||||
("add-app", |app| {
|
||||
app.screen = app::Screen::Settings;
|
||||
app.settings_tab = app::SettingsTab::Audio;
|
||||
app.form.open_add();
|
||||
app.form.source_name = rune::TextEdit::new("Discord");
|
||||
app.form.source_device = rune::TextEdit::new("Discord.exe");
|
||||
}),
|
||||
("delete", |app| {
|
||||
app.confirm_delete = app.games.first().map(|game| game.recording_id.clone());
|
||||
}),
|
||||
("daemon", |app| {
|
||||
app.screen = app::Screen::Settings;
|
||||
app.settings_tab = app::SettingsTab::Advanced;
|
||||
}),
|
||||
("review", |app| app::demo_review(app)),
|
||||
("details", |app| {
|
||||
app::demo_review(app);
|
||||
app.review.show_details = true;
|
||||
}),
|
||||
("many", |app| {
|
||||
app.screen = app::Screen::History;
|
||||
app.games = (0..30)
|
||||
.flat_map(|_| crate::history::sample())
|
||||
.map(|game| game.summary())
|
||||
.collect();
|
||||
app.games_loaded = true;
|
||||
}),
|
||||
],
|
||||
setup: Some(app::setup),
|
||||
poll: Some(app::poll),
|
||||
on_key: Some(app::on_key),
|
||||
..AppSpec::new("League Recorder", (1200.0, 800.0), app::App::new, app::view)
|
||||
})
|
||||
.args(args)
|
||||
.keep_running()
|
||||
.on_ready(move |handle| {
|
||||
app::remember_window(handle);
|
||||
if hidden {
|
||||
handle.hide();
|
||||
}
|
||||
})
|
||||
.run();
|
||||
}
|
||||
|
||||
/// `--fetch-ffmpeg`: download ffmpeg with the same code the first run uses, printing progress.
|
||||
fn fetch_ffmpeg() {
|
||||
let shown = std::cell::Cell::new(u64::MAX);
|
||||
let result = export::fetch(|event| match event {
|
||||
export::FetchEvent::Bytes { done, total } => {
|
||||
let pct = (done * 100).checked_div(total).unwrap_or(0);
|
||||
if pct != shown.get() {
|
||||
shown.set(pct);
|
||||
println!("ffmpeg: {pct}%");
|
||||
}
|
||||
}
|
||||
export::FetchEvent::Unpacking => println!("ffmpeg: unpacking"),
|
||||
export::FetchEvent::Finished(_) => {}
|
||||
});
|
||||
match result {
|
||||
Ok(()) => println!("ffmpeg: ready"),
|
||||
Err(e) => {
|
||||
eprintln!("{e}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `--probe`: bring the daemon up and print what it answers, then exit. A quick check that the
|
||||
/// IPC client and the daemon agree without opening a window.
|
||||
fn probe() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("async runtime");
|
||||
runtime.block_on(async {
|
||||
match daemon::ensure_running().await {
|
||||
Ok(()) => println!("daemon: ready"),
|
||||
Err(e) => {
|
||||
println!("daemon: {e}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
let client = ipc::Client::new();
|
||||
for (name, command) in [
|
||||
("status", ipc::Command::GetStatus),
|
||||
("settings", ipc::Command::GetSettings),
|
||||
("encoders", ipc::Command::GetEncoders),
|
||||
("audioDevices", ipc::Command::GetAudioDevices),
|
||||
] {
|
||||
match client.call(command, None).await {
|
||||
Ok(data) => println!("{name}: {data}"),
|
||||
Err(e) => println!("{name}: error: {e}"),
|
||||
}
|
||||
}
|
||||
// Parse with the app model, which is what the settings screen receives.
|
||||
match client.call(ipc::Command::GetSettings, None).await {
|
||||
Ok(data) => match crate::settings::from_response(&data) {
|
||||
Ok(settings) => println!(
|
||||
"parsed: {} fps, {:?}, {} application sources, encoder {}",
|
||||
settings.video.frame_rate,
|
||||
settings.video.quality,
|
||||
settings.audio.capture_apps.len(),
|
||||
settings.video.encoder_preset.encoder_id(),
|
||||
),
|
||||
Err(e) => println!("parsed: failed: {e}"),
|
||||
},
|
||||
Err(e) => println!("parsed: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
//! Windows integration that the Tauri app got from plugins: launch at login, one instance,
|
||||
//! toast notifications and the tray icon.
|
||||
|
||||
/// The app's reverse-DNS id, used for single-instance and notifications.
|
||||
pub const APP_ID: &str = "v.leaguerecorder";
|
||||
pub const APP_NAME: &str = "League Recorder";
|
||||
|
||||
#[cfg(windows)]
|
||||
const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
|
||||
#[cfg(windows)]
|
||||
const RUN_VALUE: &str = "LeagueRecorder";
|
||||
|
||||
/// Launch at login writes the executable into the user's `Run` key.
|
||||
#[cfg(windows)]
|
||||
pub fn autostart_enabled() -> bool {
|
||||
use winreg::RegKey;
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
let Ok(key) = RegKey::predef(HKEY_CURRENT_USER).open_subkey(RUN_KEY) else {
|
||||
return false;
|
||||
};
|
||||
key.get_value::<String, _>(RUN_VALUE).is_ok()
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn autostart_enabled() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn set_autostart(on: bool) -> Result<(), String> {
|
||||
use winreg::RegKey;
|
||||
use winreg::enums::HKEY_CURRENT_USER;
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
let (key, _) = hkcu
|
||||
.create_subkey(RUN_KEY)
|
||||
.map_err(|e| format!("cannot open the Run key: {e}"))?;
|
||||
if on {
|
||||
let exe =
|
||||
std::env::current_exe().map_err(|e| format!("cannot find the executable: {e}"))?;
|
||||
let value = format!("\"{}\" --hidden", exe.display());
|
||||
key.set_value(RUN_VALUE, &value)
|
||||
.map_err(|e| format!("cannot write the Run key: {e}"))
|
||||
} else {
|
||||
match key.delete_value(RUN_VALUE) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||
Err(e) => Err(format!("cannot remove the Run value: {e}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn set_autostart(_on: bool) -> Result<(), String> {
|
||||
Err("launch at login is implemented for Windows only".into())
|
||||
}
|
||||
|
||||
/// Register the app so Windows can show its toasts, and group its windows on the taskbar.
|
||||
pub fn register_notifications() {
|
||||
let identity = rune_notify::Identity::new(APP_ID, APP_NAME);
|
||||
if let Err(e) = rune_notify::register(&identity) {
|
||||
eprintln!("notifications unavailable: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Post a toast, unless a window already has the user's attention.
|
||||
pub fn notify(id: &str, title: &str, body: &str) {
|
||||
if rune_notify::app_focused() {
|
||||
return;
|
||||
}
|
||||
let notification = rune_notify::Notification::new(id, title).body(body);
|
||||
rune_notify::post(¬ification);
|
||||
}
|
||||
|
||||
/// The app's icon for the title bar, the taskbar and Alt+Tab: the same medallion the exe
|
||||
/// carries and the installer shows. Call once at startup, before the event loop; rune sizes
|
||||
/// it for each use and a headless run sets nothing.
|
||||
pub fn set_app_icon() {
|
||||
let bytes = include_bytes!("../icons/icon_full.png").as_slice();
|
||||
if let Err(e) = rune::set_app_icon(bytes) {
|
||||
eprintln!("app icon unavailable: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A 32 px tray icon: the app's medallion, decoded to the straight RGBA rows the tray takes.
|
||||
pub fn tray_icon() -> rune::TrayIcon {
|
||||
let (width, height, pixels) = tray_icon_pixels();
|
||||
rune::TrayIcon::rgba(width, height, pixels)
|
||||
}
|
||||
|
||||
/// The medallion at its bundled 32 px: straight RGBA rows for [`rune::TrayIcon`].
|
||||
fn tray_icon_pixels() -> (u32, u32, Vec<u8>) {
|
||||
let image = image::load_from_memory(include_bytes!("../icons/32x32.png"))
|
||||
.expect("the bundled tray icon decodes")
|
||||
.into_rgba8();
|
||||
(image.width(), image.height(), image.into_raw())
|
||||
}
|
||||
|
||||
/// The tray menu. `recording` flips the record item's label.
|
||||
pub fn tray_menu(recording: bool) -> Vec<rune::TrayItem> {
|
||||
vec![
|
||||
rune::TrayItem::action("show", "Open League Recorder"),
|
||||
rune::TrayItem::action("hide", "Hide window"),
|
||||
rune::TrayItem::Separator,
|
||||
rune::TrayItem::action(
|
||||
"record",
|
||||
if recording {
|
||||
"Stop recording"
|
||||
} else {
|
||||
"Start recording"
|
||||
},
|
||||
),
|
||||
rune::TrayItem::Separator,
|
||||
rune::TrayItem::action("quit", "Quit"),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_tray_icon_decodes_to_32_px_of_rgba() {
|
||||
let (width, height, pixels) = tray_icon_pixels();
|
||||
assert_eq!((width, height), (32, 32));
|
||||
assert_eq!(pixels.len(), (32 * 32 * 4) as usize);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Champion portraits, fetched from Data Dragon and cached on disk.
|
||||
//!
|
||||
//! Rune decodes images but has no HTTP client on native, so the bytes come down here first. A
|
||||
//! portrait is drawn as soon as it is on disk, and the app redraws when a download lands.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::io::Read;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{Receiver, Sender, channel};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Riot's public asset CDN.
|
||||
const HOST: &str = "https://ddragon.leagueoflegends.com";
|
||||
|
||||
/// The champion list: Data Dragon ids ("Kaisa") by display name ("Kai'Sa"), for one patch.
|
||||
#[derive(Clone, serde::Deserialize, serde::Serialize)]
|
||||
struct Catalog {
|
||||
version: String,
|
||||
ids: HashMap<String, String>,
|
||||
}
|
||||
|
||||
/// Where the portraits and the champion list are cached.
|
||||
fn cache_dir() -> PathBuf {
|
||||
directories::ProjectDirs::from("com", "leaguerecorder", "leaguerecorder")
|
||||
.map(|dirs| dirs.cache_dir().join("portraits"))
|
||||
.unwrap_or_else(|| PathBuf::from("./portraits"))
|
||||
}
|
||||
|
||||
/// Champion portraits drawn from the cache, with the missing ones fetched in the background.
|
||||
pub struct Portraits {
|
||||
dir: PathBuf,
|
||||
images: rune::ImageCache,
|
||||
catalog: Arc<Mutex<Option<Catalog>>>,
|
||||
asked: Mutex<HashSet<String>>,
|
||||
tx: Sender<String>,
|
||||
}
|
||||
|
||||
impl Portraits {
|
||||
pub fn new(waker: rune::Waker) -> Self {
|
||||
let dir = cache_dir();
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let catalog = Arc::new(Mutex::new(read_catalog(&dir)));
|
||||
let (tx, rx) = channel();
|
||||
let worker = Worker {
|
||||
dir: dir.clone(),
|
||||
catalog: catalog.clone(),
|
||||
wake: waker.clone(),
|
||||
};
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name("portraits".into())
|
||||
.spawn(move || worker.run(rx));
|
||||
if spawned.is_err() {
|
||||
eprintln!("portrait downloads are unavailable");
|
||||
}
|
||||
Self {
|
||||
dir,
|
||||
images: rune::ImageCache::new(waker),
|
||||
catalog,
|
||||
asked: Mutex::new(HashSet::new()),
|
||||
tx,
|
||||
}
|
||||
}
|
||||
|
||||
/// The portrait for a champion's display name at `size` points, once it is on disk. A
|
||||
/// missing one is queued and the app redraws when it arrives.
|
||||
pub fn image(&self, champion: &str, size: f32, scale: f32) -> Option<rune::Image> {
|
||||
let champion = champion.trim();
|
||||
if champion.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let path = {
|
||||
let catalog = self.catalog.lock().unwrap();
|
||||
let Some(catalog) = catalog.as_ref() else {
|
||||
drop(catalog);
|
||||
self.ask(champion);
|
||||
return None;
|
||||
};
|
||||
let id = catalog.ids.get(champion)?;
|
||||
self.dir.join(format!("{id}.png"))
|
||||
};
|
||||
if !path.is_file() {
|
||||
self.ask(champion);
|
||||
return None;
|
||||
}
|
||||
Some(self.images.file(&path, size, scale))
|
||||
}
|
||||
|
||||
fn ask(&self, champion: &str) {
|
||||
if self.asked.lock().unwrap().insert(champion.to_string()) {
|
||||
let _ = self.tx.send(champion.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The cache's background thread: the champion list first, then one portrait at a time.
|
||||
struct Worker {
|
||||
dir: PathBuf,
|
||||
catalog: Arc<Mutex<Option<Catalog>>>,
|
||||
wake: rune::Waker,
|
||||
}
|
||||
|
||||
impl Worker {
|
||||
fn run(self, rx: Receiver<String>) {
|
||||
if self.catalog.lock().unwrap().is_none() {
|
||||
match self.ensure_catalog() {
|
||||
Some(catalog) => {
|
||||
*self.catalog.lock().unwrap() = Some(catalog);
|
||||
(self.wake)();
|
||||
}
|
||||
None => eprintln!("champion list unavailable; drawing initials instead"),
|
||||
}
|
||||
}
|
||||
while let Ok(name) = rx.recv() {
|
||||
self.download(&name);
|
||||
}
|
||||
}
|
||||
|
||||
/// The cached champion list, or a fresh one written next to the portraits.
|
||||
fn ensure_catalog(&self) -> Option<Catalog> {
|
||||
if let Some(catalog) = read_catalog(&self.dir) {
|
||||
return Some(catalog);
|
||||
}
|
||||
let catalog = fetch_catalog()?;
|
||||
let text = serde_json::to_vec(&catalog).ok()?;
|
||||
let path = self.dir.join("catalog.json");
|
||||
let _ = std::fs::write(path.with_extension("part"), text);
|
||||
let _ = std::fs::rename(path.with_extension("part"), &path);
|
||||
Some(catalog)
|
||||
}
|
||||
|
||||
fn download(&self, champion: &str) {
|
||||
let (id, version) = {
|
||||
let catalog = self.catalog.lock().unwrap();
|
||||
let Some(catalog) = catalog.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let Some(id) = catalog.ids.get(champion).cloned() else {
|
||||
return;
|
||||
};
|
||||
(id, catalog.version.clone())
|
||||
};
|
||||
let path = self.dir.join(format!("{id}.png"));
|
||||
if path.is_file() {
|
||||
return;
|
||||
}
|
||||
let url = format!("{HOST}/cdn/{version}/img/champion/{id}.png");
|
||||
let Some(bytes) = get(&url) else {
|
||||
return;
|
||||
};
|
||||
if bytes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let part = path.with_extension("part");
|
||||
if std::fs::write(&part, bytes).is_ok() && std::fs::rename(&part, &path).is_ok() {
|
||||
(self.wake)();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_catalog(dir: &std::path::Path) -> Option<Catalog> {
|
||||
let bytes = std::fs::read(dir.join("catalog.json")).ok()?;
|
||||
serde_json::from_slice(&bytes).ok()
|
||||
}
|
||||
|
||||
/// The champion list of the latest patch: display names to Data Dragon ids.
|
||||
fn fetch_catalog() -> Option<Catalog> {
|
||||
let versions: Vec<String> =
|
||||
serde_json::from_slice(&get(&format!("{HOST}/api/versions.json"))?).ok()?;
|
||||
let version = versions.into_iter().next()?;
|
||||
let url = format!("{HOST}/cdn/{version}/data/en_US/champion.json");
|
||||
let data: serde_json::Value = serde_json::from_slice(&get(&url)?).ok()?;
|
||||
let mut ids = HashMap::new();
|
||||
for (id, champion) in data.get("data")?.as_object()? {
|
||||
if let Some(name) = champion.get("name").and_then(|name| name.as_str()) {
|
||||
ids.insert(name.to_string(), id.clone());
|
||||
}
|
||||
}
|
||||
(!ids.is_empty()).then_some(Catalog { version, ids })
|
||||
}
|
||||
|
||||
fn get(url: &str) -> Option<Vec<u8>> {
|
||||
let mut response = ureq::get(url)
|
||||
.config()
|
||||
.timeout_global(Some(Duration::from_secs(20)))
|
||||
.build()
|
||||
.call()
|
||||
.ok()?;
|
||||
let mut bytes = Vec::new();
|
||||
response
|
||||
.body_mut()
|
||||
.as_reader()
|
||||
.read_to_end(&mut bytes)
|
||||
.ok()?;
|
||||
Some(bytes)
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! Which processes are running, and where their executable lives.
|
||||
//!
|
||||
//! The audio sources name a process (`Discord.exe`); the settings screen wants to say whether
|
||||
//! that process is up and draw its icon. One snapshot of the process table answers both.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// What the settings screen knows about one named process.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Found {
|
||||
pub running: bool,
|
||||
/// The executable to read the icon from, when the snapshot could open the process.
|
||||
pub path: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
/// Running processes by normalised name: lowercase, without the `.exe`.
|
||||
pub type Processes = HashMap<String, Found>;
|
||||
|
||||
/// `Discord.exe` and `discord` are the same process.
|
||||
pub fn normalize(name: &str) -> String {
|
||||
let name = name.trim().to_ascii_lowercase();
|
||||
name.strip_suffix(".exe").unwrap_or(&name).to_string()
|
||||
}
|
||||
|
||||
/// One pass over the process table, keeping only `names`.
|
||||
///
|
||||
/// A name that is not running maps to a `Found` with `running: false`, so the screen can tell
|
||||
/// "not running" from "not asked about yet".
|
||||
pub fn snapshot(names: impl IntoIterator<Item = String>) -> Processes {
|
||||
let wanted: HashMap<String, Found> = names
|
||||
.into_iter()
|
||||
.map(|name| (normalize(&name), Found::default()))
|
||||
.collect();
|
||||
if wanted.is_empty() {
|
||||
return wanted;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows_snapshot(wanted)
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
wanted
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn windows_snapshot(mut wanted: Processes) -> Processes {
|
||||
use windows::Win32::Foundation::CloseHandle;
|
||||
use windows::Win32::System::Diagnostics::ToolHelp::{
|
||||
CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW,
|
||||
TH32CS_SNAPPROCESS,
|
||||
};
|
||||
|
||||
// SAFETY: the snapshot handle is closed below, and `entry` is a plain struct the calls fill.
|
||||
unsafe {
|
||||
let Ok(snapshot) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) else {
|
||||
return wanted;
|
||||
};
|
||||
let mut entry = PROCESSENTRY32W {
|
||||
dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
let mut more = Process32FirstW(snapshot, &mut entry).is_ok();
|
||||
while more {
|
||||
if let Some(found) = wanted.get_mut(&normalize(&exe_name(&entry))) {
|
||||
found.running = true;
|
||||
if found.path.is_none() {
|
||||
found.path = exe_path(entry.th32ProcessID);
|
||||
}
|
||||
}
|
||||
// A process can exit mid-walk, which ends the enumeration early on some builds.
|
||||
more = Process32NextW(snapshot, &mut entry).is_ok();
|
||||
}
|
||||
let _ = CloseHandle(snapshot);
|
||||
}
|
||||
// A program that is not open has no process to read its icon from, so look where Windows
|
||||
// keeps it.
|
||||
for (name, found) in wanted.iter_mut() {
|
||||
if found.path.is_none() {
|
||||
found.path = locate(name);
|
||||
}
|
||||
}
|
||||
wanted
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn exe_name(entry: &windows::Win32::System::Diagnostics::ToolHelp::PROCESSENTRY32W) -> String {
|
||||
let len = entry
|
||||
.szExeFile
|
||||
.iter()
|
||||
.position(|&c| c == 0)
|
||||
.unwrap_or(entry.szExeFile.len());
|
||||
String::from_utf16_lossy(&entry.szExeFile[..len])
|
||||
}
|
||||
|
||||
/// The full path of a process's executable, when it can be opened.
|
||||
#[cfg(windows)]
|
||||
fn exe_path(pid: u32) -> Option<std::path::PathBuf> {
|
||||
use windows::Win32::Foundation::CloseHandle;
|
||||
use windows::Win32::System::Threading::{
|
||||
OpenProcess, PROCESS_NAME_WIN32, PROCESS_QUERY_LIMITED_INFORMATION,
|
||||
QueryFullProcessImageNameW,
|
||||
};
|
||||
use windows::core::PWSTR;
|
||||
|
||||
let mut buffer = [0u16; 512];
|
||||
let mut len = buffer.len() as u32;
|
||||
// SAFETY: `buffer` outlives the call, and `len` carries its capacity in and the written
|
||||
// length out.
|
||||
unsafe {
|
||||
let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?;
|
||||
let query = QueryFullProcessImageNameW(
|
||||
handle,
|
||||
PROCESS_NAME_WIN32,
|
||||
PWSTR(buffer.as_mut_ptr()),
|
||||
&mut len,
|
||||
);
|
||||
let _ = CloseHandle(handle);
|
||||
query.ok()?;
|
||||
}
|
||||
Some(std::path::PathBuf::from(String::from_utf16_lossy(
|
||||
&buffer[..len as usize],
|
||||
)))
|
||||
}
|
||||
|
||||
/// Where a program that is not running might be installed, so its icon can still be drawn.
|
||||
///
|
||||
/// The search is bounded (a few thousand directories, five levels) and remembers its misses, so
|
||||
/// a name costs at most one walk per run of the app.
|
||||
fn locate(name: &str) -> Option<std::path::PathBuf> {
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
static CACHE: OnceLock<Mutex<HashMap<String, Option<std::path::PathBuf>>>> = OnceLock::new();
|
||||
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
if let Some(hit) = cache.lock().ok()?.get(name) {
|
||||
return hit.clone();
|
||||
}
|
||||
let file = format!("{name}.exe");
|
||||
let roots = [
|
||||
"ProgramFiles",
|
||||
"ProgramFiles(x86)",
|
||||
"LOCALAPPDATA",
|
||||
"APPDATA",
|
||||
"ProgramData",
|
||||
];
|
||||
let mut budget = 20_000usize;
|
||||
let found = roots
|
||||
.iter()
|
||||
.filter_map(|var| std::env::var_os(var).map(std::path::PathBuf::from))
|
||||
.find_map(|root| walk(&root, &file, 5, &mut budget));
|
||||
if let Ok(mut cache) = cache.lock() {
|
||||
cache.insert(name.to_string(), found.clone());
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn walk(
|
||||
dir: &std::path::Path,
|
||||
file: &str,
|
||||
depth: u32,
|
||||
budget: &mut usize,
|
||||
) -> Option<std::path::PathBuf> {
|
||||
if depth == 0 || *budget == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut below = Vec::new();
|
||||
for entry in std::fs::read_dir(dir).ok()?.flatten() {
|
||||
*budget = budget.saturating_sub(1);
|
||||
if *budget == 0 {
|
||||
break;
|
||||
}
|
||||
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
|
||||
let path = entry.path();
|
||||
if name == file {
|
||||
return Some(path);
|
||||
}
|
||||
if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
|
||||
below.push(path);
|
||||
}
|
||||
}
|
||||
below
|
||||
.into_iter()
|
||||
.find_map(|dir| walk(&dir, file, depth - 1, budget))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_process_name_ignores_case_and_the_exe_suffix() {
|
||||
assert_eq!(normalize("Discord.exe"), "discord");
|
||||
assert_eq!(normalize(" discord.EXE "), "discord");
|
||||
assert_eq!(normalize("chrome"), "chrome");
|
||||
assert_eq!(normalize(""), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_that_are_not_asked_about_are_not_in_the_snapshot() {
|
||||
let found = snapshot(Vec::new());
|
||||
assert!(found.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn the_process_table_finds_this_test_binary() {
|
||||
let exe = std::env::current_exe().expect("the test binary's path");
|
||||
let name = exe
|
||||
.file_name()
|
||||
.expect("the test binary's name")
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
let found = snapshot(vec![name.clone()]);
|
||||
let found = found
|
||||
.get(&normalize(&name))
|
||||
.expect("the name was asked about");
|
||||
assert!(found.running, "{name} runs: this test is it");
|
||||
assert!(
|
||||
found.path.as_ref().is_some_and(|path| path.is_file()),
|
||||
"{name} resolves to its executable"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_process_that_is_not_running_is_not_found() {
|
||||
let found = snapshot(vec!["definitely-not-a-process-1f3a.exe".to_string()]);
|
||||
let found = found.values().next().expect("the name was asked about");
|
||||
assert!(!found.running);
|
||||
assert!(found.path.is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
//! Match history: the timelines on disk, newest first, filtered by queue.
|
||||
//!
|
||||
//! The card reads like `GameHistory.vue`: result banner, champion portrait, queue, KDA and
|
||||
//! per-minute stats. Items are not shown: the timeline does not carry them.
|
||||
|
||||
use rune::tok::{radius, space, type_};
|
||||
use rune::{Color, El, col, el, row, text};
|
||||
|
||||
use crate::app::App;
|
||||
use crate::format;
|
||||
use crate::history::{self, Outcome, QueueCategory, Summary};
|
||||
use crate::icons;
|
||||
use crate::screens::review;
|
||||
use crate::ui::{self, Paint, body, heading};
|
||||
|
||||
use rune_kit::{Kit, Menu, MenuItem, Placement};
|
||||
|
||||
const FILTERS: [Option<QueueCategory>; 6] = [
|
||||
None,
|
||||
Some(QueueCategory::RankedSolo),
|
||||
Some(QueueCategory::RankedFlex),
|
||||
Some(QueueCategory::Normals),
|
||||
Some(QueueCategory::Aram),
|
||||
Some(QueueCategory::Custom),
|
||||
];
|
||||
|
||||
fn filter_label(filter: Option<QueueCategory>) -> &'static str {
|
||||
filter.map_or("All", QueueCategory::label)
|
||||
}
|
||||
|
||||
fn outcome_color(p: Paint, outcome: Outcome) -> Color {
|
||||
match outcome {
|
||||
Outcome::Victory => p.success,
|
||||
Outcome::Defeat => p.danger,
|
||||
Outcome::Terminated => p.muted(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn view(app: &App, p: Paint, layer: &mut Vec<El>) -> El {
|
||||
let kit = rune_kit::Kit::neutral(app.dark);
|
||||
let filtered: Vec<&Summary> = app
|
||||
.games
|
||||
.iter()
|
||||
.filter(|g| app.filter.is_none_or(|f| g.category() == f))
|
||||
.collect();
|
||||
|
||||
// The scroll bar gets its own strip at the end, clear of the cards.
|
||||
let mut list = col().key("games").w_full().gap(space::S2).pr(14.0);
|
||||
if !app.games_loaded {
|
||||
list = list.child(
|
||||
text("Loading match history…")
|
||||
.key("loading")
|
||||
.font(body(13.0))
|
||||
.color(p.muted())
|
||||
.padding(space::S6),
|
||||
);
|
||||
} else if app.games.is_empty() {
|
||||
list = list.child(empty(
|
||||
p,
|
||||
"No games recorded",
|
||||
"Start playing: the daemon records each game and it shows up here.",
|
||||
));
|
||||
} else if filtered.is_empty() {
|
||||
list = list.child(empty(
|
||||
p,
|
||||
"No games match this filter",
|
||||
"Pick another queue above.",
|
||||
));
|
||||
} else {
|
||||
for (index, game) in filtered.iter().enumerate() {
|
||||
list = list.child(game_card(app, p, &kit, layer, game, index));
|
||||
}
|
||||
}
|
||||
|
||||
let mut filters = row().key("filters").gap(4.0).center_y();
|
||||
for filter in FILTERS {
|
||||
let selected = app.filter == filter;
|
||||
filters = filters.child(ui::tab(
|
||||
p,
|
||||
filter_label(filter),
|
||||
filter_label(filter),
|
||||
selected,
|
||||
move |app: &mut App| app.filter = filter,
|
||||
));
|
||||
}
|
||||
|
||||
col()
|
||||
.key("history")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.padding(space::S6)
|
||||
.gap(space::S3)
|
||||
.child(
|
||||
row()
|
||||
.key("history-header")
|
||||
.w_full()
|
||||
.justify_between()
|
||||
.center_y()
|
||||
.child(
|
||||
col()
|
||||
.key("history-title")
|
||||
.gap(2.0)
|
||||
.child(
|
||||
text("Match history")
|
||||
.key("title")
|
||||
.font(heading(20.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(count_label(app))
|
||||
.key("count")
|
||||
.font(body(11.5))
|
||||
.color(p.muted()),
|
||||
),
|
||||
)
|
||||
.child(filters),
|
||||
)
|
||||
.child(
|
||||
app.scroll.follow(
|
||||
"list-scroller",
|
||||
col()
|
||||
.w_full()
|
||||
.grow(1.0)
|
||||
.min_h(0.0)
|
||||
.scroll(rune::ScrollSpec {
|
||||
stick_bottom: false,
|
||||
})
|
||||
.child(list),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// The line under the title: how many recordings there are, and how many have been read.
|
||||
///
|
||||
/// The list reads a page at a time, so the two differ while it is filling up.
|
||||
fn count_label(app: &App) -> String {
|
||||
let total = app.games_paths.len().max(app.games.len());
|
||||
if app.more_games() {
|
||||
format!("{} recordings · {} loaded", total, app.games.len())
|
||||
} else {
|
||||
format!("{total} recordings")
|
||||
}
|
||||
}
|
||||
|
||||
fn empty(p: Paint, title: &str, detail: &str) -> El {
|
||||
col()
|
||||
.key("empty")
|
||||
.w_full()
|
||||
.py(64.0)
|
||||
.gap(6.0)
|
||||
.center()
|
||||
.child(
|
||||
text(title)
|
||||
.key("empty-title")
|
||||
.font(heading(15.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(detail)
|
||||
.key("empty-detail")
|
||||
.font(body(12.0))
|
||||
.color(p.muted()),
|
||||
)
|
||||
}
|
||||
|
||||
fn game_card(
|
||||
app: &App,
|
||||
p: Paint,
|
||||
k: &Kit,
|
||||
layer: &mut Vec<El>,
|
||||
game: &Summary,
|
||||
index: usize,
|
||||
) -> El {
|
||||
let outcome = game.outcome();
|
||||
let ink = outcome_color(p, outcome);
|
||||
let id = game.recording_id.clone();
|
||||
let champion = game.champion().unwrap_or_else(|| "Unknown champion".into());
|
||||
let duration = game.duration_secs.max(0) as f64;
|
||||
let lp = game.lp_change();
|
||||
let stats = game.stats();
|
||||
|
||||
let mut banner = row()
|
||||
.key("banner")
|
||||
.w_full()
|
||||
.h(26.0)
|
||||
.px(space::S3)
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.fill(ink.alpha(0.16))
|
||||
.child(
|
||||
row()
|
||||
.key("banner-left")
|
||||
.gap(8.0)
|
||||
.center_y()
|
||||
.child(
|
||||
text(outcome.label())
|
||||
.key("outcome")
|
||||
.font(type_::LABEL)
|
||||
.color(ink),
|
||||
)
|
||||
.child(
|
||||
text(game.summoner().unwrap_or_default())
|
||||
.key("summoner")
|
||||
.font(body(11.0))
|
||||
.color(p.muted()),
|
||||
),
|
||||
);
|
||||
if let Some(lp) = &lp {
|
||||
let lp_ink = if lp.delta >= 0 { p.success } else { p.danger };
|
||||
banner = banner.child(
|
||||
text(format!(
|
||||
"{} LP · {}",
|
||||
format::lp_delta(lp.delta),
|
||||
format::rank(&lp.tier, &lp.division)
|
||||
))
|
||||
.key("lp")
|
||||
.font(type_::MONO_CAPTION)
|
||||
.color(lp_ink),
|
||||
);
|
||||
}
|
||||
|
||||
let kda = match &stats {
|
||||
Some(s) => format!("{}/{}/{}", s.kills, s.deaths, s.assists),
|
||||
None => "0/0/0".into(),
|
||||
};
|
||||
let ratio = stats.as_ref().map_or("0.0".into(), |s| {
|
||||
format::kda_ratio(s.kills, s.deaths, s.assists)
|
||||
});
|
||||
let mut stats_row = row().key("stats").gap(18.0).center_y();
|
||||
if let Some(s) = &stats {
|
||||
stats_row = stats_row
|
||||
.child(stat(p, &format::cs_per_min(s), "CS/m"))
|
||||
.child(stat(p, &format::gold_per_min(s), "Gold/m"))
|
||||
.child(stat(p, &s.vision_score.to_string(), "Vision"));
|
||||
}
|
||||
|
||||
el().key(format!("game-{index}"))
|
||||
.role("button")
|
||||
.label(format!("{champion}, {}", outcome.label()))
|
||||
.focusable(true)
|
||||
.w_full()
|
||||
.radius(radius::LG)
|
||||
.fill(p.t.card)
|
||||
.border(p.hair, p.t.card_border)
|
||||
.shadow(1.0, 2.0, p.t.shadow)
|
||||
.shadow(8.0, 24.0, p.t.shadow_soft)
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(move |app: &mut App| review::open(app, &id))
|
||||
.child(
|
||||
col().key("card").w_full().child(banner).child(
|
||||
row()
|
||||
.key("content")
|
||||
.w_full()
|
||||
.px(space::S3)
|
||||
.py(space::S3)
|
||||
.gap(space::S3)
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.child(
|
||||
row()
|
||||
.key("identity")
|
||||
.gap(space::S3)
|
||||
.center_y()
|
||||
.child(ui::champion_portrait(
|
||||
app,
|
||||
p,
|
||||
game.champion().as_deref(),
|
||||
52.0,
|
||||
))
|
||||
.child(
|
||||
col()
|
||||
.key("identity-labels")
|
||||
.gap(2.0)
|
||||
.child(
|
||||
text(champion)
|
||||
.key("champion")
|
||||
.font(heading(16.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(format!(
|
||||
"{} · {}",
|
||||
game.queue_label(),
|
||||
format::duration(duration)
|
||||
))
|
||||
.key("queue")
|
||||
.font(body(11.5))
|
||||
.color(p.muted()),
|
||||
)
|
||||
.child(
|
||||
text(format::relative_time(game.start_time))
|
||||
.key("when")
|
||||
.font(body(11.0))
|
||||
.color(p.muted()),
|
||||
),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
col()
|
||||
.key("kda")
|
||||
.gap(1.0)
|
||||
.items_end()
|
||||
.child(
|
||||
text(kda)
|
||||
.key("kda-values")
|
||||
.font(heading(15.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text(format!("{ratio} KDA"))
|
||||
.key("kda-ratio")
|
||||
.font(body(11.0))
|
||||
.color(p.muted()),
|
||||
),
|
||||
)
|
||||
.child(stats_row)
|
||||
.child(
|
||||
row()
|
||||
.key("actions")
|
||||
.gap(space::S3)
|
||||
.center_y()
|
||||
.child(
|
||||
text("Review →")
|
||||
.key("open")
|
||||
.font(type_::LABEL)
|
||||
.color(p.accent),
|
||||
)
|
||||
.child(card_menu(app, k, layer, p, game, index)),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
fn stat(p: Paint, value: &str, label: &str) -> El {
|
||||
col()
|
||||
.key(format!("stat-{label}"))
|
||||
.gap(0.0)
|
||||
.items_end()
|
||||
.child(
|
||||
text(value)
|
||||
.key("value")
|
||||
.font(type_::MONO_CAPTION)
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(text(label).key("label").font(body(10.5)).color(p.muted()))
|
||||
}
|
||||
|
||||
/// The dots at the end of a card: they open the menu of actions a recording offers. The menu
|
||||
/// is drawn over this window, so it stays inside it, and more actions can join `Delete` later.
|
||||
/// The key is the card's position, so rows stay distinct even where ids repeat.
|
||||
fn card_menu(
|
||||
app: &App,
|
||||
k: &Kit,
|
||||
layer: &mut Vec<El>,
|
||||
p: Paint,
|
||||
game: &Summary,
|
||||
index: usize,
|
||||
) -> El {
|
||||
let menu = Menu::new(format!("menu-{index}"))
|
||||
.trigger(ui::menu_button(
|
||||
p,
|
||||
format!("menu-{index}"),
|
||||
&icons::DOTS,
|
||||
"Recording options",
|
||||
move |app: &mut App| app.menu_open = Some(index),
|
||||
))
|
||||
.placement(Placement::BottomEnd)
|
||||
.open(app.menu_open == Some(index))
|
||||
.on_close(|app: &mut App| app.menu_open = None)
|
||||
.item({
|
||||
let id = game.recording_id.clone();
|
||||
MenuItem::new("Delete")
|
||||
.danger(true)
|
||||
.on_select(move |app: &mut App| {
|
||||
app.menu_open = None;
|
||||
app.confirm_delete = Some(id.clone());
|
||||
})
|
||||
});
|
||||
menu.build(k, layer)
|
||||
}
|
||||
|
||||
/// The confirmation the menu's Delete opens: the row leaves the list and its files leave the
|
||||
/// disk. `app::view` draws it over the whole window, title bar included.
|
||||
pub fn delete_dialog(app: &App, p: Paint, layer: &mut Vec<El>) {
|
||||
let panel = col()
|
||||
.key("delete-dialog")
|
||||
.role("dialog")
|
||||
.label("Delete this recording")
|
||||
.w(380.0)
|
||||
.padding(space::S6)
|
||||
.gap(space::S3)
|
||||
.radius(radius::LG)
|
||||
.fill(p.t.card)
|
||||
.border(p.hair, p.t.card_border)
|
||||
.shadow(4.0, 12.0, p.t.shadow)
|
||||
.shadow(24.0, 48.0, p.t.shadow_soft)
|
||||
.modal(true, |app: &mut App| app.confirm_delete = None)
|
||||
.child(
|
||||
text("Are you sure you want to delete this entry?")
|
||||
.key("delete-question")
|
||||
.font(heading(15.0))
|
||||
.color(p.t.text),
|
||||
)
|
||||
.child(
|
||||
text("The recording and its timeline are removed from disk.")
|
||||
.key("delete-note")
|
||||
.font(body(12.0))
|
||||
.color(p.muted()),
|
||||
)
|
||||
.child(
|
||||
row()
|
||||
.key("delete-actions")
|
||||
.w_full()
|
||||
.gap(space::S2)
|
||||
.justify_end()
|
||||
.child(ui::button(p, "delete-no", "No", false, |app: &mut App| {
|
||||
app.confirm_delete = None;
|
||||
}))
|
||||
.child(ui::button_danger(
|
||||
p,
|
||||
"delete-yes",
|
||||
"Yes",
|
||||
|app: &mut App| {
|
||||
delete_confirmed(app);
|
||||
},
|
||||
)),
|
||||
);
|
||||
|
||||
layer.push(
|
||||
el().key("delete-scrim")
|
||||
.absolute(0.0, 0.0)
|
||||
.w_full()
|
||||
.h_full()
|
||||
.fill(Color::BLACK.alpha(if app.dark { 0.55 } else { 0.28 }))
|
||||
.a11y_hidden(),
|
||||
);
|
||||
layer.push(
|
||||
el().key("delete-layer")
|
||||
.absolute(0.0, 0.0)
|
||||
.w_full()
|
||||
.h_full()
|
||||
.padding(16.0)
|
||||
.center()
|
||||
.child(panel),
|
||||
);
|
||||
}
|
||||
|
||||
/// Yes on the dialog: the files go, the row goes, the dialog closes.
|
||||
fn delete_confirmed(app: &mut App) {
|
||||
let Some(id) = app.confirm_delete.take() else {
|
||||
return;
|
||||
};
|
||||
// A review left open keeps the clip's file in use, and the delete would fail on it.
|
||||
if app.reviewed().is_some_and(|game| game.recording_id == id) {
|
||||
review::leave(app);
|
||||
}
|
||||
let Some(summary) = app.games.iter().find(|g| g.recording_id == id).cloned() else {
|
||||
return;
|
||||
};
|
||||
if let Err(e) = history::delete(&id, summary.video_file.as_deref()) {
|
||||
app.notify_error(e);
|
||||
return;
|
||||
}
|
||||
app.forget_game(&id);
|
||||
app.notify("Recording deleted");
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! The three screens: settings, match history and the game review.
|
||||
|
||||
pub mod history;
|
||||
pub mod review;
|
||||
pub mod settings;
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,462 @@
|
||||
//! The daemon's settings model (`record-daemon/src/config/settings.rs`).
|
||||
//!
|
||||
//! Kept field for field, snake_case and all: `updateSettings` parses this with serde and rejects
|
||||
//! anything it does not expect.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::daemon;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Settings {
|
||||
#[serde(default)]
|
||||
pub video: VideoSettings,
|
||||
#[serde(default)]
|
||||
pub output: OutputSettings,
|
||||
#[serde(default)]
|
||||
pub audio: AudioSettings,
|
||||
#[serde(default)]
|
||||
pub daemon: DaemonSettings,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct VideoSettings {
|
||||
#[serde(default)]
|
||||
pub encoder_preset: EncoderPreset,
|
||||
#[serde(default)]
|
||||
pub quality: Quality,
|
||||
#[serde(default = "frame_rate")]
|
||||
pub frame_rate: u32,
|
||||
#[serde(default = "yes")]
|
||||
pub hardware_acceleration: bool,
|
||||
}
|
||||
|
||||
impl Default for VideoSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
encoder_preset: EncoderPreset::default(),
|
||||
quality: Quality::default(),
|
||||
frame_rate: frame_rate(),
|
||||
hardware_acceleration: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(tag = "type", rename_all = "lowercase")]
|
||||
pub enum EncoderPreset {
|
||||
Nvenc {
|
||||
#[serde(default = "nvenc_bitrate")]
|
||||
bitrate: u32,
|
||||
#[serde(default = "nvenc_cq")]
|
||||
cq_level: u32,
|
||||
#[serde(default = "yes")]
|
||||
two_pass: bool,
|
||||
},
|
||||
Amf {
|
||||
#[serde(default = "nvenc_bitrate")]
|
||||
bitrate: u32,
|
||||
#[serde(default)]
|
||||
quality: AmfQuality,
|
||||
},
|
||||
X264 {
|
||||
#[serde(default = "x264_preset")]
|
||||
preset: String,
|
||||
#[serde(default = "x264_bitrate")]
|
||||
bitrate: u32,
|
||||
#[serde(default)]
|
||||
crf: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
impl Default for EncoderPreset {
|
||||
fn default() -> Self {
|
||||
Self::Nvenc {
|
||||
bitrate: nvenc_bitrate(),
|
||||
cq_level: nvenc_cq(),
|
||||
two_pass: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // encoder_id and bitrate are read by the tests
|
||||
impl EncoderPreset {
|
||||
/// The daemon's encoder id for this preset (`GetEncodersResponse::current`).
|
||||
pub fn encoder_id(&self) -> &'static str {
|
||||
match self {
|
||||
EncoderPreset::Nvenc { .. } => "jim_nvenc",
|
||||
EncoderPreset::Amf { .. } => "amd_amf_h264",
|
||||
EncoderPreset::X264 { .. } => "x264",
|
||||
}
|
||||
}
|
||||
|
||||
/// The name a daemon-reported encoder id (`.current`) stands for.
|
||||
pub fn encoder_name(id: &str) -> Option<&'static str> {
|
||||
match id {
|
||||
"jim_nvenc" => Some("NVIDIA NVENC"),
|
||||
"amd_amf_h264" => Some("AMD AMF"),
|
||||
"x264" => Some("x264 (Software)"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
EncoderPreset::Nvenc { .. } => "NVIDIA NVENC",
|
||||
EncoderPreset::Amf { .. } => "AMD AMF",
|
||||
EncoderPreset::X264 { .. } => "x264 (Software)",
|
||||
}
|
||||
}
|
||||
|
||||
/// This preset with the encoder changed, keeping the bitrate where both have one.
|
||||
pub fn with_kind(&self, kind: &str) -> EncoderPreset {
|
||||
let bitrate = match self {
|
||||
EncoderPreset::Nvenc { bitrate, .. }
|
||||
| EncoderPreset::Amf { bitrate, .. }
|
||||
| EncoderPreset::X264 { bitrate, .. } => *bitrate,
|
||||
};
|
||||
match kind {
|
||||
"amf" | "AMD AMF" | "amd_amf_h264" => EncoderPreset::Amf {
|
||||
bitrate,
|
||||
quality: AmfQuality::Balanced,
|
||||
},
|
||||
"x264" | "x264 (Software)" => EncoderPreset::X264 {
|
||||
preset: x264_preset(),
|
||||
bitrate,
|
||||
crf: None,
|
||||
},
|
||||
_ => EncoderPreset::Nvenc {
|
||||
bitrate,
|
||||
cq_level: nvenc_cq(),
|
||||
two_pass: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn bitrate(&self) -> u32 {
|
||||
match self {
|
||||
EncoderPreset::Nvenc { bitrate, .. }
|
||||
| EncoderPreset::Amf { bitrate, .. }
|
||||
| EncoderPreset::X264 { bitrate, .. } => *bitrate,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AmfQuality {
|
||||
Speed,
|
||||
#[default]
|
||||
Balanced,
|
||||
Quality,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Quality {
|
||||
Low,
|
||||
Medium,
|
||||
#[default]
|
||||
High,
|
||||
Ultra,
|
||||
}
|
||||
|
||||
impl Quality {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Quality::Low => "Low",
|
||||
Quality::Medium => "Medium",
|
||||
Quality::High => "High",
|
||||
Quality::Ultra => "Ultra",
|
||||
}
|
||||
}
|
||||
|
||||
/// What a quality level records at: the screen's resolution, at this bitrate.
|
||||
pub fn detail(self) -> &'static str {
|
||||
match self {
|
||||
Quality::Low => "Your screen's resolution at 4.5 Mbps",
|
||||
Quality::Medium => "Your screen's resolution at 6 Mbps",
|
||||
Quality::High => "Your screen's resolution at 8 Mbps",
|
||||
Quality::Ultra => "Your screen's resolution at 12 Mbps",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct OutputSettings {
|
||||
#[serde(default = "output_path")]
|
||||
pub path: String,
|
||||
#[serde(default = "naming_pattern")]
|
||||
pub naming_pattern: String,
|
||||
#[serde(default = "container")]
|
||||
pub container: String,
|
||||
#[serde(default)]
|
||||
pub split_size_mb: u32,
|
||||
#[serde(default)]
|
||||
pub split_time_minutes: u32,
|
||||
}
|
||||
|
||||
impl Default for OutputSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
path: output_path(),
|
||||
naming_pattern: naming_pattern(),
|
||||
container: container(),
|
||||
split_size_mb: 0,
|
||||
split_time_minutes: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct DaemonSettings {
|
||||
#[serde(default = "yes")]
|
||||
pub auto_record: bool,
|
||||
#[serde(default = "yes")]
|
||||
pub monitor_client: bool,
|
||||
#[serde(default = "poll_interval")]
|
||||
pub poll_interval_ms: u64,
|
||||
#[serde(default)]
|
||||
pub socket_path: Option<String>,
|
||||
#[serde(default = "log_level")]
|
||||
pub log_level: String,
|
||||
#[serde(default = "yes")]
|
||||
pub save_timeline: bool,
|
||||
}
|
||||
|
||||
impl Default for DaemonSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
auto_record: true,
|
||||
monitor_client: true,
|
||||
poll_interval_ms: poll_interval(),
|
||||
socket_path: None,
|
||||
log_level: log_level(),
|
||||
save_timeline: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct AudioSettings {
|
||||
#[serde(default = "yes")]
|
||||
pub enabled: bool,
|
||||
#[serde(default = "audio_bitrate")]
|
||||
pub bitrate: u32,
|
||||
#[serde(default = "sample_rate")]
|
||||
pub sample_rate: u32,
|
||||
#[serde(default = "channels")]
|
||||
pub channels: u32,
|
||||
#[serde(default = "yes")]
|
||||
pub capture_game: bool,
|
||||
#[serde(default = "volume")]
|
||||
pub game_volume: u32,
|
||||
#[serde(default)]
|
||||
pub capture_mic: bool,
|
||||
#[serde(default)]
|
||||
pub mic_device: Option<String>,
|
||||
#[serde(default = "volume")]
|
||||
pub mic_volume: u32,
|
||||
#[serde(default)]
|
||||
pub capture_apps: Vec<AudioSource>,
|
||||
#[serde(default = "volume")]
|
||||
pub apps_volume: u32,
|
||||
}
|
||||
|
||||
impl Default for AudioSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
bitrate: audio_bitrate(),
|
||||
sample_rate: sample_rate(),
|
||||
channels: channels(),
|
||||
capture_game: true,
|
||||
game_volume: volume(),
|
||||
capture_mic: false,
|
||||
mic_device: None,
|
||||
mic_volume: volume(),
|
||||
capture_apps: Vec::new(),
|
||||
apps_volume: volume(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct AudioSource {
|
||||
#[serde(default)]
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(rename = "type")]
|
||||
pub source_type: AudioSourceType,
|
||||
pub device: String,
|
||||
#[serde(default = "yes")]
|
||||
pub enabled: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub volume: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AudioSourceType {
|
||||
Application,
|
||||
DeviceOutput,
|
||||
DeviceInput,
|
||||
}
|
||||
|
||||
impl AudioSourceType {
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
AudioSourceType::Application => "Application",
|
||||
AudioSourceType::DeviceOutput => "Output device",
|
||||
AudioSourceType::DeviceInput => "Input device",
|
||||
}
|
||||
}
|
||||
}
|
||||
// ---------------------------------------------------------------------------
|
||||
// Defaults, matching the daemon
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
fn frame_rate() -> u32 {
|
||||
60
|
||||
}
|
||||
fn nvenc_bitrate() -> u32 {
|
||||
8000
|
||||
}
|
||||
fn nvenc_cq() -> u32 {
|
||||
20
|
||||
}
|
||||
fn x264_preset() -> String {
|
||||
"veryfast".into()
|
||||
}
|
||||
fn x264_bitrate() -> u32 {
|
||||
6000
|
||||
}
|
||||
fn output_path() -> String {
|
||||
daemon::recordings_dir().display().to_string()
|
||||
}
|
||||
fn naming_pattern() -> String {
|
||||
"{date}_{time}_{champion}".into()
|
||||
}
|
||||
fn container() -> String {
|
||||
"mp4".into()
|
||||
}
|
||||
fn poll_interval() -> u64 {
|
||||
1000
|
||||
}
|
||||
fn log_level() -> String {
|
||||
"info".into()
|
||||
}
|
||||
fn audio_bitrate() -> u32 {
|
||||
160
|
||||
}
|
||||
fn sample_rate() -> u32 {
|
||||
48_000
|
||||
}
|
||||
fn channels() -> u32 {
|
||||
2
|
||||
}
|
||||
fn volume() -> u32 {
|
||||
100
|
||||
}
|
||||
|
||||
/// Split the daemon's `{ settings: {...} }` wrapper.
|
||||
///
|
||||
/// Every field of [`Settings`] has a default, so a reply that carries no settings at all
|
||||
/// (`{"success": true}`, the answer to `updateSettings`) would parse into the defaults and
|
||||
/// quietly replace what the user has. The daemon always writes the `video` key, and a reply
|
||||
/// without it is an error.
|
||||
pub fn from_response(data: &serde_json::Value) -> Result<Settings, String> {
|
||||
let inner = data.get("settings").unwrap_or(data);
|
||||
if inner.get("video").is_none() {
|
||||
return Err("the daemon's reply carries no settings".to_string());
|
||||
}
|
||||
serde_json::from_value(inner.clone()).map_err(|e| format!("settings did not parse: {e}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn defaults_serialize_the_way_the_daemon_reads_them() {
|
||||
let value = serde_json::to_value(Settings::default()).unwrap();
|
||||
// The daemon parses these exact keys; a rename here makes updateSettings fail.
|
||||
assert_eq!(value["video"]["encoder_preset"]["type"], "nvenc");
|
||||
assert_eq!(value["video"]["encoder_preset"]["cq_level"], 20);
|
||||
assert_eq!(value["video"]["quality"], "high");
|
||||
assert_eq!(value["video"]["frame_rate"], 60);
|
||||
assert_eq!(value["output"]["container"], "mp4");
|
||||
assert!(value["output"]["path"].is_string());
|
||||
assert_eq!(value["audio"]["game_volume"], 100);
|
||||
assert_eq!(value["daemon"]["poll_interval_ms"], 1000);
|
||||
assert!(value["daemon"]["socket_path"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_round_trip_through_json() {
|
||||
let settings = Settings::default();
|
||||
let text = serde_json::to_string(&settings).unwrap();
|
||||
let back: Settings = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(settings, back);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_response_wrapper_is_peeled_once() {
|
||||
let wrapped = json!({"settings": serde_json::to_value(Settings::default()).unwrap()});
|
||||
assert!(from_response(&wrapped).is_ok());
|
||||
let bare = serde_json::to_value(Settings::default()).unwrap();
|
||||
assert!(from_response(&bare).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reply_without_settings_is_an_error() {
|
||||
let replied = json!({"success": true});
|
||||
assert!(from_response(&replied).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_encoder_keeps_its_bitrate_when_it_changes_kind() {
|
||||
let preset = EncoderPreset::X264 {
|
||||
preset: "medium".into(),
|
||||
bitrate: 9000,
|
||||
crf: None,
|
||||
};
|
||||
let nvenc = preset.with_kind("nvenc");
|
||||
assert_eq!(nvenc.encoder_id(), "jim_nvenc");
|
||||
assert_eq!(nvenc.bitrate(), 9000);
|
||||
assert_eq!(preset.with_kind("amf").encoder_id(), "amd_amf_h264");
|
||||
assert_eq!(
|
||||
preset.with_kind("amd_amf_h264").encoder_id(),
|
||||
"amd_amf_h264"
|
||||
);
|
||||
assert_eq!(preset.with_kind("x264").encoder_id(), "x264");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn choosing_an_encoder_by_its_menu_label_works() {
|
||||
let preset = EncoderPreset::default();
|
||||
assert_eq!(preset.with_kind("AMD AMF").encoder_id(), "amd_amf_h264");
|
||||
assert_eq!(preset.with_kind("x264 (Software)").encoder_id(), "x264");
|
||||
assert_eq!(preset.with_kind("NVIDIA NVENC").encoder_id(), "jim_nvenc");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_source_type_names_match_the_daemon() {
|
||||
assert_eq!(
|
||||
serde_json::to_value(AudioSourceType::Application).unwrap(),
|
||||
"application"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(AudioSourceType::DeviceOutput).unwrap(),
|
||||
"deviceoutput"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(AudioSourceType::DeviceInput).unwrap(),
|
||||
"deviceinput"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
//! The app's palette.
|
||||
//!
|
||||
//! One shell colour scheme: near-black surfaces tinted blue, brass for what the user acts on,
|
||||
//! and mint or coral only for results. Champion art and victory banners are the loudest things
|
||||
//! on screen, so the chrome around them stays quiet.
|
||||
//!
|
||||
//! Every colour is OKLCH, written as lightness, chroma and hue. The two appearances share the
|
||||
//! hues and swap lightness, so a control keeps its identity in light mode.
|
||||
|
||||
use rune::tok::Theme;
|
||||
use rune::{Color, oklch, oklcha};
|
||||
|
||||
/// Hues, one per role. Neutrals take a touch of the shell's blue; text keeps the same cast.
|
||||
const SHELL: f32 = 268.0;
|
||||
const BRASS: f32 = 84.0;
|
||||
const MINT: f32 = 157.0;
|
||||
const CORAL: f32 = 22.0;
|
||||
|
||||
pub struct Palette {
|
||||
/// Surfaces and ink: what rune's widgets read.
|
||||
pub theme: Theme,
|
||||
/// The window chrome: title bar and status bar, a step above or below the page.
|
||||
pub chrome: Color,
|
||||
/// A field's well, sunk into the card it sits in.
|
||||
pub field: Color,
|
||||
/// What the user acts on: primary buttons, sliders, the selected tab.
|
||||
pub accent: Color,
|
||||
/// Ink for text on an accent fill.
|
||||
pub accent_ink: Color,
|
||||
pub success: Color,
|
||||
pub danger: Color,
|
||||
pub warning: Color,
|
||||
}
|
||||
|
||||
pub fn palette(dark: bool) -> Palette {
|
||||
if dark {
|
||||
Palette {
|
||||
theme: Theme {
|
||||
bg: oklch(0.168, 0.012, SHELL),
|
||||
card: oklch(0.212, 0.014, SHELL),
|
||||
card_border: oklcha(1.0, 0.0, 0.0, 0.055),
|
||||
text: oklch(0.962, 0.003, SHELL),
|
||||
text_secondary: oklch(0.734, 0.012, SHELL),
|
||||
separator: oklcha(1.0, 0.0, 0.0, 0.05),
|
||||
control_track: oklcha(1.0, 0.0, 0.0, 0.045),
|
||||
control_off: oklcha(1.0, 0.0, 0.0, 0.09),
|
||||
indicator: oklch(0.44, 0.01, SHELL),
|
||||
knob: oklch(0.985, 0.0, 0.0),
|
||||
hover: oklcha(1.0, 0.0, 0.0, 0.018),
|
||||
press: oklcha(1.0, 0.0, 0.0, 0.035),
|
||||
shadow: oklcha(0.0, 0.0, 0.0, 0.45),
|
||||
shadow_soft: oklcha(0.0, 0.0, 0.0, 0.3),
|
||||
edge: oklcha(0.0, 0.0, 0.0, 0.32),
|
||||
knob_shadow: oklcha(0.0, 0.0, 0.0, 0.32),
|
||||
},
|
||||
chrome: oklch(0.192, 0.013, SHELL),
|
||||
field: oklch(0.178, 0.012, SHELL),
|
||||
accent: oklch(0.818, 0.116, BRASS),
|
||||
accent_ink: oklch(0.245, 0.035, BRASS),
|
||||
success: oklch(0.782, 0.132, MINT),
|
||||
danger: oklch(0.706, 0.152, CORAL),
|
||||
warning: oklch(0.812, 0.115, 72.0),
|
||||
}
|
||||
} else {
|
||||
Palette {
|
||||
theme: Theme {
|
||||
bg: oklch(0.966, 0.004, SHELL),
|
||||
card: oklch(1.0, 0.0, 0.0),
|
||||
card_border: oklcha(0.2, 0.02, SHELL, 0.1),
|
||||
text: oklch(0.235, 0.012, SHELL),
|
||||
text_secondary: oklch(0.515, 0.013, SHELL),
|
||||
separator: oklcha(0.2, 0.02, SHELL, 0.12),
|
||||
control_track: oklcha(0.2, 0.01, SHELL, 0.13),
|
||||
control_off: oklcha(0.2, 0.01, SHELL, 0.22),
|
||||
indicator: oklch(1.0, 0.0, 0.0),
|
||||
knob: oklch(1.0, 0.0, 0.0),
|
||||
hover: oklcha(0.2, 0.01, SHELL, 0.06),
|
||||
press: oklcha(0.2, 0.01, SHELL, 0.11),
|
||||
shadow: oklcha(0.2, 0.02, SHELL, 0.16),
|
||||
shadow_soft: oklcha(0.2, 0.02, SHELL, 0.07),
|
||||
edge: oklcha(0.2, 0.02, SHELL, 0.2),
|
||||
knob_shadow: oklcha(0.2, 0.02, SHELL, 0.3),
|
||||
},
|
||||
chrome: oklch(0.988, 0.003, SHELL),
|
||||
field: oklch(0.955, 0.004, SHELL),
|
||||
accent: oklch(0.535, 0.104, 74.0),
|
||||
accent_ink: oklch(1.0, 0.0, 0.0),
|
||||
success: oklch(0.512, 0.122, MINT),
|
||||
danger: oklch(0.55, 0.165, CORAL),
|
||||
warning: oklch(0.52, 0.112, 68.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Relative luminance of a linear-light colour, as WCAG defines contrast.
|
||||
fn luminance(c: Color) -> f64 {
|
||||
0.2126 * c.r as f64 + 0.7152 * c.g as f64 + 0.0722 * c.b as f64
|
||||
}
|
||||
|
||||
fn contrast(a: Color, b: Color) -> f64 {
|
||||
let (x, y) = (luminance(a), luminance(b));
|
||||
let (hi, lo) = if x > y { (x, y) } else { (y, x) };
|
||||
(hi + 0.05) / (lo + 0.05)
|
||||
}
|
||||
|
||||
/// Every colour that carries text keeps WCAG AA (4.5:1) on the surfaces it is drawn on,
|
||||
/// in both appearances. The palette is tuned by hand, so this is the guard that a nudge
|
||||
/// to one number did not make a label unreadable.
|
||||
#[test]
|
||||
fn ink_reads_on_the_surfaces() {
|
||||
for dark in [true, false] {
|
||||
let p = palette(dark);
|
||||
let mode = if dark { "dark" } else { "light" };
|
||||
for (name, ink) in [
|
||||
("text", p.theme.text),
|
||||
("text_secondary", p.theme.text_secondary),
|
||||
("accent", p.accent),
|
||||
("success", p.success),
|
||||
("danger", p.danger),
|
||||
("warning", p.warning),
|
||||
] {
|
||||
for (surface, bg) in [
|
||||
("bg", p.theme.bg),
|
||||
("card", p.theme.card),
|
||||
("chrome", p.chrome),
|
||||
] {
|
||||
let ratio = contrast(ink, bg);
|
||||
assert!(
|
||||
ratio >= 4.5,
|
||||
"{mode}: {name} on {surface} is {ratio:.2}:1, under 4.5:1"
|
||||
);
|
||||
}
|
||||
}
|
||||
let ratio = contrast(p.accent, p.accent_ink);
|
||||
assert!(
|
||||
ratio >= 4.5,
|
||||
"{mode}: accent_ink on accent is {ratio:.2}:1, under 4.5:1"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A field's well has to be visible inside the card it sits in.
|
||||
#[test]
|
||||
fn the_field_well_stands_out_from_the_card() {
|
||||
for dark in [true, false] {
|
||||
let p = palette(dark);
|
||||
let ratio = contrast(p.field, p.theme.card);
|
||||
assert!(ratio >= 1.04, "{dark}: field vs card is {ratio:.2}:1");
|
||||
}
|
||||
}
|
||||
}
|
||||
+807
@@ -0,0 +1,807 @@
|
||||
//! Shared colours and small controls for the screens.
|
||||
|
||||
use rune::tok::{Theme, motion, radius, space, type_};
|
||||
use rune::{Color, Drag, El, Phase, TextStyle, col, el, row, text};
|
||||
|
||||
use crate::app::App;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Paint {
|
||||
pub t: Theme,
|
||||
pub accent: Color,
|
||||
pub accent_ink: Color,
|
||||
pub success: Color,
|
||||
pub danger: Color,
|
||||
pub warning: Color,
|
||||
pub chrome: Color,
|
||||
pub field: Color,
|
||||
pub hair: f32,
|
||||
pub scale: f32,
|
||||
}
|
||||
|
||||
impl Paint {
|
||||
pub fn new(dark: bool, scale: f32) -> Self {
|
||||
let palette = crate::theme::palette(dark);
|
||||
Self {
|
||||
t: palette.theme,
|
||||
accent: palette.accent,
|
||||
accent_ink: palette.accent_ink,
|
||||
success: palette.success,
|
||||
danger: palette.danger,
|
||||
warning: palette.warning,
|
||||
chrome: palette.chrome,
|
||||
field: palette.field,
|
||||
hair: 1.0 / scale,
|
||||
scale,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn muted(&self) -> Color {
|
||||
self.t.text_secondary
|
||||
}
|
||||
}
|
||||
|
||||
pub fn heading(size: f32) -> TextStyle {
|
||||
TextStyle::new(size, 600.0)
|
||||
}
|
||||
|
||||
pub fn body(size: f32) -> TextStyle {
|
||||
TextStyle::new(size, 400.0)
|
||||
}
|
||||
|
||||
/// A titled card of rows with hairlines between them.
|
||||
pub fn card(p: Paint, title: Option<&str>, rows: Vec<El>) -> El {
|
||||
card_action(p, title, None, rows)
|
||||
}
|
||||
|
||||
/// [`card`] with a control in its header, such as the button that adds to the list below.
|
||||
pub fn card_action(p: Paint, title: Option<&str>, action: Option<El>, rows: Vec<El>) -> El {
|
||||
let count = rows.len();
|
||||
let mut inner = col()
|
||||
.key("card")
|
||||
.padding(space::S1)
|
||||
.fill(p.t.card)
|
||||
.radius(radius::LG)
|
||||
.border(p.hair, p.t.card_border)
|
||||
.shadow(1.0, 2.0, p.t.shadow)
|
||||
.shadow(8.0, 24.0, p.t.shadow_soft);
|
||||
for (i, r) in rows.into_iter().enumerate() {
|
||||
inner = inner.child(r);
|
||||
if i + 1 < count {
|
||||
inner = inner.child(
|
||||
el().key(format!("sep{i}"))
|
||||
.h(p.hair)
|
||||
.ml(space::S3)
|
||||
.mr(space::S3)
|
||||
.fill(p.t.separator)
|
||||
.a11y_hidden(),
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut section = col().gap(space::S2);
|
||||
if let Some(title) = title {
|
||||
let mut header = row()
|
||||
.key("header")
|
||||
.w_full()
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.child(
|
||||
text(title)
|
||||
.key("header-label")
|
||||
.font(type_::SECTION)
|
||||
.color(p.t.text_secondary)
|
||||
.ml(space::S3),
|
||||
);
|
||||
if let Some(action) = action {
|
||||
header = header.child(action);
|
||||
}
|
||||
section = section.child(header);
|
||||
}
|
||||
section.child(inner)
|
||||
}
|
||||
|
||||
/// The 44-point row every setting sits in: a label on the left, a control on the right.
|
||||
pub fn setting_row(p: Paint, key: &str, label: &str, control: El) -> El {
|
||||
row()
|
||||
.key(key)
|
||||
.h(44.0)
|
||||
.px(space::S3)
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.radius(radius::MD)
|
||||
.label(label)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::BODY)
|
||||
.color(p.t.text)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(control)
|
||||
}
|
||||
|
||||
/// A row with a subtitle under the label.
|
||||
pub fn setting_row_with(p: Paint, key: &str, label: &str, subtitle: &str, control: El) -> El {
|
||||
row()
|
||||
.key(key)
|
||||
.h(52.0)
|
||||
.px(space::S3)
|
||||
.center_y()
|
||||
.justify_between()
|
||||
.radius(radius::MD)
|
||||
.label(label)
|
||||
.child(
|
||||
col()
|
||||
.key("labels")
|
||||
.gap(1.0)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::BODY)
|
||||
.color(p.t.text)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
text(subtitle)
|
||||
.key("subtitle")
|
||||
.font(body(11.5))
|
||||
.color(p.t.text_secondary)
|
||||
.a11y_hidden(),
|
||||
),
|
||||
)
|
||||
.child(control)
|
||||
}
|
||||
|
||||
/// A 38 × 22 switch with a 18-point knob.
|
||||
pub fn switch(p: Paint, key: &str, on: bool) -> El {
|
||||
let (w, h, k) = (38.0, 22.0, 18.0);
|
||||
let inset = (h - k) / 2.0;
|
||||
el().key(key)
|
||||
.role("switch")
|
||||
.size(w, h)
|
||||
.radius(h / 2.0)
|
||||
.fill(if on { p.accent } else { p.t.control_off })
|
||||
.motion(motion::SNAPPY)
|
||||
.child(
|
||||
el().key("knob")
|
||||
.size(k, k)
|
||||
.absolute(if on { w - k - inset } else { inset }, inset)
|
||||
.radius(k / 2.0)
|
||||
.fill(p.t.knob)
|
||||
.shadow(1.0, 3.0, p.t.knob_shadow)
|
||||
.shadow(0.0, 0.5, p.t.edge)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A labelled switch row. The whole row is the target and the keyboard stop.
|
||||
pub fn toggle_row(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
label: &str,
|
||||
on: bool,
|
||||
flip: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
setting_row(
|
||||
p,
|
||||
key,
|
||||
label,
|
||||
switch(p, &format!("{key}-switch"), on).a11y_hidden(),
|
||||
)
|
||||
.role("switch")
|
||||
.checked(on)
|
||||
.focusable(true)
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(flip)
|
||||
}
|
||||
|
||||
/// A 0-100 slider with its value spelled out on the right.
|
||||
pub fn slider(
|
||||
p: Paint,
|
||||
key: impl Into<String>,
|
||||
label: &'static str,
|
||||
value: u32,
|
||||
on_change: impl Fn(&mut App, u32) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
slider_width(p, key, label, 180.0, value, on_change)
|
||||
}
|
||||
|
||||
/// [`slider`] at a given width, for the player bar where 180 points is too much.
|
||||
pub fn slider_width(
|
||||
p: Paint,
|
||||
key: impl Into<String>,
|
||||
label: &'static str,
|
||||
width: f32,
|
||||
value: u32,
|
||||
on_change: impl Fn(&mut App, u32) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
let key = key.into();
|
||||
let (w, h, k, bar) = (width, 22.0, 18.0, 4.0);
|
||||
let travel = w - k;
|
||||
let v = (value.min(100) as f32 / 100.0).clamp(0.0, 1.0);
|
||||
let to_value = move |x: f32| (((x - k / 2.0) / travel).clamp(0.0, 1.0) * 100.0).round() as u32;
|
||||
let on_change = std::sync::Arc::new(on_change);
|
||||
let drag_change = on_change.clone();
|
||||
let step_change = on_change;
|
||||
row()
|
||||
.key(format!("{key}-control"))
|
||||
.gap(space::S3)
|
||||
.center_y()
|
||||
.child(
|
||||
el().key(key)
|
||||
.role("slider")
|
||||
.label(label)
|
||||
.range_value(f64::from(value.min(100)), 0.0, 100.0)
|
||||
.range_step(5.0)
|
||||
.a11y_value(format!("{value}%"))
|
||||
.on_step(move |s: &mut App, steps, _| {
|
||||
let next = (i64::from(value) + i64::from(steps) * 5).clamp(0, 100) as u32;
|
||||
step_change(s, next);
|
||||
})
|
||||
.size(w, h)
|
||||
.motion(motion::SNAPPY)
|
||||
.on_drag(move |s: &mut App, d: &mut Drag, tx| match d.phase {
|
||||
Phase::Down => {
|
||||
d.data = v;
|
||||
let knob = k / 2.0 + v * travel;
|
||||
if (d.x - knob).abs() > k / 2.0 + 2.0 {
|
||||
let next = to_value(d.x);
|
||||
drag_change(s, next);
|
||||
}
|
||||
}
|
||||
Phase::Move => {
|
||||
let knob = k / 2.0 + d.data * travel;
|
||||
let grab = if (d.start_x - knob).abs() <= k / 2.0 + 2.0 {
|
||||
d.start_x - knob
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let next = to_value(d.x - grab);
|
||||
drag_change(s, next);
|
||||
tx.instant();
|
||||
}
|
||||
Phase::Up => {}
|
||||
})
|
||||
.child(
|
||||
el().key("track")
|
||||
.size(w, bar)
|
||||
.absolute(0.0, (h - bar) / 2.0)
|
||||
.radius(bar / 2.0)
|
||||
.fill(p.t.control_off)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
el().key("fill")
|
||||
.size(k / 2.0 + v * travel, bar)
|
||||
.absolute(0.0, (h - bar) / 2.0)
|
||||
.radius(bar / 2.0)
|
||||
.fill(p.accent)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
el().key("knob")
|
||||
.size(k, k)
|
||||
.absolute(v * travel, (h - k) / 2.0)
|
||||
.radius(k / 2.0)
|
||||
.fill(p.t.knob)
|
||||
.shadow(1.0, 3.0, p.t.knob_shadow)
|
||||
.shadow(0.0, 0.5, p.t.edge)
|
||||
.a11y_hidden(),
|
||||
),
|
||||
)
|
||||
.child(
|
||||
text(format!("{value}%"))
|
||||
.key("value")
|
||||
.w(40.0)
|
||||
.font(type_::MONO_CAPTION)
|
||||
.color(p.t.text_secondary)
|
||||
.align(rune::Align::End)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A one-line text field for a settings row. The text sits at the row's end edge, like every
|
||||
/// other control, so values start and end on one line down the card.
|
||||
pub fn text_field(
|
||||
p: Paint,
|
||||
key: &'static str,
|
||||
label: &str,
|
||||
edit: &rune::TextEdit,
|
||||
to: fn(&mut App) -> &mut rune::TextEdit,
|
||||
) -> El {
|
||||
text_field_width(p, key, label, 220.0, rune::Align::End, edit, to, |app| {
|
||||
app.form.dirty = true;
|
||||
})
|
||||
}
|
||||
|
||||
/// [`text_field`] at a given width and text alignment; a dialog field is wide and starts at its
|
||||
/// left edge, where typing begins.
|
||||
#[allow(clippy::too_many_arguments)] // the columns of a field: size, alignment and what typing does
|
||||
pub fn text_field_width(
|
||||
p: Paint,
|
||||
key: &'static str,
|
||||
label: &str,
|
||||
width: f32,
|
||||
align: rune::Align,
|
||||
edit: &rune::TextEdit,
|
||||
to: fn(&mut App) -> &mut rune::TextEdit,
|
||||
on_input: fn(&mut App),
|
||||
) -> El {
|
||||
let focused = edit.focused;
|
||||
row()
|
||||
.key(key)
|
||||
.h(28.0)
|
||||
.w(width)
|
||||
.px(8.0)
|
||||
.center_y()
|
||||
.radius(radius::MD)
|
||||
.fill(p.field)
|
||||
.border(
|
||||
p.hair,
|
||||
if focused {
|
||||
p.accent.alpha(0.7)
|
||||
} else {
|
||||
p.t.card_border
|
||||
},
|
||||
)
|
||||
.child(
|
||||
rune::text_input(edit, type_::BODY)
|
||||
.key("input")
|
||||
.single_line()
|
||||
.w_full()
|
||||
.label(label)
|
||||
.color(p.t.text)
|
||||
.align(align)
|
||||
.caret(p.t.text, p.accent.alpha(0.3))
|
||||
.on_edit(to)
|
||||
.on_input_change(move |app: &mut App, _| on_input(app)),
|
||||
)
|
||||
}
|
||||
|
||||
/// A pill tab; the selected one fills with the accent.
|
||||
pub fn tab(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
label: &str,
|
||||
selected: bool,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
el().key(key)
|
||||
.role("tab")
|
||||
.label(label)
|
||||
.checked(selected)
|
||||
.focusable(true)
|
||||
.px(18.0)
|
||||
.h(28.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(if selected {
|
||||
p.accent.alpha(0.22)
|
||||
} else {
|
||||
Color::TRANSPARENT
|
||||
})
|
||||
.border(
|
||||
p.hair,
|
||||
if selected {
|
||||
p.accent.alpha(0.32)
|
||||
} else {
|
||||
Color::TRANSPARENT
|
||||
},
|
||||
)
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(on_press)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::LABEL)
|
||||
.color(if selected {
|
||||
p.accent
|
||||
} else {
|
||||
p.t.text_secondary
|
||||
})
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A small pill button.
|
||||
pub fn button(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
label: &str,
|
||||
primary: bool,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
el().key(key)
|
||||
.role("button")
|
||||
.label(label)
|
||||
.focusable(true)
|
||||
.h(28.0)
|
||||
.px(14.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(if primary { p.accent } else { p.t.control_off })
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(on_press)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::LABEL)
|
||||
.color(if primary { p.accent_ink } else { p.t.text })
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// One transport control: an icon, its accessible label, round like the bar it sits in.
|
||||
pub fn media_button(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
icon: &'static rune::Icon,
|
||||
label: &str,
|
||||
primary: bool,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
let ink = if primary { p.accent_ink } else { p.t.text };
|
||||
el().key(key)
|
||||
.role("button")
|
||||
.label(label)
|
||||
.focusable(true)
|
||||
.size(32.0, 32.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(if primary { p.accent } else { p.t.control_off })
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(on_press)
|
||||
.child(rune::icon(icon, 16.0).color(ink).a11y_hidden())
|
||||
}
|
||||
|
||||
/// A small square button holding one glyph, for the corner of a card or a dialog.
|
||||
pub fn icon_button(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
glyph: &str,
|
||||
label: &str,
|
||||
primary: bool,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
el().key(key)
|
||||
.role("button")
|
||||
.label(label)
|
||||
.focusable(true)
|
||||
.size(24.0, 24.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(if primary {
|
||||
p.accent.alpha(0.14)
|
||||
} else {
|
||||
Color::TRANSPARENT
|
||||
})
|
||||
.border(
|
||||
p.hair,
|
||||
if primary {
|
||||
p.accent.alpha(0.32)
|
||||
} else {
|
||||
Color::TRANSPARENT
|
||||
},
|
||||
)
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(on_press)
|
||||
.child(
|
||||
text(glyph)
|
||||
.key("glyph")
|
||||
.font(body(if primary { 16.0 } else { 15.0 }))
|
||||
.color(if primary { p.accent } else { p.muted() })
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A primary button with nothing to do yet, for a dialog whose fields are still empty.
|
||||
pub fn button_muted(p: Paint, key: &str, label: &str) -> El {
|
||||
el().key(key)
|
||||
.role("button")
|
||||
.label(label)
|
||||
.disabled(true)
|
||||
.h(28.0)
|
||||
.px(14.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(p.accent.alpha(0.28))
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::LABEL)
|
||||
.color(p.accent_ink.alpha(0.55))
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
|
||||
/// A process's icon as Windows draws it for the executable, with its initial until the icon is
|
||||
/// decoded and for processes whose executable has none.
|
||||
pub fn process_icon(app: &App, p: Paint, process: &str, size: f32) -> El {
|
||||
let radius = (size * 0.22).max(2.0);
|
||||
let initial = process
|
||||
.trim()
|
||||
.chars()
|
||||
.next()
|
||||
.map(|c| c.to_ascii_uppercase().to_string())
|
||||
.unwrap_or_else(|| "?".to_string());
|
||||
let image = app
|
||||
.processes
|
||||
.get(&crate::process::normalize(process))
|
||||
.and_then(|found| found.path.as_deref())
|
||||
.and_then(|path| {
|
||||
app.icons
|
||||
.as_ref()
|
||||
.map(|icons| icons.app_icon_scaled(path, size, p.scale))
|
||||
});
|
||||
let tile = el()
|
||||
.key("process-icon")
|
||||
.size(size, size)
|
||||
.radius(radius)
|
||||
.fill(p.t.control_off)
|
||||
.a11y_hidden();
|
||||
match image {
|
||||
Some(image) => tile.child(
|
||||
el().key("process-image")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.radius(radius)
|
||||
.pixels(image.pixels()),
|
||||
),
|
||||
None => tile.child(
|
||||
text(initial)
|
||||
.key("initial")
|
||||
.font(body(size * 0.52))
|
||||
.color(p.muted())
|
||||
.center(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a process is up: a chip beside its name in the list.
|
||||
pub fn process_state(p: Paint, running: bool, width: f32) -> El {
|
||||
let color = if running { p.success } else { p.muted() };
|
||||
row()
|
||||
.key("process-state")
|
||||
.w(width)
|
||||
.h(20.0)
|
||||
.px(8.0)
|
||||
.gap(6.0)
|
||||
.center_y()
|
||||
.radius(radius::MD)
|
||||
.fill(color.alpha(0.12))
|
||||
.child(
|
||||
el().key("state-dot")
|
||||
.size(6.0, 6.0)
|
||||
.radius(3.0)
|
||||
.fill(color)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
.child(
|
||||
text(if running { "Running" } else { "Not found" })
|
||||
.key("state-label")
|
||||
.font(body(10.5))
|
||||
.color(color),
|
||||
)
|
||||
}
|
||||
|
||||
/// A coloured dot used for status.
|
||||
pub fn dot(color: Color) -> El {
|
||||
el().key("dot")
|
||||
.size(8.0, 8.0)
|
||||
.radius(4.0)
|
||||
.fill(color)
|
||||
.a11y_hidden()
|
||||
}
|
||||
|
||||
/// A square champion portrait at `size` points: the Data Dragon file once it is on disk,
|
||||
/// initials on a colour derived from the name until then (and offline).
|
||||
pub fn champion_portrait(app: &App, p: Paint, champion: Option<&str>, size: f32) -> El {
|
||||
let name = champion.unwrap_or_default();
|
||||
let hue = name
|
||||
.bytes()
|
||||
.fold(2166136261u32, |hash, byte| {
|
||||
hash.wrapping_mul(16777619) ^ byte as u32
|
||||
})
|
||||
.rem_euclid(360) as f32;
|
||||
let (fill, ink) = if name.is_empty() {
|
||||
(p.t.control_off, p.muted())
|
||||
} else {
|
||||
(rune::oklch(0.36, 0.075, hue), rune::oklch(0.94, 0.02, hue))
|
||||
};
|
||||
let radius = (size * 0.14).max(2.0);
|
||||
let tile = el()
|
||||
.key("portrait")
|
||||
.size(size, size)
|
||||
.radius(radius)
|
||||
.fill(fill)
|
||||
.border(p.hair, ink.alpha(0.18))
|
||||
.a11y_hidden();
|
||||
match app
|
||||
.portraits
|
||||
.as_ref()
|
||||
.and_then(|portraits| portraits.image(name, size, p.scale))
|
||||
{
|
||||
Some(image) => tile.child(
|
||||
el().key("portrait-image")
|
||||
.w_full()
|
||||
.h_full()
|
||||
.radius(radius)
|
||||
.pixels(image.pixels()),
|
||||
),
|
||||
None => tile.child(
|
||||
text(initials(name))
|
||||
.font(heading(size * 0.33))
|
||||
.color(ink)
|
||||
.center(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Up to two letters from the champion's name: `Kai'Sa` is KS, `Jinx` is J.
|
||||
fn initials(name: &str) -> String {
|
||||
let letters: Vec<char> = name
|
||||
.split(|c: char| !c.is_alphanumeric())
|
||||
.filter(|word| !word.is_empty())
|
||||
.filter_map(|word| word.chars().next())
|
||||
.take(2)
|
||||
.collect();
|
||||
if letters.is_empty() {
|
||||
"?".into()
|
||||
} else {
|
||||
letters.into_iter().collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A scroll viewport's scroll bar: a thumb in a strip of its own at the viewport's end edge,
|
||||
/// shown whenever the content overflows, and dragged to scroll.
|
||||
///
|
||||
/// The screen lays the thumb where the viewport's strip is (the content leaves it room), so it
|
||||
/// never draws over a card. `follow` takes where the viewport is, `thumb` draws it.
|
||||
pub struct ScrollBar {
|
||||
area: rune::Live<[f32; 4]>,
|
||||
thumb: rune::Live<[f32; 4]>,
|
||||
last: std::rc::Rc<std::cell::Cell<rune::ScrollPos>>,
|
||||
}
|
||||
|
||||
impl Default for ScrollBar {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ScrollBar {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
area: rune::Live::new([0.0; 4]),
|
||||
thumb: rune::Live::new([0.0; 4]),
|
||||
last: std::rc::Rc::new(std::cell::Cell::new(rune::ScrollPos::default())),
|
||||
}
|
||||
}
|
||||
/// Where the viewport is scrolled to, as of the last frame that reported it.
|
||||
///
|
||||
/// A screen can read this to load more rows as the end of a long list comes into view.
|
||||
pub fn position(&self) -> rune::ScrollPos {
|
||||
self.last.get()
|
||||
}
|
||||
|
||||
/// Make this viewport's scrolling move the thumb, and its key one a drag can scroll to.
|
||||
pub fn follow(&self, key: &'static str, viewport: El) -> El {
|
||||
let reported = self.area.clone();
|
||||
let area = self.area.clone();
|
||||
let thumb = self.thumb.clone();
|
||||
let layout_thumb = self.thumb.clone();
|
||||
let last = self.last.clone();
|
||||
let layout_last = self.last.clone();
|
||||
viewport
|
||||
.on_layout_tx(move |_app: &mut App, rect, tx| {
|
||||
reported.set(rect);
|
||||
place(&layout_thumb, rect, layout_last.get());
|
||||
tx.live_only();
|
||||
})
|
||||
.on_scroll_offset(move |at: rune::ScrollPos| {
|
||||
last.set(at);
|
||||
place(&thumb, area.get(), at);
|
||||
})
|
||||
.key(key)
|
||||
}
|
||||
|
||||
/// The thumb, drawn over the window. `key` must differ per bar on one screen.
|
||||
pub fn thumb(&self, p: Paint, key: &'static str, viewport: &'static str) -> El {
|
||||
let last = self.last.clone();
|
||||
let area = self.area.clone();
|
||||
el().key(key)
|
||||
.absolute(0.0, 0.0)
|
||||
.size(10.0, 0.0)
|
||||
.radius(5.0)
|
||||
.fill(p.t.text_secondary.alpha(0.45))
|
||||
.hover(p.t.text_secondary.alpha(0.8))
|
||||
.live_rect(&self.thumb)
|
||||
.a11y_hidden()
|
||||
.on_drag_any(move |d: &mut rune::Drag, tx: &mut rune::Tx| {
|
||||
tx.live_only();
|
||||
let at = last.get();
|
||||
let max = at.max[1];
|
||||
let [_, _, _, area_h] = area.get();
|
||||
let travel = (area_h - d.h).max(1.0);
|
||||
if max <= 0.5 || area_h <= 1.0 {
|
||||
return;
|
||||
}
|
||||
match d.phase {
|
||||
rune::Phase::Down => d.data = at.offset[1],
|
||||
rune::Phase::Move => {
|
||||
let y = (d.data + d.dy * max / travel).clamp(0.0, max);
|
||||
tx.scroll_to(viewport, 0.0, y);
|
||||
}
|
||||
rune::Phase::Up => {}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the thumb where `at` says the viewport is, inside `area`'s window rect.
|
||||
fn place(thumb: &rune::Live<[f32; 4]>, [x, y, w, h]: [f32; 4], at: rune::ScrollPos) {
|
||||
let content = at.viewport[1] + at.max[1];
|
||||
if h <= 1.0 || w <= 1.0 || at.max[1] <= 0.5 || content <= 0.0 {
|
||||
thumb.set([0.0, 0.0, 0.0, 0.0]);
|
||||
return;
|
||||
}
|
||||
let height = (h * at.viewport[1] / content).clamp(28.0, h);
|
||||
let progress = (at.offset[1] / at.max[1]).clamp(0.0, 1.0);
|
||||
thumb.set([x + w - 12.0, y + progress * (h - height), 10.0, height]);
|
||||
}
|
||||
|
||||
/// A small square button holding an icon: the trigger a menu opens from. Its handler says what
|
||||
/// opening means; the menu itself is drawn in the window, so it can never leave it.
|
||||
pub fn menu_button(
|
||||
p: Paint,
|
||||
key: impl Into<String>,
|
||||
icon: &'static rune::Icon,
|
||||
label: &str,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
el().key(key.into())
|
||||
.role("button")
|
||||
.label(label)
|
||||
.focusable(true)
|
||||
.size(24.0, 24.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.hover(p.t.hover)
|
||||
.press(p.t.press)
|
||||
.on_press(on_press)
|
||||
.child(rune::icon(icon, 18.0).color(p.muted()).a11y_hidden())
|
||||
}
|
||||
|
||||
/// A quiet destructive button: danger ink for a confirm whose answer cannot be undone.
|
||||
pub fn button_danger(
|
||||
p: Paint,
|
||||
key: &str,
|
||||
label: &str,
|
||||
on_press: impl Fn(&mut App) + Send + Sync + 'static,
|
||||
) -> El {
|
||||
el().key(key)
|
||||
.role("button")
|
||||
.label(label)
|
||||
.focusable(true)
|
||||
.h(28.0)
|
||||
.px(14.0)
|
||||
.center()
|
||||
.radius(radius::MD)
|
||||
.fill(p.danger.alpha(0.14))
|
||||
.border(p.hair, p.danger.alpha(0.32))
|
||||
.hover(p.danger.alpha(0.22))
|
||||
.press(p.danger.alpha(0.3))
|
||||
.on_press(on_press)
|
||||
.child(
|
||||
text(label)
|
||||
.key("label")
|
||||
.font(type_::LABEL)
|
||||
.color(p.danger)
|
||||
.a11y_hidden(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "6e1143dda817360dd3a2a64f9133c6e5dfabd881"
|
||||
},
|
||||
"path_in_vcs": "parley_engine"
|
||||
}
|
||||
+545
@@ -0,0 +1,545 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck"
|
||||
version = "1.25.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
|
||||
dependencies = [
|
||||
"bytemuck_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bytemuck_derive"
|
||||
version = "1.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core_maths"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30"
|
||||
dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "displaydoc"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "81bf886368962a7d8456f136073ed33ed1b0770c690d2063731bb6a776e99f33"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fontique"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbf1df16263783918b7da396077521f92b729ef7c429444dfcf03581f1448b77"
|
||||
dependencies = [
|
||||
"hashbrown",
|
||||
"linebender_resource_handle",
|
||||
"memmap2",
|
||||
"parlance",
|
||||
"read-fonts",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "harfrust"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"bytemuck",
|
||||
"core_maths",
|
||||
"read-fonts",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.17.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
||||
dependencies = [
|
||||
"foldhash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_collections"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"potential_utf",
|
||||
"utf8_iter",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_core"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"litemap",
|
||||
"serde",
|
||||
"tinystr",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_fallback"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "251af8e57c9400e3eb58242fe5b8b1152b2a64fdf4cf632f923c38ccee6f2fa9"
|
||||
dependencies = [
|
||||
"icu_locale_core",
|
||||
"icu_locale_fallback_data",
|
||||
"icu_provider",
|
||||
"potential_utf",
|
||||
"tinystr",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_locale_fallback_data"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "decf2a22ec8fa68f1a0c1129a3f8583f8f8bc24e8b9ccbe98ead99f62a4dc3a8"
|
||||
|
||||
[[package]]
|
||||
name = "icu_normalizer"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
|
||||
dependencies = [
|
||||
"icu_collections",
|
||||
"icu_normalizer_data",
|
||||
"icu_properties",
|
||||
"icu_provider",
|
||||
"smallvec",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_normalizer_data"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
|
||||
|
||||
[[package]]
|
||||
name = "icu_properties"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"icu_collections",
|
||||
"icu_locale_core",
|
||||
"icu_properties_data",
|
||||
"icu_provider",
|
||||
"zerotrie",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_properties_data"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
|
||||
|
||||
[[package]]
|
||||
name = "icu_provider"
|
||||
version = "2.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"icu_locale_core",
|
||||
"serde",
|
||||
"stable_deref_trait",
|
||||
"writeable",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerotrie",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_segmenter"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "82d07aafccd67af15d02512a6adf5896fbc5ed00f2e99b471d2efa14016db3db"
|
||||
dependencies = [
|
||||
"icu_collections",
|
||||
"icu_locale_fallback",
|
||||
"icu_provider",
|
||||
"icu_segmenter_data",
|
||||
"potential_utf",
|
||||
"smallvec",
|
||||
"utf8_iter",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "icu_segmenter_data"
|
||||
version = "2.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae293c039020f9ec10710af98d29ce6aa2051486638b49c9a6409f3b4a9e98ad"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.186"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
||||
|
||||
[[package]]
|
||||
name = "libm"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
|
||||
|
||||
[[package]]
|
||||
name = "linebender_resource_handle"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
|
||||
|
||||
[[package]]
|
||||
name = "litemap"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
|
||||
|
||||
[[package]]
|
||||
name = "memmap2"
|
||||
version = "0.9.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "parlance"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parley_data"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c43b63f808f6cc8f4a3b07de0d62a977bddd2e0bb5c232bd9e93ba8ef92e5e4b"
|
||||
dependencies = [
|
||||
"icu_collections",
|
||||
"icu_properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parley_emoji"
|
||||
version = "0.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c4482d912d7671a7cd2089794f90ef3bb5f5f8c738230fb0fcd50fa020f0ed3"
|
||||
|
||||
[[package]]
|
||||
name = "parley_engine"
|
||||
version = "0.12.0"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust",
|
||||
"hashbrown",
|
||||
"icu_locale_core",
|
||||
"icu_normalizer",
|
||||
"icu_properties",
|
||||
"icu_segmenter",
|
||||
"linebender_resource_handle",
|
||||
"parlance",
|
||||
"parley_data",
|
||||
"parley_emoji",
|
||||
"skrifa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "potential_utf"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"writeable",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.41.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"core_maths",
|
||||
"font-types",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.44.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"core_maths",
|
||||
"read-fonts",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.16.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"
|
||||
|
||||
[[package]]
|
||||
name = "stable_deref_trait"
|
||||
version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.118"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "3.0.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "synstructure"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinystr"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"serde_core",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "utf8_iter"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
|
||||
|
||||
[[package]]
|
||||
name = "yoke"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
|
||||
dependencies = [
|
||||
"stable_deref_trait",
|
||||
"yoke-derive",
|
||||
"zerofrom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yoke-derive"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom"
|
||||
version = "0.1.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
|
||||
dependencies = [
|
||||
"zerofrom-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerofrom-derive"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.118",
|
||||
"synstructure",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerotrie"
|
||||
version = "0.2.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
|
||||
dependencies = [
|
||||
"displaydoc",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerovec"
|
||||
version = "0.11.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"yoke",
|
||||
"zerofrom",
|
||||
"zerovec-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerovec-derive"
|
||||
version = "0.11.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 3.0.6",
|
||||
]
|
||||
Vendored
+162
@@ -0,0 +1,162 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
name = "parley_engine"
|
||||
version = "0.12.0"
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Parley Engine provides low level APIs for implementing text layout."
|
||||
readme = "README.md"
|
||||
keywords = [
|
||||
"text",
|
||||
"layout",
|
||||
]
|
||||
categories = [
|
||||
"gui",
|
||||
"graphics",
|
||||
]
|
||||
license = "Apache-2.0 OR MIT"
|
||||
repository = "https://github.com/linebender/parley"
|
||||
resolver = "2"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
[features]
|
||||
bytemuck = [
|
||||
"fontique/bytemuck",
|
||||
"parlance/bytemuck",
|
||||
]
|
||||
complex-scripts = []
|
||||
line-dictionaries = []
|
||||
default = ["std"]
|
||||
libm = [
|
||||
"fontique/libm",
|
||||
"harfrust/libm",
|
||||
"skrifa/libm",
|
||||
]
|
||||
std = [
|
||||
"fontique/std",
|
||||
"harfrust/std",
|
||||
"parlance/std",
|
||||
"parley_emoji/std",
|
||||
"skrifa/std",
|
||||
]
|
||||
|
||||
[lib]
|
||||
name = "parley_engine"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies.fontique]
|
||||
version = "0.12.0"
|
||||
default-features = false
|
||||
|
||||
[dependencies.harfrust]
|
||||
version = "0.12.0"
|
||||
default-features = false
|
||||
|
||||
[dependencies.hashbrown]
|
||||
version = "0.17.1"
|
||||
features = [
|
||||
"default-hasher",
|
||||
"raw-entry",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[dependencies.icu_locale_core]
|
||||
version = "2.3.0"
|
||||
default-features = false
|
||||
|
||||
[dependencies.icu_normalizer]
|
||||
version = "2.3.0"
|
||||
features = ["compiled_data"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.icu_properties]
|
||||
version = "2.3.0"
|
||||
features = ["compiled_data"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.icu_segmenter]
|
||||
version = "2.3.0"
|
||||
features = ["compiled_data"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.linebender_resource_handle]
|
||||
version = "0.1.1"
|
||||
default-features = false
|
||||
|
||||
[dependencies.parlance]
|
||||
version = "0.1.1"
|
||||
default-features = false
|
||||
|
||||
[dependencies.parley_data]
|
||||
version = "0.12.0"
|
||||
features = ["baked"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.parley_emoji]
|
||||
version = "0.12.0"
|
||||
default-features = false
|
||||
|
||||
[dependencies.skrifa]
|
||||
version = "0.44.0"
|
||||
default-features = false
|
||||
|
||||
[lints.clippy]
|
||||
allow_attributes_without_reason = "warn"
|
||||
cargo_common_metadata = "warn"
|
||||
cast_possible_truncation = "warn"
|
||||
collection_is_never_read = "warn"
|
||||
dbg_macro = "warn"
|
||||
debug_assert_with_mut_call = "warn"
|
||||
default_trait_access = "warn"
|
||||
doc_markdown = "warn"
|
||||
fn_to_numeric_cast_any = "warn"
|
||||
infinite_loop = "warn"
|
||||
large_stack_arrays = "warn"
|
||||
mismatching_type_param_order = "warn"
|
||||
missing_assert_message = "warn"
|
||||
missing_fields_in_debug = "warn"
|
||||
negative_feature_names = "warn"
|
||||
redundant_feature_names = "warn"
|
||||
same_functions_in_if_condition = "warn"
|
||||
semicolon_if_nothing_returned = "warn"
|
||||
should_panic_without_expect = "warn"
|
||||
todo = "warn"
|
||||
too_many_arguments = "allow"
|
||||
unseparated_literal_suffix = "warn"
|
||||
use_self = "warn"
|
||||
wildcard_dependencies = "warn"
|
||||
|
||||
[lints.rust]
|
||||
elided_lifetimes_in_paths = "warn"
|
||||
keyword_idents_2024 = "forbid"
|
||||
missing_debug_implementations = "warn"
|
||||
missing_docs = "warn"
|
||||
non_ascii_idents = "forbid"
|
||||
non_local_definitions = "forbid"
|
||||
trivial_numeric_casts = "warn"
|
||||
unnameable_types = "warn"
|
||||
unreachable_pub = "warn"
|
||||
unsafe_code = "deny"
|
||||
unsafe_op_in_unsafe_fn = "forbid"
|
||||
unused_import_braces = "warn"
|
||||
unused_lifetimes = "warn"
|
||||
unused_macro_rules = "warn"
|
||||
unused_qualifications = "warn"
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
[package]
|
||||
name = "parley_engine"
|
||||
version.workspace = true
|
||||
description = "Parley Engine provides low level APIs for implementing text layout."
|
||||
keywords = ["text", "layout"]
|
||||
categories = ["gui", "graphics"]
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
all-features = true
|
||||
|
||||
[features]
|
||||
default = ["std"]
|
||||
std = ["fontique/std", "harfrust/std", "parlance/std", "parley_emoji/std", "skrifa/std"]
|
||||
libm = ["fontique/libm", "harfrust/libm", "skrifa/libm"]
|
||||
bytemuck = ["fontique/bytemuck", "parlance/bytemuck"]
|
||||
# Enables dictionary-based line and word breaking for complex scripts (CJK, Thai, Khmer, Lao, Myanmar).
|
||||
# When disabled, a lightweight segmenter is used that falls back to character-level breaks for those scripts.
|
||||
complex-scripts = []
|
||||
|
||||
[dependencies]
|
||||
fontique = { workspace = true }
|
||||
parlance = { workspace = true }
|
||||
parley_data = { workspace = true, features = ["baked"] }
|
||||
parley_emoji = { workspace = true }
|
||||
|
||||
harfrust = { workspace = true }
|
||||
hashbrown = { workspace = true }
|
||||
icu_locale_core = { workspace = true }
|
||||
icu_normalizer = { workspace = true, features = ["compiled_data"] }
|
||||
icu_properties = { workspace = true, features = ["compiled_data"] }
|
||||
icu_segmenter = { workspace = true, features = ["compiled_data"] }
|
||||
linebender_resource_handle = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
Copyright 2025 the Parley Authors
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
Vendored
+137
@@ -0,0 +1,137 @@
|
||||
<div align="center">
|
||||
|
||||
# Parley Engine
|
||||
|
||||
**Low level text layout**
|
||||
|
||||
[](https://crates.io/crates/parley_engine)
|
||||
[](https://docs.rs/parley_engine)
|
||||
[](#license)
|
||||
\
|
||||
[](https://xi.zulipchat.com/#narrow/channel/205635-parley)
|
||||
[](https://github.com/linebender/parley/actions)
|
||||
[](https://deps.rs/crate/parley_engine)
|
||||
|
||||
</div>
|
||||
|
||||
<!-- We use cargo-rdme to update the README with the contents of lib.rs.
|
||||
To edit the following section, update it in lib.rs, then run:
|
||||
cargo rdme --workspace-project=parley_engine --heading-base-level=0
|
||||
Full documentation at https://github.com/orium/cargo-rdme -->
|
||||
|
||||
<!-- Intra-doc links used in lib.rs should be evaluated here.
|
||||
See https://linebender.org/blog/doc-include/ for related discussion. -->
|
||||
|
||||
<!-- cargo-rdme start -->
|
||||
|
||||
Parley Engine provides low level APIs for shaping paragraphs of text.
|
||||
|
||||
## Usage
|
||||
|
||||
Use [`Analyzer`], [`Analysis`], [`Shaper`] and [`ShapedText`] to shape a paragraph of text into
|
||||
glyphs. Correct reshaping of lines is in progress; in the meantime you can break text at
|
||||
[`Atom`] or [`ShapedCluster`][crate::shape::ShapedCluster] boundaries.
|
||||
|
||||
Text analysis is performed before shaping, and the same source string must be passed to each
|
||||
stage.
|
||||
|
||||
Higher-level users may prefer using [`parley`][parley], which uses this crate and implements
|
||||
layout and styling.
|
||||
|
||||
```rust
|
||||
let mut analysis = Analysis::default();
|
||||
let mut analyzer = Analyzer::default();
|
||||
let mut shaped_text = ShapedText::default();
|
||||
let mut shaper = Shaper::default();
|
||||
|
||||
let text = "The quick brown ثعلب jumps over the lazy dog.";
|
||||
let char_count = text.chars().count();
|
||||
let char_style_indices = vec![0; char_count];
|
||||
|
||||
analyzer.analyze(text, &AnalysisOptions::default(), &mut analysis);
|
||||
shaper.shape_text(
|
||||
text,
|
||||
&analysis,
|
||||
&char_style_indices,
|
||||
[Item {
|
||||
char_end: char_count.try_into().unwrap(),
|
||||
options: ShapeOptions {
|
||||
font_size: 16.0,
|
||||
language: None,
|
||||
features: &[],
|
||||
variations: &[],
|
||||
},
|
||||
}],
|
||||
select_font, // Selects fonts covering each cluster.
|
||||
&mut shaped_text,
|
||||
);
|
||||
|
||||
for (run_idx, run) in shaped_text.runs().iter().enumerate() {
|
||||
let slice = shaped_text.run_slice(run_idx as u32);
|
||||
// You can, for example, measure grapheme advances for hit-testing or
|
||||
// placing carets.
|
||||
for atom in slice.atoms_start() {
|
||||
for grapheme in atom.graphemes_start() {
|
||||
std::dbg!(grapheme);
|
||||
}
|
||||
}
|
||||
|
||||
// Or get glyphs for rendering (for simplicity, this iterates clusters in
|
||||
// logical order, but for rendering you'd want to reorder runs and clusters
|
||||
// according to their `run.bidi_level`).
|
||||
for cluster in slice.shaped_clusters_range() {
|
||||
for glyph in slice.shaped_cluster_glyphs(cluster) {
|
||||
std::dbg!(glyph);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- `std` (enabled by default): This is currently unused and is provided for forward compatibility.
|
||||
- `bytemuck`: Forwarded to [`parlance`], which then implements traits from `bytemuck` on its
|
||||
types.
|
||||
|
||||
[parley]: https://docs.rs/parley
|
||||
|
||||
<!-- cargo-rdme end -->
|
||||
|
||||
## Minimum supported Rust Version (MSRV)
|
||||
|
||||
This version of Parley Engine has been verified to compile with **Rust 1.88** and later.
|
||||
|
||||
Future versions of Parley Engine might increase the Rust version requirement.
|
||||
It will not be treated as a breaking change and as such can even happen with small patch releases.
|
||||
|
||||
<details>
|
||||
<summary>Click here if compiling fails.</summary>
|
||||
|
||||
As time has passed, some of Parley Engine's dependencies could have released versions with a higher Rust requirement.
|
||||
If you encounter a compilation issue due to a dependency and don't want to upgrade your Rust toolchain, then you could downgrade the dependency.
|
||||
|
||||
```sh
|
||||
# Use the problematic dependency's name and version
|
||||
cargo update -p package_name --precise 0.1.1
|
||||
```
|
||||
</details>
|
||||
|
||||
## Community
|
||||
|
||||
Discussion of Parley Engine development happens in the [Linebender Zulip](https://xi.zulipchat.com/), specifically the [#parley channel](https://xi.zulipchat.com/#narrow/channel/205635-parley).
|
||||
All public content can be read without logging in.
|
||||
|
||||
Contributions are welcome by pull request. The [Rust code of conduct] applies.
|
||||
|
||||
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache 2.0 license, shall be licensed as noted in the [License](#license) section, without any additional terms or conditions.
|
||||
|
||||
## License
|
||||
|
||||
Licensed under either of
|
||||
|
||||
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
|
||||
|
||||
at your option.
|
||||
|
||||
[Rust code of conduct]: https://www.rust-lang.org/policies/code-of-conduct
|
||||
+934
@@ -0,0 +1,934 @@
|
||||
// Copyright 2025 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Text analysis.
|
||||
//!
|
||||
//! Analysis is performed prior to shaping and is independent of fonts, turning a `&str` into
|
||||
//! [`Analysis`].
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use core::ops::Range;
|
||||
|
||||
use icu_locale_core::{LanguageIdentifier, langid};
|
||||
use icu_normalizer::properties::{
|
||||
CanonicalComposition, CanonicalCompositionBorrowed, CanonicalDecomposition,
|
||||
CanonicalDecompositionBorrowed,
|
||||
};
|
||||
use icu_properties::props::{BidiMirroringGlyph, GeneralCategory, GraphemeClusterBreak, Script};
|
||||
use icu_properties::{
|
||||
CodePointMapData, CodePointMapDataBorrowed, PropertyNamesShort, PropertyNamesShortBorrowed,
|
||||
};
|
||||
use icu_segmenter::options::{
|
||||
LineBreakOptions, LineBreakStrictness, LineBreakWordOption, WordBreakInvariantOptions,
|
||||
};
|
||||
use icu_segmenter::{
|
||||
GraphemeClusterSegmenter, GraphemeClusterSegmenterBorrowed, LineSegmenter,
|
||||
LineSegmenterBorrowed, WordSegmenter, WordSegmenterBorrowed,
|
||||
};
|
||||
use parlance::{BaseDirection, BidiLevel, LineBreak, WordBreak};
|
||||
use parley_data::Properties;
|
||||
|
||||
use crate::bidi;
|
||||
use crate::break_overrides::LineBreakContext;
|
||||
use crate::{AnalysisOptions, Analyzer, LineBreakConfig};
|
||||
|
||||
/// The result of [`Analyzer::analyze`].
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Analysis {
|
||||
/// Info for each character.
|
||||
pub(crate) info: Vec<CharInfo>,
|
||||
|
||||
/// Bidi level for each character, parallel to `info`.
|
||||
///
|
||||
/// Empty if the text is all LTR.
|
||||
pub(crate) levels: Vec<BidiLevel>,
|
||||
|
||||
/// The base bidi level of the paragraph of text.
|
||||
pub(crate) paragraph_level: BidiLevel,
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
/// Create a reusable [`Analysis`].
|
||||
///
|
||||
/// Pass this to [`Analyzer::analyze`].
|
||||
#[inline]
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Clear the result while retaining capacity.
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.info.clear();
|
||||
self.levels.clear();
|
||||
self.paragraph_level = BidiLevel::new(0);
|
||||
}
|
||||
|
||||
/// The per-character info in source order.
|
||||
#[inline(always)]
|
||||
pub fn char_info(&self) -> &[CharInfo] {
|
||||
&self.info
|
||||
}
|
||||
|
||||
/// The bidi level for each character, parallel to [`Self::char_info`].
|
||||
///
|
||||
/// Empty when the whole paragraph is left-to-right.
|
||||
#[inline(always)]
|
||||
pub fn bidi_levels(&self) -> &[BidiLevel] {
|
||||
&self.levels
|
||||
}
|
||||
|
||||
/// The base bidi level of the paragraph of text.
|
||||
#[inline(always)]
|
||||
pub fn paragraph_level(&self) -> BidiLevel {
|
||||
self.paragraph_level
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Make `pub(crate)` once `parley_engine` owns shaping.
|
||||
#[doc(hidden)]
|
||||
#[expect(missing_debug_implementations, reason = "Will become private")]
|
||||
pub struct AnalysisDataSources;
|
||||
|
||||
impl AnalysisDataSources {
|
||||
#[expect(clippy::new_without_default, reason = "Will become private")]
|
||||
pub fn new() -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn properties(&self, c: char) -> Properties {
|
||||
Properties::get(c)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn grapheme_segmenter(&self) -> GraphemeClusterSegmenterBorrowed<'_> {
|
||||
const { GraphemeClusterSegmenter::new() }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn word_segmenter(&self) -> WordSegmenterBorrowed<'static> {
|
||||
#[cfg(feature = "complex-scripts")]
|
||||
{
|
||||
WordSegmenter::new_dictionary(WordBreakInvariantOptions::default())
|
||||
}
|
||||
#[cfg(not(feature = "complex-scripts"))]
|
||||
{
|
||||
const { WordSegmenter::new_for_non_complex_scripts(WordBreakInvariantOptions::default()) }
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn line_segmenter(&self, key: SegmenterKey) -> LineSegmenterBorrowed<'static> {
|
||||
// We use Japanese arbitrarily; see `SegmenterKey::ja_zh`.
|
||||
static JA: LanguageIdentifier = langid!("ja");
|
||||
|
||||
let mut opt = LineBreakOptions::default();
|
||||
opt.word_option = Some(key.word_option);
|
||||
opt.strictness = Some(key.strictness);
|
||||
opt.content_locale = key.ja_zh.then_some(&JA);
|
||||
line_segmenter_impl(opt)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn composing_normalizer(&self) -> CanonicalCompositionBorrowed<'_> {
|
||||
const { CanonicalComposition::new() }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn decomposing_normalizer(&self) -> CanonicalDecompositionBorrowed<'_> {
|
||||
const { CanonicalDecomposition::new() }
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn script_short_name(&self) -> PropertyNamesShortBorrowed<'static, Script> {
|
||||
PropertyNamesShort::new()
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn brackets(&self) -> CodePointMapDataBorrowed<'_, BidiMirroringGlyph> {
|
||||
const { CodePointMapData::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The segmenters an [`Analyzer`] has made, kept for its next texts (Rune:
|
||||
/// vendor/parley_engine.patch). Making one looks up its rule data and, with `complex-scripts`,
|
||||
/// loads the dictionaries; they're `'static` and `Copy`, so a kept one is the same value a new
|
||||
/// one would be.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Segmenters {
|
||||
line: Vec<(SegmenterKey, LineSegmenterBorrowed<'static>)>,
|
||||
word: Option<WordSegmenterBorrowed<'static>>,
|
||||
}
|
||||
|
||||
impl Segmenters {
|
||||
fn line(&mut self, key: SegmenterKey) -> LineSegmenterBorrowed<'static> {
|
||||
if let Some((_, segmenter)) = self.line.iter().find(|(k, _)| *k == key) {
|
||||
return *segmenter;
|
||||
}
|
||||
let segmenter = AnalysisDataSources::new().line_segmenter(key);
|
||||
self.line.push((key, segmenter));
|
||||
segmenter
|
||||
}
|
||||
|
||||
fn word(&mut self) -> WordSegmenterBorrowed<'static> {
|
||||
*self
|
||||
.word
|
||||
.get_or_insert_with(|| AnalysisDataSources::new().word_segmenter())
|
||||
}
|
||||
}
|
||||
|
||||
// `line-dictionaries` (Rune: vendor/parley_engine.patch): the line segmenter's Thai, Lao, Khmer and
|
||||
// Burmese dictionaries without the word segmenter's (Chinese and Japanese words come from the host's
|
||||
// `dictionary` segmenter instead).
|
||||
#[cfg(any(feature = "complex-scripts", feature = "line-dictionaries"))]
|
||||
#[inline(always)]
|
||||
fn line_segmenter_impl(opt: LineBreakOptions<'_>) -> LineSegmenterBorrowed<'static> {
|
||||
LineSegmenter::new_dictionary(opt)
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "complex-scripts", feature = "line-dictionaries")))]
|
||||
#[inline(always)]
|
||||
fn line_segmenter_impl(opt: LineBreakOptions<'_>) -> LineSegmenterBorrowed<'static> {
|
||||
LineSegmenter::new_for_non_complex_scripts(opt)
|
||||
}
|
||||
|
||||
/// The line segmenter configuration for a [`LineBreakConfig`].
|
||||
///
|
||||
/// Configurations which result in the same segmentation map to the same key.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct SegmenterKey {
|
||||
word_option: LineBreakWordOption,
|
||||
strictness: LineBreakStrictness,
|
||||
/// See [`LineBreakConfig::language`]; the only languages which impact segmentation are
|
||||
/// Chinese and Japanese. These impact it in the same way, and only under
|
||||
/// [`LineBreak::Normal`] and [`LineBreak::Loose`], so we only track whether one of them
|
||||
/// applies.
|
||||
ja_zh: bool,
|
||||
}
|
||||
|
||||
impl SegmenterKey {
|
||||
const DEFAULT: Self = Self {
|
||||
word_option: LineBreakWordOption::Normal,
|
||||
strictness: LineBreakStrictness::Strict,
|
||||
ja_zh: false,
|
||||
};
|
||||
|
||||
fn new(config: &LineBreakConfig) -> Self {
|
||||
let strictness = match config.line_break {
|
||||
LineBreak::Strict => LineBreakStrictness::Strict,
|
||||
LineBreak::Normal => LineBreakStrictness::Normal,
|
||||
LineBreak::Loose => LineBreakStrictness::Loose,
|
||||
// We add opportunities per grapheme ourselves.
|
||||
LineBreak::Anywhere => return Self::DEFAULT,
|
||||
};
|
||||
let word_option = match config.word_break {
|
||||
WordBreak::Normal => LineBreakWordOption::Normal,
|
||||
WordBreak::BreakAll => LineBreakWordOption::BreakAll,
|
||||
WordBreak::KeepAll => LineBreakWordOption::KeepAll,
|
||||
};
|
||||
let ja_zh = match strictness {
|
||||
LineBreakStrictness::Normal | LineBreakStrictness::Loose => config
|
||||
.language
|
||||
.is_some_and(|language| matches!(language.language(), "ja" | "zh")),
|
||||
_ => false,
|
||||
};
|
||||
Self {
|
||||
word_option,
|
||||
strictness,
|
||||
ja_zh,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-character analysis info.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CharInfo {
|
||||
/// The Unicode script this character belongs to.
|
||||
pub script: Script,
|
||||
flags: u16,
|
||||
}
|
||||
|
||||
impl CharInfo {
|
||||
const VARIATION_SELECTOR_SHIFT: u16 = 0;
|
||||
const REGION_INDICATOR_SHIFT: u16 = 1;
|
||||
const CONTROL_SHIFT: u16 = 2;
|
||||
const EMOJI_OR_PICTOGRAPH_SHIFT: u16 = 3;
|
||||
const CONTRIBUTES_TO_SHAPING_SHIFT: u16 = 4;
|
||||
const FORCE_NORMALIZE_SHIFT: u16 = 5;
|
||||
const GRAPHEME_START_SHIFT: u16 = 6;
|
||||
const WORD_BOUNDARY_SHIFT: u8 = 7;
|
||||
const SOFT_WRAP_OPPORTUNITY_SHIFT: u16 = 8;
|
||||
const EMOJI_SHIFT: u16 = 9;
|
||||
const EMOJI_PRESENTATION_SHIFT: u16 = 10;
|
||||
const EMOJI_MODIFIER_SHIFT: u16 = 11;
|
||||
const EMOJI_MODIFIER_BASE_SHIFT: u16 = 12;
|
||||
|
||||
const VARIATION_SELECTOR_MASK: u16 = 1 << Self::VARIATION_SELECTOR_SHIFT;
|
||||
const REGION_INDICATOR_MASK: u16 = 1 << Self::REGION_INDICATOR_SHIFT;
|
||||
const CONTROL_MASK: u16 = 1 << Self::CONTROL_SHIFT;
|
||||
const EMOJI_OR_PICTOGRAPH_MASK: u16 = 1 << Self::EMOJI_OR_PICTOGRAPH_SHIFT;
|
||||
const CONTRIBUTES_TO_SHAPING_MASK: u16 = 1 << Self::CONTRIBUTES_TO_SHAPING_SHIFT;
|
||||
const FORCE_NORMALIZE_MASK: u16 = 1 << Self::FORCE_NORMALIZE_SHIFT;
|
||||
const GRAPHEME_START_MASK: u16 = 1 << Self::GRAPHEME_START_SHIFT;
|
||||
const WORD_BOUNDARY_MASK: u16 = 1 << Self::WORD_BOUNDARY_SHIFT;
|
||||
const SOFT_WRAP_OPPORTUNITY_MASK: u16 = 1 << Self::SOFT_WRAP_OPPORTUNITY_SHIFT;
|
||||
const EMOJI_MASK: u16 = 1 << Self::EMOJI_SHIFT;
|
||||
const EMOJI_PRESENTATION_MASK: u16 = 1 << Self::EMOJI_PRESENTATION_SHIFT;
|
||||
const EMOJI_MODIFIER_MASK: u16 = 1 << Self::EMOJI_MODIFIER_SHIFT;
|
||||
const EMOJI_MODIFIER_BASE_MASK: u16 = 1 << Self::EMOJI_MODIFIER_BASE_SHIFT;
|
||||
|
||||
fn new(
|
||||
script: Script,
|
||||
is_variation_selector: bool,
|
||||
is_region_indicator: bool,
|
||||
is_control: bool,
|
||||
is_emoji_or_pictograph: bool,
|
||||
contributes_to_shaping: bool,
|
||||
force_normalize: bool,
|
||||
is_grapheme_start: bool,
|
||||
is_word_boundary: bool,
|
||||
is_soft_wrap_opportunity: bool,
|
||||
is_emoji: bool,
|
||||
is_emoji_presentation: bool,
|
||||
is_emoji_modifier: bool,
|
||||
is_emoji_modifier_base: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
script,
|
||||
flags: (is_variation_selector as u16) << Self::VARIATION_SELECTOR_SHIFT
|
||||
| (is_region_indicator as u16) << Self::REGION_INDICATOR_SHIFT
|
||||
| (is_control as u16) << Self::CONTROL_SHIFT
|
||||
| (is_emoji_or_pictograph as u16) << Self::EMOJI_OR_PICTOGRAPH_SHIFT
|
||||
| (contributes_to_shaping as u16) << Self::CONTRIBUTES_TO_SHAPING_SHIFT
|
||||
| (force_normalize as u16) << Self::FORCE_NORMALIZE_SHIFT
|
||||
| (is_grapheme_start as u16) << Self::GRAPHEME_START_SHIFT
|
||||
| (is_word_boundary as u16) << Self::WORD_BOUNDARY_SHIFT
|
||||
| (is_soft_wrap_opportunity as u16) << Self::SOFT_WRAP_OPPORTUNITY_SHIFT
|
||||
| (is_emoji as u16) << Self::EMOJI_SHIFT
|
||||
| (is_emoji_presentation as u16) << Self::EMOJI_PRESENTATION_SHIFT
|
||||
| (is_emoji_modifier as u16) << Self::EMOJI_MODIFIER_SHIFT
|
||||
| (is_emoji_modifier_base as u16) << Self::EMOJI_MODIFIER_BASE_SHIFT,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this character is a variation selector.
|
||||
#[inline(always)]
|
||||
pub fn is_variation_selector(self) -> bool {
|
||||
self.flags & Self::VARIATION_SELECTOR_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character is a regional indicator symbol.
|
||||
#[inline(always)]
|
||||
pub fn is_region_indicator(self) -> bool {
|
||||
self.flags & Self::REGION_INDICATOR_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character is a control character.
|
||||
#[inline(always)]
|
||||
pub fn is_control(self) -> bool {
|
||||
self.flags & Self::CONTROL_MASK != 0
|
||||
}
|
||||
|
||||
/// Returns whether the character has either of the `Emoji` or`Extended_Pictographic` properties.
|
||||
///
|
||||
/// Parley Engine uses this to determine whether a character might be part of an Emoji, and so whether to do
|
||||
/// more stringent checks.
|
||||
///
|
||||
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
|
||||
#[inline(always)]
|
||||
pub fn is_emoji_or_pictograph(self) -> bool {
|
||||
self.flags & Self::EMOJI_OR_PICTOGRAPH_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character has the `Emoji` property ([UTS #51][]).
|
||||
///
|
||||
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
|
||||
#[inline(always)]
|
||||
pub fn is_emoji(self) -> bool {
|
||||
self.flags & Self::EMOJI_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character has the `Emoji_Presentation` property ([UTS #51][]), i.e. it is
|
||||
/// displayed as an emoji by default.
|
||||
///
|
||||
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
|
||||
#[inline(always)]
|
||||
pub fn is_emoji_presentation(self) -> bool {
|
||||
self.flags & Self::EMOJI_PRESENTATION_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character has the `Emoji_Modifier` property ([UTS #51][]), i.e. it is a
|
||||
/// skin tone modifier.
|
||||
///
|
||||
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
|
||||
#[inline(always)]
|
||||
pub fn is_emoji_modifier(self) -> bool {
|
||||
self.flags & Self::EMOJI_MODIFIER_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character has the `Emoji_Modifier_Base` property ([UTS #51][]), i.e. it can
|
||||
/// be followed by a skin tone modifier.
|
||||
///
|
||||
/// [UTS #51]: https://www.unicode.org/reports/tr51/tr51-29.html#Emoji_Properties
|
||||
#[inline(always)]
|
||||
pub fn is_emoji_modifier_base(self) -> bool {
|
||||
self.flags & Self::EMOJI_MODIFIER_BASE_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character contributes glyphs to shaping (`false` for control characters and
|
||||
/// most format characters).
|
||||
#[inline(always)]
|
||||
pub fn contributes_to_shaping(self) -> bool {
|
||||
self.flags & Self::CONTRIBUTES_TO_SHAPING_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character should be normalized before glyph mapping during shaping.
|
||||
#[inline(always)]
|
||||
pub fn force_normalize(self) -> bool {
|
||||
self.flags & Self::FORCE_NORMALIZE_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether this character begins a grapheme cluster ([UAX #29 § 3][graphemes]).
|
||||
///
|
||||
/// [graphemes]: https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
|
||||
#[inline(always)]
|
||||
pub fn is_grapheme_start(self) -> bool {
|
||||
self.flags & Self::GRAPHEME_START_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether there is a word boundary before this character ([UAX #29 § 4][words]).
|
||||
///
|
||||
/// [words]: https://www.unicode.org/reports/tr29/#Word_Boundaries
|
||||
#[inline(always)]
|
||||
pub fn is_word_boundary(self) -> bool {
|
||||
self.flags & Self::WORD_BOUNDARY_MASK != 0
|
||||
}
|
||||
|
||||
/// Whether there is a soft wrap opportunity before this character ([UAX #14][line-breaking]).
|
||||
///
|
||||
/// Note mandatory breaks (like `\n`) are encoded as [`Whitespace`](crate::shape::Whitespace).
|
||||
///
|
||||
/// [line-breaking]: https://www.unicode.org/reports/tr14/
|
||||
#[inline(always)]
|
||||
pub fn is_soft_wrap_opportunity(self) -> bool {
|
||||
self.flags & Self::SOFT_WRAP_OPPORTUNITY_MASK != 0
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn analyze_text(
|
||||
analyzer: &mut Analyzer,
|
||||
text: &str,
|
||||
options: &AnalysisOptions<'_>,
|
||||
analysis: &mut Analysis,
|
||||
) {
|
||||
/// Turns the sparse, sorted, non-overlapping `options.line_break` into a contiguous sequence of
|
||||
/// `(range, segmenter key)` segments covering all of `text`.
|
||||
///
|
||||
/// Any region not covered by an override takes the default configuration.
|
||||
struct DenseLineBreaks<'a> {
|
||||
line_break: &'a [(Range<usize>, LineBreakConfig)],
|
||||
/// Index of the next word break to emit.
|
||||
next: usize,
|
||||
/// Start of the next segment to emit.
|
||||
cursor: usize,
|
||||
text_len: usize,
|
||||
}
|
||||
|
||||
impl<'a> DenseLineBreaks<'a> {
|
||||
fn new(line_break: &'a [(Range<usize>, LineBreakConfig)], text_len: usize) -> Self {
|
||||
Self {
|
||||
line_break,
|
||||
next: 0,
|
||||
cursor: 0,
|
||||
text_len,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for DenseLineBreaks<'_> {
|
||||
type Item = (Range<usize>, SegmenterKey);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.cursor >= self.text_len {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Ignore empty ranges.
|
||||
while self
|
||||
.line_break
|
||||
.get(self.next)
|
||||
.is_some_and(|(range, _)| range.is_empty())
|
||||
{
|
||||
self.next += 1;
|
||||
}
|
||||
|
||||
match self.line_break.get(self.next) {
|
||||
// A gap before the next override: fill it with the default up to its start.
|
||||
Some((range, _)) if self.cursor < range.start => {
|
||||
let segment = self.cursor..range.start;
|
||||
self.cursor = range.start;
|
||||
Some((segment, SegmenterKey::DEFAULT))
|
||||
}
|
||||
// At the next override: emit it.
|
||||
Some((range, config)) => {
|
||||
self.cursor = range.end;
|
||||
self.next += 1;
|
||||
Some((range.start..range.end, SegmenterKey::new(config)))
|
||||
}
|
||||
// No overrides remain: fill the default to the end.
|
||||
None => {
|
||||
let segment = self.cursor..self.text_len;
|
||||
self.cursor = self.text_len;
|
||||
Some((segment, SegmenterKey::DEFAULT))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct LineBreakSegmentIter<'a, I: Iterator> {
|
||||
text: &'a str,
|
||||
segments: I,
|
||||
char_indices: core::str::CharIndices<'a>,
|
||||
current_char: (usize, char),
|
||||
building_range_start: usize,
|
||||
previous_key: SegmenterKey,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
impl<'a, I> LineBreakSegmentIter<'a, I>
|
||||
where
|
||||
I: Iterator<Item = (Range<usize>, SegmenterKey)>,
|
||||
{
|
||||
fn new(text: &'a str, segments: I, first_segment: (Range<usize>, SegmenterKey)) -> Self {
|
||||
let mut char_indices = text.char_indices();
|
||||
let current_char_len = char_indices.next().unwrap();
|
||||
|
||||
Self {
|
||||
text,
|
||||
segments,
|
||||
char_indices,
|
||||
current_char: current_char_len,
|
||||
building_range_start: first_segment.0.start,
|
||||
previous_key: first_segment.1,
|
||||
done: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, I> Iterator for LineBreakSegmentIter<'a, I>
|
||||
where
|
||||
I: Iterator<Item = (Range<usize>, SegmenterKey)>,
|
||||
{
|
||||
type Item = (&'a str, SegmenterKey, bool);
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.done {
|
||||
return None;
|
||||
}
|
||||
|
||||
for (range, key) in self.segments.by_ref() {
|
||||
assert!(range.start < range.end, "Segments must not be empty");
|
||||
|
||||
let style_start_index = range.start;
|
||||
let mut prev_char_index = self.current_char;
|
||||
|
||||
// Find the character at the style boundary.
|
||||
while self.current_char.0 < style_start_index {
|
||||
prev_char_index = self.current_char;
|
||||
self.current_char = self.char_indices.next().unwrap();
|
||||
}
|
||||
|
||||
let current_key = key;
|
||||
if self.previous_key == current_key {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Produce one substring for each different segmenter key run
|
||||
let prev_size = prev_char_index.1.len_utf8();
|
||||
let size = self.current_char.1.len_utf8();
|
||||
|
||||
let substring = &self.text[self.building_range_start..style_start_index + size];
|
||||
let result_style = self.previous_key;
|
||||
|
||||
self.building_range_start = style_start_index - prev_size;
|
||||
self.previous_key = current_key;
|
||||
|
||||
return Some((substring, result_style, false));
|
||||
}
|
||||
|
||||
// Final segment
|
||||
self.done = true;
|
||||
let last_substring = &self.text[self.building_range_start..self.text.len()];
|
||||
Some((last_substring, self.previous_key, true))
|
||||
}
|
||||
}
|
||||
|
||||
if text.is_empty() {
|
||||
analyzer
|
||||
.bidi
|
||||
.resolve(core::iter::empty(), options.base_direction);
|
||||
analysis.paragraph_level = analyzer.bidi.base_level();
|
||||
return;
|
||||
}
|
||||
|
||||
// Line boundaries (word break naming refers to the line boundary determination config).
|
||||
//
|
||||
// This breaks text into sequences with similar line boundary config (part of style
|
||||
// information). If this config is consistent for all text, we use a fast path through this.
|
||||
let mut segments = DenseLineBreaks::new(options.line_break, text.len());
|
||||
// `text` is non-empty (checked above), so there is always at least one segment.
|
||||
let first_segment = segments.next().unwrap();
|
||||
let contiguous_substrings = LineBreakSegmentIter::new(text, segments, first_segment);
|
||||
|
||||
let mut global_offset = 0;
|
||||
let mut line_boundary_positions: Vec<usize> = Vec::new();
|
||||
|
||||
let data_sources = AnalysisDataSources::new();
|
||||
|
||||
for (substring_index, (substring, segmenter_key, last)) in contiguous_substrings.enumerate() {
|
||||
// Fast path for text with a single segmenter configuration.
|
||||
if substring_index == 0 && last {
|
||||
let mut lb_iter = analyzer
|
||||
.segmenters
|
||||
.line(segmenter_key)
|
||||
.segment_str(substring);
|
||||
|
||||
let _first = lb_iter.next();
|
||||
let second = lb_iter.next();
|
||||
if second.is_none() {
|
||||
continue;
|
||||
}
|
||||
let third = lb_iter.next();
|
||||
if third.is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let iter = [second.unwrap(), third.unwrap()].into_iter().chain(lb_iter);
|
||||
|
||||
line_boundary_positions.extend(iter);
|
||||
// Remove the unnecessary boundary at the end added by ICU4X.
|
||||
line_boundary_positions.pop();
|
||||
break;
|
||||
}
|
||||
|
||||
let line_boundaries_iter = analyzer
|
||||
.segmenters
|
||||
.line(segmenter_key)
|
||||
.segment_str(substring);
|
||||
|
||||
let mut substring_chars = substring.chars();
|
||||
if substring_index != 0 {
|
||||
global_offset -= substring_chars.next().unwrap().len_utf8();
|
||||
}
|
||||
// There will always be at least two characters if we are not taking the fast path for
|
||||
// a single word break style substring.
|
||||
let last_len = substring_chars.next_back().unwrap().len_utf8();
|
||||
|
||||
// Mark line boundaries (overriding word boundaries where present).
|
||||
for (index, pos) in line_boundaries_iter.enumerate() {
|
||||
// icu adds leading and trailing line boundaries, which we don't use.
|
||||
if index == 0 || pos == substring.len() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// For all but the last substring, we ignore line boundaries caused by the last
|
||||
// character, as this character is carried back from the next substring, and will be
|
||||
// accounted for there.
|
||||
if !last && pos == substring.len() - last_len {
|
||||
continue;
|
||||
}
|
||||
line_boundary_positions.push(pos + global_offset);
|
||||
}
|
||||
|
||||
if !last {
|
||||
global_offset += substring.len() - last_len;
|
||||
}
|
||||
}
|
||||
|
||||
// Words, and in Thai, Lao, Khmer and Burmese line breaks, that the host's dictionary finds
|
||||
// (`dictionary`; Rune: vendor/parley_engine.patch).
|
||||
let mut dictionary = crate::dictionary::Words::of(text, |c| data_sources.properties(c));
|
||||
let before = line_boundary_positions.len();
|
||||
line_boundary_positions.extend(dictionary.line_breaks());
|
||||
if line_boundary_positions.len() > before {
|
||||
line_boundary_positions.sort_unstable();
|
||||
line_boundary_positions.dedup();
|
||||
}
|
||||
|
||||
// Collect boundary byte positions compactly
|
||||
let mut wb_iter = analyzer.segmenters.word().segment_str(text).peekable();
|
||||
let mut gb_iter = data_sources
|
||||
.grapheme_segmenter()
|
||||
.segment_str(text)
|
||||
.peekable();
|
||||
|
||||
// Merge boundaries - line takes precedence over word
|
||||
let mut lb_iter = line_boundary_positions.iter().peekable();
|
||||
let mut prev_char = None;
|
||||
let mut prev_prev_char = None;
|
||||
// Whether the preceding character is a mandatory break.
|
||||
let mut prev_is_mandatory_linebreak = false;
|
||||
// Whether the preceding character is a break-space, i.e. a space, tab or ideographic space in
|
||||
// a `break_spaces` range.
|
||||
let mut prev_is_break_space = false;
|
||||
let mut break_spaces_iter = options.break_spaces.iter().peekable();
|
||||
let mut break_anywhere_iter = options
|
||||
.line_break
|
||||
.iter()
|
||||
.filter(|(_, config)| config.line_break == LineBreak::Anywhere)
|
||||
.map(|(range, _)| range)
|
||||
.peekable();
|
||||
let boundary_iter = text.char_indices().map(|(byte_pos, ch)| {
|
||||
// advance any stale word boundary positions
|
||||
while let Some(&w) = wb_iter.peek() {
|
||||
if w < byte_pos {
|
||||
_ = wb_iter.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// advance any stale grapheme boundary positions
|
||||
while let Some(&g) = gb_iter.peek() {
|
||||
if g < byte_pos {
|
||||
_ = gb_iter.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// advance any stale line boundary positions
|
||||
while let Some(&l) = lb_iter.peek() {
|
||||
if *l < byte_pos {
|
||||
_ = lb_iter.next();
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let mut is_word = false;
|
||||
if let Some(&w) = wb_iter.peek()
|
||||
&& w == byte_pos
|
||||
{
|
||||
is_word = true;
|
||||
_ = wb_iter.next();
|
||||
}
|
||||
let mut is_grapheme_start = false;
|
||||
if let Some(&g) = gb_iter.peek()
|
||||
&& g == byte_pos
|
||||
{
|
||||
is_grapheme_start = true;
|
||||
_ = gb_iter.next();
|
||||
}
|
||||
let properties = data_sources.properties(ch);
|
||||
|
||||
// For characters requiring a dictionary for deciding word boundaries, apply
|
||||
// UAX #29 Rule WB999 in case there's no dictionary (because ICU4X does not); inside a run
|
||||
// the host's dictionary segmented, its boundaries decide.
|
||||
if let Some(bound) = dictionary.word_at(byte_pos) {
|
||||
is_word = bound;
|
||||
} else if !is_word
|
||||
&& is_grapheme_start
|
||||
&& properties.needs_dictionary_word_break()
|
||||
&& !has_word_dictionary(properties.script())
|
||||
{
|
||||
is_word = true;
|
||||
}
|
||||
|
||||
let is_icu_line = if let Some(&l) = lb_iter.peek()
|
||||
&& *l == byte_pos
|
||||
{
|
||||
_ = lb_iter.next();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
// CSS Text 4 § 4.3.1 `break-spaces`: a soft wrap opportunity exists after each preserved
|
||||
// space or tab (but never directly before a mandatory break, UAX #14 LB6).
|
||||
while break_spaces_iter
|
||||
.peek()
|
||||
.is_some_and(|range| range.end <= byte_pos)
|
||||
{
|
||||
_ = break_spaces_iter.next();
|
||||
}
|
||||
let after_break_space = prev_is_break_space;
|
||||
prev_is_break_space = break_spaces_iter
|
||||
.peek()
|
||||
.is_some_and(|range| range.contains(&byte_pos))
|
||||
&& matches!(ch, ' ' | '\t' | '\u{3000}');
|
||||
|
||||
while break_anywhere_iter
|
||||
.peek()
|
||||
.is_some_and(|range| range.end <= byte_pos)
|
||||
{
|
||||
_ = break_anywhere_iter.next();
|
||||
}
|
||||
let is_break_anywhere = break_anywhere_iter
|
||||
.peek()
|
||||
.is_some_and(|range| range.contains(&byte_pos));
|
||||
|
||||
let is_mandatory_linebreak = properties.is_mandatory_linebreak();
|
||||
|
||||
// We never have a soft wrap opportunity before a mandatory break (following UAX #14 LB6),
|
||||
// and we never have one right after a mandatory break: the mandatory break is handled
|
||||
// separately.
|
||||
let is_soft_wrap_opportunity = if is_mandatory_linebreak || prev_is_mandatory_linebreak {
|
||||
false
|
||||
} else {
|
||||
let mut opportunity = if is_break_anywhere {
|
||||
// `line-break: anywhere`: an opportunity around every grapheme.
|
||||
prev_char.is_some() && is_grapheme_start
|
||||
} else {
|
||||
is_icu_line || after_break_space
|
||||
};
|
||||
// Consumers can override soft wrap opportunities, except around a mandatory
|
||||
// break.
|
||||
if let (Some(prev), Some(lb_override)) = (prev_char, options.line_break_override) {
|
||||
let forced = lb_override(LineBreakContext {
|
||||
before_before: prev_prev_char,
|
||||
before: prev,
|
||||
after: ch,
|
||||
});
|
||||
if let Some(forced) = forced {
|
||||
opportunity = forced;
|
||||
}
|
||||
}
|
||||
opportunity
|
||||
};
|
||||
|
||||
prev_prev_char = prev_char;
|
||||
prev_char = Some(ch);
|
||||
prev_is_mandatory_linebreak = is_mandatory_linebreak;
|
||||
|
||||
(
|
||||
is_soft_wrap_opportunity,
|
||||
is_word,
|
||||
is_grapheme_start,
|
||||
ch,
|
||||
properties,
|
||||
)
|
||||
});
|
||||
|
||||
let mut needs_bidi_resolution = false;
|
||||
|
||||
analysis.info.reserve(text.len());
|
||||
for (is_soft_wrap_opportunity, is_word, is_grapheme_start, ch, properties) in boundary_iter {
|
||||
let script = properties.script();
|
||||
let grapheme_cluster_break = properties.grapheme_cluster_break();
|
||||
let bidi_class = properties.bidi_class();
|
||||
let general_category = properties.general_category();
|
||||
let is_emoji_or_pictograph = properties.is_emoji_or_pictograph();
|
||||
let is_variation_selector = properties.is_variation_selector();
|
||||
let is_region_indicator = properties.is_region_indicator();
|
||||
|
||||
let force_normalize = {
|
||||
// "Extend" break chars should be normalized first, with two exceptions
|
||||
if matches!(grapheme_cluster_break, GraphemeClusterBreak::Extend) &&
|
||||
ch as u32 != 0x200C && // Is not a Zero Width Non-Joiner &&
|
||||
!is_variation_selector
|
||||
{
|
||||
true
|
||||
} else {
|
||||
// All spacing mark break chars should be normalized first.
|
||||
matches!(grapheme_cluster_break, GraphemeClusterBreak::SpacingMark)
|
||||
}
|
||||
};
|
||||
|
||||
needs_bidi_resolution |= bidi::needs_bidi_resolution(bidi_class);
|
||||
|
||||
analysis.info.push(CharInfo::new(
|
||||
script,
|
||||
is_variation_selector,
|
||||
is_region_indicator,
|
||||
general_category == GeneralCategory::Control,
|
||||
is_emoji_or_pictograph,
|
||||
contributes_to_shaping(general_category, script),
|
||||
force_normalize,
|
||||
is_grapheme_start,
|
||||
is_word,
|
||||
is_soft_wrap_opportunity,
|
||||
properties.is_emoji(),
|
||||
properties.is_emoji_presentation(),
|
||||
properties.is_emoji_modifier(),
|
||||
properties.is_emoji_modifier_base(),
|
||||
));
|
||||
}
|
||||
|
||||
if needs_bidi_resolution || options.base_direction == BaseDirection::Rtl {
|
||||
analyzer.bidi.resolve(
|
||||
text.chars().map(|ch| {
|
||||
let bidi_class = data_sources.properties(ch).bidi_class();
|
||||
// TODO: maybe extend Properties to u64 to fit BidiMirroringGlyph
|
||||
let bracket = data_sources.brackets().get(ch);
|
||||
(ch, (bidi_class, bracket))
|
||||
}),
|
||||
options.base_direction,
|
||||
);
|
||||
core::mem::swap(&mut analysis.levels, &mut analyzer.bidi.levels);
|
||||
analysis.paragraph_level = analyzer.bidi.base_level();
|
||||
}
|
||||
}
|
||||
|
||||
/// All characters contribute to shaping except:
|
||||
/// - Control characters
|
||||
/// - Format characters, unless they use the "Inherited" script
|
||||
#[inline(always)]
|
||||
pub(crate) fn contributes_to_shaping(general_category: GeneralCategory, script: Script) -> bool {
|
||||
if matches!(
|
||||
general_category,
|
||||
GeneralCategory::Control
|
||||
| GeneralCategory::LineSeparator
|
||||
| GeneralCategory::ParagraphSeparator
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
!(general_category == GeneralCategory::Format && script != Script::Inherited)
|
||||
}
|
||||
|
||||
/// Whether ICU4X has a word-segmentation dictionary for this script.
|
||||
///
|
||||
/// If it does not, we need to apply UAX #29 Rule WB999 manually, because ICU4X does not.
|
||||
///
|
||||
/// This is approximate, because ICU4X actually decides based on a table of code point ranges: e.g.,
|
||||
/// some Han characters do not get a dictionary check. That's only a problem if there's a run of
|
||||
/// repeated such characters, which is probably not too likely to be a problem in practice.
|
||||
///
|
||||
/// If ICU4X does implement WB999 in the future, we can stop doing it manually (and this method can
|
||||
/// be removed).
|
||||
#[inline(always)]
|
||||
fn has_word_dictionary(script: Script) -> bool {
|
||||
cfg!(feature = "complex-scripts")
|
||||
&& matches!(
|
||||
script,
|
||||
Script::Han
|
||||
| Script::Hiragana
|
||||
| Script::Thai
|
||||
| Script::Lao
|
||||
| Script::Khmer
|
||||
| Script::Myanmar
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use alloc::vec::Vec;
|
||||
use icu_segmenter::WordSegmenter;
|
||||
use icu_segmenter::options::WordBreakInvariantOptions;
|
||||
|
||||
/// For some characters, determining word boundaries requires a dictionary lookup.
|
||||
///
|
||||
/// Without dictionaries, ICU4X reports such runs as being a single word. But note
|
||||
/// UAX #29 Rule WB999 says that, without a dictionary, there should be word boundaries.
|
||||
///
|
||||
/// We do that patchup ourselves. Once this test starts failing, it's likely ICU4X now follows
|
||||
/// that rule, and we can drop the patchup (the code calling [`super::has_word_dictionary`]).
|
||||
/// Once that's the case, [`parley_data::Properties::needs_dictionary_word_break`] can also be
|
||||
/// dropped.
|
||||
#[test]
|
||||
fn icu4x_word_segmentation_patchup_required() {
|
||||
let segmenter =
|
||||
WordSegmenter::new_for_non_complex_scripts(WordBreakInvariantOptions::default());
|
||||
let breaks: Vec<_> = segmenter.segment_str("中文文本测试").collect();
|
||||
assert_eq!(breaks, &[0, 18]);
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! The analyzer API.
|
||||
|
||||
use core::ops::Range;
|
||||
|
||||
use parlance::{BaseDirection, Language, LineBreak, WordBreak};
|
||||
|
||||
use crate::{bidi::BidiResolver, break_overrides::LineBreakOverrideFn};
|
||||
|
||||
use crate::analysis::{Analysis, analyze_text};
|
||||
|
||||
/// Reusable scratch for [`Analyzer::analyze`].
|
||||
#[derive(Default)]
|
||||
pub struct Analyzer {
|
||||
pub(crate) bidi: BidiResolver,
|
||||
pub(crate) segmenters: crate::analysis::Segmenters,
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for Analyzer {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("Analyzer").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Analyzer {
|
||||
/// Creates a new analyzer.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Analyze `text`, overwriting `analysis`.
|
||||
///
|
||||
/// This reuses the allocations of `analysis`.
|
||||
pub fn analyze(&mut self, text: &str, options: &AnalysisOptions<'_>, analysis: &mut Analysis) {
|
||||
analysis.clear();
|
||||
analyze_text(self, text, options, analysis);
|
||||
}
|
||||
}
|
||||
|
||||
/// Configuration of line break opportunities for a range of text.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub struct LineBreakConfig {
|
||||
/// CSS `word-break`.
|
||||
pub word_break: WordBreak,
|
||||
/// CSS `line-break`.
|
||||
pub line_break: LineBreak,
|
||||
/// The content language.
|
||||
///
|
||||
/// Chinese and Japanese content uses tailored line breaking rules, which for example allow
|
||||
/// breaks before small kana and some punctuation under [`LineBreak::Normal`] and
|
||||
/// [`LineBreak::Loose`].
|
||||
pub language: Option<Language>,
|
||||
}
|
||||
|
||||
/// Options controlling [`Analyzer::analyze`].
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct AnalysisOptions<'a> {
|
||||
/// The paragraph's base direction.
|
||||
///
|
||||
/// Defaults to [`BaseDirection::Auto`], which infers the direction from the text.
|
||||
pub base_direction: BaseDirection,
|
||||
|
||||
/// Line breaking configuration for ranges of the source text.
|
||||
///
|
||||
/// Ranges must be sorted and non-overlapping, and must start and end on character boundaries of
|
||||
/// the text. Empty ranges are ignored. Gaps use [`LineBreakConfig::default`].
|
||||
pub line_break: &'a [(Range<usize>, LineBreakConfig)],
|
||||
|
||||
/// Ranges of the source text in which a soft wrap opportunity follows every space, tab, and
|
||||
/// ideographic space.
|
||||
///
|
||||
/// This implements the additional soft wrap opportunities of
|
||||
/// [CSS's white-space-collapse: break-spaces][css-break-spaces].
|
||||
///
|
||||
/// Outside these ranges, [UAX #14 § 6][uax-14-algorithm] is followed, which defines where soft
|
||||
/// wrap opportunities exist. For example, rules LB7 and LB18 give a sequence of spaces an
|
||||
/// opportunity only at its end. The ranges specified here add an opportunity after every space,
|
||||
/// tab, and ideographic space, except directly before a mandatory break. This overrides the
|
||||
/// "non-tailorable" UAX #14 Rule LB7, and so deviates from Unicode's line breaking algorithm.
|
||||
///
|
||||
/// Ranges must be sorted and non-overlapping, and must start and end on character boundaries
|
||||
/// of the text. Empty ranges are ignored. Gaps apply the default rules.
|
||||
///
|
||||
/// [css-break-spaces]: https://www.w3.org/TR/css-text-4/#valdef-white-space-collapse-break-spaces
|
||||
/// [uax-14-algorithm]: https://unicode.org/reports/tr14/#Algorithm
|
||||
pub break_spaces: &'a [Range<usize>],
|
||||
|
||||
/// The callback which will be called as a first provider of line breaking decisions.
|
||||
///
|
||||
/// See [`LineBreakOverrideFn`] for more details.
|
||||
pub line_break_override: Option<&'a LineBreakOverrideFn>,
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for AnalysisOptions<'_> {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("AnalysisOptions")
|
||||
.field("base_direction", &self.base_direction)
|
||||
.field("line_break", &self.line_break)
|
||||
.field("break_spaces", &self.break_spaces)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use parlance::BidiLevel;
|
||||
|
||||
use super::{AnalysisOptions, Analyzer};
|
||||
use crate::{Analysis, BaseDirection};
|
||||
|
||||
fn analyze(text: &str, base_direction: BaseDirection) -> Analysis {
|
||||
let mut analyzer = Analyzer::new();
|
||||
let mut analysis = Analysis::new();
|
||||
analyzer.analyze(
|
||||
text,
|
||||
&AnalysisOptions {
|
||||
base_direction,
|
||||
..AnalysisOptions::default()
|
||||
},
|
||||
&mut analysis,
|
||||
);
|
||||
analysis
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_rtl_resolves_numeric_and_neutral_text() {
|
||||
let text = "123 / 456";
|
||||
let auto = analyze(text, BaseDirection::Auto);
|
||||
let rtl = analyze(text, BaseDirection::Rtl);
|
||||
|
||||
assert_eq!(auto.paragraph_level(), BidiLevel::new(0));
|
||||
assert!(auto.paragraph_level().is_ltr());
|
||||
assert!(auto.bidi_levels().is_empty());
|
||||
|
||||
assert_eq!(rtl.paragraph_level(), BidiLevel::new(1));
|
||||
assert!(rtl.paragraph_level().is_rtl());
|
||||
assert_eq!(rtl.bidi_levels().len(), text.chars().count());
|
||||
for (ch, level) in text.chars().zip(rtl.bidi_levels()) {
|
||||
if ch.is_ascii_digit() {
|
||||
assert!(level.is_ltr());
|
||||
}
|
||||
}
|
||||
assert!(rtl.bidi_levels().iter().any(|level| level.is_rtl()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_ltr_takes_precedence_over_first_strong_direction() {
|
||||
let text = "مرحبا hello";
|
||||
let auto = analyze(text, BaseDirection::Auto);
|
||||
let ltr = analyze(text, BaseDirection::Ltr);
|
||||
|
||||
assert!(auto.paragraph_level().is_rtl());
|
||||
assert!(ltr.paragraph_level().is_ltr());
|
||||
assert_ne!(auto.bidi_levels(), ltr.bidi_levels());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_rtl_preserves_ltr_run_direction() {
|
||||
let analysis = analyze("hello", BaseDirection::Rtl);
|
||||
|
||||
assert!(analysis.paragraph_level().is_rtl());
|
||||
assert!(analysis.bidi_levels().iter().all(|level| level.is_ltr()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_direction_applies_to_empty_text() {
|
||||
let analysis = analyze("", BaseDirection::Rtl);
|
||||
|
||||
assert!(analysis.paragraph_level().is_rtl());
|
||||
assert!(analysis.bidi_levels().is_empty());
|
||||
}
|
||||
}
|
||||
Vendored
+917
@@ -0,0 +1,917 @@
|
||||
// Copyright 2021 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Unicode bidirectional algorithm.
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use icu_properties::props::{BidiClass, BidiMirroringGlyph, BidiPairedBracketType};
|
||||
use parlance::{BaseDirection, BidiLevel};
|
||||
|
||||
/// Resolver for the Unicode bidirectional algorithm.
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct BidiResolver {
|
||||
base_level: BidiLevel,
|
||||
pub(crate) levels: Vec<BidiLevel>,
|
||||
initial_types: Vec<BidiClass>,
|
||||
types: Vec<BidiClass>,
|
||||
brackets: Vec<(usize, char, BidiMirroringGlyph)>,
|
||||
bracket_pairs: Vec<(usize, usize)>,
|
||||
runs: Vec<Run>,
|
||||
indices: Vec<usize>,
|
||||
flags: u16,
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for BidiResolver {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("BidiResolver")
|
||||
.field("base_level", &self.base_level)
|
||||
.field("levels", &self.levels)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl BidiResolver {
|
||||
/// Returns the base level of the text.
|
||||
pub(crate) fn base_level(&self) -> BidiLevel {
|
||||
self.base_level
|
||||
}
|
||||
|
||||
/// Clears the resolver state.
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.initial_types.clear();
|
||||
self.levels.clear();
|
||||
self.types.clear();
|
||||
self.brackets.clear();
|
||||
self.bracket_pairs.clear();
|
||||
self.flags = 0;
|
||||
self.base_level = BidiLevel::new(0);
|
||||
}
|
||||
|
||||
/// Resolves a paragraph with the specified base direction and
|
||||
/// precomputed types.
|
||||
pub(crate) fn resolve(
|
||||
&mut self,
|
||||
chars: impl Iterator<Item = (char, (BidiClass, BidiMirroringGlyph))>,
|
||||
base_direction: BaseDirection,
|
||||
) {
|
||||
self.clear();
|
||||
let mut needs_bidi = false;
|
||||
let mut len = 0;
|
||||
for (i, (ch, (t, bracket))) in chars.enumerate() {
|
||||
self.initial_types.push(t);
|
||||
|
||||
if bracket.paired_bracket_type != BidiPairedBracketType::None {
|
||||
self.brackets.push((i, ch, bracket));
|
||||
}
|
||||
|
||||
needs_bidi = needs_bidi || mask(t) & BIDI_MASK != 0;
|
||||
len += 1;
|
||||
}
|
||||
self.base_level = match base_direction {
|
||||
BaseDirection::Auto => Self::default_level(&self.initial_types),
|
||||
BaseDirection::Ltr => BidiLevel::new(0),
|
||||
BaseDirection::Rtl => BidiLevel::new(1),
|
||||
};
|
||||
if !needs_bidi && self.base_level == BidiLevel::new(0) {
|
||||
self.flags |= 1;
|
||||
self.levels.resize(len, self.base_level);
|
||||
return;
|
||||
}
|
||||
self.types.extend_from_slice(&self.initial_types);
|
||||
self.resolve_levels();
|
||||
self.resolve_runs();
|
||||
//self.dump_sequences();
|
||||
for i in 0..self.runs.len() {
|
||||
if self.runs[i].in_sequence {
|
||||
continue;
|
||||
}
|
||||
self.types.truncate(len);
|
||||
self.indices.clear();
|
||||
let mut cur = i;
|
||||
let level = self.runs[i].level;
|
||||
let sos = self.runs[i].sos;
|
||||
let mut eos;
|
||||
loop {
|
||||
let run = &self.runs[cur];
|
||||
for i in run.start..run.end {
|
||||
let ty = self.types[i];
|
||||
if !is_removed_by_x9(ty) {
|
||||
self.types.push(ty);
|
||||
self.indices.push(i);
|
||||
}
|
||||
}
|
||||
eos = run.eos;
|
||||
cur = match run.next {
|
||||
Some(i) => i,
|
||||
None => break,
|
||||
};
|
||||
}
|
||||
self.resolve_sequence(level.to_u8(), sos, eos, self.indices.len());
|
||||
}
|
||||
for i in 0..len {
|
||||
let t = self.initial_types[i];
|
||||
if t == BidiClass::SegmentSeparator || t == BidiClass::ParagraphSeparator {
|
||||
self.levels[i] = self.base_level;
|
||||
for j in (0..i).rev() {
|
||||
let t = self.initial_types[j];
|
||||
if is_removed_by_x9(t) {
|
||||
continue;
|
||||
} else if t == BidiClass::WhiteSpace
|
||||
|| is_isolate_initiator(t)
|
||||
|| t == BidiClass::PopDirectionalIsolate
|
||||
{
|
||||
self.levels[j] = self.base_level;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if is_removed_by_x9(t) {
|
||||
if i == 0 {
|
||||
self.levels[i] = self.base_level;
|
||||
} else {
|
||||
self.levels[i] = self.levels[i - 1];
|
||||
}
|
||||
//self.levels[i] = 0xFF;
|
||||
}
|
||||
}
|
||||
for i in (0..len).rev() {
|
||||
let t = self.initial_types[i];
|
||||
if is_removed_by_x9(t) {
|
||||
continue;
|
||||
} else if t == BidiClass::WhiteSpace
|
||||
|| is_isolate_initiator(t)
|
||||
|| t == BidiClass::PopDirectionalIsolate
|
||||
{
|
||||
// UAX #9 L1: whitespace, isolate initiators and PDIs that end the paragraph take
|
||||
// the paragraph's level (Rune: vendor/parley_engine.patch).
|
||||
self.levels[i] = self.base_level;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_level(types: &[BidiClass]) -> BidiLevel {
|
||||
let mut isolates = 0;
|
||||
for ty in types {
|
||||
let ty = *ty;
|
||||
match ty {
|
||||
BidiClass::RightToLeftIsolate
|
||||
| BidiClass::LeftToRightIsolate
|
||||
| BidiClass::FirstStrongIsolate => isolates += 1,
|
||||
BidiClass::PopDirectionalIsolate if isolates > 0 => isolates -= 1,
|
||||
BidiClass::LeftToRight | BidiClass::RightToLeft | BidiClass::ArabicLetter
|
||||
if isolates == 0 =>
|
||||
{
|
||||
return if ty == BidiClass::LeftToRight {
|
||||
BidiLevel::new(0)
|
||||
} else {
|
||||
BidiLevel::new(1)
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
BidiLevel::new(0)
|
||||
}
|
||||
|
||||
fn default_level_until_pdi(types: &[BidiClass]) -> u8 {
|
||||
let mut isolates = 0;
|
||||
for ty in types {
|
||||
let ty = *ty;
|
||||
match ty {
|
||||
BidiClass::RightToLeftIsolate
|
||||
| BidiClass::LeftToRightIsolate
|
||||
| BidiClass::FirstStrongIsolate => isolates += 1,
|
||||
BidiClass::PopDirectionalIsolate => {
|
||||
if isolates > 0 {
|
||||
isolates -= 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
BidiClass::LeftToRight | BidiClass::RightToLeft | BidiClass::ArabicLetter
|
||||
if isolates == 0 =>
|
||||
{
|
||||
return if ty == BidiClass::LeftToRight { 0 } else { 1 };
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
fn resolve_levels(&mut self) {
|
||||
let base = self.base_level;
|
||||
let len = self.types.len();
|
||||
self.levels.clear();
|
||||
self.levels.resize(len, BidiLevel::new(0));
|
||||
let mut stack = Stack::new();
|
||||
let mut overflow_isolates = 0;
|
||||
let mut overflow_embedding = 0;
|
||||
let mut valid_isolates = 0;
|
||||
stack.push(base, BidiClass::OtherNeutral, false);
|
||||
for i in 0..len {
|
||||
let t = self.types[i];
|
||||
let tmask = mask(t);
|
||||
if tmask & EXPLICIT_MASK != 0 {
|
||||
let is_isolate = tmask & ISOLATE_MASK != 0;
|
||||
let is_rtl = if t == BidiClass::FirstStrongIsolate && i + 1 < len {
|
||||
Self::default_level_until_pdi(&self.types[i + 1..]) == 1
|
||||
} else {
|
||||
tmask & RTL_MASK != 0
|
||||
};
|
||||
if is_isolate {
|
||||
self.levels[i] = stack.embedding_level();
|
||||
let os = stack.override_status();
|
||||
if os != BidiClass::OtherNeutral {
|
||||
self.types[i] = os;
|
||||
}
|
||||
}
|
||||
let new_level = if is_rtl {
|
||||
stack.embedding_level().next_odd()
|
||||
} else {
|
||||
stack.embedding_level().next_even()
|
||||
};
|
||||
if new_level <= BidiLevel::MAX && overflow_isolates == 0 && overflow_embedding == 0
|
||||
{
|
||||
if is_isolate {
|
||||
valid_isolates += 1;
|
||||
}
|
||||
stack.push(
|
||||
new_level,
|
||||
if t == BidiClass::LeftToRightOverride {
|
||||
BidiClass::LeftToRight
|
||||
} else if t == BidiClass::RightToLeftOverride {
|
||||
BidiClass::RightToLeft
|
||||
} else {
|
||||
BidiClass::OtherNeutral
|
||||
},
|
||||
is_isolate,
|
||||
);
|
||||
} else if is_isolate {
|
||||
overflow_isolates += 1;
|
||||
} else if overflow_isolates == 0 {
|
||||
overflow_embedding += 1;
|
||||
}
|
||||
} else if t == BidiClass::PopDirectionalIsolate {
|
||||
if overflow_isolates > 0 {
|
||||
overflow_isolates -= 1;
|
||||
} else if valid_isolates == 0 {
|
||||
// empty
|
||||
} else {
|
||||
overflow_embedding = 0;
|
||||
while !stack.isolate_status() {
|
||||
stack.pop();
|
||||
}
|
||||
stack.pop();
|
||||
valid_isolates -= 1;
|
||||
}
|
||||
self.levels[i] = stack.embedding_level();
|
||||
if stack.override_status() != BidiClass::OtherNeutral {
|
||||
self.types[i] = stack.override_status();
|
||||
}
|
||||
} else if t == BidiClass::PopDirectionalFormat {
|
||||
self.levels[i] = stack.embedding_level();
|
||||
if overflow_isolates > 0 {
|
||||
// empty
|
||||
} else if overflow_embedding > 0 {
|
||||
overflow_embedding -= 1;
|
||||
} else if !stack.isolate_status() && stack.depth >= 2 {
|
||||
stack.pop();
|
||||
}
|
||||
} else if t == BidiClass::ParagraphSeparator {
|
||||
stack.depth = 1;
|
||||
overflow_isolates = 0;
|
||||
overflow_embedding = 0;
|
||||
valid_isolates = 0;
|
||||
self.levels[i] = base;
|
||||
} else if t != BidiClass::BoundaryNeutral {
|
||||
self.levels[i] = stack.embedding_level();
|
||||
if stack.override_status() != BidiClass::OtherNeutral {
|
||||
self.types[i] = stack.override_status();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_runs(&mut self) {
|
||||
let len = self.types.len();
|
||||
self.runs.clear();
|
||||
let mut start = 0;
|
||||
while start < len {
|
||||
if !is_removed_by_x9(self.types[start]) {
|
||||
break;
|
||||
}
|
||||
start += 1;
|
||||
}
|
||||
if start == len {
|
||||
return;
|
||||
}
|
||||
let mut level = self.levels[start];
|
||||
let mut offset = 0;
|
||||
for i in start + 1..len {
|
||||
if is_removed_by_x9(self.types[i]) {
|
||||
continue;
|
||||
}
|
||||
if self.levels[i] != level {
|
||||
self.runs.push(Run::new(level, offset, i));
|
||||
offset = i;
|
||||
level = self.levels[i];
|
||||
}
|
||||
}
|
||||
if offset < len {
|
||||
self.runs.push(Run::new(level, offset, len));
|
||||
}
|
||||
for run in &mut self.runs {
|
||||
while run.start < run.end {
|
||||
if is_removed_by_x9(self.types[run.start]) {
|
||||
run.start += 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
while run.end > run.start {
|
||||
if is_removed_by_x9(self.types[run.end - 1]) {
|
||||
run.end -= 1;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if run.start == run.end {
|
||||
continue;
|
||||
}
|
||||
if self.types[run.start] == BidiClass::PopDirectionalIsolate {
|
||||
run.starts_with_pdi = true;
|
||||
}
|
||||
let mut prev_level = self.base_level;
|
||||
for i in (0..run.start).rev() {
|
||||
if !is_removed_by_x9(self.types[i]) {
|
||||
prev_level = self.levels[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
run.sos = type_from_level(prev_level.max(run.level));
|
||||
if is_isolate_initiator(self.initial_types[run.end - 1]) {
|
||||
run.ends_with_isolate = true;
|
||||
run.eos = type_from_level(self.base_level.max(run.level));
|
||||
} else {
|
||||
let mut next_level = self.base_level;
|
||||
for i in run.end..len {
|
||||
if !is_removed_by_x9(self.types[i]) {
|
||||
next_level = self.levels[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
run.eos = type_from_level(next_level.max(run.level));
|
||||
}
|
||||
}
|
||||
for i in 0..self.runs.len() {
|
||||
if self.runs[i].ends_with_isolate {
|
||||
let level = self.runs[i].level;
|
||||
for j in i + 1..self.runs.len() {
|
||||
if self.runs[j].starts_with_pdi && self.runs[j].level == level {
|
||||
self.runs[i].next = Some(j);
|
||||
self.runs[j].in_sequence = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::needless_range_loop, reason = "Deferred")]
|
||||
fn resolve_sequence(&mut self, level: u8, sos: BidiClass, eos: BidiClass, len: usize) {
|
||||
if len == 0 {
|
||||
return;
|
||||
}
|
||||
const W1_MASK: u32 = mask(BidiClass::LeftToRightIsolate)
|
||||
| mask(BidiClass::RightToLeftIsolate)
|
||||
| mask(BidiClass::FirstStrongIsolate)
|
||||
| mask(BidiClass::PopDirectionalIsolate);
|
||||
const W2_MASK: u32 = mask(BidiClass::LeftToRight)
|
||||
| mask(BidiClass::RightToLeft)
|
||||
| mask(BidiClass::ArabicLetter);
|
||||
const W4_MASK: u32 = mask(BidiClass::EuropeanSeparator) | mask(BidiClass::CommonSeparator);
|
||||
let mut prev = sos;
|
||||
let mut prev_strong = prev;
|
||||
let types = &mut self.types[self.initial_types.len()..];
|
||||
for i in 0..len {
|
||||
let mut t = types[i];
|
||||
let tmask = mask(t);
|
||||
if t == BidiClass::NonspacingMark {
|
||||
// W1
|
||||
types[i] = prev;
|
||||
} else {
|
||||
if tmask & W1_MASK != 0 {
|
||||
prev = BidiClass::OtherNeutral;
|
||||
continue;
|
||||
}
|
||||
if t == BidiClass::EuropeanNumber {
|
||||
// W2
|
||||
if prev_strong == BidiClass::ArabicLetter {
|
||||
t = BidiClass::ArabicNumber;
|
||||
types[i] = t;
|
||||
}
|
||||
} else if tmask & W2_MASK != 0 {
|
||||
prev_strong = t;
|
||||
// W3
|
||||
if t == BidiClass::ArabicLetter {
|
||||
t = BidiClass::RightToLeft;
|
||||
types[i] = t;
|
||||
}
|
||||
} else if tmask & W4_MASK != 0 && i < (len - 1) {
|
||||
// W4
|
||||
let mut next = types[i + 1];
|
||||
if next == BidiClass::EuropeanNumber && prev_strong == BidiClass::ArabicLetter {
|
||||
next = BidiClass::ArabicNumber;
|
||||
}
|
||||
if prev == BidiClass::EuropeanNumber && next == BidiClass::EuropeanNumber {
|
||||
t = BidiClass::EuropeanNumber;
|
||||
types[i] = t;
|
||||
} else if t == BidiClass::CommonSeparator
|
||||
&& prev == BidiClass::ArabicNumber
|
||||
&& next == BidiClass::ArabicNumber
|
||||
{
|
||||
t = BidiClass::ArabicNumber;
|
||||
types[i] = t;
|
||||
}
|
||||
}
|
||||
prev = t;
|
||||
}
|
||||
}
|
||||
// W5
|
||||
let mut i = 0;
|
||||
while i < len {
|
||||
if types[i] == BidiClass::EuropeanTerminator {
|
||||
let limit = find_limit(types, i, BidiClass::EuropeanTerminator);
|
||||
let mut t = if i == 0 { sos } else { types[i - 1] };
|
||||
if t != BidiClass::EuropeanNumber {
|
||||
t = if limit == len { eos } else { types[limit] };
|
||||
}
|
||||
if t == BidiClass::EuropeanNumber {
|
||||
for j in i..limit {
|
||||
types[j] = BidiClass::EuropeanNumber;
|
||||
}
|
||||
}
|
||||
i = limit;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
// W6, W7
|
||||
const W6_MASK: u32 = mask(BidiClass::EuropeanSeparator)
|
||||
| mask(BidiClass::EuropeanTerminator)
|
||||
| mask(BidiClass::CommonSeparator);
|
||||
prev_strong = sos;
|
||||
for i in 0..len {
|
||||
let t = types[i];
|
||||
if mask(t) & W6_MASK != 0 {
|
||||
// W6
|
||||
types[i] = BidiClass::OtherNeutral;
|
||||
} else if t == BidiClass::EuropeanNumber {
|
||||
// W7
|
||||
if prev_strong == BidiClass::LeftToRight {
|
||||
types[i] = BidiClass::LeftToRight;
|
||||
}
|
||||
} else if t == BidiClass::LeftToRight || t == BidiClass::RightToLeft {
|
||||
prev_strong = t;
|
||||
}
|
||||
}
|
||||
// N0
|
||||
if !self.brackets.is_empty() {
|
||||
let base_brackets = self.bracket_pairs.len();
|
||||
let mut bracket_stack = BracketStack::new();
|
||||
for i in 0..len {
|
||||
if types[i] != BidiClass::OtherNeutral {
|
||||
continue;
|
||||
}
|
||||
let index = self.indices[i];
|
||||
if let Ok(index) = self.brackets.binary_search_by(|x| x.0.cmp(&index)) {
|
||||
let (_, ch, bracket) = self.brackets[index];
|
||||
match bracket.paired_bracket_type {
|
||||
BidiPairedBracketType::Open => {
|
||||
if bracket_stack.depth == MAX_BRACKET_STACK {
|
||||
break;
|
||||
}
|
||||
bracket_stack.push(i, bracket.mirroring_glyph.unwrap());
|
||||
}
|
||||
BidiPairedBracketType::Close => {
|
||||
if let Some(open) = bracket_stack.find_and_pop(ch) {
|
||||
self.bracket_pairs.push((open, i));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.bracket_pairs.len() > base_brackets {
|
||||
let embed_dir = if level & 1 != 0 {
|
||||
BidiClass::RightToLeft
|
||||
} else {
|
||||
BidiClass::LeftToRight
|
||||
};
|
||||
let bracket_pairs = &mut self.bracket_pairs[base_brackets..];
|
||||
bracket_pairs.sort_unstable_by_key(|a| a.0);
|
||||
for pair in bracket_pairs {
|
||||
let mut pair_dir = BidiClass::OtherNeutral;
|
||||
for i in pair.0 + 1..pair.1 {
|
||||
let dir = match types[i] {
|
||||
BidiClass::EuropeanNumber
|
||||
| BidiClass::ArabicNumber
|
||||
| BidiClass::ArabicLetter
|
||||
| BidiClass::RightToLeft => BidiClass::RightToLeft,
|
||||
BidiClass::LeftToRight => BidiClass::LeftToRight,
|
||||
_ => BidiClass::OtherNeutral,
|
||||
};
|
||||
if dir == BidiClass::OtherNeutral {
|
||||
continue;
|
||||
}
|
||||
pair_dir = dir;
|
||||
if dir == embed_dir {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if pair_dir == BidiClass::OtherNeutral {
|
||||
pair.0 = self.indices[pair.0];
|
||||
pair.1 = self.indices[pair.1];
|
||||
continue;
|
||||
}
|
||||
if pair_dir != embed_dir {
|
||||
pair_dir = sos;
|
||||
for i in (0..pair.0).rev() {
|
||||
let dir = match types[i] {
|
||||
BidiClass::EuropeanNumber
|
||||
| BidiClass::ArabicNumber
|
||||
| BidiClass::ArabicLetter
|
||||
| BidiClass::RightToLeft => BidiClass::RightToLeft,
|
||||
BidiClass::LeftToRight => BidiClass::LeftToRight,
|
||||
_ => BidiClass::OtherNeutral,
|
||||
};
|
||||
if dir != BidiClass::OtherNeutral {
|
||||
pair_dir = dir;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if pair_dir == embed_dir || pair_dir == BidiClass::OtherNeutral {
|
||||
pair_dir = embed_dir;
|
||||
}
|
||||
}
|
||||
types[pair.0] = pair_dir;
|
||||
types[pair.1] = pair_dir;
|
||||
for i in pair.0 + 1..pair.1 {
|
||||
let index = self.indices[i];
|
||||
if self.initial_types[index] == BidiClass::NonspacingMark {
|
||||
types[i] = pair_dir;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for i in pair.1 + 1..len {
|
||||
let index = self.indices[i];
|
||||
if self.initial_types[index] == BidiClass::NonspacingMark {
|
||||
types[i] = pair_dir;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
pair.0 = self.indices[pair.0];
|
||||
pair.1 = self.indices[pair.1];
|
||||
}
|
||||
}
|
||||
}
|
||||
// N1, N2
|
||||
const N_MASK: u32 = mask(BidiClass::ParagraphSeparator)
|
||||
| mask(BidiClass::SegmentSeparator)
|
||||
| mask(BidiClass::WhiteSpace)
|
||||
| mask(BidiClass::OtherNeutral)
|
||||
| mask(BidiClass::RightToLeftIsolate)
|
||||
| mask(BidiClass::LeftToRightIsolate)
|
||||
| mask(BidiClass::FirstStrongIsolate)
|
||||
| mask(BidiClass::PopDirectionalIsolate);
|
||||
let mut i = 0;
|
||||
while i < len {
|
||||
let t = types[i];
|
||||
if mask(t) & N_MASK != 0 {
|
||||
let offset = i;
|
||||
let limit = find_limit_by_mask(types, offset, N_MASK);
|
||||
let mut leading;
|
||||
let mut trailing;
|
||||
if offset == 0 {
|
||||
leading = sos;
|
||||
} else {
|
||||
leading = types[offset - 1];
|
||||
if leading == BidiClass::ArabicNumber || leading == BidiClass::EuropeanNumber {
|
||||
leading = BidiClass::RightToLeft;
|
||||
}
|
||||
}
|
||||
if limit == len {
|
||||
trailing = eos;
|
||||
} else {
|
||||
trailing = types[limit];
|
||||
if trailing == BidiClass::ArabicNumber || trailing == BidiClass::EuropeanNumber
|
||||
{
|
||||
trailing = BidiClass::RightToLeft;
|
||||
}
|
||||
}
|
||||
let resolved = if leading == trailing {
|
||||
// N1
|
||||
leading
|
||||
} else {
|
||||
// N2
|
||||
if level & 1 != 0 {
|
||||
BidiClass::RightToLeft
|
||||
} else {
|
||||
BidiClass::LeftToRight
|
||||
}
|
||||
};
|
||||
for j in offset..limit {
|
||||
types[j] = resolved;
|
||||
}
|
||||
i = limit - 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
// Implicit levels
|
||||
if level & 1 == 0 {
|
||||
// I1
|
||||
for i in 0..len {
|
||||
let index = self.indices[i];
|
||||
let t = types[i];
|
||||
if t == BidiClass::RightToLeft {
|
||||
self.levels[index] = BidiLevel::new(level + 1);
|
||||
} else if t != BidiClass::LeftToRight {
|
||||
self.levels[index] = BidiLevel::new(level + 2);
|
||||
} else {
|
||||
self.levels[index] = BidiLevel::new(level);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// I2
|
||||
for i in 0..len {
|
||||
let index = self.indices[i];
|
||||
let t = types[i];
|
||||
if t != BidiClass::RightToLeft {
|
||||
self.levels[index] = BidiLevel::new(level + 1);
|
||||
} else {
|
||||
self.levels[index] = BidiLevel::new(level);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a default bidi type for a level.
|
||||
pub(crate) fn type_from_level(level: BidiLevel) -> BidiClass {
|
||||
if level.is_ltr() {
|
||||
BidiClass::LeftToRight
|
||||
} else {
|
||||
BidiClass::RightToLeft
|
||||
}
|
||||
}
|
||||
|
||||
/// Computes an ordering for a sequence of bidi runs based on levels.
|
||||
pub(crate) fn _reorder<F>(order: &mut [usize], levels: F)
|
||||
where
|
||||
F: Fn(usize) -> u8,
|
||||
{
|
||||
let mut max_level = 0;
|
||||
let mut lowest_odd_level = 255;
|
||||
for (i, o) in order.iter_mut().enumerate() {
|
||||
*o = i;
|
||||
let level = levels(i);
|
||||
if level > max_level {
|
||||
max_level = level;
|
||||
}
|
||||
if level & 1 != 0 && level < lowest_odd_level {
|
||||
lowest_odd_level = level;
|
||||
}
|
||||
}
|
||||
let len = order.len();
|
||||
for level in (lowest_odd_level..=max_level).rev() {
|
||||
let mut i = 0;
|
||||
while i < len {
|
||||
if levels(i) >= level {
|
||||
let mut end = i + 1;
|
||||
while end < len && levels(end) >= level {
|
||||
end += 1;
|
||||
}
|
||||
let mut j = i;
|
||||
let mut k = end - 1;
|
||||
while j < k {
|
||||
order.swap(j, k);
|
||||
j += 1;
|
||||
k -= 1;
|
||||
}
|
||||
i = end;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether the character needs bidirectional resolution.
|
||||
#[inline(always)]
|
||||
pub(crate) fn needs_bidi_resolution(bidi_class: BidiClass) -> bool {
|
||||
mask(bidi_class) & BIDI_MASK != 0
|
||||
}
|
||||
|
||||
const OVERRIDE_MASK: u32 = mask(BidiClass::RightToLeftEmbedding)
|
||||
| mask(BidiClass::LeftToRightEmbedding)
|
||||
| mask(BidiClass::RightToLeftOverride)
|
||||
| mask(BidiClass::LeftToRightOverride);
|
||||
const ISOLATE_MASK: u32 = mask(BidiClass::RightToLeftIsolate)
|
||||
| mask(BidiClass::LeftToRightIsolate)
|
||||
| mask(BidiClass::FirstStrongIsolate);
|
||||
const EXPLICIT_MASK: u32 = OVERRIDE_MASK | ISOLATE_MASK;
|
||||
const RTL_MASK: u32 = mask(BidiClass::RightToLeftEmbedding)
|
||||
| mask(BidiClass::RightToLeftOverride)
|
||||
| mask(BidiClass::RightToLeftIsolate);
|
||||
const REMOVED_BY_X9_MASK: u32 =
|
||||
OVERRIDE_MASK | mask(BidiClass::PopDirectionalFormat) | mask(BidiClass::BoundaryNeutral);
|
||||
const BIDI_MASK: u32 = EXPLICIT_MASK
|
||||
| mask(BidiClass::RightToLeft)
|
||||
| mask(BidiClass::ArabicLetter)
|
||||
| mask(BidiClass::ArabicNumber);
|
||||
const _RESET_MASK: u32 =
|
||||
ISOLATE_MASK | mask(BidiClass::PopDirectionalIsolate) | mask(BidiClass::WhiteSpace);
|
||||
|
||||
fn is_isolate_initiator(ty: BidiClass) -> bool {
|
||||
mask(ty) & ISOLATE_MASK != 0
|
||||
}
|
||||
|
||||
pub(crate) fn is_removed_by_x9(ty: BidiClass) -> bool {
|
||||
mask(ty) & REMOVED_BY_X9_MASK != 0
|
||||
}
|
||||
|
||||
pub(crate) fn _is_reset(ty: BidiClass) -> bool {
|
||||
mask(ty) & _RESET_MASK != 0
|
||||
}
|
||||
|
||||
fn find_limit(types: &[BidiClass], offset: usize, ty: BidiClass) -> usize {
|
||||
let mut len = offset;
|
||||
for &t in &types[offset..] {
|
||||
if t != ty {
|
||||
break;
|
||||
}
|
||||
len += 1;
|
||||
}
|
||||
len
|
||||
}
|
||||
|
||||
fn find_limit_by_mask(types: &[BidiClass], offset: usize, mask: u32) -> usize {
|
||||
let mut len = offset;
|
||||
for &t in &types[offset..] {
|
||||
if self::mask(t) & mask == 0 {
|
||||
break;
|
||||
}
|
||||
len += 1;
|
||||
}
|
||||
len
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Run {
|
||||
level: BidiLevel,
|
||||
ends_with_isolate: bool,
|
||||
starts_with_pdi: bool,
|
||||
sos: BidiClass,
|
||||
eos: BidiClass,
|
||||
start: usize,
|
||||
end: usize,
|
||||
in_sequence: bool,
|
||||
next: Option<usize>,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
fn new(level: BidiLevel, start: usize, end: usize) -> Self {
|
||||
Self {
|
||||
level,
|
||||
ends_with_isolate: false,
|
||||
starts_with_pdi: false,
|
||||
sos: BidiClass::OtherNeutral,
|
||||
eos: BidiClass::OtherNeutral,
|
||||
start,
|
||||
end,
|
||||
in_sequence: false,
|
||||
next: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_STACK: usize = BidiLevel::MAX.to_u8() as usize;
|
||||
|
||||
struct Stack {
|
||||
embedding_level: [BidiLevel; MAX_STACK + 1],
|
||||
override_status: [BidiClass; MAX_STACK + 1],
|
||||
isolate_status: [bool; MAX_STACK + 1],
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
impl Stack {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
depth: 0,
|
||||
embedding_level: [BidiLevel::new(0); MAX_STACK + 1],
|
||||
override_status: [BidiClass::OtherNeutral; MAX_STACK + 1],
|
||||
isolate_status: [false; MAX_STACK + 1],
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, level: BidiLevel, override_status: BidiClass, isolate_status: bool) {
|
||||
let d = self.depth;
|
||||
self.embedding_level[d] = level;
|
||||
self.override_status[d] = override_status;
|
||||
self.isolate_status[d] = isolate_status;
|
||||
self.depth += 1;
|
||||
}
|
||||
|
||||
fn pop(&mut self) {
|
||||
if self.depth > 1 {
|
||||
self.depth -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn embedding_level(&self) -> BidiLevel {
|
||||
self.embedding_level[self.depth - 1]
|
||||
}
|
||||
|
||||
fn override_status(&self) -> BidiClass {
|
||||
self.override_status[self.depth - 1]
|
||||
}
|
||||
|
||||
fn isolate_status(&self) -> bool {
|
||||
self.isolate_status[self.depth - 1]
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_BRACKET_STACK: usize = 63;
|
||||
|
||||
struct BracketStack {
|
||||
openers: [(usize, char); MAX_BRACKET_STACK],
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
impl BracketStack {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
openers: [(0, '\0'); MAX_BRACKET_STACK],
|
||||
depth: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, offset: usize, closer: char) {
|
||||
self.openers[self.depth] = (offset, closer);
|
||||
self.depth += 1;
|
||||
}
|
||||
|
||||
fn find_and_pop(&mut self, closer: char) -> Option<usize> {
|
||||
if self.depth == 0 {
|
||||
return None;
|
||||
}
|
||||
for i in (0..self.depth).rev() {
|
||||
let c = self.openers[i].1;
|
||||
if c == closer
|
||||
|| (c == '\u{232A}' && closer == '\u{3009}')
|
||||
|| (c == '\u{3009}' && closer == '\u{232A}')
|
||||
{
|
||||
self.depth = i;
|
||||
return Some(self.openers[i].0);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns a bidi class into a single bit, for cheap set membership testing.
|
||||
const fn mask(t: BidiClass) -> u32 {
|
||||
let bit = match t {
|
||||
BidiClass::LeftToRight => 0,
|
||||
BidiClass::RightToLeft => 1,
|
||||
BidiClass::EuropeanNumber => 2,
|
||||
BidiClass::EuropeanSeparator => 3,
|
||||
BidiClass::EuropeanTerminator => 4,
|
||||
BidiClass::ArabicNumber => 5,
|
||||
BidiClass::CommonSeparator => 6,
|
||||
BidiClass::ParagraphSeparator => 7,
|
||||
BidiClass::SegmentSeparator => 8,
|
||||
BidiClass::WhiteSpace => 9,
|
||||
BidiClass::OtherNeutral => 10,
|
||||
BidiClass::LeftToRightEmbedding => 11,
|
||||
BidiClass::LeftToRightOverride => 12,
|
||||
BidiClass::ArabicLetter => 13,
|
||||
BidiClass::RightToLeftEmbedding => 14,
|
||||
BidiClass::RightToLeftOverride => 15,
|
||||
BidiClass::PopDirectionalFormat => 16,
|
||||
BidiClass::NonspacingMark => 17,
|
||||
BidiClass::BoundaryNeutral => 18,
|
||||
BidiClass::FirstStrongIsolate => 19,
|
||||
BidiClass::LeftToRightIsolate => 20,
|
||||
BidiClass::RightToLeftIsolate => 21,
|
||||
BidiClass::PopDirectionalIsolate => 22,
|
||||
_ => {
|
||||
debug_assert!(false, "unhandled Bidi_Class");
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
1 << bit
|
||||
}
|
||||
+436
@@ -0,0 +1,436 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Overrides for line-break opportunities.
|
||||
|
||||
use core::ops::RangeInclusive;
|
||||
|
||||
/// Context for a potential line break opportunity between two adjacent code points.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct LineBreakContext {
|
||||
/// The code point before the `before` code point, if any.
|
||||
pub before_before: Option<char>,
|
||||
/// The code point before the potential break.
|
||||
pub before: char,
|
||||
/// The code point after the potential break.
|
||||
pub after: char,
|
||||
}
|
||||
|
||||
/// Line break opportunity override.
|
||||
///
|
||||
/// Called for each adjacent pair of Unicode code points in the text, in order, except for pairs
|
||||
/// containing a mandatory break character. The [`LineBreakContext`] describes the potential break.
|
||||
///
|
||||
/// Returning:
|
||||
/// - `Some(true)` : forces a line break opportunity between the pair
|
||||
/// - `Some(false)` : suppresses any opportunity
|
||||
/// - `None` : defers to the default (ICU) behavior
|
||||
///
|
||||
/// Note that pairs with a mandatory break aren't soft wrap opportunities. Mandatory breaks are
|
||||
/// reported as [`Whitespace`][crate::shape::Whitespace].
|
||||
///
|
||||
/// This is typically used to force preferential line breaking decisions when it
|
||||
/// comes to ASCII punctuation like `/`, `-`, etc. For example, to prevent break
|
||||
/// opportunities within "1/2".
|
||||
///
|
||||
/// A separate use case is to match the line breaking behavior of existing systems
|
||||
/// such as web browsers. See [`CHROMIUM_LINE_BREAK_OVERRIDE`] for a ready-made
|
||||
/// override function that mirrors Chromium's behavior.
|
||||
pub type LineBreakOverrideFn = dyn Fn(LineBreakContext) -> Option<bool> + Send + Sync;
|
||||
|
||||
/// A line break override function mirroring Chromium's preferred line breaking behavior.
|
||||
///
|
||||
/// See: <https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/text/character_property_data_generator.cc;l=449-495>
|
||||
///
|
||||
/// # Differences from other browsers
|
||||
///
|
||||
/// ## Compared to Safari
|
||||
///
|
||||
/// Chromium (and this table) differs from Safari in 9 cases:
|
||||
/// - A "-" followed by one of "!|$|)|/|:|;|?|]|}" is suppressed in Chromium, but broken in Safari.
|
||||
///
|
||||
/// ## Compared to Firefox
|
||||
///
|
||||
/// Firefox always defers to the default ICU behavior.
|
||||
pub static CHROMIUM_LINE_BREAK_OVERRIDE: &LineBreakOverrideFn =
|
||||
&(chromium_override as fn(LineBreakContext) -> Option<bool>);
|
||||
|
||||
fn chromium_override(cx: LineBreakContext) -> Option<bool> {
|
||||
let LineBreakContext {
|
||||
before_before,
|
||||
before,
|
||||
after,
|
||||
..
|
||||
} = cx;
|
||||
// CSS "does not fully define where soft wrap opportunities occur".
|
||||
// (https://www.w3.org/TR/css-text-3/#line-breaking)
|
||||
// We find that Chrome always treats the position after a space sequence
|
||||
// as a line break opportunity, despite this not matching UAX-14
|
||||
// (see LB13: https://www.unicode.org/reports/tr14/#LB13; we're not currently
|
||||
// aware of any others).
|
||||
//
|
||||
// See also https://github.com/linebender/parley/pull/485, and https://github.com/linebender/parley/issues/619.
|
||||
//
|
||||
// See `LazyLineBreakIterator::NextBreakablePosition`
|
||||
// <https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/text/text_break_iterator.cc;l=282-303>
|
||||
if before == ' ' && after != ' ' {
|
||||
return Some(true);
|
||||
}
|
||||
// Before consulting 'before' / 'after' pair table, check for the special "-" case.
|
||||
//
|
||||
// Chromium doesn't allow breaking when it looks like the minus sign is for a negative
|
||||
// number like "Subtract -5 from X". But, Chromium does allow breaking when the minus
|
||||
// sign is part of a long URL like "AAAA-2222".
|
||||
//
|
||||
// See <https://github.com/chromium/chromium/blob/c6bee15e8f336c8feabf539d8bbb540c134ec20a/third_party/blink/renderer/platform/text/text_break_iterator.cc#L224-L240>
|
||||
if before == '-' && after.is_ascii_digit() {
|
||||
return Some(before_before.is_some_and(|c| c.is_ascii_alphanumeric()));
|
||||
}
|
||||
CHROMIUM_LINE_BREAK_TABLE.lookup(before, after)
|
||||
}
|
||||
|
||||
/// A static table mirroring Chromium's preferred line breaking behavior for `before` / `after`
|
||||
/// printable ASCII code points.
|
||||
static CHROMIUM_LINE_BREAK_TABLE: AsciiLineBreakTable<5> =
|
||||
AsciiLineBreakTableBuilder::chromium().build::<5>();
|
||||
|
||||
/// A line break override table for ASCII character pairs.
|
||||
///
|
||||
/// See [`LineBreakOverrideFn`] for more details.
|
||||
///
|
||||
/// All table operations are `const`, which means that derived tables don't
|
||||
/// need a runtime construction step.
|
||||
///
|
||||
/// The table is row-deduplicated. Each `before` character maps to
|
||||
/// one of `N` distinct rows, so tables can be kept tiny.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # use parley_engine::break_overrides::CHROMIUM_LINE_BREAK_OVERRIDE;
|
||||
/// # use parley_engine::{Analysis, AnalysisOptions, Analyzer};
|
||||
/// # let mut analyzer = Analyzer::new();
|
||||
/// # let mut analysis = Analysis::new();
|
||||
/// let text = "Hello there!";
|
||||
/// let options = AnalysisOptions {
|
||||
/// // Emulate Chromium:
|
||||
/// line_break_override: Some(CHROMIUM_LINE_BREAK_OVERRIDE),
|
||||
/// ..AnalysisOptions::default()
|
||||
/// };
|
||||
/// analyzer.analyze(text, &options, &mut analysis);
|
||||
/// ```
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AsciiLineBreakTable<const N: usize> {
|
||||
/// Maps each `before` character (`0..128`) to a row in `rows`.
|
||||
row_of: [u8; 128],
|
||||
/// The distinct rows.
|
||||
rows: [Row; N],
|
||||
}
|
||||
|
||||
impl<const N: usize> AsciiLineBreakTable<N> {
|
||||
/// Look up the break override for a `(before, after)` pair.
|
||||
///
|
||||
/// Return semantics copied from [`LineBreakOverrideFn`].
|
||||
pub const fn lookup(&self, before: char, after: char) -> Option<bool> {
|
||||
let (b, a) = (before as u32, after as u32);
|
||||
if b >= 128 || a >= 128 {
|
||||
return None;
|
||||
}
|
||||
let row = &self.rows[self.row_of[b as usize] as usize];
|
||||
if row.overridden & (1_u128 << a) == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(row.allow & (1_u128 << a) != 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// A single deduplicated row of a [`AsciiLineBreakTable`].
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Row {
|
||||
/// Bits set means the pair has an override.
|
||||
overridden: u128,
|
||||
/// Bits set means a break is allowed.
|
||||
allow: u128,
|
||||
}
|
||||
|
||||
/// A builder for an [`AsciiLineBreakTable`].
|
||||
///
|
||||
/// Construction is `const`. We create a dense `128 x 128` grid of overrides,
|
||||
/// then compress it into a row-deduplicated table via [`AsciiLineBreakTableBuilder::build`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AsciiLineBreakTableBuilder {
|
||||
/// Bit `after` set in row `before` means the pair has an explicit override.
|
||||
overridden: [u128; 128],
|
||||
/// Bit `after` set in row `before` means a break is allowed for that pair.
|
||||
allow: [u128; 128],
|
||||
}
|
||||
|
||||
impl AsciiLineBreakTableBuilder {
|
||||
/// A builder that defers every pair to the default ICU behavior.
|
||||
pub const fn new() -> Self {
|
||||
Self {
|
||||
overridden: [0; 128],
|
||||
allow: [0; 128],
|
||||
}
|
||||
}
|
||||
|
||||
/// Override every pair in the cartesian product of the two inclusive ASCII
|
||||
/// ranges.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// All range bounds must be printable ASCII (`<= '\u{7f}'`).
|
||||
pub const fn with_pairs(
|
||||
mut self,
|
||||
before: RangeInclusive<char>,
|
||||
after: RangeInclusive<char>,
|
||||
allow_break: bool,
|
||||
) -> Self {
|
||||
assert!(
|
||||
*before.end() as u32 <= 0x7f && *after.end() as u32 <= 0x7f,
|
||||
"only printable ASCII is supported",
|
||||
);
|
||||
let mut before_pos = *before.start() as u32;
|
||||
while before_pos <= *before.end() as u32 {
|
||||
let mut after_pos = *after.start() as u32;
|
||||
while after_pos <= *after.end() as u32 {
|
||||
let bit = 1_u128 << after_pos;
|
||||
self.overridden[before_pos as usize] |= bit;
|
||||
if allow_break {
|
||||
self.allow[before_pos as usize] |= bit;
|
||||
} else {
|
||||
self.allow[before_pos as usize] &= !bit;
|
||||
}
|
||||
after_pos += 1;
|
||||
}
|
||||
before_pos += 1;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Compress the dense grid into a row-deduplicated [`AsciiLineBreakTable`]
|
||||
/// with at most `N` distinct rows.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `N` does not exactly match the number of distinct rows required.
|
||||
pub const fn build<const N: usize>(&self) -> AsciiLineBreakTable<N> {
|
||||
// Row 0 is reserved as the "defer everything" row.
|
||||
let mut rows = [Row {
|
||||
overridden: 0,
|
||||
allow: 0,
|
||||
}; N];
|
||||
let mut len = 1_usize;
|
||||
let mut row_of = [0_u8; 128];
|
||||
|
||||
let mut b = 0;
|
||||
while b < 128 {
|
||||
let (ov, al) = (self.overridden[b], self.allow[b]);
|
||||
let mut idx = 0;
|
||||
let mut found = usize::MAX;
|
||||
while idx < len {
|
||||
if rows[idx].overridden == ov && rows[idx].allow == al {
|
||||
found = idx;
|
||||
break;
|
||||
}
|
||||
idx += 1;
|
||||
}
|
||||
let r = if found != usize::MAX {
|
||||
found
|
||||
} else {
|
||||
assert!(
|
||||
len < N,
|
||||
"N is too small to contain table. Repeat with a larger N."
|
||||
);
|
||||
rows[len] = Row {
|
||||
overridden: ov,
|
||||
allow: al,
|
||||
};
|
||||
len += 1;
|
||||
len - 1
|
||||
};
|
||||
#[expect(
|
||||
clippy::cast_possible_truncation,
|
||||
reason = "TODO: fix this (`N` should be `u8`, or `row_of` should contain `usize`)"
|
||||
)]
|
||||
{
|
||||
row_of[b] = r as u8;
|
||||
}
|
||||
b += 1;
|
||||
}
|
||||
|
||||
assert!(
|
||||
len == N,
|
||||
"N is larger than required. Repeat with a smaller N."
|
||||
);
|
||||
|
||||
AsciiLineBreakTable { row_of, rows }
|
||||
}
|
||||
|
||||
/// See [`CHROMIUM_LINE_BREAK_TABLE`] for more details.
|
||||
const fn chromium() -> Self {
|
||||
// The printable ASCII range `'!'..=0x7F`.
|
||||
const ALL: RangeInclusive<char> = '!'..='\u{7f}';
|
||||
|
||||
Self::new()
|
||||
.with_pairs(ALL, ALL, false)
|
||||
.with_pairs(ALL, '('..='(', true)
|
||||
.with_pairs(ALL, '<'..='<', true)
|
||||
.with_pairs(ALL, '['..='[', true)
|
||||
.with_pairs(ALL, '{'..='{', true)
|
||||
.with_pairs('-'..='-', ALL, true)
|
||||
.with_pairs('?'..='?', ALL, true)
|
||||
.with_pairs('-'..='-', '$'..='$', false)
|
||||
.with_pairs(ALL, '!'..='!', false)
|
||||
.with_pairs('?'..='?', '"'..='"', false)
|
||||
.with_pairs('?'..='?', '\''..='\'', false)
|
||||
.with_pairs(ALL, ')'..=')', false)
|
||||
.with_pairs(ALL, ','..=',', false)
|
||||
.with_pairs(ALL, '.'..='.', false)
|
||||
.with_pairs(ALL, '/'..='/', false)
|
||||
.with_pairs('-'..='-', '0'..='9', false)
|
||||
.with_pairs(ALL, ':'..=':', false)
|
||||
.with_pairs(ALL, ';'..=';', false)
|
||||
.with_pairs(ALL, '?'..='?', false)
|
||||
.with_pairs(ALL, ']'..=']', false)
|
||||
.with_pairs(ALL, '}'..='}', false)
|
||||
.with_pairs('$'..='$', ALL, false)
|
||||
.with_pairs('\''..='\'', ALL, false)
|
||||
.with_pairs('('..='(', ALL, false)
|
||||
.with_pairs('/'..='/', ALL, false)
|
||||
.with_pairs('0'..='9', ALL, false)
|
||||
.with_pairs('<'..='<', ALL, false)
|
||||
.with_pairs('@'..='@', ALL, false)
|
||||
.with_pairs('A'..='Z', ALL, false)
|
||||
.with_pairs('['..='[', ALL, false)
|
||||
.with_pairs('^'..='`', ALL, false)
|
||||
.with_pairs('a'..='z', ALL, false)
|
||||
.with_pairs('{'..='{', ALL, false)
|
||||
.with_pairs('\u{7f}'..='\u{7f}', ALL, false)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AsciiLineBreakTableBuilder {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::AsciiLineBreakTableBuilder;
|
||||
use super::CHROMIUM_LINE_BREAK_TABLE;
|
||||
use super::LineBreakContext;
|
||||
use super::chromium_override;
|
||||
|
||||
fn cx(before_before: Option<char>, before: char, after: char) -> LineBreakContext {
|
||||
LineBreakContext {
|
||||
before_before,
|
||||
before,
|
||||
after,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chromium_hyphen_digit_depends_on_preceding_char() {
|
||||
// A break between '-' and a digit is allowed only when the character
|
||||
// preceding the '-' is ASCII alphanumeric.
|
||||
assert_eq!(chromium_override(cx(Some('D'), '-', '1')), Some(true));
|
||||
assert_eq!(chromium_override(cx(Some('4'), '-', '5')), Some(true));
|
||||
// Otherwise the '-' may be a minus sign, so the break is suppressed.
|
||||
assert_eq!(chromium_override(cx(Some(' '), '-', '1')), Some(false));
|
||||
assert_eq!(chromium_override(cx(Some('('), '-', '1')), Some(false));
|
||||
// No preceding character (start of text) behaves like a non-alphanumeric
|
||||
// context, matching Chromium's `last_last_ch == 0`.
|
||||
assert_eq!(chromium_override(cx(None, '-', '1')), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chromium_ignores_uax_14_lb13() {
|
||||
// Blink allows a break after a space run unconditionally.
|
||||
// See comment in non-test code for more details.
|
||||
for after in ['}', ')', ']', '!', '.', ',', '/', ':', ';', '?', 'b', '('] {
|
||||
assert_eq!(
|
||||
chromium_override(cx(None, ' ', after)),
|
||||
Some(true),
|
||||
"expected a break after the space, before {after:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chromium_hyphen_non_digit_defers_to_table() {
|
||||
// '-' followed by a non-digit ignores `before_before` and uses the table.
|
||||
assert_eq!(chromium_override(cx(Some('D'), '-', 'b')), Some(true));
|
||||
assert_eq!(chromium_override(cx(None, '-', 'b')), Some(true));
|
||||
// Non-ASCII after '-' defers to ICU.
|
||||
assert_eq!(chromium_override(cx(Some('D'), '-', 'é')), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chromium_suppresses_ascii_punctuation_breaks() {
|
||||
let t = &CHROMIUM_LINE_BREAK_TABLE;
|
||||
// No break before or after a slash.
|
||||
assert_eq!(t.lookup('a', '/'), Some(false));
|
||||
assert_eq!(t.lookup('/', 'b'), Some(false));
|
||||
// No break around other punctuation.
|
||||
assert_eq!(t.lookup('a', '.'), Some(false));
|
||||
assert_eq!(t.lookup('a', ':'), Some(false));
|
||||
// No break between letters.
|
||||
assert_eq!(t.lookup('a', 'b'), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chromium_allows_some_breaks() {
|
||||
let t = &CHROMIUM_LINE_BREAK_TABLE;
|
||||
// Break allowed before opening punctuation, but only when the preceding
|
||||
// character's row was not later suppressed.
|
||||
assert_eq!(t.lookup(')', '('), Some(true));
|
||||
assert_eq!(t.lookup(')', '<'), Some(true));
|
||||
assert_eq!(t.lookup('a', '('), Some(false));
|
||||
// Break allowed after '-' and '?' except when...
|
||||
assert_eq!(t.lookup('-', 'b'), Some(true));
|
||||
assert_eq!(t.lookup('?', 'b'), Some(true));
|
||||
// ...break not allowed after '-' before a digit, or '?' before a quote.
|
||||
assert_eq!(t.lookup('-', '5'), Some(false));
|
||||
assert_eq!(t.lookup('?', '"'), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_ascii_pairs_defer_to_icu() {
|
||||
let t = &CHROMIUM_LINE_BREAK_TABLE;
|
||||
assert_eq!(t.lookup('a', 'é'), None);
|
||||
assert_eq!(t.lookup('é', 'a'), None);
|
||||
// Space (0x20) is below the printable range, so it defers too.
|
||||
assert_eq!(t.lookup('a', ' '), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_table_defers_to_icu() {
|
||||
let t = AsciiLineBreakTableBuilder::new().build::<1>();
|
||||
assert_eq!(t.lookup('a', '/'), None);
|
||||
assert_eq!(t.lookup('a', '('), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dedup_matches_dense_for_chromium() {
|
||||
let builder = AsciiLineBreakTableBuilder::chromium();
|
||||
for b in 0..128_u32 {
|
||||
for a in 0..128_u32 {
|
||||
let bit = 1_u128 << a;
|
||||
let dense = if builder.overridden[b as usize] & bit == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(builder.allow[b as usize] & bit != 0)
|
||||
};
|
||||
let (before, after) = (char::from_u32(b).unwrap(), char::from_u32(a).unwrap());
|
||||
assert_eq!(
|
||||
CHROMIUM_LINE_BREAK_TABLE.lookup(before, after),
|
||||
dense,
|
||||
"mismatch at (before={b:#04x}, after={a:#04x})",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Word boundaries for the scripts whose words need a dictionary (Thai, Lao, Khmer, Burmese,
|
||||
//! Chinese and Japanese), from outside Parley (Rune: vendor/parley_engine.patch). A build without
|
||||
//! `complex-scripts` links none of ICU's dictionaries; a host that has its own (a browser's
|
||||
//! `Intl.Segmenter`) gives them here. Its boundaries are the words inside each such run and, in
|
||||
//! Thai, Lao, Khmer and Burmese, the run's line break opportunities too, as ICU's dictionary
|
||||
//! line segmenter makes them (UAX #14 breaks class SA at word boundaries).
|
||||
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use icu_properties::props::{GeneralCategory, Script};
|
||||
use parley_data::Properties;
|
||||
|
||||
/// Appends to `out` the word boundaries strictly inside `text`, as ascending byte offsets, for a
|
||||
/// `text` all in one dictionary language: `language` is `th`, `lo`, `km`, `my` or `ja` (Han,
|
||||
/// hiragana and katakana, whose dictionary Chinese and Japanese share).
|
||||
pub type DictionarySegmenter = fn(text: &str, language: &str, out: &mut Vec<usize>);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
static SEGMENTER: std::sync::OnceLock<DictionarySegmenter> = std::sync::OnceLock::new();
|
||||
|
||||
/// Gives Parley the host's dictionary word boundaries, once (a second call changes nothing).
|
||||
/// Without `complex-scripts` and without this, a Thai phrase has no break opportunity and a
|
||||
/// Chinese sentence's words are its characters. Needs `std`.
|
||||
pub fn set_dictionary_segmenter(segmenter: DictionarySegmenter) {
|
||||
#[cfg(feature = "std")]
|
||||
let _ = SEGMENTER.set(segmenter);
|
||||
#[cfg(not(feature = "std"))]
|
||||
let _ = segmenter;
|
||||
}
|
||||
|
||||
fn segmenter() -> Option<DictionarySegmenter> {
|
||||
#[cfg(all(feature = "std", not(feature = "complex-scripts")))]
|
||||
return SEGMENTER.get().copied();
|
||||
#[cfg(not(all(feature = "std", not(feature = "complex-scripts"))))]
|
||||
None
|
||||
}
|
||||
|
||||
/// The dictionary language a character's script asks for, and whether its words are its line
|
||||
/// break opportunities (class SA).
|
||||
fn language(script: Script) -> Option<(&'static str, bool)> {
|
||||
Some(match script {
|
||||
Script::Thai => ("th", true),
|
||||
Script::Lao => ("lo", true),
|
||||
Script::Khmer => ("km", true),
|
||||
Script::Myanmar => ("my", true),
|
||||
Script::Han | Script::Hiragana | Script::Katakana => ("ja", false),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// A mark, a joiner or a length mark (ー) carries on the run before it.
|
||||
fn continues(properties: Properties, ch: char) -> bool {
|
||||
matches!(properties.script(), Script::Inherited)
|
||||
|| matches!(
|
||||
properties.general_category(),
|
||||
GeneralCategory::NonspacingMark | GeneralCategory::SpacingMark | GeneralCategory::EnclosingMark
|
||||
)
|
||||
|| matches!(ch, '\u{200C}' | '\u{200D}' | '\u{30FC}')
|
||||
}
|
||||
|
||||
/// The text's dictionary runs and the host's word boundaries inside them.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Words {
|
||||
/// `(start, end, sa)` byte ranges, ascending.
|
||||
runs: Vec<(usize, usize, bool)>,
|
||||
/// Boundaries strictly inside the runs, ascending.
|
||||
bounds: Vec<usize>,
|
||||
run: usize,
|
||||
bound: usize,
|
||||
}
|
||||
|
||||
impl Words {
|
||||
pub(crate) fn of(text: &str, properties: impl Fn(char) -> Properties) -> Self {
|
||||
let Some(segment) = segmenter() else { return Self::default() };
|
||||
let mut words = Self::default();
|
||||
let mut open: Option<(usize, &'static str, bool)> = None;
|
||||
let close = |words: &mut Self, start: usize, end: usize, lang: &'static str, sa: bool| {
|
||||
let run = &text[start..end];
|
||||
// A single character has no boundary inside it.
|
||||
if run.chars().nth(1).is_none() {
|
||||
return;
|
||||
}
|
||||
let mut found = Vec::new();
|
||||
segment(run, lang, &mut found);
|
||||
words.bounds.extend(found.into_iter().filter(|&b| b > 0 && b < run.len() && run.is_char_boundary(b)).map(|b| b + start));
|
||||
words.runs.push((start, end, sa));
|
||||
};
|
||||
for (at, ch) in text.char_indices() {
|
||||
let props = properties(ch);
|
||||
if let Some((start, lang, sa)) = open {
|
||||
if continues(props, ch) || language(props.script()).is_some_and(|(l, _)| l == lang) {
|
||||
continue;
|
||||
}
|
||||
close(&mut words, start, at, lang, sa);
|
||||
}
|
||||
open = language(props.script()).map(|(lang, sa)| (at, lang, sa));
|
||||
}
|
||||
if let Some((start, lang, sa)) = open {
|
||||
close(&mut words, start, text.len(), lang, sa);
|
||||
}
|
||||
words
|
||||
}
|
||||
|
||||
/// The boundaries inside Thai, Lao, Khmer and Burmese runs: their line break opportunities.
|
||||
/// None with `line-dictionaries`, whose line segmenter finds them itself.
|
||||
pub(crate) fn line_breaks(&self) -> impl Iterator<Item = usize> + '_ {
|
||||
let mut run = if cfg!(feature = "line-dictionaries") { self.runs.len() } else { 0 };
|
||||
self.bounds.iter().copied().filter(move |&b| {
|
||||
while self.runs.get(run).is_some_and(|r| r.1 <= b) {
|
||||
run += 1;
|
||||
}
|
||||
self.runs.get(run).is_some_and(|r| r.0 < b && r.2)
|
||||
})
|
||||
}
|
||||
|
||||
/// Inside a run (past its first character), whether `at` is a word boundary; `None` outside
|
||||
/// one, where the rule-based segmenter decides. Asked in ascending order.
|
||||
pub(crate) fn word_at(&mut self, at: usize) -> Option<bool> {
|
||||
while self.runs.get(self.run).is_some_and(|r| r.1 <= at) {
|
||||
self.run += 1;
|
||||
}
|
||||
let run = self.runs.get(self.run)?;
|
||||
if at <= run.0 {
|
||||
return None;
|
||||
}
|
||||
while self.bounds.get(self.bound).is_some_and(|&b| b < at) {
|
||||
self.bound += 1;
|
||||
}
|
||||
Some(self.bounds.get(self.bound) == Some(&at))
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
// Copyright 2025 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
/// Glyph with an offset and advance.
|
||||
#[derive(Copy, Clone, Default, Debug, PartialEq)]
|
||||
#[expect(missing_docs, reason = "Deferred")]
|
||||
pub struct Glyph {
|
||||
pub id: u32,
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub advance: f32,
|
||||
}
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Itemization breaks text into individually-shapeable items.
|
||||
|
||||
use core::{ops::Range, str::CharIndices};
|
||||
|
||||
use icu_properties::props::Script as IcuScript;
|
||||
use parlance::{BidiLevel, Script};
|
||||
|
||||
use crate::{Analysis, CharInfo, ShapeOptions};
|
||||
|
||||
/// A range of text.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TextRange {
|
||||
/// The range of byte offsets.
|
||||
pub byte_range: Range<usize>,
|
||||
|
||||
/// The range of character indices.
|
||||
pub char_range: Range<usize>,
|
||||
}
|
||||
|
||||
/// A span of text inside an [`Item`] with constant script and bidirectional embedding level.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Segment {
|
||||
/// The text range of this item.
|
||||
pub range: TextRange,
|
||||
|
||||
/// The bidi level of characters in this item.
|
||||
pub bidi_level: BidiLevel,
|
||||
|
||||
/// The script of characters in this item.
|
||||
///
|
||||
/// Characters in the source text that do not have a particular script (i.e., they are one of
|
||||
/// [`Script::COMMON`], [`Script::UNKNOWN`] or [`Script::INHERITED`]) get their script from
|
||||
/// surrounding context. Currently, these just inherit the script of the preceding characters.
|
||||
/// Leading characters without a particular script inherit the script of the first character
|
||||
/// *with* a particular script. These heuristics may change in the future. For more, see UAX 24
|
||||
/// (<https://www.unicode.org/reports/tr24/>) Section 5.
|
||||
pub script: Script,
|
||||
}
|
||||
|
||||
/// A span of text shaped with specific [`ShapeOptions`].
|
||||
///
|
||||
/// An [`Item`] represents a sequence of constant [`ShapeOptions`], but cannot always be passed to
|
||||
/// the shaper as a single unit. Within an item, the script or bidirectional text embedding level
|
||||
/// may change, which requires further splitting the item into segments of constant script and bidi
|
||||
/// level (see [`Segment`]).
|
||||
#[derive(Debug)]
|
||||
pub struct Item<'a> {
|
||||
/// The character offset in the source text which this item ends.
|
||||
///
|
||||
/// This must be strictly greater than the previous item's end. For the first item, it must be
|
||||
/// greater than 0.
|
||||
pub char_end: u32,
|
||||
|
||||
/// The options to shape this item with.
|
||||
//
|
||||
// TODO: should users instead be allowed to build `options` at the `Segment` level (i.e.,
|
||||
// through some callback)? The motivation is for users to have access to the segment's `Script`
|
||||
// and be able to set font features based on that. If the entirety of `ShapeOptions` moves
|
||||
// there, it would allow users to set, e.g., a font size per segment, even though it's not
|
||||
// necessarily an item boundary; and note an item then doesn't mean a whole lot anymore. We
|
||||
// could also allow only some options to be per-segment. In any case, we're probably moving
|
||||
// towards a future where items reset grapheme segmentation, but segments do not (note Gecko and
|
||||
// Blink also reset grapheme segmentation when something like font size changes, but not when
|
||||
// the script changes).
|
||||
pub options: ShapeOptions<'a>,
|
||||
// TODO: we probably should allow users to pass in some data (like we allow passing
|
||||
// style_indices elsewhere), which we copy onto `ShapedRun`. That allows users to easily
|
||||
// correlate `ShapedRun`s with some data they themselves hold.
|
||||
//
|
||||
// This is potentially important for better correctness in `parley`: it itemizes based on
|
||||
// `nearly_eq` of shaping-relevant styles like font size, i.e., it should then read that item's
|
||||
// style to know the font size, even though it may be different for the run.
|
||||
// /// Opaque data copied onto every `ShapedRun` produced from this item.
|
||||
// pub user_data: u16,
|
||||
}
|
||||
|
||||
/// Produces the items in a text via [`Self::next`]; created by [`Analysis::itemize`].
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Itemizer<'a> {
|
||||
/// Our underlying iterator over the input text.
|
||||
char_indices: CharIndices<'a>,
|
||||
/// The per-char info, parallel to [`Self::char_indices`].
|
||||
char_info: &'a [CharInfo],
|
||||
/// The per-char bidi level, parallel to [`Self::char_indices`].
|
||||
bidi_levels: &'a [BidiLevel],
|
||||
|
||||
/// The paragraph's base bidi level.
|
||||
///
|
||||
/// If [`Self::bidi_levels`] is empty as a special case, this is the bidi level of each
|
||||
/// character.
|
||||
paragraph_bidi_level: BidiLevel,
|
||||
|
||||
/// The running character offset of the last-processed item.
|
||||
current_char_offset: usize,
|
||||
/// The running script of the last-processed item.
|
||||
current_script: IcuScript,
|
||||
}
|
||||
|
||||
impl Analysis {
|
||||
/// Divide the `text` into individually-shapeable segments.
|
||||
///
|
||||
/// The `text` passed in must be the same as used for producing the `self` analysis.
|
||||
///
|
||||
/// The text is divided into items produced by a predicate passed to [`Itemizer::next`] and
|
||||
/// further divided into segments of constant bidi level and script.
|
||||
///
|
||||
/// Characters that don't have a particular script have their script resolved based on
|
||||
/// surrounding context (see [`Segment::script`]).
|
||||
pub(crate) fn itemize<'a>(&'a self, text: &'a str) -> Itemizer<'a> {
|
||||
let first_real_script = self
|
||||
.char_info()
|
||||
.iter()
|
||||
.map(|x| x.script)
|
||||
.find(|&script| real_script(script))
|
||||
.unwrap_or(IcuScript::Latin);
|
||||
|
||||
Itemizer {
|
||||
char_indices: text.char_indices(),
|
||||
char_info: self.char_info(),
|
||||
bidi_levels: self.bidi_levels(),
|
||||
paragraph_bidi_level: self.paragraph_level(),
|
||||
|
||||
current_char_offset: 0,
|
||||
current_script: first_real_script,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Itemizer<'_> {
|
||||
/// Produce the next segment, if any.
|
||||
///
|
||||
/// For consecutive characters where the bidi level and script are unchanging, the `split_after`
|
||||
/// predicate is called with the growing item range, and can be used to split on additional
|
||||
/// properties like shaping-relevant style changes (e.g., font size) or properties like
|
||||
/// language.
|
||||
///
|
||||
/// The predicate is given a range encoding the current item and considers whether to split
|
||||
/// after that item based on the next character. Iff the predicate returns `true`, the text is
|
||||
/// split after that item; i.e., given a range of `start..end`, the predicate controls whether
|
||||
/// that item is now finished, or whether it is extended to include the character at `end` (at
|
||||
/// which point the item spans `start..end+1`).
|
||||
//
|
||||
// TODO: currently the items from `split_after` have the same effect as a change in bidi or
|
||||
// script. This is not how browsers handle things. In particular, `split_after` should reset
|
||||
// grapheme segmentation, whereas bidi and script should produce separately-shaped segments.
|
||||
#[inline]
|
||||
pub(crate) fn next(
|
||||
&mut self,
|
||||
mut split_after: impl FnMut(TextRange) -> bool,
|
||||
) -> Option<Segment> {
|
||||
if self.char_info.is_empty() {
|
||||
// We're already finished.
|
||||
debug_assert!(
|
||||
self.char_indices.next().is_none() && self.bidi_levels.is_empty(),
|
||||
"`char_info`, `bidi_levels`, and `char_indices` should now all be empty \
|
||||
(though note `bidi_levels` may already have been empty as a special-case)"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut item_bidi_level = BidiLevel::new(0); // Initialized in the loop.
|
||||
|
||||
let start_byte_offset = self.char_indices.offset();
|
||||
let mut item_char_len = 0;
|
||||
loop {
|
||||
let byte_offset = self.char_indices.offset();
|
||||
|
||||
let bidi_level = if self.bidi_levels.is_empty() {
|
||||
self.paragraph_bidi_level
|
||||
} else {
|
||||
self.bidi_levels[0]
|
||||
};
|
||||
let mut script = self.char_info[0].script;
|
||||
|
||||
if !real_script(script) {
|
||||
// This is a very simple heuristic, where if a character does not have a "real
|
||||
// script," it inherits the script of the preceding character. UAX 24 paragraph
|
||||
// 5.1 says this "works well in many cases", but also suggests performing, e.g.,
|
||||
// bracket matching (for example, the parentheses in `hello (αβγ)` should ideally
|
||||
// both be marked as being `Latin`). At that point, `Itemizer` would probably like
|
||||
// to have reusable scratch for the bracket stack.
|
||||
script = self.current_script;
|
||||
}
|
||||
|
||||
// First iteration of the loop, initialize item properties.
|
||||
if item_char_len == 0 {
|
||||
item_bidi_level = bidi_level;
|
||||
self.current_script = script;
|
||||
}
|
||||
|
||||
if bidi_level != item_bidi_level || script != self.current_script {
|
||||
break;
|
||||
}
|
||||
|
||||
if item_char_len > 0
|
||||
&& split_after(TextRange {
|
||||
byte_range: start_byte_offset..byte_offset,
|
||||
char_range: self.current_char_offset..self.current_char_offset + item_char_len,
|
||||
})
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
self.char_indices.next().expect("The passed in `text` was not of the same length as the text used to generate `Analysis`");
|
||||
self.char_info = &self.char_info[1..];
|
||||
if !self.bidi_levels.is_empty() {
|
||||
self.bidi_levels = &self.bidi_levels[1..];
|
||||
}
|
||||
|
||||
item_char_len += 1;
|
||||
|
||||
if self.char_info.is_empty() {
|
||||
// The text is now empty, so we're finished.
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let start_char_offset = self.current_char_offset;
|
||||
self.current_char_offset += item_char_len;
|
||||
|
||||
Some(Segment {
|
||||
range: TextRange {
|
||||
byte_range: start_byte_offset..self.char_indices.offset(),
|
||||
char_range: start_char_offset..self.current_char_offset,
|
||||
},
|
||||
script: icu_script_to_parlance_script(self.current_script),
|
||||
bidi_level: item_bidi_level,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn real_script(script: IcuScript) -> bool {
|
||||
script != IcuScript::Common && script != IcuScript::Unknown && script != IcuScript::Inherited
|
||||
}
|
||||
|
||||
/// Convert an ICU script into a [`Script`].
|
||||
#[inline]
|
||||
fn icu_script_to_parlance_script(script: IcuScript) -> Script {
|
||||
static SHORT_NAMES: icu_properties::PropertyNamesShortBorrowed<'static, IcuScript> =
|
||||
icu_properties::PropertyNamesShort::new();
|
||||
|
||||
SHORT_NAMES
|
||||
.get(script)
|
||||
.and_then(|name| Script::parse(name).ok())
|
||||
.unwrap_or(Script::UNKNOWN)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use alloc::vec::Vec;
|
||||
use parlance::Script;
|
||||
|
||||
use crate::{Analysis, AnalysisOptions, Analyzer};
|
||||
|
||||
use super::Segment;
|
||||
|
||||
const LATN: Script = Script::from_bytes(*b"Latn");
|
||||
const GREK: Script = Script::from_bytes(*b"Grek");
|
||||
const ARAB: Script = Script::from_bytes(*b"Arab");
|
||||
|
||||
fn analyze(text: &str) -> Analysis {
|
||||
let mut analyzer = Analyzer::new();
|
||||
let mut analysis = Analysis::new();
|
||||
let options = AnalysisOptions::default();
|
||||
analyzer.analyze(text, &options, &mut analysis);
|
||||
analysis
|
||||
}
|
||||
|
||||
fn items(text: &str) -> Vec<Segment> {
|
||||
let analysis = analyze(text);
|
||||
let mut itemizer = analysis.itemize(text);
|
||||
core::iter::from_fn(|| itemizer.next(|_| false)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty() {
|
||||
assert!(items("").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_direction() {
|
||||
let text = "hello مرحبا";
|
||||
let items = items(text);
|
||||
assert!(items.len() >= 2);
|
||||
assert_eq!(items[0].script, LATN);
|
||||
assert!(items[0].bidi_level.is_ltr());
|
||||
assert!(
|
||||
items
|
||||
.iter()
|
||||
.any(|item| item.script == ARAB && item.bidi_level.is_rtl())
|
||||
);
|
||||
|
||||
// Items tile the text contiguously.
|
||||
let mut cursor = 0;
|
||||
for item in &items {
|
||||
assert_eq!(item.range.byte_range.start, cursor);
|
||||
cursor = item.range.byte_range.end;
|
||||
}
|
||||
assert_eq!(cursor, text.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn predicate() {
|
||||
let text = "abcdef";
|
||||
let analysis = analyze(text);
|
||||
let mut itemizer = analysis.itemize(text);
|
||||
let items: Vec<_> =
|
||||
core::iter::from_fn(|| itemizer.next(|range| range.char_range.end == 3)).collect();
|
||||
assert_eq!(items.len(), 2);
|
||||
assert_eq!(items[0].range.byte_range, 0..3);
|
||||
assert_eq!(items[0].range.char_range, 0..3);
|
||||
assert_eq!(items[1].range.byte_range, 3..6);
|
||||
assert_eq!(items[1].range.char_range, 3..6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neutral_backward() {
|
||||
// Latin, a space (`Common`), then Greek.
|
||||
let text = "abc αβγ";
|
||||
let items = items(text);
|
||||
assert_eq!(items.len(), 2);
|
||||
// The space attaches to the Latin run.
|
||||
assert_eq!(&text[items[0].range.byte_range.clone()], "abc ");
|
||||
assert_eq!(items[0].script, LATN);
|
||||
assert_eq!(&text[items[1].range.byte_range.clone()], "αβγ");
|
||||
assert_eq!(items[1].script, GREK);
|
||||
}
|
||||
}
|
||||
Vendored
+130
@@ -0,0 +1,130 @@
|
||||
// Copyright 2025 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Parley Engine provides low level APIs for shaping paragraphs of text.
|
||||
//!
|
||||
//! ## Usage
|
||||
//!
|
||||
//! Use [`Analyzer`], [`Analysis`], [`Shaper`] and [`ShapedText`] to shape a paragraph of text into
|
||||
//! glyphs. Correct reshaping of lines is in progress; in the meantime you can break text at
|
||||
//! [`Atom`] or [`ShapedCluster`][crate::shape::ShapedCluster] boundaries.
|
||||
//!
|
||||
//! Text analysis is performed before shaping, and the same source string must be passed to each
|
||||
//! stage.
|
||||
//!
|
||||
//! Higher-level users may prefer using [`parley`][parley], which uses this crate and implements
|
||||
//! layout and styling.
|
||||
//!
|
||||
//! ```rust,no_run
|
||||
//! # // We only compile this doctest because we don't have a font available.
|
||||
//! # use parley_engine::{Analysis, AnalysisOptions, Analyzer, FontInstanceRef, FontSelector, ShapedText, ShapeOptions, Shaper};
|
||||
//! # use parley_engine::shape::CharCluster;
|
||||
//! # use parley_engine::itemize::{Item, Segment};
|
||||
//! #
|
||||
//! # struct NoFont;
|
||||
//! # impl FontSelector for NoFont {
|
||||
//! # fn select_font(
|
||||
//! # &mut self,
|
||||
//! # _segment: &Segment,
|
||||
//! # _options: &ShapeOptions<'_>,
|
||||
//! # _cluster: &mut CharCluster,
|
||||
//! # ) -> Option<FontInstanceRef<'_>> {
|
||||
//! # unimplemented!()
|
||||
//! # }
|
||||
//! # }
|
||||
//! #
|
||||
//! # let select_font = NoFont;
|
||||
//! let mut analysis = Analysis::default();
|
||||
//! let mut analyzer = Analyzer::default();
|
||||
//! let mut shaped_text = ShapedText::default();
|
||||
//! let mut shaper = Shaper::default();
|
||||
//!
|
||||
//! let text = "The quick brown ثعلب jumps over the lazy dog.";
|
||||
//! let char_count = text.chars().count();
|
||||
//! let char_style_indices = vec![0; char_count];
|
||||
//!
|
||||
//! analyzer.analyze(text, &AnalysisOptions::default(), &mut analysis);
|
||||
//! shaper.shape_text(
|
||||
//! text,
|
||||
//! &analysis,
|
||||
//! &char_style_indices,
|
||||
//! [Item {
|
||||
//! char_end: char_count.try_into().unwrap(),
|
||||
//! options: ShapeOptions {
|
||||
//! font_size: 16.0,
|
||||
//! language: None,
|
||||
//! features: &[],
|
||||
//! variations: &[],
|
||||
//! },
|
||||
//! }],
|
||||
//! select_font, // Selects fonts covering each cluster.
|
||||
//! &mut shaped_text,
|
||||
//! );
|
||||
//!
|
||||
//! for (run_idx, run) in shaped_text.runs().iter().enumerate() {
|
||||
//! let slice = shaped_text.run_slice(run_idx as u32);
|
||||
//! // You can, for example, measure grapheme advances for hit-testing or
|
||||
//! // placing carets.
|
||||
//! for atom in slice.atoms_start() {
|
||||
//! for grapheme in atom.graphemes_start() {
|
||||
//! std::dbg!(grapheme);
|
||||
//! }
|
||||
//! }
|
||||
//!
|
||||
//! // Or get glyphs for rendering (for simplicity, this iterates clusters in
|
||||
//! // logical order, but for rendering you'd want to reorder runs and clusters
|
||||
//! // according to their `run.bidi_level`).
|
||||
//! for cluster in slice.shaped_clusters_range() {
|
||||
//! for glyph in slice.shaped_cluster_glyphs(cluster) {
|
||||
//! std::dbg!(glyph);
|
||||
//! }
|
||||
//! }
|
||||
//! }
|
||||
//! ```
|
||||
//!
|
||||
//! ## Features
|
||||
//!
|
||||
//! - `std` (enabled by default): This is currently unused and is provided for forward compatibility.
|
||||
//! - `bytemuck`: Forwarded to [`parlance`], which then implements traits from `bytemuck` on its
|
||||
//! types.
|
||||
//!
|
||||
//! [parley]: https://docs.rs/parley
|
||||
|
||||
// LINEBENDER LINT SET - lib.rs - v3
|
||||
// See https://linebender.org/wiki/canonical-lints/
|
||||
// These lints shouldn't apply to examples or tests.
|
||||
#![cfg_attr(not(test), warn(unused_crate_dependencies))]
|
||||
// These lints shouldn't apply to examples.
|
||||
#![warn(clippy::print_stdout, clippy::print_stderr)]
|
||||
// Targeting e.g. 32-bit means structs containing usize can give false positives for 64-bit.
|
||||
#![cfg_attr(target_pointer_width = "64", warn(clippy::trivially_copy_pass_by_ref))]
|
||||
// END LINEBENDER LINT SET
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
// Vendored: the upstream crate has an unreachable expression rustc warns about; keep the build log quiet.
|
||||
#![allow(unreachable_code)]
|
||||
#![no_std]
|
||||
#[cfg(feature = "std")]
|
||||
extern crate std;
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
mod analysis;
|
||||
mod analyzer;
|
||||
mod bidi;
|
||||
pub mod break_overrides;
|
||||
pub mod dictionary;
|
||||
pub mod platform;
|
||||
mod glyph;
|
||||
pub mod itemize;
|
||||
mod lru_cache;
|
||||
pub mod shape;
|
||||
|
||||
pub use linebender_resource_handle::FontData;
|
||||
pub use parlance::{BaseDirection, NormalizedCoord};
|
||||
|
||||
pub use analysis::{Analysis, AnalysisDataSources, CharInfo};
|
||||
pub use analyzer::{AnalysisOptions, Analyzer, LineBreakConfig};
|
||||
pub use glyph::Glyph;
|
||||
pub use shape::atom::{Atom, Atoms, Grapheme, Graphemes, ShapedClusterGlyphs, ShapedSlice};
|
||||
pub use shape::shaped_text::{FontMetrics, ShapedRun, ShapedText};
|
||||
pub use shape::shaper::{FontInstance, FontInstanceRef, FontSelector, ShapeOptions, Shaper};
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
// Copyright 2025 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use hashbrown::Equivalent;
|
||||
|
||||
/// An entry in the cache.
|
||||
pub(crate) struct Entry<ID, T> {
|
||||
pub epoch: u64,
|
||||
pub id: ID,
|
||||
pub data: T,
|
||||
}
|
||||
|
||||
/// A least-recently-used cache. This cache uses a linear scan of its entries
|
||||
/// to find a given entry - it is optimised for a low number of entries. Preferably
|
||||
/// keep `max_entries` low - in the order of tens.
|
||||
pub(crate) struct LruCache<ID, T> {
|
||||
entries: Vec<Entry<ID, T>>,
|
||||
epoch: u64,
|
||||
max_entries: usize,
|
||||
}
|
||||
|
||||
impl<ID, T> LruCache<ID, T> {
|
||||
pub(crate) fn new(max_entries: usize) -> Self {
|
||||
Self {
|
||||
entries: Vec::default(),
|
||||
epoch: 0,
|
||||
max_entries,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a reference to the entry with the given ID. If the entry is not
|
||||
/// found, it is created and returned using `make_data`.
|
||||
///
|
||||
/// The lookup key must be `Equivalent` to ID for lookups and convertible `Into<ID>`
|
||||
/// for creating new entries.
|
||||
pub(crate) fn entry<K>(&mut self, id: K, make_data: impl FnOnce() -> T) -> &T
|
||||
where
|
||||
K: Equivalent<ID> + Into<ID>,
|
||||
{
|
||||
let index = self.find_entry(id, make_data);
|
||||
self.epoch += 1;
|
||||
let entry = &mut self.entries[index];
|
||||
entry.epoch = self.epoch;
|
||||
&entry.data
|
||||
}
|
||||
|
||||
fn find_entry<K>(&mut self, id: K, make_data: impl FnOnce() -> T) -> usize
|
||||
where
|
||||
K: Equivalent<ID> + Into<ID>,
|
||||
{
|
||||
let epoch = self.epoch;
|
||||
let mut lowest_serial = epoch;
|
||||
let mut lowest_index = 0;
|
||||
for (i, entry) in self.entries.iter().enumerate() {
|
||||
if id.equivalent(&entry.id) {
|
||||
return i;
|
||||
}
|
||||
if entry.epoch < lowest_serial {
|
||||
lowest_serial = entry.epoch;
|
||||
lowest_index = i;
|
||||
}
|
||||
}
|
||||
if self.entries.len() < self.max_entries {
|
||||
lowest_index = self.entries.len();
|
||||
self.entries.push(Entry {
|
||||
epoch,
|
||||
id: id.into(),
|
||||
data: make_data(),
|
||||
});
|
||||
} else {
|
||||
let entry = &mut self.entries[lowest_index];
|
||||
entry.epoch = epoch;
|
||||
entry.id = id.into();
|
||||
entry.data = make_data();
|
||||
}
|
||||
lowest_index
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use alloc::string::{String, ToString};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct TestId(String);
|
||||
struct TestLookupKey<'a>(&'a str);
|
||||
|
||||
impl<'a> Equivalent<TestId> for TestLookupKey<'a> {
|
||||
fn equivalent(&self, key: &TestId) -> bool {
|
||||
self.0 == key.0.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<TestLookupKey<'a>> for TestId {
|
||||
fn from(key: TestLookupKey<'a>) -> Self {
|
||||
Self(key.0.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl Equivalent<Self> for TestId {
|
||||
fn equivalent(&self, key: &Self) -> bool {
|
||||
self.0 == key.0
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_retrieve_existing_entry() {
|
||||
let mut cache = LruCache::new(3);
|
||||
|
||||
// Insert an entry
|
||||
let value1 = cache.entry(TestLookupKey("key1"), || 42);
|
||||
assert_eq!(*value1, 42);
|
||||
|
||||
// Retrieve the same entry - make_data should not be called
|
||||
let value2 = cache.entry(TestLookupKey("key1"), || {
|
||||
panic!("Should not create new data")
|
||||
});
|
||||
assert_eq!(*value2, 42);
|
||||
assert_eq!(cache.entries.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_multiple_entries() {
|
||||
let mut cache = LruCache::new(3);
|
||||
|
||||
let value1 = cache.entry(TestLookupKey("key1"), || 1);
|
||||
assert_eq!(*value1, 1);
|
||||
|
||||
let value2 = cache.entry(TestLookupKey("key2"), || 2);
|
||||
assert_eq!(*value2, 2);
|
||||
|
||||
let value3 = cache.entry(TestLookupKey("key3"), || 3);
|
||||
assert_eq!(*value3, 3);
|
||||
|
||||
assert_eq!(cache.entries.len(), 3);
|
||||
assert_eq!(cache.epoch, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lru_eviction() {
|
||||
let mut cache = LruCache::new(3);
|
||||
|
||||
// Add three entries
|
||||
cache.entry(TestLookupKey("key1"), || 1);
|
||||
cache.entry(TestLookupKey("key2"), || 2);
|
||||
cache.entry(TestLookupKey("key3"), || 3);
|
||||
|
||||
// Access key1 to update its epoch
|
||||
cache.entry(TestLookupKey("key1"), || panic!("Should not create"));
|
||||
|
||||
// Add key4 - should evict key2 (oldest untouched)
|
||||
cache.entry(TestLookupKey("key4"), || 4);
|
||||
|
||||
// Verify key1 is still present
|
||||
let value1 = cache.entry(TestLookupKey("key1"), || {
|
||||
panic!("key1 should still be present")
|
||||
});
|
||||
assert_eq!(*value1, 1);
|
||||
|
||||
// Verify key2 was evicted
|
||||
let mut was_created = false;
|
||||
cache.entry(TestLookupKey("key2"), || {
|
||||
was_created = true;
|
||||
20
|
||||
});
|
||||
assert!(was_created, "key2 should have been evicted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lru_eviction_after_multiple_hits() {
|
||||
let mut cache = LruCache::new(3);
|
||||
|
||||
cache.entry(TestLookupKey("key1"), || 1);
|
||||
cache.entry(TestLookupKey("key2"), || 2);
|
||||
cache.entry(TestLookupKey("key3"), || 3);
|
||||
|
||||
// Hit all three in order: key3 first (making it LRU among hits),
|
||||
// then key1, then key2 (most recently used).
|
||||
cache.entry(TestLookupKey("key3"), || panic!("Should not create"));
|
||||
cache.entry(TestLookupKey("key1"), || panic!("Should not create"));
|
||||
cache.entry(TestLookupKey("key2"), || panic!("Should not create"));
|
||||
|
||||
// Insert key4 — should evict key3 (least recently accessed)
|
||||
cache.entry(TestLookupKey("key4"), || 4);
|
||||
|
||||
// key1 and key2 should still be present with original values
|
||||
// (check these first since verifying key3 eviction will trigger another eviction)
|
||||
let v1 = cache.entry(TestLookupKey("key1"), || {
|
||||
panic!("key1 should still be present")
|
||||
});
|
||||
assert_eq!(*v1, 1);
|
||||
|
||||
let v2 = cache.entry(TestLookupKey("key2"), || {
|
||||
panic!("key2 should still be present")
|
||||
});
|
||||
assert_eq!(*v2, 2);
|
||||
|
||||
// key3 should have been evicted
|
||||
let mut key3_recreated = false;
|
||||
cache.entry(TestLookupKey("key3"), || {
|
||||
key3_recreated = true;
|
||||
30
|
||||
});
|
||||
assert!(key3_recreated, "key3 should have been evicted as the LRU");
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! A face of last resort that the platform draws (Rune: vendor/parley_engine.patch). A host that
|
||||
//! can shape and draw text itself (a browser's canvas, with the system's fonts, shaping and
|
||||
//! colour emoji) registers a font that covers every character and gives its runs a shaper here.
|
||||
//! A run in that font isn't shaped by HarfRust: the host gives one glyph per grapheme, its
|
||||
//! advance measured as the platform lays the run out, and the glyph ids are the host's own, for
|
||||
//! it to draw them.
|
||||
|
||||
use alloc::vec::Vec;
|
||||
|
||||
/// A run in the platform's face, for its shaper.
|
||||
#[derive(Debug)]
|
||||
pub struct PlatformText<'a> {
|
||||
/// The run's text.
|
||||
pub text: &'a str,
|
||||
/// Byte offsets into `text` where each grapheme starts, ascending, the first 0.
|
||||
pub graphemes: &'a [u32],
|
||||
/// Byte offsets where each unit the platform draws whole starts (at grapheme starts, between
|
||||
/// break opportunities), ascending, the first 0. A line never breaks inside one.
|
||||
pub units: &'a [u32],
|
||||
/// The font size, in the layout's units.
|
||||
pub size: f32,
|
||||
/// The weight asked for (`wght`, 100 to 900).
|
||||
pub weight: f32,
|
||||
/// Italic asked for.
|
||||
pub italic: bool,
|
||||
/// The run is right to left.
|
||||
pub rtl: bool,
|
||||
/// The run's language tag, if it has one.
|
||||
pub language: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// One glyph per grapheme of a [`PlatformText`], in logical order.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct PlatformGlyph {
|
||||
/// The host's id for what this glyph draws.
|
||||
pub id: u32,
|
||||
/// The grapheme's advance, in the layout's units.
|
||||
pub advance: f32,
|
||||
/// How far right of its pen the glyph draws, in the layout's units.
|
||||
pub x_offset: f32,
|
||||
}
|
||||
|
||||
/// Fills `out` with one glyph per grapheme of the run, in logical order.
|
||||
pub type PlatformShaper = fn(run: &PlatformText<'_>, out: &mut Vec<PlatformGlyph>);
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
static PLATFORM: std::sync::OnceLock<(u64, PlatformShaper)> = std::sync::OnceLock::new();
|
||||
|
||||
/// Makes the font whose data has id `font` (`Blob::id`) the platform's face, shaped by `shaper`,
|
||||
/// once (a second call changes nothing). Needs `std`.
|
||||
pub fn set_platform_face(font: u64, shaper: PlatformShaper) {
|
||||
#[cfg(feature = "std")]
|
||||
let _ = PLATFORM.set((font, shaper));
|
||||
#[cfg(not(feature = "std"))]
|
||||
let _ = (font, shaper);
|
||||
}
|
||||
|
||||
/// The shaper for the font with data id `font`, if it's the platform's face.
|
||||
pub(crate) fn shaper(font: u64) -> Option<PlatformShaper> {
|
||||
#[cfg(feature = "std")]
|
||||
return PLATFORM.get().filter(|(id, _)| *id == font).map(|(_, shaper)| *shaper);
|
||||
#[cfg(not(feature = "std"))]
|
||||
{
|
||||
let _ = font;
|
||||
None
|
||||
}
|
||||
}
|
||||
+1008
File diff suppressed because it is too large.
Load diff
+215
@@ -0,0 +1,215 @@
|
||||
// Copyright 2025 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
use alloc::boxed::Box;
|
||||
use hashbrown::Equivalent;
|
||||
use parlance::FontVariation;
|
||||
|
||||
#[derive(PartialEq, Copy, Clone)]
|
||||
pub(crate) struct ShapeDataKey {
|
||||
/// The font collection's blob ID.
|
||||
font_blob_id: u64,
|
||||
/// The font's index in the font collection.
|
||||
font_index: u32,
|
||||
}
|
||||
|
||||
impl ShapeDataKey {
|
||||
pub(crate) const fn new(font_blob_id: u64, font_index: u32) -> Self {
|
||||
Self {
|
||||
font_blob_id,
|
||||
font_index,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Equivalent<Self> for ShapeDataKey {
|
||||
#[inline(always)]
|
||||
fn equivalent(&self, key: &Self) -> bool {
|
||||
self == key
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Self> for ShapeDataKey {
|
||||
#[inline(always)]
|
||||
fn from(key: &Self) -> Self {
|
||||
*key
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ShapeInstanceId {
|
||||
/// The font collection's blob ID.
|
||||
font_blob_id: u64,
|
||||
/// The font's index in the font collection.
|
||||
font_index: u32,
|
||||
synthesis: fontique::Synthesis,
|
||||
variations: Option<Box<[FontVariation]>>,
|
||||
}
|
||||
|
||||
pub(crate) struct ShapeInstanceKey<'a> {
|
||||
/// The font collection's blob ID.
|
||||
font_blob_id: u64,
|
||||
/// The font's index in the font collection.
|
||||
font_index: u32,
|
||||
synthesis: &'a fontique::Synthesis,
|
||||
variations: Option<&'a [FontVariation]>,
|
||||
}
|
||||
|
||||
impl<'a> ShapeInstanceKey<'a> {
|
||||
pub(crate) const fn new(
|
||||
font_blob_id: u64,
|
||||
font_index: u32,
|
||||
synthesis: &'a fontique::Synthesis,
|
||||
variations: Option<&'a [FontVariation]>,
|
||||
) -> Self {
|
||||
Self {
|
||||
font_blob_id,
|
||||
font_index,
|
||||
synthesis,
|
||||
variations,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Equivalent<ShapeInstanceId> for ShapeInstanceKey<'a> {
|
||||
#[inline(always)]
|
||||
fn equivalent(&self, key: &ShapeInstanceId) -> bool {
|
||||
self.font_blob_id == key.font_blob_id
|
||||
&& self.font_index == key.font_index
|
||||
&& *self.synthesis == key.synthesis
|
||||
&& self.variations == key.variations.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<ShapeInstanceKey<'a>> for ShapeInstanceId {
|
||||
#[inline(always)]
|
||||
fn from(key: ShapeInstanceKey<'a>) -> Self {
|
||||
Self {
|
||||
font_blob_id: key.font_blob_id,
|
||||
font_index: key.font_index,
|
||||
synthesis: *key.synthesis,
|
||||
variations: key.variations.map(|v| v.to_vec().into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A shaped run's font metrics: its font instance at a size (Rune: vendor/parley_engine.patch).
|
||||
pub(crate) struct RunMetricsId {
|
||||
instance: ShapeInstanceId,
|
||||
font_size: u32,
|
||||
}
|
||||
|
||||
pub(crate) struct RunMetricsKey<'a> {
|
||||
instance: ShapeInstanceKey<'a>,
|
||||
font_size: f32,
|
||||
}
|
||||
|
||||
impl<'a> RunMetricsKey<'a> {
|
||||
pub(crate) const fn new(instance: ShapeInstanceKey<'a>, font_size: f32) -> Self {
|
||||
Self {
|
||||
instance,
|
||||
font_size,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Equivalent<RunMetricsId> for RunMetricsKey<'a> {
|
||||
#[inline(always)]
|
||||
fn equivalent(&self, key: &RunMetricsId) -> bool {
|
||||
self.font_size.to_bits() == key.font_size && self.instance.equivalent(&key.instance)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<RunMetricsKey<'a>> for RunMetricsId {
|
||||
#[inline(always)]
|
||||
fn from(key: RunMetricsKey<'a>) -> Self {
|
||||
Self {
|
||||
instance: key.instance.into(),
|
||||
font_size: key.font_size.to_bits(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ShapePlanId {
|
||||
/// The font collection's blob ID.
|
||||
font_blob_id: u64,
|
||||
/// The font's index in the font collection.
|
||||
font_index: u32,
|
||||
synthesis: fontique::Synthesis,
|
||||
direction: harfrust::Direction,
|
||||
script: harfrust::Script,
|
||||
language: Option<harfrust::Language>,
|
||||
features: Box<[harfrust::Feature]>,
|
||||
variations: Option<Box<[FontVariation]>>,
|
||||
}
|
||||
|
||||
pub(crate) struct ShapePlanKey<'a> {
|
||||
/// The font collection's blob ID.
|
||||
font_blob_id: u64,
|
||||
/// The font's index in the font collection.
|
||||
font_index: u32,
|
||||
synthesis: &'a fontique::Synthesis,
|
||||
direction: harfrust::Direction,
|
||||
script: harfrust::Script,
|
||||
language: Option<harfrust::Language>,
|
||||
features: &'a [harfrust::Feature],
|
||||
variations: Option<&'a [FontVariation]>,
|
||||
}
|
||||
|
||||
impl<'a> ShapePlanKey<'a> {
|
||||
pub(crate) const fn new(
|
||||
font_blob_id: u64,
|
||||
font_index: u32,
|
||||
synthesis: &'a fontique::Synthesis,
|
||||
direction: harfrust::Direction,
|
||||
script: harfrust::Script,
|
||||
language: Option<harfrust::Language>,
|
||||
features: &'a [harfrust::Feature],
|
||||
variations: Option<&'a [FontVariation]>,
|
||||
) -> Self {
|
||||
Self {
|
||||
font_blob_id,
|
||||
font_index,
|
||||
synthesis,
|
||||
direction,
|
||||
script,
|
||||
language,
|
||||
features,
|
||||
variations,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Equivalent<ShapePlanId> for ShapePlanKey<'a> {
|
||||
#[inline(always)]
|
||||
fn equivalent(&self, key: &ShapePlanId) -> bool {
|
||||
self.font_blob_id == key.font_blob_id
|
||||
&& self.font_index == key.font_index
|
||||
&& *self.synthesis == key.synthesis
|
||||
&& self.direction == key.direction
|
||||
&& self.script == key.script
|
||||
&& self.language == key.language
|
||||
&& self.features.len() == key.features.len()
|
||||
&& self.variations == key.variations.as_deref()
|
||||
&& self
|
||||
.features
|
||||
.iter()
|
||||
.zip(key.features.iter())
|
||||
.all(|(a, b)| a == b)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<ShapePlanKey<'a>> for ShapePlanId {
|
||||
#[inline(always)]
|
||||
fn from(key: ShapePlanKey<'a>) -> Self {
|
||||
Self {
|
||||
font_blob_id: key.font_blob_id,
|
||||
font_index: key.font_index,
|
||||
synthesis: *key.synthesis,
|
||||
direction: key.direction,
|
||||
script: key.script,
|
||||
language: key.language,
|
||||
features: key.features.to_vec().into(),
|
||||
variations: key.variations.map(|v| v.to_vec().into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
+638
@@ -0,0 +1,638 @@
|
||||
// Copyright 2025 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
#![expect(missing_docs, reason = "Deferred")]
|
||||
#![expect(missing_debug_implementations, reason = "Deferred")]
|
||||
|
||||
use core::cmp::Ordering;
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use icu_normalizer::properties::Decomposed;
|
||||
use parley_emoji::{EmojiDFA, EmojiPresentationStyle, EmojiSegmentationCategory};
|
||||
|
||||
use crate::{CharInfo, analysis::AnalysisDataSources};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CharCluster {
|
||||
chars: Vec<Char>,
|
||||
map_len: u8,
|
||||
start: u32,
|
||||
end: u32,
|
||||
force_normalize: bool,
|
||||
comp: Form,
|
||||
decomp: Form,
|
||||
emoji_presentation_style: EmojiPresentationStyle,
|
||||
}
|
||||
|
||||
impl CharCluster {
|
||||
#[inline]
|
||||
pub fn range(&self) -> SourceRange {
|
||||
SourceRange {
|
||||
start: self.start,
|
||||
end: self.end,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn chars(&self) -> &[Char] {
|
||||
&self.chars
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_emoji(&self) -> bool {
|
||||
self.emoji_presentation_style.is_emoji()
|
||||
}
|
||||
}
|
||||
|
||||
/// Source range of a cluster in code units.
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct SourceRange {
|
||||
pub start: u32,
|
||||
pub end: u32,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Default)]
|
||||
pub struct Char {
|
||||
/// The character.
|
||||
pub ch: char,
|
||||
/// Whether the character
|
||||
pub is_control_character: bool,
|
||||
/// True if the character should be considered when mapping glyphs.
|
||||
pub contributes_to_shaping: bool,
|
||||
/// Indexes into the list of styles for the containing text run, to find the style applicable
|
||||
/// to this character.
|
||||
pub style_index: u16,
|
||||
}
|
||||
|
||||
/// Whitespace class of a character.
|
||||
///
|
||||
/// All white space characters as defined
|
||||
/// [by Unicode](https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt) map to a variant of
|
||||
/// this enum. The variants are based on the various sets of white space as in
|
||||
/// [CSS Text 4][css-text-4].
|
||||
///
|
||||
/// A character maps to [`Whitespace::None`] if and only if that character's [`char::is_whitespace`]
|
||||
/// is `false`.
|
||||
///
|
||||
/// [css-text-4]: https://www.w3.org/TR/css-text-4/
|
||||
#[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug)]
|
||||
#[repr(u8)]
|
||||
pub enum Whitespace {
|
||||
/// Not white space.
|
||||
None = 0,
|
||||
|
||||
/// Standard space.
|
||||
Space = 1,
|
||||
|
||||
/// Non-breaking space (U+00A0).
|
||||
NoBreakSpace = 2,
|
||||
|
||||
/// Ideographic space (U+3000).
|
||||
///
|
||||
/// Note CSS Text 4 doesn't treat this space any differently from [`Self::OtherSpaceSeparator`],
|
||||
/// but some applications do.
|
||||
IdeographicSpace = 3,
|
||||
|
||||
/// The Unicode "space separators" (category `Zs`), except for the standard space, non-breaking
|
||||
/// space and ideographic space.
|
||||
///
|
||||
/// Applications may want to treat those three space separators differently from the general
|
||||
/// class of space separators.
|
||||
OtherSpaceSeparator = 4,
|
||||
|
||||
/// Horizontal tab.
|
||||
Tab = 5,
|
||||
|
||||
/// Newline (CR, LF, CRLF, LS, or PS).
|
||||
Newline = 6,
|
||||
|
||||
/// Vertical tab, form feed and next line.
|
||||
///
|
||||
/// These are Unicode `White_Space`, but CSS Text 4 § 4 says to treat them as visible glyphs.
|
||||
///
|
||||
/// Note [`Self::Tab`] and some of [`Self::Newline`] are also in the Unicode `Cc` category.
|
||||
/// There are also `Cc` characters that aren't `White_Space` (those would be
|
||||
/// [`Whitespace::None`]).
|
||||
ControlWhitespace = 7,
|
||||
// NOTE: if you grow these variants more than eight, ensure you also update the encoding in
|
||||
// `GraphemeFlags`.
|
||||
}
|
||||
|
||||
impl Whitespace {
|
||||
#[inline]
|
||||
pub(crate) const fn from_char(c: char) -> Self {
|
||||
// See https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt.
|
||||
match c {
|
||||
' ' => Self::Space,
|
||||
'\u{00A0}' => Self::NoBreakSpace,
|
||||
'\u{3000}' => Self::IdeographicSpace,
|
||||
// Ogham space mark, en quad through hair space, narrow no-break space, medium
|
||||
// mathematical space.
|
||||
'\u{1680}' | '\u{2000}'..='\u{200A}' | '\u{202F}' | '\u{205F}' => {
|
||||
Self::OtherSpaceSeparator
|
||||
}
|
||||
'\t' => Self::Tab,
|
||||
// Newline, carriage return, line separator, paragraph separator.
|
||||
'\n' | '\r' | '\u{2028}' | '\u{2029}' => Self::Newline,
|
||||
// Vertical tab, form feed, next line. These are `White_Space` that CSS says to render
|
||||
// as control characters.
|
||||
'\u{000b}' | '\u{000c}' | '\u{0085}' => Self::ControlWhitespace,
|
||||
_ => Self::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true for space or no break space.
|
||||
#[inline]
|
||||
pub fn is_space_or_nbsp(self) -> bool {
|
||||
matches!(self, Self::Space | Self::NoBreakSpace)
|
||||
}
|
||||
}
|
||||
|
||||
/// A font's coverage of a character cluster.
|
||||
///
|
||||
/// This is the fraction `covered / total` of characters covered by a font. Coverages are ordered by
|
||||
/// the value of the fraction (with `0 / 0` considered to be completely covered). Use, e.g.,
|
||||
/// [`Self::cmp`] to compare coverages.
|
||||
///
|
||||
/// In the unlikely event there are more characters than this in the character cluster, the counts
|
||||
/// are saturated to [`u8::MAX`].
|
||||
#[derive(Copy, Clone, Eq, Debug)]
|
||||
pub struct Coverage {
|
||||
/// The number of characters covered by the font.
|
||||
pub covered: u8,
|
||||
|
||||
/// The number of characters counting towards coverage.
|
||||
pub total: u8,
|
||||
}
|
||||
|
||||
impl Coverage {
|
||||
/// Zero coverage.
|
||||
///
|
||||
/// Useful, for example, as a starting "best coverage," in case you're searching for a
|
||||
/// best-covering font.
|
||||
pub const NONE: Self = Self {
|
||||
covered: 0,
|
||||
total: u8::MAX,
|
||||
};
|
||||
|
||||
/// Complete coverage, meaning all characters contributing to shaping are covered.
|
||||
///
|
||||
/// A coverage compares equal to `COMPLETE` exactly when it is complete, see also
|
||||
/// [`Self::is_complete`].
|
||||
pub const COMPLETE: Self = Self {
|
||||
covered: u8::MAX,
|
||||
total: u8::MAX,
|
||||
};
|
||||
|
||||
/// Returns `true` iff all characters are covered.
|
||||
#[inline(always)]
|
||||
#[must_use]
|
||||
pub fn is_complete(self) -> bool {
|
||||
self.covered >= self.total
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Coverage {
|
||||
#[inline]
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.cmp(other) == Ordering::Equal
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialOrd for Coverage {
|
||||
#[inline]
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
|
||||
impl Ord for Coverage {
|
||||
/// Coverages are ordered by the value of the fraction `covered / total`.
|
||||
#[inline]
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
// We check `is_complete` explicitly, such that fractions of `x / 0`, which are considered
|
||||
// complete, are ordered identically to other complete fractions. Cases other than those
|
||||
// with a denominator of 0 would have already been correctly ordered by value through the
|
||||
// cross-multiplication in the `(false, false)` arm, but note we now order all complete
|
||||
// fractions as `Ordering::Equal`.
|
||||
match (self.is_complete(), other.is_complete()) {
|
||||
(true, true) => Ordering::Equal,
|
||||
(true, false) => Ordering::Greater,
|
||||
(false, true) => Ordering::Less,
|
||||
(false, false) => (u16::from(self.covered) * u16::from(other.total))
|
||||
.cmp(&(u16::from(other.covered) * u16::from(self.total))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CharCluster {
|
||||
#[inline]
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.chars.clear();
|
||||
self.map_len = 0;
|
||||
self.start = 0;
|
||||
self.end = 0;
|
||||
self.force_normalize = false;
|
||||
self.comp.clear();
|
||||
self.decomp.clear();
|
||||
self.emoji_presentation_style = EmojiPresentationStyle::Default;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn len(&self) -> usize {
|
||||
self.chars.len()
|
||||
}
|
||||
|
||||
/// Returns the primary style index for the cluster.
|
||||
#[inline(always)]
|
||||
pub fn style_index(&self) -> u16 {
|
||||
self.chars[0].style_index
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn contributes_to_shaping(ch: char, analysis_data_sources: &AnalysisDataSources) -> bool {
|
||||
let props = analysis_data_sources.properties(ch);
|
||||
crate::analysis::contributes_to_shaping(props.general_category(), props.script())
|
||||
}
|
||||
|
||||
fn decomposed(&mut self, analysis_data_sources: &AnalysisDataSources) -> Option<&[Char]> {
|
||||
match self.decomp.state {
|
||||
FormState::Invalid => None,
|
||||
FormState::None => {
|
||||
self.decomp.state = FormState::Invalid;
|
||||
|
||||
// Only attempt pairwise normalization (1 <-> 2 characters)
|
||||
if self.chars.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let decomposer = analysis_data_sources.decomposing_normalizer();
|
||||
let decomp = decomposer.decompose(self.chars[0].ch);
|
||||
match decomp {
|
||||
Decomposed::Default | Decomposed::Singleton(_) => {
|
||||
return None;
|
||||
}
|
||||
Decomposed::Expansion(a, b) => {
|
||||
let mut copy = self.chars[0];
|
||||
copy.ch = a;
|
||||
copy.contributes_to_shaping =
|
||||
Self::contributes_to_shaping(a, analysis_data_sources);
|
||||
self.decomp.chars[0] = copy;
|
||||
|
||||
copy.ch = b;
|
||||
copy.contributes_to_shaping =
|
||||
Self::contributes_to_shaping(b, analysis_data_sources);
|
||||
self.decomp.chars[1] = copy;
|
||||
|
||||
self.decomp.len = 2;
|
||||
}
|
||||
}
|
||||
|
||||
self.decomp.state = FormState::Valid;
|
||||
self.decomp.setup();
|
||||
Some(self.decomp.chars())
|
||||
}
|
||||
FormState::Valid => Some(self.decomp.chars()),
|
||||
}
|
||||
}
|
||||
|
||||
fn composed(&mut self, analysis_data_sources: &AnalysisDataSources) -> Option<&[Char]> {
|
||||
match self.comp.state {
|
||||
FormState::Invalid => None,
|
||||
FormState::None => {
|
||||
self.comp.state = FormState::Invalid;
|
||||
|
||||
// Only attempt pairwise normalization (1 <-> 2 characters)
|
||||
if self.chars.len() != 2 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let composer = analysis_data_sources.composing_normalizer();
|
||||
let ch = composer.compose(self.chars[0].ch, self.chars[1].ch)?;
|
||||
|
||||
let mut copy = self.chars[0];
|
||||
copy.ch = ch;
|
||||
copy.contributes_to_shaping =
|
||||
Self::contributes_to_shaping(ch, analysis_data_sources);
|
||||
self.comp.chars[0] = copy;
|
||||
self.comp.len = 1;
|
||||
|
||||
self.comp.state = FormState::Valid;
|
||||
self.comp.setup();
|
||||
Some(self.comp.chars())
|
||||
}
|
||||
FormState::Valid => Some(self.comp.chars()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculate a candidate font's coverage of this character cluster.
|
||||
///
|
||||
/// The callback `covers` should return whether the character is covered by the font under
|
||||
/// consideration. The coverage returned is the best coverage of the character cluster's
|
||||
/// characters, or the characters of its normalized forms (see
|
||||
/// <https://www.unicode.org/reports/tr15/>).
|
||||
///
|
||||
/// Coverages are ordered by how much of the cluster they cover, see [`Coverage`]. Note
|
||||
/// [`Coverage::total`] may be different from the count of [`Self::chars`], and may also differ
|
||||
/// between subsequent calls due to returning the best coverage of either the original
|
||||
/// characters or one of the normalized forms.
|
||||
pub fn calculate_coverage(
|
||||
&mut self,
|
||||
covers: impl Fn(char) -> bool,
|
||||
analysis_data_sources: &AnalysisDataSources,
|
||||
) -> Coverage {
|
||||
let len = self.len();
|
||||
let mut best_coverage = Mapper {
|
||||
chars: &self.chars[..len],
|
||||
map_len: self.map_len,
|
||||
}
|
||||
.coverage(&covers);
|
||||
if best_coverage.is_complete() {
|
||||
return best_coverage;
|
||||
}
|
||||
if self.force_normalize && self.composed(analysis_data_sources).is_some() {
|
||||
let coverage = self.comp.coverage(&covers);
|
||||
if coverage > best_coverage {
|
||||
best_coverage = coverage;
|
||||
if coverage.is_complete() {
|
||||
return best_coverage;
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.decomposed(analysis_data_sources).is_some() {
|
||||
let coverage = self.decomp.coverage(&covers);
|
||||
if coverage > best_coverage {
|
||||
best_coverage = coverage;
|
||||
if coverage.is_complete() {
|
||||
return best_coverage;
|
||||
}
|
||||
}
|
||||
if !self.force_normalize && self.composed(analysis_data_sources).is_some() {
|
||||
let coverage = self.comp.coverage(&covers);
|
||||
if coverage > best_coverage {
|
||||
best_coverage = coverage;
|
||||
if coverage.is_complete() {
|
||||
return best_coverage;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
best_coverage
|
||||
}
|
||||
|
||||
/// Rebuilds `self` in-place using the existing allocation for the given grapheme.
|
||||
///
|
||||
/// `chars` must yield the grapheme's characters with associated analysis info, and style index.
|
||||
///
|
||||
/// `code_unit_offset_in_string` must be the byte offset of the grapheme's first character in the
|
||||
/// source string. When this method returns, its value is the byte offset just past the end of
|
||||
/// the grapheme in the source string.
|
||||
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
|
||||
#[inline]
|
||||
pub(crate) fn fill(
|
||||
&mut self,
|
||||
chars: impl Iterator<Item = (char, CharInfo, u16)>,
|
||||
code_unit_offset_in_string: &mut usize,
|
||||
) {
|
||||
// Reset cluster but keep allocation
|
||||
self.clear();
|
||||
|
||||
let mut force_normalize = false;
|
||||
let mut is_emoji = false;
|
||||
let mut map_len: u8 = 0;
|
||||
let mut emoji_dfa = EmojiDFA::new();
|
||||
let mut leading_is_emoji_presentation = false;
|
||||
let start = *code_unit_offset_in_string as u32;
|
||||
|
||||
for (i, (ch, info, style_index)) in chars.enumerate() {
|
||||
*code_unit_offset_in_string += ch.len_utf8();
|
||||
force_normalize |= info.force_normalize();
|
||||
|
||||
is_emoji |= info.is_emoji_or_pictograph();
|
||||
|
||||
let mut is_emoji_presentation_selector = false;
|
||||
|
||||
if is_emoji {
|
||||
if i == 0 {
|
||||
leading_is_emoji_presentation = info.is_emoji_presentation();
|
||||
}
|
||||
|
||||
let category = EmojiSegmentationCategory::from_codepoint(
|
||||
ch as u32,
|
||||
info.is_emoji(),
|
||||
info.is_emoji_presentation(),
|
||||
info.is_emoji_modifier(),
|
||||
info.is_emoji_modifier_base(),
|
||||
info.is_region_indicator(),
|
||||
);
|
||||
|
||||
is_emoji_presentation_selector = category.is_presentation_selector();
|
||||
|
||||
emoji_dfa.step_record(category);
|
||||
}
|
||||
|
||||
// Variation selectors don't impact font coverage, and are default ignorable.
|
||||
// TODO: Is there a default ignorable flag we should be using instead?
|
||||
let contributes_to_shaping =
|
||||
info.contributes_to_shaping() && !is_emoji_presentation_selector;
|
||||
if contributes_to_shaping {
|
||||
map_len = map_len.saturating_add(1);
|
||||
}
|
||||
|
||||
self.chars.push(Char {
|
||||
ch,
|
||||
contributes_to_shaping,
|
||||
style_index,
|
||||
is_control_character: info.is_control(),
|
||||
});
|
||||
}
|
||||
|
||||
// Finalize cluster metadata
|
||||
let end = *code_unit_offset_in_string as u32;
|
||||
self.map_len = map_len;
|
||||
self.start = start;
|
||||
self.end = end;
|
||||
self.force_normalize = force_normalize;
|
||||
|
||||
if is_emoji {
|
||||
self.emoji_presentation_style =
|
||||
emoji_dfa.presentation_style(leading_is_emoji_presentation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
enum FormState {
|
||||
None,
|
||||
Valid,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Form {
|
||||
chars: [Char; 2],
|
||||
len: u8,
|
||||
map_len: u8,
|
||||
state: FormState,
|
||||
}
|
||||
|
||||
impl Default for Form {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Form {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
chars: [Char::default(), Char::default()],
|
||||
len: 0,
|
||||
map_len: 0,
|
||||
state: FormState::None,
|
||||
}
|
||||
}
|
||||
|
||||
fn clear(&mut self) {
|
||||
self.chars = [Char::default(), Char::default()];
|
||||
self.len = 0;
|
||||
self.map_len = 0;
|
||||
self.state = FormState::None;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn chars(&self) -> &[Char] {
|
||||
&self.chars[..self.len as usize]
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
|
||||
fn setup(&mut self) {
|
||||
self.map_len = self
|
||||
.chars()
|
||||
.iter()
|
||||
.filter(|c| !c.is_control_character)
|
||||
.count() as u8;
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn coverage(&self, covers: &impl Fn(char) -> bool) -> Coverage {
|
||||
Mapper {
|
||||
chars: &self.chars[..self.len as usize],
|
||||
map_len: self.map_len,
|
||||
}
|
||||
.coverage(covers)
|
||||
}
|
||||
}
|
||||
|
||||
struct Mapper<'a> {
|
||||
chars: &'a [Char],
|
||||
map_len: u8,
|
||||
}
|
||||
|
||||
impl<'a> Mapper<'a> {
|
||||
/// Returns the coverage of characters contributing to shaping.
|
||||
fn coverage(&self, covers: &impl Fn(char) -> bool) -> Coverage {
|
||||
let mut mapped: u8 = 0;
|
||||
for c in self.chars.iter() {
|
||||
if c.contributes_to_shaping && covers(c.ch) {
|
||||
mapped = mapped.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
// If this assert is hit, some bookkeeping is wrong somewhere, but the returned coverage is
|
||||
// then simply considered to be complete.
|
||||
debug_assert!(
|
||||
mapped <= self.map_len,
|
||||
"Counted more covered characters than the number of characters we consider to be contributing."
|
||||
);
|
||||
|
||||
Coverage {
|
||||
covered: mapped,
|
||||
total: self.map_len,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::shape::Whitespace;
|
||||
|
||||
use super::Coverage;
|
||||
|
||||
#[test]
|
||||
fn ordering() {
|
||||
assert!(Coverage::NONE < Coverage::COMPLETE);
|
||||
|
||||
assert_eq!(
|
||||
Coverage {
|
||||
covered: 0,
|
||||
total: 0,
|
||||
},
|
||||
Coverage::COMPLETE
|
||||
);
|
||||
assert_eq!(
|
||||
Coverage {
|
||||
covered: 5,
|
||||
total: 5,
|
||||
},
|
||||
Coverage::COMPLETE
|
||||
);
|
||||
assert_eq!(
|
||||
Coverage {
|
||||
// `covered` is greater than `total`, which shouldn't be produced by us, but is
|
||||
// possible because `Coverage`'s fields are `pub`.
|
||||
covered: 3,
|
||||
total: 2,
|
||||
},
|
||||
Coverage::COMPLETE
|
||||
);
|
||||
assert_eq!(
|
||||
Coverage {
|
||||
covered: 255,
|
||||
total: 255,
|
||||
},
|
||||
Coverage::COMPLETE
|
||||
);
|
||||
|
||||
assert!(
|
||||
Coverage {
|
||||
covered: 4,
|
||||
total: 5,
|
||||
} > Coverage::NONE
|
||||
);
|
||||
assert!(
|
||||
Coverage {
|
||||
covered: 4,
|
||||
total: 5,
|
||||
} < Coverage::COMPLETE
|
||||
);
|
||||
|
||||
assert!(
|
||||
Coverage {
|
||||
covered: 254,
|
||||
total: 255,
|
||||
} > Coverage::NONE
|
||||
);
|
||||
assert!(
|
||||
Coverage {
|
||||
covered: 254,
|
||||
total: 255,
|
||||
} < Coverage::COMPLETE
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whitespace() {
|
||||
// Test all code points from `NUL` up to the last `White_Space` character as defined in
|
||||
// https://www.unicode.org/Public/UCD/latest/ucd/PropList.txt.
|
||||
for c in '\u{0000}'..='\u{3000}' {
|
||||
let ws = Whitespace::from_char(c);
|
||||
assert!(
|
||||
c.is_whitespace() && ws != Whitespace::None
|
||||
|| !c.is_whitespace() && ws == Whitespace::None,
|
||||
"`Whitespace` should encode exactly all of Unicode's `White_Space` characters."
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+393
@@ -0,0 +1,393 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
#![expect(missing_docs, reason = "Deferred")]
|
||||
|
||||
use core::ops::Range;
|
||||
|
||||
use crate::shape::Whitespace;
|
||||
|
||||
/// Data for a single character of the source text.
|
||||
///
|
||||
/// This is a character in the Unicode scalar value sense, i.e., it corresponds to a single `char`
|
||||
/// of the source text.
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub struct Character {
|
||||
pub text_byte_start: u32,
|
||||
/// Style index for this character.
|
||||
pub style_index: u16,
|
||||
/// The whitespace class of this character.
|
||||
pub whitespace: Whitespace,
|
||||
/// Properties of this character.
|
||||
pub flags: CharacterFlags,
|
||||
/// Whether this character begins a grapheme cluster.
|
||||
pub grapheme_start: bool,
|
||||
}
|
||||
|
||||
impl Character {
|
||||
/// The byte range of this character in the source text.
|
||||
#[inline(always)]
|
||||
pub fn text_byte_range(&self) -> Range<usize> {
|
||||
self.text_byte_start as usize..self.text_byte_start as usize + self.flags.len_utf8()
|
||||
}
|
||||
|
||||
/// Returns if this character is any whitespace.
|
||||
#[inline(always)]
|
||||
pub fn is_whitespace(self) -> bool {
|
||||
self.whitespace != Whitespace::None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct ShapedClusterFlags(u16);
|
||||
|
||||
impl ShapedClusterFlags {
|
||||
const GLYPH_LEN_MASK: u16 = 0x00FF;
|
||||
const INLINE_GLYPH: u16 = 1 << 8;
|
||||
const GRAPHEME_START: u16 = 1 << 9;
|
||||
const SAFE_TO_BREAK_BEFORE: u16 = 1 << 10;
|
||||
/// Whether a soft wrap opportunity exists before the cluster's first character.
|
||||
const SOFT_WRAP_BEFORE: u16 = 1 << 11;
|
||||
/// [`Whitespace`] class of the cluster's first character (3 bits).
|
||||
const WHITESPACE_SHIFT: u16 = 12;
|
||||
const WHITESPACE_MASK: u16 = 0b111 << Self::WHITESPACE_SHIFT;
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) const fn new(glyph_len: u8) -> Self {
|
||||
Self(glyph_len as u16)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) const fn with_inline_glyph(mut self, set: bool) -> Self {
|
||||
self.0 = self.0 & !Self::INLINE_GLYPH | if set { Self::INLINE_GLYPH } else { 0 };
|
||||
self
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) const fn with_grapheme_start(mut self, set: bool) -> Self {
|
||||
self.0 = self.0 & !Self::GRAPHEME_START | if set { Self::GRAPHEME_START } else { 0 };
|
||||
self
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) const fn with_safe_to_break_before(mut self, set: bool) -> Self {
|
||||
self.0 =
|
||||
self.0 & !Self::SAFE_TO_BREAK_BEFORE | if set { Self::SAFE_TO_BREAK_BEFORE } else { 0 };
|
||||
self
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) const fn with_first_char(
|
||||
mut self,
|
||||
soft_wrap_opportunity: bool,
|
||||
whitespace: Whitespace,
|
||||
) -> Self {
|
||||
self.0 = self.0 & !(Self::SOFT_WRAP_BEFORE | Self::WHITESPACE_MASK)
|
||||
| if soft_wrap_opportunity {
|
||||
Self::SOFT_WRAP_BEFORE
|
||||
} else {
|
||||
0
|
||||
}
|
||||
| ((whitespace as u16) << Self::WHITESPACE_SHIFT);
|
||||
self
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
const fn is_soft_wrap_opportunity_before(self) -> bool {
|
||||
self.0 & Self::SOFT_WRAP_BEFORE != 0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
const fn whitespace(self) -> Whitespace {
|
||||
match (self.0 & Self::WHITESPACE_MASK) >> Self::WHITESPACE_SHIFT {
|
||||
1 => Whitespace::Space,
|
||||
2 => Whitespace::NoBreakSpace,
|
||||
3 => Whitespace::IdeographicSpace,
|
||||
4 => Whitespace::OtherSpaceSeparator,
|
||||
5 => Whitespace::Tab,
|
||||
6 => Whitespace::Newline,
|
||||
7 => Whitespace::ControlWhitespace,
|
||||
_ => Whitespace::None,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
const fn glyph_len(self) -> u8 {
|
||||
(self.0 & Self::GLYPH_LEN_MASK) as u8
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
const fn has_inline_glyph(self) -> bool {
|
||||
self.0 & Self::INLINE_GLYPH != 0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
const fn is_grapheme_start(self) -> bool {
|
||||
self.0 & Self::GRAPHEME_START != 0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
const fn is_safe_to_break_before(self) -> bool {
|
||||
self.0 & Self::SAFE_TO_BREAK_BEFORE != 0
|
||||
}
|
||||
}
|
||||
|
||||
/// A span of characters and the glyphs they shaped into.
|
||||
///
|
||||
/// Shaping may reorder, compose, decompose, etc.; there is no finer-grained correspondence between
|
||||
/// characters and glyphs. For example, a base letter with a combining mark may shape into a single
|
||||
/// glyph, a single character may shape into multiple glyphs, and a ligature may combine multiple
|
||||
/// characters into shared glyphs.
|
||||
///
|
||||
/// Shaped cluster boundaries are not necessarily [`Grapheme`][crate::Grapheme] boundaries. The
|
||||
/// shared boundaries are encoded by [`Atom`][crate::Atom]s.
|
||||
///
|
||||
/// For more information about clusters, see [HarfBuzz's documentation][harfbuzz].
|
||||
///
|
||||
/// [harfbuzz]: https://harfbuzz.github.io/working-with-harfbuzz-clusters.html
|
||||
#[derive(Copy, Clone, Debug, PartialEq)]
|
||||
pub struct ShapedCluster {
|
||||
/// The characters of this cluster, as a range into
|
||||
/// [`ShapedText::characters`](crate::ShapedText::characters).
|
||||
//
|
||||
// TODO: this currently stores the full range, but perhaps we could store only the start index.
|
||||
// See <https://github.com/linebender/parley/pull/715#discussion_r3693794119>.
|
||||
pub(crate) chars_range: (u32, u32),
|
||||
|
||||
/// Style index for this cluster.
|
||||
pub style_index: u16,
|
||||
|
||||
/// The index into the glyph array where this cluster's glyphs start.
|
||||
///
|
||||
/// If [`Self::has_inline_glyph`] is `true`, this is a glyph identifier instead. For more, see
|
||||
/// the documentation on that method.
|
||||
pub glyph_offset: u32,
|
||||
|
||||
// /// Number of glyphs in this cluster (0xFF = single glyph stored inline)
|
||||
// pub glyph_len: u8,
|
||||
pub(crate) flags: ShapedClusterFlags,
|
||||
|
||||
/// Advance width for this cluster
|
||||
pub advance: f32,
|
||||
}
|
||||
|
||||
impl ShapedCluster {
|
||||
/// The characters of this cluster, as a range into [`ShapedText::characters`](crate::ShapedText::characters).
|
||||
///
|
||||
/// This is also the range of character positions in the source text (in the Unicode scalar
|
||||
/// value sense).
|
||||
#[inline(always)]
|
||||
pub fn chars_range(&self) -> Range<u32> {
|
||||
self.chars_range.0..self.chars_range.1
|
||||
}
|
||||
|
||||
/// The number of glyphs of this cluster.
|
||||
#[inline(always)]
|
||||
pub fn glyph_len(self) -> u8 {
|
||||
if self.has_inline_glyph() {
|
||||
1
|
||||
} else {
|
||||
self.flags.glyph_len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this cluster's glyph is stored inline in [`Self::glyph_offset`].
|
||||
///
|
||||
/// This is only possible if [`Self::glyph_len`] is one, and the glyph has no offset.
|
||||
/// [`Self::glyph_offset`] then encodes the glyph identifier rather than an index into the glyph
|
||||
/// array. The glyph's advance then is this cluster's advance.
|
||||
#[inline(always)]
|
||||
pub fn has_inline_glyph(self) -> bool {
|
||||
self.flags.has_inline_glyph()
|
||||
}
|
||||
|
||||
/// Whether this shaped cluster's logical start also starts a grapheme.
|
||||
#[inline(always)]
|
||||
pub fn is_grapheme_start(self) -> bool {
|
||||
self.flags.is_grapheme_start()
|
||||
}
|
||||
|
||||
/// Whether breaking logically before this shaped cluster requires reshaping.
|
||||
///
|
||||
/// Note that if this shaped cluster does not start a grapheme (see
|
||||
/// [`Self::is_grapheme_start`]), you have to reshape regardless of this value.
|
||||
#[inline(always)]
|
||||
pub fn is_safe_to_break_before(self) -> bool {
|
||||
self.flags.is_safe_to_break_before()
|
||||
}
|
||||
|
||||
/// Whether a soft wrap opportunity exists before this cluster's first character.
|
||||
///
|
||||
/// This is [`Character::flags`]' soft-wrap bit of the first character of [`Self::chars_range`],
|
||||
/// cached here so that measuring text does not need to touch the character array.
|
||||
#[inline(always)]
|
||||
pub fn is_soft_wrap_opportunity_before(self) -> bool {
|
||||
self.flags.is_soft_wrap_opportunity_before()
|
||||
}
|
||||
|
||||
/// The [`Whitespace`] class of this cluster's first character.
|
||||
///
|
||||
/// See [`Self::is_soft_wrap_opportunity_before`].
|
||||
#[inline(always)]
|
||||
pub fn whitespace(self) -> Whitespace {
|
||||
self.flags.whitespace()
|
||||
}
|
||||
|
||||
/// The number of characters in this cluster.
|
||||
#[inline(always)]
|
||||
pub fn char_len(self) -> u32 {
|
||||
self.chars_range.1 - self.chars_range.0
|
||||
}
|
||||
|
||||
/// The number of graphemes this cluster overlaps.
|
||||
pub(crate) fn graphemes_overlapped(&self, characters: &[Character]) -> u32 {
|
||||
let start = self.chars_range().start as usize + 1;
|
||||
let end = self.chars_range().end as usize;
|
||||
let mut graphemes = 1;
|
||||
for character in &characters[start..end] {
|
||||
graphemes += u32::from(character.grapheme_start);
|
||||
}
|
||||
graphemes
|
||||
}
|
||||
}
|
||||
|
||||
/// Properties of a [`Character`].
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CharacterFlags(u8);
|
||||
|
||||
impl CharacterFlags {
|
||||
/// Bits 0..2: the UTF-8 length of the source character minus one.
|
||||
///
|
||||
/// (Note the UTF-8 length of any character is between 1 and 4 inclusive.)
|
||||
const LEN_UTF8_MASK: u8 = 0b11;
|
||||
/// Whether the source character is an emoji.
|
||||
const EMOJI: u8 = 1 << 2;
|
||||
/// Whether there is a word boundary before the character.
|
||||
const WORD_BOUNDARY: u8 = 1 << 3;
|
||||
/// Whether there is a soft wrap opportunity before the character.
|
||||
const SOFT_WRAP_OPPORTUNITY: u8 = 1 << 4;
|
||||
|
||||
#[inline(always)]
|
||||
pub fn new(source_char: char, is_word_boundary: bool, is_soft_wrap_opportunity: bool) -> Self {
|
||||
// TODO: Defer to ICU4X properties (see: https://docs.rs/icu/latest/icu/properties/props/struct.Emoji.html).
|
||||
let is_emoji = matches!(source_char as u32, 0x1F600..=0x1F64F | 0x1F300..=0x1F5FF | 0x1F680..=0x1F6FF | 0x2600..=0x26FF | 0x2700..=0x27BF);
|
||||
#[expect(
|
||||
clippy::cast_possible_truncation,
|
||||
reason = "`len_utf8` is between 1 and 4 inclusive"
|
||||
)]
|
||||
let len_utf8 = source_char.len_utf8() as u8;
|
||||
Self(
|
||||
(len_utf8 - 1)
|
||||
| if is_emoji { Self::EMOJI } else { 0 }
|
||||
| if is_word_boundary {
|
||||
Self::WORD_BOUNDARY
|
||||
} else {
|
||||
0
|
||||
}
|
||||
| if is_soft_wrap_opportunity {
|
||||
Self::SOFT_WRAP_OPPORTUNITY
|
||||
} else {
|
||||
0
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether there is a soft wrap opportunity before this character ([UAX #14][line-breaking]).
|
||||
///
|
||||
/// Note mandatory breaks (like `\n`) are encoded as [`Whitespace`].
|
||||
///
|
||||
/// [line-breaking]: https://www.unicode.org/reports/tr14/
|
||||
#[inline(always)]
|
||||
pub fn is_soft_wrap_opportunity(self) -> bool {
|
||||
self.0 & Self::SOFT_WRAP_OPPORTUNITY != 0
|
||||
}
|
||||
|
||||
/// Returns if there is a word boundary before the character.
|
||||
#[inline(always)]
|
||||
pub fn is_word_boundary(self) -> bool {
|
||||
self.0 & Self::WORD_BOUNDARY != 0
|
||||
}
|
||||
|
||||
/// Returns if the character is an emoji.
|
||||
#[inline(always)]
|
||||
pub fn is_emoji(self) -> bool {
|
||||
self.0 & Self::EMOJI != 0
|
||||
}
|
||||
|
||||
/// Returns the number of bytes the source character would need if encoded in UTF-8.
|
||||
///
|
||||
/// That number of bytes is always between 1 and 4, inclusive.
|
||||
#[inline(always)]
|
||||
pub fn len_utf8(self) -> usize {
|
||||
(self.0 & Self::LEN_UTF8_MASK) as usize + 1
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn character_flags() {
|
||||
for (ch, len, emoji) in [
|
||||
('a', 1, false),
|
||||
(' ', 1, false),
|
||||
('\t', 1, false),
|
||||
('\r', 1, false),
|
||||
('\n', 1, false),
|
||||
('\u{00e9}', 2, false),
|
||||
('\u{2028}', 3, false),
|
||||
('\u{2600}', 3, true),
|
||||
('\u{1F600}', 4, true),
|
||||
] {
|
||||
for (is_word_boundary, is_soft_wrap_opportunity) in
|
||||
[(false, false), (true, false), (false, true), (true, true)]
|
||||
{
|
||||
let flags = CharacterFlags::new(ch, is_word_boundary, is_soft_wrap_opportunity);
|
||||
assert_eq!(flags.len_utf8(), len, "{ch:?}");
|
||||
assert_eq!(flags.is_emoji(), emoji, "{ch:?}");
|
||||
assert_eq!(flags.is_word_boundary(), is_word_boundary, "{ch:?}");
|
||||
assert_eq!(
|
||||
flags.is_soft_wrap_opportunity(),
|
||||
is_soft_wrap_opportunity,
|
||||
"{ch:?}"
|
||||
);
|
||||
}
|
||||
|
||||
let character = Character {
|
||||
text_byte_start: 3,
|
||||
style_index: 7,
|
||||
whitespace: Whitespace::from_char(ch),
|
||||
flags: CharacterFlags::new(ch, false, false),
|
||||
grapheme_start: true,
|
||||
};
|
||||
assert_eq!(character.text_byte_range(), 3..3 + len, "{ch:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_char_flags_round_trip() {
|
||||
let soft_wraps = [false, true];
|
||||
let whitespaces = [
|
||||
Whitespace::None,
|
||||
Whitespace::Space,
|
||||
Whitespace::NoBreakSpace,
|
||||
Whitespace::IdeographicSpace,
|
||||
Whitespace::OtherSpaceSeparator,
|
||||
Whitespace::Tab,
|
||||
Whitespace::Newline,
|
||||
Whitespace::ControlWhitespace,
|
||||
];
|
||||
for soft_wrap in soft_wraps {
|
||||
for whitespace in whitespaces {
|
||||
let flags = ShapedClusterFlags::new(3)
|
||||
.with_grapheme_start(true)
|
||||
.with_first_char(soft_wrap, whitespace);
|
||||
assert_eq!(flags.is_soft_wrap_opportunity_before(), soft_wrap);
|
||||
assert_eq!(flags.whitespace(), whitespace);
|
||||
assert_eq!(flags.glyph_len(), 3);
|
||||
assert!(flags.is_grapheme_start());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Text shaping utilities.
|
||||
|
||||
pub(crate) mod atom;
|
||||
mod cache;
|
||||
mod cluster;
|
||||
mod data;
|
||||
pub(crate) mod shaped_text;
|
||||
pub(crate) mod shaper;
|
||||
|
||||
pub use cluster::{Char, CharCluster, Coverage, SourceRange, Whitespace};
|
||||
pub use data::{Character, CharacterFlags, ShapedCluster};
|
||||
|
||||
pub(crate) use data::ShapedClusterFlags;
|
||||
+859
@@ -0,0 +1,859 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Data structures to store the result of shaping.
|
||||
|
||||
use core::ops::Range;
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use parlance::{BidiLevel, NormalizedCoord};
|
||||
use skrifa::MetadataProvider;
|
||||
|
||||
use crate::{
|
||||
CharInfo, FontInstance, Glyph,
|
||||
itemize::{Segment, TextRange},
|
||||
};
|
||||
|
||||
use super::{
|
||||
Character, CharacterFlags, ShapedCluster, ShapedClusterFlags, Whitespace, atom::ShapedSlice,
|
||||
shaper::ShapeOptions,
|
||||
};
|
||||
|
||||
/// Metrics that apply to the glyphs of a font.
|
||||
///
|
||||
/// These metrics are scaled by the font size.
|
||||
///
|
||||
/// The `underline_*` and `strikethrough_*` fields are derived if not set by the font.
|
||||
///
|
||||
// TODO: Perhaps it'd be nicer if we exposed unscaled metrics (design units) instead. This currently
|
||||
// just follows what `parley` used to do in its `RunMetrics`. If we go unscaled, we should then
|
||||
// either also store units per em, or em-normalize the values like CSS does.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct FontMetrics {
|
||||
/// Distance from the baseline to the top of the alignment box.
|
||||
pub ascent: f32,
|
||||
/// Distance from the baseline to the bottom of the alignment box.
|
||||
pub descent: f32,
|
||||
/// Recommended additional spacing between lines.
|
||||
pub leading: f32,
|
||||
/// Offset of the top of underline decoration from the baseline.
|
||||
pub underline_offset: f32,
|
||||
/// Thickness of the underline decoration.
|
||||
pub underline_size: f32,
|
||||
/// Offset of the top of strikethrough decoration from the baseline.
|
||||
pub strikethrough_offset: f32,
|
||||
/// Thickness of the strikethrough decoration.
|
||||
pub strikethrough_size: f32,
|
||||
/// Distance from the baseline to the top of a typical English capital.
|
||||
pub cap_height: Option<f32>,
|
||||
/// Distance from the baseline to the top of the lowercase "x" or
|
||||
/// similar character.
|
||||
pub x_height: Option<f32>,
|
||||
}
|
||||
|
||||
impl FontMetrics {
|
||||
/// Metrics to use when no font is available at all.
|
||||
///
|
||||
/// These roughly match common Latin fonts, so that a layout without fonts still has plausible
|
||||
/// line heights.
|
||||
pub const fn fallback(font_size: f32) -> Self {
|
||||
Self {
|
||||
ascent: font_size * 0.8,
|
||||
descent: font_size * 0.2,
|
||||
leading: 0.,
|
||||
underline_offset: 0.,
|
||||
underline_size: 0.,
|
||||
strikethrough_offset: 0.,
|
||||
strikethrough_size: 0.,
|
||||
cap_height: None,
|
||||
x_height: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute the metrics of `font` at `font_size`, positioned at the variable font location
|
||||
/// given by the `synthesis` and `variations` axis settings.
|
||||
///
|
||||
/// Returns `None` if the font data cannot be parsed.
|
||||
pub fn from_font_instance(
|
||||
font: &FontInstance,
|
||||
font_size: f32,
|
||||
variations: &[parlance::FontVariation],
|
||||
) -> Option<Self> {
|
||||
// A style's metrics depend on its font instance, size and variations alone; a style
|
||||
// table asks for the same few again in every layout (Rune: vendor/parley_engine.patch).
|
||||
#[cfg(feature = "std")]
|
||||
{
|
||||
type Memo = Vec<(u64, u32, fontique::Synthesis, u32, Vec<parlance::FontVariation>, Option<FontMetrics>)>;
|
||||
std::thread_local! {
|
||||
static MEMO: core::cell::RefCell<Memo> = const { core::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
let (id, index, size) = (font.font.data.id(), font.font.index, font_size.to_bits());
|
||||
let found = MEMO.with_borrow(|memo| {
|
||||
memo.iter()
|
||||
.find(|m| m.0 == id && m.1 == index && m.2 == font.synthesis && m.3 == size && m.4 == variations)
|
||||
.map(|m| m.5)
|
||||
});
|
||||
if let Some(metrics) = found {
|
||||
return metrics;
|
||||
}
|
||||
let metrics = Self::compute_from_font_instance(font, font_size, variations);
|
||||
MEMO.with_borrow_mut(|memo| {
|
||||
if memo.len() >= 64 {
|
||||
memo.remove(0);
|
||||
}
|
||||
memo.push((id, index, font.synthesis, size, variations.to_vec(), metrics));
|
||||
});
|
||||
return metrics;
|
||||
}
|
||||
Self::compute_from_font_instance(font, font_size, variations)
|
||||
}
|
||||
|
||||
fn compute_from_font_instance(
|
||||
font: &FontInstance,
|
||||
font_size: f32,
|
||||
variations: &[parlance::FontVariation],
|
||||
) -> Option<Self> {
|
||||
let font_ref =
|
||||
skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).ok()?;
|
||||
let location = font_ref.axes().location(
|
||||
font.synthesis
|
||||
.variation_settings()
|
||||
.iter()
|
||||
.map(|(tag, value)| (skrifa::Tag::new(&tag.to_be_bytes()), *value))
|
||||
.chain(
|
||||
variations
|
||||
.iter()
|
||||
.map(|v| (skrifa::Tag::new(&v.tag.to_bytes()), v.value)),
|
||||
),
|
||||
);
|
||||
Some(Self::from_skrifa_metrics(
|
||||
&skrifa::metrics::Metrics::new(
|
||||
&font_ref,
|
||||
skrifa::prelude::Size::new(font_size),
|
||||
&location,
|
||||
),
|
||||
font_size,
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn from_skrifa_metrics(metrics: &skrifa::metrics::Metrics, font_size: f32) -> Self {
|
||||
// Default values from HarfBuzz: https://github.com/harfbuzz/harfbuzz/blob/12ee77ee00514c442bcd28f9aa9d56b708c37382/src/hb-ot-metrics.cc#L355-L372
|
||||
let fallback_decoration_size = font_size / 18.0;
|
||||
|
||||
let (underline_offset, underline_size) = if let Some(underline) = metrics.underline {
|
||||
(underline.offset, underline.thickness)
|
||||
} else {
|
||||
(-fallback_decoration_size, fallback_decoration_size)
|
||||
};
|
||||
let (strikethrough_offset, strikethrough_size) = if let Some(strikeout) = metrics.strikeout
|
||||
{
|
||||
(strikeout.offset, strikeout.thickness)
|
||||
} else {
|
||||
(metrics.ascent / 2.0, fallback_decoration_size)
|
||||
};
|
||||
|
||||
Self {
|
||||
ascent: metrics.ascent,
|
||||
descent: -metrics.descent,
|
||||
leading: metrics.leading,
|
||||
underline_offset,
|
||||
underline_size,
|
||||
strikethrough_offset,
|
||||
strikethrough_size,
|
||||
x_height: metrics.x_height,
|
||||
cap_height: metrics.cap_height,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of shaping.
|
||||
///
|
||||
/// After [analyzing][crate::Analysis] your text, [shape the text][crate::Shaper::shape_text],
|
||||
/// writing the result into this [`ShapedText`]. This then holds your shaped paragraph of text.
|
||||
///
|
||||
/// This shaped text holds spans of the source text's characters that were shaped into
|
||||
/// [`ShapedCluster`]s. Note that the boundaries of shaped clusters and graphemes need not coincide;
|
||||
/// see [`ShapedCluster`]s documentation for more information.
|
||||
///
|
||||
/// Use [`Self::run_slice`] to get a run's [`ShapedSlice`]. From there, you can interact with slices
|
||||
/// of shaped text, such as walking [atoms](crate::Atom) (e.g., [`ShapedSlice::atoms_start`]) and
|
||||
/// [graphemes](crate::Grapheme) (e.g., [`ShapedSlice::graphemes_start`]).
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ShapedText {
|
||||
runs: Vec<ShapedRun>,
|
||||
characters: Vec<Character>,
|
||||
shaped_clusters: Vec<ShapedCluster>,
|
||||
glyphs: Vec<Glyph>,
|
||||
fonts: Vec<FontInstance>,
|
||||
normalized_coords: Vec<NormalizedCoord>,
|
||||
}
|
||||
|
||||
impl ShapedText {
|
||||
/// Create a reusable [`ShapedText`].
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Reserve capacity for at least `additional_chars` more characters.
|
||||
///
|
||||
/// This speculatively reserves capacity for `additional_chars` more clusters and glyphs.
|
||||
#[inline]
|
||||
pub(crate) fn reserve(&mut self, additional_chars: usize) {
|
||||
self.characters.reserve(additional_chars);
|
||||
self.shaped_clusters.reserve(additional_chars);
|
||||
self.glyphs.reserve(additional_chars);
|
||||
}
|
||||
|
||||
/// Clear the result while retaining capacity.
|
||||
#[inline]
|
||||
pub fn clear(&mut self) {
|
||||
self.runs.clear();
|
||||
self.characters.clear();
|
||||
self.shaped_clusters.clear();
|
||||
self.glyphs.clear();
|
||||
self.fonts.clear();
|
||||
self.normalized_coords.clear();
|
||||
}
|
||||
|
||||
/// Get a [`ShapedSlice`] of the run at `run_index`.
|
||||
pub fn run_slice(&self, run_index: u32) -> ShapedSlice<'_> {
|
||||
let run = &self.runs[run_index as usize];
|
||||
ShapedSlice {
|
||||
characters: &self.characters,
|
||||
|
||||
shaped_clusters: &self.shaped_clusters,
|
||||
glyphs: &self.glyphs,
|
||||
|
||||
clusters: (
|
||||
run.shaped_clusters_range.start,
|
||||
run.shaped_clusters_range.end,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The shaped runs.
|
||||
///
|
||||
/// Each run contains glyphs that can be rendered with a single font.
|
||||
#[inline(always)]
|
||||
pub fn runs(&self) -> &[ShapedRun] {
|
||||
&self.runs
|
||||
}
|
||||
|
||||
/// Escape hatch for `parley` tests that remap style indices to check whether layouts are
|
||||
/// otherwise identical. This is not for public consumption!
|
||||
#[doc(hidden)]
|
||||
#[inline(always)]
|
||||
pub fn remap_styles(&mut self, remap: &[u16]) {
|
||||
for character in self.characters.iter_mut() {
|
||||
character.style_index = remap[character.style_index as usize];
|
||||
}
|
||||
for shaped_cluster in self.shaped_clusters.iter_mut() {
|
||||
shaped_cluster.style_index = remap[shaped_cluster.style_index as usize];
|
||||
}
|
||||
}
|
||||
|
||||
/// The character data of the text, in logical order.
|
||||
///
|
||||
/// [`ShapedRun::characters_range`] indexes into this. The nth [`Character`] corresponds exactly
|
||||
/// to the nth character of the source text (in the Unicode scalar value sense). This contains
|
||||
/// every character of the source text unless shaping was aborted due to
|
||||
/// [`FontSelector::select_font`][crate::FontSelector::select_font] failing to return a font.
|
||||
#[inline(always)]
|
||||
pub fn characters(&self) -> &[Character] {
|
||||
&self.characters
|
||||
}
|
||||
|
||||
/// The shaped clusters.
|
||||
///
|
||||
/// [`ShapedRun::shaped_clusters_range`] indexes into this.
|
||||
#[inline(always)]
|
||||
pub fn shaped_clusters(&self) -> &[ShapedCluster] {
|
||||
&self.shaped_clusters
|
||||
}
|
||||
|
||||
/// The shaped glyphs.
|
||||
///
|
||||
/// [`ShapedRun::glyphs_range`] indexes into this.
|
||||
#[inline(always)]
|
||||
pub fn glyphs(&self) -> &[Glyph] {
|
||||
&self.glyphs
|
||||
}
|
||||
|
||||
/// The fonts.
|
||||
///
|
||||
/// [`ShapedRun::font_index`] indexes into this.
|
||||
#[inline(always)]
|
||||
pub fn fonts(&self) -> &[FontInstance] {
|
||||
&self.fonts
|
||||
}
|
||||
|
||||
/// The normalized font coordinates used by runs in this shaped text.
|
||||
///
|
||||
/// [`ShapedRun::normalized_coords_range`] splits this into per-run slices.
|
||||
#[inline(always)]
|
||||
pub fn normalized_coords(&self) -> &[NormalizedCoord] {
|
||||
&self.normalized_coords
|
||||
}
|
||||
|
||||
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
|
||||
pub(crate) fn push_run(
|
||||
&mut self,
|
||||
text: &str,
|
||||
range: TextRange,
|
||||
segment: &Segment,
|
||||
options: &ShapeOptions<'_>,
|
||||
char_info: &[CharInfo],
|
||||
char_style_indices: &[u16],
|
||||
font: &FontInstance,
|
||||
glyph_infos: &[harfrust::GlyphInfo],
|
||||
glyph_positions: &[harfrust::GlyphPosition],
|
||||
normalized_coords: &[harfrust::NormalizedCoord],
|
||||
(font_metrics, units_per_em): (FontMetrics, f32),
|
||||
) {
|
||||
debug_assert_eq!(
|
||||
range.char_range.len(),
|
||||
text[range.byte_range.clone()].chars().count(),
|
||||
"The claimed character range and the text's covered byte range should agree"
|
||||
);
|
||||
|
||||
let normalized_coords_range = {
|
||||
let start = self.normalized_coords.len();
|
||||
self.normalized_coords.extend(
|
||||
normalized_coords
|
||||
.iter()
|
||||
.map(|c| NormalizedCoord::from_bits(c.to_bits())),
|
||||
);
|
||||
start..self.normalized_coords.len()
|
||||
};
|
||||
|
||||
let font_index = self
|
||||
.fonts
|
||||
.iter()
|
||||
.position(|f| f == font)
|
||||
.unwrap_or_else(|| {
|
||||
let index = self.fonts.len();
|
||||
self.fonts.push(font.clone());
|
||||
index
|
||||
});
|
||||
|
||||
// `HarfRust` returns glyphs in visual order, so we need to process them as such while
|
||||
// maintaining logical ordering of clusters.
|
||||
|
||||
let scale_factor = options.font_size / units_per_em;
|
||||
let shaped_clusters_start = self.shaped_clusters.len();
|
||||
|
||||
// Push all characters.
|
||||
let characters_start = self.characters.len();
|
||||
for (((byte_offset, ch), info), style_index) in text[range.byte_range.clone()]
|
||||
.char_indices()
|
||||
.zip(&char_info[range.char_range.clone()])
|
||||
.zip(&char_style_indices[range.char_range.clone()])
|
||||
{
|
||||
self.characters.push(Character {
|
||||
text_byte_start: (range.byte_range.start + byte_offset) as u32,
|
||||
style_index: *style_index,
|
||||
whitespace: Whitespace::from_char(ch),
|
||||
flags: CharacterFlags::new(
|
||||
ch,
|
||||
info.is_word_boundary(),
|
||||
info.is_soft_wrap_opportunity(),
|
||||
),
|
||||
grapheme_start: info.is_grapheme_start(),
|
||||
});
|
||||
}
|
||||
// TODO: we force a grapheme break at the start of the run, as itemization could have split
|
||||
// a grapheme into two. Ideally, grapheme segmentation should be performed after
|
||||
// itemization, at which case this will always be true.
|
||||
self.characters[characters_start].grapheme_start = true;
|
||||
|
||||
let glyphs_start = self.glyphs.len();
|
||||
if segment.bidi_level.is_ltr() {
|
||||
process_shaped_clusters(
|
||||
&mut self.shaped_clusters,
|
||||
&mut self.glyphs,
|
||||
scale_factor,
|
||||
glyph_infos.iter(),
|
||||
glyph_positions.iter(),
|
||||
&self.characters,
|
||||
characters_start,
|
||||
);
|
||||
} else {
|
||||
process_shaped_clusters(
|
||||
&mut self.shaped_clusters,
|
||||
&mut self.glyphs,
|
||||
scale_factor,
|
||||
glyph_infos.iter().rev(),
|
||||
glyph_positions.iter().rev(),
|
||||
&self.characters,
|
||||
characters_start,
|
||||
);
|
||||
// Reverse each cluster's glyphs, such that they are in paint order.
|
||||
//
|
||||
// TODO: could this become a single `reverse` over the range?
|
||||
for cluster in &self.shaped_clusters[shaped_clusters_start..] {
|
||||
if !cluster.has_inline_glyph() && cluster.glyph_len() > 1 {
|
||||
let start = cluster.glyph_offset as usize;
|
||||
self.glyphs[start..start + cluster.glyph_len() as usize].reverse();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let shaped_clusters_range = shaped_clusters_start as u32..self.shaped_clusters.len() as u32;
|
||||
let run_advance = self.shaped_clusters[shaped_clusters_start..]
|
||||
.iter()
|
||||
.map(|cluster| cluster.advance)
|
||||
.sum();
|
||||
|
||||
self.runs.push(ShapedRun {
|
||||
range,
|
||||
font_size: options.font_size,
|
||||
font_index,
|
||||
characters_range: characters_start as u32..self.characters.len() as u32,
|
||||
shaped_clusters_range,
|
||||
glyphs_range: glyphs_start..self.glyphs.len(),
|
||||
normalized_coords_range,
|
||||
bidi_level: segment.bidi_level,
|
||||
advance: run_advance,
|
||||
font_metrics,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// One shaped run, belonging to a [`ShapedText`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ShapedRun {
|
||||
/// The range of text this run corresponds to.
|
||||
pub range: TextRange,
|
||||
/// Font size.
|
||||
pub font_size: f32,
|
||||
/// This run's font, as an index into [`ShapedText::fonts`].
|
||||
//
|
||||
// Note: We carry the font index instead of having `ShapedRun` carry `Arc<FontInstance>`,
|
||||
// meaning `ShapedRun` could become `Copy` once we have access to `core::range::Range`.
|
||||
pub font_index: usize,
|
||||
/// This run's characters, as a range into [`ShapedText::characters`].
|
||||
pub characters_range: Range<u32>,
|
||||
/// This run's shaped clusters, as a range into [`ShapedText::shaped_clusters`].
|
||||
pub shaped_clusters_range: Range<u32>,
|
||||
/// This run's glyphs, as a range into [`ShapedText::glyphs`].
|
||||
pub glyphs_range: Range<usize>,
|
||||
/// The normalized variation coords of this run, as a range into [`ShapedText::normalized_coords`].
|
||||
pub normalized_coords_range: Range<usize>,
|
||||
/// The bidi level of the run.
|
||||
pub bidi_level: BidiLevel,
|
||||
/// Total advance of the run.
|
||||
pub advance: f32,
|
||||
/// The font metrics of this run.
|
||||
pub font_metrics: FontMetrics,
|
||||
}
|
||||
|
||||
/// Processes shaped glyphs from `HarfRust` and converts them into `ShapedCluster` and `Glyph`.
|
||||
///
|
||||
/// # Parameters
|
||||
///
|
||||
/// ## Output Parameters (mutated by this function):
|
||||
/// * `shaped_clusters` - Vector where new `ShapedCluster` entries will be pushed.
|
||||
/// * `glyphs` - Vector where new `Glyph` entries will be pushed. Note: single-glyph clusters
|
||||
/// with zero offsets are inlined directly into `ShapedCluster`.
|
||||
///
|
||||
/// ## Input Parameters:
|
||||
/// * `scale_factor` - Scaling factor used to convert font units to the target size.
|
||||
/// * `glyph_infos` - `HarfRust` glyph information in logical order (i.e., reversed for RTL runs).
|
||||
/// * `glyph_positions` - `HarfRust` glyph positioning data in logical order (i.e., reversed for RTL
|
||||
/// runs).
|
||||
/// * `characters` must contain the shaped characters whose clusters we're now processing, starting at
|
||||
/// index `characters_start`.
|
||||
/// * `characters_start` - See `characters`.
|
||||
fn process_shaped_clusters<'a>(
|
||||
shaped_clusters: &mut Vec<ShapedCluster>,
|
||||
glyphs: &mut Vec<Glyph>,
|
||||
scale_factor: f32,
|
||||
glyph_infos: impl Iterator<Item = &'a harfrust::GlyphInfo>,
|
||||
glyph_positions: impl Iterator<Item = &'a harfrust::GlyphPosition>,
|
||||
characters: &[Character],
|
||||
characters_start: usize,
|
||||
) {
|
||||
struct Cluster {
|
||||
id: u32,
|
||||
characters_start: usize,
|
||||
glyphs_start: usize,
|
||||
glyphs: u32,
|
||||
inline_glyph: Option<Glyph>,
|
||||
advance: f32,
|
||||
}
|
||||
|
||||
/// Flush `cluster`, whose characters end at `char_end`, onto `shaped_clusters`.
|
||||
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
|
||||
fn flush(
|
||||
cluster: &mut Cluster,
|
||||
char_end: usize,
|
||||
characters: &[Character],
|
||||
shaped_clusters: &mut Vec<ShapedCluster>,
|
||||
) {
|
||||
let first_character = &characters[cluster.characters_start];
|
||||
let is_newline = first_character.whitespace == Whitespace::Newline;
|
||||
let (glyph_offset, glyph_len, inline_glyph, advance) = if is_newline {
|
||||
// Elide glyphs of newlines.
|
||||
(cluster.glyphs_start as u32, 0, false, 0.)
|
||||
} else if let Some(inline_glyph) = cluster.inline_glyph.take() {
|
||||
(inline_glyph.id, 1, true, cluster.advance)
|
||||
} else {
|
||||
(
|
||||
cluster.glyphs_start as u32,
|
||||
cluster.glyphs as u8,
|
||||
false,
|
||||
cluster.advance,
|
||||
)
|
||||
};
|
||||
|
||||
shaped_clusters.push(ShapedCluster {
|
||||
chars_range: (cluster.characters_start as u32, char_end as u32),
|
||||
style_index: first_character.style_index,
|
||||
flags: ShapedClusterFlags::new(glyph_len)
|
||||
.with_grapheme_start(first_character.grapheme_start)
|
||||
// TODO: fill with actual shaping data (`parley` currently just ignores this)
|
||||
.with_safe_to_break_before(false)
|
||||
.with_inline_glyph(inline_glyph)
|
||||
.with_first_char(
|
||||
first_character.flags.is_soft_wrap_opportunity(),
|
||||
first_character.whitespace,
|
||||
),
|
||||
glyph_offset,
|
||||
advance,
|
||||
});
|
||||
}
|
||||
|
||||
let mut cluster = Cluster {
|
||||
id: 0,
|
||||
characters_start,
|
||||
glyphs_start: glyphs.len(),
|
||||
glyphs: 0,
|
||||
inline_glyph: None,
|
||||
advance: 0.,
|
||||
};
|
||||
|
||||
for (glyph_info, glyph_pos) in glyph_infos.zip(glyph_positions) {
|
||||
if glyph_info.cluster != cluster.id {
|
||||
let char_end = characters_start + glyph_info.cluster as usize;
|
||||
flush(&mut cluster, char_end, characters, shaped_clusters);
|
||||
|
||||
cluster = Cluster {
|
||||
id: glyph_info.cluster,
|
||||
characters_start: char_end,
|
||||
glyphs_start: glyphs.len(),
|
||||
glyphs: 0,
|
||||
inline_glyph: None,
|
||||
advance: 0.,
|
||||
};
|
||||
}
|
||||
|
||||
let glyph = Glyph {
|
||||
id: glyph_info.glyph_id,
|
||||
x: (glyph_pos.x_offset as f32) * scale_factor,
|
||||
// Convert from font space (Y-up) to layout space (Y-down)
|
||||
y: -(glyph_pos.y_offset as f32) * scale_factor,
|
||||
advance: (glyph_pos.x_advance as f32) * scale_factor,
|
||||
};
|
||||
if cluster.glyphs == 0 && glyph.x == 0. && glyph.y == 0. {
|
||||
// Defer this potential zero-offset, single glyph cluster
|
||||
cluster.inline_glyph = Some(glyph);
|
||||
} else {
|
||||
if let Some(pending_glyph) = cluster.inline_glyph.take() {
|
||||
glyphs.push(pending_glyph);
|
||||
}
|
||||
glyphs.push(glyph);
|
||||
}
|
||||
cluster.advance += glyph.advance;
|
||||
cluster.glyphs += 1;
|
||||
}
|
||||
|
||||
// Flush the final cluster.
|
||||
flush(&mut cluster, characters.len(), characters, shaped_clusters);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use alloc::{sync::Arc, vec, vec::Vec};
|
||||
|
||||
use fontique::Synthesis;
|
||||
use linebender_resource_handle::{Blob, FontData};
|
||||
|
||||
use crate::{
|
||||
Analysis, AnalysisOptions, Analyzer, FontInstance, FontInstanceRef, FontSelector,
|
||||
ShapeOptions, Shaper,
|
||||
itemize::{Item, Segment},
|
||||
shape::CharCluster,
|
||||
};
|
||||
|
||||
use super::ShapedText;
|
||||
|
||||
const ROBOTO: &[u8] =
|
||||
include_bytes!("../../../parley_dev/assets/fonts/roboto_fonts/Roboto-Regular.ttf");
|
||||
const NOTO_KUFI_ARABIC: &[u8] =
|
||||
include_bytes!("../../../parley_dev/assets/fonts/noto_fonts/NotoKufiArabic-Regular.otf");
|
||||
const NOTO_COLOR_EMOJI: &[u8] = include_bytes!(
|
||||
"../../../parley_dev/assets/fonts/noto_color_emoji/NotoColorEmoji-Subset.ttf"
|
||||
);
|
||||
|
||||
/// A [`FontSelector`] shaping everything with a single font.
|
||||
struct SingleFont(FontInstance);
|
||||
|
||||
impl FontSelector for SingleFont {
|
||||
fn select_font(
|
||||
&mut self,
|
||||
_item: &Segment,
|
||||
_options: &ShapeOptions<'_>,
|
||||
_cluster: &mut CharCluster,
|
||||
) -> Option<FontInstanceRef<'_>> {
|
||||
Some(self.0.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`FontSelector`] shaping clusters starting with a particular character with one font, and
|
||||
/// all other clusters with another, to split the text into runs at that character.
|
||||
struct FontForChar {
|
||||
ch: char,
|
||||
font: FontInstance,
|
||||
other_font: FontInstance,
|
||||
}
|
||||
|
||||
impl FontSelector for FontForChar {
|
||||
fn select_font(
|
||||
&mut self,
|
||||
_segment: &Segment,
|
||||
_options: &ShapeOptions<'_>,
|
||||
cluster: &mut CharCluster,
|
||||
) -> Option<FontInstanceRef<'_>> {
|
||||
if cluster.chars()[0].ch == self.ch {
|
||||
Some(self.font.as_ref())
|
||||
} else {
|
||||
Some(self.other_font.as_ref())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn analyze(text: &str) -> Analysis {
|
||||
let mut analysis = Analysis::new();
|
||||
Analyzer::new().analyze(
|
||||
text,
|
||||
&AnalysisOptions {
|
||||
line_break: &[],
|
||||
line_break_override: None,
|
||||
..AnalysisOptions::default()
|
||||
},
|
||||
&mut analysis,
|
||||
);
|
||||
analysis
|
||||
}
|
||||
|
||||
fn font_instance(font_data: &'static [u8]) -> FontInstance {
|
||||
FontInstance {
|
||||
font: FontData::new(Blob::new(Arc::new(font_data)), 0),
|
||||
synthesis: Synthesis::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn shape_with_font(text: &str, font_data: &'static [u8]) -> ShapedText {
|
||||
shape_with_font_selector(text, SingleFont(font_instance(font_data)))
|
||||
}
|
||||
|
||||
fn shape_with_font_selector(text: &str, select_font: impl FontSelector) -> ShapedText {
|
||||
let analysis = analyze(text);
|
||||
let mut shaper = Shaper::default();
|
||||
let mut shaped = ShapedText::new();
|
||||
|
||||
let char_style_indices = vec![0; text.chars().count()];
|
||||
let items = [Item {
|
||||
char_end: text.chars().count().try_into().unwrap(),
|
||||
options: ShapeOptions {
|
||||
font_size: 32.0,
|
||||
language: None,
|
||||
features: &[],
|
||||
variations: &[],
|
||||
},
|
||||
}];
|
||||
shaper.shape_text(
|
||||
text,
|
||||
&analysis,
|
||||
&char_style_indices,
|
||||
items,
|
||||
select_font,
|
||||
&mut shaped,
|
||||
);
|
||||
shaped
|
||||
}
|
||||
|
||||
/// A run can shape into no glyphs at all: `HarfRust` normally shapes `default-ignorable`
|
||||
/// characters (like a soft-hyphen) into a space glyph with zero advance, but if the space glyph
|
||||
/// is not available, it just deletes the character.
|
||||
///
|
||||
/// This checks whether we handle that.
|
||||
#[test]
|
||||
fn run_without_glyphs_is_kept() {
|
||||
// The soft hyphen is `default-ignorable`, and is a grapheme of its own, so font selection
|
||||
// gives it a run of its own.
|
||||
let shaped = shape_with_font_selector(
|
||||
"a\u{00AD}b",
|
||||
FontForChar {
|
||||
ch: '\u{00AD}',
|
||||
// Our Noto Color Emoji subset has no space character.
|
||||
font: font_instance(NOTO_COLOR_EMOJI),
|
||||
other_font: font_instance(ROBOTO),
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
shaped.characters().iter().count(),
|
||||
3,
|
||||
"the characters of a run without glyphs are shaped"
|
||||
);
|
||||
let [a, soft_hyphen, b] = shaped.runs() else {
|
||||
panic!("expected three runs, got {}", shaped.runs().len());
|
||||
};
|
||||
assert_eq!(a.characters_range, 0..1);
|
||||
assert_eq!(soft_hyphen.characters_range, 1..2);
|
||||
assert_eq!(b.characters_range, 2..3);
|
||||
|
||||
assert!(soft_hyphen.glyphs_range.is_empty());
|
||||
assert_eq!(soft_hyphen.advance, 0.);
|
||||
|
||||
// The soft-hyphen's run should have a single cluster, and it must be without glyphs.
|
||||
let clusters = shaped.run_slice(1).shaped_clusters();
|
||||
assert_eq!(clusters.len(), 1);
|
||||
assert_eq!(clusters[0].glyph_len(), 0);
|
||||
assert_eq!(clusters[0].chars_range(), 1..2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_cluster_run_advance_matches_its_cluster() {
|
||||
let shaped = shape_with_font("A", ROBOTO);
|
||||
let run = &shaped.runs()[0];
|
||||
let cluster = &shaped.shaped_clusters()[run.shaped_clusters_range.start as usize];
|
||||
|
||||
assert!(cluster.advance > 0.0);
|
||||
assert_eq!(run.advance, cluster.advance);
|
||||
}
|
||||
|
||||
/// [U+0600 U+0623 U+064F] is a single grapheme in text-wide segmentation, but U+0600 has
|
||||
/// bidi class AN while the following characters resolve to a different bidi level, so
|
||||
/// itemization splits the grapheme into the items [U+0600] [U+0623 U+064F]. The item
|
||||
/// boundary forces a grapheme start on U+0623.
|
||||
#[test]
|
||||
fn one_grapheme_split_across_items() {
|
||||
let shaped = shape_with_font("\u{0600}\u{0623}\u{064F}", NOTO_KUFI_ARABIC);
|
||||
|
||||
let grapheme_starts: Vec<bool> =
|
||||
shaped.characters.iter().map(|c| c.grapheme_start).collect();
|
||||
assert_eq!(grapheme_starts, [true, true, false]);
|
||||
|
||||
let clusters: Vec<(u32, u32, bool)> = shaped
|
||||
.shaped_clusters
|
||||
.iter()
|
||||
.map(|c| {
|
||||
(
|
||||
c.chars_range().start,
|
||||
c.chars_range().end,
|
||||
c.is_grapheme_start(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(clusters, [(0, 1, true), (1, 3, true)]);
|
||||
}
|
||||
|
||||
/// "ffi" is three graphemes but shapes into one cluster.
|
||||
#[test]
|
||||
fn three_graphemes_one_cluster() {
|
||||
let shaped = shape_with_font("ffi", ROBOTO);
|
||||
|
||||
let grapheme_starts: Vec<bool> =
|
||||
shaped.characters.iter().map(|c| c.grapheme_start).collect();
|
||||
assert_eq!(grapheme_starts, [true, true, true]);
|
||||
|
||||
let clusters: Vec<(u32, u32, bool)> = shaped
|
||||
.shaped_clusters
|
||||
.iter()
|
||||
.map(|c| {
|
||||
(
|
||||
c.chars_range().start,
|
||||
c.chars_range().end,
|
||||
c.is_grapheme_start(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(clusters, [(0, 3, true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newlines_removed() {
|
||||
for newline in ["\n", "\r", "\u{2028}", "\u{2029}"] {
|
||||
let shaped = shape_with_font(&alloc::format!("a{newline}b"), ROBOTO);
|
||||
|
||||
let index = shaped
|
||||
.shaped_clusters
|
||||
.iter()
|
||||
.position(|cluster| cluster.chars_range().start == 1)
|
||||
.unwrap();
|
||||
let newline_cluster = &shaped.shaped_clusters[index];
|
||||
assert_eq!(newline_cluster.glyph_len(), 0, "newline glyphs are removed");
|
||||
assert_eq!(newline_cluster.advance, 0., "newline advance is set to 0");
|
||||
}
|
||||
}
|
||||
|
||||
/// An itemization boundary forces a cluster break in shaping, and must force a grapheme start.
|
||||
#[test]
|
||||
fn item_boundaries_force_grapheme_start() {
|
||||
// Two regional indicators forming a single flag grapheme...
|
||||
let text = "\u{1F1E6}\u{1F1E7}";
|
||||
let char_style_indices = vec![0; text.chars().count()];
|
||||
let analysis = analyze(text);
|
||||
assert_eq!(
|
||||
analysis
|
||||
.char_info()
|
||||
.iter()
|
||||
.map(|info| info.is_grapheme_start())
|
||||
.collect::<Vec<_>>(),
|
||||
[true, false]
|
||||
);
|
||||
|
||||
let font = font_instance(ROBOTO);
|
||||
let mut shaper = Shaper::default();
|
||||
let mut shaped = ShapedText::new();
|
||||
|
||||
// ...split over two items.
|
||||
let items = [
|
||||
Item {
|
||||
char_end: 1,
|
||||
options: ShapeOptions {
|
||||
font_size: 32.0,
|
||||
language: None,
|
||||
features: &[],
|
||||
variations: &[],
|
||||
},
|
||||
},
|
||||
Item {
|
||||
char_end: text.chars().count().try_into().unwrap(),
|
||||
options: ShapeOptions {
|
||||
font_size: 32.0,
|
||||
language: None,
|
||||
features: &[],
|
||||
variations: &[],
|
||||
},
|
||||
},
|
||||
];
|
||||
shaper.shape_text(
|
||||
text,
|
||||
&analysis,
|
||||
&char_style_indices,
|
||||
items,
|
||||
SingleFont(font),
|
||||
&mut shaped,
|
||||
);
|
||||
|
||||
let grapheme_starts: Vec<bool> =
|
||||
shaped.characters.iter().map(|c| c.grapheme_start).collect();
|
||||
assert_eq!(grapheme_starts, [true, true]);
|
||||
|
||||
// But note that, had we had three regional indicator symbols, like `[R0 R1 R2]` itemized as
|
||||
// `[R0] [R1 R2]`, the last pair should form a single grapheme. We don't do that currently.
|
||||
}
|
||||
}
|
||||
+605
@@ -0,0 +1,605 @@
|
||||
// Copyright 2026 the Parley Authors
|
||||
// SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
//! Shaping of text.
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use core::mem;
|
||||
use harfrust::ShapeOptions as HarfShapeOptions;
|
||||
use linebender_resource_handle::{Blob, FontData};
|
||||
use parlance::{FontFeature, FontVariation, Language};
|
||||
|
||||
use crate::shape::shaped_text::FontMetrics;
|
||||
use crate::{
|
||||
Analysis, CharInfo, ShapedText,
|
||||
itemize::{Item, Segment, TextRange},
|
||||
lru_cache::LruCache,
|
||||
shape::{CharCluster, cache},
|
||||
};
|
||||
|
||||
/// Shaping options for one item.
|
||||
///
|
||||
/// These are styling options relevant for shaping. They're styling, in that they're not derived
|
||||
/// from the underlying text. When you [shape the text][`Shaper::shape_text`], you should split the
|
||||
/// text into [`Item`]s at the points where these options change.
|
||||
#[derive(Debug)]
|
||||
pub struct ShapeOptions<'a> {
|
||||
/// The font size to shape the item with.
|
||||
pub font_size: f32,
|
||||
/// The language to shape the item with.
|
||||
pub language: Option<Language>,
|
||||
/// The font features to shape the item with.
|
||||
///
|
||||
/// If there are font features with duplicate [tags][`FontFeature::tag`], later values override
|
||||
/// earlier values.
|
||||
pub features: &'a [FontFeature],
|
||||
/// The font variations that are constant over an item.
|
||||
pub variations: &'a [FontVariation],
|
||||
}
|
||||
|
||||
/// The font instance to shape an item with.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FontInstance {
|
||||
/// The font.
|
||||
pub font: FontData,
|
||||
/// Font synthesis suggestions.
|
||||
// TODO: Synthesis carries more than we need, and ties us to `fontique`. We can likely change
|
||||
// this to opaque user data.
|
||||
pub synthesis: fontique::Synthesis,
|
||||
}
|
||||
|
||||
impl FontInstance {
|
||||
/// Borrow this font instance.
|
||||
#[inline]
|
||||
pub fn as_ref(&self) -> FontInstanceRef<'_> {
|
||||
FontInstanceRef {
|
||||
data: &self.font.data,
|
||||
index: self.font.index,
|
||||
synthesis: &self.synthesis,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A borrowed [`FontInstance`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct FontInstanceRef<'a> {
|
||||
/// Blob containing the content of the font file.
|
||||
pub data: &'a Blob<u8>,
|
||||
/// Index of the font in a collection, or 0 for a single font.
|
||||
pub index: u32,
|
||||
/// Font synthesis suggestions.
|
||||
pub synthesis: &'a fontique::Synthesis,
|
||||
}
|
||||
|
||||
impl From<FontInstanceRef<'_>> for FontInstance {
|
||||
#[inline]
|
||||
fn from(font: FontInstanceRef<'_>) -> Self {
|
||||
Self {
|
||||
font: FontData {
|
||||
data: font.data.clone(),
|
||||
index: font.index,
|
||||
},
|
||||
synthesis: *font.synthesis,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reusable scratch to shape text using [`Self::shape_text`].
|
||||
pub struct Shaper {
|
||||
shape_data_cache: LruCache<cache::ShapeDataKey, harfrust::ShaperData>,
|
||||
shape_instance_cache: LruCache<cache::ShapeInstanceId, harfrust::ShaperInstance>,
|
||||
shape_plan_cache: LruCache<cache::ShapePlanId, harfrust::ShapePlan>,
|
||||
/// Each run's font metrics and units per em (Rune: vendor/parley_engine.patch).
|
||||
run_metrics_cache: LruCache<cache::RunMetricsId, (FontMetrics, f32)>,
|
||||
unicode_buffer: Option<harfrust::UnicodeBuffer>,
|
||||
features: Vec<harfrust::Feature>,
|
||||
char_cluster: CharCluster,
|
||||
}
|
||||
|
||||
impl Default for Shaper {
|
||||
fn default() -> Self {
|
||||
const MAX_ENTRIES: usize = 16;
|
||||
Self {
|
||||
shape_data_cache: LruCache::new(MAX_ENTRIES),
|
||||
shape_instance_cache: LruCache::new(MAX_ENTRIES),
|
||||
shape_plan_cache: LruCache::new(MAX_ENTRIES),
|
||||
run_metrics_cache: LruCache::new(MAX_ENTRIES),
|
||||
unicode_buffer: Some(harfrust::UnicodeBuffer::new()),
|
||||
features: Vec::new(),
|
||||
char_cluster: CharCluster::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for Shaper {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
f.debug_struct("Shaper").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl Shaper {
|
||||
/// Shape text into glyphs, overwriting `shaped_text`.
|
||||
///
|
||||
/// The `text` passed in must be the same as used for producing `analysis`.
|
||||
///
|
||||
/// This uses the items returned by `items`, and further itemizes the text into
|
||||
/// individually-shapeable segments of constant bidi level and script. `items` should be used to
|
||||
/// split on properties like shaping-relevant style changes (e.g., font size) or properties like
|
||||
/// language.
|
||||
///
|
||||
/// `char_style_indices` holds per-character style indices; these are copied onto
|
||||
/// [`Character`][super::Character`] and [`ShapedCluster`][super::ShapedCluster]. A shaped
|
||||
/// cluster's style index is that of its logically first constituent character.
|
||||
///
|
||||
/// Characters that don't have a particular script have their script resolved based on
|
||||
/// surrounding context (see [`Segment::script`]).
|
||||
///
|
||||
/// Each segment is then broken into runs of maximal sequences of character clusters for which
|
||||
/// `select_font` returns the same font.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `items` does not cover the entire source text, or the font returned by
|
||||
/// `select_font` is malformed.
|
||||
pub fn shape_text<'options>(
|
||||
&mut self,
|
||||
text: &str,
|
||||
analysis: &Analysis,
|
||||
// TODO: rename to something like `user_data` (s.t. we don't assume it's a style per se).
|
||||
char_style_indices: &[u16],
|
||||
items: impl IntoIterator<Item = Item<'options>>,
|
||||
mut select_font: impl FontSelector,
|
||||
shaped_text: &mut ShapedText,
|
||||
) {
|
||||
shaped_text.clear();
|
||||
shaped_text.reserve(text.len());
|
||||
|
||||
let char_count = analysis.char_info().len();
|
||||
debug_assert_eq!(
|
||||
char_style_indices.len(),
|
||||
char_count,
|
||||
"The number of character style indices must be equal to the character count"
|
||||
);
|
||||
|
||||
let mut previous_item_end = 0;
|
||||
let mut itemizer = analysis.itemize(text);
|
||||
|
||||
for item in items {
|
||||
assert!(
|
||||
item.char_end > previous_item_end,
|
||||
"item ends must be strictly increasing"
|
||||
);
|
||||
assert!(
|
||||
item.char_end as usize <= char_count,
|
||||
"items must not span past the text"
|
||||
);
|
||||
|
||||
loop {
|
||||
let segment = itemizer
|
||||
.next(
|
||||
#[inline(always)]
|
||||
|text_range| text_range.char_range.end == item.char_end as usize,
|
||||
)
|
||||
.expect("A segment must be yielded, given items tile the full text exactly");
|
||||
|
||||
if shape_segment(
|
||||
self,
|
||||
text,
|
||||
&segment,
|
||||
&item.options,
|
||||
&mut select_font,
|
||||
analysis.char_info(),
|
||||
char_style_indices,
|
||||
shaped_text,
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
// Abort on error. This happens iff `FontSelector::select_font` failed to return a
|
||||
// font. By aborting we ensure `ShapedText` covers the source text contiguously (as
|
||||
// we need a font to construct `ShapedRun`).
|
||||
return;
|
||||
};
|
||||
|
||||
debug_assert!(
|
||||
segment.range.char_range.end <= item.char_end as usize,
|
||||
"Segments must not span past the item."
|
||||
);
|
||||
if segment.range.char_range.end == item.char_end as usize {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
previous_item_end = item.char_end;
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
previous_item_end as usize, char_count,
|
||||
"`items` does not cover the entire source text"
|
||||
);
|
||||
debug_assert_eq!(
|
||||
shaped_text.characters().len(),
|
||||
char_count,
|
||||
"All characters must have been processed"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Shape one segment.
|
||||
///
|
||||
/// Returns `Err(())` if shaping should be aborted, which happens iff [`FontSelector::select_font`]
|
||||
/// returned `None`.
|
||||
fn shape_segment(
|
||||
scx: &mut Shaper,
|
||||
text: &str,
|
||||
segment: &Segment,
|
||||
options: &ShapeOptions<'_>,
|
||||
select_font: &mut impl FontSelector,
|
||||
char_info: &[CharInfo],
|
||||
char_style_indices: &[u16],
|
||||
shaped_text: &mut ShapedText,
|
||||
) -> Result<(), ()> {
|
||||
select_font.begin_segment(segment, options);
|
||||
|
||||
let text_range = &segment.range.byte_range;
|
||||
let char_range = &segment.range.char_range;
|
||||
|
||||
let segment_text = &text[text_range.clone()];
|
||||
|
||||
// Only process current segment
|
||||
let segment_char_info = &char_info[char_range.start..char_range.end];
|
||||
let segment_char_style_indices = &char_style_indices[char_range.start..char_range.end];
|
||||
|
||||
if segment_text.is_empty() {
|
||||
return Ok(()); // No clusters
|
||||
}
|
||||
|
||||
let char_cluster = &mut scx.char_cluster;
|
||||
|
||||
// Shaping inputs that are constant over the segment.
|
||||
let direction = if segment.bidi_level.is_rtl() {
|
||||
harfrust::Direction::RightToLeft
|
||||
} else {
|
||||
harfrust::Direction::LeftToRight
|
||||
};
|
||||
let hb_script = script_to_harfrust(segment.script);
|
||||
let language = options
|
||||
.language
|
||||
.as_ref()
|
||||
.and_then(|lang| lang.as_str().parse::<harfrust::Language>().ok());
|
||||
scx.features.clear();
|
||||
scx.features.extend(options.features.iter().map(|feature| {
|
||||
harfrust::Feature::new(
|
||||
harfrust::Tag::new(&feature.tag.to_bytes()),
|
||||
feature.value as u32,
|
||||
..,
|
||||
)
|
||||
}));
|
||||
|
||||
// Shape a run of the segment with a single font, appending it to `shaped_text`.
|
||||
let mut shape_run = |font: &FontInstance, range: TextRange| {
|
||||
// The platform's face: its host measures the run and draws it (`platform`).
|
||||
if let Some(platform) = crate::platform::shaper(font.font.data.id()) {
|
||||
shape_platform_run(platform, text, range, segment, options, char_info, char_style_indices, font, shaped_text);
|
||||
return;
|
||||
}
|
||||
// TODO: How do we want to handle errors like this?
|
||||
let font_ref =
|
||||
harfrust::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap();
|
||||
|
||||
// Create harfrust shaper
|
||||
let shaper_data = scx.shape_data_cache.entry(
|
||||
cache::ShapeDataKey::new(font.font.data.id(), font.font.index),
|
||||
|| harfrust::ShaperData::new(&font_ref),
|
||||
);
|
||||
let instance = scx.shape_instance_cache.entry(
|
||||
cache::ShapeInstanceKey::new(
|
||||
font.font.data.id(),
|
||||
font.font.index,
|
||||
&font.synthesis,
|
||||
Some(options.variations),
|
||||
),
|
||||
|| {
|
||||
harfrust::ShaperInstance::from_variations(
|
||||
&font_ref,
|
||||
variations_iter(&font.synthesis, options.variations),
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
let harf_shaper = shaper_data
|
||||
.shaper(&font_ref)
|
||||
.instance(Some(instance))
|
||||
.build();
|
||||
let shaper_plan = scx.shape_plan_cache.entry(
|
||||
cache::ShapePlanKey::new(
|
||||
font.font.data.id(),
|
||||
font.font.index,
|
||||
&font.synthesis,
|
||||
direction,
|
||||
hb_script,
|
||||
language.clone(),
|
||||
&scx.features,
|
||||
Some(options.variations),
|
||||
),
|
||||
|| {
|
||||
harfrust::ShapePlan::new(
|
||||
&harf_shaper,
|
||||
direction,
|
||||
Some(hb_script),
|
||||
language.as_ref(),
|
||||
&scx.features,
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
// Prepare harfrust buffer
|
||||
let mut buffer = mem::take(&mut scx.unicode_buffer).unwrap();
|
||||
buffer.clear();
|
||||
buffer.set_cluster_level(harfrust::BufferClusterLevel::MonotoneCharacters);
|
||||
|
||||
// Use the entire run text including newlines.
|
||||
let run_text = &text[range.byte_range.clone()];
|
||||
buffer.reserve(run_text.len());
|
||||
#[expect(clippy::cast_possible_truncation, reason = "Deferred")]
|
||||
for (i, ch) in run_text.chars().enumerate() {
|
||||
// Ensure that each cluster's index matches the index into `infos`. This is required
|
||||
// for efficient cluster lookup within `data.rs`.
|
||||
//
|
||||
// In other words, instead of using `buffer.push_str`, which iterates `run_text`
|
||||
// with `char_indices`, push each char individually via `.chars` with a cluster index
|
||||
// that matches its `infos` counterpart. This allows us to lookup `infos` via cluster
|
||||
// index in `data.rs`.
|
||||
buffer.add(ch, i as u32);
|
||||
}
|
||||
|
||||
buffer.set_pre_context(&text[..range.byte_range.start]);
|
||||
buffer.set_post_context(&text[range.byte_range.end..]);
|
||||
buffer.set_direction(direction);
|
||||
buffer.set_script(hb_script);
|
||||
|
||||
if let Some(lang) = &language {
|
||||
buffer.set_language(lang.clone());
|
||||
}
|
||||
|
||||
let glyph_buffer = harf_shaper.shape(
|
||||
buffer,
|
||||
HarfShapeOptions::new()
|
||||
.plan(Some(shaper_plan))
|
||||
.features(&scx.features)
|
||||
.point_size(Some(options.font_size)),
|
||||
);
|
||||
|
||||
// A run's metrics depend on its font instance and size alone: made once for each.
|
||||
let metrics = *scx.run_metrics_cache.entry(
|
||||
cache::RunMetricsKey::new(
|
||||
cache::ShapeInstanceKey::new(
|
||||
font.font.data.id(),
|
||||
font.font.index,
|
||||
&font.synthesis,
|
||||
Some(options.variations),
|
||||
),
|
||||
options.font_size,
|
||||
),
|
||||
|| {
|
||||
let font_ref =
|
||||
skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap();
|
||||
let metrics = skrifa::metrics::Metrics::new(
|
||||
&font_ref,
|
||||
skrifa::prelude::Size::new(options.font_size),
|
||||
harf_shaper.coords(),
|
||||
);
|
||||
(
|
||||
FontMetrics::from_skrifa_metrics(&metrics, options.font_size),
|
||||
metrics.units_per_em as f32,
|
||||
)
|
||||
},
|
||||
);
|
||||
shaped_text.push_run(
|
||||
text,
|
||||
range,
|
||||
segment,
|
||||
options,
|
||||
char_info,
|
||||
char_style_indices,
|
||||
font,
|
||||
glyph_buffer.glyph_infos(),
|
||||
glyph_buffer.glyph_positions(),
|
||||
harf_shaper.coords(),
|
||||
metrics,
|
||||
);
|
||||
|
||||
// Replace buffer to reuse allocation in the next run.
|
||||
scx.unicode_buffer = Some(glyph_buffer.clear());
|
||||
};
|
||||
|
||||
// This is the run being accumulated, i.e., consecutive graphemes for which `select_font`
|
||||
// returns the same font.
|
||||
let mut run: Option<(FontInstance, TextRange)> = None;
|
||||
|
||||
// The segment's characters with their analysis data and style indices.
|
||||
let mut chars = segment_text
|
||||
.chars()
|
||||
.zip(segment_char_info)
|
||||
.zip(segment_char_style_indices)
|
||||
.map(|((ch, &info), &style_index)| (ch, info, style_index));
|
||||
|
||||
// The lengths of the segment's graphemes in characters.
|
||||
let grapheme_lengths = segment_char_info
|
||||
.chunk_by(|_, info| !info.is_grapheme_start())
|
||||
.map(<[_]>::len);
|
||||
|
||||
// The end of the previous grapheme.
|
||||
let mut byte_end = text_range.start;
|
||||
let mut char_end = char_range.start;
|
||||
|
||||
for grapheme_length in grapheme_lengths {
|
||||
let (byte_start, char_start) = (byte_end, char_end);
|
||||
char_cluster.fill(chars.by_ref().take(grapheme_length), &mut byte_end);
|
||||
char_end += grapheme_length;
|
||||
let grapheme = TextRange {
|
||||
byte_range: byte_start..byte_end,
|
||||
char_range: char_start..char_end,
|
||||
};
|
||||
|
||||
let font = select_font
|
||||
.select_font(segment, options, char_cluster)
|
||||
.ok_or(())?;
|
||||
|
||||
if let Some((run_font, run_range)) = &mut run
|
||||
&& run_font.as_ref() == font
|
||||
{
|
||||
run_range.byte_range.end = byte_end;
|
||||
run_range.char_range.end = char_end;
|
||||
} else {
|
||||
if let Some((run_font, run_range)) = run.take() {
|
||||
// The font changed: shape the previous run.
|
||||
shape_run(&run_font, run_range);
|
||||
}
|
||||
run = Some((font.into(), grapheme));
|
||||
}
|
||||
}
|
||||
if let Some((run_font, run_range)) = run {
|
||||
shape_run(&run_font, run_range);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn variations_iter<'a>(
|
||||
synthesis: &'a fontique::Synthesis,
|
||||
item: &'a [FontVariation],
|
||||
) -> impl Iterator<Item = harfrust::Variation> + 'a {
|
||||
synthesis
|
||||
.variation_settings()
|
||||
.iter()
|
||||
.map(|(tag, value)| harfrust::Variation {
|
||||
tag: *tag,
|
||||
value: *value,
|
||||
})
|
||||
.chain(item.iter().map(|variation| harfrust::Variation {
|
||||
tag: harfrust::Tag::new(&variation.tag.to_bytes()),
|
||||
value: variation.value,
|
||||
}))
|
||||
}
|
||||
|
||||
/// A run in the platform's face (`platform`), appended to `shaped_text`: its host gives a glyph
|
||||
/// per grapheme, with units it draws whole between the run's break opportunities.
|
||||
#[expect(clippy::too_many_arguments, reason = "the shape_run closure's inputs")]
|
||||
fn shape_platform_run(
|
||||
shaper: crate::platform::PlatformShaper,
|
||||
text: &str,
|
||||
range: TextRange,
|
||||
segment: &Segment,
|
||||
options: &ShapeOptions<'_>,
|
||||
char_info: &[CharInfo],
|
||||
char_style_indices: &[u16],
|
||||
font: &FontInstance,
|
||||
shaped_text: &mut ShapedText,
|
||||
) {
|
||||
let run_text = &text[range.byte_range.clone()];
|
||||
let (mut graphemes, mut units, mut clusters) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let mut after_newline = false;
|
||||
for (i, ((at, ch), info)) in run_text.char_indices().zip(&char_info[range.char_range.clone()]).enumerate() {
|
||||
let newline = matches!(ch, '\n' | '\r' | '\u{0B}' | '\u{0C}' | '\u{85}' | '\u{2028}' | '\u{2029}');
|
||||
let grapheme = i == 0 || info.is_grapheme_start() || newline || after_newline;
|
||||
if grapheme {
|
||||
#[expect(clippy::cast_possible_truncation, reason = "a run is under 4 GiB")]
|
||||
{
|
||||
if i == 0 || info.is_soft_wrap_opportunity() || newline || after_newline {
|
||||
units.push(at as u32);
|
||||
}
|
||||
graphemes.push(at as u32);
|
||||
clusters.push(i as u32);
|
||||
}
|
||||
}
|
||||
after_newline = newline;
|
||||
}
|
||||
let wght = harfrust::Tag::new(b"wght");
|
||||
let weight = variations_iter(&font.synthesis, options.variations)
|
||||
.filter(|v| v.tag == wght)
|
||||
.last()
|
||||
.map_or(if font.synthesis.embolden() { 700. } else { 400. }, |v| v.value);
|
||||
let rtl = segment.bidi_level.is_rtl();
|
||||
let mut glyphs = Vec::with_capacity(graphemes.len());
|
||||
shaper(
|
||||
&crate::platform::PlatformText {
|
||||
text: run_text,
|
||||
graphemes: &graphemes,
|
||||
units: &units,
|
||||
size: options.font_size,
|
||||
weight,
|
||||
italic: font.synthesis.skew().is_some(),
|
||||
rtl,
|
||||
language: options.language.as_ref().map(|l| l.as_str()),
|
||||
},
|
||||
&mut glyphs,
|
||||
);
|
||||
glyphs.resize(graphemes.len(), crate::platform::PlatformGlyph::default());
|
||||
let font_ref = skrifa::FontRef::from_index(font.font.data.as_ref(), font.font.index).unwrap();
|
||||
let metrics = skrifa::metrics::Metrics::new(
|
||||
&font_ref,
|
||||
skrifa::prelude::Size::new(options.font_size),
|
||||
skrifa::instance::LocationRef::default(),
|
||||
);
|
||||
let upem = metrics.units_per_em as f32;
|
||||
let units_of = |px: f32| (px * upem / options.font_size.max(1e-3)).round() as i32;
|
||||
let mut infos: Vec<harfrust::GlyphInfo> = Vec::with_capacity(glyphs.len());
|
||||
let mut positions: Vec<harfrust::GlyphPosition> = Vec::with_capacity(glyphs.len());
|
||||
for (glyph, &cluster) in glyphs.iter().zip(&clusters) {
|
||||
let mut info = harfrust::GlyphInfo::default();
|
||||
info.glyph_id = glyph.id;
|
||||
info.cluster = cluster;
|
||||
infos.push(info);
|
||||
let mut position = harfrust::GlyphPosition::default();
|
||||
position.x_advance = units_of(glyph.advance);
|
||||
position.x_offset = units_of(glyph.x_offset);
|
||||
positions.push(position);
|
||||
}
|
||||
// In visual order, as HarfRust gives them.
|
||||
if rtl {
|
||||
infos.reverse();
|
||||
positions.reverse();
|
||||
}
|
||||
shaped_text.push_run(
|
||||
text,
|
||||
range,
|
||||
segment,
|
||||
options,
|
||||
char_info,
|
||||
char_style_indices,
|
||||
font,
|
||||
&infos,
|
||||
&positions,
|
||||
&[],
|
||||
(FontMetrics::from_skrifa_metrics(&metrics, options.font_size), upem),
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn script_to_harfrust(script: fontique::Script) -> harfrust::Script {
|
||||
harfrust::Script::from_iso15924_tag(harfrust::Tag::new(&script.to_bytes()))
|
||||
.unwrap_or(harfrust::script::UNKNOWN)
|
||||
}
|
||||
|
||||
/// Implements font selection for shaping.
|
||||
pub trait FontSelector {
|
||||
/// Called when a new segment starts.
|
||||
///
|
||||
/// This can be useful to inspect, e.g., the segment's script.
|
||||
fn begin_segment(&mut self, segment: &Segment, options: &ShapeOptions<'_>) {
|
||||
let _ = (segment, options);
|
||||
}
|
||||
|
||||
/// Called once per character cluster within the current segment.
|
||||
///
|
||||
/// A character cluster will usually be a grapheme, though if text direction or script changes
|
||||
/// mid-grapheme, it will be split over segments.
|
||||
///
|
||||
/// Shaping is aborted if this returns `None`; [`ShapedText`] then contains a partial result.
|
||||
fn select_font(
|
||||
&mut self,
|
||||
segment: &Segment,
|
||||
options: &ShapeOptions<'_>,
|
||||
cluster: &mut CharCluster,
|
||||
) -> Option<FontInstanceRef<'_>>;
|
||||
}
|
||||
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "40f4a34ebaf56f9a046231f54125ad046239d3f3"
|
||||
},
|
||||
"path_in_vcs": "wgpu-hal"
|
||||
}
|
||||
+2564
File diff suppressed because it is too large.
Load diff
Vendored
+542
@@ -0,0 +1,542 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2021"
|
||||
rust-version = "1.87"
|
||||
name = "wgpu-hal"
|
||||
version = "30.0.1"
|
||||
authors = ["gfx-rs developers"]
|
||||
build = "build.rs"
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Hardware abstraction layer for wgpu, the cross-platform, safe, pure-rust graphics API"
|
||||
homepage = "https://wgpu.rs/"
|
||||
readme = "README.md"
|
||||
keywords = ["graphics"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/gfx-rs/wgpu"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = [
|
||||
"metal",
|
||||
"vulkan",
|
||||
"gles",
|
||||
"renderdoc",
|
||||
]
|
||||
rustdoc-args = [
|
||||
"--cfg",
|
||||
"docsrs",
|
||||
]
|
||||
targets = [
|
||||
"x86_64-unknown-linux-gnu",
|
||||
"x86_64-apple-darwin",
|
||||
"x86_64-pc-windows-msvc",
|
||||
"wasm32-unknown-unknown",
|
||||
]
|
||||
|
||||
[package.metadata.cargo-machete]
|
||||
ignored = ["cfg_aliases"]
|
||||
|
||||
[features]
|
||||
device_lost_panic = []
|
||||
dx12 = [
|
||||
"dep:arrayvec",
|
||||
"dep:bit-set",
|
||||
"dep:bytemuck",
|
||||
"dep:gpu-allocator",
|
||||
"dep:libloading",
|
||||
"dep:once_cell",
|
||||
"dep:ordered-float",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:range-alloc",
|
||||
"dep:windows-core",
|
||||
"gpu-allocator/d3d12",
|
||||
"naga/hlsl-out",
|
||||
"once_cell/std",
|
||||
"windows/Win32_Devices_DeviceAndDriverInstallation",
|
||||
"windows/Win32_Devices_Display",
|
||||
"windows/Win32_Graphics_Direct3D_Dxc",
|
||||
"windows/Win32_Graphics_Direct3D_Fxc",
|
||||
"windows/Win32_Graphics_Direct3D",
|
||||
"windows/Win32_Graphics_Direct3D12",
|
||||
"windows/Win32_Graphics_DirectComposition",
|
||||
"windows/Win32_Graphics_Dxgi_Common",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
"windows/Win32_Security",
|
||||
"windows/Win32_System_Diagnostics_Debug",
|
||||
"windows/Win32_System_Kernel",
|
||||
"windows/Win32_System_Performance",
|
||||
"windows/Win32_System_Threading",
|
||||
"windows/Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
fragile-send-sync-non-atomic-wasm = ["wgpu-types/fragile-send-sync-non-atomic-wasm"]
|
||||
gles = [
|
||||
"dep:arrayvec",
|
||||
"dep:bytemuck",
|
||||
"dep:glow",
|
||||
"dep:glutin_wgl_sys",
|
||||
"dep:js-sys",
|
||||
"dep:khronos-egl",
|
||||
"dep:libloading",
|
||||
"dep:ndk-sys",
|
||||
"dep:objc2",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:wasm-bindgen",
|
||||
"dep:wayland-sys",
|
||||
"dep:web-sys",
|
||||
"dep:windows-result",
|
||||
"naga/glsl-out",
|
||||
"wgpu-types/web",
|
||||
"windows-result/std",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
"windows/Win32_Graphics_OpenGL",
|
||||
"windows/Win32_System_LibraryLoader",
|
||||
"windows/Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
internal_error_panic = []
|
||||
metal = [
|
||||
"naga/msl-out",
|
||||
"dep:arrayvec",
|
||||
"dep:block2",
|
||||
"dep:bytemuck",
|
||||
"dep:libloading",
|
||||
"dep:objc2",
|
||||
"dep:objc2-core-foundation",
|
||||
"dep:objc2-core-graphics",
|
||||
"dep:objc2-foundation",
|
||||
"dep:objc2-metal",
|
||||
"dep:objc2-quartz-core",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:smallvec",
|
||||
"dep:raw-window-metal",
|
||||
]
|
||||
portable-atomic = [
|
||||
"dep:portable-atomic",
|
||||
"dep:portable-atomic-util",
|
||||
]
|
||||
renderdoc = [
|
||||
"dep:libloading",
|
||||
"dep:renderdoc-sys",
|
||||
]
|
||||
static-dxc = ["dep:mach-dxcompiler-rs"]
|
||||
validation_canary = ["dep:parking_lot"]
|
||||
vulkan = [
|
||||
"naga/spv-out",
|
||||
"dep:android_system_properties",
|
||||
"dep:arrayvec",
|
||||
"dep:ash",
|
||||
"dep:bytemuck",
|
||||
"dep:libc",
|
||||
"dep:libloading",
|
||||
"dep:ordered-float",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:raw-window-metal",
|
||||
"dep:smallvec",
|
||||
"dep:windows",
|
||||
"gpu-allocator/vulkan",
|
||||
"windows/Win32",
|
||||
"windows/Win32_Devices_Display",
|
||||
"windows/Win32_Foundation",
|
||||
"windows/Win32_Graphics_Dxgi",
|
||||
"windows/Win32_Graphics_Dxgi_Common",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
]
|
||||
|
||||
[lib]
|
||||
name = "wgpu_hal"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[example]]
|
||||
name = "halmark"
|
||||
path = "examples/halmark/main.rs"
|
||||
|
||||
[[example]]
|
||||
name = "raw-gles"
|
||||
path = "examples/raw-gles.rs"
|
||||
required-features = ["gles"]
|
||||
|
||||
[[example]]
|
||||
name = "ray-traced-triangle"
|
||||
path = "examples/ray-traced-triangle/main.rs"
|
||||
|
||||
[dependencies.arrayvec]
|
||||
version = "0.7.1"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.bitflags]
|
||||
version = "2.9"
|
||||
|
||||
[dependencies.bytemuck]
|
||||
version = "1.22"
|
||||
features = [
|
||||
"extern_crate_alloc",
|
||||
"min_const_generics",
|
||||
"derive",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[dependencies.cfg-if]
|
||||
version = "1"
|
||||
|
||||
[dependencies.glow]
|
||||
version = "0.17"
|
||||
optional = true
|
||||
|
||||
[dependencies.hashbrown]
|
||||
version = "0.17"
|
||||
features = [
|
||||
"default-hasher",
|
||||
"inline-more",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[dependencies.log]
|
||||
version = "0.4.29"
|
||||
|
||||
[dependencies.naga]
|
||||
version = "30.0.0"
|
||||
|
||||
[dependencies.naga-types]
|
||||
version = "30.0.0"
|
||||
|
||||
[dependencies.ordered-float]
|
||||
version = ">=3, <6.0"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.parking_lot]
|
||||
version = "0.12.3"
|
||||
optional = true
|
||||
|
||||
[dependencies.profiling]
|
||||
version = "1.0.1"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.raw-window-handle]
|
||||
version = "0.6.2"
|
||||
default-features = false
|
||||
|
||||
[dependencies.static_assertions]
|
||||
version = "1.1"
|
||||
|
||||
[dependencies.thiserror]
|
||||
version = "2.0.12"
|
||||
default-features = false
|
||||
|
||||
[dependencies.wgpu-naga-bridge]
|
||||
version = "30.0.0"
|
||||
|
||||
[dependencies.wgpu-types]
|
||||
version = "30.0.0"
|
||||
default-features = false
|
||||
|
||||
[dev-dependencies.env_logger]
|
||||
version = "0.11"
|
||||
default-features = false
|
||||
|
||||
[dev-dependencies.glam]
|
||||
version = "0.33.0"
|
||||
|
||||
[dev-dependencies.naga]
|
||||
version = "30.0.0"
|
||||
features = [
|
||||
"wgsl-in",
|
||||
"termcolor",
|
||||
]
|
||||
|
||||
[dev-dependencies.winit]
|
||||
version = "0.30.8"
|
||||
features = ["android-native-activity"]
|
||||
|
||||
[build-dependencies.cfg_aliases]
|
||||
version = "0.2.2"
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies.js-sys]
|
||||
version = "0.3.104"
|
||||
optional = true
|
||||
default-features = true
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies.wasm-bindgen]
|
||||
version = "0.2.127"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies.web-sys]
|
||||
version = "0.3.104"
|
||||
features = [
|
||||
"default",
|
||||
"Window",
|
||||
"HtmlCanvasElement",
|
||||
"WebGl2RenderingContext",
|
||||
"OffscreenCanvas",
|
||||
"VideoFrame",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(all(unix, not(target_vendor = "apple"), not(target_family = "wasm")))'.dependencies.drm]
|
||||
version = "0.15"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(all(windows, not(target_arch = "aarch64"), target_env = "msvc"))'.dependencies.mach-dxcompiler-rs]
|
||||
version = "0.1.4"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(any(not(target_has_atomic = "64"), not(target_has_atomic = "ptr")))'.dependencies.portable-atomic]
|
||||
version = "1.10"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos", target_env = "ohos")))'.dev-dependencies.glutin]
|
||||
version = "0.32"
|
||||
features = [
|
||||
"egl",
|
||||
"wgl",
|
||||
"wayland",
|
||||
"x11",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos", target_env = "ohos")))'.dev-dependencies.glutin-winit]
|
||||
version = "0.5"
|
||||
features = [
|
||||
"egl",
|
||||
"wgl",
|
||||
"wayland",
|
||||
"x11",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.ash]
|
||||
version = "0.38"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.gpu-allocator]
|
||||
version = "0.28"
|
||||
features = ["hashbrown"]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.khronos-egl]
|
||||
version = "6"
|
||||
features = ["dynamic"]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.libloading]
|
||||
version = "0.8"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.renderdoc-sys]
|
||||
version = "1"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies.smallvec]
|
||||
version = "1.14"
|
||||
features = ["union"]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(not(target_has_atomic = "ptr"))'.dependencies.portable-atomic-util]
|
||||
version = "0.2.4"
|
||||
features = ["alloc"]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies.android_system_properties]
|
||||
version = "0.1.1"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies.ndk-sys]
|
||||
version = "0.6"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_os = "emscripten")'.dependencies.khronos-egl]
|
||||
version = "6"
|
||||
features = [
|
||||
"static",
|
||||
"no-pkg-config",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_os = "emscripten")'.dependencies.libloading]
|
||||
version = "0.8"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.block2]
|
||||
version = "0.6.2"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.bytemuck]
|
||||
version = "1.22"
|
||||
features = [
|
||||
"extern_crate_alloc",
|
||||
"min_const_generics",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2]
|
||||
version = "0.6.3"
|
||||
optional = true
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-core-foundation]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"CFCGTypes",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-core-graphics]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"CGColorSpace",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-foundation]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"NSError",
|
||||
"NSProcessInfo",
|
||||
"NSRange",
|
||||
"NSString",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-metal]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"block2",
|
||||
"MTLAllocation",
|
||||
"MTLBlitCommandEncoder",
|
||||
"MTLBlitPass",
|
||||
"MTLBuffer",
|
||||
"MTLCaptureManager",
|
||||
"MTLCaptureScope",
|
||||
"MTLCommandBuffer",
|
||||
"MTLCommandEncoder",
|
||||
"MTLCommandQueue",
|
||||
"MTLComputeCommandEncoder",
|
||||
"MTLComputePass",
|
||||
"MTLComputePipeline",
|
||||
"MTLCounters",
|
||||
"MTLDepthStencil",
|
||||
"MTLDevice",
|
||||
"MTLDrawable",
|
||||
"MTLEvent",
|
||||
"MTLLibrary",
|
||||
"MTLPipeline",
|
||||
"MTLPixelFormat",
|
||||
"MTLRenderCommandEncoder",
|
||||
"MTLRenderPass",
|
||||
"MTLRenderPipeline",
|
||||
"MTLResource",
|
||||
"MTLSampler",
|
||||
"MTLStageInputOutputDescriptor",
|
||||
"MTLTexture",
|
||||
"MTLTypes",
|
||||
"MTLVertexDescriptor",
|
||||
"MTLAccelerationStructure",
|
||||
"MTLAccelerationStructureTypes",
|
||||
"MTLAccelerationStructureCommandEncoder",
|
||||
"MTLResidencySet",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.objc2-quartz-core]
|
||||
version = "0.3.2"
|
||||
features = [
|
||||
"std",
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-graphics",
|
||||
"CALayer",
|
||||
"CAMetalLayer",
|
||||
"objc2-metal",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies.raw-window-metal]
|
||||
version = "1.0"
|
||||
optional = true
|
||||
|
||||
[target."cfg(unix)".dependencies.libc]
|
||||
version = "0.2.183"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(unix)".dependencies.wayland-sys]
|
||||
version = "0.31.3"
|
||||
features = [
|
||||
"client",
|
||||
"dlopen",
|
||||
"egl",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[target."cfg(windows)".dependencies.bit-set]
|
||||
version = "0.10"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(windows)".dependencies.glutin_wgl_sys]
|
||||
version = "0.6"
|
||||
optional = true
|
||||
|
||||
[target."cfg(windows)".dependencies.once_cell]
|
||||
version = "1.21"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(windows)".dependencies.range-alloc]
|
||||
version = "0.1"
|
||||
optional = true
|
||||
|
||||
[target."cfg(windows)".dependencies.windows]
|
||||
version = "0.62"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(windows)".dependencies.windows-core]
|
||||
version = "0.62"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[target."cfg(windows)".dependencies.windows-result]
|
||||
version = "0.4"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[lints.rust]
|
||||
missing_debug_implementations = "warn"
|
||||
|
||||
[lints.rust.unexpected_cfgs]
|
||||
level = "warn"
|
||||
priority = 0
|
||||
check-cfg = [
|
||||
'cfg(feature, values("cargo-clippy"))',
|
||||
"cfg(web_sys_unstable_apis)",
|
||||
]
|
||||
+365
@@ -0,0 +1,365 @@
|
||||
[package]
|
||||
name = "wgpu-hal"
|
||||
version.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
description = "Hardware abstraction layer for wgpu, the cross-platform, safe, pure-rust graphics API"
|
||||
homepage.workspace = true
|
||||
repository.workspace = true
|
||||
keywords.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
# Override the workspace's `rust-version` key. `wgpu-core` and its dependencies
|
||||
# have a less strict MSRV, to allow firefox more leeway in updating their Rust toolchain.
|
||||
#
|
||||
# See the repo README for more information on MSRV policy.
|
||||
rust-version = "1.87"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
# Ideally we would enable all the features.
|
||||
#
|
||||
# However, the dx12 features fail to be documented because the docs.rs runner cross-compiling under
|
||||
# x86_64-unknown-linux-gnu cannot compile in that environment at the moment.
|
||||
features = ["metal", "vulkan", "gles", "renderdoc"]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
targets = [
|
||||
"x86_64-unknown-linux-gnu",
|
||||
"x86_64-apple-darwin",
|
||||
"x86_64-pc-windows-msvc",
|
||||
"wasm32-unknown-unknown",
|
||||
]
|
||||
|
||||
[package.metadata.cargo-machete]
|
||||
# Cargo machete can't check build.rs dependencies. See https://github.com/bnjbvr/cargo-machete/issues/100
|
||||
ignored = ["cfg_aliases"]
|
||||
|
||||
[lints.rust]
|
||||
missing_debug_implementations = "warn"
|
||||
unexpected_cfgs = { level = "warn", check-cfg = [
|
||||
'cfg(feature, values("cargo-clippy"))', # objc's `msg_send` macro injects this in our code https://github.com/SSheldon/rust-objc/issues/125
|
||||
'cfg(web_sys_unstable_apis)', # web-sys uses this
|
||||
] }
|
||||
|
||||
[lib]
|
||||
|
||||
[features]
|
||||
########################
|
||||
### Backend Features ###
|
||||
########################
|
||||
|
||||
# The interaction of features between wgpu-core and wgpu-hal is a bit nuanced to get
|
||||
# the desired behavior on all platforms.
|
||||
#
|
||||
# At the wgpu-hal level the features are defined to enable the backends on all platforms
|
||||
# that can compile the backend. Vulkan for example will have an effect on Windows, Mac, Linux, and Android.
|
||||
# This is done with target conditional dependencies in wgpu-hal. This allows `--all-features`
|
||||
# to compile on all platforms.
|
||||
#
|
||||
# wgpu-core's features are defined to enable the backends on their "default" platforms. For example we
|
||||
# exclude the Vulkan backend on MacOS unless a separate feature `vulkan-portability` is enabled. In response
|
||||
# to these features, it enables features of platform specific crates. For example, the `vulkan` feature in wgpu-core
|
||||
# enables the `vulkan` feature in `wgpu-core-deps-windows-linux-android` which in turn enables the
|
||||
# `vulkan` feature in `wgpu-hal` _only_ on those platforms. If you enable the `vulkan-portability` feature, it
|
||||
# will enable the `vulkan` feature in `wgpu-core-deps-apple`. The only way to do this is unfortunately to have
|
||||
# a separate crate for each platform category that participates in the feature unification.
|
||||
#
|
||||
# This trick doesn't work at the `wgpu` level, because the `wgpu` -> `wgpu-core` dependency is conditional,
|
||||
# making the Cargo.toml signifigantly more complicated in all areas.
|
||||
#
|
||||
# See https://github.com/gfx-rs/wgpu/issues/3514, https://github.com/gfx-rs/wgpu/pull/7076,
|
||||
# and https://github.com/rust-lang/cargo/issues/1197 for more information.
|
||||
|
||||
## Enables the Metal backend when targeting Apple platforms.
|
||||
metal = [
|
||||
# Metal is only available on Apple platforms, therefore request MSL output also only if we target an Apple platform.
|
||||
"naga/msl-out",
|
||||
"dep:arrayvec",
|
||||
"dep:block2",
|
||||
"dep:bytemuck",
|
||||
"dep:libloading",
|
||||
"dep:objc2",
|
||||
"dep:objc2-core-foundation",
|
||||
"dep:objc2-core-graphics",
|
||||
"dep:objc2-foundation",
|
||||
"dep:objc2-metal",
|
||||
"dep:objc2-quartz-core",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:smallvec",
|
||||
"dep:raw-window-metal",
|
||||
]
|
||||
vulkan = [
|
||||
"naga/spv-out",
|
||||
"dep:android_system_properties",
|
||||
"dep:arrayvec",
|
||||
"dep:ash",
|
||||
"dep:bytemuck",
|
||||
"dep:libc",
|
||||
"dep:libloading",
|
||||
"dep:ordered-float",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:raw-window-metal",
|
||||
"dep:smallvec",
|
||||
"dep:windows",
|
||||
"gpu-allocator/vulkan",
|
||||
"windows/Win32",
|
||||
"windows/Win32_Devices_Display",
|
||||
"windows/Win32_Foundation",
|
||||
"windows/Win32_Graphics_Dxgi",
|
||||
"windows/Win32_Graphics_Dxgi_Common",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
]
|
||||
gles = [
|
||||
"dep:arrayvec",
|
||||
"dep:bytemuck",
|
||||
"dep:glow",
|
||||
"dep:glutin_wgl_sys",
|
||||
"dep:js-sys",
|
||||
"dep:khronos-egl",
|
||||
"dep:libloading",
|
||||
"dep:ndk-sys",
|
||||
"dep:objc2",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:wasm-bindgen",
|
||||
"dep:wayland-sys",
|
||||
"dep:web-sys",
|
||||
"dep:windows-result",
|
||||
"naga/glsl-out",
|
||||
"wgpu-types/web",
|
||||
"windows-result/std", # Need to enable this for the `Error` impl on `windows_result::Error` to work.
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
"windows/Win32_Graphics_OpenGL",
|
||||
"windows/Win32_System_LibraryLoader",
|
||||
"windows/Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
## Enables the DX12 backend when targeting Windows.
|
||||
dx12 = [
|
||||
"dep:arrayvec",
|
||||
"dep:bit-set",
|
||||
"dep:bytemuck",
|
||||
"dep:gpu-allocator",
|
||||
"dep:libloading",
|
||||
"dep:once_cell",
|
||||
"dep:ordered-float",
|
||||
"dep:parking_lot",
|
||||
"dep:profiling",
|
||||
"dep:range-alloc",
|
||||
"dep:windows-core",
|
||||
"gpu-allocator/d3d12",
|
||||
"naga/hlsl-out",
|
||||
"once_cell/std",
|
||||
"windows/Win32_Devices_DeviceAndDriverInstallation",
|
||||
"windows/Win32_Devices_Display",
|
||||
"windows/Win32_Graphics_Direct3D_Dxc",
|
||||
"windows/Win32_Graphics_Direct3D_Fxc",
|
||||
"windows/Win32_Graphics_Direct3D",
|
||||
"windows/Win32_Graphics_Direct3D12",
|
||||
"windows/Win32_Graphics_DirectComposition",
|
||||
"windows/Win32_Graphics_Dxgi_Common",
|
||||
"windows/Win32_Graphics_Gdi",
|
||||
"windows/Win32_Security",
|
||||
"windows/Win32_System_Diagnostics_Debug",
|
||||
"windows/Win32_System_Kernel",
|
||||
"windows/Win32_System_Performance",
|
||||
"windows/Win32_System_Threading",
|
||||
"windows/Win32_UI_WindowsAndMessaging",
|
||||
]
|
||||
|
||||
###########################
|
||||
### Misc Other Features ###
|
||||
###########################
|
||||
|
||||
static-dxc = ["dep:mach-dxcompiler-rs"]
|
||||
renderdoc = ["dep:libloading", "dep:renderdoc-sys"]
|
||||
fragile-send-sync-non-atomic-wasm = [
|
||||
"wgpu-types/fragile-send-sync-non-atomic-wasm",
|
||||
]
|
||||
portable-atomic = ["dep:portable-atomic", "dep:portable-atomic-util"]
|
||||
|
||||
###################################
|
||||
### Internal Debugging Features ###
|
||||
###################################
|
||||
|
||||
# Panic when running into a device lost error (for debugging purposes).
|
||||
# Only affects the d3d12 and vulkan backends.
|
||||
device_lost_panic = []
|
||||
# Panic when running into an internal error other than out-of-memory and device lost
|
||||
# (for debugging purposes).
|
||||
#
|
||||
# Only affects the d3d12 and vulkan backends.
|
||||
internal_error_panic = []
|
||||
# Tracks validation errors in a `VALIDATION_CANARY` static.
|
||||
validation_canary = ["dep:parking_lot"]
|
||||
|
||||
[[example]]
|
||||
name = "halmark"
|
||||
|
||||
[[example]]
|
||||
name = "raw-gles"
|
||||
required-features = ["gles"]
|
||||
|
||||
#####################
|
||||
### Platform: All ###
|
||||
#####################
|
||||
|
||||
[dependencies]
|
||||
naga.workspace = true
|
||||
wgpu-naga-bridge.workspace = true
|
||||
naga-types = { workspace = true }
|
||||
wgpu-types = { workspace = true, default-features = false }
|
||||
|
||||
# Dependencies in the lib and empty backend
|
||||
bitflags.workspace = true
|
||||
cfg-if.workspace = true
|
||||
log = { workspace = true }
|
||||
parking_lot = { workspace = true, optional = true }
|
||||
raw-window-handle.workspace = true
|
||||
thiserror.workspace = true
|
||||
|
||||
# Target agnostic dependencies used only in backends.
|
||||
arrayvec = { workspace = true, optional = true }
|
||||
bytemuck = { workspace = true, optional = true, features = ["derive"] }
|
||||
hashbrown = { workspace = true }
|
||||
ordered-float = { workspace = true, optional = true }
|
||||
profiling = { workspace = true, optional = true, default-features = false }
|
||||
static_assertions = { workspace = true }
|
||||
|
||||
# Backend: GLES
|
||||
glow = { workspace = true, optional = true }
|
||||
|
||||
########################
|
||||
### Platform: Native ###
|
||||
########################
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
# Backend: Vulkan and Dx12
|
||||
gpu-allocator = { workspace = true, optional = true }
|
||||
# Backend: Vulkan
|
||||
ash = { workspace = true, optional = true }
|
||||
smallvec = { workspace = true, optional = true, features = ["union"] }
|
||||
# Backend: GLES
|
||||
khronos-egl = { workspace = true, features = ["dynamic"], optional = true }
|
||||
libloading = { workspace = true, optional = true }
|
||||
renderdoc-sys = { workspace = true, optional = true }
|
||||
|
||||
##########################
|
||||
### Platform: All Unix ###
|
||||
##########################
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
# Backend: Vulkan
|
||||
libc = { workspace = true, optional = true }
|
||||
# backend: GLES
|
||||
wayland-sys = { version = "0.31.3", features = [
|
||||
"client",
|
||||
"dlopen",
|
||||
"egl",
|
||||
], optional = true }
|
||||
|
||||
## Support creating textures from DRM display/window handles.
|
||||
[target.'cfg(all(unix, not(target_vendor = "apple"), not(target_family = "wasm")))'.dependencies]
|
||||
drm = { version = "0.15", optional = true }
|
||||
|
||||
#########################
|
||||
### Platform: Windows ###
|
||||
#########################
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# Backend: Dx12 and GLES
|
||||
windows = { workspace = true, optional = true }
|
||||
windows-core = { workspace = true, optional = true }
|
||||
windows-result = { workspace = true, optional = true }
|
||||
# Backend: Dx12
|
||||
bit-set = { workspace = true, optional = true }
|
||||
range-alloc = { workspace = true, optional = true }
|
||||
once_cell = { workspace = true, optional = true }
|
||||
# backend: GLES
|
||||
glutin_wgl_sys = { workspace = true, optional = true }
|
||||
|
||||
### Platform: x86/x86_64 Windows ###
|
||||
# This doesn't support aarch64. See https://github.com/gfx-rs/wgpu/issues/6860.
|
||||
# This doesn't support x86_64-pc-windows-gnu. See https://github.com/gfx-rs/wgpu/issues/8303
|
||||
#
|
||||
# ⚠️ Keep in sync with static_dxc cfg in build.rs and cfg_alias in `wgpu` crate ⚠️
|
||||
[target.'cfg(all(windows, not(target_arch = "aarch64"), target_env = "msvc"))'.dependencies]
|
||||
mach-dxcompiler-rs = { workspace = true, optional = true }
|
||||
|
||||
#######################
|
||||
### Platform: Apple ###
|
||||
#######################
|
||||
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies]
|
||||
# Backend: Metal
|
||||
block2 = { workspace = true, optional = true }
|
||||
bytemuck = { workspace = true, optional = true }
|
||||
objc2 = { workspace = true, optional = true }
|
||||
objc2-core-foundation = { workspace = true, optional = true }
|
||||
objc2-core-graphics = { workspace = true, optional = true }
|
||||
objc2-foundation = { workspace = true, optional = true }
|
||||
objc2-metal = { workspace = true, optional = true }
|
||||
objc2-quartz-core = { workspace = true, optional = true }
|
||||
|
||||
# backend: Metal + Vulkan
|
||||
raw-window-metal = { workspace = true, optional = true }
|
||||
|
||||
#########################
|
||||
### Platform: Android ###
|
||||
#########################
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
android_system_properties = { workspace = true, optional = true }
|
||||
ndk-sys = { workspace = true, optional = true }
|
||||
|
||||
#############################
|
||||
### Platform: Webassembly ###
|
||||
#############################
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies]
|
||||
# Backend: GLES
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
web-sys = { workspace = true, optional = true, features = [
|
||||
"default",
|
||||
"Window",
|
||||
"HtmlCanvasElement",
|
||||
"WebGl2RenderingContext",
|
||||
"OffscreenCanvas",
|
||||
"VideoFrame",
|
||||
] }
|
||||
js-sys = { workspace = true, optional = true, default-features = true }
|
||||
|
||||
############################
|
||||
### Platform: Emscripten ###
|
||||
############################
|
||||
|
||||
[target.'cfg(target_os = "emscripten")'.dependencies]
|
||||
# Backend: GLES
|
||||
khronos-egl = { workspace = true, optional = true, features = [
|
||||
"static",
|
||||
"no-pkg-config",
|
||||
] }
|
||||
# Note: it's unused by emscripten, but we keep it to have single code base in egl.rs
|
||||
libloading = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(any(not(target_has_atomic = "64"), not(target_has_atomic = "ptr")))'.dependencies]
|
||||
portable-atomic = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(not(target_has_atomic = "ptr"))'.dependencies]
|
||||
portable-atomic-util = { workspace = true, features = [
|
||||
"alloc",
|
||||
], optional = true }
|
||||
|
||||
[build-dependencies]
|
||||
cfg_aliases.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
env_logger.workspace = true
|
||||
glam.workspace = true # for ray-traced-triangle example
|
||||
naga = { workspace = true, features = ["wgsl-in", "termcolor"] }
|
||||
winit.workspace = true # for "halmark" example
|
||||
|
||||
### Platform: Windows + MacOS + Linux for "raw-gles" example ###
|
||||
[target.'cfg(not(any(target_arch = "wasm32", target_os = "ios", target_os = "visionos", target_env = "ohos")))'.dev-dependencies]
|
||||
glutin-winit = { workspace = true, features = ["egl", "wgl", "wayland", "x11"] }
|
||||
glutin = { workspace = true, features = ["egl", "wgl", "wayland", "x11"] }
|
||||
Vendored
+176
@@ -0,0 +1,176 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 The gfx-rs developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+119
@@ -0,0 +1,119 @@
|
||||
# `wgpu_hal`: a cross-platform unsafe graphics abstraction
|
||||
|
||||
This crate defines a set of traits abstracting over modern graphics APIs,
|
||||
with implementations ("backends") for Vulkan, Metal, Direct3D, and GL.
|
||||
|
||||
`wgpu_hal` is a spiritual successor to
|
||||
[gfx-hal](https://github.com/gfx-rs/gfx), but with reduced scope, and
|
||||
oriented towards WebGPU implementation goals. It has no overhead for
|
||||
validation or tracking, and the API translation overhead is kept to the bare
|
||||
minimum by the design of WebGPU. This API can be used for resource-demanding
|
||||
applications and engines.
|
||||
|
||||
The `wgpu_hal` crate's main design choices:
|
||||
|
||||
- Our traits are meant to be _portable_: proper use
|
||||
should get equivalent results regardless of the backend.
|
||||
|
||||
- Our traits' contracts are _unsafe_: implementations perform minimal
|
||||
validation, if any, and incorrect use will often cause undefined behavior.
|
||||
This allows us to minimize the overhead we impose over the underlying
|
||||
graphics system. If you need safety, the [`wgpu-core`] crate provides a
|
||||
safe API for driving `wgpu_hal`, implementing all necessary validation,
|
||||
resource state tracking, and so on. (Note that `wgpu-core` is designed for
|
||||
use via FFI; the [`wgpu`] crate provides more idiomatic Rust bindings for
|
||||
`wgpu-core`.) Or, you can do your own validation.
|
||||
|
||||
- In the same vein, returned errors _only cover cases the user can't
|
||||
anticipate_, like running out of memory or losing the device. Any errors
|
||||
that the user could reasonably anticipate are their responsibility to
|
||||
avoid. For example, `wgpu_hal` returns no error for mapping a buffer that's
|
||||
not mappable: as the buffer creator, the user should already know if they
|
||||
can map it.
|
||||
|
||||
- We use _static dispatch_. The traits are not
|
||||
generally object-safe. You must select a specific backend type
|
||||
like [`vulkan::Api`] or [`metal::Api`], and then use that
|
||||
according to the main traits, or call backend-specific methods.
|
||||
|
||||
- We use _idiomatic Rust parameter passing_,
|
||||
taking objects by reference, returning them by value, and so on,
|
||||
unlike `wgpu-core`, which refers to objects by ID.
|
||||
|
||||
- We map buffer contents _persistently_. This means that the buffer
|
||||
can remain mapped on the CPU while the GPU reads or writes to it.
|
||||
You must explicitly indicate when data might need to be
|
||||
transferred between CPU and GPU, if `wgpu_hal` indicates that the
|
||||
mapping is not coherent (that is, automatically synchronized
|
||||
between the two devices).
|
||||
|
||||
- You must record _explicit barriers_ between different usages of a
|
||||
resource. For example, if a buffer is written to by a compute
|
||||
shader, and then used as and index buffer to a draw call, you
|
||||
must use [`CommandEncoder::transition_buffers`] between those two
|
||||
operations.
|
||||
|
||||
- Pipeline layouts are _explicitly specified_ when setting bind
|
||||
group. Incompatible layouts disturb groups bound at higher indices.
|
||||
|
||||
- The API _accepts collections as iterators_, to avoid forcing the user to
|
||||
store data in particular containers. The implementation doesn't guarantee
|
||||
that any of the iterators are drained, unless stated otherwise by the
|
||||
function documentation. For this reason, we recommend that iterators don't
|
||||
do any mutating work.
|
||||
|
||||
Unfortunately, `wgpu_hal`'s safety requirements are not fully documented.
|
||||
Ideally, all trait methods would have doc comments setting out the
|
||||
requirements users must meet to ensure correct and portable behavior. If you
|
||||
are aware of a specific requirement that a backend imposes that is not
|
||||
ensured by the traits' documented rules, please file an issue. Or, if you are
|
||||
a capable technical writer, please file a pull request!
|
||||
|
||||
[`wgpu-core`]: https://crates.io/crates/wgpu-core
|
||||
[`wgpu`]: https://crates.io/crates/wgpu
|
||||
[`vulkan::Api`]: vulkan/struct.Api.html
|
||||
[`metal::Api`]: metal/struct.Api.html
|
||||
|
||||
## Primary backends
|
||||
|
||||
The `wgpu_hal` crate has full-featured backends implemented on the following
|
||||
platform graphics APIs:
|
||||
|
||||
- Vulkan, available on Linux, Android, and Windows, using the [`ash`] crate's
|
||||
Vulkan bindings. It's also available on macOS, if you install [MoltenVK].
|
||||
|
||||
- Metal on macOS, using the [`metal`] crate's bindings.
|
||||
|
||||
- Direct3D 12 on Windows, using the [`windows`] crate's bindings.
|
||||
|
||||
[`ash`]: https://crates.io/crates/ash
|
||||
[MoltenVK]: https://github.com/KhronosGroup/MoltenVK
|
||||
[`metal`]: https://crates.io/crates/metal
|
||||
[`windows`]: https://crates.io/crates/windows
|
||||
|
||||
## Secondary backends
|
||||
|
||||
The `wgpu_hal` crate has a partial implementation based on the following
|
||||
platform graphics API:
|
||||
|
||||
- The GL backend is available anywhere OpenGL, OpenGL ES, or WebGL are
|
||||
available. See the [`gles`] module documentation for details.
|
||||
|
||||
[`gles`]: gles/index.html
|
||||
|
||||
You can see what capabilities an adapter is missing by checking the
|
||||
[`DownlevelCapabilities`][tdc] in [`ExposedAdapter::capabilities`], available
|
||||
from [`Instance::enumerate_adapters`].
|
||||
|
||||
The API is generally designed to fit the primary backends better than the
|
||||
secondary backends, so the latter may impose more overhead.
|
||||
|
||||
[tdc]: wgt::DownlevelCapabilities
|
||||
|
||||
## Debugging
|
||||
|
||||
Most of the information on the wiki [Debugging wgpu Applications][wiki-debug]
|
||||
page still applies to this API, with the exception of API tracing/replay
|
||||
functionality, which is only available in `wgpu-core`.
|
||||
|
||||
[wiki-debug]: https://github.com/gfx-rs/wgpu/wiki/Debugging-wgpu-Applications
|
||||
Vendored
+36
@@ -0,0 +1,36 @@
|
||||
fn main() {
|
||||
cfg_aliases::cfg_aliases! {
|
||||
native: { not(target_arch = "wasm32") },
|
||||
send_sync: { any(
|
||||
not(target_arch = "wasm32"),
|
||||
all(feature = "fragile-send-sync-non-atomic-wasm", not(target_feature = "atomics"))
|
||||
) },
|
||||
webgl: { all(target_arch = "wasm32", not(target_os = "emscripten"), gles) },
|
||||
Emscripten: { all(target_os = "emscripten", gles) },
|
||||
dx12: { all(target_os = "windows", feature = "dx12") },
|
||||
gles: { all(feature = "gles") },
|
||||
// Within the GL ES backend, use `std` and be Send + Sync only if we are using a target
|
||||
// that, among the ones where the GL ES backend is supported, has `std`.
|
||||
gles_with_std: { all(
|
||||
feature = "gles",
|
||||
any(
|
||||
not(target_arch = "wasm32"),
|
||||
// Accept wasm32-unknown-unknown, which uniquely has a stub `std`
|
||||
all(target_vendor = "unknown", target_os = "unknown"),
|
||||
// Accept wasm32-unknown-emscripten and similar, which has a real `std`
|
||||
target_os = "emscripten"
|
||||
)
|
||||
) },
|
||||
metal: { all(target_vendor = "apple", feature = "metal") },
|
||||
vulkan: { all(not(target_arch = "wasm32"), feature = "vulkan") },
|
||||
drm: { all(
|
||||
feature = "drm",
|
||||
any(target_os = "linux", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd")
|
||||
) },
|
||||
any_backend: { any(dx12, metal, vulkan, gles) },
|
||||
// ⚠️ Keep in sync with target.cfg() definition in Cargo.toml and cfg_alias in `wgpu` crate ⚠️
|
||||
static_dxc: { all(target_os = "windows", feature = "static-dxc", not(target_arch = "aarch64"), target_env = "msvc") },
|
||||
supports_64bit_atomics: { target_has_atomic = "64" },
|
||||
supports_ptr_atomics: { target_has_atomic = "ptr" }
|
||||
}
|
||||
}
|
||||
+919
@@ -0,0 +1,919 @@
|
||||
//! This example shows basic usage of wgpu-hal by rendering
|
||||
//! a ton of moving sprites, each with a separate texture and draw call.
|
||||
extern crate wgpu_hal as hal;
|
||||
|
||||
use hal::{
|
||||
Adapter as _, CommandEncoder as _, Device as _, Instance as _, Queue as _, Surface as _,
|
||||
};
|
||||
use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
event::{ElementState, KeyEvent, WindowEvent},
|
||||
event_loop::{ActiveEventLoop, ControlFlow},
|
||||
keyboard::{Key, NamedKey},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
use std::{
|
||||
borrow::{Borrow, Cow},
|
||||
iter,
|
||||
num::NonZeroU64,
|
||||
ptr,
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
const MAX_BUNNIES: usize = 1 << 20;
|
||||
const BUNNY_SIZE: f32 = 0.15 * 256.0;
|
||||
const GRAVITY: f32 = -9.8 * 100.0;
|
||||
const MAX_VELOCITY: f32 = 750.0;
|
||||
const DESIRED_MAX_LATENCY: u32 = 2;
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
struct Globals {
|
||||
mvp: [[f32; 4]; 4],
|
||||
size: [f32; 2],
|
||||
pad: [f32; 2],
|
||||
}
|
||||
|
||||
#[repr(C, align(256))]
|
||||
#[derive(Clone, Copy)]
|
||||
struct Locals {
|
||||
position: [f32; 2],
|
||||
velocity: [f32; 2],
|
||||
color: u32,
|
||||
_pad: u32,
|
||||
}
|
||||
|
||||
struct ExecutionContext<A: hal::Api> {
|
||||
encoder: A::CommandEncoder,
|
||||
fence: A::Fence,
|
||||
fence_value: hal::FenceValue,
|
||||
used_views: Vec<A::TextureView>,
|
||||
used_cmd_bufs: Vec<A::CommandBuffer>,
|
||||
frames_recorded: usize,
|
||||
}
|
||||
|
||||
impl<A: hal::Api> ExecutionContext<A> {
|
||||
unsafe fn wait_and_clear(&mut self, device: &A::Device) {
|
||||
device.wait(&self.fence, self.fence_value, None).unwrap();
|
||||
self.encoder.reset_all(self.used_cmd_bufs.drain(..));
|
||||
for view in self.used_views.drain(..) {
|
||||
device.destroy_texture_view(view);
|
||||
}
|
||||
self.frames_recorded = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
struct Example<A: hal::Api> {
|
||||
instance: A::Instance,
|
||||
adapter: A::Adapter,
|
||||
surface: A::Surface,
|
||||
surface_format: wgpu_types::TextureFormat,
|
||||
device: A::Device,
|
||||
queue: A::Queue,
|
||||
global_group: A::BindGroup,
|
||||
local_group: A::BindGroup,
|
||||
global_group_layout: A::BindGroupLayout,
|
||||
local_group_layout: A::BindGroupLayout,
|
||||
pipeline_layout: A::PipelineLayout,
|
||||
shader: A::ShaderModule,
|
||||
pipeline: A::RenderPipeline,
|
||||
bunnies: Vec<Locals>,
|
||||
local_buffer: A::Buffer,
|
||||
local_alignment: u32,
|
||||
global_buffer: A::Buffer,
|
||||
sampler: A::Sampler,
|
||||
texture: A::Texture,
|
||||
texture_view: A::TextureView,
|
||||
contexts: Vec<ExecutionContext<A>>,
|
||||
context_index: usize,
|
||||
extent: [u32; 2],
|
||||
start: Instant,
|
||||
}
|
||||
|
||||
impl<A: hal::Api> Example<A> {
|
||||
fn init(window: &winit::window::Window) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
// The Instance can be initialized with the DisplayHandle from the EventLoop as well
|
||||
let raw_display_handle = window.display_handle()?;
|
||||
|
||||
let instance_desc = hal::InstanceDescriptor {
|
||||
name: "example",
|
||||
flags: wgpu_types::InstanceFlags::from_build_config().with_env(),
|
||||
memory_budget_thresholds: wgpu_types::MemoryBudgetThresholds::default(),
|
||||
// Can't rely on having DXC available, so use FXC instead
|
||||
backend_options: wgpu_types::BackendOptions::default(),
|
||||
telemetry: None,
|
||||
display: Some(raw_display_handle),
|
||||
};
|
||||
let instance = unsafe { A::Instance::init(&instance_desc)? };
|
||||
let surface = {
|
||||
let raw_window_handle = window.window_handle()?.as_raw();
|
||||
|
||||
unsafe {
|
||||
instance
|
||||
.create_surface(raw_display_handle.as_raw(), raw_window_handle)
|
||||
.unwrap()
|
||||
}
|
||||
};
|
||||
|
||||
let (adapter, capabilities) = unsafe {
|
||||
let mut adapters = instance.enumerate_adapters(Some(&surface));
|
||||
if adapters.is_empty() {
|
||||
return Err("no adapters found".into());
|
||||
}
|
||||
let exposed = adapters.swap_remove(0);
|
||||
(exposed.adapter, exposed.capabilities)
|
||||
};
|
||||
|
||||
let surface_caps = unsafe { adapter.surface_capabilities(&surface) }
|
||||
.ok_or("failed to get surface capabilities")?;
|
||||
log::info!("Surface caps: {surface_caps:#?}");
|
||||
|
||||
let hal::OpenDevice { device, queue } = unsafe {
|
||||
adapter
|
||||
.open(
|
||||
wgpu_types::Features::empty(),
|
||||
&wgpu_types::Limits::default(),
|
||||
&wgpu_types::MemoryHints::default(),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let window_size: (u32, u32) = window.inner_size().into();
|
||||
let surface_config = hal::SurfaceConfiguration {
|
||||
maximum_frame_latency: DESIRED_MAX_LATENCY.clamp(
|
||||
*surface_caps.maximum_frame_latency.start(),
|
||||
*surface_caps.maximum_frame_latency.end(),
|
||||
),
|
||||
present_mode: wgpu_types::PresentMode::Fifo,
|
||||
composite_alpha_mode: wgpu_types::CompositeAlphaMode::Opaque,
|
||||
format: wgpu_types::TextureFormat::Bgra8UnormSrgb,
|
||||
color_space: wgpu_types::SurfaceColorSpace::Srgb,
|
||||
extent: wgpu_types::Extent3d {
|
||||
width: window_size.0,
|
||||
height: window_size.1,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
view_formats: vec![],
|
||||
};
|
||||
unsafe {
|
||||
surface.configure(&device, &surface_config).unwrap();
|
||||
};
|
||||
|
||||
let naga_shader = {
|
||||
let shader_file = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("examples")
|
||||
.join("halmark")
|
||||
.join("shader.wgsl");
|
||||
let source = std::fs::read_to_string(shader_file).unwrap();
|
||||
let module = naga::front::wgsl::Frontend::new().parse(&source).unwrap();
|
||||
let info = naga::valid::Validator::new(
|
||||
naga::valid::ValidationFlags::all(),
|
||||
naga::valid::Capabilities::empty(),
|
||||
)
|
||||
.validate(&module)
|
||||
.unwrap();
|
||||
hal::NagaShader {
|
||||
module: Cow::Owned(module),
|
||||
info,
|
||||
debug_source: None,
|
||||
}
|
||||
};
|
||||
let shader_desc = hal::ShaderModuleDescriptor {
|
||||
label: None,
|
||||
runtime_checks: wgpu_types::ShaderRuntimeChecks::checked(),
|
||||
};
|
||||
let shader = unsafe {
|
||||
device
|
||||
.create_shader_module(&shader_desc, hal::ShaderInput::Naga(naga_shader))
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let global_bgl_desc = hal::BindGroupLayoutDescriptor {
|
||||
label: None,
|
||||
flags: hal::BindGroupLayoutFlags::empty(),
|
||||
entries: &[
|
||||
wgpu_types::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu_types::ShaderStages::VERTEX,
|
||||
ty: wgpu_types::BindingType::Buffer {
|
||||
ty: wgpu_types::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: wgpu_types::BufferSize::new(size_of::<Globals>() as _),
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu_types::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu_types::ShaderStages::FRAGMENT,
|
||||
ty: wgpu_types::BindingType::Texture {
|
||||
sample_type: wgpu_types::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu_types::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu_types::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu_types::ShaderStages::FRAGMENT,
|
||||
ty: wgpu_types::BindingType::Sampler(wgpu_types::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
let global_group_layout =
|
||||
unsafe { device.create_bind_group_layout(&global_bgl_desc).unwrap() };
|
||||
|
||||
let local_bgl_desc = hal::BindGroupLayoutDescriptor {
|
||||
label: None,
|
||||
flags: hal::BindGroupLayoutFlags::empty(),
|
||||
entries: &[wgpu_types::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu_types::ShaderStages::VERTEX,
|
||||
ty: wgpu_types::BindingType::Buffer {
|
||||
ty: wgpu_types::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: true,
|
||||
min_binding_size: wgpu_types::BufferSize::new(size_of::<Locals>() as _),
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
};
|
||||
let local_group_layout =
|
||||
unsafe { device.create_bind_group_layout(&local_bgl_desc).unwrap() };
|
||||
|
||||
let pipeline_layout_desc = hal::PipelineLayoutDescriptor {
|
||||
label: None,
|
||||
flags: hal::PipelineLayoutFlags::empty(),
|
||||
bind_group_layouts: &[Some(&global_group_layout), Some(&local_group_layout)],
|
||||
immediate_size: 0,
|
||||
};
|
||||
let pipeline_layout = unsafe {
|
||||
device
|
||||
.create_pipeline_layout(&pipeline_layout_desc)
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
let constants = naga::back::PipelineConstants::default();
|
||||
let pipeline_desc = hal::RenderPipelineDescriptor {
|
||||
label: None,
|
||||
layout: &pipeline_layout,
|
||||
vertex_processor: hal::VertexProcessor::Standard {
|
||||
vertex_stage: hal::ProgrammableStage {
|
||||
module: &shader,
|
||||
entry_point: "vs_main",
|
||||
constants: &constants,
|
||||
zero_initialize_workgroup_memory: true,
|
||||
},
|
||||
vertex_buffers: &[],
|
||||
},
|
||||
fragment_stage: Some(hal::ProgrammableStage {
|
||||
module: &shader,
|
||||
entry_point: "fs_main",
|
||||
constants: &constants,
|
||||
zero_initialize_workgroup_memory: true,
|
||||
}),
|
||||
primitive: wgpu_types::PrimitiveState {
|
||||
topology: wgpu_types::PrimitiveTopology::TriangleStrip,
|
||||
..wgpu_types::PrimitiveState::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu_types::MultisampleState::default(),
|
||||
color_targets: &[Some(wgpu_types::ColorTargetState {
|
||||
format: surface_config.format,
|
||||
blend: Some(wgpu_types::BlendState::ALPHA_BLENDING),
|
||||
write_mask: wgpu_types::ColorWrites::default(),
|
||||
})],
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
};
|
||||
let pipeline = unsafe { device.create_render_pipeline(&pipeline_desc).unwrap() };
|
||||
|
||||
let texture_data = [0xFFu8; 4];
|
||||
|
||||
let staging_buffer_desc = hal::BufferDescriptor {
|
||||
label: Some("stage"),
|
||||
size: texture_data.len() as wgpu_types::BufferAddress,
|
||||
usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::COPY_SRC,
|
||||
memory_flags: hal::MemoryFlags::TRANSIENT | hal::MemoryFlags::PREFER_COHERENT,
|
||||
};
|
||||
let staging_buffer = unsafe { device.create_buffer(&staging_buffer_desc).unwrap() };
|
||||
unsafe {
|
||||
let mapping = device
|
||||
.map_buffer(&staging_buffer, 0..staging_buffer_desc.size)
|
||||
.unwrap();
|
||||
ptr::copy_nonoverlapping(
|
||||
texture_data.as_ptr(),
|
||||
mapping.ptr.as_ptr(),
|
||||
texture_data.len(),
|
||||
);
|
||||
device.unmap_buffer(&staging_buffer);
|
||||
assert!(mapping.is_coherent);
|
||||
}
|
||||
|
||||
let texture_desc = hal::TextureDescriptor {
|
||||
label: None,
|
||||
size: wgpu_types::Extent3d {
|
||||
width: 1,
|
||||
height: 1,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu_types::TextureDimension::D2,
|
||||
format: wgpu_types::TextureFormat::Rgba8UnormSrgb,
|
||||
usage: wgpu_types::TextureUses::COPY_DST | wgpu_types::TextureUses::RESOURCE,
|
||||
memory_flags: hal::MemoryFlags::empty(),
|
||||
view_formats: vec![],
|
||||
};
|
||||
let texture = unsafe { device.create_texture(&texture_desc).unwrap() };
|
||||
|
||||
let cmd_encoder_desc = hal::CommandEncoderDescriptor {
|
||||
label: None,
|
||||
queue: &queue,
|
||||
};
|
||||
let mut cmd_encoder = unsafe { device.create_command_encoder(&cmd_encoder_desc).unwrap() };
|
||||
unsafe { cmd_encoder.begin_encoding(Some("init")).unwrap() };
|
||||
{
|
||||
let buffer_barrier = hal::BufferBarrier {
|
||||
buffer: &staging_buffer,
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::BufferUses::empty(),
|
||||
to: wgpu_types::BufferUses::COPY_SRC,
|
||||
},
|
||||
};
|
||||
let texture_barrier1 = hal::TextureBarrier {
|
||||
texture: &texture,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::TextureUses::UNINITIALIZED,
|
||||
to: wgpu_types::TextureUses::COPY_DST,
|
||||
},
|
||||
};
|
||||
let texture_barrier2 = hal::TextureBarrier {
|
||||
texture: &texture,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::TextureUses::COPY_DST,
|
||||
to: wgpu_types::TextureUses::RESOURCE,
|
||||
},
|
||||
};
|
||||
let copy = hal::BufferTextureCopy {
|
||||
buffer_layout: wgpu_types::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(4),
|
||||
rows_per_image: None,
|
||||
},
|
||||
texture_base: hal::TextureCopyBase {
|
||||
origin: wgpu_types::Origin3d::ZERO,
|
||||
mip_level: 0,
|
||||
array_layer: 0,
|
||||
aspect: hal::FormatAspects::COLOR,
|
||||
},
|
||||
size: hal::CopyExtent {
|
||||
width: 1,
|
||||
height: 1,
|
||||
depth: 1,
|
||||
},
|
||||
};
|
||||
unsafe {
|
||||
cmd_encoder.transition_buffers(iter::once(buffer_barrier));
|
||||
cmd_encoder.transition_textures(iter::once(texture_barrier1));
|
||||
cmd_encoder.copy_buffer_to_texture(&staging_buffer, &texture, iter::once(copy));
|
||||
cmd_encoder.transition_textures(iter::once(texture_barrier2));
|
||||
}
|
||||
}
|
||||
|
||||
let sampler_desc = hal::SamplerDescriptor {
|
||||
label: None,
|
||||
address_modes: [wgpu_types::AddressMode::ClampToEdge; 3],
|
||||
mag_filter: wgpu_types::FilterMode::Linear,
|
||||
min_filter: wgpu_types::FilterMode::Nearest,
|
||||
mipmap_filter: wgpu_types::MipmapFilterMode::Nearest,
|
||||
lod_clamp: 0.0..32.0,
|
||||
compare: None,
|
||||
anisotropy_clamp: 1,
|
||||
border_color: None,
|
||||
};
|
||||
let sampler = unsafe { device.create_sampler(&sampler_desc).unwrap() };
|
||||
|
||||
let globals = Globals {
|
||||
// cgmath::ortho() projection
|
||||
mvp: [
|
||||
[2.0 / window_size.0 as f32, 0.0, 0.0, 0.0],
|
||||
[0.0, 2.0 / window_size.1 as f32, 0.0, 0.0],
|
||||
[0.0, 0.0, 1.0, 0.0],
|
||||
[-1.0, -1.0, 0.0, 1.0],
|
||||
],
|
||||
size: [BUNNY_SIZE; 2],
|
||||
pad: [0.0; 2],
|
||||
};
|
||||
|
||||
let global_buffer_desc = hal::BufferDescriptor {
|
||||
label: Some("global"),
|
||||
size: size_of::<Globals>() as wgpu_types::BufferAddress,
|
||||
usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::UNIFORM,
|
||||
memory_flags: hal::MemoryFlags::PREFER_COHERENT,
|
||||
};
|
||||
let global_buffer = unsafe {
|
||||
let buffer = device.create_buffer(&global_buffer_desc).unwrap();
|
||||
let mapping = device
|
||||
.map_buffer(&buffer, 0..global_buffer_desc.size)
|
||||
.unwrap();
|
||||
ptr::copy_nonoverlapping(
|
||||
&globals as *const Globals as *const u8,
|
||||
mapping.ptr.as_ptr(),
|
||||
size_of::<Globals>(),
|
||||
);
|
||||
device.unmap_buffer(&buffer);
|
||||
assert!(mapping.is_coherent);
|
||||
buffer
|
||||
};
|
||||
|
||||
let local_alignment = wgpu_types::math::align_to(
|
||||
size_of::<Locals>() as u32,
|
||||
capabilities.limits.min_uniform_buffer_offset_alignment,
|
||||
);
|
||||
let local_buffer_desc = hal::BufferDescriptor {
|
||||
label: Some("local"),
|
||||
size: (MAX_BUNNIES as wgpu_types::BufferAddress)
|
||||
* (local_alignment as wgpu_types::BufferAddress),
|
||||
usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::UNIFORM,
|
||||
memory_flags: hal::MemoryFlags::PREFER_COHERENT,
|
||||
};
|
||||
let local_buffer = unsafe { device.create_buffer(&local_buffer_desc).unwrap() };
|
||||
|
||||
let view_desc = hal::TextureViewDescriptor {
|
||||
label: None,
|
||||
format: texture_desc.format,
|
||||
dimension: wgpu_types::TextureViewDimension::D2,
|
||||
usage: wgpu_types::TextureUses::RESOURCE,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
};
|
||||
let texture_view = unsafe { device.create_texture_view(&texture, &view_desc).unwrap() };
|
||||
|
||||
let global_group = {
|
||||
// SAFETY: This is the same size that was specified for buffer creation.
|
||||
let global_buffer_binding = hal::BufferBinding::new_unchecked(
|
||||
&global_buffer,
|
||||
0,
|
||||
NonZeroU64::new(global_buffer_desc.size),
|
||||
);
|
||||
let texture_binding = hal::TextureBinding {
|
||||
view: &texture_view,
|
||||
usage: wgpu_types::TextureUses::RESOURCE,
|
||||
};
|
||||
let global_group_desc = hal::BindGroupDescriptor {
|
||||
label: Some("global"),
|
||||
layout: &global_group_layout,
|
||||
buffers: &[global_buffer_binding],
|
||||
samplers: &[&sampler],
|
||||
textures: &[texture_binding],
|
||||
acceleration_structures: &[],
|
||||
external_textures: &[],
|
||||
entries: &[
|
||||
hal::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource_index: 0,
|
||||
count: 1,
|
||||
},
|
||||
hal::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource_index: 0,
|
||||
count: 1,
|
||||
},
|
||||
hal::BindGroupEntry {
|
||||
binding: 2,
|
||||
resource_index: 0,
|
||||
count: 1,
|
||||
},
|
||||
],
|
||||
};
|
||||
unsafe { device.create_bind_group(&global_group_desc).unwrap() }
|
||||
};
|
||||
|
||||
let local_group = {
|
||||
// SAFETY: The size must fit within the buffer.
|
||||
let local_buffer_binding = hal::BufferBinding::new_unchecked(
|
||||
&local_buffer,
|
||||
0,
|
||||
wgpu_types::BufferSize::new(size_of::<Locals>() as _),
|
||||
);
|
||||
let local_group_desc = hal::BindGroupDescriptor {
|
||||
label: Some("local"),
|
||||
layout: &local_group_layout,
|
||||
buffers: &[local_buffer_binding],
|
||||
samplers: &[],
|
||||
textures: &[],
|
||||
acceleration_structures: &[],
|
||||
external_textures: &[],
|
||||
entries: &[hal::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource_index: 0,
|
||||
count: 1,
|
||||
}],
|
||||
};
|
||||
unsafe { device.create_bind_group(&local_group_desc).unwrap() }
|
||||
};
|
||||
|
||||
let init_fence_value = 1;
|
||||
let fence = unsafe {
|
||||
let mut fence = device.create_fence().unwrap();
|
||||
let init_cmd = cmd_encoder.end_encoding().unwrap();
|
||||
queue
|
||||
.submit(&[&init_cmd], &[], (&mut fence, init_fence_value))
|
||||
.unwrap();
|
||||
device.wait(&fence, init_fence_value, None).unwrap();
|
||||
device.destroy_buffer(staging_buffer);
|
||||
cmd_encoder.reset_all(iter::once(init_cmd));
|
||||
fence
|
||||
};
|
||||
|
||||
Ok(Example {
|
||||
instance,
|
||||
surface,
|
||||
surface_format: surface_config.format,
|
||||
adapter,
|
||||
device,
|
||||
queue,
|
||||
pipeline_layout,
|
||||
shader,
|
||||
pipeline,
|
||||
global_group,
|
||||
local_group,
|
||||
global_group_layout,
|
||||
local_group_layout,
|
||||
bunnies: Vec::new(),
|
||||
local_buffer,
|
||||
local_alignment,
|
||||
global_buffer,
|
||||
sampler,
|
||||
texture,
|
||||
texture_view,
|
||||
contexts: vec![ExecutionContext {
|
||||
encoder: cmd_encoder,
|
||||
fence,
|
||||
fence_value: init_fence_value + 1,
|
||||
used_views: Vec::new(),
|
||||
used_cmd_bufs: Vec::new(),
|
||||
frames_recorded: 0,
|
||||
}],
|
||||
context_index: 0,
|
||||
extent: [window_size.0, window_size.1],
|
||||
start: Instant::now(),
|
||||
})
|
||||
}
|
||||
|
||||
fn is_empty(&self) -> bool {
|
||||
self.bunnies.is_empty()
|
||||
}
|
||||
|
||||
fn exit(mut self) {
|
||||
unsafe {
|
||||
{
|
||||
let ctx = &mut self.contexts[self.context_index];
|
||||
self.queue
|
||||
.submit(&[], &[], (&mut ctx.fence, ctx.fence_value))
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
for mut ctx in self.contexts {
|
||||
ctx.wait_and_clear(&self.device);
|
||||
drop(ctx.encoder);
|
||||
self.device.destroy_fence(ctx.fence);
|
||||
}
|
||||
|
||||
self.device.destroy_bind_group(self.local_group);
|
||||
self.device.destroy_bind_group(self.global_group);
|
||||
self.device.destroy_buffer(self.local_buffer);
|
||||
self.device.destroy_buffer(self.global_buffer);
|
||||
self.device.destroy_texture_view(self.texture_view);
|
||||
self.device.destroy_texture(self.texture);
|
||||
self.device.destroy_sampler(self.sampler);
|
||||
self.device.destroy_shader_module(self.shader);
|
||||
self.device.destroy_render_pipeline(self.pipeline);
|
||||
self.device
|
||||
.destroy_bind_group_layout(self.local_group_layout);
|
||||
self.device
|
||||
.destroy_bind_group_layout(self.global_group_layout);
|
||||
self.device.destroy_pipeline_layout(self.pipeline_layout);
|
||||
|
||||
self.surface.unconfigure(&self.device);
|
||||
drop(self.queue);
|
||||
drop(self.device);
|
||||
drop(self.surface);
|
||||
drop(self.adapter);
|
||||
}
|
||||
}
|
||||
|
||||
fn update(&mut self, event: winit::event::WindowEvent) {
|
||||
if let winit::event::WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: Key::Named(NamedKey::Space),
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
} = event
|
||||
{
|
||||
let spawn_count = 64 + self.bunnies.len() / 2;
|
||||
let elapsed = self.start.elapsed();
|
||||
let color = elapsed.as_nanos() as u32;
|
||||
println!(
|
||||
"Spawning {} bunnies, total at {}",
|
||||
spawn_count,
|
||||
self.bunnies.len() + spawn_count
|
||||
);
|
||||
for i in 0..spawn_count {
|
||||
let random = ((elapsed.as_nanos() * (i + 1) as u128) & 0xFF) as f32 / 255.0;
|
||||
let speed = random * MAX_VELOCITY - (MAX_VELOCITY * 0.5);
|
||||
self.bunnies.push(Locals {
|
||||
position: [0.0, 0.5 * (self.extent[1] as f32)],
|
||||
velocity: [speed, 0.0],
|
||||
color,
|
||||
_pad: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn render(&mut self) {
|
||||
let delta = 0.01;
|
||||
for bunny in self.bunnies.iter_mut() {
|
||||
bunny.position[0] += bunny.velocity[0] * delta;
|
||||
bunny.position[1] += bunny.velocity[1] * delta;
|
||||
bunny.velocity[1] += GRAVITY * delta;
|
||||
if (bunny.velocity[0] > 0.0
|
||||
&& bunny.position[0] + 0.5 * BUNNY_SIZE > self.extent[0] as f32)
|
||||
|| (bunny.velocity[0] < 0.0 && bunny.position[0] - 0.5 * BUNNY_SIZE < 0.0)
|
||||
{
|
||||
bunny.velocity[0] *= -1.0;
|
||||
}
|
||||
if bunny.velocity[1] < 0.0 && bunny.position[1] < 0.5 * BUNNY_SIZE {
|
||||
bunny.velocity[1] *= -1.0;
|
||||
}
|
||||
}
|
||||
|
||||
if !self.bunnies.is_empty() {
|
||||
let size = self.bunnies.len() * self.local_alignment as usize;
|
||||
unsafe {
|
||||
let mapping = self
|
||||
.device
|
||||
.map_buffer(&self.local_buffer, 0..size as wgpu_types::BufferAddress)
|
||||
.unwrap();
|
||||
ptr::copy_nonoverlapping(
|
||||
self.bunnies.as_ptr() as *const u8,
|
||||
mapping.ptr.as_ptr(),
|
||||
size,
|
||||
);
|
||||
assert!(mapping.is_coherent);
|
||||
self.device.unmap_buffer(&self.local_buffer);
|
||||
}
|
||||
}
|
||||
|
||||
let ctx = &mut self.contexts[self.context_index];
|
||||
|
||||
let surface_tex = unsafe {
|
||||
self.surface
|
||||
.acquire_texture(None, &ctx.fence)
|
||||
.unwrap()
|
||||
.texture
|
||||
};
|
||||
|
||||
let target_barrier0 = hal::TextureBarrier {
|
||||
texture: surface_tex.borrow(),
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::TextureUses::UNINITIALIZED,
|
||||
to: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
},
|
||||
};
|
||||
unsafe {
|
||||
ctx.encoder.begin_encoding(Some("frame")).unwrap();
|
||||
ctx.encoder.transition_textures(iter::once(target_barrier0));
|
||||
}
|
||||
|
||||
let surface_view_desc = hal::TextureViewDescriptor {
|
||||
label: None,
|
||||
format: self.surface_format,
|
||||
dimension: wgpu_types::TextureViewDimension::D2,
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
};
|
||||
let surface_tex_view = unsafe {
|
||||
self.device
|
||||
.create_texture_view(surface_tex.borrow(), &surface_view_desc)
|
||||
.unwrap()
|
||||
};
|
||||
let pass_desc = hal::RenderPassDescriptor {
|
||||
label: None,
|
||||
extent: wgpu_types::Extent3d {
|
||||
width: self.extent[0],
|
||||
height: self.extent[1],
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
sample_count: 1,
|
||||
color_attachments: &[Some(hal::ColorAttachment {
|
||||
target: hal::Attachment {
|
||||
view: &surface_tex_view,
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
},
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: hal::AttachmentOps::STORE | hal::AttachmentOps::LOAD_CLEAR,
|
||||
clear_value: wgpu_types::Color {
|
||||
r: 0.1,
|
||||
g: 0.2,
|
||||
b: 0.3,
|
||||
a: 1.0,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
multiview_mask: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
};
|
||||
unsafe {
|
||||
ctx.encoder.begin_render_pass(&pass_desc).unwrap();
|
||||
ctx.encoder.set_render_pipeline(&self.pipeline);
|
||||
ctx.encoder
|
||||
.set_bind_group(&self.pipeline_layout, 0, &self.global_group, &[]);
|
||||
}
|
||||
|
||||
for i in 0..self.bunnies.len() {
|
||||
let offset = (i as wgpu_types::DynamicOffset)
|
||||
* (self.local_alignment as wgpu_types::DynamicOffset);
|
||||
unsafe {
|
||||
ctx.encoder
|
||||
.set_bind_group(&self.pipeline_layout, 1, &self.local_group, &[offset]);
|
||||
ctx.encoder.draw(0, 4, 0, 1);
|
||||
}
|
||||
}
|
||||
|
||||
ctx.frames_recorded += 1;
|
||||
|
||||
let target_barrier1 = hal::TextureBarrier {
|
||||
texture: surface_tex.borrow(),
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
usage: hal::StateTransition {
|
||||
from: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
to: wgpu_types::TextureUses::PRESENT,
|
||||
},
|
||||
};
|
||||
unsafe {
|
||||
ctx.encoder.end_render_pass();
|
||||
ctx.encoder.transition_textures(iter::once(target_barrier1));
|
||||
}
|
||||
|
||||
unsafe {
|
||||
let cmd_buf = ctx.encoder.end_encoding().unwrap();
|
||||
self.queue
|
||||
.submit(
|
||||
&[&cmd_buf],
|
||||
&[&surface_tex],
|
||||
(&mut ctx.fence, ctx.fence_value),
|
||||
)
|
||||
.unwrap();
|
||||
self.queue.present(&self.surface, surface_tex).unwrap();
|
||||
ctx.used_cmd_bufs.push(cmd_buf);
|
||||
ctx.used_views.push(surface_tex_view);
|
||||
};
|
||||
|
||||
log::debug!("Context switch from {}", self.context_index);
|
||||
let old_fence_value = ctx.fence_value;
|
||||
if self.contexts.len() == 1 {
|
||||
let hal_desc = hal::CommandEncoderDescriptor {
|
||||
label: None,
|
||||
queue: &self.queue,
|
||||
};
|
||||
self.contexts.push(unsafe {
|
||||
ExecutionContext {
|
||||
encoder: self.device.create_command_encoder(&hal_desc).unwrap(),
|
||||
fence: self.device.create_fence().unwrap(),
|
||||
fence_value: 0,
|
||||
used_views: Vec::new(),
|
||||
used_cmd_bufs: Vec::new(),
|
||||
frames_recorded: 0,
|
||||
}
|
||||
});
|
||||
}
|
||||
self.context_index = (self.context_index + 1) % self.contexts.len();
|
||||
let next = &mut self.contexts[self.context_index];
|
||||
unsafe {
|
||||
next.wait_and_clear(&self.device);
|
||||
}
|
||||
next.fence_value = old_fence_value + 1;
|
||||
}
|
||||
}
|
||||
|
||||
cfg_if::cfg_if! {
|
||||
// Apple + Metal
|
||||
if #[cfg(all(target_vendor = "apple", feature = "metal"))] {
|
||||
type Api = hal::api::Metal;
|
||||
}
|
||||
// Wasm + Vulkan
|
||||
else if #[cfg(all(not(target_arch = "wasm32"), feature = "vulkan"))] {
|
||||
type Api = hal::api::Vulkan;
|
||||
}
|
||||
// Windows + DX12
|
||||
else if #[cfg(all(windows, feature = "dx12"))] {
|
||||
type Api = hal::api::Dx12;
|
||||
}
|
||||
// Anything + GLES
|
||||
else if #[cfg(feature = "gles")] {
|
||||
type Api = hal::api::Gles;
|
||||
}
|
||||
// Fallback
|
||||
else {
|
||||
type Api = hal::api::Noop;
|
||||
}
|
||||
}
|
||||
|
||||
struct App {
|
||||
example: Option<Example<Api>>,
|
||||
window: Option<Window>,
|
||||
last_frame_inst: Instant,
|
||||
frame_count: u32,
|
||||
accum_time: f32,
|
||||
}
|
||||
|
||||
impl ApplicationHandler for App {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
if self.window.is_some() {
|
||||
return;
|
||||
}
|
||||
let window = event_loop
|
||||
.create_window(Window::default_attributes().with_title("hal-bunnymark"))
|
||||
.unwrap();
|
||||
let example = Example::<Api>::init(&window).expect("Selected backend is not supported");
|
||||
self.window = Some(window);
|
||||
self.example = Some(example);
|
||||
println!("Press space to spawn bunnies.");
|
||||
self.window.as_ref().unwrap().request_redraw();
|
||||
}
|
||||
|
||||
fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
self.example.take().unwrap().exit();
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
_window_id: winit::window::WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
event_loop.set_control_flow(ControlFlow::Poll);
|
||||
|
||||
match event {
|
||||
WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: Key::Named(NamedKey::Escape),
|
||||
state: ElementState::Pressed,
|
||||
..
|
||||
},
|
||||
..
|
||||
}
|
||||
| WindowEvent::CloseRequested => event_loop.exit(),
|
||||
WindowEvent::RedrawRequested => {
|
||||
let ex = self.example.as_mut().unwrap();
|
||||
{
|
||||
self.accum_time += self.last_frame_inst.elapsed().as_secs_f32();
|
||||
self.last_frame_inst = Instant::now();
|
||||
self.frame_count += 1;
|
||||
if self.frame_count == 100 && !ex.is_empty() {
|
||||
println!(
|
||||
"Avg frame time {}ms",
|
||||
self.accum_time * 1000.0 / self.frame_count as f32
|
||||
);
|
||||
self.accum_time = 0.0;
|
||||
self.frame_count = 0;
|
||||
}
|
||||
}
|
||||
ex.render();
|
||||
self.window.as_ref().unwrap().request_redraw();
|
||||
}
|
||||
_ => {
|
||||
self.example.as_mut().unwrap().update(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
env_logger::init();
|
||||
|
||||
let event_loop = winit::event_loop::EventLoop::new().unwrap();
|
||||
let mut app = App {
|
||||
example: None,
|
||||
window: None,
|
||||
last_frame_inst: Instant::now(),
|
||||
frame_count: 0,
|
||||
accum_time: 0.0,
|
||||
};
|
||||
event_loop.run_app(&mut app).unwrap();
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
struct Globals {
|
||||
mvp: mat4x4<f32>,
|
||||
size: vec2<f32>,
|
||||
_pad0: u32,
|
||||
_pad1: u32,
|
||||
};
|
||||
|
||||
struct Locals {
|
||||
position: vec2<f32>,
|
||||
velocity: vec2<f32>,
|
||||
color: u32,
|
||||
_pad0: u32,
|
||||
_pad1: u32,
|
||||
_pad2: u32,
|
||||
};
|
||||
|
||||
@group(0)
|
||||
@binding(0)
|
||||
var<uniform> globals: Globals;
|
||||
|
||||
@group(1)
|
||||
@binding(0)
|
||||
var<uniform> locals: Locals;
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) tex_coords: vec2<f32>,
|
||||
@location(1) color: vec4<f32>,
|
||||
};
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vi: u32) -> VertexOutput {
|
||||
let tc = vec2<f32>(f32(vi & 1u), 0.5 * f32(vi & 2u));
|
||||
let offset = vec2<f32>(tc.x * globals.size.x, tc.y * globals.size.y);
|
||||
let pos = globals.mvp * vec4<f32>(locals.position + offset, 0.0, 1.0);
|
||||
let color = vec4<f32>((vec4<u32>(locals.color) >> vec4<u32>(0u, 8u, 16u, 24u)) & vec4<u32>(255u)) / 255.0;
|
||||
return VertexOutput(pos, tc, color);
|
||||
}
|
||||
|
||||
@group(0)
|
||||
@binding(1)
|
||||
var tex: texture_2d<f32>;
|
||||
@group(0)
|
||||
@binding(2)
|
||||
var sam: sampler;
|
||||
|
||||
@fragment
|
||||
fn fs_main(vertex: VertexOutput) -> @location(0) vec4<f32> {
|
||||
return vertex.color * textureSampleLevel(tex, sam, vertex.tex_coords, 0.0);
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="canvas" width="640" height="400"></canvas>
|
||||
<script>
|
||||
var Module = {
|
||||
canvas: document.getElementById("canvas"),
|
||||
preRun: [
|
||||
function () {
|
||||
ENV.RUST_LOG = "debug";
|
||||
},
|
||||
],
|
||||
};
|
||||
</script>
|
||||
<script src="raw-gles.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+396
@@ -0,0 +1,396 @@
|
||||
//! This example shows interop with raw GLES contexts -
|
||||
//! the ability to hook up wgpu-hal to an existing context and draw into it.
|
||||
//!
|
||||
//! Emscripten build:
|
||||
//! 1. install emsdk
|
||||
//! 2. build this example with cargo:
|
||||
//! EMCC_CFLAGS="-g -s ERROR_ON_UNDEFINED_SYMBOLS=0 --no-entry -s FULL_ES3=1" cargo build --example raw-gles --target wasm32-unknown-emscripten
|
||||
//! 3. copy raw-gles.em.html into target directory and open it in browser:
|
||||
//! cp wgpu-hal/examples/raw-gles.em.html target/wasm32-unknown-emscripten/debug/examples
|
||||
|
||||
extern crate wgpu_hal as hal;
|
||||
|
||||
#[cfg(not(any(
|
||||
target_arch = "wasm32",
|
||||
target_os = "ios",
|
||||
target_os = "visionos",
|
||||
target_env = "ohos"
|
||||
)))]
|
||||
fn main() {
|
||||
use std::ffi::CString;
|
||||
|
||||
use glutin::{
|
||||
config::GlConfig as _,
|
||||
context::{NotCurrentGlContext as _, PossiblyCurrentGlContext as _, Version},
|
||||
display::{GetGlDisplay as _, GlDisplay as _},
|
||||
surface::GlSurface as _,
|
||||
};
|
||||
use glutin_winit::GlWindow as _;
|
||||
use raw_window_handle::HasWindowHandle as _;
|
||||
use winit::{
|
||||
application::ApplicationHandler,
|
||||
event::{KeyEvent, WindowEvent},
|
||||
event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
|
||||
keyboard::{Key, NamedKey},
|
||||
window::Window,
|
||||
};
|
||||
|
||||
env_logger::init();
|
||||
println!("Initializing external GL context");
|
||||
|
||||
/// Find the config with the maximum number of samples, so our triangle will be
|
||||
/// smooth.
|
||||
fn gl_config_picker(
|
||||
configs: Box<dyn Iterator<Item = glutin::config::Config> + '_>,
|
||||
) -> glutin::config::Config {
|
||||
configs
|
||||
.reduce(|accum, config| {
|
||||
if config.num_samples() > accum.num_samples() {
|
||||
config
|
||||
} else {
|
||||
accum
|
||||
}
|
||||
})
|
||||
.expect("Failed to find a matching config")
|
||||
}
|
||||
|
||||
struct App {
|
||||
gl_config: Option<glutin::config::Config>,
|
||||
not_current_gl_context: Option<glutin::context::NotCurrentContext>,
|
||||
state: Option<(
|
||||
glutin::context::PossiblyCurrentContext,
|
||||
glutin::surface::Surface<glutin::surface::WindowSurface>,
|
||||
Window,
|
||||
)>,
|
||||
exposed: Option<hal::ExposedAdapter<hal::api::Gles>>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
gl_config: None,
|
||||
not_current_gl_context: None,
|
||||
state: None,
|
||||
exposed: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ApplicationHandler for App {
|
||||
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
|
||||
// First call: create display, pick config, create GL context.
|
||||
if self.gl_config.is_none() {
|
||||
// Only Windows requires the window to be present before creating the display.
|
||||
// Other platforms don't really need one.
|
||||
let window_attributes = cfg!(windows).then(|| {
|
||||
Window::default_attributes()
|
||||
.with_title("wgpu raw GLES example (press Escape to exit)")
|
||||
});
|
||||
|
||||
let template = glutin::config::ConfigTemplateBuilder::new();
|
||||
|
||||
let display_builder =
|
||||
glutin_winit::DisplayBuilder::new().with_window_attributes(window_attributes);
|
||||
|
||||
let (window, gl_config) = display_builder
|
||||
.build(event_loop, template, gl_config_picker)
|
||||
.expect("Failed to build window and config from display");
|
||||
|
||||
println!("Picked a config with {} samples", gl_config.num_samples());
|
||||
|
||||
let raw_window_handle = window
|
||||
.as_ref()
|
||||
.and_then(|window| window.window_handle().ok())
|
||||
.map(|handle| handle.as_raw());
|
||||
|
||||
let gl_display = gl_config.display();
|
||||
|
||||
// Glutin tries to create an OpenGL context by default.
|
||||
// Force it to use any version of GLES.
|
||||
let context_attributes = glutin::context::ContextAttributesBuilder::new()
|
||||
// wgpu expects GLES 3.0+.
|
||||
.with_context_api(glutin::context::ContextApi::Gles(Some(Version::new(3, 0))))
|
||||
.build(raw_window_handle);
|
||||
|
||||
let gl_context = unsafe {
|
||||
gl_display
|
||||
.create_context(&gl_config, &context_attributes)
|
||||
.expect("failed to create context")
|
||||
};
|
||||
|
||||
self.not_current_gl_context = Some(gl_context);
|
||||
self.gl_config = Some(gl_config);
|
||||
|
||||
// On Windows, the window was already created by DisplayBuilder.
|
||||
if let Some(window) = window {
|
||||
self.create_surface(event_loop, window);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Create window + surface (non-Windows first call, or Android re-resume).
|
||||
if self.state.is_none() {
|
||||
let gl_config = self.gl_config.as_ref().unwrap();
|
||||
let window = glutin_winit::finalize_window(
|
||||
event_loop,
|
||||
Window::default_attributes()
|
||||
.with_title("wgpu raw GLES example (press Escape to exit)"),
|
||||
gl_config,
|
||||
)
|
||||
.unwrap();
|
||||
self.create_surface(event_loop, window);
|
||||
}
|
||||
}
|
||||
|
||||
fn suspended(&mut self, _event_loop: &ActiveEventLoop) {
|
||||
// This event is only raised on Android, where the backing NativeWindow for a GL
|
||||
// Surface can appear and disappear at any moment.
|
||||
println!("Android window removed");
|
||||
|
||||
// Destroy the GL Surface and un-current the GL Context before ndk-glue releases
|
||||
// the window back to the system.
|
||||
if let Some((gl_context, ..)) = self.state.take() {
|
||||
assert!(self
|
||||
.not_current_gl_context
|
||||
.replace(gl_context.make_not_current().unwrap())
|
||||
.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
&mut self,
|
||||
event_loop: &ActiveEventLoop,
|
||||
_window_id: winit::window::WindowId,
|
||||
event: WindowEvent,
|
||||
) {
|
||||
event_loop.set_control_flow(ControlFlow::Wait);
|
||||
|
||||
match event {
|
||||
WindowEvent::CloseRequested
|
||||
| WindowEvent::KeyboardInput {
|
||||
event:
|
||||
KeyEvent {
|
||||
logical_key: Key::Named(NamedKey::Escape),
|
||||
..
|
||||
},
|
||||
..
|
||||
} => event_loop.exit(),
|
||||
WindowEvent::Resized(size) => {
|
||||
if size.width != 0 && size.height != 0 {
|
||||
// Some platforms like EGL require resizing GL surface to update the size.
|
||||
// Notable platforms here are Wayland and macOS, other don't require it
|
||||
// and the function is no-op, but it's wise to resize it for portability
|
||||
// reasons.
|
||||
if let Some((gl_context, gl_surface, window)) = &self.state {
|
||||
window.resize_surface(gl_surface, gl_context);
|
||||
}
|
||||
}
|
||||
}
|
||||
WindowEvent::RedrawRequested => {
|
||||
if let (Some(exposed), Some((gl_context, gl_surface, window))) =
|
||||
(&self.exposed, &self.state)
|
||||
{
|
||||
let inner_size = window.inner_size();
|
||||
|
||||
fill_screen(exposed, inner_size.width, inner_size.height);
|
||||
|
||||
println!("Showing the window");
|
||||
gl_surface
|
||||
.swap_buffers(gl_context)
|
||||
.expect("Failed to swap buffers");
|
||||
}
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn create_surface(&mut self, _event_loop: &ActiveEventLoop, window: Window) {
|
||||
let gl_config = self.gl_config.as_ref().unwrap();
|
||||
|
||||
let attrs = window
|
||||
.build_surface_attributes(Default::default())
|
||||
.expect("Failed to build surface attributes");
|
||||
let gl_surface = unsafe {
|
||||
gl_config
|
||||
.display()
|
||||
.create_window_surface(gl_config, &attrs)
|
||||
.expect("Cannot create GL WindowSurface")
|
||||
};
|
||||
|
||||
// Make it current.
|
||||
let gl_context = self
|
||||
.not_current_gl_context
|
||||
.take()
|
||||
.unwrap()
|
||||
.make_current(&gl_surface)
|
||||
.expect("GL context cannot be made current with WindowSurface");
|
||||
|
||||
// The context needs to be current for the Renderer to set up shaders and
|
||||
// buffers. It also performs function loading, which needs a current context on
|
||||
// WGL.
|
||||
println!("Hooking up to wgpu-hal");
|
||||
self.exposed.get_or_insert_with(|| {
|
||||
unsafe {
|
||||
<hal::api::Gles as hal::Api>::Adapter::new_external(
|
||||
|name| {
|
||||
// XXX: On WGL this should only be called after the context was
|
||||
// made current
|
||||
gl_config
|
||||
.display()
|
||||
.get_proc_address(&CString::new(name).expect(name))
|
||||
},
|
||||
wgpu_types::GlBackendOptions::default(),
|
||||
)
|
||||
}
|
||||
.expect("GL adapter can't be initialized")
|
||||
});
|
||||
|
||||
window.request_redraw();
|
||||
self.state = Some((gl_context, gl_surface, window));
|
||||
}
|
||||
}
|
||||
|
||||
let event_loop = EventLoop::new().unwrap();
|
||||
let mut app = App::new();
|
||||
event_loop
|
||||
.run_app(&mut app)
|
||||
.expect("Couldn't run event loop");
|
||||
}
|
||||
|
||||
#[cfg(target_os = "emscripten")]
|
||||
fn main() {
|
||||
env_logger::init();
|
||||
|
||||
println!("Initializing external GL context");
|
||||
let egl = khronos_egl::Instance::new(khronos_egl::Static);
|
||||
let display = unsafe { egl.get_display(khronos_egl::DEFAULT_DISPLAY) }.unwrap();
|
||||
egl.initialize(display)
|
||||
.expect("unable to initialize display");
|
||||
|
||||
let attributes = [
|
||||
khronos_egl::RED_SIZE,
|
||||
8,
|
||||
khronos_egl::GREEN_SIZE,
|
||||
8,
|
||||
khronos_egl::BLUE_SIZE,
|
||||
8,
|
||||
khronos_egl::NONE,
|
||||
];
|
||||
|
||||
let config = egl
|
||||
.choose_first_config(display, &attributes)
|
||||
.unwrap()
|
||||
.expect("unable to choose config");
|
||||
let surface = unsafe {
|
||||
let window = std::ptr::null_mut::<std::ffi::c_void>();
|
||||
egl.create_window_surface(display, config, window, None)
|
||||
}
|
||||
.expect("unable to create surface");
|
||||
|
||||
let context_attributes = [khronos_egl::CONTEXT_CLIENT_VERSION, 3, khronos_egl::NONE];
|
||||
|
||||
let gl_context = egl
|
||||
.create_context(display, config, None, &context_attributes)
|
||||
.expect("unable to create context");
|
||||
egl.make_current(display, Some(surface), Some(surface), Some(gl_context))
|
||||
.expect("can't make context current");
|
||||
|
||||
println!("Hooking up to wgpu-hal");
|
||||
let exposed = unsafe {
|
||||
<hal::api::Gles as hal::Api>::Adapter::new_external(|name| {
|
||||
egl.get_proc_address(name)
|
||||
.map_or(std::ptr::null(), |p| p as *const _)
|
||||
})
|
||||
}
|
||||
.expect("GL adapter can't be initialized");
|
||||
|
||||
fill_screen(&exposed, 640, 400);
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
all(target_arch = "wasm32", not(target_os = "emscripten")),
|
||||
target_os = "ios",
|
||||
target_os = "visionos",
|
||||
target_env = "ohos"
|
||||
))]
|
||||
fn main() {
|
||||
eprintln!("This example is not supported on this platform")
|
||||
}
|
||||
|
||||
#[cfg(not(any(
|
||||
all(target_arch = "wasm32", not(target_os = "emscripten")),
|
||||
target_os = "ios",
|
||||
target_os = "visionos"
|
||||
)))]
|
||||
fn fill_screen(exposed: &hal::ExposedAdapter<hal::api::Gles>, width: u32, height: u32) {
|
||||
use hal::{Adapter as _, CommandEncoder as _, Device as _, Queue as _};
|
||||
|
||||
let od = unsafe {
|
||||
exposed.adapter.open(
|
||||
wgpu_types::Features::empty(),
|
||||
&wgpu_types::Limits::downlevel_defaults(),
|
||||
&wgpu_types::MemoryHints::default(),
|
||||
)
|
||||
}
|
||||
.unwrap();
|
||||
|
||||
let format = wgpu_types::TextureFormat::Rgba8UnormSrgb;
|
||||
let texture = <hal::api::Gles as hal::Api>::Texture::default_framebuffer(format);
|
||||
let view = unsafe {
|
||||
od.device
|
||||
.create_texture_view(
|
||||
&texture,
|
||||
&hal::TextureViewDescriptor {
|
||||
label: None,
|
||||
format,
|
||||
dimension: wgpu_types::TextureViewDimension::D2,
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
range: wgpu_types::ImageSubresourceRange::default(),
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
println!("Filling the screen");
|
||||
let mut encoder = unsafe {
|
||||
od.device
|
||||
.create_command_encoder(&hal::CommandEncoderDescriptor {
|
||||
label: None,
|
||||
queue: &od.queue,
|
||||
})
|
||||
.unwrap()
|
||||
};
|
||||
let mut fence = unsafe { od.device.create_fence().unwrap() };
|
||||
let rp_desc = hal::RenderPassDescriptor {
|
||||
label: None,
|
||||
extent: wgpu_types::Extent3d {
|
||||
width,
|
||||
height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
sample_count: 1,
|
||||
color_attachments: &[Some(hal::ColorAttachment {
|
||||
target: hal::Attachment {
|
||||
view: &view,
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET,
|
||||
},
|
||||
depth_slice: None,
|
||||
resolve_target: None,
|
||||
ops: hal::AttachmentOps::STORE | hal::AttachmentOps::LOAD_CLEAR,
|
||||
clear_value: wgpu_types::Color::BLUE,
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
multiview_mask: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
};
|
||||
unsafe {
|
||||
encoder.begin_encoding(None).unwrap();
|
||||
encoder.begin_render_pass(&rp_desc).unwrap();
|
||||
encoder.end_render_pass();
|
||||
let cmd_buf = encoder.end_encoding().unwrap();
|
||||
od.queue.submit(&[&cmd_buf], &[], (&mut fence, 0)).unwrap();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,39 @@
|
||||
enable wgpu_ray_query;
|
||||
|
||||
struct Uniforms {
|
||||
view_inv: mat4x4<f32>,
|
||||
proj_inv: mat4x4<f32>,
|
||||
};
|
||||
@group(0) @binding(0)
|
||||
var<uniform> uniforms: Uniforms;
|
||||
|
||||
@group(0) @binding(1)
|
||||
var output: texture_storage_2d<rgba8unorm, write>;
|
||||
|
||||
@group(0) @binding(2)
|
||||
var acc_struct: acceleration_structure;
|
||||
|
||||
@compute @workgroup_size(8, 8)
|
||||
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
|
||||
let target_size = textureDimensions(output);
|
||||
|
||||
let pixel_center = vec2<f32>(global_id.xy) + vec2<f32>(0.5);
|
||||
let in_uv = pixel_center / vec2<f32>(target_size.xy);
|
||||
let d = in_uv * 2.0 - 1.0;
|
||||
|
||||
let origin = (uniforms.view_inv * vec4<f32>(0.0, 0.0, 0.0, 1.0)).xyz;
|
||||
let temp = uniforms.proj_inv * vec4<f32>(d.x, d.y, 1.0, 1.0);
|
||||
let direction = (uniforms.view_inv * vec4<f32>(normalize(temp.xyz), 0.0)).xyz;
|
||||
|
||||
var rq: ray_query;
|
||||
rayQueryInitialize(&rq, acc_struct, RayDesc(0u, 0xFFu, 0.1, 200.0, origin, direction));
|
||||
rayQueryProceed(&rq);
|
||||
|
||||
var color = vec4<f32>(0.0, 0.0, 0.0, 1.0);
|
||||
let intersection = rayQueryGetCommittedIntersection(&rq);
|
||||
if intersection.kind != RAY_QUERY_INTERSECTION_NONE {
|
||||
color = vec4<f32>(intersection.barycentrics, 1.0 - intersection.barycentrics.x - intersection.barycentrics.y, 1.0);
|
||||
}
|
||||
|
||||
textureStore(output, global_id.xy, color);
|
||||
}
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
use alloc::string::String;
|
||||
use std::{ffi::OsString, os::windows::ffi::OsStringExt};
|
||||
|
||||
use windows::Win32::Graphics::Dxgi;
|
||||
|
||||
// Helper to convert DXGI adapter name to a normal string
|
||||
pub fn map_adapter_name(name: [u16; 128]) -> String {
|
||||
let len = name.iter().take_while(|&&c| c != 0).count();
|
||||
let name = OsString::from_wide(&name[..len]);
|
||||
name.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
pub fn map_texture_format_failable(
|
||||
format: wgt::TextureFormat,
|
||||
) -> Option<Dxgi::Common::DXGI_FORMAT> {
|
||||
use wgt::TextureFormat as Tf;
|
||||
use Dxgi::Common::*;
|
||||
|
||||
Some(match format {
|
||||
Tf::R8Unorm => DXGI_FORMAT_R8_UNORM,
|
||||
Tf::R8Snorm => DXGI_FORMAT_R8_SNORM,
|
||||
Tf::R8Uint => DXGI_FORMAT_R8_UINT,
|
||||
Tf::R8Sint => DXGI_FORMAT_R8_SINT,
|
||||
Tf::R16Uint => DXGI_FORMAT_R16_UINT,
|
||||
Tf::R16Sint => DXGI_FORMAT_R16_SINT,
|
||||
Tf::R16Unorm => DXGI_FORMAT_R16_UNORM,
|
||||
Tf::R16Snorm => DXGI_FORMAT_R16_SNORM,
|
||||
Tf::R16Float => DXGI_FORMAT_R16_FLOAT,
|
||||
Tf::Rg8Unorm => DXGI_FORMAT_R8G8_UNORM,
|
||||
Tf::Rg8Snorm => DXGI_FORMAT_R8G8_SNORM,
|
||||
Tf::Rg8Uint => DXGI_FORMAT_R8G8_UINT,
|
||||
Tf::Rg8Sint => DXGI_FORMAT_R8G8_SINT,
|
||||
Tf::Rg16Unorm => DXGI_FORMAT_R16G16_UNORM,
|
||||
Tf::Rg16Snorm => DXGI_FORMAT_R16G16_SNORM,
|
||||
Tf::R32Uint => DXGI_FORMAT_R32_UINT,
|
||||
Tf::R32Sint => DXGI_FORMAT_R32_SINT,
|
||||
Tf::R32Float => DXGI_FORMAT_R32_FLOAT,
|
||||
Tf::Rg16Uint => DXGI_FORMAT_R16G16_UINT,
|
||||
Tf::Rg16Sint => DXGI_FORMAT_R16G16_SINT,
|
||||
Tf::Rg16Float => DXGI_FORMAT_R16G16_FLOAT,
|
||||
Tf::Rgba8Unorm => DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
Tf::Rgba8UnormSrgb => DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
|
||||
Tf::Bgra8UnormSrgb => DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,
|
||||
Tf::Rgba8Snorm => DXGI_FORMAT_R8G8B8A8_SNORM,
|
||||
Tf::Bgra8Unorm => DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
Tf::Rgba8Uint => DXGI_FORMAT_R8G8B8A8_UINT,
|
||||
Tf::Rgba8Sint => DXGI_FORMAT_R8G8B8A8_SINT,
|
||||
Tf::Rgb9e5Ufloat => DXGI_FORMAT_R9G9B9E5_SHAREDEXP,
|
||||
Tf::Rgb10a2Uint => DXGI_FORMAT_R10G10B10A2_UINT,
|
||||
Tf::Rgb10a2Unorm => DXGI_FORMAT_R10G10B10A2_UNORM,
|
||||
Tf::Rg11b10Ufloat => DXGI_FORMAT_R11G11B10_FLOAT,
|
||||
Tf::R64Uint => DXGI_FORMAT_R32G32_UINT, // R64 emulated by R32G32
|
||||
Tf::Rg32Uint => DXGI_FORMAT_R32G32_UINT,
|
||||
Tf::Rg32Sint => DXGI_FORMAT_R32G32_SINT,
|
||||
Tf::Rg32Float => DXGI_FORMAT_R32G32_FLOAT,
|
||||
Tf::Rgba16Uint => DXGI_FORMAT_R16G16B16A16_UINT,
|
||||
Tf::Rgba16Sint => DXGI_FORMAT_R16G16B16A16_SINT,
|
||||
Tf::Rgba16Unorm => DXGI_FORMAT_R16G16B16A16_UNORM,
|
||||
Tf::Rgba16Snorm => DXGI_FORMAT_R16G16B16A16_SNORM,
|
||||
Tf::Rgba16Float => DXGI_FORMAT_R16G16B16A16_FLOAT,
|
||||
Tf::Rgba32Uint => DXGI_FORMAT_R32G32B32A32_UINT,
|
||||
Tf::Rgba32Sint => DXGI_FORMAT_R32G32B32A32_SINT,
|
||||
Tf::Rgba32Float => DXGI_FORMAT_R32G32B32A32_FLOAT,
|
||||
Tf::Stencil8 => DXGI_FORMAT_D24_UNORM_S8_UINT,
|
||||
Tf::Depth16Unorm => DXGI_FORMAT_D16_UNORM,
|
||||
Tf::Depth24Plus => DXGI_FORMAT_D24_UNORM_S8_UINT,
|
||||
Tf::Depth24PlusStencil8 => DXGI_FORMAT_D24_UNORM_S8_UINT,
|
||||
Tf::Depth32Float => DXGI_FORMAT_D32_FLOAT,
|
||||
Tf::Depth32FloatStencil8 => DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
|
||||
Tf::NV12 => DXGI_FORMAT_NV12,
|
||||
Tf::P010 => DXGI_FORMAT_P010,
|
||||
Tf::Bc1RgbaUnorm => DXGI_FORMAT_BC1_UNORM,
|
||||
Tf::Bc1RgbaUnormSrgb => DXGI_FORMAT_BC1_UNORM_SRGB,
|
||||
Tf::Bc2RgbaUnorm => DXGI_FORMAT_BC2_UNORM,
|
||||
Tf::Bc2RgbaUnormSrgb => DXGI_FORMAT_BC2_UNORM_SRGB,
|
||||
Tf::Bc3RgbaUnorm => DXGI_FORMAT_BC3_UNORM,
|
||||
Tf::Bc3RgbaUnormSrgb => DXGI_FORMAT_BC3_UNORM_SRGB,
|
||||
Tf::Bc4RUnorm => DXGI_FORMAT_BC4_UNORM,
|
||||
Tf::Bc4RSnorm => DXGI_FORMAT_BC4_SNORM,
|
||||
Tf::Bc5RgUnorm => DXGI_FORMAT_BC5_UNORM,
|
||||
Tf::Bc5RgSnorm => DXGI_FORMAT_BC5_SNORM,
|
||||
Tf::Bc6hRgbUfloat => DXGI_FORMAT_BC6H_UF16,
|
||||
Tf::Bc6hRgbFloat => DXGI_FORMAT_BC6H_SF16,
|
||||
Tf::Bc7RgbaUnorm => DXGI_FORMAT_BC7_UNORM,
|
||||
Tf::Bc7RgbaUnormSrgb => DXGI_FORMAT_BC7_UNORM_SRGB,
|
||||
Tf::Etc2Rgb8Unorm
|
||||
| Tf::Etc2Rgb8UnormSrgb
|
||||
| Tf::Etc2Rgb8A1Unorm
|
||||
| Tf::Etc2Rgb8A1UnormSrgb
|
||||
| Tf::Etc2Rgba8Unorm
|
||||
| Tf::Etc2Rgba8UnormSrgb
|
||||
| Tf::EacR11Unorm
|
||||
| Tf::EacR11Snorm
|
||||
| Tf::EacRg11Unorm
|
||||
| Tf::EacRg11Snorm
|
||||
| Tf::Astc {
|
||||
block: _,
|
||||
channel: _,
|
||||
} => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn map_texture_format(format: wgt::TextureFormat) -> Dxgi::Common::DXGI_FORMAT {
|
||||
match map_texture_format_failable(format) {
|
||||
Some(f) => f,
|
||||
None => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
// Note: DXGI doesn't allow sRGB format on the swapchain,
|
||||
// but creating RTV of swapchain buffers with sRGB works.
|
||||
pub fn map_texture_format_nosrgb(format: wgt::TextureFormat) -> Dxgi::Common::DXGI_FORMAT {
|
||||
match format {
|
||||
wgt::TextureFormat::Bgra8UnormSrgb => Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
wgt::TextureFormat::Rgba8UnormSrgb => Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
_ => map_texture_format(format),
|
||||
}
|
||||
}
|
||||
|
||||
// SRV and UAV can't use the depth or typeless formats
|
||||
// see https://microsoft.github.io/DirectX-Specs/d3d/PlanarDepthStencilDDISpec.html#view-creation
|
||||
pub fn map_texture_format_for_srv_uav(
|
||||
format: wgt::TextureFormat,
|
||||
aspect: crate::FormatAspects,
|
||||
) -> Option<Dxgi::Common::DXGI_FORMAT> {
|
||||
Some(match (format, aspect) {
|
||||
(wgt::TextureFormat::Depth16Unorm, crate::FormatAspects::DEPTH) => {
|
||||
Dxgi::Common::DXGI_FORMAT_R16_UNORM
|
||||
}
|
||||
(wgt::TextureFormat::Depth32Float, crate::FormatAspects::DEPTH) => {
|
||||
Dxgi::Common::DXGI_FORMAT_R32_FLOAT
|
||||
}
|
||||
(wgt::TextureFormat::Depth32FloatStencil8, crate::FormatAspects::DEPTH) => {
|
||||
Dxgi::Common::DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS
|
||||
}
|
||||
(
|
||||
wgt::TextureFormat::Depth24Plus | wgt::TextureFormat::Depth24PlusStencil8,
|
||||
crate::FormatAspects::DEPTH,
|
||||
) => Dxgi::Common::DXGI_FORMAT_R24_UNORM_X8_TYPELESS,
|
||||
|
||||
(wgt::TextureFormat::Depth32FloatStencil8, crate::FormatAspects::STENCIL) => {
|
||||
Dxgi::Common::DXGI_FORMAT_X32_TYPELESS_G8X24_UINT
|
||||
}
|
||||
(
|
||||
wgt::TextureFormat::Stencil8 | wgt::TextureFormat::Depth24PlusStencil8,
|
||||
crate::FormatAspects::STENCIL,
|
||||
) => Dxgi::Common::DXGI_FORMAT_X24_TYPELESS_G8_UINT,
|
||||
|
||||
(_, crate::FormatAspects::DEPTH)
|
||||
| (_, crate::FormatAspects::STENCIL)
|
||||
| (_, crate::FormatAspects::DEPTH_STENCIL) => return None,
|
||||
|
||||
_ => map_texture_format(format),
|
||||
})
|
||||
}
|
||||
|
||||
// see https://microsoft.github.io/DirectX-Specs/d3d/PlanarDepthStencilDDISpec.html#planar-layout-for-staging-from-buffer
|
||||
pub fn map_texture_format_for_copy(
|
||||
format: wgt::TextureFormat,
|
||||
aspect: crate::FormatAspects,
|
||||
) -> Option<Dxgi::Common::DXGI_FORMAT> {
|
||||
Some(match (format, aspect) {
|
||||
(wgt::TextureFormat::Depth16Unorm, crate::FormatAspects::DEPTH) => {
|
||||
Dxgi::Common::DXGI_FORMAT_R16_UNORM
|
||||
}
|
||||
(
|
||||
wgt::TextureFormat::Depth32Float | wgt::TextureFormat::Depth32FloatStencil8,
|
||||
crate::FormatAspects::DEPTH,
|
||||
) => Dxgi::Common::DXGI_FORMAT_R32_FLOAT,
|
||||
|
||||
(
|
||||
wgt::TextureFormat::Stencil8
|
||||
| wgt::TextureFormat::Depth24PlusStencil8
|
||||
| wgt::TextureFormat::Depth32FloatStencil8,
|
||||
crate::FormatAspects::STENCIL,
|
||||
) => Dxgi::Common::DXGI_FORMAT_R8_UINT,
|
||||
|
||||
// `CopyTextureRegion` on a plane subresource wants the
|
||||
// single-plane DXGI format, not the planar one.
|
||||
(format, aspects) if format.is_multi_planar_format() && aspects.is_one() => {
|
||||
map_texture_format(format.aspect_specific_format(aspects.map())?)
|
||||
}
|
||||
|
||||
(format, crate::FormatAspects::COLOR) => map_texture_format(format),
|
||||
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn map_texture_format_for_resource(
|
||||
format: wgt::TextureFormat,
|
||||
usage: wgt::TextureUses,
|
||||
has_view_formats: bool,
|
||||
casting_fully_typed_format_supported: bool,
|
||||
) -> Dxgi::Common::DXGI_FORMAT {
|
||||
use wgt::TextureFormat as Tf;
|
||||
use Dxgi::Common::*;
|
||||
|
||||
if casting_fully_typed_format_supported {
|
||||
map_texture_format(format)
|
||||
|
||||
// We might view this resource as srgb or non-srgb
|
||||
} else if has_view_formats {
|
||||
match format {
|
||||
Tf::Rgba8Unorm | Tf::Rgba8UnormSrgb => DXGI_FORMAT_R8G8B8A8_TYPELESS,
|
||||
Tf::Bgra8Unorm | Tf::Bgra8UnormSrgb => DXGI_FORMAT_B8G8R8A8_TYPELESS,
|
||||
Tf::Bc1RgbaUnorm | Tf::Bc1RgbaUnormSrgb => DXGI_FORMAT_BC1_TYPELESS,
|
||||
Tf::Bc2RgbaUnorm | Tf::Bc2RgbaUnormSrgb => DXGI_FORMAT_BC2_TYPELESS,
|
||||
Tf::Bc3RgbaUnorm | Tf::Bc3RgbaUnormSrgb => DXGI_FORMAT_BC3_TYPELESS,
|
||||
Tf::Bc7RgbaUnorm | Tf::Bc7RgbaUnormSrgb => DXGI_FORMAT_BC7_TYPELESS,
|
||||
format => map_texture_format(format),
|
||||
}
|
||||
|
||||
// We might view this resource as SRV/UAV but also as DSV
|
||||
} else if format.is_depth_stencil_format()
|
||||
&& usage.intersects(
|
||||
wgt::TextureUses::RESOURCE
|
||||
| wgt::TextureUses::STORAGE_READ_ONLY
|
||||
| wgt::TextureUses::STORAGE_WRITE_ONLY
|
||||
| wgt::TextureUses::STORAGE_READ_WRITE,
|
||||
)
|
||||
{
|
||||
match format {
|
||||
Tf::Depth16Unorm => DXGI_FORMAT_R16_TYPELESS,
|
||||
Tf::Depth32Float => DXGI_FORMAT_R32_TYPELESS,
|
||||
Tf::Depth32FloatStencil8 => DXGI_FORMAT_R32G8X24_TYPELESS,
|
||||
Tf::Stencil8 | Tf::Depth24Plus | Tf::Depth24PlusStencil8 => DXGI_FORMAT_R24G8_TYPELESS,
|
||||
_ => unreachable!(),
|
||||
}
|
||||
} else {
|
||||
map_texture_format(format)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_index_format(format: wgt::IndexFormat) -> Dxgi::Common::DXGI_FORMAT {
|
||||
match format {
|
||||
wgt::IndexFormat::Uint16 => Dxgi::Common::DXGI_FORMAT_R16_UINT,
|
||||
wgt::IndexFormat::Uint32 => Dxgi::Common::DXGI_FORMAT_R32_UINT,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_vertex_format(format: wgt::VertexFormat) -> Dxgi::Common::DXGI_FORMAT {
|
||||
use wgt::VertexFormat as Vf;
|
||||
use Dxgi::Common::*;
|
||||
|
||||
match format {
|
||||
Vf::Unorm8 => DXGI_FORMAT_R8_UNORM,
|
||||
Vf::Snorm8 => DXGI_FORMAT_R8_SNORM,
|
||||
Vf::Uint8 => DXGI_FORMAT_R8_UINT,
|
||||
Vf::Sint8 => DXGI_FORMAT_R8_SINT,
|
||||
Vf::Unorm8x2 => DXGI_FORMAT_R8G8_UNORM,
|
||||
Vf::Snorm8x2 => DXGI_FORMAT_R8G8_SNORM,
|
||||
Vf::Uint8x2 => DXGI_FORMAT_R8G8_UINT,
|
||||
Vf::Sint8x2 => DXGI_FORMAT_R8G8_SINT,
|
||||
Vf::Unorm8x4 => DXGI_FORMAT_R8G8B8A8_UNORM,
|
||||
Vf::Snorm8x4 => DXGI_FORMAT_R8G8B8A8_SNORM,
|
||||
Vf::Uint8x4 => DXGI_FORMAT_R8G8B8A8_UINT,
|
||||
Vf::Sint8x4 => DXGI_FORMAT_R8G8B8A8_SINT,
|
||||
Vf::Unorm16 => DXGI_FORMAT_R16_UNORM,
|
||||
Vf::Snorm16 => DXGI_FORMAT_R16_SNORM,
|
||||
Vf::Uint16 => DXGI_FORMAT_R16_UINT,
|
||||
Vf::Sint16 => DXGI_FORMAT_R16_SINT,
|
||||
Vf::Float16 => DXGI_FORMAT_R16_FLOAT,
|
||||
Vf::Unorm16x2 => DXGI_FORMAT_R16G16_UNORM,
|
||||
Vf::Snorm16x2 => DXGI_FORMAT_R16G16_SNORM,
|
||||
Vf::Uint16x2 => DXGI_FORMAT_R16G16_UINT,
|
||||
Vf::Sint16x2 => DXGI_FORMAT_R16G16_SINT,
|
||||
Vf::Float16x2 => DXGI_FORMAT_R16G16_FLOAT,
|
||||
Vf::Unorm16x4 => DXGI_FORMAT_R16G16B16A16_UNORM,
|
||||
Vf::Snorm16x4 => DXGI_FORMAT_R16G16B16A16_SNORM,
|
||||
Vf::Uint16x4 => DXGI_FORMAT_R16G16B16A16_UINT,
|
||||
Vf::Sint16x4 => DXGI_FORMAT_R16G16B16A16_SINT,
|
||||
Vf::Float16x4 => DXGI_FORMAT_R16G16B16A16_FLOAT,
|
||||
Vf::Uint32 => DXGI_FORMAT_R32_UINT,
|
||||
Vf::Sint32 => DXGI_FORMAT_R32_SINT,
|
||||
Vf::Float32 => DXGI_FORMAT_R32_FLOAT,
|
||||
Vf::Uint32x2 => DXGI_FORMAT_R32G32_UINT,
|
||||
Vf::Sint32x2 => DXGI_FORMAT_R32G32_SINT,
|
||||
Vf::Float32x2 => DXGI_FORMAT_R32G32_FLOAT,
|
||||
Vf::Uint32x3 => DXGI_FORMAT_R32G32B32_UINT,
|
||||
Vf::Sint32x3 => DXGI_FORMAT_R32G32B32_SINT,
|
||||
Vf::Float32x3 => DXGI_FORMAT_R32G32B32_FLOAT,
|
||||
Vf::Uint32x4 => DXGI_FORMAT_R32G32B32A32_UINT,
|
||||
Vf::Sint32x4 => DXGI_FORMAT_R32G32B32A32_SINT,
|
||||
Vf::Float32x4 => DXGI_FORMAT_R32G32B32A32_FLOAT,
|
||||
Vf::Unorm10_10_10_2 => DXGI_FORMAT_R10G10B10A2_UNORM,
|
||||
Vf::Unorm8x4Bgra => DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||
Vf::Float64 | Vf::Float64x2 | Vf::Float64x3 | Vf::Float64x4 => unimplemented!(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_acomposite_alpha_mode(mode: wgt::CompositeAlphaMode) -> Dxgi::Common::DXGI_ALPHA_MODE {
|
||||
match mode {
|
||||
wgt::CompositeAlphaMode::PreMultiplied => Dxgi::Common::DXGI_ALPHA_MODE_PREMULTIPLIED,
|
||||
wgt::CompositeAlphaMode::PostMultiplied => Dxgi::Common::DXGI_ALPHA_MODE_STRAIGHT,
|
||||
wgt::CompositeAlphaMode::Opaque => Dxgi::Common::DXGI_ALPHA_MODE_IGNORE,
|
||||
wgt::CompositeAlphaMode::Auto | wgt::CompositeAlphaMode::Inherit => {
|
||||
Dxgi::Common::DXGI_ALPHA_MODE_UNSPECIFIED
|
||||
}
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
use alloc::{borrow::Cow, string::String};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use windows::Win32::{Foundation, System::Diagnostics::Debug};
|
||||
|
||||
// This is a mutex as opposed to an atomic as we need to completely
|
||||
// lock everyone out until we have registered or unregistered the
|
||||
// exception handler, otherwise really nasty races could happen.
|
||||
//
|
||||
// By routing all the registration through these functions we can guarantee
|
||||
// there is either 1 or 0 exception handlers registered, not multiple.
|
||||
static EXCEPTION_HANDLER_COUNT: Mutex<usize> = Mutex::new(0);
|
||||
|
||||
pub fn register_exception_handler() {
|
||||
let mut count_guard = EXCEPTION_HANDLER_COUNT.lock();
|
||||
if *count_guard == 0 {
|
||||
unsafe { Debug::AddVectoredExceptionHandler(0, Some(output_debug_string_handler)) };
|
||||
}
|
||||
*count_guard += 1;
|
||||
}
|
||||
|
||||
pub fn unregister_exception_handler() {
|
||||
let mut count_guard = EXCEPTION_HANDLER_COUNT.lock();
|
||||
if *count_guard == 1 {
|
||||
unsafe { Debug::RemoveVectoredExceptionHandler(output_debug_string_handler as *mut _) };
|
||||
}
|
||||
*count_guard -= 1;
|
||||
}
|
||||
|
||||
const MESSAGE_PREFIXES: &[(&str, log::Level)] = &[
|
||||
("CORRUPTION", log::Level::Error),
|
||||
("ERROR", log::Level::Error),
|
||||
("WARNING", log::Level::Warn),
|
||||
// We intentionally suppress "INFO" messages down to debug
|
||||
// so that users are not innundated with info messages from the runtime.
|
||||
("INFO", log::Level::Debug),
|
||||
("MESSAGE", log::Level::Trace),
|
||||
];
|
||||
|
||||
unsafe extern "system" fn output_debug_string_handler(
|
||||
exception_info: *mut Debug::EXCEPTION_POINTERS,
|
||||
) -> i32 {
|
||||
// See https://stackoverflow.com/a/41480827
|
||||
let record = unsafe { &*(*exception_info).ExceptionRecord };
|
||||
if record.NumberParameters != 2 {
|
||||
return Debug::EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
let message = match record.ExceptionCode {
|
||||
Foundation::DBG_PRINTEXCEPTION_C => {
|
||||
String::from_utf8_lossy(bytemuck::cast_slice(&record.ExceptionInformation))
|
||||
}
|
||||
Foundation::DBG_PRINTEXCEPTION_WIDE_C => Cow::Owned(String::from_utf16_lossy(
|
||||
bytemuck::cast_slice(&record.ExceptionInformation),
|
||||
)),
|
||||
_ => return Debug::EXCEPTION_CONTINUE_SEARCH,
|
||||
};
|
||||
|
||||
let message = match message.strip_prefix("D3D12 ") {
|
||||
Some(msg) => msg
|
||||
.trim_end_matches("\n\0")
|
||||
.trim_end_matches("[ STATE_CREATION WARNING #0: UNKNOWN]"),
|
||||
None => return Debug::EXCEPTION_CONTINUE_SEARCH,
|
||||
};
|
||||
|
||||
let (message, level) = match MESSAGE_PREFIXES
|
||||
.iter()
|
||||
.find(|&&(prefix, _)| message.starts_with(prefix))
|
||||
{
|
||||
Some(&(prefix, level)) => (&message[prefix.len() + 2..], level),
|
||||
None => (message, log::Level::Debug),
|
||||
};
|
||||
|
||||
if level == log::Level::Warn && message.contains("#82") {
|
||||
// This is are useless spammy warnings (#820, #821):
|
||||
// "The application did not pass any clear value to resource creation"
|
||||
return Debug::EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
if level == log::Level::Warn && message.contains("DRAW_EMPTY_SCISSOR_RECTANGLE") {
|
||||
// This is normal, WebGPU allows passing empty scissor rectangles.
|
||||
return Debug::EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
|
||||
let _ = std::panic::catch_unwind(|| {
|
||||
log::log!(level, "{message}");
|
||||
});
|
||||
|
||||
#[cfg(feature = "validation_canary")]
|
||||
if cfg!(debug_assertions) && level == log::Level::Error {
|
||||
use alloc::string::ToString as _;
|
||||
|
||||
// Set canary and continue
|
||||
crate::VALIDATION_CANARY.add(message.to_string());
|
||||
}
|
||||
|
||||
Debug::EXCEPTION_CONTINUE_EXECUTION
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
use alloc::{string::String, vec::Vec};
|
||||
use core::ops::Deref;
|
||||
|
||||
use windows::{core::Interface as _, Win32::Graphics::Dxgi};
|
||||
|
||||
use crate::dx12::DxgiLib;
|
||||
|
||||
use super::result::HResult as _;
|
||||
|
||||
// We can rely on the presence of DXGI 1.4 since D3D12 requires WDDM 2.0, Windows 10 (1507), and so does DXGI 1.4.
|
||||
|
||||
pub(crate) fn should_keep_adapter(adapter: &Dxgi::IDXGIAdapter1) -> bool {
|
||||
let desc = unsafe { adapter.GetDesc1() }.unwrap();
|
||||
|
||||
// The Intel Haswell family of iGPUs had support for the D3D12 API but it was later
|
||||
// removed due to a security vulnerability.
|
||||
//
|
||||
// We are explicitly filtering out all the devices in the family because we are now
|
||||
// getting reports of device loss at a later time than at device creation time (`D3D12CreateDevice`).
|
||||
//
|
||||
// See https://www.intel.com/content/www/us/en/support/articles/000057520/graphics.html
|
||||
// This list of device IDs is from https://dgpu-docs.intel.com/devices/hardware-table.html
|
||||
let haswell_device_ids = [
|
||||
0x0422, 0x0426, 0x042A, 0x042B, 0x042E, 0x0C22, 0x0C26, 0x0C2A, 0x0C2B, 0x0C2E, 0x0A22,
|
||||
0x0A2A, 0x0A2B, 0x0D2A, 0x0D2B, 0x0D2E, 0x0A26, 0x0A2E, 0x0D22, 0x0D26, 0x0412, 0x0416,
|
||||
0x0D12, 0x041A, 0x041B, 0x0C12, 0x0C16, 0x0C1A, 0x0C1B, 0x0C1E, 0x0A12, 0x0A1A, 0x0A1B,
|
||||
0x0D16, 0x0D1A, 0x0D1B, 0x0D1E, 0x041E, 0x0A16, 0x0A1E, 0x0402, 0x0406, 0x040A, 0x040B,
|
||||
0x040E, 0x0C02, 0x0C06, 0x0C0A, 0x0C0B, 0x0C0E, 0x0A02, 0x0A06, 0x0A0A, 0x0A0B, 0x0A0E,
|
||||
0x0D02, 0x0D06, 0x0D0A, 0x0D0B, 0x0D0E,
|
||||
];
|
||||
if desc.VendorId == 0x8086 && haswell_device_ids.contains(&desc.DeviceId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If run completely headless, windows will show two different WARP adapters, one
|
||||
// which is lying about being an integrated card. This is so that programs
|
||||
// that ignore software adapters will actually run on headless/gpu-less machines.
|
||||
//
|
||||
// We don't want that and discourage that kind of filtering anyway, so we skip the integrated WARP.
|
||||
if desc.VendorId == 5140
|
||||
&& !Dxgi::DXGI_ADAPTER_FLAG(desc.Flags as i32).contains(Dxgi::DXGI_ADAPTER_FLAG_SOFTWARE)
|
||||
{
|
||||
let adapter_name = super::conv::map_adapter_name(desc.Description);
|
||||
if adapter_name.contains("Microsoft Basic Render Driver") {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum DxgiAdapter {
|
||||
/// Provided by DXGI 1.4
|
||||
Adapter3(Dxgi::IDXGIAdapter3),
|
||||
/// Provided by DXGI 1.6
|
||||
Adapter4(Dxgi::IDXGIAdapter4),
|
||||
}
|
||||
|
||||
impl DxgiAdapter {
|
||||
pub fn query_video_memory_info(
|
||||
&self,
|
||||
group: Dxgi::DXGI_MEMORY_SEGMENT_GROUP,
|
||||
) -> Result<Dxgi::DXGI_QUERY_VIDEO_MEMORY_INFO, crate::DeviceError> {
|
||||
let mut info = Dxgi::DXGI_QUERY_VIDEO_MEMORY_INFO::default();
|
||||
unsafe { self.QueryVideoMemoryInfo(0, group, &mut info) }
|
||||
.into_device_result("QueryVideoMemoryInfo")?;
|
||||
Ok(info)
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for DxgiAdapter {
|
||||
type Target = Dxgi::IDXGIAdapter3;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
match self {
|
||||
DxgiAdapter::Adapter3(a) => a,
|
||||
DxgiAdapter::Adapter4(a) => a,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enumerate_adapters(factory: DxgiFactory) -> Vec<DxgiAdapter> {
|
||||
let mut adapters = Vec::with_capacity(8);
|
||||
|
||||
for cur_index in 0.. {
|
||||
profiling::scope!("IDXGIFactory1::EnumAdapters1");
|
||||
let adapter1: Dxgi::IDXGIAdapter1 = match unsafe { factory.EnumAdapters1(cur_index) } {
|
||||
Ok(a) => a,
|
||||
Err(e) if e.code() == Dxgi::DXGI_ERROR_NOT_FOUND => break,
|
||||
Err(e) => {
|
||||
log::error!("Failed enumerating adapters: {e}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
if !should_keep_adapter(&adapter1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Ok(adapter4) = adapter1.cast::<Dxgi::IDXGIAdapter4>() {
|
||||
adapters.push(DxgiAdapter::Adapter4(adapter4));
|
||||
} else {
|
||||
let adapter3 = adapter1.cast::<Dxgi::IDXGIAdapter3>().unwrap();
|
||||
adapters.push(DxgiAdapter::Adapter3(adapter3));
|
||||
}
|
||||
}
|
||||
|
||||
adapters
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum DxgiFactory {
|
||||
/// Provided by DXGI 1.4
|
||||
Factory4(Dxgi::IDXGIFactory4),
|
||||
/// Provided by DXGI 1.5
|
||||
Factory5(Dxgi::IDXGIFactory5),
|
||||
/// Provided by DXGI 1.6
|
||||
Factory6(Dxgi::IDXGIFactory6),
|
||||
}
|
||||
|
||||
impl Deref for DxgiFactory {
|
||||
type Target = Dxgi::IDXGIFactory4;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
match self {
|
||||
DxgiFactory::Factory4(f) => f,
|
||||
DxgiFactory::Factory5(f) => f,
|
||||
DxgiFactory::Factory6(f) => f,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DxgiFactory {
|
||||
pub fn as_factory5(&self) -> Option<&Dxgi::IDXGIFactory5> {
|
||||
match self {
|
||||
Self::Factory4(_) => None,
|
||||
Self::Factory5(f) => Some(f),
|
||||
Self::Factory6(f) => Some(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_factory(
|
||||
instance_flags: wgt::InstanceFlags,
|
||||
) -> Result<(DxgiLib, DxgiFactory), crate::InstanceError> {
|
||||
let lib_dxgi = DxgiLib::new().map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("failed to load dxgi.dll"), e)
|
||||
})?;
|
||||
|
||||
let mut factory_flags = Dxgi::DXGI_CREATE_FACTORY_FLAGS::default();
|
||||
|
||||
if instance_flags.contains(wgt::InstanceFlags::VALIDATION) {
|
||||
// The `DXGI_CREATE_FACTORY_DEBUG` flag is only allowed to be passed to
|
||||
// `CreateDXGIFactory2` if the debug interface is actually available. So
|
||||
// we check for whether it exists first.
|
||||
if let Ok(Some(_)) = lib_dxgi.debug_interface1() {
|
||||
factory_flags |= Dxgi::DXGI_CREATE_FACTORY_DEBUG;
|
||||
}
|
||||
}
|
||||
|
||||
let factory4 = match lib_dxgi.create_factory4(factory_flags) {
|
||||
Ok(factory) => factory,
|
||||
Err(err) => {
|
||||
return Err(crate::InstanceError::with_source(
|
||||
String::from("IDXGIFactory4 creation failed"),
|
||||
err,
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if let Ok(factory6) = factory4.cast::<Dxgi::IDXGIFactory6>() {
|
||||
return Ok((lib_dxgi, DxgiFactory::Factory6(factory6)));
|
||||
}
|
||||
|
||||
if let Ok(factory5) = factory4.cast::<Dxgi::IDXGIFactory5>() {
|
||||
return Ok((lib_dxgi, DxgiFactory::Factory5(factory5)));
|
||||
}
|
||||
|
||||
Ok((lib_dxgi, DxgiFactory::Factory4(factory4)))
|
||||
}
|
||||
+352
@@ -0,0 +1,352 @@
|
||||
//! Reading a window's [`wgt::DisplayHdrInfo`] through DXGI.
|
||||
//!
|
||||
//! Lives in `auxil/dxgi` so the DX12 and Vulkan-on-Windows backends share it:
|
||||
//! both query through a [`DxgiHdrSource`], so the same monitor reports identical
|
||||
//! numbers under either backend.
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use windows::{
|
||||
core::Interface as _,
|
||||
Win32::{
|
||||
Foundation::HWND,
|
||||
Graphics::{Dxgi, Gdi},
|
||||
},
|
||||
};
|
||||
|
||||
/// The primary colors of a color space, in CIE 1931 xy:
|
||||
/// `[[red_x, red_y], [green_x, green_y], [blue_x, blue_y]]`.
|
||||
type Primaries = [[f32; 2]; 3];
|
||||
|
||||
/// Reference primaries (CIE 1931 xy: red, green, blue) for the three coarse
|
||||
/// gamut buckets, used to classify a display's reported primaries.
|
||||
const REC709: Primaries = [[0.640, 0.330], [0.300, 0.600], [0.150, 0.060]];
|
||||
const DISPLAY_P3: Primaries = [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060]];
|
||||
const REC2020: Primaries = [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]];
|
||||
|
||||
/// Classifies reported primaries into the closest coarse [`wgt::DisplayGamut`]
|
||||
/// bucket (least-squares over the R/G/B chromaticities). Advisory only.
|
||||
///
|
||||
/// Returns `None` if every primary is zeroed (the EDID reported nothing usable),
|
||||
/// so a bogus all-zero descriptor is not misclassified as sRGB.
|
||||
fn classify_gamut(red: [f32; 2], green: [f32; 2], blue: [f32; 2]) -> Option<wgt::DisplayGamut> {
|
||||
let measured = [red, green, blue];
|
||||
if measured.iter().all(|p| p[0] == 0.0 && p[1] == 0.0) {
|
||||
return None;
|
||||
}
|
||||
let dist = |reference: &Primaries| -> f32 {
|
||||
measured
|
||||
.iter()
|
||||
.zip(reference)
|
||||
.map(|(m, r)| {
|
||||
let dx = m[0] - r[0];
|
||||
let dy = m[1] - r[1];
|
||||
dx * dx + dy * dy
|
||||
})
|
||||
.sum()
|
||||
};
|
||||
[
|
||||
(wgt::DisplayGamut::Srgb, dist(&REC709)),
|
||||
(wgt::DisplayGamut::DisplayP3, dist(&DISPLAY_P3)),
|
||||
(wgt::DisplayGamut::Rec2020, dist(&REC2020)),
|
||||
]
|
||||
.into_iter()
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map(|(gamut, _)| gamut)
|
||||
}
|
||||
|
||||
/// Maps an [`IDXGIOutput6::GetDesc1`] result and the SDR white level (from
|
||||
/// [`sdr_white_nits_for_monitor`]) into the backend-agnostic
|
||||
/// [`wgt::DisplayHdrInfo`].
|
||||
///
|
||||
/// Pure: it interprets `desc1` without any system call. Numeric values are
|
||||
/// advisory (EDID-sourced); see [`wgt::DisplayLuminance`].
|
||||
///
|
||||
/// [`IDXGIOutput6::GetDesc1`]: windows::Win32::Graphics::Dxgi::IDXGIOutput6::GetDesc1
|
||||
fn display_hdr_info_from_desc1(
|
||||
desc1: &Dxgi::DXGI_OUTPUT_DESC1,
|
||||
sdr_white_nits: Option<f32>,
|
||||
) -> wgt::DisplayHdrInfo {
|
||||
// The output is in an HDR color space if its `ColorSpace` is one of the two
|
||||
// Windows uses for HDR swap-chains: HDR10 / PQ (`G2084_NONE_P2020`) or
|
||||
// scRGB / linear-extended-sRGB (`G10_NONE_P709`). Checking both ensures scRGB
|
||||
// HDR is not misreported as SDR.
|
||||
let high_dynamic_range = desc1.ColorSpace
|
||||
== Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020
|
||||
|| desc1.ColorSpace == Dxgi::Common::DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709;
|
||||
|
||||
let luminance = wgt::DisplayLuminance {
|
||||
max_nits: Some(desc1.MaxLuminance),
|
||||
max_full_frame_nits: Some(desc1.MaxFullFrameLuminance),
|
||||
min_nits: Some(desc1.MinLuminance),
|
||||
sdr_white_nits,
|
||||
};
|
||||
|
||||
let chromaticity = wgt::DisplayChromaticity {
|
||||
red: Some(desc1.RedPrimary),
|
||||
green: Some(desc1.GreenPrimary),
|
||||
blue: Some(desc1.BluePrimary),
|
||||
white: Some(desc1.WhitePoint),
|
||||
};
|
||||
|
||||
let coarse = wgt::DisplayCoarseRange {
|
||||
high_dynamic_range: Some(high_dynamic_range),
|
||||
gamut: classify_gamut(desc1.RedPrimary, desc1.GreenPrimary, desc1.BluePrimary),
|
||||
};
|
||||
|
||||
// `headroom` is `None`: DXGI exposes absolute luminance (captured in
|
||||
// `luminance`) rather than a relative headroom ratio. `bits_per_color` drops
|
||||
// values that don't fit `u8`.
|
||||
wgt::DisplayHdrInfo {
|
||||
luminance: Some(luminance),
|
||||
headroom: None,
|
||||
chromaticity: Some(chromaticity),
|
||||
coarse: Some(coarse),
|
||||
bits_per_color: u8::try_from(desc1.BitsPerColor).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A window's display HDR info, read through DXGI.
|
||||
///
|
||||
/// Bundles the window's `HWND` with the DXGI factory used to query it. The factory
|
||||
/// is built once and reused, rebuilt only when DXGI reports it stale; the monitor
|
||||
/// lookup and adapter/output walk still run every call, since the window can move
|
||||
/// between displays and the SDR white level changes at runtime.
|
||||
pub struct DxgiHdrSource {
|
||||
hwnd: HWND,
|
||||
factory: Mutex<Option<Dxgi::IDXGIFactory1>>,
|
||||
}
|
||||
|
||||
// SAFETY: `HWND` and `IDXGIFactory1` are `!Send`/`!Sync` in windows-rs. The `HWND`
|
||||
// is only ever read to run a DXGI query (fine from any thread), and the factory is
|
||||
// free-threaded for the enumeration done here with the `Mutex` serializing access.
|
||||
// This mirrors the manual `Send`/`Sync` on `dx12::Surface`.
|
||||
unsafe impl Send for DxgiHdrSource {}
|
||||
unsafe impl Sync for DxgiHdrSource {}
|
||||
|
||||
impl DxgiHdrSource {
|
||||
/// Creates a source for the window identified by `hwnd`. The `HWND` is
|
||||
/// borrowed; using the source after that window is destroyed is undefined
|
||||
/// behavior.
|
||||
pub fn new(hwnd: HWND) -> Self {
|
||||
Self {
|
||||
hwnd,
|
||||
factory: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the window's [`wgt::DisplayHdrInfo`], or `None` if its monitor can't
|
||||
/// be identified or queried (a headless or composition window, a
|
||||
/// pre-Win10-1703 system without `IDXGIOutput6`, or a COM failure). Never
|
||||
/// panics.
|
||||
pub fn display_hdr_info(&self) -> Option<wgt::DisplayHdrInfo> {
|
||||
let desc1 = self.output_desc1()?;
|
||||
let sdr_white_nits = sdr_white_nits_for_monitor(desc1.Monitor);
|
||||
Some(display_hdr_info_from_desc1(&desc1, sdr_white_nits))
|
||||
}
|
||||
|
||||
/// The [`DXGI_OUTPUT_DESC1`] for the window's monitor, reusing the cached
|
||||
/// factory unless DXGI reports it stale.
|
||||
///
|
||||
/// [`DXGI_OUTPUT_DESC1`]: Dxgi::DXGI_OUTPUT_DESC1
|
||||
fn output_desc1(&self) -> Option<Dxgi::DXGI_OUTPUT_DESC1> {
|
||||
let mut factory = self.factory.lock();
|
||||
|
||||
// A factory only enumerates the adapter/output topology it saw at
|
||||
// creation, so rebuild it once it reports `IsCurrent() == false` (a
|
||||
// monitor or GPU was plugged or unplugged).
|
||||
// SAFETY: a cached factory is live; `IsCurrent` takes no caller pointers.
|
||||
let need_new = factory
|
||||
.as_ref()
|
||||
.is_none_or(|f| !unsafe { f.IsCurrent() }.as_bool());
|
||||
if need_new {
|
||||
// SAFETY: `CreateDXGIFactory1` takes no caller pointers; the `windows`
|
||||
// binding fills the interface out-pointer itself.
|
||||
match unsafe { Dxgi::CreateDXGIFactory1() } {
|
||||
Ok(new) => *factory = Some(new),
|
||||
Err(e) => {
|
||||
log::warn!("CreateDXGIFactory1 failed: {e}");
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
output_desc1_from_factory(factory.as_ref()?, self.hwnd)
|
||||
}
|
||||
}
|
||||
|
||||
/// The [`DXGI_OUTPUT_DESC1`] for the monitor backing `wnd_handle`, found by
|
||||
/// walking every adapter's outputs on `factory` — not just the rendering
|
||||
/// adapter's, so the monitor is found on hybrid-GPU systems where the window sits
|
||||
/// on a display wired to a different adapter. `None` if none match.
|
||||
///
|
||||
/// [`DXGI_OUTPUT_DESC1`]: Dxgi::DXGI_OUTPUT_DESC1
|
||||
fn output_desc1_from_factory(
|
||||
factory: &Dxgi::IDXGIFactory1,
|
||||
wnd_handle: HWND,
|
||||
) -> Option<Dxgi::DXGI_OUTPUT_DESC1> {
|
||||
// SAFETY: `MonitorFromWindow` is sound for any `HWND`; an invalid one yields
|
||||
// a null `HMONITOR`, checked below.
|
||||
let hmonitor = unsafe { Gdi::MonitorFromWindow(wnd_handle, Gdi::MONITOR_DEFAULTTONEAREST) };
|
||||
if hmonitor.is_invalid() {
|
||||
log::warn!("MonitorFromWindow failed; cannot identify the window's output");
|
||||
return None;
|
||||
}
|
||||
for adapter_index in 0.. {
|
||||
// SAFETY: `factory` is live; `EnumAdapters1` takes only an index.
|
||||
let adapter = match unsafe { factory.EnumAdapters1(adapter_index) } {
|
||||
Ok(adapter) => adapter,
|
||||
// End of the adapter list: the monitor matched none of them.
|
||||
Err(e) if e.code() == Dxgi::DXGI_ERROR_NOT_FOUND => break,
|
||||
Err(e) => {
|
||||
log::warn!("IDXGIFactory1::EnumAdapters1 failed: {e}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
for output_index in 0.. {
|
||||
// SAFETY: `adapter` is live (from above); `EnumOutputs` takes only
|
||||
// an index.
|
||||
let output = match unsafe { adapter.EnumOutputs(output_index) } {
|
||||
Ok(output) => output,
|
||||
// End of this adapter's outputs: move on to the next adapter.
|
||||
Err(e) if e.code() == Dxgi::DXGI_ERROR_NOT_FOUND => break,
|
||||
Err(e) => {
|
||||
log::warn!("IDXGIAdapter1::EnumOutputs failed: {e}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
// SAFETY: `output` is live (from above); `GetDesc` returns a
|
||||
// binding-owned `DXGI_OUTPUT_DESC` by value.
|
||||
let desc = match unsafe { output.GetDesc() } {
|
||||
Ok(desc) => desc,
|
||||
Err(e) => {
|
||||
log::warn!("IDXGIOutput::GetDesc failed: {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if desc.Monitor != hmonitor {
|
||||
continue;
|
||||
}
|
||||
// The window's monitor matched, so a failure past this point is a
|
||||
// real anomaly. `IDXGIOutput6` (DXGI 1.6 / Win10 1703+) is required
|
||||
// for `GetDesc1`.
|
||||
let output6 = match output.cast::<Dxgi::IDXGIOutput6>() {
|
||||
Ok(output6) => output6,
|
||||
Err(e) => {
|
||||
log::warn!("Casting to IDXGIOutput6 failed: {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// SAFETY: `output6` is live (from the cast above); `GetDesc1`
|
||||
// returns a binding-owned `DXGI_OUTPUT_DESC1` by value.
|
||||
return match unsafe { output6.GetDesc1() } {
|
||||
Ok(desc1) => Some(desc1),
|
||||
Err(e) => {
|
||||
log::warn!("IDXGIOutput6::GetDesc1 failed: {e}");
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
log::warn!("No DXGI output matches the window's monitor");
|
||||
None
|
||||
}
|
||||
|
||||
/// Best-effort SDR white level in nits for `hmonitor`, via the Windows
|
||||
/// DisplayConfig API. Tracks the brightness slider, so it changes at runtime.
|
||||
///
|
||||
/// This is the only [`wgt::DisplayLuminance`] field `GetDesc1` doesn't carry; it
|
||||
/// bridges absolute nits and relative headroom. It lives in
|
||||
/// `DISPLAYCONFIG_SDR_WHITE_LEVEL`, outside DXGI, so it needs its own query.
|
||||
///
|
||||
/// Returns `None` on any failure (no match, query error, or a `0` reading). Never
|
||||
/// panics. Pass [`Dxgi::DXGI_OUTPUT_DESC1::Monitor`] so the value matches the rest
|
||||
/// of the `DisplayHdrInfo`.
|
||||
fn sdr_white_nits_for_monitor(hmonitor: Gdi::HMONITOR) -> Option<f32> {
|
||||
use windows::Win32::{
|
||||
Devices::Display::{
|
||||
DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QueryDisplayConfig,
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL,
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_MODE_INFO,
|
||||
DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SDR_WHITE_LEVEL,
|
||||
DISPLAYCONFIG_SOURCE_DEVICE_NAME, QDC_ONLY_ACTIVE_PATHS,
|
||||
},
|
||||
Foundation::ERROR_SUCCESS,
|
||||
Graphics::Gdi::{GetMonitorInfoW, MONITORINFO, MONITORINFOEXW},
|
||||
};
|
||||
|
||||
// 1. HMONITOR -> GDI device name (e.g. `\\.\DISPLAY1`).
|
||||
let mut monitor_info = MONITORINFOEXW::default();
|
||||
monitor_info.monitorInfo.cbSize = size_of::<MONITORINFOEXW>() as u32;
|
||||
// `GetMonitorInfoW` takes a `*mut MONITORINFO`; the `EXW` variant is
|
||||
// layout-compatible (it starts with `MONITORINFO`) and reports `cbSize`.
|
||||
let lpmi = core::ptr::from_mut(&mut monitor_info).cast::<MONITORINFO>();
|
||||
// SAFETY: `lpmi` points at a live `MONITORINFOEXW` with `cbSize` set, which
|
||||
// bounds the write; an invalid `hmonitor` just fails (handled below).
|
||||
let got_info = unsafe { GetMonitorInfoW(hmonitor, lpmi) };
|
||||
if !got_info.as_bool() {
|
||||
return None;
|
||||
}
|
||||
let gdi_device_name = monitor_info.szDevice;
|
||||
|
||||
// 2. Enumerate the active DisplayConfig paths.
|
||||
let mut path_count = 0u32;
|
||||
let mut mode_count = 0u32;
|
||||
// SAFETY: both out-params are live `u32`s; the call only writes the required
|
||||
// buffer sizes into them.
|
||||
if unsafe {
|
||||
GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut path_count, &mut mode_count)
|
||||
} != ERROR_SUCCESS
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut paths = alloc::vec![DISPLAYCONFIG_PATH_INFO::default(); path_count as usize];
|
||||
let mut modes = alloc::vec![DISPLAYCONFIG_MODE_INFO::default(); mode_count as usize];
|
||||
// SAFETY: `paths`/`modes` are sized to the counts reported above and passed
|
||||
// with those counts, bounding the writes.
|
||||
if unsafe {
|
||||
QueryDisplayConfig(
|
||||
QDC_ONLY_ACTIVE_PATHS,
|
||||
&mut path_count,
|
||||
paths.as_mut_ptr(),
|
||||
&mut mode_count,
|
||||
modes.as_mut_ptr(),
|
||||
None,
|
||||
)
|
||||
} != ERROR_SUCCESS
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
// 3. Match the path whose source is this monitor, then read its target's
|
||||
// SDR white level. `DisplayConfigGetDeviceInfo` returns a WIN32 code as
|
||||
// `i32` (`0` == `ERROR_SUCCESS`).
|
||||
for path in paths.iter().take(path_count as usize) {
|
||||
let mut source = DISPLAYCONFIG_SOURCE_DEVICE_NAME::default();
|
||||
source.header.r#type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
|
||||
source.header.size = size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as u32;
|
||||
source.header.adapterId = path.sourceInfo.adapterId;
|
||||
source.header.id = path.sourceInfo.id;
|
||||
// SAFETY: `source` is live with `header.type`/`header.size` set, which
|
||||
// bounds the call's access to that struct.
|
||||
if unsafe { DisplayConfigGetDeviceInfo(&mut source.header) } != ERROR_SUCCESS.0 as i32 {
|
||||
continue;
|
||||
}
|
||||
if source.viewGdiDeviceName != gdi_device_name {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut white = DISPLAYCONFIG_SDR_WHITE_LEVEL::default();
|
||||
white.header.r#type = DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL;
|
||||
white.header.size = size_of::<DISPLAYCONFIG_SDR_WHITE_LEVEL>() as u32;
|
||||
white.header.adapterId = path.targetInfo.adapterId;
|
||||
white.header.id = path.targetInfo.id;
|
||||
// SAFETY: `white` is live with `header.type`/`header.size` set, which
|
||||
// bounds the call's access to that struct.
|
||||
if unsafe { DisplayConfigGetDeviceInfo(&mut white.header) } != ERROR_SUCCESS.0 as i32 {
|
||||
return None;
|
||||
}
|
||||
// `SDRWhiteLevel` encodes nits as `(nits / 80) * 1000`; `0` means the OS
|
||||
// reported nothing usable.
|
||||
return (white.SDRWhiteLevel > 0).then(|| white.SDRWhiteLevel as f32 * 80.0 / 1000.0);
|
||||
}
|
||||
None
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
// Every module here is gated behind `dx12` except `hdr` (the
|
||||
// `DXGI_OUTPUT_DESC1` -> `DisplayHdrInfo` mapping), which the
|
||||
// Vulkan-on-Windows backend also uses.
|
||||
#[cfg(dx12)]
|
||||
pub mod conv;
|
||||
#[cfg(dx12)]
|
||||
pub mod exception;
|
||||
#[cfg(dx12)]
|
||||
pub mod factory;
|
||||
pub mod hdr;
|
||||
#[cfg(dx12)]
|
||||
pub mod name;
|
||||
#[cfg(dx12)]
|
||||
pub mod result;
|
||||
#[cfg(dx12)]
|
||||
pub mod time;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
use windows::Win32::Graphics::Direct3D12::ID3D12Object;
|
||||
|
||||
use crate::auxil::dxgi::result::HResult;
|
||||
|
||||
/// Helper trait for setting the name of a D3D12 object.
|
||||
///
|
||||
/// This is implemented on all types that can be converted to an [`ID3D12Object`].
|
||||
pub trait ObjectExt {
|
||||
fn set_name(&self, name: &str) -> Result<(), crate::DeviceError>;
|
||||
}
|
||||
|
||||
impl<T> ObjectExt for T
|
||||
where
|
||||
// Windows impls `From` for all parent interfaces, so we can use that to convert to ID3D12Object.
|
||||
//
|
||||
// This includes implementations for references.
|
||||
for<'a> &'a ID3D12Object: From<&'a T>,
|
||||
{
|
||||
fn set_name(&self, name: &str) -> Result<(), crate::DeviceError> {
|
||||
let name = windows::core::HSTRING::from(name);
|
||||
let object: &ID3D12Object = self.into();
|
||||
unsafe { object.SetName(&name).into_device_result("SetName") }
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
use windows::Win32::{Foundation, Graphics::Dxgi};
|
||||
|
||||
pub(crate) trait HResult<O> {
|
||||
fn into_device_result(self, description: &str) -> Result<O, crate::DeviceError>;
|
||||
}
|
||||
impl<T> HResult<T> for windows::core::Result<T> {
|
||||
fn into_device_result(self, description: &str) -> Result<T, crate::DeviceError> {
|
||||
#![allow(unreachable_code)]
|
||||
|
||||
self.map_err(|err| {
|
||||
log::error!("{description} failed: {err}");
|
||||
|
||||
match err.code() {
|
||||
Foundation::E_OUTOFMEMORY => crate::DeviceError::OutOfMemory,
|
||||
Dxgi::DXGI_ERROR_DEVICE_RESET | Dxgi::DXGI_ERROR_DEVICE_REMOVED => {
|
||||
#[cfg(feature = "device_lost_panic")]
|
||||
panic!("{description} failed: Device lost ({err})");
|
||||
crate::DeviceError::Lost
|
||||
}
|
||||
_ => {
|
||||
#[cfg(feature = "internal_error_panic")]
|
||||
panic!("{description} failed: {err}");
|
||||
crate::DeviceError::Unexpected
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
#![allow(dead_code, reason = "IPresentationManager is unused currently")]
|
||||
|
||||
use windows::Win32::System::Performance::{QueryPerformanceCounter, QueryPerformanceFrequency};
|
||||
|
||||
pub enum PresentationTimer {
|
||||
/// DXGI uses [`QueryPerformanceCounter()`]
|
||||
Dxgi {
|
||||
/// How many ticks of QPC per second
|
||||
frequency: u64,
|
||||
},
|
||||
/// [`IPresentationManager`] uses [`QueryInterruptTimePrecise()`]
|
||||
///
|
||||
/// [`IPresentationManager`]: https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/Graphics/CompositionSwapchain/struct.IPresentationManager.html
|
||||
/// [`QueryInterruptTimePrecise()`]: https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/System/WindowsProgramming/fn.QueryInterruptTimePrecise.html
|
||||
#[allow(non_snake_case)]
|
||||
IPresentationManager {
|
||||
fnQueryInterruptTimePrecise: unsafe extern "system" fn(*mut u64),
|
||||
},
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for PresentationTimer {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match *self {
|
||||
Self::Dxgi { frequency } => f
|
||||
.debug_struct("DXGI")
|
||||
.field("frequency", &frequency)
|
||||
.finish(),
|
||||
Self::IPresentationManager {
|
||||
fnQueryInterruptTimePrecise,
|
||||
} => f
|
||||
.debug_struct("IPresentationManager")
|
||||
.field(
|
||||
"QueryInterruptTimePrecise",
|
||||
&(fnQueryInterruptTimePrecise as usize),
|
||||
)
|
||||
.finish(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PresentationTimer {
|
||||
/// Create a presentation timer using QueryPerformanceFrequency (what DXGI uses for presentation times)
|
||||
pub fn new_dxgi() -> Self {
|
||||
let mut frequency = 0;
|
||||
unsafe { QueryPerformanceFrequency(&mut frequency) }.unwrap();
|
||||
|
||||
Self::Dxgi {
|
||||
frequency: frequency
|
||||
.try_into()
|
||||
.expect("Frequency should not be negative"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a presentation timer using QueryInterruptTimePrecise (what IPresentationManager uses for presentation times)
|
||||
///
|
||||
/// Panics if QueryInterruptTimePrecise isn't found (below Win10)
|
||||
pub fn new_ipresentation_manager() -> Self {
|
||||
// We need to load this explicitly, as QueryInterruptTimePrecise is only available on Windows 10+
|
||||
//
|
||||
// Docs say it's in kernel32.dll, but it's actually in kernelbase.dll.
|
||||
// api-ms-win-core-realtime-l1-1-1.dll
|
||||
let kernelbase =
|
||||
libloading::os::windows::Library::open_already_loaded("kernelbase.dll").unwrap();
|
||||
// No concerns about lifetimes here as kernelbase is always there.
|
||||
let ptr = unsafe {
|
||||
kernelbase
|
||||
.get(c"QueryInterruptTimePrecise".to_bytes())
|
||||
.unwrap()
|
||||
};
|
||||
Self::IPresentationManager {
|
||||
fnQueryInterruptTimePrecise: *ptr,
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the current time in nanoseconds.
|
||||
pub fn get_timestamp_ns(&self) -> u128 {
|
||||
// Always do u128 math _after_ hitting the timing function.
|
||||
match *self {
|
||||
PresentationTimer::Dxgi { frequency } => {
|
||||
let mut counter = 0;
|
||||
unsafe { QueryPerformanceCounter(&mut counter) }.unwrap();
|
||||
|
||||
// counter * (1_000_000_000 / freq) but re-ordered to make more precise
|
||||
(counter as u128 * 1_000_000_000) / frequency as u128
|
||||
}
|
||||
PresentationTimer::IPresentationManager {
|
||||
fnQueryInterruptTimePrecise,
|
||||
} => {
|
||||
let mut counter = 0;
|
||||
unsafe { fnQueryInterruptTimePrecise(&mut counter) };
|
||||
|
||||
// QueryInterruptTimePrecise uses units of 100ns for its tick.
|
||||
counter as u128 * 100
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+241
@@ -0,0 +1,241 @@
|
||||
// Mostly DX12-only, but also compiled for Vulkan-on-Windows, which reuses
|
||||
// `dxgi::hdr` to query display HDR info. The DX12-only submodules stay gated
|
||||
// behind `dx12` in `dxgi/mod.rs`.
|
||||
#[cfg(any(dx12, all(vulkan, windows)))]
|
||||
pub(super) mod dxgi;
|
||||
|
||||
#[cfg(all(native, feature = "renderdoc"))]
|
||||
pub(super) mod renderdoc;
|
||||
|
||||
pub mod db {
|
||||
pub mod amd {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x1002;
|
||||
}
|
||||
pub mod apple {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x106B;
|
||||
}
|
||||
pub mod arm {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x13B5;
|
||||
}
|
||||
pub mod broadcom {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x14E4;
|
||||
}
|
||||
pub mod imgtec {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x1010;
|
||||
}
|
||||
pub mod intel {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x8086;
|
||||
pub const DEVICE_KABY_LAKE_MASK: u32 = 0x5900;
|
||||
pub const DEVICE_SKY_LAKE_MASK: u32 = 0x1900;
|
||||
}
|
||||
pub mod mesa {
|
||||
// Mesa does not actually have a PCI vendor id.
|
||||
//
|
||||
// To match Vulkan, we use the VkVendorId for Mesa in the gles backend so that lavapipe (Vulkan) and
|
||||
// llvmpipe (OpenGL) have the same vendor id.
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x10005;
|
||||
}
|
||||
pub mod nvidia {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x10DE;
|
||||
}
|
||||
pub mod qualcomm {
|
||||
/// cbindgen:ignore
|
||||
pub const VENDOR: u32 = 0x5143;
|
||||
}
|
||||
}
|
||||
|
||||
/// Maximum binding size for the shaders that only support `i32` indexing.
|
||||
/// Interestingly, the index itself can't reach that high, because the minimum
|
||||
/// element size is 4 bytes, but the compiler toolchain still computes the
|
||||
/// offset at some intermediate point, internally, as i32.
|
||||
pub const MAX_I32_BINDING_SIZE: u32 = (1 << 31) - 1;
|
||||
|
||||
pub use wgpu_naga_bridge::map_naga_stage;
|
||||
|
||||
impl crate::CopyExtent {
|
||||
pub fn map_extent_to_copy_size(extent: &wgt::Extent3d, dim: wgt::TextureDimension) -> Self {
|
||||
Self {
|
||||
width: extent.width,
|
||||
height: extent.height,
|
||||
depth: match dim {
|
||||
wgt::TextureDimension::D1 | wgt::TextureDimension::D2 => 1,
|
||||
wgt::TextureDimension::D3 => extent.depth_or_array_layers,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn min(&self, other: &Self) -> Self {
|
||||
Self {
|
||||
width: self.width.min(other.width),
|
||||
height: self.height.min(other.height),
|
||||
depth: self.depth.min(other.depth),
|
||||
}
|
||||
}
|
||||
|
||||
// Get the copy size at a specific mipmap level. This doesn't make most sense,
|
||||
// since the copy extents are provided *for* a mipmap level to start with.
|
||||
// But backends use `CopyExtent` more sparingly, and this piece is shared.
|
||||
pub fn at_mip_level(&self, level: u32) -> Self {
|
||||
Self {
|
||||
width: (self.width >> level).max(1),
|
||||
height: (self.height >> level).max(1),
|
||||
depth: (self.depth >> level).max(1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::TextureCopyBase {
|
||||
pub fn max_copy_size(&self, full_size: &crate::CopyExtent) -> crate::CopyExtent {
|
||||
let mip = full_size.at_mip_level(self.mip_level);
|
||||
crate::CopyExtent {
|
||||
width: mip.width - self.origin.x,
|
||||
height: mip.height - self.origin.y,
|
||||
depth: mip.depth - self.origin.z,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::BufferTextureCopy {
|
||||
pub fn clamp_size_to_virtual(&mut self, full_size: &crate::CopyExtent) {
|
||||
let max_size = self.texture_base.max_copy_size(full_size);
|
||||
self.size = self.size.min(&max_size);
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::TextureCopy {
|
||||
pub fn clamp_size_to_virtual(
|
||||
&mut self,
|
||||
full_src_size: &crate::CopyExtent,
|
||||
full_dst_size: &crate::CopyExtent,
|
||||
) {
|
||||
let max_src_size = self.src_base.max_copy_size(full_src_size);
|
||||
let max_dst_size = self.dst_base.max_copy_size(full_dst_size);
|
||||
self.size = self.size.min(&max_src_size).min(&max_dst_size);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adjust `limits` to honor HAL-imposed maximums and comply with WebGPU's
|
||||
/// adapter capability guarantees.
|
||||
#[cfg_attr(not(any_backend), allow(dead_code))]
|
||||
pub(crate) fn adjust_raw_limits(mut limits: wgt::Limits) -> wgt::Limits {
|
||||
// Apply hal limits.
|
||||
limits.max_bind_groups = limits.max_bind_groups.min(crate::MAX_BIND_GROUPS as u32);
|
||||
limits.max_vertex_buffers = limits
|
||||
.max_vertex_buffers
|
||||
.min(crate::MAX_VERTEX_BUFFERS as u32);
|
||||
// Once we allow the 2 limits above to be higher than 24 we should use
|
||||
// `cap_limits_to_be_under_the_sum_limit` to cap them under
|
||||
// `max_bind_groups_plus_vertex_buffers`.
|
||||
const { assert!(crate::MAX_BIND_GROUPS + crate::MAX_VERTEX_BUFFERS == 24) };
|
||||
limits.max_bind_groups_plus_vertex_buffers = limits.max_bind_groups_plus_vertex_buffers.min(24);
|
||||
limits.max_color_attachments = limits
|
||||
.max_color_attachments
|
||||
.min(crate::MAX_COLOR_ATTACHMENTS as u32);
|
||||
|
||||
// Adjust limits according to WebGPU adapter capability guarantees.
|
||||
// See <https://gpuweb.github.io/gpuweb/#adapter-capability-guarantees>.
|
||||
|
||||
// WebGPU requires maxBindingsPerBindGroup to be at least the sum of all
|
||||
// per-stage limits multiplied with the maximum shader stages per pipeline.
|
||||
//
|
||||
// Since backends already report their maximum maxBindingsPerBindGroup,
|
||||
// we need to lower all per-stage limits to satisfy this guarantee.
|
||||
const MAX_SHADER_STAGES_PER_PIPELINE: u32 = 2;
|
||||
let max_per_stage_resources =
|
||||
limits.max_bindings_per_bind_group / MAX_SHADER_STAGES_PER_PIPELINE;
|
||||
|
||||
cap_limits_to_be_under_the_sum_limit(
|
||||
[
|
||||
&mut limits.max_sampled_textures_per_shader_stage,
|
||||
&mut limits.max_uniform_buffers_per_shader_stage,
|
||||
&mut limits.max_storage_textures_per_shader_stage,
|
||||
&mut limits.max_storage_buffers_per_shader_stage,
|
||||
&mut limits.max_samplers_per_shader_stage,
|
||||
&mut limits.max_acceleration_structures_per_shader_stage,
|
||||
],
|
||||
max_per_stage_resources,
|
||||
);
|
||||
|
||||
// Not required by the spec but dynamic buffers count
|
||||
// towards non-dynamic buffer limits as well.
|
||||
limits.max_dynamic_uniform_buffers_per_pipeline_layout = limits
|
||||
.max_dynamic_uniform_buffers_per_pipeline_layout
|
||||
.min(limits.max_uniform_buffers_per_shader_stage);
|
||||
limits.max_dynamic_storage_buffers_per_pipeline_layout = limits
|
||||
.max_dynamic_storage_buffers_per_pipeline_layout
|
||||
.min(limits.max_storage_buffers_per_shader_stage);
|
||||
|
||||
limits.min_uniform_buffer_offset_alignment = limits.min_uniform_buffer_offset_alignment.max(32);
|
||||
limits.min_storage_buffer_offset_alignment = limits.min_storage_buffer_offset_alignment.max(32);
|
||||
|
||||
limits.max_uniform_buffer_binding_size = limits
|
||||
.max_uniform_buffer_binding_size
|
||||
.min(limits.max_buffer_size);
|
||||
limits.max_storage_buffer_binding_size = limits
|
||||
.max_storage_buffer_binding_size
|
||||
.min(limits.max_buffer_size);
|
||||
|
||||
limits.max_storage_buffer_binding_size &= !(u64::from(wgt::STORAGE_BINDING_SIZE_ALIGNMENT) - 1);
|
||||
limits.max_vertex_buffer_array_stride &= !(wgt::VERTEX_ALIGNMENT as u32 - 1);
|
||||
|
||||
let x = limits.max_compute_workgroup_size_x;
|
||||
let y = limits.max_compute_workgroup_size_y;
|
||||
let z = limits.max_compute_workgroup_size_z;
|
||||
let m = limits.max_compute_invocations_per_workgroup;
|
||||
limits.max_compute_workgroup_size_x = x.min(m);
|
||||
limits.max_compute_workgroup_size_y = y.min(m);
|
||||
limits.max_compute_workgroup_size_z = z.min(m);
|
||||
limits.max_compute_invocations_per_workgroup = m.min(x.saturating_mul(y).saturating_mul(z));
|
||||
|
||||
limits.max_immediate_size = limits.max_immediate_size.min(256);
|
||||
|
||||
limits
|
||||
}
|
||||
|
||||
/// Evenly allocates space to each limit,
|
||||
/// capping them only if strictly necessary.
|
||||
pub fn cap_limits_to_be_under_the_sum_limit<const N: usize>(
|
||||
mut limits: [&mut u32; N],
|
||||
sum_limit: u32,
|
||||
) {
|
||||
limits.sort();
|
||||
|
||||
let mut rem_limit = sum_limit;
|
||||
let mut divisor = limits.len() as u32;
|
||||
for limit_to_adjust in limits {
|
||||
let limit = rem_limit / divisor;
|
||||
*limit_to_adjust = (*limit_to_adjust).min(limit);
|
||||
rem_limit -= *limit_to_adjust;
|
||||
divisor -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_cap_limits_to_be_under_the_sum_limit() {
|
||||
test([3, 3, 3], 3, [1, 1, 1]);
|
||||
test([3, 2, 1], 3, [1, 1, 1]);
|
||||
test([1, 2, 3], 6, [1, 2, 3]);
|
||||
test([1, 2, 3], 3, [1, 1, 1]);
|
||||
test([1, 8, 100], 6, [1, 2, 3]);
|
||||
test([2, 80, 80], 6, [2, 2, 2]);
|
||||
test([2, 80, 80], 12, [2, 5, 5]);
|
||||
|
||||
#[track_caller]
|
||||
fn test<const N: usize>(mut input: [u32; N], limit: u32, output: [u32; N]) {
|
||||
cap_limits_to_be_under_the_sum_limit(input.each_mut(), limit);
|
||||
assert_eq!(input, output);
|
||||
}
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
//! RenderDoc integration - <https://renderdoc.org/>
|
||||
#![cfg_attr(not(any(feature = "gles", feature = "vulkan")), allow(dead_code))]
|
||||
|
||||
use alloc::format;
|
||||
use alloc::string::String;
|
||||
use core::{ffi, ptr};
|
||||
|
||||
/// The dynamically loaded RenderDoc API function table
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
pub struct RenderDocApi {
|
||||
api: renderdoc_sys::RENDERDOC_API_1_4_1,
|
||||
lib: libloading::Library,
|
||||
}
|
||||
|
||||
unsafe impl Send for RenderDocApi {}
|
||||
unsafe impl Sync for RenderDocApi {}
|
||||
|
||||
/// RenderDoc API type
|
||||
#[derive(Debug)]
|
||||
pub enum RenderDoc {
|
||||
/// RenderDoc functionality is available
|
||||
Available {
|
||||
/// RenderDoc API with function pointers
|
||||
api: RenderDocApi,
|
||||
},
|
||||
/// RenderDoc functionality is _not_ available
|
||||
NotAvailable {
|
||||
/// A description why renderdoc functionality is not available
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
// TODO: replace with libloading API once supported
|
||||
#[cfg(unix)]
|
||||
const RTLD_NOLOAD: i32 = 0x4;
|
||||
|
||||
impl RenderDoc {
|
||||
pub unsafe fn new() -> Self {
|
||||
type GetApiFn = unsafe extern "C" fn(version: u32, out: *mut *mut ffi::c_void) -> i32;
|
||||
|
||||
#[cfg(windows)]
|
||||
let renderdoc_filename = "renderdoc.dll";
|
||||
#[cfg(all(unix, not(target_os = "android")))]
|
||||
let renderdoc_filename = "librenderdoc.so";
|
||||
#[cfg(target_os = "android")]
|
||||
let renderdoc_filename = "libVkLayer_GLES_RenderDoc.so";
|
||||
|
||||
#[cfg(unix)]
|
||||
let renderdoc_result: Result<libloading::Library, libloading::Error> = unsafe {
|
||||
libloading::os::unix::Library::open(
|
||||
Some(renderdoc_filename),
|
||||
libloading::os::unix::RTLD_NOW | RTLD_NOLOAD,
|
||||
)
|
||||
}
|
||||
.map(|lib| lib.into());
|
||||
|
||||
#[cfg(windows)]
|
||||
let renderdoc_result: Result<libloading::Library, libloading::Error> =
|
||||
libloading::os::windows::Library::open_already_loaded(renderdoc_filename)
|
||||
.map(|lib| lib.into());
|
||||
|
||||
let renderdoc_lib = match renderdoc_result {
|
||||
Ok(lib) => lib,
|
||||
Err(e) => {
|
||||
return RenderDoc::NotAvailable {
|
||||
reason: format!(
|
||||
"Unable to load renderdoc library '{renderdoc_filename}': {e:?}"
|
||||
),
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let get_api: libloading::Symbol<GetApiFn> =
|
||||
match unsafe { renderdoc_lib.get(c"RENDERDOC_GetAPI".to_bytes()) } {
|
||||
Ok(api) => api,
|
||||
Err(e) => {
|
||||
return RenderDoc::NotAvailable {
|
||||
reason: format!(
|
||||
"Unable to get RENDERDOC_GetAPI from renderdoc library '{renderdoc_filename}': {e:?}"
|
||||
),
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut obj = ptr::null_mut();
|
||||
match unsafe { get_api(10401, &mut obj) } {
|
||||
1 => RenderDoc::Available {
|
||||
api: RenderDocApi {
|
||||
api: unsafe { *obj.cast::<renderdoc_sys::RENDERDOC_API_1_4_1>() },
|
||||
lib: renderdoc_lib,
|
||||
},
|
||||
},
|
||||
return_value => RenderDoc::NotAvailable {
|
||||
reason: format!(
|
||||
"Unable to get API from renderdoc library '{renderdoc_filename}': {return_value}"
|
||||
),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for RenderDoc {
|
||||
fn default() -> Self {
|
||||
if !cfg!(debug_assertions) {
|
||||
return RenderDoc::NotAvailable {
|
||||
reason: "RenderDoc support is only enabled with 'debug_assertions'".into(),
|
||||
};
|
||||
}
|
||||
unsafe { Self::new() }
|
||||
}
|
||||
}
|
||||
/// An implementation specific handle
|
||||
pub type Handle = *mut ffi::c_void;
|
||||
|
||||
impl RenderDoc {
|
||||
/// Start a RenderDoc frame capture
|
||||
pub unsafe fn start_frame_capture(&self, device_handle: Handle, window_handle: Handle) -> bool {
|
||||
match *self {
|
||||
Self::Available { api: ref entry } => {
|
||||
unsafe { entry.api.StartFrameCapture.unwrap()(device_handle, window_handle) };
|
||||
true
|
||||
}
|
||||
Self::NotAvailable { ref reason } => {
|
||||
log::warn!("Could not start RenderDoc frame capture: {reason}");
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// End a RenderDoc frame capture
|
||||
pub unsafe fn end_frame_capture(&self, device_handle: Handle, window_handle: Handle) {
|
||||
match *self {
|
||||
Self::Available { api: ref entry } => {
|
||||
unsafe { entry.api.EndFrameCapture.unwrap()(device_handle, window_handle) };
|
||||
}
|
||||
Self::NotAvailable { ref reason } => {
|
||||
log::warn!("Could not end RenderDoc frame capture: {reason}")
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
+1546
File diff suppressed because it is too large.
Load diff
+1868
File diff suppressed because it is too large.
Load diff
Vendored
+467
@@ -0,0 +1,467 @@
|
||||
use windows::Win32::Graphics::{Direct3D, Direct3D12, Dxgi};
|
||||
|
||||
pub fn map_buffer_usage_to_resource_flags(
|
||||
usage: wgt::BufferUses,
|
||||
) -> Direct3D12::D3D12_RESOURCE_FLAGS {
|
||||
let mut flags = Direct3D12::D3D12_RESOURCE_FLAG_NONE;
|
||||
if usage.contains(wgt::BufferUses::STORAGE_READ_WRITE)
|
||||
|| usage.contains(wgt::BufferUses::ACCELERATION_STRUCTURE_QUERY)
|
||||
{
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
}
|
||||
flags
|
||||
}
|
||||
|
||||
pub fn map_buffer_descriptor(
|
||||
desc: &crate::BufferDescriptor<'_>,
|
||||
) -> Direct3D12::D3D12_RESOURCE_DESC {
|
||||
Direct3D12::D3D12_RESOURCE_DESC {
|
||||
Dimension: Direct3D12::D3D12_RESOURCE_DIMENSION_BUFFER,
|
||||
Alignment: 0,
|
||||
Width: desc.size,
|
||||
Height: 1,
|
||||
DepthOrArraySize: 1,
|
||||
MipLevels: 1,
|
||||
Format: Dxgi::Common::DXGI_FORMAT_UNKNOWN,
|
||||
SampleDesc: Dxgi::Common::DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
Layout: Direct3D12::D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
|
||||
Flags: map_buffer_usage_to_resource_flags(desc.usage),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_texture_dimension(dim: wgt::TextureDimension) -> Direct3D12::D3D12_RESOURCE_DIMENSION {
|
||||
match dim {
|
||||
wgt::TextureDimension::D1 => Direct3D12::D3D12_RESOURCE_DIMENSION_TEXTURE1D,
|
||||
wgt::TextureDimension::D2 => Direct3D12::D3D12_RESOURCE_DIMENSION_TEXTURE2D,
|
||||
wgt::TextureDimension::D3 => Direct3D12::D3D12_RESOURCE_DIMENSION_TEXTURE3D,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_texture_usage_to_resource_flags(
|
||||
usage: wgt::TextureUses,
|
||||
) -> Direct3D12::D3D12_RESOURCE_FLAGS {
|
||||
let mut flags = Direct3D12::D3D12_RESOURCE_FLAG_NONE;
|
||||
|
||||
if usage.contains(wgt::TextureUses::COLOR_TARGET) {
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
}
|
||||
if usage
|
||||
.intersects(wgt::TextureUses::DEPTH_STENCIL_READ | wgt::TextureUses::DEPTH_STENCIL_WRITE)
|
||||
{
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
|
||||
if !usage.contains(wgt::TextureUses::RESOURCE) {
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE;
|
||||
}
|
||||
}
|
||||
if usage.intersects(
|
||||
wgt::TextureUses::STORAGE_READ_ONLY
|
||||
| wgt::TextureUses::STORAGE_WRITE_ONLY
|
||||
| wgt::TextureUses::STORAGE_READ_WRITE,
|
||||
) {
|
||||
flags |= Direct3D12::D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
}
|
||||
|
||||
flags
|
||||
}
|
||||
|
||||
pub fn map_address_mode(mode: wgt::AddressMode) -> Direct3D12::D3D12_TEXTURE_ADDRESS_MODE {
|
||||
use wgt::AddressMode as Am;
|
||||
match mode {
|
||||
Am::Repeat => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_WRAP,
|
||||
Am::MirrorRepeat => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_MIRROR,
|
||||
Am::ClampToEdge => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
Am::ClampToBorder => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_BORDER,
|
||||
//Am::MirrorClamp => Direct3D12::D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_filter_mode(mode: wgt::FilterMode) -> Direct3D12::D3D12_FILTER_TYPE {
|
||||
match mode {
|
||||
wgt::FilterMode::Nearest => Direct3D12::D3D12_FILTER_TYPE_POINT,
|
||||
wgt::FilterMode::Linear => Direct3D12::D3D12_FILTER_TYPE_LINEAR,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_mipmap_filter_mode(mode: wgt::MipmapFilterMode) -> Direct3D12::D3D12_FILTER_TYPE {
|
||||
match mode {
|
||||
wgt::MipmapFilterMode::Nearest => Direct3D12::D3D12_FILTER_TYPE_POINT,
|
||||
wgt::MipmapFilterMode::Linear => Direct3D12::D3D12_FILTER_TYPE_LINEAR,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_comparison(func: wgt::CompareFunction) -> Direct3D12::D3D12_COMPARISON_FUNC {
|
||||
use wgt::CompareFunction as Cf;
|
||||
match func {
|
||||
Cf::Never => Direct3D12::D3D12_COMPARISON_FUNC_NEVER,
|
||||
Cf::Less => Direct3D12::D3D12_COMPARISON_FUNC_LESS,
|
||||
Cf::LessEqual => Direct3D12::D3D12_COMPARISON_FUNC_LESS_EQUAL,
|
||||
Cf::Equal => Direct3D12::D3D12_COMPARISON_FUNC_EQUAL,
|
||||
Cf::GreaterEqual => Direct3D12::D3D12_COMPARISON_FUNC_GREATER_EQUAL,
|
||||
Cf::Greater => Direct3D12::D3D12_COMPARISON_FUNC_GREATER,
|
||||
Cf::NotEqual => Direct3D12::D3D12_COMPARISON_FUNC_NOT_EQUAL,
|
||||
Cf::Always => Direct3D12::D3D12_COMPARISON_FUNC_ALWAYS,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_border_color(border_color: Option<wgt::SamplerBorderColor>) -> [f32; 4] {
|
||||
use wgt::SamplerBorderColor as Sbc;
|
||||
match border_color {
|
||||
Some(Sbc::TransparentBlack) | Some(Sbc::Zero) | None => [0.0; 4],
|
||||
Some(Sbc::OpaqueBlack) => [0.0, 0.0, 0.0, 1.0],
|
||||
Some(Sbc::OpaqueWhite) => [1.0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_visibility(visibility: wgt::ShaderStages) -> Direct3D12::D3D12_SHADER_VISIBILITY {
|
||||
match visibility {
|
||||
wgt::ShaderStages::VERTEX => Direct3D12::D3D12_SHADER_VISIBILITY_VERTEX,
|
||||
wgt::ShaderStages::FRAGMENT => Direct3D12::D3D12_SHADER_VISIBILITY_PIXEL,
|
||||
_ => Direct3D12::D3D12_SHADER_VISIBILITY_ALL,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_binding_type(ty: &wgt::BindingType) -> Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE {
|
||||
use wgt::BindingType as Bt;
|
||||
match *ty {
|
||||
Bt::Sampler { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER,
|
||||
Bt::Buffer {
|
||||
ty: wgt::BufferBindingType::Uniform,
|
||||
..
|
||||
} => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_CBV,
|
||||
Bt::Buffer {
|
||||
ty: wgt::BufferBindingType::Storage { read_only: true },
|
||||
..
|
||||
}
|
||||
| Bt::Texture { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
|
||||
Bt::Buffer {
|
||||
ty: wgt::BufferBindingType::Storage { read_only: false },
|
||||
..
|
||||
}
|
||||
| Bt::StorageTexture { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_UAV,
|
||||
Bt::AccelerationStructure { .. } => Direct3D12::D3D12_DESCRIPTOR_RANGE_TYPE_SRV,
|
||||
// External textures require multiple bindings and therefore cannot
|
||||
// be mapped to a single descriptor range type. They must be handled
|
||||
// separately by the caller.
|
||||
Bt::ExternalTexture => unreachable!("External textures must be handled separately"),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_buffer_usage_to_state(usage: wgt::BufferUses) -> Direct3D12::D3D12_RESOURCE_STATES {
|
||||
use wgt::BufferUses as Bu;
|
||||
let mut state = Direct3D12::D3D12_RESOURCE_STATE_COMMON;
|
||||
|
||||
if usage.intersects(Bu::COPY_SRC) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
}
|
||||
if usage.intersects(Bu::COPY_DST) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
}
|
||||
if usage.intersects(Bu::INDEX) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_INDEX_BUFFER;
|
||||
}
|
||||
if usage.intersects(Bu::VERTEX | Bu::UNIFORM) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
|
||||
}
|
||||
if usage.intersects(Bu::STORAGE_READ_WRITE) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
|
||||
} else if usage.intersects(Bu::STORAGE_READ_ONLY) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE
|
||||
| Direct3D12::D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
|
||||
}
|
||||
if usage.intersects(Bu::INDIRECT) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
|
||||
}
|
||||
if usage.intersects(Bu::ACCELERATION_STRUCTURE_QUERY) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
pub fn map_texture_usage_to_state(usage: wgt::TextureUses) -> Direct3D12::D3D12_RESOURCE_STATES {
|
||||
use wgt::TextureUses as Tu;
|
||||
let mut state = Direct3D12::D3D12_RESOURCE_STATE_COMMON;
|
||||
//Note: `RESOLVE_SOURCE` and `RESOLVE_DEST` are not used here
|
||||
//Note: `PRESENT` is the same as `COMMON`
|
||||
if usage == wgt::TextureUses::UNINITIALIZED {
|
||||
return state;
|
||||
}
|
||||
|
||||
if usage.intersects(Tu::COPY_SRC) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
}
|
||||
if usage.intersects(Tu::COPY_DST) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
}
|
||||
if usage.intersects(Tu::RESOURCE) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE
|
||||
| Direct3D12::D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
|
||||
}
|
||||
if usage.intersects(Tu::COLOR_TARGET) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_RENDER_TARGET;
|
||||
}
|
||||
if usage.intersects(Tu::DEPTH_STENCIL_READ) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_DEPTH_READ;
|
||||
}
|
||||
if usage.intersects(Tu::DEPTH_STENCIL_WRITE) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_DEPTH_WRITE;
|
||||
}
|
||||
if usage.intersects(Tu::STORAGE_READ_ONLY | Tu::STORAGE_WRITE_ONLY | Tu::STORAGE_READ_WRITE) {
|
||||
state |= Direct3D12::D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
pub fn map_topology(
|
||||
topology: wgt::PrimitiveTopology,
|
||||
) -> (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY,
|
||||
) {
|
||||
match topology {
|
||||
wgt::PrimitiveTopology::PointList => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_POINTLIST,
|
||||
),
|
||||
wgt::PrimitiveTopology::LineList => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_LINELIST,
|
||||
),
|
||||
wgt::PrimitiveTopology::LineStrip => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_LINESTRIP,
|
||||
),
|
||||
wgt::PrimitiveTopology::TriangleList => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,
|
||||
),
|
||||
wgt::PrimitiveTopology::TriangleStrip => (
|
||||
Direct3D12::D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
|
||||
Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_polygon_mode(mode: wgt::PolygonMode) -> Direct3D12::D3D12_FILL_MODE {
|
||||
match mode {
|
||||
wgt::PolygonMode::Fill => Direct3D12::D3D12_FILL_MODE_SOLID,
|
||||
wgt::PolygonMode::Line => Direct3D12::D3D12_FILL_MODE_WIREFRAME,
|
||||
wgt::PolygonMode::Point => panic!(
|
||||
"{:?} is not enabled for this backend",
|
||||
wgt::Features::POLYGON_MODE_POINT
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// D3D12 doesn't support passing factors ending in `_COLOR` for alpha blending
|
||||
/// (see <https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_render_target_blend_desc>).
|
||||
/// Therefore this function takes an additional `is_alpha` argument
|
||||
/// which if set will return an equivalent `_ALPHA` factor.
|
||||
fn map_blend_factor(factor: wgt::BlendFactor, is_alpha: bool) -> Direct3D12::D3D12_BLEND {
|
||||
use wgt::BlendFactor as Bf;
|
||||
match factor {
|
||||
Bf::Zero => Direct3D12::D3D12_BLEND_ZERO,
|
||||
Bf::One => Direct3D12::D3D12_BLEND_ONE,
|
||||
Bf::Src if is_alpha => Direct3D12::D3D12_BLEND_SRC_ALPHA,
|
||||
Bf::Src => Direct3D12::D3D12_BLEND_SRC_COLOR,
|
||||
Bf::OneMinusSrc if is_alpha => Direct3D12::D3D12_BLEND_INV_SRC_ALPHA,
|
||||
Bf::OneMinusSrc => Direct3D12::D3D12_BLEND_INV_SRC_COLOR,
|
||||
Bf::Dst if is_alpha => Direct3D12::D3D12_BLEND_DEST_ALPHA,
|
||||
Bf::Dst => Direct3D12::D3D12_BLEND_DEST_COLOR,
|
||||
Bf::OneMinusDst if is_alpha => Direct3D12::D3D12_BLEND_INV_DEST_ALPHA,
|
||||
Bf::OneMinusDst => Direct3D12::D3D12_BLEND_INV_DEST_COLOR,
|
||||
Bf::SrcAlpha => Direct3D12::D3D12_BLEND_SRC_ALPHA,
|
||||
Bf::OneMinusSrcAlpha => Direct3D12::D3D12_BLEND_INV_SRC_ALPHA,
|
||||
Bf::DstAlpha => Direct3D12::D3D12_BLEND_DEST_ALPHA,
|
||||
Bf::OneMinusDstAlpha => Direct3D12::D3D12_BLEND_INV_DEST_ALPHA,
|
||||
Bf::Constant => Direct3D12::D3D12_BLEND_BLEND_FACTOR,
|
||||
Bf::OneMinusConstant => Direct3D12::D3D12_BLEND_INV_BLEND_FACTOR,
|
||||
Bf::SrcAlphaSaturated => Direct3D12::D3D12_BLEND_SRC_ALPHA_SAT,
|
||||
Bf::Src1 if is_alpha => Direct3D12::D3D12_BLEND_SRC1_ALPHA,
|
||||
Bf::Src1 => Direct3D12::D3D12_BLEND_SRC1_COLOR,
|
||||
Bf::OneMinusSrc1 if is_alpha => Direct3D12::D3D12_BLEND_INV_SRC1_ALPHA,
|
||||
Bf::OneMinusSrc1 => Direct3D12::D3D12_BLEND_INV_SRC1_COLOR,
|
||||
Bf::Src1Alpha => Direct3D12::D3D12_BLEND_SRC1_ALPHA,
|
||||
Bf::OneMinusSrc1Alpha => Direct3D12::D3D12_BLEND_INV_SRC1_ALPHA,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_blend_component(
|
||||
component: &wgt::BlendComponent,
|
||||
is_alpha: bool,
|
||||
) -> (
|
||||
Direct3D12::D3D12_BLEND_OP,
|
||||
Direct3D12::D3D12_BLEND,
|
||||
Direct3D12::D3D12_BLEND,
|
||||
) {
|
||||
let raw_op = match component.operation {
|
||||
wgt::BlendOperation::Add => Direct3D12::D3D12_BLEND_OP_ADD,
|
||||
wgt::BlendOperation::Subtract => Direct3D12::D3D12_BLEND_OP_SUBTRACT,
|
||||
wgt::BlendOperation::ReverseSubtract => Direct3D12::D3D12_BLEND_OP_REV_SUBTRACT,
|
||||
wgt::BlendOperation::Min => Direct3D12::D3D12_BLEND_OP_MIN,
|
||||
wgt::BlendOperation::Max => Direct3D12::D3D12_BLEND_OP_MAX,
|
||||
};
|
||||
let raw_src = map_blend_factor(component.src_factor, is_alpha);
|
||||
let raw_dst = map_blend_factor(component.dst_factor, is_alpha);
|
||||
(raw_op, raw_src, raw_dst)
|
||||
}
|
||||
|
||||
pub fn map_render_targets(
|
||||
color_targets: &[Option<wgt::ColorTargetState>],
|
||||
) -> [Direct3D12::D3D12_RENDER_TARGET_BLEND_DESC;
|
||||
Direct3D12::D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT as usize] {
|
||||
let dummy_target = Direct3D12::D3D12_RENDER_TARGET_BLEND_DESC {
|
||||
BlendEnable: false.into(),
|
||||
LogicOpEnable: false.into(),
|
||||
SrcBlend: Direct3D12::D3D12_BLEND_ZERO,
|
||||
DestBlend: Direct3D12::D3D12_BLEND_ZERO,
|
||||
BlendOp: Direct3D12::D3D12_BLEND_OP_ADD,
|
||||
SrcBlendAlpha: Direct3D12::D3D12_BLEND_ZERO,
|
||||
DestBlendAlpha: Direct3D12::D3D12_BLEND_ZERO,
|
||||
BlendOpAlpha: Direct3D12::D3D12_BLEND_OP_ADD,
|
||||
LogicOp: Direct3D12::D3D12_LOGIC_OP_CLEAR,
|
||||
RenderTargetWriteMask: 0,
|
||||
};
|
||||
let mut raw_targets =
|
||||
[dummy_target; Direct3D12::D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT as usize];
|
||||
|
||||
for (raw, ct) in raw_targets.iter_mut().zip(color_targets.iter()) {
|
||||
if let Some(ct) = ct.as_ref() {
|
||||
raw.RenderTargetWriteMask = ct.write_mask.bits() as u8;
|
||||
if let Some(ref blend) = ct.blend {
|
||||
let (color_op, color_src, color_dst) = map_blend_component(&blend.color, false);
|
||||
let (alpha_op, alpha_src, alpha_dst) = map_blend_component(&blend.alpha, true);
|
||||
raw.BlendEnable = true.into();
|
||||
raw.BlendOp = color_op;
|
||||
raw.SrcBlend = color_src;
|
||||
raw.DestBlend = color_dst;
|
||||
raw.BlendOpAlpha = alpha_op;
|
||||
raw.SrcBlendAlpha = alpha_src;
|
||||
raw.DestBlendAlpha = alpha_dst;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
raw_targets
|
||||
}
|
||||
|
||||
fn map_stencil_op(op: wgt::StencilOperation) -> Direct3D12::D3D12_STENCIL_OP {
|
||||
use wgt::StencilOperation as So;
|
||||
match op {
|
||||
So::Keep => Direct3D12::D3D12_STENCIL_OP_KEEP,
|
||||
So::Zero => Direct3D12::D3D12_STENCIL_OP_ZERO,
|
||||
So::Replace => Direct3D12::D3D12_STENCIL_OP_REPLACE,
|
||||
So::IncrementClamp => Direct3D12::D3D12_STENCIL_OP_INCR_SAT,
|
||||
So::IncrementWrap => Direct3D12::D3D12_STENCIL_OP_INCR,
|
||||
So::DecrementClamp => Direct3D12::D3D12_STENCIL_OP_DECR_SAT,
|
||||
So::DecrementWrap => Direct3D12::D3D12_STENCIL_OP_DECR,
|
||||
So::Invert => Direct3D12::D3D12_STENCIL_OP_INVERT,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_stencil_face(face: &wgt::StencilFaceState) -> Direct3D12::D3D12_DEPTH_STENCILOP_DESC {
|
||||
Direct3D12::D3D12_DEPTH_STENCILOP_DESC {
|
||||
StencilFailOp: map_stencil_op(face.fail_op),
|
||||
StencilDepthFailOp: map_stencil_op(face.depth_fail_op),
|
||||
StencilPassOp: map_stencil_op(face.pass_op),
|
||||
StencilFunc: map_comparison(face.compare),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn map_depth_stencil(ds: &wgt::DepthStencilState) -> Direct3D12::D3D12_DEPTH_STENCIL_DESC {
|
||||
Direct3D12::D3D12_DEPTH_STENCIL_DESC {
|
||||
DepthEnable: ds.is_depth_enabled().into(),
|
||||
DepthWriteMask: if ds.depth_write_enabled.unwrap_or_default() {
|
||||
Direct3D12::D3D12_DEPTH_WRITE_MASK_ALL
|
||||
} else {
|
||||
Direct3D12::D3D12_DEPTH_WRITE_MASK_ZERO
|
||||
},
|
||||
DepthFunc: map_comparison(ds.depth_compare.unwrap_or_default()),
|
||||
StencilEnable: ds.stencil.is_enabled().into(),
|
||||
StencilReadMask: ds.stencil.read_mask as u8,
|
||||
StencilWriteMask: ds.stencil.write_mask as u8,
|
||||
FrontFace: map_stencil_face(&ds.stencil.front),
|
||||
BackFace: map_stencil_face(&ds.stencil.back),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn map_acceleration_structure_build_flags(
|
||||
flags: wgt::AccelerationStructureFlags,
|
||||
mode: Option<crate::AccelerationStructureBuildMode>,
|
||||
) -> Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAGS {
|
||||
let mut d3d_flags = Default::default();
|
||||
if flags.contains(wgt::AccelerationStructureFlags::ALLOW_COMPACTION) {
|
||||
d3d_flags |=
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_COMPACTION;
|
||||
}
|
||||
|
||||
if flags.contains(wgt::AccelerationStructureFlags::ALLOW_UPDATE) {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_UPDATE;
|
||||
}
|
||||
|
||||
if flags.contains(wgt::AccelerationStructureFlags::LOW_MEMORY) {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_MINIMIZE_MEMORY;
|
||||
}
|
||||
|
||||
if flags.contains(wgt::AccelerationStructureFlags::PREFER_FAST_BUILD) {
|
||||
d3d_flags |=
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_BUILD;
|
||||
}
|
||||
|
||||
if flags.contains(wgt::AccelerationStructureFlags::PREFER_FAST_TRACE) {
|
||||
d3d_flags |=
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE;
|
||||
}
|
||||
|
||||
if let Some(crate::AccelerationStructureBuildMode::Update) = mode {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PERFORM_UPDATE
|
||||
}
|
||||
|
||||
d3d_flags
|
||||
}
|
||||
|
||||
pub(crate) fn map_acceleration_structure_geometry_flags(
|
||||
flags: wgt::AccelerationStructureGeometryFlags,
|
||||
) -> Direct3D12::D3D12_RAYTRACING_GEOMETRY_FLAGS {
|
||||
let mut d3d_flags = Default::default();
|
||||
if flags.contains(wgt::AccelerationStructureGeometryFlags::OPAQUE) {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE;
|
||||
}
|
||||
if flags.contains(wgt::AccelerationStructureGeometryFlags::NO_DUPLICATE_ANY_HIT_INVOCATION) {
|
||||
d3d_flags |= Direct3D12::D3D12_RAYTRACING_GEOMETRY_FLAG_NO_DUPLICATE_ANYHIT_INVOCATION;
|
||||
}
|
||||
d3d_flags
|
||||
}
|
||||
|
||||
pub(crate) fn map_acceleration_structure_copy_mode(
|
||||
mode: wgt::AccelerationStructureCopy,
|
||||
) -> Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE {
|
||||
match mode {
|
||||
wgt::AccelerationStructureCopy::Clone => {
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_CLONE
|
||||
}
|
||||
wgt::AccelerationStructureCopy::Compact => {
|
||||
Direct3D12::D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn make_shader_component_mapping(
|
||||
src0: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING,
|
||||
src1: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING,
|
||||
src2: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING,
|
||||
src3: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING,
|
||||
) -> Direct3D12::D3D12_SHADER_COMPONENT_MAPPING {
|
||||
const M: i32 = Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_MASK as i32;
|
||||
const S: i32 = Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_SHIFT as i32;
|
||||
Direct3D12::D3D12_SHADER_COMPONENT_MAPPING(
|
||||
(src0.0 & M)
|
||||
| (src1.0 & M) << S
|
||||
| (src2.0 & M) << (S * 2)
|
||||
| (src3.0 & M) << (S * 3)
|
||||
| Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_ALWAYS_SET_BIT_AVOIDING_ZEROMEM_MISTAKES
|
||||
as i32,
|
||||
)
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
use alloc::sync::Arc;
|
||||
use core::{ffi, ptr};
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use windows::{
|
||||
core::Interface as _,
|
||||
Win32::{Foundation::HWND, Graphics::DirectComposition},
|
||||
};
|
||||
|
||||
use super::DynLib;
|
||||
|
||||
// Lazy-loaded DirectComposition library
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct DCompLib {
|
||||
lib: Lazy<Result<DynLib, crate::SurfaceError>>,
|
||||
}
|
||||
|
||||
impl DCompLib {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
lib: Lazy::new(|| unsafe {
|
||||
DynLib::new("dcomp.dll").map_err(|err| {
|
||||
log::error!("Error loading dcomp.dll: {err}");
|
||||
crate::SurfaceError::Other("Error loading dcomp.dll")
|
||||
})
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_lib(&self) -> Result<&DynLib, crate::SurfaceError> {
|
||||
match self.lib.as_ref() {
|
||||
Ok(lib) => Ok(lib),
|
||||
Err(err) => Err(err.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn create_device(
|
||||
&self,
|
||||
) -> Result<DirectComposition::IDCompositionDevice, crate::SurfaceError> {
|
||||
let lib = self.get_lib()?;
|
||||
|
||||
// Calls windows::Win32::Graphics::DirectComposition::DCompositionCreateDevice2 on dcomp.dll
|
||||
type Fun = extern "system" fn(
|
||||
pdxdevice: *mut ffi::c_void,
|
||||
riid: *const windows_core::GUID,
|
||||
ppdcompdevice: *mut *mut ffi::c_void,
|
||||
) -> windows_core::HRESULT;
|
||||
let func: libloading::Symbol<Fun> =
|
||||
unsafe { lib.get(c"DCompositionCreateDevice2".to_bytes()) }?;
|
||||
|
||||
let mut res: Option<DirectComposition::IDCompositionDevice> = None;
|
||||
|
||||
(func)(
|
||||
ptr::null_mut(),
|
||||
&DirectComposition::IDCompositionDevice::IID,
|
||||
<*mut _>::cast(&mut res),
|
||||
)
|
||||
.map(|| res.unwrap())
|
||||
.map_err(|err| {
|
||||
log::error!("DirectComposition::DCompositionCreateDevice2 failed: {err}");
|
||||
crate::SurfaceError::Other("DirectComposition::DCompositionCreateDevice2")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct DCompState {
|
||||
inner: Option<InnerState>,
|
||||
}
|
||||
|
||||
impl DCompState {
|
||||
/// This will create a DirectComposition device and a target for the window handle if not already initialized.
|
||||
/// If the device is already initialized, it will return the existing state.
|
||||
pub unsafe fn get_or_init(
|
||||
&mut self,
|
||||
lib: &Arc<DCompLib>,
|
||||
hwnd: &HWND,
|
||||
) -> Result<&mut InnerState, crate::SurfaceError> {
|
||||
if self.inner.is_none() {
|
||||
self.inner = Some(unsafe { InnerState::init(lib, hwnd) }?);
|
||||
}
|
||||
Ok(self.inner.as_mut().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InnerState {
|
||||
pub visual: DirectComposition::IDCompositionVisual,
|
||||
pub device: DirectComposition::IDCompositionDevice,
|
||||
// Must be kept alive but is otherwise unused after initialization.
|
||||
pub _target: DirectComposition::IDCompositionTarget,
|
||||
}
|
||||
|
||||
impl InnerState {
|
||||
/// Creates a DirectComposition device and a target for the given window handle.
|
||||
pub unsafe fn init(lib: &Arc<DCompLib>, hwnd: &HWND) -> Result<Self, crate::SurfaceError> {
|
||||
profiling::scope!("DCompState::init");
|
||||
let dcomp_device = lib.create_device()?;
|
||||
|
||||
let target = unsafe { dcomp_device.CreateTargetForHwnd(*hwnd, false) }.map_err(|err| {
|
||||
log::error!("IDCompositionDevice::CreateTargetForHwnd failed: {err}");
|
||||
crate::SurfaceError::Other("IDCompositionDevice::CreateTargetForHwnd")
|
||||
})?;
|
||||
|
||||
let visual = unsafe { dcomp_device.CreateVisual() }.map_err(|err| {
|
||||
log::error!("IDCompositionDevice::CreateVisual failed: {err}");
|
||||
crate::SurfaceError::Other("IDCompositionDevice::CreateVisual")
|
||||
})?;
|
||||
|
||||
unsafe { target.SetRoot(&visual) }.map_err(|err| {
|
||||
log::error!("IDCompositionTarget::SetRoot failed: {err}");
|
||||
crate::SurfaceError::Other("IDCompositionTarget::SetRoot")
|
||||
})?;
|
||||
|
||||
Ok(InnerState {
|
||||
visual,
|
||||
device: dcomp_device,
|
||||
_target: target,
|
||||
})
|
||||
}
|
||||
}
|
||||
+344
@@ -0,0 +1,344 @@
|
||||
use alloc::vec::Vec;
|
||||
use core::fmt;
|
||||
|
||||
use bit_set::BitSet;
|
||||
use parking_lot::Mutex;
|
||||
use range_alloc::RangeAllocator;
|
||||
use windows::Win32::Graphics::Direct3D12;
|
||||
|
||||
use crate::auxil::dxgi::result::HResult as _;
|
||||
|
||||
const HEAP_SIZE_FIXED: usize = 64;
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub(super) struct DualHandle {
|
||||
cpu: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
pub gpu: Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE,
|
||||
/// How large the block allocated to this handle is.
|
||||
count: u64,
|
||||
}
|
||||
|
||||
impl fmt::Debug for DualHandle {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("DualHandle")
|
||||
.field("cpu", &self.cpu.ptr)
|
||||
.field("gpu", &self.gpu.ptr)
|
||||
.field("count", &self.count)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
type DescriptorIndex = u64;
|
||||
|
||||
pub(super) struct GeneralHeap {
|
||||
pub raw: Direct3D12::ID3D12DescriptorHeap,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
handle_size: u64,
|
||||
total_handles: u64,
|
||||
start: DualHandle,
|
||||
ranges: Mutex<RangeAllocator<DescriptorIndex>>,
|
||||
// Zero-sized without wgpu's counters. Updated under the range lock, so a free racing
|
||||
// an allocation cannot inflate the high-water mark.
|
||||
live: wgt::InternalCounter,
|
||||
peak: wgt::InternalCounter,
|
||||
}
|
||||
|
||||
impl GeneralHeap {
|
||||
pub(super) fn new(
|
||||
device: &Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
total_handles: u64,
|
||||
) -> Result<Self, crate::DeviceError> {
|
||||
let raw = {
|
||||
profiling::scope!("ID3D12Device::CreateDescriptorHeap");
|
||||
let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: ty,
|
||||
NumDescriptors: total_handles as u32,
|
||||
Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
|
||||
NodeMask: 0,
|
||||
};
|
||||
unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) }
|
||||
.into_device_result("Descriptor heap creation")?
|
||||
};
|
||||
|
||||
let start = DualHandle {
|
||||
cpu: unsafe { raw.GetCPUDescriptorHandleForHeapStart() },
|
||||
gpu: unsafe { raw.GetGPUDescriptorHandleForHeapStart() },
|
||||
count: 0,
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
raw,
|
||||
ty,
|
||||
handle_size: unsafe { device.GetDescriptorHandleIncrementSize(ty) } as u64,
|
||||
total_handles,
|
||||
start,
|
||||
ranges: Mutex::new(RangeAllocator::new(0..total_handles)),
|
||||
live: Default::default(),
|
||||
peak: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn at(&self, index: DescriptorIndex, count: u64) -> DualHandle {
|
||||
assert!(index < self.total_handles);
|
||||
DualHandle {
|
||||
cpu: self.cpu_descriptor_at(index),
|
||||
gpu: self.gpu_descriptor_at(index),
|
||||
count,
|
||||
}
|
||||
}
|
||||
|
||||
fn cpu_descriptor_at(&self, index: u64) -> Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.start.cpu.ptr + (self.handle_size * index) as usize,
|
||||
}
|
||||
}
|
||||
|
||||
fn gpu_descriptor_at(&self, index: u64) -> Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE {
|
||||
Direct3D12::D3D12_GPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.start.gpu.ptr + self.handle_size * index,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn allocate_slice(&self, count: u64) -> Result<DescriptorIndex, crate::DeviceError> {
|
||||
let mut ranges = self.ranges.lock();
|
||||
let range = ranges.allocate_range(count).map_err(|err| {
|
||||
log::error!("Unable to allocate descriptors: {err:?}");
|
||||
crate::DeviceError::OutOfMemory
|
||||
})?;
|
||||
self.live.add(count as isize);
|
||||
let live = self.live.read();
|
||||
if live > self.peak.read() {
|
||||
self.peak.set(live);
|
||||
std::eprintln!("dx12: peak live view descriptors {live}/{} ({} B each)", self.total_handles, self.handle_size);
|
||||
}
|
||||
Ok(range.start)
|
||||
}
|
||||
|
||||
/// Free handles previously given out by this `DescriptorHeapSlice`.
|
||||
/// Do not use this with handles not given out by this `DescriptorHeapSlice`.
|
||||
pub(crate) fn free_slice(&self, handle: DualHandle) {
|
||||
let start = (handle.gpu.ptr - self.start.gpu.ptr) / self.handle_size;
|
||||
let mut ranges = self.ranges.lock();
|
||||
ranges.free_range(start..start + handle.count);
|
||||
self.live.sub(handle.count as isize);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fixed-size free-list allocator for CPU descriptors.
|
||||
struct FixedSizeHeap {
|
||||
_raw: Direct3D12::ID3D12DescriptorHeap,
|
||||
/// Bit flag representation of available handles in the heap.
|
||||
///
|
||||
/// 0 - Occupied
|
||||
/// 1 - free
|
||||
availability: u64,
|
||||
handle_size: usize,
|
||||
start: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
}
|
||||
|
||||
impl FixedSizeHeap {
|
||||
fn new(
|
||||
device: &Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
) -> Result<Self, crate::DeviceError> {
|
||||
let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: ty,
|
||||
NumDescriptors: HEAP_SIZE_FIXED as u32,
|
||||
Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
|
||||
NodeMask: 0,
|
||||
};
|
||||
let heap =
|
||||
unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) }
|
||||
.into_device_result("Descriptor heap creation")?;
|
||||
|
||||
Ok(Self {
|
||||
handle_size: unsafe { device.GetDescriptorHandleIncrementSize(ty) } as usize,
|
||||
availability: !0, // all free!
|
||||
start: unsafe { heap.GetCPUDescriptorHandleForHeapStart() },
|
||||
_raw: heap,
|
||||
})
|
||||
}
|
||||
|
||||
fn alloc_handle(
|
||||
&mut self,
|
||||
) -> Result<Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE, crate::DeviceError> {
|
||||
// Find first free slot.
|
||||
let slot = self.availability.trailing_zeros() as usize;
|
||||
if slot >= HEAP_SIZE_FIXED {
|
||||
log::error!("Failed to allocate a handle form a fixed size heap");
|
||||
return Err(crate::DeviceError::OutOfMemory);
|
||||
}
|
||||
// Set the slot as occupied.
|
||||
self.availability ^= 1 << slot;
|
||||
|
||||
Ok(Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.start.ptr + self.handle_size * slot,
|
||||
})
|
||||
}
|
||||
|
||||
fn free_handle(&mut self, handle: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE) {
|
||||
let slot = (handle.ptr - self.start.ptr) / self.handle_size;
|
||||
assert!(slot < HEAP_SIZE_FIXED);
|
||||
assert_eq!(self.availability & (1 << slot), 0);
|
||||
self.availability ^= 1 << slot;
|
||||
}
|
||||
|
||||
fn is_full(&self) -> bool {
|
||||
self.availability == 0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Handle {
|
||||
pub raw: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
heap_index: usize,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Handle {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
fmt.debug_struct("Handle")
|
||||
.field("ptr", &self.raw.ptr)
|
||||
.field("heap_index", &self.heap_index)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct CpuPool {
|
||||
device: Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
heaps: Vec<FixedSizeHeap>,
|
||||
available_heap_indices: BitSet,
|
||||
}
|
||||
|
||||
impl CpuPool {
|
||||
pub(super) fn new(
|
||||
device: Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
) -> Self {
|
||||
Self {
|
||||
device,
|
||||
ty,
|
||||
heaps: Vec::new(),
|
||||
available_heap_indices: BitSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn alloc_handle(&mut self) -> Result<Handle, crate::DeviceError> {
|
||||
let heap_index = self
|
||||
.available_heap_indices
|
||||
.iter()
|
||||
.next()
|
||||
.unwrap_or(self.heaps.len());
|
||||
|
||||
// Allocate a new heap
|
||||
if heap_index == self.heaps.len() {
|
||||
self.heaps.push(FixedSizeHeap::new(&self.device, self.ty)?);
|
||||
self.available_heap_indices.insert(heap_index);
|
||||
}
|
||||
|
||||
let heap = &mut self.heaps[heap_index];
|
||||
let handle = Handle {
|
||||
raw: heap.alloc_handle()?,
|
||||
heap_index,
|
||||
};
|
||||
if heap.is_full() {
|
||||
self.available_heap_indices.remove(heap_index);
|
||||
}
|
||||
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
pub(super) fn free_handle(&mut self, handle: Handle) {
|
||||
self.heaps[handle.heap_index].free_handle(handle.raw);
|
||||
self.available_heap_indices.insert(handle.heap_index);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct CpuHeapInner {
|
||||
pub _raw: Direct3D12::ID3D12DescriptorHeap,
|
||||
pub stage: Vec<Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE>,
|
||||
}
|
||||
|
||||
pub(super) struct CpuHeap {
|
||||
pub inner: Mutex<CpuHeapInner>,
|
||||
start: Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
handle_size: u32,
|
||||
total: u32,
|
||||
}
|
||||
|
||||
unsafe impl Send for CpuHeap {}
|
||||
unsafe impl Sync for CpuHeap {}
|
||||
|
||||
impl CpuHeap {
|
||||
pub(super) fn new(
|
||||
device: &Direct3D12::ID3D12Device,
|
||||
ty: Direct3D12::D3D12_DESCRIPTOR_HEAP_TYPE,
|
||||
total: u32,
|
||||
) -> Result<Self, crate::DeviceError> {
|
||||
let handle_size = unsafe { device.GetDescriptorHandleIncrementSize(ty) };
|
||||
let desc = Direct3D12::D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: ty,
|
||||
NumDescriptors: total,
|
||||
Flags: Direct3D12::D3D12_DESCRIPTOR_HEAP_FLAG_NONE,
|
||||
NodeMask: 0,
|
||||
};
|
||||
let raw = unsafe { device.CreateDescriptorHeap::<Direct3D12::ID3D12DescriptorHeap>(&desc) }
|
||||
.into_device_result("CPU descriptor heap creation")?;
|
||||
|
||||
let start = unsafe { raw.GetCPUDescriptorHandleForHeapStart() };
|
||||
|
||||
Ok(Self {
|
||||
inner: Mutex::new(CpuHeapInner {
|
||||
_raw: raw,
|
||||
stage: Vec::new(),
|
||||
}),
|
||||
start,
|
||||
handle_size,
|
||||
total,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn at(&self, index: u32) -> Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
debug_assert!(
|
||||
index < self.total,
|
||||
"Index ({index}) out of bounds {total}",
|
||||
total = self.total
|
||||
);
|
||||
Direct3D12::D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.start.ptr + (self.handle_size * index) as usize,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for CpuHeap {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("CpuHeap")
|
||||
.field("start", &self.start.ptr)
|
||||
.field("handle_size", &self.handle_size)
|
||||
.field("total", &self.total)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) unsafe fn upload(
|
||||
device: &Direct3D12::ID3D12Device,
|
||||
src: &CpuHeapInner,
|
||||
dst: &GeneralHeap,
|
||||
dummy_copy_counts: &[u32],
|
||||
) -> Result<DualHandle, crate::DeviceError> {
|
||||
let count = src.stage.len() as u32;
|
||||
let index = dst.allocate_slice(count as u64)?;
|
||||
unsafe {
|
||||
device.CopyDescriptors(
|
||||
1,
|
||||
&dst.cpu_descriptor_at(index),
|
||||
Some(&count),
|
||||
count,
|
||||
src.stage.as_ptr(),
|
||||
Some(dummy_copy_counts.as_ptr()),
|
||||
dst.ty,
|
||||
)
|
||||
};
|
||||
Ok(dst.at(index, count as u64))
|
||||
}
|
||||
+2691
File diff suppressed because it is too large.
Load diff
+176
@@ -0,0 +1,176 @@
|
||||
use alloc::sync::Arc;
|
||||
use core::ops::Deref;
|
||||
|
||||
use windows::core::Interface as _;
|
||||
use windows::Win32::Graphics::{Direct3D, Direct3D12};
|
||||
|
||||
use super::D3D12Lib;
|
||||
use crate::auxil::dxgi::factory::DxgiAdapter;
|
||||
|
||||
/// Abstraction over D3D12 device creation.
|
||||
///
|
||||
/// Supports two paths:
|
||||
/// - **Independent**: Uses `ID3D12DeviceFactory` from the Agility SDK's Independent Devices API.
|
||||
/// - **Legacy**: Uses the traditional `D3D12CreateDevice` export.
|
||||
pub(super) enum DeviceFactory {
|
||||
/// Uses `ID3D12DeviceFactory` from the Independent Devices API.
|
||||
Independent(Direct3D12::ID3D12DeviceFactory),
|
||||
/// Uses the traditional `D3D12CreateDevice` export.
|
||||
Legacy,
|
||||
}
|
||||
|
||||
impl DeviceFactory {
|
||||
/// Create a new `DeviceFactory`.
|
||||
///
|
||||
/// If `agility_sdk` is `Some`, attempts to set up the Independent Devices API path.
|
||||
/// On failure, the behavior depends on
|
||||
/// [`on_load_failure`](wgt::Dx12AgilitySDKLoadFailure):
|
||||
/// - [`Fallback`](wgt::Dx12AgilitySDKLoadFailure::Fallback): logs a warning and
|
||||
/// returns `Ok(Legacy)`.
|
||||
/// - [`Error`](wgt::Dx12AgilitySDKLoadFailure::Error): returns an `Err`.
|
||||
pub(super) fn new(
|
||||
lib: &D3D12Lib,
|
||||
agility_sdk: Option<&wgt::Dx12AgilitySDK>,
|
||||
) -> Result<Self, crate::InstanceError> {
|
||||
let Some(agility_sdk) = agility_sdk else {
|
||||
log::debug!("No D3D12 Agility SDK configuration provided; using system D3D12 runtime");
|
||||
return Ok(Self::Legacy);
|
||||
};
|
||||
|
||||
match Self::try_create_independent(lib, agility_sdk) {
|
||||
Ok(factory) => {
|
||||
log::debug!(
|
||||
"Using D3D12 Agility SDK v{} from '{}'",
|
||||
agility_sdk.sdk_version,
|
||||
agility_sdk.sdk_path
|
||||
);
|
||||
Ok(Self::Independent(factory))
|
||||
}
|
||||
Err(err) => {
|
||||
let message = format!(
|
||||
"Failed to initialize D3D12 Agility SDK (v{} at '{}'): {err}",
|
||||
agility_sdk.sdk_version, agility_sdk.sdk_path
|
||||
);
|
||||
|
||||
match agility_sdk.on_load_failure {
|
||||
wgt::Dx12AgilitySDKLoadFailure::Fallback => {
|
||||
log::warn!("{message}; falling back to system D3D12 runtime");
|
||||
Ok(Self::Legacy)
|
||||
}
|
||||
wgt::Dx12AgilitySDKLoadFailure::Error => {
|
||||
Err(crate::InstanceError::new(message))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn try_create_independent(
|
||||
lib: &D3D12Lib,
|
||||
agility_sdk: &wgt::Dx12AgilitySDK,
|
||||
) -> Result<Direct3D12::ID3D12DeviceFactory, DeviceFactoryError> {
|
||||
// Step 1: Get ID3D12SDKConfiguration1 via D3D12GetInterface
|
||||
let sdk_config: Direct3D12::ID3D12SDKConfiguration1 = lib
|
||||
.get_interface(&Direct3D12::CLSID_D3D12SDKConfiguration)
|
||||
.map_err(DeviceFactoryError::GetInterface)?;
|
||||
|
||||
// Step 2: Create device factory with the specified SDK version and path
|
||||
let sdk_path = std::ffi::CString::new(agility_sdk.sdk_path.as_bytes())
|
||||
.map_err(|_| DeviceFactoryError::InvalidPath)?;
|
||||
let factory: Direct3D12::ID3D12DeviceFactory = unsafe {
|
||||
sdk_config.CreateDeviceFactory(
|
||||
agility_sdk.sdk_version,
|
||||
windows::core::PCSTR(sdk_path.as_ptr().cast::<u8>()),
|
||||
)
|
||||
}
|
||||
.map_err(DeviceFactoryError::CreateDeviceFactory)?;
|
||||
|
||||
Ok(factory)
|
||||
}
|
||||
|
||||
/// Enable the D3D12 debug layer and optionally GPU-based validation.
|
||||
///
|
||||
/// - **Legacy**: configures debug globally via `D3D12GetDebugInterface`.
|
||||
/// - **Independent**: uses `GetConfigurationInterface` to get an
|
||||
/// `ID3D12Debug` scoped to the factory.
|
||||
pub(super) fn enable_debug_layer(&self, lib: &D3D12Lib, flags: wgt::InstanceFlags) {
|
||||
if !flags
|
||||
.intersects(wgt::InstanceFlags::VALIDATION | wgt::InstanceFlags::GPU_BASED_VALIDATION)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let debug_controller = match self {
|
||||
Self::Independent(factory) => {
|
||||
match unsafe {
|
||||
factory.GetConfigurationInterface::<Direct3D12::ID3D12Debug>(
|
||||
&Direct3D12::CLSID_D3D12Debug,
|
||||
)
|
||||
} {
|
||||
Ok(debug) => debug,
|
||||
Err(err) => {
|
||||
log::warn!("Failed to get debug interface from device factory: {err}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::Legacy => match lib.debug_interface() {
|
||||
Ok(Some(debug)) => debug,
|
||||
Ok(None) => return,
|
||||
Err(err) => {
|
||||
log::warn!("Failed to get debug interface: {err}");
|
||||
return;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
if flags.intersects(wgt::InstanceFlags::VALIDATION) {
|
||||
unsafe { debug_controller.EnableDebugLayer() }
|
||||
}
|
||||
if flags.intersects(wgt::InstanceFlags::GPU_BASED_VALIDATION) {
|
||||
if let Ok(debug1) = debug_controller.cast::<Direct3D12::ID3D12Debug1>() {
|
||||
unsafe { debug1.SetEnableGPUBasedValidation(true) }
|
||||
} else {
|
||||
log::warn!("Failed to enable GPU-based validation");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a D3D12 device using the appropriate method.
|
||||
pub(super) fn create_device(
|
||||
&self,
|
||||
lib: &Arc<D3D12Lib>,
|
||||
adapter: &DxgiAdapter,
|
||||
feature_level: Direct3D::D3D_FEATURE_LEVEL,
|
||||
) -> Result<Direct3D12::ID3D12Device, super::CreateDeviceError> {
|
||||
match self {
|
||||
Self::Independent(factory) => {
|
||||
let mut result__: Option<Direct3D12::ID3D12Device> = None;
|
||||
unsafe { factory.CreateDevice(adapter.deref(), feature_level, &mut result__) }
|
||||
.map_err(|e| super::CreateDeviceError::D3D12CreateDevice(e.into()))?;
|
||||
|
||||
result__.ok_or(super::CreateDeviceError::RetDeviceIsNull)
|
||||
}
|
||||
Self::Legacy => lib.create_device(adapter, feature_level),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Debug for DeviceFactory {
|
||||
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
|
||||
match self {
|
||||
Self::Independent(_) => write!(f, "DeviceFactory::Independent"),
|
||||
Self::Legacy => write!(f, "DeviceFactory::Legacy"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum DeviceFactoryError {
|
||||
#[error("failed to get ID3D12SDKConfiguration1: {0}")]
|
||||
GetInterface(super::GetInterfaceError),
|
||||
#[error("SDK path contains null bytes")]
|
||||
InvalidPath,
|
||||
#[error("CreateDeviceFactory failed: {0}")]
|
||||
CreateDeviceFactory(windows::core::Error),
|
||||
}
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
use alloc::{string::String, sync::Arc, vec::Vec};
|
||||
|
||||
use parking_lot::RwLock;
|
||||
use windows::Win32::{Foundation, Graphics::Dxgi};
|
||||
|
||||
use super::SurfaceTarget;
|
||||
use crate::{
|
||||
auxil,
|
||||
dx12::{
|
||||
device_creation::DeviceFactory, shader_compilation::CompilerContainer, D3D12Lib, DCompLib,
|
||||
},
|
||||
};
|
||||
|
||||
impl crate::Instance for super::Instance {
|
||||
type A = super::Api;
|
||||
|
||||
unsafe fn init(desc: &crate::InstanceDescriptor<'_>) -> Result<Self, crate::InstanceError> {
|
||||
profiling::scope!("Init DX12 Backend");
|
||||
let lib_main = D3D12Lib::new().map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("failed to load d3d12.dll"), e)
|
||||
})?;
|
||||
|
||||
// Create DeviceFactory first so we know which debug path to use
|
||||
let device_factory =
|
||||
DeviceFactory::new(&lib_main, desc.backend_options.dx12.agility_sdk.as_ref())?;
|
||||
|
||||
device_factory.enable_debug_layer(&lib_main, desc.flags);
|
||||
|
||||
let (lib_dxgi, factory) = auxil::dxgi::factory::create_factory(desc.flags)?;
|
||||
|
||||
// Create IDXGIFactoryMedia
|
||||
let factory_media = lib_dxgi.create_factory_media().ok();
|
||||
|
||||
let mut supports_allow_tearing = false;
|
||||
if let Some(factory5) = factory.as_factory5() {
|
||||
let mut allow_tearing = Foundation::FALSE;
|
||||
let hr = unsafe {
|
||||
factory5.CheckFeatureSupport(
|
||||
Dxgi::DXGI_FEATURE_PRESENT_ALLOW_TEARING,
|
||||
<*mut _>::cast(&mut allow_tearing),
|
||||
size_of_val(&allow_tearing) as u32,
|
||||
)
|
||||
};
|
||||
|
||||
match hr {
|
||||
Err(err) => log::warn!("Unable to check for tearing support: {err}"),
|
||||
Ok(()) => supports_allow_tearing = true,
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize the shader compiler
|
||||
let compiler_container = match desc.backend_options.dx12.shader_compiler.clone() {
|
||||
wgt::Dx12Compiler::DynamicDxc { dxc_path } => {
|
||||
CompilerContainer::new_dynamic_dxc(dxc_path.into()).map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("Failed to load dynamic DXC"), e)
|
||||
})?
|
||||
}
|
||||
wgt::Dx12Compiler::StaticDxc => CompilerContainer::new_static_dxc().map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("Failed to load static DXC"), e)
|
||||
})?,
|
||||
wgt::Dx12Compiler::Fxc => CompilerContainer::new_fxc().map_err(|e| {
|
||||
crate::InstanceError::with_source(String::from("Failed to load FXC"), e)
|
||||
})?,
|
||||
wgt::Dx12Compiler::Auto => {
|
||||
if cfg!(static_dxc) {
|
||||
// Prefer static DXC if its compiled in
|
||||
CompilerContainer::new_static_dxc().map_err(|e| {
|
||||
crate::InstanceError::with_source(
|
||||
String::from("Failed to load static DXC"),
|
||||
e,
|
||||
)
|
||||
})?
|
||||
} else {
|
||||
// Try to load dynamic DXC
|
||||
let dynamic = CompilerContainer::new_dynamic_dxc("dxcompiler.dll".into());
|
||||
match dynamic {
|
||||
Ok(v) => v,
|
||||
Err(super::shader_compilation::GetContainerError::FailedToLoad(..)) => {
|
||||
// If it can't be found load FXC
|
||||
CompilerContainer::new_fxc().map_err(|e| {
|
||||
crate::InstanceError::with_source(
|
||||
String::from("Failed to load FXC"),
|
||||
e,
|
||||
)
|
||||
})?
|
||||
}
|
||||
Err(e) => {
|
||||
// If another error occurs when loading static DXC return that error
|
||||
return Err(crate::InstanceError::with_source(
|
||||
String::from("Failed to load dynamic DXC"),
|
||||
e,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
match compiler_container {
|
||||
CompilerContainer::DynamicDxc(..) => {
|
||||
log::debug!("Using dynamic DXC for shader compilation")
|
||||
}
|
||||
CompilerContainer::StaticDxc(..) => {
|
||||
log::debug!("Using static DXC for shader compilation")
|
||||
}
|
||||
CompilerContainer::Fxc(..) => {
|
||||
log::debug!("Using FXC for shader compilation")
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
// The call to create_factory will only succeed if we get a factory4, so this is safe.
|
||||
factory,
|
||||
factory_media,
|
||||
library: Arc::new(lib_main),
|
||||
device_factory: Arc::new(device_factory),
|
||||
dcomp_lib: Arc::new(DCompLib::new()),
|
||||
presentation_system: desc.backend_options.dx12.presentation_system,
|
||||
_lib_dxgi: lib_dxgi,
|
||||
supports_allow_tearing,
|
||||
flags: desc.flags,
|
||||
memory_budget_thresholds: desc.memory_budget_thresholds,
|
||||
compiler_container: Arc::new(compiler_container),
|
||||
options: desc.backend_options.dx12.clone(),
|
||||
telemetry: desc.telemetry,
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn create_surface(
|
||||
&self,
|
||||
display_handle: raw_window_handle::RawDisplayHandle,
|
||||
window_handle: raw_window_handle::RawWindowHandle,
|
||||
) -> Result<super::Surface, crate::InstanceError> {
|
||||
assert!(matches!(
|
||||
display_handle,
|
||||
raw_window_handle::RawDisplayHandle::Windows(_)
|
||||
));
|
||||
match window_handle {
|
||||
raw_window_handle::RawWindowHandle::Win32(handle) => {
|
||||
// https://github.com/rust-windowing/raw-window-handle/issues/171
|
||||
let handle = Foundation::HWND(handle.hwnd.get() as *mut _);
|
||||
let target = match self.presentation_system {
|
||||
wgt::Dx12SwapchainKind::DxgiFromHwnd => SurfaceTarget::WndHandle(handle),
|
||||
wgt::Dx12SwapchainKind::DxgiFromVisual => SurfaceTarget::VisualFromWndHandle {
|
||||
handle,
|
||||
dcomp_state: Default::default(),
|
||||
},
|
||||
};
|
||||
|
||||
Ok(super::Surface {
|
||||
factory: self.factory.clone(),
|
||||
factory_media: self.factory_media.clone(),
|
||||
target,
|
||||
supports_allow_tearing: self.supports_allow_tearing,
|
||||
swap_chain: RwLock::new(None),
|
||||
options: self.options.clone(),
|
||||
hdr_source: Some(auxil::dxgi::hdr::DxgiHdrSource::new(handle)),
|
||||
})
|
||||
}
|
||||
_ => Err(crate::InstanceError::new(format!(
|
||||
"window handle {window_handle:?} is not a Win32 handle"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn enumerate_adapters(
|
||||
&self,
|
||||
_surface_hint: Option<&super::Surface>,
|
||||
) -> Vec<crate::ExposedAdapter<super::Api>> {
|
||||
let adapters = auxil::dxgi::factory::enumerate_adapters(self.factory.clone());
|
||||
|
||||
adapters
|
||||
.into_iter()
|
||||
.filter_map(|raw| {
|
||||
super::Adapter::expose(
|
||||
raw,
|
||||
&self.library,
|
||||
&self.device_factory,
|
||||
&self.dcomp_lib,
|
||||
self.flags,
|
||||
self.memory_budget_thresholds,
|
||||
self.compiler_container.clone(),
|
||||
self.options.clone(),
|
||||
self.telemetry,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl super::Instance {
|
||||
/// Exposes one adapter the caller found through DXGI, as `enumerate_adapters` exposes each
|
||||
/// one it lists, without creating a device on any other adapter or loading another adapter's
|
||||
/// driver. `None` when the adapter is one `enumerate_adapters` skips or can't run D3D12.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `adapter` must come from a DXGI factory in this process.
|
||||
pub unsafe fn expose_adapter(
|
||||
&self,
|
||||
adapter: &Dxgi::IDXGIAdapter1,
|
||||
) -> Option<crate::ExposedAdapter<super::Api>> {
|
||||
use windows::core::Interface as _;
|
||||
if !auxil::dxgi::factory::should_keep_adapter(adapter) {
|
||||
return None;
|
||||
}
|
||||
let raw = match adapter.cast::<Dxgi::IDXGIAdapter4>() {
|
||||
Ok(adapter4) => auxil::dxgi::factory::DxgiAdapter::Adapter4(adapter4),
|
||||
Err(_) => auxil::dxgi::factory::DxgiAdapter::Adapter3(adapter.cast().ok()?),
|
||||
};
|
||||
super::Adapter::expose(
|
||||
raw,
|
||||
&self.library,
|
||||
&self.device_factory,
|
||||
&self.dcomp_lib,
|
||||
self.flags,
|
||||
self.memory_budget_thresholds,
|
||||
self.compiler_container.clone(),
|
||||
self.options.clone(),
|
||||
self.telemetry,
|
||||
)
|
||||
}
|
||||
}
|
||||
Vendored
+1935
File diff suppressed because it is too large.
Load diff
+344
@@ -0,0 +1,344 @@
|
||||
//! We try to use pipeline stream descriptors where possible, but this isn't allowed
|
||||
//! on some older windows 10 versions. Therefore, we also must have some logic to
|
||||
//! convert such descriptors to the "traditional" equivalent,
|
||||
//! `D3D12_GRAPHICS_PIPELINE_STATE_DESC`.
|
||||
//!
|
||||
//! Stream descriptors allow extending the pipeline, enabling more advanced features,
|
||||
//! including mesh shaders and multiview/view instancing. Using a stream descriptor
|
||||
//! is like using a vulkan descriptor with a `pNext` chain. It doesn't have direct
|
||||
//! benefits to all use cases, but allows new use cases.
|
||||
//!
|
||||
//! The code for pipeline stream descriptors is very complicated, and can have bad
|
||||
//! consequences if it is written incorrectly. It has been isolated to this file for
|
||||
//! that reason.
|
||||
|
||||
use core::{ffi::c_void, mem::ManuallyDrop, ptr::NonNull};
|
||||
|
||||
use alloc::vec::Vec;
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::Win32::Graphics::Dxgi::Common::*;
|
||||
use windows_core::Interface;
|
||||
|
||||
use crate::dx12::borrow_interface_temporarily;
|
||||
|
||||
// Wrapper newtypes for various pipeline subobjects which
|
||||
// use complicated or non-unique representations.
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
// Option<NonNull<c_void>> is guaranteed to have the same representation as a raw pointer.
|
||||
struct RootSignature(Option<NonNull<c_void>>);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct VertexShader(D3D12_SHADER_BYTECODE);
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct PixelShader(D3D12_SHADER_BYTECODE);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct MeshShader(D3D12_SHADER_BYTECODE);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct TaskShader(D3D12_SHADER_BYTECODE);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct SampleMask(u32);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Copy, Clone)]
|
||||
struct NodeMask(u32);
|
||||
|
||||
/// Trait for types that can be used as subobjects in a pipeline state stream.
|
||||
///
|
||||
/// Safety:
|
||||
/// - The type must be the correct alignment and size for the subobject it represents.
|
||||
/// - The type must map to exactly one `D3D12_PIPELINE_STATE_SUBOBJECT_TYPE` variant.
|
||||
/// - The variant must correctly represent the type's role in the pipeline state stream.
|
||||
/// - The type must be `Copy` to ensure safe duplication in the stream.
|
||||
/// - The type must be valid to memcpy into the pipeline state stream.
|
||||
unsafe trait RenderPipelineStreamObject: Copy {
|
||||
const SUBOBJECT_TYPE: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE;
|
||||
}
|
||||
|
||||
macro_rules! implement_stream_object {
|
||||
(unsafe $ty:ty => $variant:expr) => {
|
||||
unsafe impl RenderPipelineStreamObject for $ty {
|
||||
const SUBOBJECT_TYPE: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE = $variant;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
implement_stream_object! { unsafe RootSignature => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE }
|
||||
implement_stream_object! { unsafe VertexShader => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS }
|
||||
implement_stream_object! { unsafe PixelShader => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS }
|
||||
implement_stream_object! { unsafe MeshShader => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS }
|
||||
implement_stream_object! { unsafe TaskShader => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_AS }
|
||||
implement_stream_object! { unsafe D3D12_BLEND_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND }
|
||||
implement_stream_object! { unsafe SampleMask => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK }
|
||||
implement_stream_object! { unsafe D3D12_RASTERIZER_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER }
|
||||
implement_stream_object! { unsafe D3D12_DEPTH_STENCIL_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL }
|
||||
implement_stream_object! { unsafe D3D12_PRIMITIVE_TOPOLOGY_TYPE => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY }
|
||||
implement_stream_object! { unsafe D3D12_RT_FORMAT_ARRAY => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS }
|
||||
implement_stream_object! { unsafe DXGI_FORMAT => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT }
|
||||
implement_stream_object! { unsafe DXGI_SAMPLE_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC }
|
||||
implement_stream_object! { unsafe NodeMask => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK }
|
||||
implement_stream_object! { unsafe D3D12_CACHED_PIPELINE_STATE => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO }
|
||||
implement_stream_object! { unsafe D3D12_PIPELINE_STATE_FLAGS => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS }
|
||||
implement_stream_object! { unsafe D3D12_INPUT_LAYOUT_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT }
|
||||
implement_stream_object! { unsafe D3D12_INDEX_BUFFER_STRIP_CUT_VALUE => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_IB_STRIP_CUT_VALUE }
|
||||
implement_stream_object! { unsafe D3D12_STREAM_OUTPUT_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT }
|
||||
implement_stream_object! { unsafe D3D12_VIEW_INSTANCING_DESC => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING }
|
||||
|
||||
/// Implementaation of a pipeline state stream, which is a sequence of subobjects put into
|
||||
/// a byte array according to some basic alignment rules.
|
||||
///
|
||||
/// Each subobject must start on an 8 byte boundary. Each subobject contains a 32 bit
|
||||
/// type identifier, followed by the actual subobject data, aligned as required by the
|
||||
/// subobject's structure.
|
||||
///
|
||||
/// See <https://learn.microsoft.com/en-us/windows/win32/api/d3d12/ns-d3d12-d3d12_pipeline_state_stream_desc>
|
||||
/// for more information.
|
||||
pub(super) struct RenderPipelineStateStream<'a> {
|
||||
bytes: Vec<u8>,
|
||||
_marker: core::marker::PhantomData<&'a ()>,
|
||||
}
|
||||
|
||||
impl<'a> RenderPipelineStateStream<'a> {
|
||||
fn new() -> Self {
|
||||
// Dynamic allocation is used here because the resulting stream can become very large.
|
||||
// We pre-allocate the size based on an estimate of the size of the struct plus some extra space
|
||||
// per member for tags and alignment padding. In practice this will always be too big, as not
|
||||
// all members will be used.
|
||||
let size_of_stream_desc = size_of::<RenderPipelineStateStreamDesc>();
|
||||
let members = 20; // Approximate number of members we might push
|
||||
let capacity = size_of_stream_desc + members * 8; // Extra space for tags and alignment
|
||||
Self {
|
||||
bytes: Vec::with_capacity(capacity),
|
||||
_marker: core::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
/// Align the internal byte buffer to the given alignment,
|
||||
/// padding with zeros as necessary.
|
||||
fn align_to(&mut self, alignment: usize) {
|
||||
let aligned_length = self.bytes.len().next_multiple_of(alignment);
|
||||
self.bytes.resize(aligned_length, 0);
|
||||
}
|
||||
|
||||
/// Adds a subobject to the pipeline state stream.
|
||||
fn add_object<T: RenderPipelineStreamObject>(&mut self, object: T) {
|
||||
// Ensure 8-byte alignment for the subobject start.
|
||||
self.align_to(8);
|
||||
|
||||
// Append the type tag (u32)
|
||||
let tag: u32 = T::SUBOBJECT_TYPE.0 as u32;
|
||||
self.bytes.extend_from_slice(&tag.to_ne_bytes());
|
||||
|
||||
// Align the data to its natural alignment.
|
||||
self.align_to(align_of_val::<T>(&object));
|
||||
|
||||
// Append the data itself, as raw bytes
|
||||
let data_ptr: *const T = &object;
|
||||
let data_u8_ptr: *const u8 = data_ptr.cast::<u8>();
|
||||
let data_size = size_of_val::<T>(&object);
|
||||
let slice = unsafe { core::slice::from_raw_parts::<u8>(data_u8_ptr, data_size) };
|
||||
self.bytes.extend_from_slice(slice);
|
||||
}
|
||||
|
||||
/// Creates a pipeline state object from the stream.
|
||||
///
|
||||
/// Safety:
|
||||
/// - All unsafety invariants required by [`ID3D12Device2::CreatePipelineState`] must be upheld by the caller.
|
||||
pub unsafe fn create_pipeline_state(
|
||||
&mut self,
|
||||
device: &ID3D12Device2,
|
||||
) -> windows::core::Result<ID3D12PipelineState> {
|
||||
let stream_desc = D3D12_PIPELINE_STATE_STREAM_DESC {
|
||||
SizeInBytes: self.bytes.len(),
|
||||
pPipelineStateSubobjectStream: self.bytes.as_mut_ptr().cast(),
|
||||
};
|
||||
|
||||
// Safety: lifetime on Self preserved the contents
|
||||
// of the stream. Other unsafety invariants are upheld by the caller.
|
||||
unsafe { device.CreatePipelineState(&stream_desc) }
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Debug)]
|
||||
pub struct RenderPipelineStateStreamDesc<'a> {
|
||||
pub root_signature: Option<&'a ID3D12RootSignature>,
|
||||
pub pixel_shader: D3D12_SHADER_BYTECODE,
|
||||
pub blend_state: D3D12_BLEND_DESC,
|
||||
pub sample_mask: u32,
|
||||
pub rasterizer_state: D3D12_RASTERIZER_DESC,
|
||||
pub depth_stencil_state: D3D12_DEPTH_STENCIL_DESC,
|
||||
pub primitive_topology_type: D3D12_PRIMITIVE_TOPOLOGY_TYPE,
|
||||
pub rtv_formats: D3D12_RT_FORMAT_ARRAY,
|
||||
pub dsv_format: DXGI_FORMAT,
|
||||
pub sample_desc: DXGI_SAMPLE_DESC,
|
||||
pub node_mask: u32,
|
||||
pub cached_pso: D3D12_CACHED_PIPELINE_STATE,
|
||||
pub flags: D3D12_PIPELINE_STATE_FLAGS,
|
||||
pub view_instancing: Option<D3D12_VIEW_INSTANCING_DESC>,
|
||||
|
||||
// Vertex pipeline specific
|
||||
pub vertex_shader: D3D12_SHADER_BYTECODE,
|
||||
pub input_layout: D3D12_INPUT_LAYOUT_DESC,
|
||||
pub index_buffer_strip_cut_value: D3D12_INDEX_BUFFER_STRIP_CUT_VALUE,
|
||||
pub stream_output: D3D12_STREAM_OUTPUT_DESC,
|
||||
|
||||
// Mesh pipeline specific
|
||||
pub task_shader: D3D12_SHADER_BYTECODE,
|
||||
pub mesh_shader: D3D12_SHADER_BYTECODE,
|
||||
}
|
||||
|
||||
impl RenderPipelineStateStreamDesc<'_> {
|
||||
pub fn to_stream(&self) -> RenderPipelineStateStream<'_> {
|
||||
let mut stream = RenderPipelineStateStream::new();
|
||||
|
||||
// Importantly here, the ID3D12RootSignature _itself_ is the pointer we're
|
||||
// trying to serialize into the stream, not a pointer to the pointer.
|
||||
//
|
||||
// This is correct because as_raw() returns turns that smart object into the raw
|
||||
// pointer that _is_ the com object handle.
|
||||
let root_sig_pointer = self
|
||||
.root_signature
|
||||
.map(|a| NonNull::new(a.as_raw()).unwrap());
|
||||
// Because the stream object borrows from self for its entire lifetime,
|
||||
// it is safe to store the pointer into it.
|
||||
stream.add_object(RootSignature(root_sig_pointer));
|
||||
|
||||
stream.add_object(self.blend_state);
|
||||
stream.add_object(SampleMask(self.sample_mask));
|
||||
stream.add_object(self.rasterizer_state);
|
||||
stream.add_object(self.depth_stencil_state);
|
||||
stream.add_object(self.primitive_topology_type);
|
||||
if self.rtv_formats.NumRenderTargets != 0 {
|
||||
stream.add_object(self.rtv_formats);
|
||||
}
|
||||
if self.dsv_format != DXGI_FORMAT_UNKNOWN {
|
||||
stream.add_object(self.dsv_format);
|
||||
}
|
||||
stream.add_object(self.sample_desc);
|
||||
if self.node_mask != 0 {
|
||||
stream.add_object(NodeMask(self.node_mask));
|
||||
}
|
||||
if !self.cached_pso.pCachedBlob.is_null() {
|
||||
stream.add_object(self.cached_pso);
|
||||
}
|
||||
stream.add_object(self.flags);
|
||||
if let Some(view_instancing) = self.view_instancing {
|
||||
stream.add_object(view_instancing);
|
||||
}
|
||||
if !self.pixel_shader.pShaderBytecode.is_null() {
|
||||
stream.add_object(PixelShader(self.pixel_shader));
|
||||
}
|
||||
if !self.vertex_shader.pShaderBytecode.is_null() {
|
||||
stream.add_object(VertexShader(self.vertex_shader));
|
||||
stream.add_object(self.input_layout);
|
||||
stream.add_object(self.index_buffer_strip_cut_value);
|
||||
stream.add_object(self.stream_output);
|
||||
}
|
||||
if !self.task_shader.pShaderBytecode.is_null() {
|
||||
stream.add_object(TaskShader(self.task_shader));
|
||||
}
|
||||
if !self.mesh_shader.pShaderBytecode.is_null() {
|
||||
stream.add_object(MeshShader(self.mesh_shader));
|
||||
}
|
||||
|
||||
stream
|
||||
}
|
||||
|
||||
/// Returns a traditional D3D12_GRAPHICS_PIPELINE_STATE_DESC.
|
||||
///
|
||||
/// Safety:
|
||||
/// - This returned struct must not outlive self.
|
||||
pub unsafe fn to_graphics_pipeline_descriptor(&self) -> D3D12_GRAPHICS_PIPELINE_STATE_DESC {
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC {
|
||||
pRootSignature: if let Some(rsig) = self.root_signature {
|
||||
unsafe { borrow_interface_temporarily(rsig) }
|
||||
} else {
|
||||
ManuallyDrop::new(None)
|
||||
},
|
||||
VS: self.vertex_shader,
|
||||
PS: self.pixel_shader,
|
||||
DS: D3D12_SHADER_BYTECODE::default(),
|
||||
HS: D3D12_SHADER_BYTECODE::default(),
|
||||
GS: D3D12_SHADER_BYTECODE::default(),
|
||||
StreamOutput: self.stream_output,
|
||||
BlendState: self.blend_state,
|
||||
SampleMask: self.sample_mask,
|
||||
RasterizerState: self.rasterizer_state,
|
||||
DepthStencilState: self.depth_stencil_state,
|
||||
InputLayout: self.input_layout,
|
||||
IBStripCutValue: self.index_buffer_strip_cut_value,
|
||||
PrimitiveTopologyType: self.primitive_topology_type,
|
||||
NumRenderTargets: self.rtv_formats.NumRenderTargets,
|
||||
RTVFormats: self.rtv_formats.RTFormats,
|
||||
DSVFormat: self.dsv_format,
|
||||
SampleDesc: self.sample_desc,
|
||||
NodeMask: self.node_mask,
|
||||
CachedPSO: self.cached_pso,
|
||||
Flags: self.flags,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn wrappers() {
|
||||
assert_eq!(size_of::<RootSignature>(), size_of::<ID3D12RootSignature>());
|
||||
assert_eq!(
|
||||
align_of::<RootSignature>(),
|
||||
align_of::<ID3D12RootSignature>()
|
||||
)
|
||||
}
|
||||
|
||||
implement_stream_object!(unsafe u16 => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(1));
|
||||
implement_stream_object!(unsafe u32 => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(2));
|
||||
implement_stream_object!(unsafe u64 => D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(3));
|
||||
|
||||
#[test]
|
||||
fn stream() {
|
||||
let mut stream = RenderPipelineStateStream::new();
|
||||
|
||||
stream.add_object(42u16);
|
||||
stream.add_object(84u32);
|
||||
stream.add_object(168u64);
|
||||
|
||||
assert_eq!(stream.bytes.len(), 32);
|
||||
|
||||
// Object 1: u16
|
||||
|
||||
// Tag at the beginning
|
||||
assert_eq!(&stream.bytes[0..4], &1u32.to_ne_bytes());
|
||||
// Data tucked in, aligned to the natural alignment of u16
|
||||
assert_eq!(&stream.bytes[4..6], &42u16.to_ne_bytes());
|
||||
// Padding to align the next subobject to an 8 byte boundary.
|
||||
assert_eq!(&stream.bytes[6..8], &[0, 0]);
|
||||
|
||||
// Object 2: u32
|
||||
|
||||
// Tag at the beginning
|
||||
assert_eq!(&stream.bytes[8..12], &2u32.to_ne_bytes());
|
||||
// Data tucked in, aligned to the natural alignment of u32
|
||||
assert_eq!(&stream.bytes[12..16], &84u32.to_ne_bytes());
|
||||
|
||||
// Object 3: u64
|
||||
|
||||
// Tag at the beginning
|
||||
assert_eq!(&stream.bytes[16..20], &3u32.to_ne_bytes());
|
||||
// Padding to align the u64 to an 8 byte boundary.
|
||||
assert_eq!(&stream.bytes[20..24], &[0, 0, 0, 0]);
|
||||
// Data tucked in, aligned to the natural alignment of u64
|
||||
assert_eq!(&stream.bytes[24..32], &168u64.to_ne_bytes());
|
||||
}
|
||||
}
|
||||
+252
@@ -0,0 +1,252 @@
|
||||
//! Sampler management for DX12.
|
||||
//!
|
||||
//! Nearly identical to the Vulkan sampler cache, with added descriptor heap management.
|
||||
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use hashbrown::{hash_map::Entry, HashMap};
|
||||
|
||||
use ordered_float::OrderedFloat;
|
||||
use parking_lot::Mutex;
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
use crate::dx12::HResult;
|
||||
|
||||
/// The index of a sampler in the global sampler heap.
|
||||
///
|
||||
/// This is a type-safe, transparent wrapper around a u32.
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct SamplerIndex(u32);
|
||||
|
||||
/// [`D3D12_SAMPLER_DESC`] is not hashable, so we wrap it in a newtype that is.
|
||||
///
|
||||
/// We use [`OrderedFloat`] to allow for floating point values to be compared and
|
||||
/// hashed in a defined way.
|
||||
#[derive(Debug, Copy, Clone)]
|
||||
struct HashableSamplerDesc(D3D12_SAMPLER_DESC);
|
||||
|
||||
impl PartialEq for HashableSamplerDesc {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.0.Filter == other.0.Filter
|
||||
&& self.0.AddressU == other.0.AddressU
|
||||
&& self.0.AddressV == other.0.AddressV
|
||||
&& self.0.AddressW == other.0.AddressW
|
||||
&& OrderedFloat(self.0.MipLODBias) == OrderedFloat(other.0.MipLODBias)
|
||||
&& self.0.MaxAnisotropy == other.0.MaxAnisotropy
|
||||
&& self.0.ComparisonFunc == other.0.ComparisonFunc
|
||||
&& self.0.BorderColor.map(OrderedFloat) == other.0.BorderColor.map(OrderedFloat)
|
||||
&& OrderedFloat(self.0.MinLOD) == OrderedFloat(other.0.MinLOD)
|
||||
&& OrderedFloat(self.0.MaxLOD) == OrderedFloat(other.0.MaxLOD)
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for HashableSamplerDesc {}
|
||||
|
||||
impl core::hash::Hash for HashableSamplerDesc {
|
||||
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
self.0.Filter.0.hash(state);
|
||||
self.0.AddressU.0.hash(state);
|
||||
self.0.AddressV.0.hash(state);
|
||||
self.0.AddressW.0.hash(state);
|
||||
OrderedFloat(self.0.MipLODBias).hash(state);
|
||||
self.0.MaxAnisotropy.hash(state);
|
||||
self.0.ComparisonFunc.0.hash(state);
|
||||
self.0.BorderColor.map(OrderedFloat).hash(state);
|
||||
OrderedFloat(self.0.MinLOD).hash(state);
|
||||
OrderedFloat(self.0.MaxLOD).hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// Entry in the sampler cache.
|
||||
struct CacheEntry {
|
||||
index: SamplerIndex,
|
||||
ref_count: u32,
|
||||
}
|
||||
|
||||
/// Container for the mutable management state of the sampler heap.
|
||||
///
|
||||
/// We have this separated, using interior mutability, to allow for the outside world
|
||||
/// to access the heap directly without needing to take the lock.
|
||||
pub(crate) struct SamplerHeapState {
|
||||
/// Mapping from the sampler description to the index within the heap and the refcount.
|
||||
mapping: HashMap<HashableSamplerDesc, CacheEntry>,
|
||||
/// List of free sampler indices.
|
||||
freelist: Vec<SamplerIndex>,
|
||||
}
|
||||
|
||||
/// Global sampler heap for the device.
|
||||
///
|
||||
/// As D3D12 only allows 2048 samplers to be in a single heap, we need to cache
|
||||
/// samplers aggressively and refer to them in shaders by index.
|
||||
pub(crate) struct SamplerHeap {
|
||||
/// Mutable management state of the sampler heap.
|
||||
state: Mutex<SamplerHeapState>,
|
||||
|
||||
/// The heap itself.
|
||||
heap: ID3D12DescriptorHeap,
|
||||
/// The CPU-side handle to the first descriptor in the heap.
|
||||
///
|
||||
/// Both the CPU and GPU handles point to the same descriptor, just in
|
||||
/// different contexts.
|
||||
heap_cpu_start_handle: D3D12_CPU_DESCRIPTOR_HANDLE,
|
||||
/// The GPU-side handle to the first descriptor in the heap.
|
||||
///
|
||||
/// Both the CPU and GPU handles point to the same descriptor, just in
|
||||
/// different contexts.
|
||||
heap_gpu_start_handle: D3D12_GPU_DESCRIPTOR_HANDLE,
|
||||
|
||||
/// This is the device-specific size of sampler descriptors.
|
||||
descriptor_stride: u32,
|
||||
}
|
||||
|
||||
impl SamplerHeap {
|
||||
pub fn new(
|
||||
device: &ID3D12Device,
|
||||
private_caps: &super::PrivateCapabilities,
|
||||
) -> Result<Self, crate::DeviceError> {
|
||||
profiling::scope!("SamplerHeap::new");
|
||||
|
||||
// WARP can report this as 2M or more. We clamp it to 64k to be safe.
|
||||
const SAMPLER_HEAP_SIZE_CLAMP: u32 = 64 * 1024;
|
||||
|
||||
let max_unique_samplers = private_caps
|
||||
.max_sampler_descriptor_heap_size
|
||||
.min(SAMPLER_HEAP_SIZE_CLAMP);
|
||||
|
||||
let desc = D3D12_DESCRIPTOR_HEAP_DESC {
|
||||
Type: D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER,
|
||||
NumDescriptors: max_unique_samplers,
|
||||
Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
|
||||
NodeMask: 0,
|
||||
};
|
||||
let heap = unsafe { device.CreateDescriptorHeap::<ID3D12DescriptorHeap>(&desc) }
|
||||
.into_device_result("Failed to create global GPU-Visible Sampler Descriptor Heap")?;
|
||||
|
||||
let heap_cpu_start_handle = unsafe { heap.GetCPUDescriptorHandleForHeapStart() };
|
||||
let heap_gpu_start_handle = unsafe { heap.GetGPUDescriptorHandleForHeapStart() };
|
||||
|
||||
let descriptor_stride =
|
||||
unsafe { device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER) };
|
||||
|
||||
Ok(Self {
|
||||
state: Mutex::new(SamplerHeapState {
|
||||
mapping: HashMap::new(),
|
||||
// Reverse so that samplers get allocated starting from zero.
|
||||
freelist: (0..max_unique_samplers).map(SamplerIndex).rev().collect(),
|
||||
}),
|
||||
heap,
|
||||
heap_cpu_start_handle,
|
||||
heap_gpu_start_handle,
|
||||
descriptor_stride,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns a reference to the raw descriptor heap.
|
||||
pub fn heap(&self) -> &ID3D12DescriptorHeap {
|
||||
&self.heap
|
||||
}
|
||||
|
||||
/// Returns a reference the handle to be bound to the descriptor table.
|
||||
pub fn gpu_descriptor_table(&self) -> D3D12_GPU_DESCRIPTOR_HANDLE {
|
||||
self.heap_gpu_start_handle
|
||||
}
|
||||
|
||||
/// Add a sampler with the given description to the heap.
|
||||
///
|
||||
/// If the sampler already exists, the refcount is incremented and the existing index is returned.
|
||||
///
|
||||
/// If the sampler does not exist, a new sampler is created and the index is returned.
|
||||
///
|
||||
/// If the heap is full, an error is returned.
|
||||
pub fn create_sampler(
|
||||
&self,
|
||||
device: &ID3D12Device,
|
||||
desc: D3D12_SAMPLER_DESC,
|
||||
) -> Result<SamplerIndex, crate::DeviceError> {
|
||||
profiling::scope!("SamplerHeap::create_sampler");
|
||||
|
||||
let hashable_desc = HashableSamplerDesc(desc);
|
||||
|
||||
// Eagarly dereference the lock to allow split borrows.
|
||||
let state = &mut *self.state.lock();
|
||||
|
||||
// Lookup the sampler in the mapping.
|
||||
match state.mapping.entry(hashable_desc) {
|
||||
Entry::Occupied(occupied_entry) => {
|
||||
// We have found a match, so increment the refcount and return the index.
|
||||
let entry = occupied_entry.into_mut();
|
||||
entry.ref_count += 1;
|
||||
Ok(entry.index)
|
||||
}
|
||||
Entry::Vacant(vacant_entry) => {
|
||||
// We need to create a new sampler.
|
||||
|
||||
// Try to get a new index from the freelist.
|
||||
let Some(index) = state.freelist.pop() else {
|
||||
// If the freelist is empty, we have hit the maximum number of samplers.
|
||||
log::error!("There is no more room in the global sampler heap for more unique samplers. Your device supports a maximum of {} unique samplers.", state.mapping.len());
|
||||
return Err(crate::DeviceError::OutOfMemory);
|
||||
};
|
||||
|
||||
// Compute the CPU side handle for the new sampler.
|
||||
let handle = D3D12_CPU_DESCRIPTOR_HANDLE {
|
||||
ptr: self.heap_cpu_start_handle.ptr
|
||||
+ self.descriptor_stride as usize * index.0 as usize,
|
||||
};
|
||||
|
||||
unsafe {
|
||||
device.CreateSampler(&desc, handle);
|
||||
}
|
||||
|
||||
// Insert the new sampler into the mapping.
|
||||
vacant_entry.insert(CacheEntry {
|
||||
index,
|
||||
ref_count: 1,
|
||||
});
|
||||
|
||||
Ok(index)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decrement the refcount of the sampler with the given description.
|
||||
///
|
||||
/// If the refcount reaches zero, the sampler is destroyed and the index is returned to the freelist.
|
||||
///
|
||||
/// The provided index is checked against the index of the sampler with the given description, ensuring
|
||||
/// that there isn't a clerical error from the caller.
|
||||
pub fn destroy_sampler(&self, desc: D3D12_SAMPLER_DESC, provided_index: SamplerIndex) {
|
||||
profiling::scope!("SamplerHeap::destroy_sampler");
|
||||
|
||||
// Eagarly dereference the lock to allow split borrows.
|
||||
let state = &mut *self.state.lock();
|
||||
|
||||
// Get the index of the sampler to destroy.
|
||||
let Entry::Occupied(mut hash_map_entry) = state.mapping.entry(HashableSamplerDesc(desc))
|
||||
else {
|
||||
log::error!(
|
||||
"Tried to destroy a sampler that doesn't exist. Sampler description: {desc:#?}"
|
||||
);
|
||||
return;
|
||||
};
|
||||
let cache_entry = hash_map_entry.get_mut();
|
||||
|
||||
// Ensure that the provided index matches the index of the sampler to destroy.
|
||||
assert_eq!(
|
||||
cache_entry.index, provided_index,
|
||||
"Mismatched sampler index, this is an implementation bug"
|
||||
);
|
||||
|
||||
// Decrement the refcount of the sampler.
|
||||
cache_entry.ref_count -= 1;
|
||||
|
||||
// If we are the last reference, remove the sampler from the mapping and return the index to the freelist.
|
||||
//
|
||||
// As samplers only exist as descriptors in the heap, there is nothing needed to be done to destroy the sampler.
|
||||
if cache_entry.ref_count == 0 {
|
||||
state.freelist.push(cache_entry.index);
|
||||
hash_map_entry.remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
+453
@@ -0,0 +1,453 @@
|
||||
use alloc::{string::String, vec::Vec};
|
||||
use core::ffi::CStr;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::auxil::dxgi::result::HResult;
|
||||
use thiserror::Error;
|
||||
use windows::{
|
||||
core::{Interface, PCSTR, PCWSTR},
|
||||
Win32::Graphics::Direct3D::{Dxc, Fxc, ID3DBlob, D3D_SHADER_MACRO},
|
||||
};
|
||||
|
||||
pub(super) enum CompilerContainer {
|
||||
Fxc(CompilerFxc),
|
||||
DynamicDxc(CompilerDynamicDxc),
|
||||
#[cfg_attr(not(static_dxc), allow(unused))]
|
||||
StaticDxc(CompilerStaticDxc),
|
||||
}
|
||||
|
||||
pub(super) struct CompilerFxc {
|
||||
/// Loaded on the first compile: an app whose shaders all come precompiled never loads it.
|
||||
fxc: std::sync::OnceLock<Result<FxcLib, String>>,
|
||||
}
|
||||
|
||||
pub(super) struct CompilerDynamicDxc {
|
||||
max_shader_model: wgt::DxcShaderModel,
|
||||
compiler: Dxc::IDxcCompiler3,
|
||||
// Has to be held onto for the lifetime of the device otherwise shaders will fail to compile.
|
||||
// Only needed when using dynamic linking.
|
||||
_dxc: DxcLib,
|
||||
}
|
||||
|
||||
pub(super) struct CompilerStaticDxc {
|
||||
max_shader_model: wgt::DxcShaderModel,
|
||||
compiler: Dxc::IDxcCompiler3,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub(super) enum GetContainerError {
|
||||
#[error(transparent)]
|
||||
Device(#[from] crate::DeviceError),
|
||||
#[error("Failed to load {0}: {1}")]
|
||||
FailedToLoad(&'static str, libloading::Error),
|
||||
}
|
||||
|
||||
impl CompilerContainer {
|
||||
pub(super) fn new_fxc() -> Result<Self, GetContainerError> {
|
||||
Ok(Self::Fxc(CompilerFxc { fxc: std::sync::OnceLock::new() }))
|
||||
}
|
||||
|
||||
pub(super) fn new_dynamic_dxc(dxc_path: PathBuf) -> Result<Self, GetContainerError> {
|
||||
let dxc = DxcLib::new_dynamic(dxc_path)
|
||||
.map_err(|e| GetContainerError::FailedToLoad("dxcompiler.dll", e))?;
|
||||
|
||||
let compiler = dxc.create_instance::<Dxc::IDxcCompiler3>()?;
|
||||
|
||||
let (mut major, mut minor) = (1, 0);
|
||||
// DXC 1.0 didn't support this. If the cast fails assume it is DXC 1.0.
|
||||
if let Ok(version_info) = compiler.cast::<Dxc::IDxcVersionInfo>() {
|
||||
unsafe {
|
||||
version_info.GetVersion(&mut major, &mut minor).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Self::DynamicDxc(CompilerDynamicDxc {
|
||||
max_shader_model: wgt::DxcShaderModel::from_dxc_version(major, minor),
|
||||
compiler,
|
||||
_dxc: dxc,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Creates a [`CompilerContainer`] that delegates to the statically-linked version of DXC.
|
||||
pub(super) fn new_static_dxc() -> Result<CompilerContainer, crate::DeviceError> {
|
||||
#[cfg(static_dxc)]
|
||||
{
|
||||
unsafe {
|
||||
let compiler = dxc_create_instance::<Dxc::IDxcCompiler3>(|clsid, iid, ppv| {
|
||||
windows_core::HRESULT(mach_dxcompiler_rs::DxcCreateInstance(
|
||||
clsid.cast(),
|
||||
iid.cast(),
|
||||
ppv,
|
||||
))
|
||||
})?;
|
||||
|
||||
Ok(CompilerContainer::StaticDxc(CompilerStaticDxc {
|
||||
max_shader_model: wgt::DxcShaderModel::V6_7,
|
||||
compiler,
|
||||
}))
|
||||
}
|
||||
}
|
||||
#[cfg(not(static_dxc))]
|
||||
{
|
||||
panic!("Attempted to create a static DXC shader compiler, but the static-dxc feature was not enabled")
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn max_shader_model(&self) -> Option<wgt::DxcShaderModel> {
|
||||
match self {
|
||||
CompilerContainer::Fxc(..) => None,
|
||||
CompilerContainer::DynamicDxc(CompilerDynamicDxc {
|
||||
max_shader_model, ..
|
||||
})
|
||||
| CompilerContainer::StaticDxc(CompilerStaticDxc {
|
||||
max_shader_model, ..
|
||||
}) => Some(max_shader_model.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn compile(
|
||||
&self,
|
||||
device: &super::Device,
|
||||
source: &str,
|
||||
source_name: Option<&CStr>,
|
||||
raw_ep: &str,
|
||||
stage_bit: wgt::ShaderStages,
|
||||
full_stage: &str,
|
||||
) -> Result<super::CompiledShader, crate::PipelineError> {
|
||||
match self {
|
||||
CompilerContainer::Fxc(CompilerFxc { fxc }) => compile_fxc(
|
||||
device,
|
||||
source,
|
||||
source_name,
|
||||
raw_ep,
|
||||
stage_bit,
|
||||
full_stage,
|
||||
fxc.get_or_init(|| FxcLib::new_dynamic().map_err(|e| format!("{e}")))
|
||||
.as_ref()
|
||||
.map_err(|e| crate::PipelineError::Linkage(stage_bit, e.clone()))?,
|
||||
),
|
||||
CompilerContainer::DynamicDxc(CompilerDynamicDxc { compiler, .. })
|
||||
| CompilerContainer::StaticDxc(CompilerStaticDxc { compiler, .. }) => compile_dxc(
|
||||
device,
|
||||
source,
|
||||
source_name,
|
||||
raw_ep,
|
||||
stage_bit,
|
||||
full_stage,
|
||||
compiler,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type D3DCompileFn = unsafe extern "system" fn(
|
||||
psrcdata: *const core::ffi::c_void,
|
||||
srcdatasize: usize,
|
||||
psourcename: PCSTR,
|
||||
pdefines: *const D3D_SHADER_MACRO,
|
||||
pinclude: *mut core::ffi::c_void,
|
||||
pentrypoint: PCSTR,
|
||||
ptarget: PCSTR,
|
||||
flags1: u32,
|
||||
flags2: u32,
|
||||
ppcode: *mut *mut core::ffi::c_void,
|
||||
pperrormsgs: *mut *mut core::ffi::c_void,
|
||||
) -> windows_core::HRESULT;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct FxcLib {
|
||||
// `d3dcompile_fn` points into `_lib`, so `_lib` must be held for as long
|
||||
// as we want to keep compiling shaders with FXC.
|
||||
_lib: crate::dx12::DynLib,
|
||||
d3dcompile_fn: D3DCompileFn,
|
||||
}
|
||||
|
||||
impl FxcLib {
|
||||
const PATH: &str = "d3dcompiler_47.dll";
|
||||
|
||||
fn new_dynamic() -> Result<Self, GetContainerError> {
|
||||
unsafe {
|
||||
let lib = crate::dx12::DynLib::new(Self::PATH)
|
||||
.map_err(|e| GetContainerError::FailedToLoad(FxcLib::PATH, e))?;
|
||||
let d3dcompile_fn: D3DCompileFn = *lib.get::<D3DCompileFn>(c"D3DCompile".to_bytes())?;
|
||||
|
||||
Ok(Self {
|
||||
_lib: lib,
|
||||
d3dcompile_fn,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn compile(
|
||||
&self,
|
||||
source: &str,
|
||||
source_name: Option<&CStr>,
|
||||
raw_ep: &str,
|
||||
full_stage: &str,
|
||||
compile_flags: u32,
|
||||
shader_data: &mut Option<ID3DBlob>,
|
||||
error: &mut Option<ID3DBlob>,
|
||||
) -> Result<windows_core::Result<()>, crate::DeviceError> {
|
||||
unsafe {
|
||||
let raw_ep = alloc::ffi::CString::new(raw_ep).unwrap();
|
||||
let full_stage = alloc::ffi::CString::new(full_stage).unwrap();
|
||||
|
||||
// If no name has been set, D3DCompile wants the null pointer.
|
||||
let source_name = source_name
|
||||
.map(|cstr| cstr.as_ptr().cast())
|
||||
.unwrap_or(core::ptr::null());
|
||||
|
||||
let shader_data: *mut Option<ID3DBlob> = shader_data;
|
||||
let error: *mut Option<ID3DBlob> = error;
|
||||
|
||||
{
|
||||
profiling::scope!("Fxc::D3DCompile");
|
||||
Ok((self.d3dcompile_fn)(
|
||||
source.as_ptr().cast(),
|
||||
source.len(),
|
||||
PCSTR(source_name),
|
||||
core::ptr::null(),
|
||||
core::ptr::null_mut(),
|
||||
PCSTR(raw_ep.as_ptr().cast()),
|
||||
PCSTR(full_stage.as_ptr().cast()),
|
||||
compile_flags,
|
||||
0,
|
||||
shader_data.cast(),
|
||||
error.cast(),
|
||||
)
|
||||
.ok())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compile_fxc(
|
||||
device: &super::Device,
|
||||
source: &str,
|
||||
source_name: Option<&CStr>,
|
||||
raw_ep: &str,
|
||||
stage_bit: wgt::ShaderStages,
|
||||
full_stage: &str,
|
||||
fxc: &FxcLib,
|
||||
) -> Result<super::CompiledShader, crate::PipelineError> {
|
||||
profiling::scope!("compile_fxc");
|
||||
let mut compile_flags = Fxc::D3DCOMPILE_ENABLE_STRICTNESS;
|
||||
if device
|
||||
.shared
|
||||
.private_caps
|
||||
.instance_flags
|
||||
.contains(wgt::InstanceFlags::DEBUG)
|
||||
{
|
||||
compile_flags |= Fxc::D3DCOMPILE_DEBUG | Fxc::D3DCOMPILE_SKIP_OPTIMIZATION;
|
||||
}
|
||||
|
||||
let mut shader_data = None;
|
||||
let mut error = None;
|
||||
let hr = fxc.compile(
|
||||
source,
|
||||
source_name,
|
||||
raw_ep,
|
||||
full_stage,
|
||||
compile_flags,
|
||||
&mut shader_data,
|
||||
&mut error,
|
||||
)?;
|
||||
|
||||
match hr {
|
||||
Ok(()) => {
|
||||
let shader_data = shader_data.unwrap();
|
||||
Ok(super::CompiledShader::Fxc(shader_data))
|
||||
}
|
||||
Err(e) => {
|
||||
let mut full_msg = format!("FXC D3DCompile error ({e})");
|
||||
if let Some(error) = error {
|
||||
use core::fmt::Write as _;
|
||||
let message = unsafe {
|
||||
core::slice::from_raw_parts(
|
||||
error.GetBufferPointer().cast(),
|
||||
error.GetBufferSize(),
|
||||
)
|
||||
};
|
||||
let _ = write!(full_msg, ": {}", String::from_utf8_lossy(message));
|
||||
}
|
||||
Err(crate::PipelineError::Linkage(stage_bit, full_msg))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait DxcObj: Interface {
|
||||
const CLSID: windows::core::GUID;
|
||||
}
|
||||
impl DxcObj for Dxc::IDxcCompiler3 {
|
||||
const CLSID: windows::core::GUID = Dxc::CLSID_DxcCompiler;
|
||||
}
|
||||
impl DxcObj for Dxc::IDxcUtils {
|
||||
const CLSID: windows::core::GUID = Dxc::CLSID_DxcUtils;
|
||||
}
|
||||
impl DxcObj for Dxc::IDxcValidator {
|
||||
const CLSID: windows::core::GUID = Dxc::CLSID_DxcValidator;
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct DxcLib {
|
||||
lib: crate::dx12::DynLib,
|
||||
}
|
||||
|
||||
impl DxcLib {
|
||||
fn new_dynamic(lib_path: PathBuf) -> Result<Self, libloading::Error> {
|
||||
unsafe { crate::dx12::DynLib::new(lib_path).map(|lib| Self { lib }) }
|
||||
}
|
||||
|
||||
pub fn create_instance<T: DxcObj>(&self) -> Result<T, crate::DeviceError> {
|
||||
unsafe {
|
||||
type DxcCreateInstanceFn = unsafe extern "system" fn(
|
||||
rclsid: *const windows_core::GUID,
|
||||
riid: *const windows_core::GUID,
|
||||
ppv: *mut *mut core::ffi::c_void,
|
||||
)
|
||||
-> windows_core::HRESULT;
|
||||
|
||||
let func: libloading::Symbol<DxcCreateInstanceFn> =
|
||||
self.lib.get(c"DxcCreateInstance".to_bytes())?;
|
||||
dxc_create_instance::<T>(|clsid, iid, ppv| func(clsid, iid, ppv))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Invokes the provided library function to create a DXC object.
|
||||
unsafe fn dxc_create_instance<T: DxcObj>(
|
||||
f: impl Fn(
|
||||
*const windows_core::GUID,
|
||||
*const windows_core::GUID,
|
||||
*mut *mut core::ffi::c_void,
|
||||
) -> windows_core::HRESULT,
|
||||
) -> Result<T, crate::DeviceError> {
|
||||
let mut result__ = None;
|
||||
f(&T::CLSID, &T::IID, <*mut _>::cast(&mut result__))
|
||||
.ok()
|
||||
.into_device_result("DxcCreateInstance")?;
|
||||
result__.ok_or(crate::DeviceError::Unexpected)
|
||||
}
|
||||
|
||||
/// Owned PCWSTR
|
||||
#[allow(clippy::upper_case_acronyms)]
|
||||
struct OPCWSTR {
|
||||
inner: Vec<u16>,
|
||||
}
|
||||
|
||||
impl OPCWSTR {
|
||||
fn new(s: &str) -> Self {
|
||||
let mut inner: Vec<_> = s.encode_utf16().collect();
|
||||
inner.push(0);
|
||||
Self { inner }
|
||||
}
|
||||
|
||||
fn ptr(&self) -> PCWSTR {
|
||||
PCWSTR(self.inner.as_ptr())
|
||||
}
|
||||
}
|
||||
|
||||
fn get_output<T: Interface>(
|
||||
res: &Dxc::IDxcResult,
|
||||
kind: Dxc::DXC_OUT_KIND,
|
||||
) -> Result<T, crate::DeviceError> {
|
||||
let mut result__: Option<T> = None;
|
||||
unsafe { res.GetOutput::<T>(kind, &mut None, <*mut _>::cast(&mut result__)) }
|
||||
.into_device_result("GetOutput")?;
|
||||
result__.ok_or(crate::DeviceError::Unexpected)
|
||||
}
|
||||
|
||||
fn as_err_str(blob: &Dxc::IDxcBlobUtf8) -> Result<&str, crate::DeviceError> {
|
||||
let ptr = unsafe { blob.GetStringPointer() };
|
||||
let len = unsafe { blob.GetStringLength() };
|
||||
core::str::from_utf8(unsafe { core::slice::from_raw_parts(ptr.0, len) })
|
||||
.map_err(|_| crate::DeviceError::Unexpected)
|
||||
}
|
||||
|
||||
fn compile_dxc(
|
||||
device: &crate::dx12::Device,
|
||||
source: &str,
|
||||
source_name: Option<&CStr>,
|
||||
raw_ep: &str,
|
||||
stage_bit: wgt::ShaderStages,
|
||||
full_stage: &str,
|
||||
compiler: &Dxc::IDxcCompiler3,
|
||||
) -> Result<crate::dx12::CompiledShader, crate::PipelineError> {
|
||||
profiling::scope!("compile_dxc");
|
||||
|
||||
let source_name = source_name.and_then(|cstr| cstr.to_str().ok());
|
||||
|
||||
let source_name = source_name.map(OPCWSTR::new);
|
||||
let raw_ep = OPCWSTR::new(raw_ep);
|
||||
let full_stage = OPCWSTR::new(full_stage);
|
||||
|
||||
let mut compile_args = arrayvec::ArrayVec::<PCWSTR, 13>::new_const();
|
||||
|
||||
if let Some(source_name) = source_name.as_ref() {
|
||||
compile_args.push(source_name.ptr())
|
||||
}
|
||||
|
||||
compile_args.extend([
|
||||
windows::core::w!("-E"),
|
||||
raw_ep.ptr(),
|
||||
windows::core::w!("-T"),
|
||||
full_stage.ptr(),
|
||||
windows::core::w!("-HV"),
|
||||
windows::core::w!("2018"), // Use HLSL 2018, Naga doesn't supported 2021 yet.
|
||||
windows::core::w!("-no-warnings"),
|
||||
Dxc::DXC_ARG_ENABLE_STRICTNESS,
|
||||
]);
|
||||
|
||||
if device
|
||||
.shared
|
||||
.private_caps
|
||||
.instance_flags
|
||||
.contains(wgt::InstanceFlags::DEBUG)
|
||||
&& !device
|
||||
.shared
|
||||
.private_caps
|
||||
.workarounds
|
||||
.avoid_shader_debug_info
|
||||
{
|
||||
compile_args.push(Dxc::DXC_ARG_DEBUG);
|
||||
compile_args.push(Dxc::DXC_ARG_SKIP_OPTIMIZATIONS);
|
||||
}
|
||||
|
||||
if device
|
||||
.features
|
||||
.intersects(wgt::Features::SHADER_F16 | wgt::Features::SHADER_I16)
|
||||
{
|
||||
compile_args.push(windows::core::w!("-enable-16bit-types"));
|
||||
}
|
||||
|
||||
let buffer = Dxc::DxcBuffer {
|
||||
Ptr: source.as_ptr().cast(),
|
||||
Size: source.len(),
|
||||
Encoding: Dxc::DXC_CP_UTF8.0,
|
||||
};
|
||||
|
||||
let compile_res: Dxc::IDxcResult =
|
||||
unsafe { compiler.Compile(&buffer, Some(&compile_args), None) }
|
||||
.into_device_result("Compile")?;
|
||||
|
||||
drop(compile_args);
|
||||
drop(source_name);
|
||||
drop(raw_ep);
|
||||
drop(full_stage);
|
||||
|
||||
let err_blob = get_output::<Dxc::IDxcBlobUtf8>(&compile_res, Dxc::DXC_OUT_ERRORS)?;
|
||||
|
||||
let len = unsafe { err_blob.GetStringLength() };
|
||||
if len != 0 {
|
||||
let err = as_err_str(&err_blob)?;
|
||||
return Err(crate::PipelineError::Linkage(
|
||||
stage_bit,
|
||||
format!("DXC compile error: {err}"),
|
||||
));
|
||||
}
|
||||
|
||||
let blob = get_output::<Dxc::IDxcBlob>(&compile_res, Dxc::DXC_OUT_OBJECT)?;
|
||||
|
||||
Ok(crate::dx12::CompiledShader::Dxc(blob))
|
||||
}
|
||||
+603
@@ -0,0 +1,603 @@
|
||||
use alloc::sync::Arc;
|
||||
|
||||
use gpu_allocator::{d3d12::AllocationCreateDesc, MemoryLocation};
|
||||
use parking_lot::Mutex;
|
||||
use windows::Win32::Graphics::{Direct3D12, Dxgi};
|
||||
|
||||
use crate::{
|
||||
auxil::dxgi::{name::ObjectExt as _, result::HResult as _},
|
||||
dx12::conv,
|
||||
AllocationSizes,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum AllocationType {
|
||||
Buffer,
|
||||
Texture,
|
||||
AccelerationStructure,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum AllocationInner {
|
||||
/// This resource is suballocated from a heap.
|
||||
Placed {
|
||||
inner: gpu_allocator::d3d12::Allocation,
|
||||
},
|
||||
/// This resource is a committed resource and does not belong to a
|
||||
/// suballocated heap. We store an approximate size, so we can manage our counters
|
||||
/// correctly.
|
||||
///
|
||||
/// This is only used for Intel Xe drivers, which have a bug that
|
||||
/// prevents suballocation from working correctly.
|
||||
Committed { size: u64 },
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Allocation {
|
||||
inner: AllocationInner,
|
||||
ty: AllocationType,
|
||||
}
|
||||
|
||||
impl Allocation {
|
||||
pub fn placed(inner: gpu_allocator::d3d12::Allocation, ty: AllocationType) -> Self {
|
||||
Self {
|
||||
inner: AllocationInner::Placed { inner },
|
||||
ty,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn none(ty: AllocationType, size: u64) -> Self {
|
||||
Self {
|
||||
inner: AllocationInner::Committed { size },
|
||||
ty,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn size(&self) -> u64 {
|
||||
match self.inner {
|
||||
AllocationInner::Placed { ref inner } => inner.size(),
|
||||
AllocationInner::Committed { size } => size,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Allocator {
|
||||
inner: Arc<Mutex<gpu_allocator::d3d12::Allocator>>,
|
||||
device_memblock_size: u64,
|
||||
host_memblock_size: u64,
|
||||
pub memory_budget_thresholds: wgt::MemoryBudgetThresholds,
|
||||
}
|
||||
|
||||
impl Allocator {
|
||||
pub(crate) fn new(
|
||||
raw: &Direct3D12::ID3D12Device,
|
||||
memory_hints: &wgt::MemoryHints,
|
||||
memory_budget_thresholds: wgt::MemoryBudgetThresholds,
|
||||
) -> Result<Self, crate::DeviceError> {
|
||||
let allocation_sizes = AllocationSizes::from_memory_hints(memory_hints);
|
||||
let device_memblock_size = allocation_sizes.min_device_memblock_size;
|
||||
let host_memblock_size = allocation_sizes.min_host_memblock_size;
|
||||
|
||||
let allocator_desc = gpu_allocator::d3d12::AllocatorCreateDesc {
|
||||
device: gpu_allocator::d3d12::ID3D12DeviceVersion::Device(raw.clone()),
|
||||
debug_settings: Default::default(),
|
||||
allocation_sizes: allocation_sizes.into(),
|
||||
};
|
||||
|
||||
let allocator = gpu_allocator::d3d12::Allocator::new(&allocator_desc).inspect_err(|e| {
|
||||
log::error!("Failed to create d3d12 allocator, error: {e}");
|
||||
})?;
|
||||
|
||||
Ok(Self {
|
||||
inner: Arc::new(Mutex::new(allocator)),
|
||||
device_memblock_size,
|
||||
host_memblock_size,
|
||||
memory_budget_thresholds,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn generate_report(&self) -> wgt::AllocatorReport {
|
||||
let mut upstream = self.inner.lock().generate_report();
|
||||
|
||||
let allocations = upstream
|
||||
.allocations
|
||||
.iter_mut()
|
||||
.map(|alloc| wgt::AllocationReport {
|
||||
name: core::mem::take(&mut alloc.name),
|
||||
offset: alloc.offset,
|
||||
size: alloc.size,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let blocks = upstream
|
||||
.blocks
|
||||
.iter()
|
||||
.map(|block| wgt::MemoryBlockReport {
|
||||
size: block.size,
|
||||
allocations: block.allocations.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
wgt::AllocatorReport {
|
||||
allocations,
|
||||
blocks,
|
||||
total_allocated_bytes: upstream.total_allocated_bytes,
|
||||
total_reserved_bytes: upstream.total_capacity_bytes,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// To allow us to construct buffers from both a `Device` and `CommandEncoder`
|
||||
/// without needing each function to take a million arguments, we create a
|
||||
/// borrowed context struct that contains the relevant members.
|
||||
pub(crate) struct DeviceAllocationContext<'a> {
|
||||
pub(crate) raw: &'a Direct3D12::ID3D12Device,
|
||||
pub(crate) shared: &'a super::DeviceShared,
|
||||
pub(crate) mem_allocator: &'a Allocator,
|
||||
pub(crate) counters: &'a wgt::HalCounters,
|
||||
}
|
||||
|
||||
impl<'a> From<&'a super::Device> for DeviceAllocationContext<'a> {
|
||||
fn from(device: &'a super::Device) -> Self {
|
||||
Self {
|
||||
raw: &device.raw,
|
||||
shared: &device.shared,
|
||||
mem_allocator: &device.mem_allocator,
|
||||
counters: &device.counters,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a super::CommandEncoder> for DeviceAllocationContext<'a> {
|
||||
fn from(encoder: &'a super::CommandEncoder) -> Self {
|
||||
Self {
|
||||
raw: &encoder.device,
|
||||
shared: &encoder.shared,
|
||||
mem_allocator: &encoder.mem_allocator,
|
||||
counters: &encoder.counters,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> DeviceAllocationContext<'a> {
|
||||
///////////////////////
|
||||
// Resource Creation //
|
||||
///////////////////////
|
||||
|
||||
pub(crate) fn create_buffer(
|
||||
&self,
|
||||
desc: &crate::BufferDescriptor,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let is_cpu_read = desc.usage.contains(wgt::BufferUses::MAP_READ);
|
||||
let is_cpu_write = desc.usage.contains(wgt::BufferUses::MAP_WRITE);
|
||||
|
||||
let location = match (is_cpu_read, is_cpu_write) {
|
||||
(true, true) => MemoryLocation::CpuToGpu,
|
||||
(true, false) => MemoryLocation::GpuToCpu,
|
||||
(false, true) => MemoryLocation::CpuToGpu,
|
||||
(false, false) => MemoryLocation::GpuOnly,
|
||||
};
|
||||
|
||||
let raw_desc = conv::map_buffer_descriptor(desc);
|
||||
let allocation_info =
|
||||
self.error_if_would_oom_on_resource_allocation(&raw_desc, location)?;
|
||||
|
||||
let (resource, allocation) = if self.shared.private_caps.suballocation_supported {
|
||||
self.create_placed_buffer(desc, raw_desc, allocation_info, location)?
|
||||
} else {
|
||||
self.create_committed_buffer(raw_desc, location)?
|
||||
};
|
||||
|
||||
if let Some(label) = desc.label {
|
||||
resource.set_name(label)?;
|
||||
}
|
||||
|
||||
self.counters.buffer_memory.add(allocation.size() as isize);
|
||||
|
||||
Ok((resource, allocation))
|
||||
}
|
||||
|
||||
pub(crate) fn create_texture(
|
||||
&self,
|
||||
desc: &crate::TextureDescriptor,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let location = MemoryLocation::GpuOnly;
|
||||
let allocation_info =
|
||||
self.error_if_would_oom_on_resource_allocation(&raw_desc, location)?;
|
||||
|
||||
let (resource, allocation) = if self.shared.private_caps.suballocation_supported {
|
||||
self.create_placed_texture(desc, raw_desc, allocation_info, location)?
|
||||
} else {
|
||||
self.create_committed_texture(desc, raw_desc)?
|
||||
};
|
||||
|
||||
if let Some(label) = desc.label {
|
||||
resource.set_name(label)?;
|
||||
}
|
||||
|
||||
self.counters.texture_memory.add(allocation.size() as isize);
|
||||
|
||||
Ok((resource, allocation))
|
||||
}
|
||||
|
||||
pub(crate) fn create_acceleration_structure(
|
||||
&self,
|
||||
desc: &crate::AccelerationStructureDescriptor,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let location = MemoryLocation::GpuOnly;
|
||||
let allocation_info =
|
||||
self.error_if_would_oom_on_resource_allocation(&raw_desc, location)?;
|
||||
|
||||
let (resource, allocation) = if self.shared.private_caps.suballocation_supported {
|
||||
self.create_placed_acceleration_structure(desc, raw_desc, allocation_info, location)?
|
||||
} else {
|
||||
self.create_committed_acceleration_structure(desc, raw_desc)?
|
||||
};
|
||||
|
||||
if let Some(label) = desc.label {
|
||||
resource.set_name(label)?;
|
||||
}
|
||||
|
||||
self.counters
|
||||
.acceleration_structure_memory
|
||||
.add(allocation.size() as isize);
|
||||
|
||||
Ok((resource, allocation))
|
||||
}
|
||||
|
||||
//////////////////////////
|
||||
// Resource Destruction //
|
||||
//////////////////////////
|
||||
|
||||
pub(crate) fn free_resource(
|
||||
&self,
|
||||
resource: Direct3D12::ID3D12Resource,
|
||||
allocation: Allocation,
|
||||
) {
|
||||
// Make sure the resource is released before we free the allocation.
|
||||
drop(resource);
|
||||
|
||||
let counter = match allocation.ty {
|
||||
AllocationType::Buffer => &self.counters.buffer_memory,
|
||||
AllocationType::Texture => &self.counters.texture_memory,
|
||||
AllocationType::AccelerationStructure => &self.counters.acceleration_structure_memory,
|
||||
};
|
||||
counter.sub(allocation.size() as isize);
|
||||
|
||||
if let AllocationInner::Placed { inner } = allocation.inner {
|
||||
match self.mem_allocator.inner.lock().free(inner) {
|
||||
Ok(_) => (),
|
||||
// TODO: Don't panic here
|
||||
Err(e) => panic!("Failed to destroy dx12 {:?}, {e}", allocation.ty),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////
|
||||
// Placed Resource Creation ///
|
||||
///////////////////////////////
|
||||
|
||||
fn create_placed_buffer(
|
||||
&self,
|
||||
desc: &crate::BufferDescriptor<'_>,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
allocation_info: Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO,
|
||||
location: MemoryLocation,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let name = desc.label.unwrap_or("Unlabeled buffer");
|
||||
|
||||
let mut allocator = self.mem_allocator.inner.lock();
|
||||
|
||||
let allocation_desc = AllocationCreateDesc {
|
||||
name,
|
||||
location,
|
||||
size: allocation_info.SizeInBytes,
|
||||
alignment: allocation_info.Alignment,
|
||||
resource_category: gpu_allocator::d3d12::ResourceCategory::from(&raw_desc),
|
||||
};
|
||||
|
||||
let allocation = allocator.allocate(&allocation_desc)?;
|
||||
let mut resource = None;
|
||||
unsafe {
|
||||
self.raw.CreatePlacedResource(
|
||||
allocation.heap(),
|
||||
allocation.offset(),
|
||||
&raw_desc,
|
||||
Direct3D12::D3D12_RESOURCE_STATE_COMMON,
|
||||
None,
|
||||
&mut resource,
|
||||
)
|
||||
}
|
||||
.into_device_result("Placed buffer creation")?;
|
||||
|
||||
let resource = resource.ok_or(crate::DeviceError::Unexpected)?;
|
||||
let wrapped_allocation = Allocation::placed(allocation, AllocationType::Buffer);
|
||||
|
||||
Ok((resource, wrapped_allocation))
|
||||
}
|
||||
|
||||
fn create_placed_texture(
|
||||
&self,
|
||||
desc: &crate::TextureDescriptor<'_>,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
allocation_info: Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO,
|
||||
location: MemoryLocation,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let name = desc.label.unwrap_or("Unlabeled texture");
|
||||
|
||||
let mut allocator = self.mem_allocator.inner.lock();
|
||||
|
||||
let allocation_desc = AllocationCreateDesc {
|
||||
name,
|
||||
location,
|
||||
size: allocation_info.SizeInBytes,
|
||||
alignment: allocation_info.Alignment,
|
||||
resource_category: gpu_allocator::d3d12::ResourceCategory::from(&raw_desc),
|
||||
};
|
||||
|
||||
let allocation = allocator.allocate(&allocation_desc)?;
|
||||
let mut resource = None;
|
||||
unsafe {
|
||||
self.raw.CreatePlacedResource(
|
||||
allocation.heap(),
|
||||
allocation.offset(),
|
||||
&raw_desc,
|
||||
Direct3D12::D3D12_RESOURCE_STATE_COMMON,
|
||||
None, // clear value
|
||||
&mut resource,
|
||||
)
|
||||
}
|
||||
.into_device_result("Placed texture creation")?;
|
||||
|
||||
let resource = resource.ok_or(crate::DeviceError::Unexpected)?;
|
||||
let wrapped_allocation = Allocation::placed(allocation, AllocationType::Texture);
|
||||
|
||||
Ok((resource, wrapped_allocation))
|
||||
}
|
||||
|
||||
fn create_placed_acceleration_structure(
|
||||
&self,
|
||||
desc: &crate::AccelerationStructureDescriptor<'_>,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
allocation_info: Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO,
|
||||
location: MemoryLocation,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let name = desc.label.unwrap_or("Unlabeled acceleration structure");
|
||||
|
||||
let mut allocator = self.mem_allocator.inner.lock();
|
||||
|
||||
let allocation_desc = AllocationCreateDesc {
|
||||
name,
|
||||
location,
|
||||
size: allocation_info.SizeInBytes,
|
||||
alignment: allocation_info.Alignment,
|
||||
resource_category: gpu_allocator::d3d12::ResourceCategory::from(&raw_desc),
|
||||
};
|
||||
|
||||
let allocation = allocator.allocate(&allocation_desc)?;
|
||||
let mut resource = None;
|
||||
unsafe {
|
||||
self.raw.CreatePlacedResource(
|
||||
allocation.heap(),
|
||||
allocation.offset(),
|
||||
&raw_desc,
|
||||
Direct3D12::D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE,
|
||||
None,
|
||||
&mut resource,
|
||||
)
|
||||
}
|
||||
.into_device_result("Placed acceleration structure creation")?;
|
||||
|
||||
let resource = resource.ok_or(crate::DeviceError::Unexpected)?;
|
||||
let wrapped_allocation =
|
||||
Allocation::placed(allocation, AllocationType::AccelerationStructure);
|
||||
|
||||
Ok((resource, wrapped_allocation))
|
||||
}
|
||||
|
||||
/////////////////////////////////
|
||||
// Committed Resource Creation //
|
||||
/////////////////////////////////
|
||||
|
||||
fn create_committed_buffer(
|
||||
&self,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
location: MemoryLocation,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let is_uma = matches!(
|
||||
self.shared.private_caps.memory_architecture,
|
||||
crate::dx12::MemoryArchitecture::Unified { .. }
|
||||
);
|
||||
|
||||
let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES {
|
||||
Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM,
|
||||
CPUPageProperty: match location {
|
||||
MemoryLocation::GpuOnly => Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE,
|
||||
MemoryLocation::CpuToGpu => Direct3D12::D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE,
|
||||
MemoryLocation::GpuToCpu => Direct3D12::D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
|
||||
_ => unreachable!(),
|
||||
},
|
||||
MemoryPoolPreference: match (is_uma, location) {
|
||||
// On dedicated GPUs, we only use L1 for GPU-only allocations.
|
||||
(false, MemoryLocation::GpuOnly) => Direct3D12::D3D12_MEMORY_POOL_L1,
|
||||
(_, _) => Direct3D12::D3D12_MEMORY_POOL_L0,
|
||||
},
|
||||
CreationNodeMask: 0,
|
||||
VisibleNodeMask: 0,
|
||||
};
|
||||
|
||||
let mut resource = None;
|
||||
|
||||
unsafe {
|
||||
self.raw.CreateCommittedResource(
|
||||
&heap_properties,
|
||||
if self.shared.private_caps.heap_create_not_zeroed {
|
||||
Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED
|
||||
} else {
|
||||
Direct3D12::D3D12_HEAP_FLAG_NONE
|
||||
},
|
||||
&raw_desc,
|
||||
Direct3D12::D3D12_RESOURCE_STATE_COMMON,
|
||||
None,
|
||||
&mut resource,
|
||||
)
|
||||
}
|
||||
.into_device_result("Committed buffer creation")?;
|
||||
|
||||
let resource = resource.ok_or(crate::DeviceError::Unexpected)?;
|
||||
let wrapped_allocation = Allocation::none(AllocationType::Buffer, raw_desc.Width);
|
||||
|
||||
Ok((resource, wrapped_allocation))
|
||||
}
|
||||
|
||||
fn create_committed_texture(
|
||||
&self,
|
||||
desc: &crate::TextureDescriptor,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES {
|
||||
Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM,
|
||||
CPUPageProperty: Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE,
|
||||
MemoryPoolPreference: match self.shared.private_caps.memory_architecture {
|
||||
crate::dx12::MemoryArchitecture::NonUnified => Direct3D12::D3D12_MEMORY_POOL_L1,
|
||||
crate::dx12::MemoryArchitecture::Unified { .. } => Direct3D12::D3D12_MEMORY_POOL_L0,
|
||||
},
|
||||
CreationNodeMask: 0,
|
||||
VisibleNodeMask: 0,
|
||||
};
|
||||
|
||||
let mut resource = None;
|
||||
|
||||
unsafe {
|
||||
self.raw.CreateCommittedResource(
|
||||
&heap_properties,
|
||||
if self.shared.private_caps.heap_create_not_zeroed {
|
||||
Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED
|
||||
} else {
|
||||
Direct3D12::D3D12_HEAP_FLAG_NONE
|
||||
},
|
||||
&raw_desc,
|
||||
Direct3D12::D3D12_RESOURCE_STATE_COMMON,
|
||||
None, // clear value
|
||||
&mut resource,
|
||||
)
|
||||
}
|
||||
.into_device_result("Committed texture creation")?;
|
||||
|
||||
let resource = resource.ok_or(crate::DeviceError::Unexpected)?;
|
||||
let wrapped_allocation = Allocation::none(
|
||||
AllocationType::Texture,
|
||||
desc.format.theoretical_memory_footprint(desc.size),
|
||||
);
|
||||
|
||||
Ok((resource, wrapped_allocation))
|
||||
}
|
||||
|
||||
fn create_committed_acceleration_structure(
|
||||
&self,
|
||||
desc: &crate::AccelerationStructureDescriptor,
|
||||
raw_desc: Direct3D12::D3D12_RESOURCE_DESC,
|
||||
) -> Result<(Direct3D12::ID3D12Resource, Allocation), crate::DeviceError> {
|
||||
let heap_properties = Direct3D12::D3D12_HEAP_PROPERTIES {
|
||||
Type: Direct3D12::D3D12_HEAP_TYPE_CUSTOM,
|
||||
CPUPageProperty: Direct3D12::D3D12_CPU_PAGE_PROPERTY_NOT_AVAILABLE,
|
||||
MemoryPoolPreference: match self.shared.private_caps.memory_architecture {
|
||||
crate::dx12::MemoryArchitecture::NonUnified => Direct3D12::D3D12_MEMORY_POOL_L1,
|
||||
crate::dx12::MemoryArchitecture::Unified { .. } => Direct3D12::D3D12_MEMORY_POOL_L0,
|
||||
},
|
||||
CreationNodeMask: 0,
|
||||
VisibleNodeMask: 0,
|
||||
};
|
||||
|
||||
let mut resource = None;
|
||||
|
||||
unsafe {
|
||||
self.raw.CreateCommittedResource(
|
||||
&heap_properties,
|
||||
if self.shared.private_caps.heap_create_not_zeroed {
|
||||
Direct3D12::D3D12_HEAP_FLAG_CREATE_NOT_ZEROED
|
||||
} else {
|
||||
Direct3D12::D3D12_HEAP_FLAG_NONE
|
||||
},
|
||||
&raw_desc,
|
||||
Direct3D12::D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE,
|
||||
None,
|
||||
&mut resource,
|
||||
)
|
||||
}
|
||||
.into_device_result("Committed acceleration structure creation")?;
|
||||
|
||||
let resource = resource.ok_or(crate::DeviceError::Unexpected)?;
|
||||
let wrapped_allocation = Allocation::none(AllocationType::AccelerationStructure, desc.size);
|
||||
|
||||
Ok((resource, wrapped_allocation))
|
||||
}
|
||||
|
||||
fn error_if_would_oom_on_resource_allocation(
|
||||
&self,
|
||||
desc: &Direct3D12::D3D12_RESOURCE_DESC,
|
||||
location: MemoryLocation,
|
||||
) -> Result<Direct3D12::D3D12_RESOURCE_ALLOCATION_INFO, crate::DeviceError> {
|
||||
let allocation_info = unsafe {
|
||||
self.raw
|
||||
.GetResourceAllocationInfo(0, core::slice::from_ref(desc))
|
||||
};
|
||||
|
||||
// Some versions of WARP return SizeInBytes == 0 for very large
|
||||
// allocations. Proceeding to attempt to allocate a zero-sized resource
|
||||
// will result in a device lost error, so it seems preferable to return
|
||||
// an out of memory error now.
|
||||
if allocation_info.SizeInBytes == 0 {
|
||||
return Err(crate::DeviceError::OutOfMemory);
|
||||
}
|
||||
|
||||
let Some(threshold) = self
|
||||
.mem_allocator
|
||||
.memory_budget_thresholds
|
||||
.for_resource_creation
|
||||
else {
|
||||
return Ok(allocation_info);
|
||||
};
|
||||
|
||||
let memory_segment_group = match location {
|
||||
MemoryLocation::Unknown => unreachable!(),
|
||||
MemoryLocation::GpuOnly => Dxgi::DXGI_MEMORY_SEGMENT_GROUP_LOCAL,
|
||||
MemoryLocation::CpuToGpu | MemoryLocation::GpuToCpu => {
|
||||
match self.shared.private_caps.memory_architecture {
|
||||
super::MemoryArchitecture::Unified { .. } => {
|
||||
Dxgi::DXGI_MEMORY_SEGMENT_GROUP_LOCAL
|
||||
}
|
||||
super::MemoryArchitecture::NonUnified => {
|
||||
Dxgi::DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let info = self
|
||||
.shared
|
||||
.adapter
|
||||
.query_video_memory_info(memory_segment_group)?;
|
||||
|
||||
let memblock_size = match location {
|
||||
MemoryLocation::Unknown => unreachable!(),
|
||||
MemoryLocation::GpuOnly => self.mem_allocator.device_memblock_size,
|
||||
MemoryLocation::CpuToGpu | MemoryLocation::GpuToCpu => {
|
||||
self.mem_allocator.host_memblock_size
|
||||
}
|
||||
};
|
||||
|
||||
if info
|
||||
.CurrentUsage
|
||||
.checked_add(allocation_info.SizeInBytes.max(memblock_size))
|
||||
.is_none_or(|usage| usage >= info.Budget / 100 * threshold as u64)
|
||||
{
|
||||
return Err(crate::DeviceError::OutOfMemory);
|
||||
}
|
||||
|
||||
Ok(allocation_info)
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
#![allow(non_camel_case_types)]
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
use windows::Win32::Graphics::Dxgi;
|
||||
|
||||
windows_core::imp::define_interface!(
|
||||
ISwapChainPanelNative,
|
||||
ISwapChainPanelNative_Vtbl,
|
||||
0x63aad0b8_7c24_40ff_85a8_640d944cc325
|
||||
);
|
||||
impl core::ops::Deref for ISwapChainPanelNative {
|
||||
type Target = windows_core::IUnknown;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
unsafe { core::mem::transmute(self) }
|
||||
}
|
||||
}
|
||||
windows_core::imp::interface_hierarchy!(ISwapChainPanelNative, windows_core::IUnknown);
|
||||
impl ISwapChainPanelNative {
|
||||
pub unsafe fn SetSwapChain<P0>(&self, swap_chain: P0) -> windows_core::Result<()>
|
||||
where
|
||||
P0: windows_core::Param<Dxgi::IDXGISwapChain1>,
|
||||
{
|
||||
unsafe {
|
||||
(windows_core::Interface::vtable(self).SetSwapChain)(
|
||||
windows_core::Interface::as_raw(self),
|
||||
swap_chain.param().abi(),
|
||||
)
|
||||
}
|
||||
.ok()
|
||||
}
|
||||
}
|
||||
#[repr(C)]
|
||||
pub struct ISwapChainPanelNative_Vtbl {
|
||||
pub base__: windows_core::IUnknown_Vtbl,
|
||||
pub SetSwapChain: unsafe extern "system" fn(
|
||||
swap_chain_panel_native: *mut core::ffi::c_void,
|
||||
swap_chain: *mut core::ffi::c_void,
|
||||
) -> windows_core::HRESULT,
|
||||
}
|
||||
Vendored
+370
@@ -0,0 +1,370 @@
|
||||
use windows::Win32::Graphics::{Direct3D12, Dxgi};
|
||||
|
||||
use crate::auxil;
|
||||
|
||||
pub(super) struct ViewDescriptor {
|
||||
dimension: wgt::TextureViewDimension,
|
||||
pub aspects: crate::FormatAspects,
|
||||
pub rtv_dsv_format: Dxgi::Common::DXGI_FORMAT,
|
||||
srv_uav_format: Option<Dxgi::Common::DXGI_FORMAT>,
|
||||
multisampled: bool,
|
||||
array_layer_base: u32,
|
||||
array_layer_count: u32,
|
||||
mip_level_base: u32,
|
||||
mip_level_count: u32,
|
||||
plane_slice_override: Option<u32>,
|
||||
}
|
||||
|
||||
impl crate::TextureViewDescriptor<'_> {
|
||||
pub(super) fn to_internal(&self, texture: &super::Texture) -> ViewDescriptor {
|
||||
let aspects = crate::FormatAspects::new(texture.format, self.range.aspect);
|
||||
|
||||
ViewDescriptor {
|
||||
dimension: self.dimension,
|
||||
aspects,
|
||||
rtv_dsv_format: auxil::dxgi::conv::map_texture_format(self.format),
|
||||
srv_uav_format: auxil::dxgi::conv::map_texture_format_for_srv_uav(self.format, aspects),
|
||||
multisampled: texture.sample_count > 1,
|
||||
mip_level_base: self.range.base_mip_level,
|
||||
mip_level_count: self.range.mip_level_count.unwrap_or(!0),
|
||||
array_layer_base: self.range.base_array_layer,
|
||||
array_layer_count: self.range.array_layer_count.unwrap_or(!0),
|
||||
plane_slice_override: texture.plane_slice_override(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn aspects_to_plane(aspects: crate::FormatAspects) -> u32 {
|
||||
match aspects {
|
||||
crate::FormatAspects::STENCIL => 1,
|
||||
crate::FormatAspects::PLANE_1 => 1,
|
||||
crate::FormatAspects::PLANE_2 => 2,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
impl ViewDescriptor {
|
||||
pub(super) fn plane_slice(&self) -> u32 {
|
||||
self.plane_slice_override
|
||||
.unwrap_or_else(|| aspects_to_plane(self.aspects))
|
||||
}
|
||||
}
|
||||
|
||||
/// Shader component mapping for stencil views
|
||||
///
|
||||
/// Stencil views use `DXGI_FORMAT_X24_TYPELESS_G8_UINT` or
|
||||
/// `DXGI_FORMAT_X32_TYPELESS_G8X24_UINT`, which have the stencil value in
|
||||
/// the green component. WebGPU specifies that the stencil value be in the
|
||||
/// red component. It also specifies that the remaining components _should_
|
||||
/// be (0, 0, 1), but may have an unspecified value.
|
||||
const STENCIL_COMPONENT_MAPPING: Direct3D12::D3D12_SHADER_COMPONENT_MAPPING =
|
||||
super::conv::make_shader_component_mapping(
|
||||
Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_1,
|
||||
Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0,
|
||||
Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0,
|
||||
Direct3D12::D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1,
|
||||
);
|
||||
|
||||
impl ViewDescriptor {
|
||||
pub(crate) unsafe fn to_srv(&self) -> Option<Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC> {
|
||||
let swizzle = if self.aspects == crate::FormatAspects::STENCIL {
|
||||
STENCIL_COMPONENT_MAPPING.0 as u32
|
||||
} else {
|
||||
Direct3D12::D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING
|
||||
};
|
||||
|
||||
let mut desc = Direct3D12::D3D12_SHADER_RESOURCE_VIEW_DESC {
|
||||
Format: self.srv_uav_format?,
|
||||
ViewDimension: Direct3D12::D3D12_SRV_DIMENSION_UNKNOWN,
|
||||
Shader4ComponentMapping: swizzle,
|
||||
Anonymous: Default::default(),
|
||||
};
|
||||
|
||||
match self.dimension {
|
||||
wgt::TextureViewDimension::D1 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE1D;
|
||||
desc.Anonymous.Texture1D = Direct3D12::D3D12_TEX1D_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
/*
|
||||
wgt::TextureViewDimension::D1Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE1DARRAY;
|
||||
desc.Anonymous.Texture1DArray = Direct3D12::D3D12_TEX1D_ARRAY_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
*/
|
||||
wgt::TextureViewDimension::D2 if self.multisampled && self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE2DMS;
|
||||
desc.Anonymous.Texture2DMS = Direct3D12::D3D12_TEX2DMS_SRV {
|
||||
UnusedField_NothingToDefine: 0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE2D;
|
||||
desc.Anonymous.Texture2D = Direct3D12::D3D12_TEX2D_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
PlaneSlice: self.plane_slice(),
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array
|
||||
if self.multisampled =>
|
||||
{
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY;
|
||||
desc.Anonymous.Texture2DMSArray = Direct3D12::D3D12_TEX2DMS_ARRAY_SRV {
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE2DARRAY;
|
||||
desc.Anonymous.Texture2DArray = Direct3D12::D3D12_TEX2D_ARRAY_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
PlaneSlice: self.plane_slice(),
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D3 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURE3D;
|
||||
desc.Anonymous.Texture3D = Direct3D12::D3D12_TEX3D_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::Cube if self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURECUBE;
|
||||
desc.Anonymous.TextureCube = Direct3D12::D3D12_TEXCUBE_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::Cube | wgt::TextureViewDimension::CubeArray => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_SRV_DIMENSION_TEXTURECUBEARRAY;
|
||||
desc.Anonymous.TextureCubeArray = Direct3D12::D3D12_TEXCUBE_ARRAY_SRV {
|
||||
MostDetailedMip: self.mip_level_base,
|
||||
MipLevels: self.mip_level_count,
|
||||
First2DArrayFace: self.array_layer_base,
|
||||
NumCubes: if self.array_layer_count == !0 {
|
||||
!0
|
||||
} else {
|
||||
self.array_layer_count / 6
|
||||
},
|
||||
ResourceMinLODClamp: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(desc)
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn to_uav(&self) -> Option<Direct3D12::D3D12_UNORDERED_ACCESS_VIEW_DESC> {
|
||||
let mut desc = Direct3D12::D3D12_UNORDERED_ACCESS_VIEW_DESC {
|
||||
Format: self.srv_uav_format?,
|
||||
ViewDimension: Direct3D12::D3D12_UAV_DIMENSION_UNKNOWN,
|
||||
Anonymous: Default::default(),
|
||||
};
|
||||
|
||||
match self.dimension {
|
||||
wgt::TextureViewDimension::D1 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE1D;
|
||||
desc.Anonymous.Texture1D = Direct3D12::D3D12_TEX1D_UAV {
|
||||
MipSlice: self.mip_level_base,
|
||||
}
|
||||
}
|
||||
/*
|
||||
wgt::TextureViewDimension::D1Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE1DARRAY;
|
||||
desc.Anonymous.Texture1DArray = Direct3D12::D3D12_TEX1D_ARRAY_UAV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize,
|
||||
}
|
||||
}*/
|
||||
wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE2D;
|
||||
desc.Anonymous.Texture2D = Direct3D12::D3D12_TEX2D_UAV {
|
||||
MipSlice: self.mip_level_base,
|
||||
PlaneSlice: self.plane_slice(),
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
|
||||
desc.Anonymous.Texture2DArray = Direct3D12::D3D12_TEX2D_ARRAY_UAV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
PlaneSlice: self.plane_slice(),
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D3 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_UAV_DIMENSION_TEXTURE3D;
|
||||
desc.Anonymous.Texture3D = Direct3D12::D3D12_TEX3D_UAV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstWSlice: 0,
|
||||
WSize: u32::MAX,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::Cube | wgt::TextureViewDimension::CubeArray => {
|
||||
panic!("Unable to view texture as cube UAV")
|
||||
}
|
||||
}
|
||||
|
||||
Some(desc)
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn to_rtv(&self) -> Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC {
|
||||
let mut desc = Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC {
|
||||
Format: self.rtv_dsv_format,
|
||||
ViewDimension: Direct3D12::D3D12_RTV_DIMENSION_UNKNOWN,
|
||||
Anonymous: Default::default(),
|
||||
};
|
||||
|
||||
match self.dimension {
|
||||
wgt::TextureViewDimension::D1 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE1D;
|
||||
desc.Anonymous.Texture1D = Direct3D12::D3D12_TEX1D_RTV {
|
||||
MipSlice: self.mip_level_base,
|
||||
}
|
||||
}
|
||||
/*
|
||||
wgt::TextureViewDimension::D1Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE1DARRAY;
|
||||
desc.Anonymous.Texture1DArray = Direct3D12::D3D12_TEX1D_ARRAY_RTV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize,
|
||||
}
|
||||
}*/
|
||||
wgt::TextureViewDimension::D2 if self.multisampled && self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2DMS;
|
||||
desc.Anonymous.Texture2DMS = Direct3D12::D3D12_TEX2DMS_RTV {
|
||||
UnusedField_NothingToDefine: 0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2D;
|
||||
desc.Anonymous.Texture2D = Direct3D12::D3D12_TEX2D_RTV {
|
||||
MipSlice: self.mip_level_base,
|
||||
PlaneSlice: self.plane_slice(),
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array
|
||||
if self.multisampled =>
|
||||
{
|
||||
desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY;
|
||||
desc.Anonymous.Texture2DMSArray = Direct3D12::D3D12_TEX2DMS_ARRAY_RTV {
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_RTV_DIMENSION_TEXTURE2DARRAY;
|
||||
desc.Anonymous.Texture2DArray = Direct3D12::D3D12_TEX2D_ARRAY_RTV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
PlaneSlice: self.plane_slice(),
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D3
|
||||
| wgt::TextureViewDimension::Cube
|
||||
| wgt::TextureViewDimension::CubeArray => {
|
||||
panic!("Unable to view texture as cube or 3D RTV")
|
||||
}
|
||||
}
|
||||
|
||||
desc
|
||||
}
|
||||
|
||||
pub(crate) unsafe fn to_dsv(
|
||||
&self,
|
||||
read_only: bool,
|
||||
) -> Direct3D12::D3D12_DEPTH_STENCIL_VIEW_DESC {
|
||||
let mut desc = Direct3D12::D3D12_DEPTH_STENCIL_VIEW_DESC {
|
||||
Format: self.rtv_dsv_format,
|
||||
ViewDimension: Direct3D12::D3D12_DSV_DIMENSION_UNKNOWN,
|
||||
Flags: {
|
||||
let mut flags = Direct3D12::D3D12_DSV_FLAG_NONE;
|
||||
if read_only {
|
||||
if self.aspects.contains(crate::FormatAspects::DEPTH) {
|
||||
flags |= Direct3D12::D3D12_DSV_FLAG_READ_ONLY_DEPTH;
|
||||
}
|
||||
if self.aspects.contains(crate::FormatAspects::STENCIL) {
|
||||
flags |= Direct3D12::D3D12_DSV_FLAG_READ_ONLY_STENCIL;
|
||||
}
|
||||
}
|
||||
flags
|
||||
},
|
||||
Anonymous: Default::default(),
|
||||
};
|
||||
|
||||
match self.dimension {
|
||||
wgt::TextureViewDimension::D1 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE1D;
|
||||
desc.Anonymous.Texture1D = Direct3D12::D3D12_TEX1D_DSV {
|
||||
MipSlice: self.mip_level_base,
|
||||
}
|
||||
}
|
||||
/*
|
||||
wgt::TextureViewDimension::D1Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE1DARRAY;
|
||||
desc.Anonymous.Texture1DArray = Direct3D12::D3D12_TEX1D_ARRAY_DSV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize,
|
||||
}
|
||||
}*/
|
||||
wgt::TextureViewDimension::D2 if self.multisampled && self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE2DMS;
|
||||
desc.Anonymous.Texture2DMS = Direct3D12::D3D12_TEX2DMS_DSV {
|
||||
UnusedField_NothingToDefine: 0,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 if self.array_layer_base == 0 => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE2D;
|
||||
|
||||
desc.Anonymous.Texture2D = Direct3D12::D3D12_TEX2D_DSV {
|
||||
MipSlice: self.mip_level_base,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array
|
||||
if self.multisampled =>
|
||||
{
|
||||
desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE2DMSARRAY;
|
||||
desc.Anonymous.Texture2DMSArray = Direct3D12::D3D12_TEX2DMS_ARRAY_DSV {
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D2 | wgt::TextureViewDimension::D2Array => {
|
||||
desc.ViewDimension = Direct3D12::D3D12_DSV_DIMENSION_TEXTURE2DARRAY;
|
||||
desc.Anonymous.Texture2DArray = Direct3D12::D3D12_TEX2D_ARRAY_DSV {
|
||||
MipSlice: self.mip_level_base,
|
||||
FirstArraySlice: self.array_layer_base,
|
||||
ArraySize: self.array_layer_count,
|
||||
}
|
||||
}
|
||||
wgt::TextureViewDimension::D3
|
||||
| wgt::TextureViewDimension::Cube
|
||||
| wgt::TextureViewDimension::CubeArray => {
|
||||
panic!("Unable to view texture as cube or 3D DSV")
|
||||
}
|
||||
}
|
||||
|
||||
desc
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
use alloc::boxed::Box;
|
||||
|
||||
use crate::{
|
||||
Adapter, Api, DeviceError, OpenDevice, SurfaceCapabilities, TextureFormatCapabilities,
|
||||
};
|
||||
|
||||
use super::{DynDevice, DynQueue, DynResource, DynResourceExt, DynSurface};
|
||||
|
||||
#[expect(missing_debug_implementations, reason = "dyn")]
|
||||
pub struct DynOpenDevice {
|
||||
pub device: Box<dyn DynDevice>,
|
||||
pub queue: Box<dyn DynQueue>,
|
||||
}
|
||||
|
||||
impl<A: Api> From<OpenDevice<A>> for DynOpenDevice {
|
||||
fn from(open_device: OpenDevice<A>) -> Self {
|
||||
Self {
|
||||
device: Box::new(open_device.device),
|
||||
queue: Box::new(open_device.queue),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait DynAdapter: DynResource {
|
||||
unsafe fn open(
|
||||
&self,
|
||||
features: wgt::Features,
|
||||
limits: &wgt::Limits,
|
||||
memory_hints: &wgt::MemoryHints,
|
||||
) -> Result<DynOpenDevice, DeviceError>;
|
||||
|
||||
unsafe fn texture_format_capabilities(
|
||||
&self,
|
||||
format: wgt::TextureFormat,
|
||||
) -> TextureFormatCapabilities;
|
||||
|
||||
unsafe fn surface_capabilities(&self, surface: &dyn DynSurface) -> Option<SurfaceCapabilities>;
|
||||
|
||||
unsafe fn surface_display_hdr_info(
|
||||
&self,
|
||||
surface: &dyn DynSurface,
|
||||
) -> Option<wgt::DisplayHdrInfo>;
|
||||
|
||||
unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp;
|
||||
|
||||
fn get_ordered_buffer_usages(&self) -> wgt::BufferUses;
|
||||
|
||||
fn get_ordered_texture_usages(&self) -> wgt::TextureUses;
|
||||
}
|
||||
|
||||
impl<A: Adapter + DynResource> DynAdapter for A {
|
||||
unsafe fn open(
|
||||
&self,
|
||||
features: wgt::Features,
|
||||
limits: &wgt::Limits,
|
||||
memory_hints: &wgt::MemoryHints,
|
||||
) -> Result<DynOpenDevice, DeviceError> {
|
||||
unsafe { A::open(self, features, limits, memory_hints) }.map(|open_device| DynOpenDevice {
|
||||
device: Box::new(open_device.device),
|
||||
queue: Box::new(open_device.queue),
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn texture_format_capabilities(
|
||||
&self,
|
||||
format: wgt::TextureFormat,
|
||||
) -> TextureFormatCapabilities {
|
||||
unsafe { A::texture_format_capabilities(self, format) }
|
||||
}
|
||||
|
||||
unsafe fn surface_capabilities(&self, surface: &dyn DynSurface) -> Option<SurfaceCapabilities> {
|
||||
let surface = surface.expect_downcast_ref();
|
||||
unsafe { A::surface_capabilities(self, surface) }
|
||||
}
|
||||
|
||||
unsafe fn surface_display_hdr_info(
|
||||
&self,
|
||||
surface: &dyn DynSurface,
|
||||
) -> Option<wgt::DisplayHdrInfo> {
|
||||
let surface = surface.expect_downcast_ref();
|
||||
unsafe { A::surface_display_hdr_info(self, surface) }
|
||||
}
|
||||
|
||||
unsafe fn get_presentation_timestamp(&self) -> wgt::PresentationTimestamp {
|
||||
unsafe { A::get_presentation_timestamp(self) }
|
||||
}
|
||||
|
||||
fn get_ordered_buffer_usages(&self) -> wgt::BufferUses {
|
||||
A::get_ordered_buffer_usages(self)
|
||||
}
|
||||
|
||||
fn get_ordered_texture_usages(&self) -> wgt::TextureUses {
|
||||
A::get_ordered_texture_usages(self)
|
||||
}
|
||||
}
|
||||
+823
@@ -0,0 +1,823 @@
|
||||
use alloc::{boxed::Box, vec::Vec};
|
||||
use core::ops::Range;
|
||||
|
||||
use crate::{
|
||||
AccelerationStructureBarrier, Api, Attachment, BufferBarrier, BufferBinding, BufferCopy,
|
||||
BufferTextureCopy, BuildAccelerationStructureDescriptor, ColorAttachment, CommandEncoder,
|
||||
ComputePassDescriptor, DepthStencilAttachment, DeviceError, DynRayTracingPipeline, Label,
|
||||
MemoryRange, PassTimestampWrites, RayTracingPassDescriptor, Rect, RenderPassDescriptor,
|
||||
TextureBarrier, TextureCopy,
|
||||
};
|
||||
|
||||
use super::{
|
||||
DynAccelerationStructure, DynBindGroup, DynBuffer, DynCommandBuffer, DynComputePipeline,
|
||||
DynPipelineLayout, DynQuerySet, DynRenderPipeline, DynResource, DynResourceExt as _,
|
||||
DynTexture, DynTextureView,
|
||||
};
|
||||
|
||||
pub trait DynCommandEncoder: DynResource + core::fmt::Debug {
|
||||
unsafe fn begin_encoding(&mut self, label: Label) -> Result<(), DeviceError>;
|
||||
|
||||
unsafe fn discard_encoding(&mut self);
|
||||
|
||||
unsafe fn end_encoding(&mut self) -> Result<Box<dyn DynCommandBuffer>, DeviceError>;
|
||||
|
||||
unsafe fn reset_all(&mut self, command_buffers: Vec<Box<dyn DynCommandBuffer>>);
|
||||
|
||||
unsafe fn transition_buffers(&mut self, barriers: &[BufferBarrier<'_, dyn DynBuffer>]);
|
||||
unsafe fn transition_textures(&mut self, barriers: &[TextureBarrier<'_, dyn DynTexture>]);
|
||||
|
||||
unsafe fn clear_buffer(&mut self, buffer: &dyn DynBuffer, range: MemoryRange);
|
||||
|
||||
unsafe fn copy_buffer_to_buffer(
|
||||
&mut self,
|
||||
src: &dyn DynBuffer,
|
||||
dst: &dyn DynBuffer,
|
||||
regions: &[BufferCopy],
|
||||
);
|
||||
|
||||
unsafe fn copy_texture_to_texture(
|
||||
&mut self,
|
||||
src: &dyn DynTexture,
|
||||
src_usage: wgt::TextureUses,
|
||||
dst: &dyn DynTexture,
|
||||
regions: &[TextureCopy],
|
||||
);
|
||||
|
||||
unsafe fn copy_buffer_to_texture(
|
||||
&mut self,
|
||||
src: &dyn DynBuffer,
|
||||
dst: &dyn DynTexture,
|
||||
regions: &[BufferTextureCopy],
|
||||
);
|
||||
|
||||
unsafe fn copy_texture_to_buffer(
|
||||
&mut self,
|
||||
src: &dyn DynTexture,
|
||||
src_usage: wgt::TextureUses,
|
||||
dst: &dyn DynBuffer,
|
||||
regions: &[BufferTextureCopy],
|
||||
);
|
||||
|
||||
unsafe fn set_bind_group(
|
||||
&mut self,
|
||||
layout: &dyn DynPipelineLayout,
|
||||
index: u32,
|
||||
group: &dyn DynBindGroup,
|
||||
dynamic_offsets: &[wgt::DynamicOffset],
|
||||
);
|
||||
|
||||
unsafe fn set_immediates(
|
||||
&mut self,
|
||||
layout: &dyn DynPipelineLayout,
|
||||
offset_bytes: u32,
|
||||
data: &[u32],
|
||||
);
|
||||
|
||||
unsafe fn insert_debug_marker(&mut self, label: &str);
|
||||
unsafe fn begin_debug_marker(&mut self, group_label: &str);
|
||||
unsafe fn end_debug_marker(&mut self);
|
||||
|
||||
unsafe fn begin_query(&mut self, set: &dyn DynQuerySet, index: u32);
|
||||
unsafe fn end_query(&mut self, set: &dyn DynQuerySet, index: u32);
|
||||
unsafe fn write_timestamp(&mut self, set: &dyn DynQuerySet, index: u32);
|
||||
unsafe fn reset_queries(&mut self, set: &dyn DynQuerySet, range: Range<u32>);
|
||||
unsafe fn copy_query_results(
|
||||
&mut self,
|
||||
set: &dyn DynQuerySet,
|
||||
range: Range<u32>,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
stride: wgt::BufferSize,
|
||||
);
|
||||
|
||||
unsafe fn begin_render_pass(
|
||||
&mut self,
|
||||
desc: &RenderPassDescriptor<dyn DynQuerySet, dyn DynTextureView>,
|
||||
) -> Result<(), DeviceError>;
|
||||
unsafe fn end_render_pass(&mut self);
|
||||
|
||||
unsafe fn set_render_pipeline(&mut self, pipeline: &dyn DynRenderPipeline);
|
||||
|
||||
unsafe fn set_index_buffer<'a>(
|
||||
&mut self,
|
||||
binding: BufferBinding<'a, dyn DynBuffer>,
|
||||
format: wgt::IndexFormat,
|
||||
);
|
||||
|
||||
unsafe fn set_vertex_buffer<'a>(
|
||||
&mut self,
|
||||
index: u32,
|
||||
binding: BufferBinding<'a, dyn DynBuffer>,
|
||||
);
|
||||
unsafe fn set_viewport(&mut self, rect: &Rect<f32>, depth_range: Range<f32>);
|
||||
unsafe fn set_scissor_rect(&mut self, rect: &Rect<u32>);
|
||||
unsafe fn set_stencil_reference(&mut self, value: u32);
|
||||
unsafe fn set_blend_constants(&mut self, color: &[f32; 4]);
|
||||
|
||||
unsafe fn draw(
|
||||
&mut self,
|
||||
first_vertex: u32,
|
||||
vertex_count: u32,
|
||||
first_instance: u32,
|
||||
instance_count: u32,
|
||||
);
|
||||
unsafe fn draw_indexed(
|
||||
&mut self,
|
||||
first_index: u32,
|
||||
index_count: u32,
|
||||
base_vertex: i32,
|
||||
first_instance: u32,
|
||||
instance_count: u32,
|
||||
);
|
||||
unsafe fn draw_mesh_tasks(
|
||||
&mut self,
|
||||
group_count_x: u32,
|
||||
group_count_y: u32,
|
||||
group_count_z: u32,
|
||||
);
|
||||
unsafe fn draw_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
);
|
||||
unsafe fn draw_indexed_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
);
|
||||
unsafe fn draw_mesh_tasks_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
);
|
||||
unsafe fn draw_indirect_count(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
count_buffer: &dyn DynBuffer,
|
||||
count_offset: wgt::BufferAddress,
|
||||
max_count: u32,
|
||||
);
|
||||
unsafe fn draw_indexed_indirect_count(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
count_buffer: &dyn DynBuffer,
|
||||
count_offset: wgt::BufferAddress,
|
||||
max_count: u32,
|
||||
);
|
||||
unsafe fn draw_mesh_tasks_indirect_count(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
count_buffer: &dyn DynBuffer,
|
||||
count_offset: wgt::BufferAddress,
|
||||
max_count: u32,
|
||||
);
|
||||
|
||||
unsafe fn begin_compute_pass(&mut self, desc: &ComputePassDescriptor<dyn DynQuerySet>);
|
||||
unsafe fn end_compute_pass(&mut self);
|
||||
|
||||
unsafe fn set_compute_pipeline(&mut self, pipeline: &dyn DynComputePipeline);
|
||||
|
||||
unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]);
|
||||
unsafe fn dispatch_workgroups_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
);
|
||||
|
||||
unsafe fn begin_ray_tracing_pass(&mut self, desc: &RayTracingPassDescriptor);
|
||||
unsafe fn end_ray_tracing_pass(&mut self);
|
||||
|
||||
unsafe fn trace_rays(
|
||||
&mut self,
|
||||
count: [u32; 3],
|
||||
ray_generation_group_data: crate::PipelineGroupData<dyn DynBuffer>,
|
||||
miss_group_data: crate::PipelineGroupData<dyn DynBuffer>,
|
||||
intersection_group_data: crate::PipelineGroupData<dyn DynBuffer>,
|
||||
);
|
||||
|
||||
unsafe fn set_ray_tracing_pipeline(&mut self, pipeline: &dyn DynRayTracingPipeline);
|
||||
|
||||
unsafe fn build_acceleration_structures<'a>(
|
||||
&mut self,
|
||||
descriptors: &'a [BuildAccelerationStructureDescriptor<
|
||||
'a,
|
||||
dyn DynBuffer,
|
||||
dyn DynAccelerationStructure,
|
||||
>],
|
||||
);
|
||||
unsafe fn place_acceleration_structure_barrier(
|
||||
&mut self,
|
||||
barrier: AccelerationStructureBarrier,
|
||||
);
|
||||
unsafe fn copy_acceleration_structure_to_acceleration_structure(
|
||||
&mut self,
|
||||
src: &dyn DynAccelerationStructure,
|
||||
dst: &dyn DynAccelerationStructure,
|
||||
copy: wgt::AccelerationStructureCopy,
|
||||
);
|
||||
unsafe fn read_acceleration_structure_compact_size(
|
||||
&mut self,
|
||||
acceleration_structure: &dyn DynAccelerationStructure,
|
||||
buf: &dyn DynBuffer,
|
||||
);
|
||||
unsafe fn set_acceleration_structure_dependencies(
|
||||
&self,
|
||||
command_buffers: &[Box<dyn DynCommandBuffer>],
|
||||
dependencies: &[&dyn DynAccelerationStructure],
|
||||
);
|
||||
}
|
||||
|
||||
impl<C: CommandEncoder + DynResource> DynCommandEncoder for C {
|
||||
unsafe fn begin_encoding(&mut self, label: Label) -> Result<(), DeviceError> {
|
||||
unsafe { C::begin_encoding(self, label) }
|
||||
}
|
||||
|
||||
unsafe fn discard_encoding(&mut self) {
|
||||
unsafe { C::discard_encoding(self) }
|
||||
}
|
||||
|
||||
unsafe fn end_encoding(&mut self) -> Result<Box<dyn DynCommandBuffer>, DeviceError> {
|
||||
unsafe { C::end_encoding(self) }.map(|cb| {
|
||||
let boxed_command_buffer: Box<<C::A as Api>::CommandBuffer> = Box::new(cb);
|
||||
let boxed_command_buffer: Box<dyn DynCommandBuffer> = boxed_command_buffer;
|
||||
boxed_command_buffer
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn reset_all(&mut self, command_buffers: Vec<Box<dyn DynCommandBuffer>>) {
|
||||
unsafe { C::reset_all(self, command_buffers.into_iter().map(|cb| cb.unbox())) }
|
||||
}
|
||||
|
||||
unsafe fn transition_buffers(&mut self, barriers: &[BufferBarrier<'_, dyn DynBuffer>]) {
|
||||
let barriers = barriers.iter().map(|barrier| BufferBarrier {
|
||||
buffer: barrier.buffer.expect_downcast_ref(),
|
||||
usage: barrier.usage.clone(),
|
||||
});
|
||||
unsafe { self.transition_buffers(barriers) };
|
||||
}
|
||||
|
||||
unsafe fn transition_textures(&mut self, barriers: &[TextureBarrier<'_, dyn DynTexture>]) {
|
||||
let barriers = barriers.iter().map(|barrier| TextureBarrier {
|
||||
texture: barrier.texture.expect_downcast_ref(),
|
||||
usage: barrier.usage.clone(),
|
||||
range: barrier.range,
|
||||
});
|
||||
unsafe { self.transition_textures(barriers) };
|
||||
}
|
||||
|
||||
unsafe fn clear_buffer(&mut self, buffer: &dyn DynBuffer, range: MemoryRange) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { C::clear_buffer(self, buffer, range) };
|
||||
}
|
||||
|
||||
unsafe fn copy_buffer_to_buffer(
|
||||
&mut self,
|
||||
src: &dyn DynBuffer,
|
||||
dst: &dyn DynBuffer,
|
||||
regions: &[BufferCopy],
|
||||
) {
|
||||
let src = src.expect_downcast_ref();
|
||||
let dst = dst.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::copy_buffer_to_buffer(self, src, dst, regions.iter().copied());
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn copy_texture_to_texture(
|
||||
&mut self,
|
||||
src: &dyn DynTexture,
|
||||
src_usage: wgt::TextureUses,
|
||||
dst: &dyn DynTexture,
|
||||
regions: &[TextureCopy],
|
||||
) {
|
||||
let src = src.expect_downcast_ref();
|
||||
let dst = dst.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::copy_texture_to_texture(self, src, src_usage, dst, regions.iter().cloned());
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn copy_buffer_to_texture(
|
||||
&mut self,
|
||||
src: &dyn DynBuffer,
|
||||
dst: &dyn DynTexture,
|
||||
regions: &[BufferTextureCopy],
|
||||
) {
|
||||
let src = src.expect_downcast_ref();
|
||||
let dst = dst.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::copy_buffer_to_texture(self, src, dst, regions.iter().cloned());
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn copy_texture_to_buffer(
|
||||
&mut self,
|
||||
src: &dyn DynTexture,
|
||||
src_usage: wgt::TextureUses,
|
||||
dst: &dyn DynBuffer,
|
||||
regions: &[BufferTextureCopy],
|
||||
) {
|
||||
let src = src.expect_downcast_ref();
|
||||
let dst = dst.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::copy_texture_to_buffer(self, src, src_usage, dst, regions.iter().cloned());
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_bind_group(
|
||||
&mut self,
|
||||
layout: &dyn DynPipelineLayout,
|
||||
index: u32,
|
||||
group: &dyn DynBindGroup,
|
||||
dynamic_offsets: &[wgt::DynamicOffset],
|
||||
) {
|
||||
let layout = layout.expect_downcast_ref();
|
||||
let group = group.expect_downcast_ref();
|
||||
unsafe { C::set_bind_group(self, layout, index, group, dynamic_offsets) };
|
||||
}
|
||||
|
||||
unsafe fn set_immediates(
|
||||
&mut self,
|
||||
layout: &dyn DynPipelineLayout,
|
||||
offset_bytes: u32,
|
||||
data: &[u32],
|
||||
) {
|
||||
let layout = layout.expect_downcast_ref();
|
||||
unsafe { C::set_immediates(self, layout, offset_bytes, data) };
|
||||
}
|
||||
|
||||
unsafe fn insert_debug_marker(&mut self, label: &str) {
|
||||
unsafe {
|
||||
C::insert_debug_marker(self, label);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn begin_debug_marker(&mut self, group_label: &str) {
|
||||
unsafe {
|
||||
C::begin_debug_marker(self, group_label);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn end_debug_marker(&mut self) {
|
||||
unsafe {
|
||||
C::end_debug_marker(self);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn begin_query(&mut self, set: &dyn DynQuerySet, index: u32) {
|
||||
let set = set.expect_downcast_ref();
|
||||
unsafe { C::begin_query(self, set, index) };
|
||||
}
|
||||
|
||||
unsafe fn end_query(&mut self, set: &dyn DynQuerySet, index: u32) {
|
||||
let set = set.expect_downcast_ref();
|
||||
unsafe { C::end_query(self, set, index) };
|
||||
}
|
||||
|
||||
unsafe fn write_timestamp(&mut self, set: &dyn DynQuerySet, index: u32) {
|
||||
let set = set.expect_downcast_ref();
|
||||
unsafe { C::write_timestamp(self, set, index) };
|
||||
}
|
||||
|
||||
unsafe fn reset_queries(&mut self, set: &dyn DynQuerySet, range: Range<u32>) {
|
||||
let set = set.expect_downcast_ref();
|
||||
unsafe { C::reset_queries(self, set, range) };
|
||||
}
|
||||
|
||||
unsafe fn copy_query_results(
|
||||
&mut self,
|
||||
set: &dyn DynQuerySet,
|
||||
range: Range<u32>,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
stride: wgt::BufferSize,
|
||||
) {
|
||||
let set = set.expect_downcast_ref();
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { C::copy_query_results(self, set, range, buffer, offset, stride) };
|
||||
}
|
||||
|
||||
unsafe fn begin_render_pass(
|
||||
&mut self,
|
||||
desc: &RenderPassDescriptor<dyn DynQuerySet, dyn DynTextureView>,
|
||||
) -> Result<(), DeviceError> {
|
||||
let color_attachments = desc
|
||||
.color_attachments
|
||||
.iter()
|
||||
.map(|attachment| {
|
||||
attachment
|
||||
.as_ref()
|
||||
.map(|attachment| attachment.expect_downcast())
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let desc: RenderPassDescriptor<<C::A as Api>::QuerySet, <C::A as Api>::TextureView> =
|
||||
RenderPassDescriptor {
|
||||
label: desc.label,
|
||||
extent: desc.extent,
|
||||
sample_count: desc.sample_count,
|
||||
color_attachments: &color_attachments,
|
||||
depth_stencil_attachment: desc
|
||||
.depth_stencil_attachment
|
||||
.as_ref()
|
||||
.map(|ds| ds.expect_downcast()),
|
||||
multiview_mask: desc.multiview_mask,
|
||||
timestamp_writes: desc
|
||||
.timestamp_writes
|
||||
.as_ref()
|
||||
.map(|writes| writes.expect_downcast()),
|
||||
occlusion_query_set: desc
|
||||
.occlusion_query_set
|
||||
.map(|set| set.expect_downcast_ref()),
|
||||
};
|
||||
unsafe { C::begin_render_pass(self, &desc) }
|
||||
}
|
||||
|
||||
unsafe fn end_render_pass(&mut self) {
|
||||
unsafe {
|
||||
C::end_render_pass(self);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_viewport(&mut self, rect: &Rect<f32>, depth_range: Range<f32>) {
|
||||
unsafe {
|
||||
C::set_viewport(self, rect, depth_range);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_scissor_rect(&mut self, rect: &Rect<u32>) {
|
||||
unsafe {
|
||||
C::set_scissor_rect(self, rect);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_stencil_reference(&mut self, value: u32) {
|
||||
unsafe {
|
||||
C::set_stencil_reference(self, value);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn set_blend_constants(&mut self, color: &[f32; 4]) {
|
||||
unsafe { C::set_blend_constants(self, color) };
|
||||
}
|
||||
|
||||
unsafe fn draw(
|
||||
&mut self,
|
||||
first_vertex: u32,
|
||||
vertex_count: u32,
|
||||
first_instance: u32,
|
||||
instance_count: u32,
|
||||
) {
|
||||
unsafe {
|
||||
C::draw(
|
||||
self,
|
||||
first_vertex,
|
||||
vertex_count,
|
||||
first_instance,
|
||||
instance_count,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
unsafe fn draw_indexed(
|
||||
&mut self,
|
||||
first_index: u32,
|
||||
index_count: u32,
|
||||
base_vertex: i32,
|
||||
first_instance: u32,
|
||||
instance_count: u32,
|
||||
) {
|
||||
unsafe {
|
||||
C::draw_indexed(
|
||||
self,
|
||||
first_index,
|
||||
index_count,
|
||||
base_vertex,
|
||||
first_instance,
|
||||
instance_count,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
unsafe fn draw_mesh_tasks(
|
||||
&mut self,
|
||||
group_count_x: u32,
|
||||
group_count_y: u32,
|
||||
group_count_z: u32,
|
||||
) {
|
||||
unsafe { C::draw_mesh_tasks(self, group_count_x, group_count_y, group_count_z) };
|
||||
}
|
||||
|
||||
unsafe fn draw_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { C::draw_indirect(self, buffer, offset, draw_count) };
|
||||
}
|
||||
|
||||
unsafe fn draw_indexed_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { C::draw_indexed_indirect(self, buffer, offset, draw_count) };
|
||||
}
|
||||
|
||||
unsafe fn draw_mesh_tasks_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
draw_count: u32,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { C::draw_mesh_tasks_indirect(self, buffer, offset, draw_count) };
|
||||
}
|
||||
|
||||
unsafe fn draw_indirect_count(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
count_buffer: &dyn DynBuffer,
|
||||
count_offset: wgt::BufferAddress,
|
||||
max_count: u32,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
let count_buffer = count_buffer.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::draw_indirect_count(self, buffer, offset, count_buffer, count_offset, max_count)
|
||||
};
|
||||
}
|
||||
|
||||
unsafe fn draw_indexed_indirect_count(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
count_buffer: &dyn DynBuffer,
|
||||
count_offset: wgt::BufferAddress,
|
||||
max_count: u32,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
let count_buffer = count_buffer.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::draw_indexed_indirect_count(
|
||||
self,
|
||||
buffer,
|
||||
offset,
|
||||
count_buffer,
|
||||
count_offset,
|
||||
max_count,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
unsafe fn draw_mesh_tasks_indirect_count(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
count_buffer: &dyn DynBuffer,
|
||||
count_offset: wgt::BufferAddress,
|
||||
max_count: u32,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
let count_buffer = count_buffer.expect_downcast_ref();
|
||||
unsafe {
|
||||
C::draw_mesh_tasks_indirect_count(
|
||||
self,
|
||||
buffer,
|
||||
offset,
|
||||
count_buffer,
|
||||
count_offset,
|
||||
max_count,
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
unsafe fn begin_compute_pass(&mut self, desc: &ComputePassDescriptor<dyn DynQuerySet>) {
|
||||
let desc = ComputePassDescriptor {
|
||||
label: desc.label,
|
||||
timestamp_writes: desc
|
||||
.timestamp_writes
|
||||
.as_ref()
|
||||
.map(|writes| writes.expect_downcast()),
|
||||
};
|
||||
unsafe { C::begin_compute_pass(self, &desc) };
|
||||
}
|
||||
|
||||
unsafe fn end_compute_pass(&mut self) {
|
||||
unsafe { C::end_compute_pass(self) };
|
||||
}
|
||||
|
||||
unsafe fn set_compute_pipeline(&mut self, pipeline: &dyn DynComputePipeline) {
|
||||
let pipeline = pipeline.expect_downcast_ref();
|
||||
unsafe { C::set_compute_pipeline(self, pipeline) };
|
||||
}
|
||||
|
||||
unsafe fn dispatch_workgroups(&mut self, count: [u32; 3]) {
|
||||
unsafe { C::dispatch_workgroups(self, count) };
|
||||
}
|
||||
|
||||
unsafe fn dispatch_workgroups_indirect(
|
||||
&mut self,
|
||||
buffer: &dyn DynBuffer,
|
||||
offset: wgt::BufferAddress,
|
||||
) {
|
||||
let buffer = buffer.expect_downcast_ref();
|
||||
unsafe { C::dispatch_workgroups_indirect(self, buffer, offset) };
|
||||
}
|
||||
|
||||
unsafe fn set_render_pipeline(&mut self, pipeline: &dyn DynRenderPipeline) {
|
||||
let pipeline = pipeline.expect_downcast_ref();
|
||||
unsafe { C::set_render_pipeline(self, pipeline) };
|
||||
}
|
||||
|
||||
unsafe fn set_index_buffer<'a>(
|
||||
&mut self,
|
||||
binding: BufferBinding<'a, dyn DynBuffer>,
|
||||
format: wgt::IndexFormat,
|
||||
) {
|
||||
let binding = binding.expect_downcast();
|
||||
unsafe { self.set_index_buffer(binding, format) };
|
||||
}
|
||||
|
||||
unsafe fn set_vertex_buffer<'a>(
|
||||
&mut self,
|
||||
index: u32,
|
||||
binding: BufferBinding<'a, dyn DynBuffer>,
|
||||
) {
|
||||
let binding = binding.expect_downcast();
|
||||
unsafe { self.set_vertex_buffer(index, binding) };
|
||||
}
|
||||
|
||||
unsafe fn begin_ray_tracing_pass(&mut self, desc: &RayTracingPassDescriptor) {
|
||||
let desc = RayTracingPassDescriptor { label: desc.label };
|
||||
unsafe { C::begin_ray_tracing_pass(self, &desc) };
|
||||
}
|
||||
|
||||
unsafe fn end_ray_tracing_pass(&mut self) {
|
||||
unsafe { C::end_ray_tracing_pass(self) };
|
||||
}
|
||||
|
||||
unsafe fn set_ray_tracing_pipeline(&mut self, pipeline: &dyn DynRayTracingPipeline) {
|
||||
let pipeline = pipeline.expect_downcast_ref();
|
||||
unsafe { C::set_ray_tracing_pipeline(self, pipeline) };
|
||||
}
|
||||
|
||||
unsafe fn trace_rays<'a>(
|
||||
&mut self,
|
||||
count: [u32; 3],
|
||||
ray_generation_group_data: crate::PipelineGroupData<'a, dyn DynBuffer>,
|
||||
miss_group_data: crate::PipelineGroupData<'a, dyn DynBuffer>,
|
||||
intersection_group_data: crate::PipelineGroupData<'a, dyn DynBuffer>,
|
||||
) {
|
||||
let downcast_group_data =
|
||||
|data: crate::PipelineGroupData<'a, dyn DynBuffer>| crate::PipelineGroupData {
|
||||
buffer: data.buffer.expect_downcast_ref(),
|
||||
offset: data.offset,
|
||||
stride: data.stride,
|
||||
count: data.count,
|
||||
};
|
||||
|
||||
unsafe {
|
||||
C::trace_rays(
|
||||
self,
|
||||
count,
|
||||
downcast_group_data(ray_generation_group_data),
|
||||
downcast_group_data(miss_group_data),
|
||||
downcast_group_data(intersection_group_data),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn build_acceleration_structures<'a>(
|
||||
&mut self,
|
||||
descriptors: &'a [BuildAccelerationStructureDescriptor<
|
||||
'a,
|
||||
dyn DynBuffer,
|
||||
dyn DynAccelerationStructure,
|
||||
>],
|
||||
) {
|
||||
// Need to collect entries here so we can reference them in the descriptor.
|
||||
// TODO: API should be redesigned to avoid this and other descriptor copies that happen due to the dyn api.
|
||||
let descriptor_entries = descriptors
|
||||
.iter()
|
||||
.map(|d| d.entries.expect_downcast())
|
||||
.collect::<Vec<_>>();
|
||||
let descriptors = descriptors
|
||||
.iter()
|
||||
.zip(descriptor_entries.iter())
|
||||
.map(|(d, entries)| BuildAccelerationStructureDescriptor::<
|
||||
<C::A as Api>::Buffer,
|
||||
<C::A as Api>::AccelerationStructure,
|
||||
> {
|
||||
entries,
|
||||
mode: d.mode,
|
||||
flags: d.flags,
|
||||
source_acceleration_structure: d
|
||||
.source_acceleration_structure
|
||||
.map(|a| a.expect_downcast_ref()),
|
||||
destination_acceleration_structure: d
|
||||
.destination_acceleration_structure
|
||||
.expect_downcast_ref(),
|
||||
scratch_buffer: d.scratch_buffer.expect_downcast_ref(),
|
||||
scratch_buffer_offset: d.scratch_buffer_offset,
|
||||
});
|
||||
unsafe { C::build_acceleration_structures(self, descriptors.len() as _, descriptors) };
|
||||
}
|
||||
|
||||
unsafe fn place_acceleration_structure_barrier(
|
||||
&mut self,
|
||||
barrier: AccelerationStructureBarrier,
|
||||
) {
|
||||
unsafe { C::place_acceleration_structure_barrier(self, barrier) };
|
||||
}
|
||||
|
||||
unsafe fn copy_acceleration_structure_to_acceleration_structure(
|
||||
&mut self,
|
||||
src: &dyn DynAccelerationStructure,
|
||||
dst: &dyn DynAccelerationStructure,
|
||||
copy: wgt::AccelerationStructureCopy,
|
||||
) {
|
||||
let src = src.expect_downcast_ref();
|
||||
let dst = dst.expect_downcast_ref();
|
||||
unsafe { C::copy_acceleration_structure_to_acceleration_structure(self, src, dst, copy) };
|
||||
}
|
||||
unsafe fn read_acceleration_structure_compact_size(
|
||||
&mut self,
|
||||
acceleration_structure: &dyn DynAccelerationStructure,
|
||||
buf: &dyn DynBuffer,
|
||||
) {
|
||||
let acceleration_structure = acceleration_structure.expect_downcast_ref();
|
||||
let buf = buf.expect_downcast_ref();
|
||||
unsafe { C::read_acceleration_structure_compact_size(self, acceleration_structure, buf) }
|
||||
}
|
||||
|
||||
unsafe fn set_acceleration_structure_dependencies(
|
||||
&self,
|
||||
command_buffers: &[Box<dyn DynCommandBuffer>],
|
||||
dependencies: &[&dyn DynAccelerationStructure],
|
||||
) {
|
||||
let command_buffers: Vec<&<C::A as Api>::CommandBuffer> = command_buffers
|
||||
.iter()
|
||||
.map(|command_buffer| command_buffer.expect_downcast_ref())
|
||||
.collect();
|
||||
let dependencies: Vec<&<C::A as Api>::AccelerationStructure> = dependencies
|
||||
.iter()
|
||||
.map(|dependency| dependency.expect_downcast_ref())
|
||||
.collect();
|
||||
unsafe { C::set_acceleration_structure_dependencies(&command_buffers, &dependencies) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> PassTimestampWrites<'a, dyn DynQuerySet> {
|
||||
pub fn expect_downcast<B: DynQuerySet>(&self) -> PassTimestampWrites<'a, B> {
|
||||
PassTimestampWrites {
|
||||
query_set: self.query_set.expect_downcast_ref(),
|
||||
beginning_of_pass_write_index: self.beginning_of_pass_write_index,
|
||||
end_of_pass_write_index: self.end_of_pass_write_index,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Attachment<'a, dyn DynTextureView> {
|
||||
pub fn expect_downcast<B: DynTextureView>(&self) -> Attachment<'a, B> {
|
||||
Attachment {
|
||||
view: self.view.expect_downcast_ref(),
|
||||
usage: self.usage,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ColorAttachment<'a, dyn DynTextureView> {
|
||||
pub fn expect_downcast<B: DynTextureView>(&self) -> ColorAttachment<'a, B> {
|
||||
ColorAttachment {
|
||||
target: self.target.expect_downcast(),
|
||||
depth_slice: self.depth_slice,
|
||||
resolve_target: self.resolve_target.as_ref().map(|rt| rt.expect_downcast()),
|
||||
ops: self.ops,
|
||||
clear_value: self.clear_value,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> DepthStencilAttachment<'a, dyn DynTextureView> {
|
||||
pub fn expect_downcast<B: DynTextureView>(&self) -> DepthStencilAttachment<'a, B> {
|
||||
DepthStencilAttachment {
|
||||
target: self.target.expect_downcast(),
|
||||
depth_ops: self.depth_ops,
|
||||
stencil_ops: self.stencil_ops,
|
||||
clear_value: self.clear_value,
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 403 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user