Compare commits
289 Commits
main
...
camera-ite
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6bc1f3ee8 | ||
|
|
27d8eb5f51 | ||
|
|
5c8563f165 | ||
|
|
98e2740116 | ||
|
|
838ed9cbc0 | ||
|
|
2f575954e9 | ||
|
|
828a298476 | ||
|
|
9058592ce1 | ||
|
|
c96eb14235 | ||
|
|
6fc1bb2afa | ||
|
|
1ee485f3c5 | ||
|
|
9c62f4fd24 | ||
|
|
a1f07f9260 | ||
|
|
cd5fc51e98 | ||
|
|
12328ef1e2 | ||
|
|
d1a67296fc | ||
|
|
0d11a9ff03 | ||
|
|
c35e44565f | ||
|
|
a15045bba8 | ||
|
|
13b9509d90 | ||
|
|
68d3fc309b | ||
|
|
2f5584d545 | ||
|
|
cb7f3ef4ac | ||
|
|
7095e1df84 | ||
|
|
ee8f789f74 | ||
|
|
1519acc799 | ||
|
|
1d90657def | ||
|
|
cf6285abe0 | ||
|
|
9ae8efb9d6 | ||
|
|
6304541985 | ||
|
|
1babfdf10d | ||
|
|
218089a21d | ||
|
|
120b0a246e | ||
|
|
a5b1370c3e | ||
|
|
c9edcaf281 | ||
|
|
ce8e943c1f | ||
|
|
0dc5b1a92f | ||
|
|
93d35e17e6 | ||
|
|
b2c4e8e72c | ||
|
|
52af8095d6 | ||
|
|
102fc2ef79 | ||
|
|
9042a004d3 | ||
|
|
5360230ca7 | ||
|
|
a4d3ec537f | ||
|
|
ba3faf2c76 | ||
|
|
aa3c892f39 | ||
|
|
de0295fbf8 | ||
|
|
10034cdab2 | ||
|
|
faf6a8f22a | ||
|
|
821e4ae499 | ||
|
|
38709f5eaf | ||
|
|
601a140a70 | ||
|
|
4976c1ce4f | ||
|
|
d3e558c2b4 | ||
|
|
a525b2c39b | ||
|
|
b7cb0b747b | ||
|
|
d56091472e | ||
|
|
8c2c1b0c14 | ||
|
|
2c979c84c4 | ||
|
|
2c3e4bd135 | ||
|
|
4616b9b3bd | ||
|
|
0257655eba | ||
|
|
ccdab7578a | ||
|
|
fc2abfe59c | ||
|
|
7282684104 | ||
|
|
dac3a3092a | ||
|
|
4ffab6580d | ||
|
|
1047f5242b | ||
|
|
eedf5446e8 | ||
|
|
824b1bdd26 | ||
|
|
814d631bb8 | ||
|
|
fe28d6670e | ||
|
|
37413a3e74 | ||
|
|
8ad5fc6584 | ||
|
|
06dfba48d7 | ||
|
|
f7ad007d54 | ||
|
|
7a556439ca | ||
|
|
945514aa31 | ||
|
|
3b557cd851 | ||
|
|
95ecef3426 | ||
|
|
a85504a71a | ||
|
|
eb2ace5d29 | ||
|
|
1923b71985 | ||
|
|
a87823dcc8 | ||
|
|
1c0290aff5 | ||
|
|
e131b2b00f | ||
|
|
728573191f | ||
|
|
cee1137269 | ||
|
|
c6af3298a2 | ||
|
|
11074c9d05 | ||
|
|
aa6ec1afd8 | ||
|
|
a524f2020b | ||
|
|
e2ce337036 | ||
|
|
34c57254a9 | ||
|
|
d7bf01c417 | ||
|
|
59d049e7bd | ||
|
|
c05921fd71 | ||
|
|
5cbd4d807f | ||
|
|
23fe6ead25 | ||
|
|
b3247f5ba8 | ||
|
|
269e5afcc9 | ||
|
|
20070eb778 | ||
|
|
c8206b14dd | ||
|
|
e9089e83a9 | ||
|
|
34faa98dc8 | ||
|
|
187d6ee7d1 | ||
|
|
f7a9976760 | ||
|
|
f42c8963e7 | ||
|
|
f17b4c8ee2 | ||
|
|
47410fe63a | ||
|
|
04d0a77093 | ||
|
|
97c2b82fa7 | ||
|
|
343962fd6f | ||
|
|
2c07278c72 | ||
|
|
bdadc527d2 | ||
|
|
7045904693 | ||
|
|
c45dc36310 | ||
|
|
ed724dcb0f | ||
|
|
c4234becb9 | ||
|
|
cac2be7a4f | ||
|
|
84ba4b47ec | ||
|
|
aea681b5c6 | ||
|
|
7c17dbddb2 | ||
|
|
3f56d1e029 | ||
|
|
2a145de758 | ||
|
|
54ad2667c3 | ||
|
|
fa6ea5adc5 | ||
|
|
ee5a226c5e | ||
|
|
3e0860073d | ||
|
|
ec7f9a1681 | ||
|
|
779431be04 | ||
|
|
683b0c20a1 | ||
|
|
341da038ea | ||
|
|
367066381d | ||
|
|
2f5760c902 | ||
|
|
9072c34d50 | ||
|
|
aefa6dc62f | ||
|
|
35f42559ac | ||
|
|
63ead46a2c | ||
|
|
5682718713 | ||
|
|
58b9ee0f01 | ||
|
|
57039a3ccb | ||
|
|
0fec416731 | ||
|
|
f2c9f91a6b | ||
|
|
aef78f12b5 | ||
|
|
c19a5bcd91 | ||
|
|
de3ada1b5d | ||
|
|
d95b3f55e5 | ||
|
|
643c4959fb | ||
|
|
1b055c9406 | ||
|
|
42782d0f87 | ||
|
|
b5fc321e36 | ||
|
|
931f857458 | ||
|
|
8ecdd3acc6 | ||
|
|
951ca7c4db | ||
|
|
fee12854ca | ||
|
|
14b9129fca | ||
|
|
55ac288391 | ||
|
|
0c15f54bdc | ||
|
|
c42f69cb69 | ||
|
|
7818ae4add | ||
|
|
c09d565dc5 | ||
|
|
9076a0b897 | ||
|
|
37f283b393 | ||
|
|
40e7c6cd20 | ||
|
|
4620e0ca09 | ||
|
|
33d12787c9 | ||
|
|
d7b895f0f4 | ||
|
|
fb027de390 | ||
|
|
19c0ec42ac | ||
|
|
baea2c71a3 | ||
|
|
0694848c9b | ||
|
|
fd95988a42 | ||
|
|
24d8fefcaa | ||
|
|
a434c2aa55 | ||
|
|
c46e01e280 | ||
|
|
529b86fa91 | ||
|
|
b5e87d5911 | ||
|
|
063be773e0 | ||
|
|
3dadbccfff | ||
|
|
cbf5af88b9 | ||
|
|
f46e870864 | ||
|
|
2358ee899a | ||
|
|
4f50772b92 | ||
|
|
c52472fe3c | ||
|
|
52011bd92f | ||
|
|
be97de8a2e | ||
|
|
e9e4d3599d | ||
|
|
6d7d7be3f1 | ||
|
|
d5a951d3c6 | ||
|
|
1b0ef4b7df | ||
|
|
66879148c6 | ||
|
|
7108cfa365 | ||
|
|
05e60c43ce | ||
|
|
75359427c9 | ||
|
|
ba938dfaf9 | ||
|
|
c3721872e0 | ||
|
|
73f3d99877 | ||
|
|
1a5edee751 | ||
|
|
27d75d3098 | ||
|
|
198b342dec | ||
|
|
457ff55904 | ||
|
|
795780130c | ||
|
|
7a69d64e46 | ||
|
|
5350adef98 | ||
|
|
1ae7e4afaa | ||
|
|
e0e5f3b3bc | ||
|
|
d1522a05e8 | ||
|
|
4f1d03196a | ||
|
|
3cf65e5c7b | ||
|
|
3f08e1e212 | ||
|
|
a0d97c8385 | ||
|
|
95629422a7 | ||
|
|
46b3d21fca | ||
|
|
2ce9bf8cd4 | ||
|
|
1f745fddde | ||
|
|
45998df389 | ||
|
|
fe22451be5 | ||
|
|
57ea51fb40 | ||
|
|
2d0865e73c | ||
|
|
8556046b25 | ||
|
|
c0c0dddf23 | ||
|
|
c2665938d9 | ||
|
|
6b7a074fea | ||
|
|
bdd5cbe8b0 | ||
|
|
6068ad5089 | ||
|
|
2de49d981b | ||
|
|
246cf5ceea | ||
|
|
17583471bf | ||
|
|
868621a68c | ||
|
|
769fa24c1d | ||
|
|
89f4aae1ff | ||
|
|
aa79cb2147 | ||
|
|
0cb039c1be | ||
|
|
697320d1c0 | ||
|
|
9f5ad2b9af | ||
|
|
2315aca8b5 | ||
|
|
004454d75e | ||
|
|
4286bc119a | ||
|
|
e7f7f1f062 | ||
|
|
226d674365 | ||
|
|
0dc9dc23e9 | ||
|
|
48719c9862 | ||
|
|
125ab4f74d | ||
|
|
42d2a41d57 | ||
|
|
692ee95500 | ||
|
|
9ec6d31d67 | ||
|
|
e30ad3957a | ||
|
|
35e6e3f1f9 | ||
|
|
597cadd9f2 | ||
|
|
358aaa917a | ||
|
|
6ef154e9b3 | ||
|
|
5874eaef78 | ||
|
|
5b15df42c3 | ||
|
|
c10735acd1 | ||
|
|
2cb000c445 | ||
|
|
77bc08a78b | ||
|
|
fe4930e919 | ||
|
|
d3653e17cb | ||
|
|
418e9fdc54 | ||
|
|
bd62e7d342 | ||
|
|
9da111a3e0 | ||
|
|
b278a43d6d | ||
|
|
892a4165f8 | ||
|
|
088e8e2c9c | ||
|
|
043a1a1b29 | ||
|
|
41e76c9d0a | ||
|
|
6b578fe044 | ||
|
|
e2b00f23ee | ||
|
|
215b91a4bd | ||
|
|
9e0ba504ac | ||
|
|
3cdb6da09c | ||
|
|
3821e14fbd | ||
|
|
e3e7714f1a | ||
|
|
cdbfc27792 | ||
|
|
cbb09a9d97 | ||
|
|
12c2443e5d | ||
|
|
8b38f61e35 | ||
|
|
fad9b7d50c | ||
|
|
60f642364f | ||
|
|
454318b0af | ||
|
|
4e858e4212 | ||
|
|
e4d0159572 | ||
|
|
8ea05e998d | ||
|
|
af3833b263 | ||
|
|
94a78314bb | ||
|
|
a572b215b9 | ||
|
|
b189a6a73c | ||
|
|
44b91bf0e8 |
2
.cargo/config.toml
Normal file
2
.cargo/config.toml
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
[build]
|
||||||
|
rustflags = ["--cfg", "tokio_unstable"]
|
||||||
13
.github/FUNDING.yml
vendored
Normal file
13
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
# These are supported funding model platforms
|
||||||
|
|
||||||
|
github: [technobaboo]
|
||||||
|
patreon: # Replace with a single Patreon username
|
||||||
|
open_collective: # Replace with a single Open Collective username
|
||||||
|
ko_fi: # Replace with a single Ko-fi username
|
||||||
|
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||||
|
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||||
|
liberapay: # Replace with a single Liberapay username
|
||||||
|
issuehunt: # Replace with a single IssueHunt username
|
||||||
|
otechie: # Replace with a single Otechie username
|
||||||
|
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||||
|
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||||
46
.github/workflows/build.yml
vendored
Normal file
46
.github/workflows/build.yml
vendored
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
name: Build
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- '*'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build_and_package:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v2
|
||||||
|
|
||||||
|
- name: Install runtime dependencies
|
||||||
|
run: sudo apt install -y --no-install-recommends libxkbcommon-dev libstdc++6 libopenxr-dev libx11-dev libxfixes-dev libgl1-mesa-dev libegl1-mesa-dev libgbm-dev libfontconfig-dev libjsoncpp-dev libxcb1-dev libglx-dev libxcb-glx0-dev libdrm-dev libwayland-dev libfreetype-dev libpng-dev
|
||||||
|
|
||||||
|
- name: Install build dependencies
|
||||||
|
run: sudo apt install -y --no-install-recommends cmake ninja-build
|
||||||
|
|
||||||
|
- name: Set up Rust
|
||||||
|
uses: actions-rs/toolchain@v1
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
|
||||||
|
- name: Build server
|
||||||
|
run: cargo build --release
|
||||||
|
|
||||||
|
|
||||||
|
- name: Install appimagetool
|
||||||
|
run: |
|
||||||
|
wget https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-$(uname -m).AppImage -O /usr/local/bin/appimagetool; \
|
||||||
|
chmod +x /usr/local/bin/appimagetool; \
|
||||||
|
sed -i 's|AI\x02|\x00\x00\x00|' /usr/local/bin/appimagetool
|
||||||
|
- name: Install cargo-appimage
|
||||||
|
run: cargo install cargo-appimage
|
||||||
|
|
||||||
|
- name: Generate AppImage
|
||||||
|
run: cargo appimage
|
||||||
|
|
||||||
|
- name: Upload AppImage
|
||||||
|
uses: actions/upload-artifact@v2
|
||||||
|
with:
|
||||||
|
name: appimage
|
||||||
|
path: '*.AppImage'
|
||||||
11
.gitignore
vendored
11
.gitignore
vendored
@@ -2,11 +2,14 @@
|
|||||||
# will have compiled files and executables
|
# will have compiled files and executables
|
||||||
/target/
|
/target/
|
||||||
|
|
||||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
|
||||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
|
||||||
Cargo.lock
|
|
||||||
|
|
||||||
# These are backup files generated by rustfmt
|
# These are backup files generated by rustfmt
|
||||||
**/*.rs.bk
|
**/*.rs.bk
|
||||||
|
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|
||||||
|
# Ignore build results from Nix
|
||||||
|
*result*
|
||||||
|
|
||||||
|
/libs/
|
||||||
|
*.AppImage
|
||||||
|
*.blend1
|
||||||
2739
Cargo.lock
generated
Normal file
2739
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
111
Cargo.toml
111
Cargo.toml
@@ -1,51 +1,102 @@
|
|||||||
[package]
|
[package]
|
||||||
edition = "2018"
|
edition = "2021"
|
||||||
name = "stardust-xr-server"
|
name = "stardust-xr-server"
|
||||||
version = "0.10.1"
|
version = "0.43.0"
|
||||||
authors = ["Nova King <technobaboo@proton.me>"]
|
authors = ["Nova King <technobaboo@proton.me>"]
|
||||||
description = "Stardust XR reference display server"
|
description = "Stardust XR reference display server"
|
||||||
license = "GPLv2"
|
license = "GPLv2"
|
||||||
repository = "https://github.com/StardustXR/stardust-xr-server/"
|
repository = "https://github.com/StardustXR/stardust-xr-server/"
|
||||||
homepage = "https://stardustxr.org"
|
homepage = "https://stardustxr.org"
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "stardust-xr-server"
|
||||||
|
path = "src/main.rs"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["wayland"]
|
||||||
|
wayland = ["dep:smithay", "dep:xkbcommon"]
|
||||||
|
xwayland = ["smithay/xwayland"]
|
||||||
|
profile_tokio = ["dep:console-subscriber", "tokio/tracing"]
|
||||||
|
profile_app = ["dep:tracing-tracy"]
|
||||||
|
|
||||||
|
[package.metadata.appimage]
|
||||||
|
auto_link = true
|
||||||
|
auto_link_exclude_list = [
|
||||||
|
"libc*",
|
||||||
|
"libdl*",
|
||||||
|
"libpthread*",
|
||||||
|
"ld-linux*",
|
||||||
|
"libGL*",
|
||||||
|
"libEGL*",
|
||||||
|
]
|
||||||
|
|
||||||
|
[profile.dev.package."*"]
|
||||||
|
opt-level = 3
|
||||||
|
[profile.release]
|
||||||
|
strip = true
|
||||||
|
lto = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0.57"
|
color-eyre = { version = "0.6.2", default-features = false }
|
||||||
clap = { version = "4.0.8", features = ["derive"] }
|
clap = { version = "4.2.4", features = ["derive"] }
|
||||||
ctrlc = "3.2.2"
|
glam = { version = "0.23.0", features = ["mint"] }
|
||||||
dashmap = "5.3.4"
|
|
||||||
flatbuffers = "2.1.2"
|
|
||||||
flexbuffers = "2.0.0"
|
|
||||||
glam = {version = "0.21.3", features = ["mint"]}
|
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
mint = "0.5.9"
|
mint = "0.5.9"
|
||||||
nanoid = "0.4.0"
|
nanoid = "0.4.0"
|
||||||
once_cell = "1.12.0"
|
once_cell = "1.17.1"
|
||||||
parking_lot = "0.12.1"
|
parking_lot = "0.12.1"
|
||||||
portable-atomic = {version = "0.3.0", features = ["float", "std"]}
|
portable-atomic = { version = "1.2.0", features = ["float", "std"] }
|
||||||
rccell = "0.1.3"
|
|
||||||
rustc-hash = "1.1.0"
|
rustc-hash = "1.1.0"
|
||||||
slab = "0.4.6"
|
tokio = { version = "1.27.0", features = ["rt-multi-thread", "signal", "time"] }
|
||||||
tokio = { version = "1", features = ["full"] }
|
|
||||||
thiserror = "1.0.31"
|
|
||||||
send_wrapper = "0.6.0"
|
send_wrapper = "0.6.0"
|
||||||
prisma = "0.1.1"
|
prisma = "0.1.1"
|
||||||
slog = "2.7.0"
|
directories = "5.0.0"
|
||||||
slog-stdlog = "4.1.1"
|
serde = { version = "1.0.160", features = ["derive"] }
|
||||||
xkbcommon = { version = "0.5.0", default-features = false }
|
serde_repr = "0.1.16"
|
||||||
stardust-xr = "0.5.2"
|
tracing = "0.1.37"
|
||||||
wayland-backend = "=0.1.0-beta.9"
|
tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
|
||||||
wayland-scanner = "=0.30.0-beta.9"
|
global_counter = "0.2.2"
|
||||||
directories = "4.0.1"
|
rand = "0.8.5"
|
||||||
serde = { version = "1.0.145", features = ["derive"] }
|
atty = "0.2.14"
|
||||||
|
xkbcommon = { version = "0.6.0", default-features = false, optional = true }
|
||||||
|
ctrlc = "3.4.1"
|
||||||
|
libc = "0.2.148"
|
||||||
|
input-event-codes = "5.16.8"
|
||||||
|
drm-fourcc = { version = "2.2.0", features = ["serde"] }
|
||||||
|
|
||||||
|
[dependencies.smithay]
|
||||||
|
# git = "https://github.com/technobaboo/smithay.git" # Until we get stereokit to understand OES samplers and external textures
|
||||||
|
git = "https://github.com/smithay/smithay.git" # Until we get stereokit to understand OES samplers and external textures
|
||||||
|
# path = "../smithay"
|
||||||
|
default-features = false
|
||||||
|
features = [
|
||||||
|
"desktop",
|
||||||
|
"backend_drm",
|
||||||
|
"backend_egl",
|
||||||
|
"renderer_gl",
|
||||||
|
"wayland_frontend",
|
||||||
|
]
|
||||||
|
version = "*"
|
||||||
|
optional = true
|
||||||
|
|
||||||
[dependencies.stereokit]
|
[dependencies.stereokit]
|
||||||
default-features = false
|
default-features = false
|
||||||
features = ["linux-egl"]
|
features = ["linux-egl"]
|
||||||
version = "0.5.0"
|
version = "0.16.9"
|
||||||
|
|
||||||
[dependencies.smithay]
|
[dependencies.console-subscriber]
|
||||||
git = "https://github.com/technobaboo/smithay.git"
|
version = "0.1.8"
|
||||||
branch = "feature/public_input"
|
optional = true
|
||||||
default-features = false
|
|
||||||
features = ["desktop", "renderer_gl", "wayland_frontend"]
|
[dependencies.tracing-tracy]
|
||||||
version = "*"
|
version = "0.10.4"
|
||||||
|
optional = true
|
||||||
|
|
||||||
|
[dependencies.stardust-xr]
|
||||||
|
git = "https://github.com/StardustXR/core.git"
|
||||||
|
branch = "camera-item"
|
||||||
|
|
||||||
|
# [patch.crates-io.stereokit]
|
||||||
|
# path = "../stereokit-rs"
|
||||||
|
# [patch.crates-io.stereokit-sys]
|
||||||
|
# path = "../stereokit-sys"
|
||||||
|
|||||||
71
README.md
71
README.md
@@ -15,8 +15,71 @@ This project is a usable Linux display server that reinvents human-computer inte
|
|||||||
```bash
|
```bash
|
||||||
cargo build
|
cargo build
|
||||||
```
|
```
|
||||||
|
The latest stable server is automatically built to an appimage at https://github.com/StardustXR/server/releases for easy testing.
|
||||||
|
|
||||||
## Install
|
## Usage
|
||||||
```bash
|
|
||||||
cargo install
|
First, try running `cargo run` in a terminal window. If a headset is plugged in and OpenXR is working no window will show up. However, the headset should show the same things as the window that opens:
|
||||||
```
|
|
||||||
|

|
||||||
|
|
||||||
|
Stardust won't do anything interesting without clients! Try some from https://github.com/StardustXR.
|
||||||
|
|
||||||
|
### Default Sky
|
||||||
|
|
||||||
|
You can set a default skytex/skylight by putting your favorite HDRI equirectangular sky in `~/.config/stardust/skytex.hdr`. Certain clients can override this.
|
||||||
|
|
||||||
|
Flatscreen mode when the default skybox is [Zhengyang Gate](https://polyhaven.com/a/zhengyang_gate):
|
||||||
|

|
||||||
|
|
||||||
|
### Windowed Mode
|
||||||
|
|
||||||
|
If the stardust server can't connect to an OpenXR runtime or you force it into flatscreen mode with `-f`, the server will show in a window.
|
||||||
|

|
||||||
|
|
||||||
|
You can navigate around by right click + dragging to look around, Shift+W/A/S/D/Q/E to move. If you have a virtual hand, left click pinches, right click points, both make a fist.
|
||||||
|
|
||||||
|
### Flags
|
||||||
|
#### Flatscreen (-f)
|
||||||
|
|
||||||
|
The server will show up in windowed mode no matter what with your mouse pointer being turned into a 3D pointer. Keyboard input will be sent to whatever your mouse is hovering over like visionOS simulator.
|
||||||
|
Flatscreen mode upon initial startup:
|
||||||
|

|
||||||
|
|
||||||
|
#### Overlay (-o \<PRIORITY>)
|
||||||
|
|
||||||
|
The server will, if in XR mode, be overlaid using the OpenXR overlay extension with the given priority.
|
||||||
|
|
||||||
|
#### Disable controller (--disable-controller)
|
||||||
|
|
||||||
|
Some runtimes such as Monado may emulate a controller using a hand, and this messes with Stardust's input system. Set this flag to ignore the controllers that the OpenXR runtime provides.
|
||||||
|
|
||||||
|
#### Execute (-e </path/to/executable>)
|
||||||
|
|
||||||
|
When wayland and OpenXR and such are initialized, run the given executable (such as a bash script) with all the environment variables needed to connect all clients of any type to the server. If not set, the server will run the executable at `~/.config/stardust/startup` if it exists. This is how stardust desktop environments can be made.
|
||||||
|
|
||||||
|
#### Help (-h, --help)
|
||||||
|
|
||||||
|
help
|
||||||
|
|
||||||
|
## Test
|
||||||
|
|
||||||
|
##### Gnome Graphical Integration Test
|
||||||
|
|
||||||
|
- `nix build .#gnome-graphical-test`
|
||||||
|
|
||||||
|
This test uses Nix to reproducibly execute a QEMU virtual machine which
|
||||||
|
spawns a full Gnome desktop. It runs `monado-service`, `stardust-xr-server`
|
||||||
|
`flatland` underneath of Gnome and then attaches `weston-cliptest` to the
|
||||||
|
`flatland` process running underneath of `stardust-xr-server`, the result is
|
||||||
|
a screenshot in PNG format that should look like expected. If any process in
|
||||||
|
this test produces an exit code above 0, the test will fail, graphical bugs
|
||||||
|
should be visible in the screenshot. An example of the result is below.
|
||||||
|
|
||||||
|
###### Result
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
##### Everything
|
||||||
|
|
||||||
|
`nix flake check` will build every test underneath of the `checks` attribute in the `flake.nix`
|
||||||
283
flake.lock
generated
Normal file
283
flake.lock
generated
Normal file
@@ -0,0 +1,283 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"fenix": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": [
|
||||||
|
"flatland",
|
||||||
|
"nixpkgs"
|
||||||
|
],
|
||||||
|
"rust-analyzer-src": "rust-analyzer-src"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1678775037,
|
||||||
|
"narHash": "sha256-chx0tWnXKpcayPkPY3Qh+2hNwptvX8XE3o+fYZ+GNzg=",
|
||||||
|
"owner": "nix-community",
|
||||||
|
"repo": "fenix",
|
||||||
|
"rev": "ee59e1c769657b1e27e608f8b981fa8f6b715583",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-community",
|
||||||
|
"repo": "fenix",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-parts": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs-lib": "nixpkgs-lib"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1690933134,
|
||||||
|
"narHash": "sha256-ab989mN63fQZBFrkk4Q8bYxQCktuHmBIBqUG1jl6/FQ=",
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "flake-parts",
|
||||||
|
"rev": "59cf3f1447cfc75087e7273b04b31e689a8599fb",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "flake-parts",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-parts_2": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs-lib": "nixpkgs-lib_2"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1688466019,
|
||||||
|
"narHash": "sha256-VeM2akYrBYMsb4W/MmBo1zmaMfgbL4cH3Pu8PGyIwJ0=",
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "flake-parts",
|
||||||
|
"rev": "8e8d955c22df93dbe24f19ea04f47a74adbdc5ec",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"id": "flake-parts",
|
||||||
|
"type": "indirect"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-parts_3": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs-lib": [
|
||||||
|
"hercules-ci-effects",
|
||||||
|
"hercules-ci-agent",
|
||||||
|
"nixpkgs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1688466019,
|
||||||
|
"narHash": "sha256-VeM2akYrBYMsb4W/MmBo1zmaMfgbL4cH3Pu8PGyIwJ0=",
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "flake-parts",
|
||||||
|
"rev": "8e8d955c22df93dbe24f19ea04f47a74adbdc5ec",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "flake-parts",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flatland": {
|
||||||
|
"inputs": {
|
||||||
|
"fenix": "fenix",
|
||||||
|
"nixpkgs": "nixpkgs"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1694190588,
|
||||||
|
"narHash": "sha256-tcvp09A54AbXkkXS/P6Ed5TUWzMEuQ9h/fnfLz7gnJc=",
|
||||||
|
"owner": "StardustXR",
|
||||||
|
"repo": "flatland",
|
||||||
|
"rev": "3867067452761959a95497d6589f9336b347270c",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "StardustXR",
|
||||||
|
"repo": "flatland",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"haskell-flake": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1684780604,
|
||||||
|
"narHash": "sha256-2uMZsewmRn7rRtAnnQNw1lj0uZBMh4m6Cs/7dV5YF08=",
|
||||||
|
"owner": "srid",
|
||||||
|
"repo": "haskell-flake",
|
||||||
|
"rev": "74210fa80a49f1b6f67223debdbf1494596ff9f2",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "srid",
|
||||||
|
"ref": "0.3.0",
|
||||||
|
"repo": "haskell-flake",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"hercules-ci-agent": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-parts": "flake-parts_3",
|
||||||
|
"haskell-flake": "haskell-flake",
|
||||||
|
"nixpkgs": "nixpkgs_2"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1688568579,
|
||||||
|
"narHash": "sha256-ON0M56wtY/TIIGPkXDlJboAmuYwc73Hi8X9iJGtxOhM=",
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "hercules-ci-agent",
|
||||||
|
"rev": "367dd8cd649b57009a6502e878005a1e54ad78c5",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"id": "hercules-ci-agent",
|
||||||
|
"type": "indirect"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"hercules-ci-effects": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-parts": "flake-parts_2",
|
||||||
|
"hercules-ci-agent": "hercules-ci-agent",
|
||||||
|
"nixpkgs": "nixpkgs_3"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1689397210,
|
||||||
|
"narHash": "sha256-fVxZnqxMbsDkB4GzGAs/B41K0wt/e+B/fLxmTFF/S20=",
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "hercules-ci-effects",
|
||||||
|
"rev": "0a63bfa3f00a3775ea3a6722b247880f1ffe91ce",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "hercules-ci",
|
||||||
|
"repo": "hercules-ci-effects",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1678703398,
|
||||||
|
"narHash": "sha256-Y1mW3dBsoWLHpYm+UIHb5VZ7rx024NNHaF16oZBx++o=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "67f26c1cfc5d5783628231e776a81c1ade623e0b",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-22.11",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs-lib": {
|
||||||
|
"locked": {
|
||||||
|
"dir": "lib",
|
||||||
|
"lastModified": 1690881714,
|
||||||
|
"narHash": "sha256-h/nXluEqdiQHs1oSgkOOWF+j8gcJMWhwnZ9PFabN6q0=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "9e1960bc196baf6881340d53dccb203a951745a2",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"dir": "lib",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs-lib_2": {
|
||||||
|
"locked": {
|
||||||
|
"dir": "lib",
|
||||||
|
"lastModified": 1688049487,
|
||||||
|
"narHash": "sha256-100g4iaKC9MalDjUW9iN6Jl/OocTDtXdeAj7pEGIRh4=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "4bc72cae107788bf3f24f30db2e2f685c9298dc9",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"dir": "lib",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs_2": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1688322751,
|
||||||
|
"narHash": "sha256-eW62dC5f33oKZL7VWlomttbUnOTHrAbte9yNUNW8rbk=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "0fbe93c5a7cac99f90b60bdf5f149383daaa615f",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs_3": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1689393711,
|
||||||
|
"narHash": "sha256-l3gyTPy/qWLDk1CY1EgYwlsxcGxN2aVd7MlCzQa69rk=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "27fcd46fa18df36d270174246e7bd8f1787129ff",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs_4": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1692734709,
|
||||||
|
"narHash": "sha256-SCFnyHCyYjwEmgUsHDDuU0TsbVMKeU1vwkR+r7uS2Rg=",
|
||||||
|
"owner": "nixos",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "b85ed9dcbf187b909ef7964774f8847d554fab3b",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nixos",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"flake-parts": "flake-parts",
|
||||||
|
"flatland": "flatland",
|
||||||
|
"hercules-ci-effects": "hercules-ci-effects",
|
||||||
|
"nixpkgs": "nixpkgs_4"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"rust-analyzer-src": {
|
||||||
|
"flake": false,
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1678695923,
|
||||||
|
"narHash": "sha256-rDhiiU8P6sf6mgj5IKgCuTRN9uYeqWr6xl4XLkKnMWg=",
|
||||||
|
"owner": "rust-lang",
|
||||||
|
"repo": "rust-analyzer",
|
||||||
|
"rev": "95497533524537b1cc7a2870ce94b0b14503be8b",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "rust-lang",
|
||||||
|
"ref": "nightly",
|
||||||
|
"repo": "rust-analyzer",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
||||||
80
flake.nix
Normal file
80
flake.nix
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
{
|
||||||
|
nixConfig = {
|
||||||
|
extra-substituters = [ "https://stardustxr.cachix.org" ];
|
||||||
|
extra-trusted-public-keys = [ "stardustxr.cachix.org-1:mWSn8Ap2RLsIWT/8gsj+VfbJB6xoOkPaZpbjO+r9HBo=" ];
|
||||||
|
};
|
||||||
|
inputs = {
|
||||||
|
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
|
||||||
|
flake-parts.url = "github:hercules-ci/flake-parts";
|
||||||
|
hercules-ci-effects.url = "github:hercules-ci/hercules-ci-effects";
|
||||||
|
|
||||||
|
# Since we do not have a monorepo, we have to fetch Flatland in order to use
|
||||||
|
# it to create VM Tests
|
||||||
|
flatland.url = "github:StardustXR/flatland";
|
||||||
|
};
|
||||||
|
outputs = inputs@{ self, flake-parts, nixpkgs, hercules-ci-effects, flatland, ... }:
|
||||||
|
let
|
||||||
|
name = (builtins.fromTOML (builtins.readFile ./Cargo.toml)).package.name;
|
||||||
|
src = builtins.path {
|
||||||
|
name = "${name}-source";
|
||||||
|
path = toString ./.;
|
||||||
|
filter = path: type:
|
||||||
|
nixpkgs.lib.all
|
||||||
|
(n: builtins.baseNameOf path != n)
|
||||||
|
[
|
||||||
|
"flake.nix"
|
||||||
|
"flake.lock"
|
||||||
|
"nix"
|
||||||
|
"README.md"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
in
|
||||||
|
flake-parts.lib.mkFlake { inherit inputs; } {
|
||||||
|
imports = [
|
||||||
|
flake-parts.flakeModules.easyOverlay
|
||||||
|
];
|
||||||
|
systems = [ "aarch64-linux" "x86_64-linux" "riscv64-linux" ];
|
||||||
|
perSystem = { config, self', inputs', pkgs, system, ... }: {
|
||||||
|
_module.args.pkgs = import inputs.nixpkgs { inherit system; overlays = [ inputs.self.overlays.default ]; };
|
||||||
|
overlayAttrs = config.packages;
|
||||||
|
packages = {
|
||||||
|
default = self'.packages.${name};
|
||||||
|
gnome-graphical-test = self'.checks.gnome-graphical-test;
|
||||||
|
"${name}" = pkgs.callPackage ./nix/stardust-xr-server.nix { inherit name src; };
|
||||||
|
};
|
||||||
|
checks.gnome-graphical-test = pkgs.nixosTest (import ./nix/gnome-graphical-test.nix { inherit pkgs self; });
|
||||||
|
devShells.default = pkgs.mkShell {
|
||||||
|
inputsFrom = [ self'.packages.default ];
|
||||||
|
LIBCLANG_PATH = "${pkgs.libclang.lib}/lib";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
flake = {
|
||||||
|
herculesCI.ciSystems = [ "x86_64-linux" ];
|
||||||
|
effects = let
|
||||||
|
pkgs = nixpkgs.legacyPackages.x86_64-linux;
|
||||||
|
hci-effects = hercules-ci-effects.lib.withPkgs pkgs;
|
||||||
|
in { branch, rev, ... }: {
|
||||||
|
gnome-graphical-test = hci-effects.mkEffect {
|
||||||
|
secretsMap."stardustxrDiscord" = "stardustxrDiscord";
|
||||||
|
secretsMap."stardustxrIpfs" = "stardustxrIpfs";
|
||||||
|
effectScript = ''
|
||||||
|
readSecretString stardustxrDiscord .webhook > .webhook
|
||||||
|
readSecretString stardustxrIpfs .basicauth > .basicauth
|
||||||
|
set -x
|
||||||
|
export RESPONSE=$(curl -H @.basicauth -F file=@${self.packages."x86_64-linux".gnome-graphical-test}/screen.png https://ipfs-api.stardustxr.org/api/v0/add)
|
||||||
|
export CID=$(echo "$RESPONSE" | ${pkgs.jq}/bin/jq -r .Hash)
|
||||||
|
set +x
|
||||||
|
export ADDRESS="https://ipfs.stardustxr.org/ipfs/$CID"
|
||||||
|
${pkgs.discord-sh}/bin/discord.sh \
|
||||||
|
--description "\`stardustxr/server\` has been modified, here's how it renders \`weston-cliptest\` on \`flatland\` via \`monado-service\` inside of the \`gnome-graphical-test\`" \
|
||||||
|
--field "Branch;${branch}" \
|
||||||
|
--field "Commit ID;${rev}" \
|
||||||
|
--field "Flatland Revision;${flatland.rev}" \
|
||||||
|
--field "Reproducer;\`nix build github:stardustxr/server/${rev}#gnome-graphical-test\`" \
|
||||||
|
--image "$ADDRESS"
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
BIN
img/flatscreen_1.png
Normal file
BIN
img/flatscreen_1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 9.6 KiB |
BIN
img/flatscreen_2.png
Normal file
BIN
img/flatscreen_2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
BIN
img/flatscreen_3.png
Normal file
BIN
img/flatscreen_3.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 789 KiB |
BIN
img/xr_mode_windowed_blank.png
Normal file
BIN
img/xr_mode_windowed_blank.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
155
nix/gnome-graphical-test.nix
Normal file
155
nix/gnome-graphical-test.nix
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
{ pkgs, lib ? pkgs.lib, self, ... }:
|
||||||
|
# Some code is copy-pasted from https://github.com/NixOS/nixpkgs/blob/master/nixos/tests/gnome.nix
|
||||||
|
# TODO: make this less boiler-platey and make a function like mkGnomeTest that does all this and upstream it to nixpkgs
|
||||||
|
{
|
||||||
|
name = "stardust-xr-server-gnome-vmtest";
|
||||||
|
meta = with lib; {
|
||||||
|
maintainers = [ maintainers.matthewcroughan ];
|
||||||
|
};
|
||||||
|
nodes.machine = { ... }: {
|
||||||
|
imports = [ "${pkgs.path}/nixos/tests/common/user-account.nix" ];
|
||||||
|
virtualisation.qemu.options = [
|
||||||
|
"-device virtio-gpu-pci"
|
||||||
|
];
|
||||||
|
environment.systemPackages = [ pkgs.monado ];
|
||||||
|
services.xserver = {
|
||||||
|
enable = true;
|
||||||
|
desktopManager.gnome = {
|
||||||
|
enable = true;
|
||||||
|
debug = true;
|
||||||
|
# Set a nice desktop background that is pleasing to the eyes :3
|
||||||
|
extraGSettingsOverrides = ''
|
||||||
|
[org.gnome.desktop.background]
|
||||||
|
picture-uri='file://${pkgs.gnome.gnome-backgrounds}/share/backgrounds/gnome/blobs-l.svg'
|
||||||
|
picture-uri-dark='file://${pkgs.gnome.gnome-backgrounds}/share/backgrounds/gnome/blobs-l.svg'
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
displayManager = {
|
||||||
|
gdm = {
|
||||||
|
enable = true;
|
||||||
|
debug = true;
|
||||||
|
};
|
||||||
|
autoLogin = {
|
||||||
|
enable = true;
|
||||||
|
user = "alice";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
systemd.user.services = {
|
||||||
|
"monado" = {
|
||||||
|
after = [ "graphical-session.target" "default.target" "org.gnome.Shell@wayland.service" ];
|
||||||
|
environment = {
|
||||||
|
XRT_COMPOSITOR_FORCE_WAYLAND = "1";
|
||||||
|
WAYLAND_DISPLAY = "wayland-0";
|
||||||
|
};
|
||||||
|
serviceConfig = {
|
||||||
|
ExecStartPre = [
|
||||||
|
"${pkgs.writeShellScript "sleep" ''
|
||||||
|
sleep 3
|
||||||
|
''}"
|
||||||
|
];
|
||||||
|
ExecStart = let
|
||||||
|
# stdin disappears in NixOS test driver ( machine.succeed() ), requiring us to specify < /dev/ttyS0 to fake stdin
|
||||||
|
exec-monado-service = pkgs.writeShellScript "exec-monado-service" "${pkgs.monado}/bin/monado-service < /dev/ttyS0";
|
||||||
|
in [
|
||||||
|
"${exec-monado-service}"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
"stardust-xr-server" = {
|
||||||
|
after = [ "monado.service" ];
|
||||||
|
serviceConfig = {
|
||||||
|
Type = "notify";
|
||||||
|
NotifyAccess = "all";
|
||||||
|
ExecStartPre = [
|
||||||
|
"${pkgs.writeShellScript "sleep" ''
|
||||||
|
sleep 3
|
||||||
|
''}"
|
||||||
|
];
|
||||||
|
ExecStart = let
|
||||||
|
notifyReady = pkgs.writeShellScript "notifyReady" "systemd-notify --ready";
|
||||||
|
exec-stardust-xr-server = pkgs.writeShellScript "exec-stardust-xr-server" "${self.packages.${pkgs.hostPlatform.system}.default}/bin/stardust-xr-server -e ${notifyReady}";
|
||||||
|
in [
|
||||||
|
"${exec-stardust-xr-server}"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
"weston-cliptest" = {
|
||||||
|
after = [ "flatland.service" ];
|
||||||
|
environment.WAYLAND_DISPLAY = "wayland-1";
|
||||||
|
serviceConfig = {
|
||||||
|
ExecStart = [
|
||||||
|
"${pkgs.weston}/bin/weston-cliptest"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
"flatland" = {
|
||||||
|
after = [ "stardust-xr-server.service" ];
|
||||||
|
serviceConfig = {
|
||||||
|
ExecStart = [
|
||||||
|
"${self.inputs.flatland.packages.${pkgs.hostPlatform.system}.default}/bin/flatland"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
"org.gnome.Shell@wayland" = {
|
||||||
|
wants = [ "monado.service" "stardust-xr-server.service" "flatland.service" "weston-cliptest.service" ];
|
||||||
|
serviceConfig = {
|
||||||
|
ExecStart = [
|
||||||
|
# Clear the list before overriding it.
|
||||||
|
""
|
||||||
|
# Eval API is now internal so Shell needs to run in unsafe mode.
|
||||||
|
# TODO: improve test driver so that it supports openqa-like manipulation
|
||||||
|
# that would allow us to drop this mess.
|
||||||
|
"${pkgs.gnome.gnome-shell}/bin/gnome-shell --unsafe-mode"
|
||||||
|
];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
testScript = { nodes, ... }: let
|
||||||
|
# Keep line widths somewhat managable
|
||||||
|
user = nodes.machine.config.users.users.alice;
|
||||||
|
uid = toString user.uid;
|
||||||
|
bus = "DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/${uid}/bus";
|
||||||
|
gdbus = "${bus} gdbus";
|
||||||
|
su = command: "su ${user.name} -c '${command}'";
|
||||||
|
|
||||||
|
# Call javascript in gnome shell, returns a tuple (success, output), where
|
||||||
|
# `success` is true if the dbus call was successful and output is what the
|
||||||
|
# javascript evaluates to.
|
||||||
|
eval = "call --session -d org.gnome.Shell -o /org/gnome/Shell -m org.gnome.Shell.Eval";
|
||||||
|
|
||||||
|
# False when startup is done
|
||||||
|
startingUp = su "${gdbus} ${eval} Main.layoutManager._startingUp";
|
||||||
|
in ''
|
||||||
|
with subtest("Login to GNOME with GDM"):
|
||||||
|
# wait for gdm to start
|
||||||
|
machine.wait_for_unit("display-manager.service")
|
||||||
|
# wait for the wayland server
|
||||||
|
machine.wait_for_file("/run/user/${uid}/wayland-0")
|
||||||
|
# wait for alice to be logged in
|
||||||
|
machine.wait_for_unit("default.target", "${user.name}")
|
||||||
|
# check that logging in has given the user ownership of devices
|
||||||
|
assert "alice" in machine.succeed("getfacl -p /dev/snd/timer")
|
||||||
|
|
||||||
|
with subtest("Wait for GNOME Shell"):
|
||||||
|
# correct output should be (true, 'false')
|
||||||
|
machine.wait_until_succeeds(
|
||||||
|
"${startingUp} | grep -q 'true,..false'"
|
||||||
|
)
|
||||||
|
|
||||||
|
# To allow monado-service to use < /dev/ttyS0
|
||||||
|
machine.succeed("chown alice /dev/ttyS0")
|
||||||
|
|
||||||
|
with subtest("Open Monado and StardustXR"):
|
||||||
|
# Close the Activities view so that Shell can correctly track the focused window.
|
||||||
|
machine.send_key("esc")
|
||||||
|
machine.wait_for_unit("monado.service", "${user.name}")
|
||||||
|
machine.wait_for_unit("stardust-xr-server.service", "${user.name}")
|
||||||
|
machine.wait_for_unit("flatland.service", "${user.name}")
|
||||||
|
machine.wait_for_unit("weston-cliptest.service", "${user.name}")
|
||||||
|
machine.sleep(3)
|
||||||
|
machine.screenshot("screen")
|
||||||
|
'';
|
||||||
|
}
|
||||||
40
nix/stardust-xr-server.nix
Normal file
40
nix/stardust-xr-server.nix
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
{ rustPlatform
|
||||||
|
, src
|
||||||
|
, name
|
||||||
|
, openxr-loader
|
||||||
|
, libGL
|
||||||
|
, mesa
|
||||||
|
, xorg
|
||||||
|
, fontconfig
|
||||||
|
, libxkbcommon
|
||||||
|
, libclang
|
||||||
|
, cmake
|
||||||
|
, cpm-cmake
|
||||||
|
, pkg-config
|
||||||
|
, llvmPackages
|
||||||
|
}:
|
||||||
|
|
||||||
|
rustPlatform.buildRustPackage rec {
|
||||||
|
inherit src name;
|
||||||
|
cargoLock = {
|
||||||
|
lockFile = (src + "/Cargo.lock");
|
||||||
|
allowBuiltinFetchGit = true;
|
||||||
|
};
|
||||||
|
CPM_SOURCE_CACHE = "./build";
|
||||||
|
postPatch = ''
|
||||||
|
sk=$(echo $cargoDepsCopy/stereokit-sys-*/StereoKit)
|
||||||
|
mkdir -p $sk/build/cpm
|
||||||
|
|
||||||
|
# This is not ideal, the original approach was to fetch the exact cmake
|
||||||
|
# file version that was wanted from GitHub directly, but at least this way it comes from Nixpkgs.. so meh
|
||||||
|
cp ${cpm-cmake}/share/cpm/CPM.cmake $sk/build/cpm/CPM_0.32.2.cmake
|
||||||
|
'';
|
||||||
|
nativeBuildInputs = [
|
||||||
|
cmake pkg-config llvmPackages.libcxxClang
|
||||||
|
];
|
||||||
|
buildInputs = [
|
||||||
|
openxr-loader libGL mesa xorg.libX11 fontconfig libxkbcommon
|
||||||
|
];
|
||||||
|
LIBCLANG_PATH = "${libclang.lib}/lib";
|
||||||
|
}
|
||||||
|
|
||||||
50
src/core/buffers.rs
Normal file
50
src/core/buffers.rs
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
use std::ffi::c_void;
|
||||||
|
|
||||||
|
use color_eyre::eyre::{ensure, Result};
|
||||||
|
use smithay::backend::{egl::EGLContext, renderer::gles::GlesRenderer};
|
||||||
|
use stereokit as sk;
|
||||||
|
|
||||||
|
struct EGLRawHandles {
|
||||||
|
display: *const c_void,
|
||||||
|
config: *const c_void,
|
||||||
|
context: *const c_void,
|
||||||
|
}
|
||||||
|
fn get_sk_egl() -> Result<EGLRawHandles> {
|
||||||
|
ensure!(
|
||||||
|
unsafe { sk::sys::backend_graphics_get() }
|
||||||
|
== sk::sys::backend_graphics__backend_graphics_opengles_egl,
|
||||||
|
"StereoKit is not running using EGL!"
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(unsafe {
|
||||||
|
EGLRawHandles {
|
||||||
|
display: sk::sys::backend_opengl_egl_get_display() as *const c_void,
|
||||||
|
config: sk::sys::backend_opengl_egl_get_config() as *const c_void,
|
||||||
|
context: sk::sys::backend_opengl_egl_get_context() as *const c_void,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct BufferManager {
|
||||||
|
pub renderer: GlesRenderer,
|
||||||
|
}
|
||||||
|
impl BufferManager {
|
||||||
|
pub fn new() -> Result<Self> {
|
||||||
|
let egl_raw_handles = get_sk_egl()?;
|
||||||
|
let renderer = unsafe {
|
||||||
|
GlesRenderer::new(EGLContext::from_raw(
|
||||||
|
egl_raw_handles.display,
|
||||||
|
egl_raw_handles.config,
|
||||||
|
egl_raw_handles.context,
|
||||||
|
)?)?
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(BufferManager { renderer })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn make_context_current(&self) {
|
||||||
|
unsafe {
|
||||||
|
let _ = self.renderer.egl_context().make_current();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,136 +1,231 @@
|
|||||||
use super::{eventloop::EventLoop, scenegraph::Scenegraph};
|
use super::{
|
||||||
use crate::{
|
client_state::{ClientState, CLIENT_STATES},
|
||||||
core::registry::Registry,
|
scenegraph::Scenegraph,
|
||||||
nodes::{data, drawable, fields, hmd, input, items, root::Root, spatial, startup, Node},
|
|
||||||
};
|
};
|
||||||
use anyhow::{anyhow, Result};
|
use crate::{
|
||||||
|
core::{registry::OwnedRegistry, task},
|
||||||
|
nodes::{audio, data, drawable, fields, hmd, input, items, root::Root, spatial, Node},
|
||||||
|
};
|
||||||
|
use color_eyre::eyre::{eyre, Result};
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use stardust_xr::messenger::Messenger;
|
use rustc_hash::FxHashMap;
|
||||||
use std::{
|
use stardust_xr::{
|
||||||
path::PathBuf,
|
messenger::{self, MessageSenderHandle},
|
||||||
sync::{Arc, Weak},
|
schemas::flex::serialize,
|
||||||
};
|
};
|
||||||
use tokio::{net::UnixStream, sync::Notify, task::JoinHandle};
|
use std::{fs, iter::FromIterator, path::PathBuf, sync::Arc};
|
||||||
|
use tokio::{net::UnixStream, task::JoinHandle};
|
||||||
|
use tracing::info;
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
pub static ref CLIENTS: Registry<Client> = Registry::new();
|
pub static ref CLIENTS: OwnedRegistry<Client> = OwnedRegistry::new();
|
||||||
pub static ref INTERNAL_CLIENT: Arc<Client> = CLIENTS.add(Client {
|
pub static ref INTERNAL_CLIENT: Arc<Client> = CLIENTS.add(Client {
|
||||||
event_loop: Weak::new(),
|
pid: None,
|
||||||
index: 0,
|
// env: None,
|
||||||
|
exe: None,
|
||||||
|
|
||||||
stop_notifier: Default::default(),
|
dispatch_join_handle: OnceCell::new(),
|
||||||
join_handle: OnceCell::new(),
|
flush_join_handle: OnceCell::new(),
|
||||||
|
disconnect_status: OnceCell::new(),
|
||||||
|
|
||||||
messenger: None,
|
message_sender_handle: None,
|
||||||
scenegraph: Default::default(),
|
scenegraph: Default::default(),
|
||||||
root: OnceCell::new(),
|
root: OnceCell::new(),
|
||||||
base_resource_prefixes: Default::default(),
|
base_resource_prefixes: Default::default(),
|
||||||
|
state: Arc::new(ClientState::default()),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Client {
|
pub fn get_env(pid: i32) -> Result<FxHashMap<String, String>, std::io::Error> {
|
||||||
event_loop: Weak<EventLoop>,
|
let env = fs::read_to_string(format!("/proc/{pid}/environ"))?;
|
||||||
index: usize,
|
Ok(FxHashMap::from_iter(
|
||||||
stop_notifier: Arc<Notify>,
|
env.split('\0')
|
||||||
join_handle: OnceCell<JoinHandle<Result<()>>>,
|
.filter_map(|var| var.split_once('='))
|
||||||
|
.map(|(k, v)| (k.to_string(), v.to_string())),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
pub fn state(env: &FxHashMap<String, String>) -> Option<Arc<ClientState>> {
|
||||||
|
let token = env.get("STARDUST_STARTUP_TOKEN")?;
|
||||||
|
CLIENT_STATES.lock().get(token).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
pub messenger: Option<Messenger>,
|
pub struct Client {
|
||||||
pub scenegraph: Scenegraph,
|
pub pid: Option<i32>,
|
||||||
|
// env: Option<FxHashMap<String, String>>,
|
||||||
|
exe: Option<PathBuf>,
|
||||||
|
dispatch_join_handle: OnceCell<JoinHandle<Result<()>>>,
|
||||||
|
flush_join_handle: OnceCell<JoinHandle<Result<()>>>,
|
||||||
|
disconnect_status: OnceCell<Result<()>>,
|
||||||
|
|
||||||
|
pub message_sender_handle: Option<MessageSenderHandle>,
|
||||||
|
pub scenegraph: Arc<Scenegraph>,
|
||||||
pub root: OnceCell<Arc<Root>>,
|
pub root: OnceCell<Arc<Root>>,
|
||||||
pub base_resource_prefixes: Mutex<Vec<PathBuf>>,
|
pub base_resource_prefixes: Mutex<Vec<PathBuf>>,
|
||||||
|
pub state: Arc<ClientState>,
|
||||||
}
|
}
|
||||||
impl Client {
|
impl Client {
|
||||||
pub fn from_connection(
|
pub fn from_connection(connection: UnixStream) -> Result<Arc<Self>> {
|
||||||
index: usize,
|
let pid = connection.peer_cred().ok().and_then(|c| c.pid());
|
||||||
event_loop: &Arc<EventLoop>,
|
let env = pid.and_then(|pid| get_env(pid).ok());
|
||||||
connection: UnixStream,
|
let exe = pid.and_then(|pid| fs::read_link(format!("/proc/{}/exe", pid)).ok());
|
||||||
) -> Arc<Self> {
|
info!(
|
||||||
println!("New client connected");
|
pid,
|
||||||
let client = CLIENTS.add(Client {
|
exe = exe
|
||||||
event_loop: Arc::downgrade(event_loop),
|
.as_ref()
|
||||||
index,
|
.and_then(|exe| exe.to_str().map(|s| s.to_string())),
|
||||||
stop_notifier: Default::default(),
|
"New client connected"
|
||||||
join_handle: OnceCell::new(),
|
);
|
||||||
|
|
||||||
messenger: Some(Messenger::new(
|
let (mut messenger_tx, mut messenger_rx) = messenger::create(connection);
|
||||||
tokio::runtime::Handle::current(),
|
let scenegraph = Arc::new(Scenegraph::default());
|
||||||
connection,
|
let state = env
|
||||||
)),
|
.as_ref()
|
||||||
scenegraph: Default::default(),
|
.and_then(state)
|
||||||
|
.unwrap_or_else(|| Arc::new(ClientState::default()));
|
||||||
|
|
||||||
|
let client = CLIENTS.add(Client {
|
||||||
|
pid,
|
||||||
|
// env,
|
||||||
|
exe: exe.clone(),
|
||||||
|
|
||||||
|
dispatch_join_handle: OnceCell::new(),
|
||||||
|
flush_join_handle: OnceCell::new(),
|
||||||
|
disconnect_status: OnceCell::new(),
|
||||||
|
|
||||||
|
message_sender_handle: Some(messenger_tx.handle()),
|
||||||
|
scenegraph: scenegraph.clone(),
|
||||||
root: OnceCell::new(),
|
root: OnceCell::new(),
|
||||||
base_resource_prefixes: Default::default(),
|
base_resource_prefixes: Default::default(),
|
||||||
|
state,
|
||||||
});
|
});
|
||||||
let _ = client.scenegraph.client.set(Arc::downgrade(&client));
|
let _ = client.scenegraph.client.set(Arc::downgrade(&client));
|
||||||
let _ = client.root.set(Root::create(&client));
|
let _ = client.root.set(Root::create(&client)?);
|
||||||
hmd::make_alias(&client);
|
hmd::make_alias(&client)?;
|
||||||
spatial::create_interface(&client);
|
spatial::create_interface(&client)?;
|
||||||
fields::create_interface(&client);
|
fields::create_interface(&client)?;
|
||||||
drawable::create_interface(&client);
|
drawable::create_interface(&client)?;
|
||||||
data::create_interface(&client);
|
audio::create_interface(&client)?;
|
||||||
items::create_interface(&client);
|
data::create_interface(&client)?;
|
||||||
input::create_interface(&client);
|
items::create_interface(&client)?;
|
||||||
startup::create_interface(&client);
|
input::create_interface(&client)?;
|
||||||
|
|
||||||
let _ = client.join_handle.set(tokio::spawn({
|
|
||||||
let client = client.clone();
|
|
||||||
async move {
|
|
||||||
let dispatch_loop = async {
|
|
||||||
loop {
|
|
||||||
client.dispatch().await?
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let flush_loop = async {
|
|
||||||
loop {
|
|
||||||
client.flush().await?
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let result = tokio::select! {
|
|
||||||
_ = client.stop_notifier.notified() => Ok(()),
|
|
||||||
e = dispatch_loop => e,
|
|
||||||
e = flush_loop => e,
|
|
||||||
};
|
|
||||||
client.disconnect().await;
|
|
||||||
result
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
client
|
client
|
||||||
|
.root
|
||||||
|
.get()
|
||||||
|
.unwrap()
|
||||||
|
.node
|
||||||
|
.send_remote_signal("restore_state", serialize(client.state.apply_to(&client))?)?;
|
||||||
|
|
||||||
|
let pid_printable = pid
|
||||||
|
.map(|pid| pid.to_string())
|
||||||
|
.unwrap_or_else(|| "??".to_string());
|
||||||
|
let exe_printable = exe
|
||||||
|
.and_then(|exe| {
|
||||||
|
exe.file_name()
|
||||||
|
.and_then(|exe| exe.to_str())
|
||||||
|
.map(|exe| exe.to_string())
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| "??".to_string());
|
||||||
|
let _ = client.dispatch_join_handle.get_or_try_init(|| {
|
||||||
|
task::new(
|
||||||
|
|| {
|
||||||
|
format!(
|
||||||
|
"client dispatch pid={} exe={}",
|
||||||
|
&pid_printable, &exe_printable,
|
||||||
|
)
|
||||||
|
},
|
||||||
|
{
|
||||||
|
let client = client.clone();
|
||||||
|
async move {
|
||||||
|
loop {
|
||||||
|
match messenger_rx.dispatch(&*scenegraph).await {
|
||||||
|
Err(e) => {
|
||||||
|
client.disconnect(Err(e.into()));
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
});
|
||||||
|
let _ = client.flush_join_handle.get_or_try_init(|| {
|
||||||
|
task::new(
|
||||||
|
|| format!("client flush pid={} exe={}", &pid_printable, &exe_printable,),
|
||||||
|
{
|
||||||
|
let client = client.clone();
|
||||||
|
async move {
|
||||||
|
loop {
|
||||||
|
match messenger_tx.flush().await {
|
||||||
|
Err(e) => {
|
||||||
|
client.disconnect(Err(e.into()));
|
||||||
|
}
|
||||||
|
_ => (),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(client)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_cmdline(&self) -> Option<Vec<String>> {
|
||||||
|
let pid = self.pid?;
|
||||||
|
let exe_proc_path = format!("/proc/{pid}/exe");
|
||||||
|
let cmdline_proc_path = format!("/proc/{pid}/cmdline");
|
||||||
|
let exe = std::fs::read_link(exe_proc_path).ok()?;
|
||||||
|
let cmdline = std::fs::read_to_string(cmdline_proc_path).ok()?;
|
||||||
|
let mut cmdline_split: Vec<_> = cmdline.split('\0').map(ToString::to_string).collect();
|
||||||
|
cmdline_split.pop();
|
||||||
|
*cmdline_split.get_mut(0).unwrap() = exe.to_str()?.to_string();
|
||||||
|
Some(cmdline_split)
|
||||||
|
}
|
||||||
|
pub fn get_cwd(&self) -> Option<PathBuf> {
|
||||||
|
let pid = self.pid?;
|
||||||
|
let cwd_proc_path = format!("/proc/{pid}/cwd");
|
||||||
|
std::fs::read_link(cwd_proc_path).ok()
|
||||||
|
}
|
||||||
|
pub async fn save_state(&self) -> Option<ClientState> {
|
||||||
|
let internal = self.root.get()?.save_state().await.ok()?;
|
||||||
|
Some(ClientState::from_deserialized(self, internal))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn get_node(&self, name: &'static str, path: &str) -> Result<Arc<Node>> {
|
pub fn get_node(&self, name: &'static str, path: &str) -> Result<Arc<Node>> {
|
||||||
self.scenegraph
|
self.scenegraph
|
||||||
.get_node(path)
|
.get_node(path)
|
||||||
.ok_or_else(|| anyhow!("{} not found", name))
|
.ok_or_else(|| eyre!("{} not found", name))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn dispatch(&self) -> Result<(), std::io::Error> {
|
pub fn disconnect(&self, reason: Result<()>) {
|
||||||
match &self.messenger {
|
let _ = self.disconnect_status.set(reason);
|
||||||
Some(messenger) => messenger.dispatch(&self.scenegraph).await,
|
if let Some(dispatch_join_handle) = self.dispatch_join_handle.get() {
|
||||||
None => Err(std::io::Error::from(std::io::ErrorKind::Unsupported)),
|
dispatch_join_handle.abort();
|
||||||
}
|
}
|
||||||
}
|
if let Some(flush_join_handle) = self.flush_join_handle.get() {
|
||||||
|
flush_join_handle.abort();
|
||||||
pub async fn flush(&self) -> Result<(), std::io::Error> {
|
|
||||||
match &self.messenger {
|
|
||||||
Some(messenger) => messenger.flush().await,
|
|
||||||
None => Err(std::io::Error::from(std::io::ErrorKind::Unsupported)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn disconnect(&self) {
|
|
||||||
self.stop_notifier.notify_one();
|
|
||||||
if let Some(event_loop) = self.event_loop.upgrade() {
|
|
||||||
event_loop.clients.lock().await.remove(self.index);
|
|
||||||
}
|
}
|
||||||
|
CLIENTS.remove(self);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Drop for Client {
|
impl Drop for Client {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.stop_notifier.notify_one();
|
info!(
|
||||||
CLIENTS.remove(self);
|
pid = self.pid,
|
||||||
println!("Client disconnected");
|
exe = self
|
||||||
|
.exe
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|exe| exe.to_str().map(|s| s.to_string())),
|
||||||
|
disconnect_status = match self.disconnect_status.take() {
|
||||||
|
Some(Ok(_)) => "Graceful disconnect".to_string(),
|
||||||
|
Some(Err(e)) => format!("Error: {}", e.root_cause()),
|
||||||
|
None => "Unknown".to_string(),
|
||||||
|
},
|
||||||
|
"Client disconnected"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
108
src/core/client_state.rs
Normal file
108
src/core/client_state.rs
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
use super::client::{get_env, Client};
|
||||||
|
use crate::nodes::{spatial::Spatial, Node};
|
||||||
|
use glam::Mat4;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use rustc_hash::FxHashMap;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::{io::Write, path::PathBuf, sync::Arc};
|
||||||
|
|
||||||
|
lazy_static::lazy_static! {
|
||||||
|
pub static ref CLIENT_STATES: Mutex<FxHashMap<String, Arc<ClientState>>> = Default::default();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
pub struct LaunchInfo {
|
||||||
|
pub cmdline: Vec<String>,
|
||||||
|
pub cwd: PathBuf,
|
||||||
|
pub env: FxHashMap<String, String>,
|
||||||
|
}
|
||||||
|
impl LaunchInfo {
|
||||||
|
fn from_client(client: &Client) -> Option<Self> {
|
||||||
|
Some(LaunchInfo {
|
||||||
|
cmdline: client.get_cmdline()?,
|
||||||
|
cwd: client.get_cwd()?,
|
||||||
|
env: get_env(client.pid?).ok()?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
|
pub struct ClientState {
|
||||||
|
pub launch_info: Option<LaunchInfo>,
|
||||||
|
pub data: Option<Vec<u8>>,
|
||||||
|
pub root: Mat4,
|
||||||
|
pub spatial_anchors: FxHashMap<String, Mat4>,
|
||||||
|
}
|
||||||
|
impl ClientState {
|
||||||
|
pub fn from_deserialized(client: &Client, state: ClientStateInternal) -> Self {
|
||||||
|
ClientState {
|
||||||
|
launch_info: LaunchInfo::from_client(client),
|
||||||
|
data: state.data,
|
||||||
|
root: Self::spatial_transform(client, &state.root.unwrap_or_default())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
spatial_anchors: state
|
||||||
|
.spatial_anchors
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(k, v)| Some((k, Self::spatial_transform(client, &v)?)))
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn spatial_transform(client: &Client, path: &str) -> Option<Mat4> {
|
||||||
|
let node = client.scenegraph.get_node(path)?;
|
||||||
|
let spatial = node.spatial.get()?;
|
||||||
|
Some(spatial.global_transform())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn token(self) -> String {
|
||||||
|
let token = nanoid::nanoid!();
|
||||||
|
CLIENT_STATES.lock().insert(token.clone(), Arc::new(self));
|
||||||
|
token
|
||||||
|
}
|
||||||
|
pub fn to_file(self) {
|
||||||
|
let project_dirs = directories::ProjectDirs::from("", "", "stardust").unwrap();
|
||||||
|
let state_dir = project_dirs.state_dir().unwrap();
|
||||||
|
std::fs::create_dir_all(state_dir).unwrap();
|
||||||
|
let mut file = std::fs::File::create(state_dir.join(nanoid::nanoid!())).unwrap();
|
||||||
|
file.write_all(&stardust_xr::schemas::flex::flexbuffers::to_vec(self).unwrap())
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
pub fn apply_to(&self, client: &Arc<Client>) -> ClientStateInternal {
|
||||||
|
if let Some(root) = client.root.get() {
|
||||||
|
root.set_transform(self.root)
|
||||||
|
}
|
||||||
|
ClientStateInternal {
|
||||||
|
data: self.data.clone(),
|
||||||
|
root: Some("/".to_string()),
|
||||||
|
spatial_anchors: self
|
||||||
|
.spatial_anchors
|
||||||
|
.iter()
|
||||||
|
.map(|(k, v)| {
|
||||||
|
(k.clone(), {
|
||||||
|
let node = Node::create(client, "/spatial/anchor", k, true)
|
||||||
|
.add_to_scenegraph()
|
||||||
|
.unwrap();
|
||||||
|
Spatial::add_to(&node, None, *v, false).unwrap();
|
||||||
|
k.clone()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Default for ClientState {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
launch_info: None,
|
||||||
|
data: None,
|
||||||
|
root: Mat4::IDENTITY,
|
||||||
|
spatial_anchors: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Serialize, Deserialize)]
|
||||||
|
pub struct ClientStateInternal {
|
||||||
|
data: Option<Vec<u8>>,
|
||||||
|
root: Option<String>,
|
||||||
|
spatial_anchors: FxHashMap<String, String>,
|
||||||
|
}
|
||||||
47
src/core/delta.rs
Normal file
47
src/core/delta.rs
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
use std::ops::{Deref, DerefMut};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Delta<T> {
|
||||||
|
value: T,
|
||||||
|
changed: bool,
|
||||||
|
}
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl<T> Delta<T> {
|
||||||
|
pub const fn new(value: T) -> Self {
|
||||||
|
Delta {
|
||||||
|
value,
|
||||||
|
changed: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn peek_delta(&self) -> Option<&T> {
|
||||||
|
self.changed.then_some(&self.value)
|
||||||
|
}
|
||||||
|
pub fn delta(&mut self) -> Option<&mut T> {
|
||||||
|
let delta = self.changed.then_some(&mut self.value);
|
||||||
|
self.changed = false;
|
||||||
|
delta
|
||||||
|
}
|
||||||
|
pub fn mark_changed(&mut self) {
|
||||||
|
self.changed = true;
|
||||||
|
}
|
||||||
|
pub const fn value(&self) -> &T {
|
||||||
|
&self.value
|
||||||
|
}
|
||||||
|
pub fn value_mut(&mut self) -> &mut T {
|
||||||
|
self.mark_changed();
|
||||||
|
&mut self.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T> Deref for Delta<T> {
|
||||||
|
type Target = T;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T> DerefMut for Delta<T> {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
self.mark_changed();
|
||||||
|
&mut self.value
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,61 +1,36 @@
|
|||||||
use super::client::Client;
|
use super::client::Client;
|
||||||
use anyhow::Result;
|
use super::task;
|
||||||
use slab::Slab;
|
use color_eyre::eyre::Result;
|
||||||
use stardust_xr::server;
|
use std::path::PathBuf;
|
||||||
use std::sync::atomic::AtomicU64;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::net::UnixListener;
|
use tokio::net::UnixListener;
|
||||||
use tokio::sync::{Mutex, Notify};
|
|
||||||
use tokio::task::JoinHandle;
|
use tokio::task::JoinHandle;
|
||||||
|
use tracing::error;
|
||||||
pub static FRAME: AtomicU64 = AtomicU64::new(0);
|
|
||||||
|
|
||||||
pub struct EventLoop {
|
pub struct EventLoop {
|
||||||
pub socket_path: String,
|
join_handle: JoinHandle<()>,
|
||||||
stop_notifier: Arc<Notify>,
|
|
||||||
pub clients: Mutex<Slab<Arc<Client>>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventLoop {
|
impl EventLoop {
|
||||||
pub fn new() -> Result<(Arc<Self>, JoinHandle<Result<()>>)> {
|
pub fn new(socket_path: PathBuf) -> Result<Arc<Self>> {
|
||||||
let socket_path = server::get_free_socket_path()
|
let socket = UnixListener::bind(socket_path)?;
|
||||||
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::Other))?;
|
|
||||||
let socket = UnixListener::bind(socket_path.clone())?;
|
|
||||||
|
|
||||||
let event_loop = Arc::new(EventLoop {
|
let join_handle = task::new(|| "event loop", async move {
|
||||||
socket_path,
|
|
||||||
stop_notifier: Default::default(),
|
|
||||||
clients: Mutex::new(Slab::new()),
|
|
||||||
});
|
|
||||||
|
|
||||||
let event_loop_join_handle = tokio::spawn({
|
|
||||||
let event_loop = event_loop.clone();
|
|
||||||
async move { EventLoop::event_loop(socket, event_loop).await }
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok((event_loop, event_loop_join_handle))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn event_loop(socket: UnixListener, event_loop: Arc<EventLoop>) -> Result<()> {
|
|
||||||
let event_loop_async = async {
|
|
||||||
loop {
|
loop {
|
||||||
let (socket, _) = socket.accept().await?;
|
let Ok((socket, _)) = socket.accept().await else { continue };
|
||||||
let mut clients = event_loop.clients.lock().await;
|
if let Err(e) = Client::from_connection(socket) {
|
||||||
let vacant_client = clients.vacant_entry();
|
error!(?e, "Unable to create client from connection");
|
||||||
let idx = vacant_client.key();
|
}
|
||||||
vacant_client.insert(Client::from_connection(idx, &event_loop, socket));
|
|
||||||
}
|
}
|
||||||
};
|
})?;
|
||||||
|
let event_loop = Arc::new(EventLoop { join_handle });
|
||||||
|
|
||||||
tokio::select! {
|
Ok(event_loop)
|
||||||
_ = event_loop.stop_notifier.notified() => Ok(()),
|
|
||||||
e = event_loop_async => e,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for EventLoop {
|
impl Drop for EventLoop {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.stop_notifier.notify_one();
|
self.join_handle.abort();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
pub mod client;
|
pub mod client;
|
||||||
|
pub mod client_state;
|
||||||
|
pub mod delta;
|
||||||
pub mod destroy_queue;
|
pub mod destroy_queue;
|
||||||
pub mod eventloop;
|
pub mod eventloop;
|
||||||
pub mod nodelist;
|
pub mod node_collections;
|
||||||
pub mod registry;
|
pub mod registry;
|
||||||
pub mod resource;
|
pub mod resource;
|
||||||
pub mod scenegraph;
|
pub mod scenegraph;
|
||||||
|
pub mod task;
|
||||||
|
pub mod typed_datamap;
|
||||||
|
pub mod buffers;
|
||||||
|
|||||||
83
src/core/node_collections.rs
Normal file
83
src/core/node_collections.rs
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
use crate::nodes::Node;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use rustc_hash::FxHashMap;
|
||||||
|
use std::{
|
||||||
|
borrow::Borrow,
|
||||||
|
hash::Hash,
|
||||||
|
sync::{Arc, Weak},
|
||||||
|
};
|
||||||
|
|
||||||
|
// #[derive(Default)]
|
||||||
|
// pub struct LifeLinkedNodeList {
|
||||||
|
// nodes: Mutex<Vec<Weak<Node>>>,
|
||||||
|
// }
|
||||||
|
// impl LifeLinkedNodeList {
|
||||||
|
// pub fn add(&self, node: Weak<Node>) {
|
||||||
|
// self.nodes.lock().push(node);
|
||||||
|
// }
|
||||||
|
// pub fn clear(&self) {
|
||||||
|
// self.nodes
|
||||||
|
// .lock()
|
||||||
|
// .iter()
|
||||||
|
// .filter_map(|node| node.upgrade())
|
||||||
|
// .for_each(|node| {
|
||||||
|
// node.destroy();
|
||||||
|
// });
|
||||||
|
// self.nodes.lock().clear();
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// impl Drop for LifeLinkedNodeList {
|
||||||
|
// fn drop(&mut self) {
|
||||||
|
// self.clear();
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
#[derive(Default, Debug)]
|
||||||
|
pub struct LifeLinkedNodeMap<K: Hash + Eq> {
|
||||||
|
nodes: Mutex<FxHashMap<K, Weak<Node>>>,
|
||||||
|
}
|
||||||
|
#[allow(dead_code)]
|
||||||
|
impl<K: Hash + Eq> LifeLinkedNodeMap<K> {
|
||||||
|
pub fn add(&self, key: K, node: &Arc<Node>) {
|
||||||
|
self.nodes.lock().insert(key, Arc::downgrade(node));
|
||||||
|
}
|
||||||
|
pub fn get<Q>(&self, key: &Q) -> Option<Arc<Node>>
|
||||||
|
where
|
||||||
|
Q: ?Sized,
|
||||||
|
K: Borrow<Q>,
|
||||||
|
Q: Hash + Eq,
|
||||||
|
{
|
||||||
|
self.nodes.lock().get(key).and_then(|n| n.upgrade())
|
||||||
|
}
|
||||||
|
pub fn nodes(&self) -> Vec<Arc<Node>> {
|
||||||
|
self.nodes
|
||||||
|
.lock()
|
||||||
|
.values()
|
||||||
|
.filter_map(|v| v.upgrade())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
pub fn remove<Q>(&self, key: &Q) -> Option<Arc<Node>>
|
||||||
|
where
|
||||||
|
Q: ?Sized,
|
||||||
|
K: Borrow<Q>,
|
||||||
|
Q: Hash + Eq,
|
||||||
|
{
|
||||||
|
self.nodes.lock().remove(key).and_then(|n| n.upgrade())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn clear(&self) {
|
||||||
|
let mut nodes = self.nodes.lock();
|
||||||
|
nodes
|
||||||
|
.values()
|
||||||
|
.filter_map(|node| node.upgrade())
|
||||||
|
.for_each(|node| {
|
||||||
|
node.destroy();
|
||||||
|
});
|
||||||
|
nodes.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<K: Hash + Eq> Drop for LifeLinkedNodeMap<K> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
use crate::nodes::Node;
|
|
||||||
use parking_lot::Mutex;
|
|
||||||
use std::sync::Weak;
|
|
||||||
|
|
||||||
#[derive(Default)]
|
|
||||||
pub struct LifeLinkedNodeList {
|
|
||||||
nodes: Mutex<Vec<Weak<Node>>>,
|
|
||||||
}
|
|
||||||
impl LifeLinkedNodeList {
|
|
||||||
pub fn add(&self, node: Weak<Node>) {
|
|
||||||
self.nodes.lock().push(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn clear(&self) {
|
|
||||||
self.nodes
|
|
||||||
.lock()
|
|
||||||
.iter()
|
|
||||||
.filter_map(|node| node.upgrade())
|
|
||||||
.for_each(|node| {
|
|
||||||
node.destroy();
|
|
||||||
});
|
|
||||||
self.nodes.lock().clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl Drop for LifeLinkedNodeList {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
self.clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +1,20 @@
|
|||||||
#![allow(dead_code)]
|
#![allow(dead_code)]
|
||||||
|
|
||||||
|
use parking_lot::{const_mutex, MappedMutexGuard, Mutex, MutexGuard};
|
||||||
|
use rustc_hash::FxHashMap;
|
||||||
use std::ptr;
|
use std::ptr;
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::{Arc, Weak};
|
||||||
|
|
||||||
use once_cell::sync::Lazy;
|
pub struct Registry<T: Send + Sync + ?Sized>(Mutex<Option<FxHashMap<usize, Weak<T>>>>);
|
||||||
use parking_lot::Mutex;
|
|
||||||
use rustc_hash::FxHashMap;
|
|
||||||
|
|
||||||
pub struct Registry<T: Send + Sync + ?Sized>(Lazy<Mutex<FxHashMap<usize, Weak<T>>>>);
|
|
||||||
|
|
||||||
impl<T: Send + Sync + ?Sized> Registry<T> {
|
impl<T: Send + Sync + ?Sized> Registry<T> {
|
||||||
pub const fn new() -> Self {
|
pub const fn new() -> Self {
|
||||||
Registry(Lazy::new(|| Mutex::new(FxHashMap::default())))
|
Registry(const_mutex(None))
|
||||||
|
}
|
||||||
|
fn lock(&self) -> MappedMutexGuard<FxHashMap<usize, Weak<T>>> {
|
||||||
|
MutexGuard::map(self.0.lock(), |r| {
|
||||||
|
r.get_or_insert_with(|| FxHashMap::default())
|
||||||
|
})
|
||||||
}
|
}
|
||||||
pub fn add(&self, t: T) -> Arc<T>
|
pub fn add(&self, t: T) -> Arc<T>
|
||||||
where
|
where
|
||||||
@@ -22,23 +25,89 @@ impl<T: Send + Sync + ?Sized> Registry<T> {
|
|||||||
t_arc
|
t_arc
|
||||||
}
|
}
|
||||||
pub fn add_raw(&self, t: &Arc<T>) {
|
pub fn add_raw(&self, t: &Arc<T>) {
|
||||||
self.0
|
self.lock()
|
||||||
.lock()
|
|
||||||
.insert(Arc::as_ptr(t) as *const () as usize, Arc::downgrade(t));
|
.insert(Arc::as_ptr(t) as *const () as usize, Arc::downgrade(t));
|
||||||
}
|
}
|
||||||
|
pub fn contains(&self, t: &T) -> bool {
|
||||||
|
self.lock()
|
||||||
|
.contains_key(&(ptr::addr_of!(*t) as *const () as usize))
|
||||||
|
}
|
||||||
pub fn get_valid_contents(&self) -> Vec<Arc<T>> {
|
pub fn get_valid_contents(&self) -> Vec<Arc<T>> {
|
||||||
self.0
|
self.lock()
|
||||||
.lock()
|
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|pair| pair.1.upgrade())
|
.filter_map(|pair| pair.1.upgrade())
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
pub fn remove(&self, t: &T) {
|
pub fn take_valid_contents(&self) -> Vec<Arc<T>> {
|
||||||
self.0
|
self.0
|
||||||
.lock()
|
.lock()
|
||||||
|
.take()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|pair| pair.1.upgrade())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
pub fn remove(&self, t: &T) {
|
||||||
|
self.lock()
|
||||||
.remove(&(ptr::addr_of!(*t) as *const () as usize));
|
.remove(&(ptr::addr_of!(*t) as *const () as usize));
|
||||||
}
|
}
|
||||||
pub fn clear(&self) {
|
pub fn clear(&self) {
|
||||||
self.0.lock().clear();
|
self.lock().clear();
|
||||||
|
}
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
let registry = self.0.lock();
|
||||||
|
let Some(registry) = &*registry else {return true};
|
||||||
|
if registry.is_empty() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
registry.values().all(|v| v.strong_count() == 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T: Send + Sync + ?Sized> Clone for Registry<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self(Mutex::new(self.0.lock().clone()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct OwnedRegistry<T: Send + Sync + ?Sized>(Mutex<Option<FxHashMap<usize, Arc<T>>>>);
|
||||||
|
|
||||||
|
impl<T: Send + Sync + ?Sized> OwnedRegistry<T> {
|
||||||
|
pub const fn new() -> Self {
|
||||||
|
OwnedRegistry(const_mutex(None))
|
||||||
|
}
|
||||||
|
fn lock(&self) -> MappedMutexGuard<FxHashMap<usize, Arc<T>>> {
|
||||||
|
MutexGuard::map(self.0.lock(), |r| {
|
||||||
|
r.get_or_insert_with(|| FxHashMap::default())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
pub fn add(&self, t: T) -> Arc<T>
|
||||||
|
where
|
||||||
|
T: Sized,
|
||||||
|
{
|
||||||
|
let t_arc = Arc::new(t);
|
||||||
|
self.add_raw(t_arc.clone());
|
||||||
|
t_arc
|
||||||
|
}
|
||||||
|
pub fn add_raw(&self, t: Arc<T>) {
|
||||||
|
self.lock().insert(Arc::as_ptr(&t) as *const () as usize, t);
|
||||||
|
}
|
||||||
|
pub fn get_vec(&self) -> Vec<Arc<T>> {
|
||||||
|
self.lock().values().cloned().collect::<Vec<_>>()
|
||||||
|
}
|
||||||
|
pub fn contains(&self, t: &T) -> bool {
|
||||||
|
self.lock()
|
||||||
|
.contains_key(&(ptr::addr_of!(*t) as *const () as usize))
|
||||||
|
}
|
||||||
|
pub fn remove(&self, t: &T) {
|
||||||
|
self.lock()
|
||||||
|
.remove(&(ptr::addr_of!(*t) as *const () as usize));
|
||||||
|
}
|
||||||
|
pub fn clear(&self) {
|
||||||
|
self.lock().clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T: Send + Sync + ?Sized> Clone for OwnedRegistry<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
Self(Mutex::new(self.0.lock().clone()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +1,43 @@
|
|||||||
use anyhow::anyhow;
|
use color_eyre::eyre::eyre;
|
||||||
use serde::{de::Visitor, Deserialize};
|
use serde::{de::Visitor, Deserialize};
|
||||||
use std::path::PathBuf;
|
use std::{ffi::OsStr, path::PathBuf};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
pub enum ResourceID {
|
pub enum ResourceID {
|
||||||
File(PathBuf),
|
File(PathBuf),
|
||||||
Namespaced { namespace: String, path: PathBuf },
|
Namespaced { namespace: String, path: PathBuf },
|
||||||
}
|
}
|
||||||
impl ResourceID {
|
impl ResourceID {
|
||||||
pub fn get_file(&self, prefixes: &[PathBuf]) -> Option<PathBuf> {
|
pub fn get_file(&self, prefixes: &[PathBuf], extensions: &[&OsStr]) -> Option<PathBuf> {
|
||||||
match self {
|
match self {
|
||||||
ResourceID::File(file) => (file.is_absolute() && file.exists()).then_some(file.clone()),
|
ResourceID::File(file) => (file.is_absolute()
|
||||||
|
&& file.exists() && Self::has_extension(file, extensions))
|
||||||
|
.then_some(file.clone()),
|
||||||
ResourceID::Namespaced { namespace, path } => {
|
ResourceID::Namespaced { namespace, path } => {
|
||||||
for prefix in prefixes {
|
let file_name = path.file_name()?;
|
||||||
let mut test_path = prefix.clone();
|
prefixes
|
||||||
test_path.push(namespace.clone());
|
.iter()
|
||||||
test_path.push(path.clone());
|
.filter_map(|prefix| {
|
||||||
|
let prefixed_path = prefix.clone().join(namespace).join(path);
|
||||||
if test_path.as_path().exists() {
|
let parent = prefixed_path.parent()?;
|
||||||
return Some(test_path);
|
std::fs::read_dir(parent).ok()
|
||||||
}
|
})
|
||||||
}
|
.flatten()
|
||||||
None
|
.filter_map(|item| item.ok())
|
||||||
|
.map(|dir_entry| dir_entry.path())
|
||||||
|
.filter(|path| path.file_stem() == Some(file_name))
|
||||||
|
.find(|path| Self::has_extension(path, extensions))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn has_extension(path: &PathBuf, extensions: &[&OsStr]) -> bool {
|
||||||
|
if let Some(path_extension) = path.extension() {
|
||||||
|
extensions.contains(&path_extension)
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
impl<'de> Deserialize<'de> for ResourceID {
|
impl<'de> Deserialize<'de> for ResourceID {
|
||||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||||
@@ -56,9 +70,7 @@ impl<'de> Visitor<'de> for ResourceVisitor {
|
|||||||
path: PathBuf::from(path),
|
path: PathBuf::from(path),
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return Err(serde::de::Error::custom(anyhow!(
|
return Err(serde::de::Error::custom(eyre!("Invalid format for string")));
|
||||||
"Invalid format for string"
|
|
||||||
)));
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,24 +1,26 @@
|
|||||||
use crate::core::client::Client;
|
|
||||||
use crate::nodes::Node;
|
use crate::nodes::Node;
|
||||||
use anyhow::Result;
|
use crate::{core::client::Client, nodes::Message};
|
||||||
|
use color_eyre::eyre::Result;
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use portable_atomic::Ordering;
|
||||||
|
use rustc_hash::FxHashMap;
|
||||||
use stardust_xr::scenegraph;
|
use stardust_xr::scenegraph;
|
||||||
use stardust_xr::scenegraph::ScenegraphError;
|
use stardust_xr::scenegraph::ScenegraphError;
|
||||||
|
use std::os::fd::OwnedFd;
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::{Arc, Weak};
|
||||||
|
use tokio::sync::oneshot;
|
||||||
use core::hash::BuildHasherDefault;
|
use tracing::{debug, debug_span};
|
||||||
use dashmap::DashMap;
|
|
||||||
use rustc_hash::FxHasher;
|
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct Scenegraph {
|
pub struct Scenegraph {
|
||||||
pub(super) client: OnceCell<Weak<Client>>,
|
pub(super) client: OnceCell<Weak<Client>>,
|
||||||
nodes: DashMap<String, Arc<Node>, BuildHasherDefault<FxHasher>>,
|
nodes: Mutex<FxHashMap<String, Arc<Node>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Scenegraph {
|
impl Scenegraph {
|
||||||
pub fn get_client(&self) -> Arc<Client> {
|
pub fn get_client(&self) -> Option<Arc<Client>> {
|
||||||
self.client.get().unwrap().upgrade().unwrap()
|
self.client.get()?.upgrade()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_node(&self, node: Node) -> Arc<Node> {
|
pub fn add_node(&self, node: Node) -> Arc<Node> {
|
||||||
@@ -27,38 +29,89 @@ impl Scenegraph {
|
|||||||
node_arc
|
node_arc
|
||||||
}
|
}
|
||||||
pub fn add_node_raw(&self, node: Arc<Node>) {
|
pub fn add_node_raw(&self, node: Arc<Node>) {
|
||||||
|
debug!(node = ?&*node, "Add node");
|
||||||
let path = node.get_path().to_string();
|
let path = node.get_path().to_string();
|
||||||
self.nodes.insert(path, node);
|
self.nodes.lock().insert(path, node);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_node(&self, path: &str) -> Option<Arc<Node>> {
|
pub fn get_node(&self, path: &str) -> Option<Arc<Node>> {
|
||||||
let mut node = self.nodes.get(path)?.clone();
|
let mut node = self.nodes.lock().get(path)?.clone();
|
||||||
if let Some(alias) = node.alias.get() {
|
while let Some(alias) = node.alias.get() {
|
||||||
node = alias.original.upgrade()?;
|
if alias.enabled.load(Ordering::Relaxed) {
|
||||||
|
node = alias.original.upgrade()?;
|
||||||
|
} else {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Some(node)
|
Some(node)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove_node(&self, path: &str) -> Option<Arc<Node>> {
|
pub fn remove_node(&self, path: &str) -> Option<Arc<Node>> {
|
||||||
let (_, node) = self.nodes.remove(path)?;
|
debug!(path, "Remove node");
|
||||||
Some(node)
|
self.nodes.lock().remove(path)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub struct MethodResponseSender(oneshot::Sender<Result<(Vec<u8>, Vec<OwnedFd>), ScenegraphError>>);
|
||||||
|
impl MethodResponseSender {
|
||||||
|
pub fn send(self, t: Result<Message, ScenegraphError>) {
|
||||||
|
let _ = self.0.send(t.map(|m| (m.data, m.fds)));
|
||||||
|
}
|
||||||
|
pub fn wrap_sync<F: FnOnce() -> color_eyre::eyre::Result<Message>>(self, f: F) {
|
||||||
|
self.send(f().map_err(|e| ScenegraphError::MethodError {
|
||||||
|
error: e.to_string(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
}
|
||||||
impl scenegraph::Scenegraph for Scenegraph {
|
impl scenegraph::Scenegraph for Scenegraph {
|
||||||
fn send_signal(&self, path: &str, method: &str, data: &[u8]) -> Result<(), ScenegraphError> {
|
fn send_signal(
|
||||||
self.get_node(path)
|
&self,
|
||||||
.ok_or(ScenegraphError::NodeNotFound)?
|
path: &str,
|
||||||
.send_local_signal(self.get_client(), method, data)
|
method: &str,
|
||||||
|
data: &[u8],
|
||||||
|
fds: Vec<OwnedFd>,
|
||||||
|
) -> Result<(), ScenegraphError> {
|
||||||
|
let Some(client) = self.get_client() else {
|
||||||
|
return Err(ScenegraphError::SignalNotFound);
|
||||||
|
};
|
||||||
|
debug_span!("Handle signal", path, method).in_scope(|| {
|
||||||
|
self.get_node(path)
|
||||||
|
.ok_or(ScenegraphError::NodeNotFound)?
|
||||||
|
.send_local_signal(
|
||||||
|
client,
|
||||||
|
method,
|
||||||
|
Message {
|
||||||
|
data: data.to_vec(),
|
||||||
|
fds,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
fn execute_method(
|
fn execute_method(
|
||||||
&self,
|
&self,
|
||||||
path: &str,
|
path: &str,
|
||||||
method: &str,
|
method: &str,
|
||||||
data: &[u8],
|
data: &[u8],
|
||||||
) -> Result<Vec<u8>, ScenegraphError> {
|
fds: Vec<OwnedFd>,
|
||||||
self.get_node(path)
|
response: oneshot::Sender<Result<(Vec<u8>, Vec<OwnedFd>), ScenegraphError>>,
|
||||||
.ok_or(ScenegraphError::NodeNotFound)?
|
) {
|
||||||
.execute_local_method(self.get_client(), method, data)
|
let Some(client) = self.get_client() else {
|
||||||
|
let _ = response.send(Err(ScenegraphError::MethodNotFound));
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
debug!(path, method, "Handle method");
|
||||||
|
let Some(node) = self.get_node(path) else {
|
||||||
|
let _ = response.send(Err(ScenegraphError::NodeNotFound));
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
node.execute_local_method(
|
||||||
|
client,
|
||||||
|
method,
|
||||||
|
Message {
|
||||||
|
data: data.to_vec(),
|
||||||
|
fds,
|
||||||
|
},
|
||||||
|
MethodResponseSender(response),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
22
src/core/task.rs
Normal file
22
src/core/task.rs
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
use color_eyre::eyre::Result;
|
||||||
|
use std::future::Future;
|
||||||
|
use tokio::task::JoinHandle;
|
||||||
|
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
pub fn new<
|
||||||
|
F: FnOnce() -> S,
|
||||||
|
S: AsRef<str>,
|
||||||
|
A: Future<Output = O> + Send + 'static,
|
||||||
|
O: Send + 'static,
|
||||||
|
>(
|
||||||
|
name_fn: F,
|
||||||
|
async_future: A,
|
||||||
|
) -> Result<JoinHandle<O>> {
|
||||||
|
#[cfg(not(feature = "profile_tokio"))]
|
||||||
|
let result = Ok(tokio::task::spawn(async_future));
|
||||||
|
#[cfg(feature = "profile_tokio")]
|
||||||
|
let result = tokio::task::Builder::new()
|
||||||
|
.name(name_fn().as_ref())
|
||||||
|
.spawn(async_future);
|
||||||
|
result
|
||||||
|
}
|
||||||
56
src/core/typed_datamap.rs
Normal file
56
src/core/typed_datamap.rs
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
#![allow(unused)]
|
||||||
|
|
||||||
|
use std::ops::{Deref, DerefMut};
|
||||||
|
|
||||||
|
use color_eyre::eyre::Result;
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use serde::{de::DeserializeOwned, Serialize};
|
||||||
|
use stardust_xr::schemas::{
|
||||||
|
flat::Datamap,
|
||||||
|
flex::flexbuffers::{FlexbufferSerializer, Reader, ReaderError},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::nodes::Message;
|
||||||
|
|
||||||
|
pub struct TypedDatamap<T: DeserializeOwned + Serialize>(T);
|
||||||
|
impl<T: DeserializeOwned + Serialize> TypedDatamap<T> {
|
||||||
|
pub fn new(data: T) -> Self {
|
||||||
|
TypedDatamap(data)
|
||||||
|
}
|
||||||
|
pub fn from_flex(message: Message) -> Result<Self> {
|
||||||
|
let root = Reader::get_root(message.as_ref())?;
|
||||||
|
T::deserialize(root).map(Self::new).map_err(|e| e.into())
|
||||||
|
}
|
||||||
|
pub fn to_datamap(&mut self) -> Result<Datamap> {
|
||||||
|
let mut serializer = FlexbufferSerializer::default();
|
||||||
|
self.0.serialize(&mut serializer)?;
|
||||||
|
Datamap::new(serializer.take_buffer()).map_err(|e| e.into())
|
||||||
|
}
|
||||||
|
pub fn serialize(&mut self) -> Option<Vec<u8>> {
|
||||||
|
let mut serializer = FlexbufferSerializer::default();
|
||||||
|
self.0.serialize(&mut serializer).ok()?;
|
||||||
|
// check if this is actually a map
|
||||||
|
Reader::get_root(serializer.view()).ok()?.get_map().ok()?;
|
||||||
|
Some(serializer.take_buffer())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T: DeserializeOwned + Serialize> Default for TypedDatamap<T>
|
||||||
|
where
|
||||||
|
T: Default,
|
||||||
|
{
|
||||||
|
fn default() -> Self {
|
||||||
|
Self(T::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T: DeserializeOwned + Serialize> Deref for TypedDatamap<T> {
|
||||||
|
type Target = T;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T: DeserializeOwned + Serialize> DerefMut for TypedDatamap<T> {
|
||||||
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||||
|
&mut self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
435
src/main.rs
435
src/main.rs
@@ -1,27 +1,42 @@
|
|||||||
mod core;
|
mod core;
|
||||||
mod nodes;
|
mod nodes;
|
||||||
mod objects;
|
mod objects;
|
||||||
|
#[cfg(feature = "wayland")]
|
||||||
mod wayland;
|
mod wayland;
|
||||||
|
|
||||||
use crate::core::destroy_queue;
|
use crate::core::client::CLIENTS;
|
||||||
use crate::nodes::{drawable, hmd, input};
|
use crate::core::client_state::ClientState;
|
||||||
|
use crate::core::{destroy_queue, buffers};
|
||||||
|
use crate::nodes::items::camera;
|
||||||
|
use crate::nodes::{audio, drawable, hmd, input};
|
||||||
|
use crate::objects::input::eye_pointer::EyePointer;
|
||||||
use crate::objects::input::mouse_pointer::MousePointer;
|
use crate::objects::input::mouse_pointer::MousePointer;
|
||||||
use crate::objects::input::sk_controller::SkController;
|
use crate::objects::input::sk_controller::SkController;
|
||||||
use crate::objects::input::sk_hand::SkHand;
|
use crate::objects::input::sk_hand::SkHand;
|
||||||
use crate::wayland::Wayland;
|
use crate::objects::play_space::PlaySpace;
|
||||||
|
|
||||||
use self::core::eventloop::EventLoop;
|
use self::core::eventloop::EventLoop;
|
||||||
use anyhow::Result;
|
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use directories::ProjectDirs;
|
use directories::ProjectDirs;
|
||||||
use slog::Drain;
|
use once_cell::sync::OnceCell;
|
||||||
|
use smithay::reexports::nix;
|
||||||
|
use stardust_xr::server;
|
||||||
|
use std::os::unix::process::CommandExt;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::process::{Command, Stdio};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use stereokit::input::Handed;
|
use std::time::Duration;
|
||||||
use stereokit::lifecycle::DepthMode;
|
use stereokit::{
|
||||||
use stereokit::render::SphericalHarmonics;
|
named_colors::BLACK, DepthMode, DisplayMode, Handed, LogLevel, StereoKitMultiThread,
|
||||||
use stereokit::texture::Texture;
|
TextureFormat, TextureType,
|
||||||
use stereokit::{lifecycle::DisplayMode, Settings};
|
};
|
||||||
|
use stereokit::{DisplayBlend, Sk};
|
||||||
|
use tokio::sync::Notify;
|
||||||
|
use tokio::task::LocalSet;
|
||||||
use tokio::{runtime::Handle, sync::oneshot};
|
use tokio::{runtime::Handle, sync::oneshot};
|
||||||
|
use tracing::metadata::LevelFilter;
|
||||||
|
use tracing::{debug_span, error, info};
|
||||||
|
use tracing_subscriber::{fmt, prelude::*, EnvFilter};
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[clap(author, version, about, long_about = None)]
|
#[clap(author, version, about, long_about = None)]
|
||||||
@@ -33,140 +48,346 @@ struct CliArgs {
|
|||||||
/// Run Stardust XR as an overlay with given priority
|
/// Run Stardust XR as an overlay with given priority
|
||||||
#[clap(id = "PRIORITY", short = 'o', long = "overlay", action)]
|
#[clap(id = "PRIORITY", short = 'o', long = "overlay", action)]
|
||||||
overlay_priority: Option<u32>,
|
overlay_priority: Option<u32>,
|
||||||
|
|
||||||
|
/// Don't create a tip input for controller because SOME RUNTIMES will lie
|
||||||
|
#[clap(long, action)]
|
||||||
|
disable_controller: bool,
|
||||||
|
|
||||||
|
/// Run a script when ready for clients to connect. If this is not set the script at $HOME/.config/stardust/startup will be ran if it exists.
|
||||||
|
#[clap(id = "PATH", short = 'e', long = "execute-startup-script", action)]
|
||||||
|
startup_script: Option<PathBuf>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> Result<()> {
|
static STARDUST_INSTANCE: OnceCell<String> = OnceCell::new();
|
||||||
let project_dirs = ProjectDirs::from("", "", "stardust").unwrap();
|
static SK_MULTITHREAD: OnceCell<Sk> = OnceCell::new();
|
||||||
let cli_args = Arc::new(CliArgs::parse());
|
static STOP_NOTIFIER: Notify = Notify::const_new();
|
||||||
let log = ::slog::Logger::root(::slog_stdlog::StdLog.fuse(), slog::o!());
|
|
||||||
slog_stdlog::init()?;
|
|
||||||
|
|
||||||
let mut stereokit = Settings::default()
|
struct EventLoopInfo {
|
||||||
.app_name("Stardust XR")
|
tokio_handle: Handle,
|
||||||
.overlay_app(cli_args.overlay_priority.is_some())
|
socket_path: PathBuf,
|
||||||
.overlay_priority(cli_args.overlay_priority.unwrap_or(u32::MAX))
|
}
|
||||||
.disable_desktop_input_window(true)
|
|
||||||
.display_preference(if cli_args.flatscreen {
|
fn main() {
|
||||||
|
ctrlc::set_handler(|| {
|
||||||
|
if atty::isnt(atty::Stream::Stdout) {
|
||||||
|
STOP_NOTIFIER.notify_waiters()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let registry = tracing_subscriber::registry();
|
||||||
|
|
||||||
|
#[cfg(feature = "profile_app")]
|
||||||
|
let registry = registry.with(tracing_tracy::TracyLayer::new().with_filter(LevelFilter::DEBUG));
|
||||||
|
|
||||||
|
#[cfg(feature = "profile_tokio")]
|
||||||
|
let (console_layer, _) = console_subscriber::ConsoleLayer::builder().build();
|
||||||
|
#[cfg(feature = "profile_tokio")]
|
||||||
|
let registry = registry.with(console_layer);
|
||||||
|
|
||||||
|
let log_layer = fmt::Layer::new()
|
||||||
|
.with_thread_names(true)
|
||||||
|
.with_ansi(true)
|
||||||
|
.with_line_number(true)
|
||||||
|
.with_filter(EnvFilter::from_default_env());
|
||||||
|
registry.with(log_layer).init();
|
||||||
|
|
||||||
|
let project_dirs = ProjectDirs::from("", "", "stardust");
|
||||||
|
if project_dirs.is_none() {
|
||||||
|
error!("Unable to get Stardust project directories, default skybox and startup script will not work.");
|
||||||
|
}
|
||||||
|
let cli_args = Arc::new(CliArgs::parse());
|
||||||
|
|
||||||
|
let sk = stereokit::Settings {
|
||||||
|
app_name: "Stardust XR".to_string(),
|
||||||
|
display_preference: if cli_args.flatscreen {
|
||||||
DisplayMode::Flatscreen
|
DisplayMode::Flatscreen
|
||||||
} else {
|
} else {
|
||||||
DisplayMode::MixedReality
|
DisplayMode::MixedReality
|
||||||
})
|
},
|
||||||
.depth_mode(DepthMode::D32)
|
blend_preference: DisplayBlend::AnyTransparent,
|
||||||
.init()
|
depth_mode: DepthMode::D32,
|
||||||
.expect("StereoKit failed to initialize");
|
log_filter: match EnvFilter::from_default_env().max_level_hint() {
|
||||||
println!("Init StereoKit");
|
Some(LevelFilter::ERROR) => LogLevel::Error,
|
||||||
|
Some(LevelFilter::WARN) => LogLevel::Warning,
|
||||||
|
Some(LevelFilter::INFO) => LogLevel::Inform,
|
||||||
|
Some(LevelFilter::DEBUG) => LogLevel::Diagnostic,
|
||||||
|
Some(LevelFilter::TRACE) => LogLevel::Diagnostic,
|
||||||
|
Some(LevelFilter::OFF) => LogLevel::None,
|
||||||
|
None => LogLevel::Warning,
|
||||||
|
},
|
||||||
|
overlay_app: cli_args.overlay_priority.is_some(),
|
||||||
|
overlay_priority: cli_args.overlay_priority.unwrap_or(u32::MAX),
|
||||||
|
disable_desktop_input_window: true,
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
.init()
|
||||||
|
.expect("StereoKit failed to initialize");
|
||||||
|
let _ = SK_MULTITHREAD.set(sk.multithreaded());
|
||||||
|
info!("Init StereoKit");
|
||||||
|
|
||||||
|
sk.material_set_shader(
|
||||||
|
sk.material_find("default/material_pbr").unwrap(),
|
||||||
|
sk.shader_find("default/shader_pbr_clip").unwrap(),
|
||||||
|
);
|
||||||
|
|
||||||
// Skytex/light stuff
|
// Skytex/light stuff
|
||||||
{
|
{
|
||||||
let skytex_path = project_dirs.config_dir().join("skytex.hdr");
|
if let Some((light, tex)) = project_dirs
|
||||||
if let Some((tex, light)) = skytex_path
|
.as_ref()
|
||||||
.exists()
|
.and_then(|dirs| {
|
||||||
.then(|| Texture::from_cubemap_equirectangular(&stereokit, &skytex_path, true, 100))
|
let skytex_path = dirs.config_dir().join("skytex.hdr");
|
||||||
|
skytex_path
|
||||||
|
.exists()
|
||||||
|
.then(|| sk.tex_create_cubemap_file(&skytex_path, true, 100).ok())
|
||||||
|
})
|
||||||
.flatten()
|
.flatten()
|
||||||
{
|
{
|
||||||
stereokit.set_skytex(&tex);
|
sk.render_set_skytex(&tex);
|
||||||
stereokit.set_skylight(&light);
|
sk.render_set_skylight(light);
|
||||||
} else if let Some(tex) = Texture::cubemap_from_spherical_harmonics(
|
} else {
|
||||||
&stereokit,
|
sk.render_set_skytex(sk.tex_gen_color(
|
||||||
&SphericalHarmonics::default(),
|
BLACK,
|
||||||
16,
|
1,
|
||||||
0.0,
|
1,
|
||||||
0.0,
|
TextureType::CUBEMAP,
|
||||||
) {
|
TextureFormat::RGBA32,
|
||||||
stereokit.set_skytex(&tex);
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mouse_pointer = cli_args.flatscreen.then(MousePointer::new);
|
let mut mouse_pointer = cli_args
|
||||||
let mut hands =
|
.flatscreen
|
||||||
(!cli_args.flatscreen).then(|| [SkHand::new(Handed::Left), SkHand::new(Handed::Right)]);
|
.then(MousePointer::new)
|
||||||
let mut controllers = (!cli_args.flatscreen).then(|| {
|
.transpose()
|
||||||
[
|
.unwrap();
|
||||||
SkController::new(Handed::Left),
|
let mut hands = (!cli_args.flatscreen)
|
||||||
SkController::new(Handed::Right),
|
.then(|| {
|
||||||
]
|
let left = SkHand::new(Handed::Left).ok();
|
||||||
});
|
let right = SkHand::new(Handed::Right).ok();
|
||||||
|
left.zip(right)
|
||||||
|
})
|
||||||
|
.flatten();
|
||||||
|
let mut controllers = (!cli_args.flatscreen && !cli_args.disable_controller)
|
||||||
|
.then(|| {
|
||||||
|
let left = SkController::new(&sk, Handed::Left).ok();
|
||||||
|
let right = SkController::new(&sk, Handed::Right).ok();
|
||||||
|
left.zip(right)
|
||||||
|
})
|
||||||
|
.flatten();
|
||||||
|
let eye_pointer = (sk.active_display_mode() == DisplayMode::MixedReality
|
||||||
|
&& sk.device_has_eye_gaze())
|
||||||
|
.then(EyePointer::new)
|
||||||
|
.transpose()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
if hands.is_none() {
|
if hands.is_none() {
|
||||||
unsafe {
|
sk.input_hand_visible(Handed::Left, false);
|
||||||
stereokit::sys::input_hand_visible(stereokit::sys::handed__handed_left, false as i32);
|
sk.input_hand_visible(Handed::Right, false);
|
||||||
stereokit::sys::input_hand_visible(stereokit::sys::handed__handed_right, false as i32);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let (event_stop_tx, event_stop_rx) = oneshot::channel::<()>();
|
let play_space = sk
|
||||||
let (handle_sender, handle_receiver) = oneshot::channel::<Handle>();
|
.world_has_bounds()
|
||||||
|
.then(|| PlaySpace::new().ok())
|
||||||
|
.flatten();
|
||||||
|
|
||||||
|
let (info_sender, info_receiver) = oneshot::channel::<EventLoopInfo>();
|
||||||
let event_thread = std::thread::Builder::new()
|
let event_thread = std::thread::Builder::new()
|
||||||
.name("event_loop".to_owned())
|
.name("event_loop".to_owned())
|
||||||
.spawn(move || event_loop(handle_sender, event_stop_rx))?;
|
.spawn(move || event_loop(info_sender))
|
||||||
let _tokio_handle = handle_receiver.blocking_recv()?.enter();
|
.unwrap();
|
||||||
|
let event_loop_info = info_receiver.blocking_recv().unwrap();
|
||||||
|
let _tokio_handle = event_loop_info.tokio_handle.enter();
|
||||||
|
|
||||||
let mut wayland = Wayland::new(log)?;
|
let mut buffer_manager = buffers::BufferManager::new().expect("Could not initialize buffer manager");
|
||||||
println!("Stardust ready!");
|
|
||||||
stereokit.run(
|
|
||||||
|sk, draw_ctx| {
|
|
||||||
hmd::frame(sk);
|
|
||||||
wayland.frame(sk);
|
|
||||||
destroy_queue::clear();
|
|
||||||
|
|
||||||
if let Some(mouse_pointer) = &mouse_pointer {
|
#[cfg(feature = "wayland")]
|
||||||
mouse_pointer.update(sk);
|
let mut wayland = wayland::Wayland::new(&buffer_manager).expect("Could not initialize wayland");
|
||||||
|
info!("Stardust ready!");
|
||||||
|
|
||||||
|
let mut startup_child = (|| {
|
||||||
|
let project_dirs = project_dirs.as_ref()?;
|
||||||
|
let startup_script_path = cli_args
|
||||||
|
.startup_script
|
||||||
|
.clone()
|
||||||
|
.and_then(|p| p.canonicalize().ok())
|
||||||
|
.unwrap_or_else(|| project_dirs.config_dir().join("startup"));
|
||||||
|
let mut startup_command = Command::new("bash");
|
||||||
|
startup_command.arg(startup_script_path);
|
||||||
|
startup_command.arg("&");
|
||||||
|
|
||||||
|
startup_command.stdin(Stdio::null());
|
||||||
|
startup_command.stdout(Stdio::null());
|
||||||
|
startup_command.stderr(Stdio::null());
|
||||||
|
startup_command.env(
|
||||||
|
"FLAT_WAYLAND_DISPLAY",
|
||||||
|
std::env::var_os("WAYLAND_DISPLAY").unwrap_or_default(),
|
||||||
|
);
|
||||||
|
startup_command.env(
|
||||||
|
"STARDUST_INSTANCE",
|
||||||
|
event_loop_info
|
||||||
|
.socket_path
|
||||||
|
.file_name()
|
||||||
|
.expect("Stardust socket path not found"),
|
||||||
|
);
|
||||||
|
#[cfg(feature = "wayland")]
|
||||||
|
{
|
||||||
|
if let Some(wayland_socket) = wayland.socket_name.as_ref() {
|
||||||
|
startup_command.env("WAYLAND_DISPLAY", &wayland_socket);
|
||||||
}
|
}
|
||||||
if let Some(hands) = &mut hands {
|
#[cfg(feature = "xwayland")]
|
||||||
hands[0].update(sk);
|
startup_command.env("DISPLAY", format!(":{}", wayland.xwayland_state.display));
|
||||||
hands[1].update(sk);
|
startup_command.env("GDK_BACKEND", "wayland");
|
||||||
}
|
startup_command.env("QT_QPA_PLATFORM", "wayland");
|
||||||
if let Some(controllers) = &mut controllers {
|
startup_command.env("MOZ_ENABLE_WAYLAND", "1");
|
||||||
controllers[0].update(sk);
|
startup_command.env("CLUTTER_BACKEND", "wayland");
|
||||||
controllers[1].update(sk);
|
startup_command.env("SDL_VIDEODRIVER", "wayland");
|
||||||
}
|
}
|
||||||
input::process_input();
|
unsafe {
|
||||||
nodes::root::Root::logic_step(sk.time_elapsed());
|
startup_command.pre_exec(|| {
|
||||||
drawable::draw(sk, draw_ctx);
|
nix::unistd::setsid()
|
||||||
|
.map(|_| ())
|
||||||
|
.map_err(|_| std::io::ErrorKind::Other.into())
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let child = startup_command.spawn().ok()?;
|
||||||
|
Some(child)
|
||||||
|
})();
|
||||||
|
|
||||||
wayland.make_context_current();
|
let mut last_frame_delta = Duration::ZERO;
|
||||||
},
|
let mut sleep_duration = Duration::ZERO;
|
||||||
|_| {
|
debug_span!("StereoKit").in_scope(|| {
|
||||||
println!("Cleanly shut down StereoKit");
|
sk.run(
|
||||||
},
|
|sk| {
|
||||||
);
|
let _span = debug_span!("StereoKit step");
|
||||||
|
let _span = _span.enter();
|
||||||
|
|
||||||
|
camera::send_rendered();
|
||||||
|
hmd::frame(sk);
|
||||||
|
#[cfg(feature = "wayland")]
|
||||||
|
wayland.frame_event(sk);
|
||||||
|
destroy_queue::clear();
|
||||||
|
|
||||||
|
if let Some(mouse_pointer) = &mut mouse_pointer {
|
||||||
|
mouse_pointer.update(sk);
|
||||||
|
}
|
||||||
|
if let Some((left_hand, right_hand)) = &mut hands {
|
||||||
|
left_hand.update(!cli_args.disable_controller, sk);
|
||||||
|
right_hand.update(!cli_args.disable_controller, sk);
|
||||||
|
}
|
||||||
|
if let Some((left_controller, right_controller)) = &mut controllers {
|
||||||
|
left_controller.update(sk);
|
||||||
|
right_controller.update(sk);
|
||||||
|
}
|
||||||
|
if let Some(eye_pointer) = &eye_pointer {
|
||||||
|
eye_pointer.update(sk);
|
||||||
|
}
|
||||||
|
if let Some(play_space) = &play_space {
|
||||||
|
play_space.update(sk);
|
||||||
|
}
|
||||||
|
input::process_input();
|
||||||
|
nodes::root::Root::send_frame_events(sk.time_elapsed_unscaled());
|
||||||
|
adaptive_sleep(
|
||||||
|
sk,
|
||||||
|
&mut last_frame_delta,
|
||||||
|
&mut sleep_duration,
|
||||||
|
Duration::from_micros(250),
|
||||||
|
);
|
||||||
|
|
||||||
|
#[cfg(feature = "wayland")]
|
||||||
|
wayland.update(sk, &mut buffer_manager);
|
||||||
|
drawable::draw(sk);
|
||||||
|
audio::update(sk);
|
||||||
|
|
||||||
|
buffer_manager.make_context_current();
|
||||||
|
|
||||||
|
camera::update(sk, &mut buffer_manager);
|
||||||
|
},
|
||||||
|
|_sk| {
|
||||||
|
info!("Cleanly shut down StereoKit");
|
||||||
|
|
||||||
|
if let Some(mut startup_child) = startup_child.take() {
|
||||||
|
let _ = startup_child.kill();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
#[cfg(feature = "wayland")]
|
||||||
drop(wayland);
|
drop(wayland);
|
||||||
|
|
||||||
let _ = event_stop_tx.send(());
|
STOP_NOTIFIER.notify_waiters();
|
||||||
event_thread
|
event_thread
|
||||||
.join()
|
.join()
|
||||||
.expect("Failed to cleanly shut down event loop")?;
|
.expect("Failed to cleanly shut down event loop")
|
||||||
println!("Cleanly shut down Stardust");
|
.unwrap();
|
||||||
Ok(())
|
|
||||||
|
info!("Cleanly shut down Stardust");
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[tokio::main]
|
fn adaptive_sleep(
|
||||||
#[tokio::main(flavor = "current_thread")]
|
sk: &impl StereoKitMultiThread,
|
||||||
async fn event_loop(
|
last_frame_delta: &mut Duration,
|
||||||
handle_sender: oneshot::Sender<Handle>,
|
sleep_duration: &mut Duration,
|
||||||
stop_rx: oneshot::Receiver<()>,
|
sleep_duration_increase: Duration,
|
||||||
) -> anyhow::Result<()> {
|
) {
|
||||||
let _ = handle_sender.send(Handle::current());
|
let frame_delta = Duration::from_secs_f64(sk.time_elapsed_unscaled());
|
||||||
// console_subscriber::init();
|
if *last_frame_delta < frame_delta {
|
||||||
|
if let Some(frame_delta_delta) = frame_delta.checked_sub(*last_frame_delta) {
|
||||||
|
if let Some(new_sleep_duration) = sleep_duration.checked_sub(frame_delta_delta) {
|
||||||
|
*sleep_duration = new_sleep_duration;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
*sleep_duration += sleep_duration_increase;
|
||||||
|
}
|
||||||
|
|
||||||
let (event_loop, event_loop_join_handle) =
|
debug_span!("Sleep", ?sleep_duration, ?frame_delta, ?last_frame_delta).in_scope(|| {
|
||||||
EventLoop::new().expect("Couldn't create server socket");
|
*last_frame_delta = frame_delta;
|
||||||
println!("Init event loop");
|
std::thread::sleep(*sleep_duration); // to give clients a chance to even update anything before drawing
|
||||||
println!("Stardust socket created at {}", event_loop.socket_path);
|
});
|
||||||
|
}
|
||||||
|
|
||||||
let result = tokio::select! {
|
#[tokio::main]
|
||||||
biased;
|
// #[tokio::main(flavor = "current_thread")]
|
||||||
_ = tokio::signal::ctrl_c() => Ok(()),
|
async fn event_loop(info_sender: oneshot::Sender<EventLoopInfo>) -> color_eyre::eyre::Result<()> {
|
||||||
_ = stop_rx => Ok(()),
|
let socket_path =
|
||||||
e = event_loop_join_handle => e?,
|
server::get_free_socket_path().expect("Unable to find a free stardust socket path");
|
||||||
};
|
STARDUST_INSTANCE.set(socket_path.file_name().unwrap().to_string_lossy().into_owned()).expect("Someone hasn't done their job, yell at Nova because how is this set multiple times what the hell");
|
||||||
|
let _event_loop = EventLoop::new(socket_path.clone()).expect("Couldn't create server socket");
|
||||||
|
info!("Init event loop");
|
||||||
|
info!(
|
||||||
|
socket_path = ?socket_path.display(),
|
||||||
|
"Stardust socket created"
|
||||||
|
);
|
||||||
|
let _ = info_sender.send(EventLoopInfo {
|
||||||
|
tokio_handle: Handle::current(),
|
||||||
|
socket_path,
|
||||||
|
});
|
||||||
|
|
||||||
println!("Cleanly shut down event loop");
|
STOP_NOTIFIER.notified().await;
|
||||||
|
println!("Stopping...");
|
||||||
|
save_clients().await;
|
||||||
|
|
||||||
|
info!("Cleanly shut down event loop");
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
stereokit::sys::sk_quit();
|
stereokit::sys::sk_quit();
|
||||||
}
|
}
|
||||||
|
|
||||||
result
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn save_clients() {
|
||||||
|
let local_set = LocalSet::new();
|
||||||
|
for client in CLIENTS.get_vec() {
|
||||||
|
local_set.spawn_local(async move {
|
||||||
|
tokio::select! {
|
||||||
|
biased;
|
||||||
|
s = client.save_state() => {s.map(ClientState::to_file);},
|
||||||
|
_ = tokio::time::sleep(Duration::from_millis(100)) => (),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
local_set.await;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,38 +1,49 @@
|
|||||||
use crate::core::client::Client;
|
|
||||||
|
|
||||||
use super::Node;
|
use super::Node;
|
||||||
|
use crate::core::client::Client;
|
||||||
|
use color_eyre::eyre::{ensure, Result};
|
||||||
|
use portable_atomic::AtomicBool;
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::{Arc, Weak};
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone)]
|
#[derive(Debug, Default, Clone)]
|
||||||
pub struct AliasInfo {
|
pub struct AliasInfo {
|
||||||
pub(super) local_signals: Vec<&'static str>,
|
pub(super) server_signals: Vec<&'static str>,
|
||||||
pub(super) local_methods: Vec<&'static str>,
|
pub(super) server_methods: Vec<&'static str>,
|
||||||
pub(super) remote_signals: Vec<&'static str>,
|
pub(super) client_signals: Vec<&'static str>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub struct Alias {
|
pub struct Alias {
|
||||||
|
pub enabled: Arc<AtomicBool>,
|
||||||
pub(super) node: Weak<Node>,
|
pub(super) node: Weak<Node>,
|
||||||
pub original: Weak<Node>,
|
pub original: Weak<Node>,
|
||||||
|
|
||||||
pub info: AliasInfo,
|
pub info: AliasInfo,
|
||||||
}
|
}
|
||||||
impl Alias {
|
impl Alias {
|
||||||
pub fn new(
|
pub fn create(
|
||||||
client: &Arc<Client>,
|
client: &Arc<Client>,
|
||||||
parent: &str,
|
parent: &str,
|
||||||
name: &str,
|
name: &str,
|
||||||
original: &Arc<Node>,
|
original: &Arc<Node>,
|
||||||
info: AliasInfo,
|
info: AliasInfo,
|
||||||
) -> Arc<Node> {
|
) -> Result<Arc<Node>> {
|
||||||
let node = Node::create(client, parent, name, true).add_to_scenegraph();
|
ensure!(
|
||||||
|
client
|
||||||
|
.scenegraph
|
||||||
|
.get_node(&(parent.to_string() + "/" + name))
|
||||||
|
.is_none(),
|
||||||
|
"Node already exists"
|
||||||
|
);
|
||||||
|
|
||||||
|
let node = Node::create(client, parent, name, true).add_to_scenegraph()?;
|
||||||
let alias = Alias {
|
let alias = Alias {
|
||||||
|
enabled: Arc::new(AtomicBool::new(true)),
|
||||||
node: Arc::downgrade(&node),
|
node: Arc::downgrade(&node),
|
||||||
original: Arc::downgrade(original),
|
original: Arc::downgrade(original),
|
||||||
info,
|
info,
|
||||||
};
|
};
|
||||||
let alias = original.aliases.add(alias);
|
let alias = original.aliases.add(alias);
|
||||||
let _ = node.alias.set(alias);
|
let _ = node.alias.set(alias);
|
||||||
node
|
Ok(node)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
136
src/nodes/audio.rs
Normal file
136
src/nodes/audio.rs
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
use super::{Message, Node};
|
||||||
|
use crate::core::client::Client;
|
||||||
|
use crate::core::destroy_queue;
|
||||||
|
use crate::core::registry::Registry;
|
||||||
|
use crate::core::resource::ResourceID;
|
||||||
|
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||||
|
use color_eyre::eyre::{ensure, eyre, Result};
|
||||||
|
use glam::{vec3, Vec4Swizzles};
|
||||||
|
use once_cell::sync::OnceCell;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use send_wrapper::SendWrapper;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use stardust_xr::schemas::flex::deserialize;
|
||||||
|
use stardust_xr::values::Transform;
|
||||||
|
use std::ops::DerefMut;
|
||||||
|
use std::{ffi::OsStr, path::PathBuf, sync::Arc};
|
||||||
|
use stereokit::{Sound as SkSound, SoundInstance, StereoKitDraw};
|
||||||
|
|
||||||
|
static SOUND_REGISTRY: Registry<Sound> = Registry::new();
|
||||||
|
|
||||||
|
pub struct Sound {
|
||||||
|
space: Arc<Spatial>,
|
||||||
|
|
||||||
|
volume: f32,
|
||||||
|
pending_audio_path: PathBuf,
|
||||||
|
sk_sound: OnceCell<SendWrapper<SkSound>>,
|
||||||
|
instance: Mutex<Option<SoundInstance>>,
|
||||||
|
stop: Mutex<Option<()>>,
|
||||||
|
play: Mutex<Option<()>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sound {
|
||||||
|
pub fn add_to(node: &Arc<Node>, resource_id: ResourceID) -> Result<Arc<Sound>> {
|
||||||
|
ensure!(
|
||||||
|
node.spatial.get().is_some(),
|
||||||
|
"Internal: Node does not have a spatial attached!"
|
||||||
|
);
|
||||||
|
let pending_audio_path = resource_id
|
||||||
|
.get_file(
|
||||||
|
&node
|
||||||
|
.get_client()
|
||||||
|
.ok_or_else(|| eyre!("Client not found"))?
|
||||||
|
.base_resource_prefixes
|
||||||
|
.lock()
|
||||||
|
.clone(),
|
||||||
|
&[OsStr::new("wav"), OsStr::new("mp3")],
|
||||||
|
)
|
||||||
|
.ok_or_else(|| eyre!("Resource not found"))?;
|
||||||
|
let sound = Sound {
|
||||||
|
space: node.spatial.get().unwrap().clone(),
|
||||||
|
volume: 1.0,
|
||||||
|
pending_audio_path,
|
||||||
|
sk_sound: OnceCell::new(),
|
||||||
|
instance: Mutex::new(None),
|
||||||
|
stop: Mutex::new(None),
|
||||||
|
play: Mutex::new(None),
|
||||||
|
};
|
||||||
|
let sound_arc = SOUND_REGISTRY.add(sound);
|
||||||
|
node.add_local_signal("play", Sound::play_flex);
|
||||||
|
node.add_local_signal("stop", Sound::stop_flex);
|
||||||
|
let _ = node.sound.set(sound_arc.clone());
|
||||||
|
Ok(sound_arc)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update(&self, sk: &impl StereoKitDraw) {
|
||||||
|
let sound = self.sk_sound.get_or_init(|| {
|
||||||
|
SendWrapper::new(sk.sound_create(self.pending_audio_path.clone()).unwrap())
|
||||||
|
});
|
||||||
|
if self.stop.lock().take().is_some() {
|
||||||
|
if let Some(instance) = self.instance.lock().take() {
|
||||||
|
sk.sound_inst_stop(instance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.play.lock().is_some() && self.instance.lock().is_none() {
|
||||||
|
self.instance.lock().replace(sk.sound_play(
|
||||||
|
sound.as_ref(),
|
||||||
|
vec3(0.0, 0.0, 0.0),
|
||||||
|
self.volume,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(instance) = self.instance.lock().deref_mut() {
|
||||||
|
sk.sound_inst_set_pos(*instance, self.space.global_transform().w_axis.xyz());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn play_flex(node: &Node, _calling_client: Arc<Client>, _message: Message) -> Result<()> {
|
||||||
|
let sound = node.sound.get().unwrap();
|
||||||
|
sound.play.lock().replace(());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop_flex(node: &Node, _calling_client: Arc<Client>, _message: Message) -> Result<()> {
|
||||||
|
let sound = node.sound.get().unwrap();
|
||||||
|
sound.stop.lock().replace(());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(sk: &impl StereoKitDraw) {
|
||||||
|
for sound in SOUND_REGISTRY.get_valid_contents() {
|
||||||
|
sound.update(sk)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_interface(client: &Arc<Client>) -> Result<()> {
|
||||||
|
let node = Node::create(client, "", "audio", false);
|
||||||
|
node.add_local_signal("create_sound", create_flex);
|
||||||
|
node.add_to_scenegraph().map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_flex(_node: &Node, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct CreateSoundInfo<'a> {
|
||||||
|
name: &'a str,
|
||||||
|
parent_path: &'a str,
|
||||||
|
transform: Transform,
|
||||||
|
resource: ResourceID,
|
||||||
|
}
|
||||||
|
let info: CreateSoundInfo = deserialize(message.as_ref())?;
|
||||||
|
let node = Node::create(&calling_client, "/audio/sound", info.name, true);
|
||||||
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
|
let transform = parse_transform(info.transform, true, true, true);
|
||||||
|
let node = node.add_to_scenegraph()?;
|
||||||
|
Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
|
Sound::add_to(&node, info.resource)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Sound {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(instance) = self.instance.lock().take() {
|
||||||
|
destroy_queue::add(instance);
|
||||||
|
}
|
||||||
|
SOUND_REGISTRY.remove(self);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,29 +1,48 @@
|
|||||||
use super::alias::AliasInfo;
|
use super::alias::AliasInfo;
|
||||||
use super::fields::Field;
|
use super::fields::Field;
|
||||||
use super::spatial::{parse_transform, Spatial};
|
use super::spatial::{parse_transform, Spatial};
|
||||||
use super::{Alias, Node};
|
use super::{Alias, Message, Node};
|
||||||
use crate::core::client::Client;
|
use crate::core::client::Client;
|
||||||
use crate::core::nodelist::LifeLinkedNodeList;
|
use crate::core::node_collections::LifeLinkedNodeMap;
|
||||||
use crate::core::registry::Registry;
|
use crate::core::registry::Registry;
|
||||||
use crate::nodes::fields::find_field;
|
use crate::core::scenegraph::MethodResponseSender;
|
||||||
|
use crate::nodes::fields::{find_field, FIELD_ALIAS_INFO};
|
||||||
use crate::nodes::spatial::find_spatial_parent;
|
use crate::nodes::spatial::find_spatial_parent;
|
||||||
use anyhow::{anyhow, ensure, Result};
|
use color_eyre::eyre::{bail, ensure, eyre, Result};
|
||||||
use glam::vec3a;
|
use glam::vec3a;
|
||||||
|
use lazy_static::lazy_static;
|
||||||
|
use mint::{Quaternion, Vector3};
|
||||||
|
use nanoid::nanoid;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use serde::Deserialize;
|
use rustc_hash::FxHashMap;
|
||||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use stardust_xr::schemas::flex::{deserialize, flexbuffers, serialize};
|
||||||
use stardust_xr::values::Transform;
|
use stardust_xr::values::Transform;
|
||||||
|
use std::fmt::Display;
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::{Arc, Weak};
|
||||||
|
|
||||||
static PULSE_SENDER_REGISTRY: Registry<PulseSender> = Registry::new();
|
lazy_static! {
|
||||||
static PULSE_RECEIVER_REGISTRY: Registry<PulseReceiver> = Registry::new();
|
pub static ref KEYMAPS: Mutex<FxHashMap<String, String>> = Mutex::new(FxHashMap::default());
|
||||||
|
}
|
||||||
|
|
||||||
fn mask_matches(mask_map_lesser: &Mask, mask_map_greater: &Mask) -> bool {
|
static PULSE_SENDER_REGISTRY: Registry<PulseSender> = Registry::new();
|
||||||
|
pub static PULSE_RECEIVER_REGISTRY: Registry<PulseReceiver> = Registry::new();
|
||||||
|
|
||||||
|
pub fn mask_matches(mask_map_lesser: &Mask, mask_map_greater: &Mask) -> bool {
|
||||||
(|| -> Result<_> {
|
(|| -> Result<_> {
|
||||||
for key in mask_map_lesser.get_mask()?.iter_keys() {
|
for key in mask_map_lesser.get_mask()?.iter_keys() {
|
||||||
let lesser_key_type = mask_map_lesser.get_mask()?.index(key)?.flexbuffer_type();
|
let lesser_key = mask_map_lesser.get_mask()?.index(key)?;
|
||||||
let greater_key_type = mask_map_greater.get_mask()?.index(key)?.flexbuffer_type();
|
let greater_key = mask_map_greater.get_mask()?.index(key)?;
|
||||||
if lesser_key_type != greater_key_type {
|
// otherwise zero-length vectors don't count the same as a single type vector
|
||||||
|
if lesser_key.flexbuffer_type().is_heterogenous_vector()
|
||||||
|
&& lesser_key.as_vector().len() == 0
|
||||||
|
&& greater_key.flexbuffer_type().is_vector()
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !lesser_key.flexbuffer_type().is_null()
|
||||||
|
&& lesser_key.flexbuffer_type() != greater_key.flexbuffer_type()
|
||||||
|
{
|
||||||
return Err(flexbuffers::ReaderError::InvalidPackedType {}.into());
|
return Err(flexbuffers::ReaderError::InvalidPackedType {}.into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -32,120 +51,155 @@ fn mask_matches(mask_map_lesser: &Mask, mask_map_greater: &Mask) -> bool {
|
|||||||
.is_ok()
|
.is_ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
type MaskMapGetFn = fn(&[u8]) -> Result<flexbuffers::MapReader<&[u8]>>;
|
pub struct Mask(pub Vec<u8>);
|
||||||
pub struct Mask {
|
|
||||||
binary: Vec<u8>,
|
|
||||||
get_fn: MaskMapGetFn,
|
|
||||||
}
|
|
||||||
impl Mask {
|
impl Mask {
|
||||||
|
pub fn from_struct<T: Default + Serialize>() -> Self {
|
||||||
|
let mut serializer = flexbuffers::FlexbufferSerializer::new();
|
||||||
|
T::default().serialize(&mut serializer).unwrap();
|
||||||
|
Mask(serializer.take_buffer())
|
||||||
|
}
|
||||||
pub fn get_mask(&self) -> Result<flexbuffers::MapReader<&[u8]>> {
|
pub fn get_mask(&self) -> Result<flexbuffers::MapReader<&[u8]>> {
|
||||||
(self.get_fn)(self.binary.as_slice())
|
flexbuffers::Reader::get_root(self.0.as_slice())
|
||||||
}
|
.map_err(|_| eyre!("Mask is not a valid flexbuffer"))?
|
||||||
pub fn set_mask(&mut self, binary: Vec<u8>, get_fn: MaskMapGetFn) {
|
.get_map()
|
||||||
self.binary = binary;
|
.map_err(|_| eyre!("Mask is not a valid map"))
|
||||||
self.get_fn = get_fn;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Default for Mask {
|
impl Display for Mask {
|
||||||
fn default() -> Self {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
Mask {
|
flexbuffers::Reader::get_root(self.0.as_slice())
|
||||||
binary: Default::default(),
|
.unwrap()
|
||||||
get_fn: mask_get_err,
|
.to_string()
|
||||||
}
|
.fmt(f)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn mask_get_err(_binary: &[u8]) -> Result<flexbuffers::MapReader<&[u8]>> {
|
|
||||||
Err(anyhow!("You need to call setMask to set the mask!"))
|
|
||||||
}
|
|
||||||
fn mask_get_map_at_root(binary: &[u8]) -> Result<flexbuffers::MapReader<&[u8]>> {
|
|
||||||
flexbuffers::Reader::get_root(binary)
|
|
||||||
.map_err(|_| anyhow!("Mask is not a valid flexbuffer"))?
|
|
||||||
.get_map()
|
|
||||||
.map_err(|_| anyhow!("Mask is not a valid map"))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct SendDataInfo<'a> {
|
||||||
|
uid: &'a str,
|
||||||
|
data: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct PulseSender {
|
pub struct PulseSender {
|
||||||
mask: Mutex<Mask>,
|
uid: String,
|
||||||
aliases: LifeLinkedNodeList,
|
node: Weak<Node>,
|
||||||
|
pub mask: Mask,
|
||||||
|
aliases: LifeLinkedNodeMap<String>,
|
||||||
}
|
}
|
||||||
impl PulseSender {
|
impl PulseSender {
|
||||||
pub fn add_to(node: &Arc<Node>) -> Result<()> {
|
pub fn add_to(node: &Arc<Node>, mask: Mask) -> Result<Arc<PulseSender>> {
|
||||||
ensure!(
|
ensure!(
|
||||||
node.spatial.get().is_some(),
|
node.spatial.get().is_some(),
|
||||||
"Internal: Node does not have a spatial attached!"
|
"Internal: Node does not have a spatial attached!"
|
||||||
);
|
);
|
||||||
|
|
||||||
let sender = Default::default();
|
let sender = PulseSender {
|
||||||
|
uid: nanoid!(),
|
||||||
|
node: Arc::downgrade(node),
|
||||||
|
mask,
|
||||||
|
aliases: LifeLinkedNodeMap::default(),
|
||||||
|
};
|
||||||
let sender = PULSE_SENDER_REGISTRY.add(sender);
|
let sender = PULSE_SENDER_REGISTRY.add(sender);
|
||||||
let _ = node.pulse_sender.set(sender);
|
let _ = node.pulse_sender.set(sender.clone());
|
||||||
node.add_local_signal("setMask", PulseSender::set_mask_flex);
|
node.add_local_signal("send_data", PulseSender::send_data_flex);
|
||||||
node.add_local_method("getReceivers", PulseSender::get_receivers_flex);
|
for receiver in PULSE_RECEIVER_REGISTRY.get_valid_contents() {
|
||||||
Ok(())
|
sender.handle_new_receiver(&receiver);
|
||||||
|
}
|
||||||
|
Ok(sender.clone())
|
||||||
}
|
}
|
||||||
pub fn set_mask_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
fn handle_new_receiver(&self, receiver: &PulseReceiver) {
|
||||||
ensure!(
|
if !mask_matches(&self.mask, &receiver.mask) {
|
||||||
node.pulse_sender.get().is_some(),
|
return;
|
||||||
"Internal: Node does not have a pulse sender aspect"
|
}
|
||||||
|
let Some(tx_node) = self.node.upgrade() else {return};
|
||||||
|
let Some(tx_client) = tx_node.get_client() else {return};
|
||||||
|
let Some(rx_node) = receiver.node.upgrade() else {return};
|
||||||
|
// Receiver itself
|
||||||
|
let rx_alias = Alias::create(
|
||||||
|
&tx_client,
|
||||||
|
tx_node.get_path(),
|
||||||
|
receiver.uid.as_str(),
|
||||||
|
&rx_node,
|
||||||
|
AliasInfo {
|
||||||
|
server_methods: vec!["sendData", "getTransform"],
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
);
|
);
|
||||||
node.pulse_sender
|
if let Ok(rx_alias) = rx_alias {
|
||||||
.get()
|
self.aliases.add(receiver.uid.clone(), &rx_alias);
|
||||||
.unwrap()
|
|
||||||
.mask
|
if let Some(rx_field_node) = receiver.field.spatial_ref().node.upgrade() {
|
||||||
.lock()
|
// Receiver's field
|
||||||
.set_mask(data.to_vec(), mask_get_map_at_root);
|
let rx_field_alias = Alias::create(
|
||||||
Ok(())
|
&tx_client,
|
||||||
}
|
rx_alias.get_path(),
|
||||||
fn get_receivers_flex(
|
"field",
|
||||||
node: &Node,
|
&rx_field_node,
|
||||||
calling_client: Arc<Client>,
|
FIELD_ALIAS_INFO.clone(),
|
||||||
_data: &[u8],
|
|
||||||
) -> Result<Vec<u8>> {
|
|
||||||
let sender_spatial = node
|
|
||||||
.spatial
|
|
||||||
.get()
|
|
||||||
.ok_or_else(|| anyhow!("Node does not have a spatial aspect!"))?;
|
|
||||||
let sender = node
|
|
||||||
.pulse_sender
|
|
||||||
.get()
|
|
||||||
.ok_or_else(|| anyhow!("Node does not have a sender aspect!"))?;
|
|
||||||
let valid_receivers = PULSE_RECEIVER_REGISTRY.get_valid_contents();
|
|
||||||
let mut distance_sorted_receivers: Vec<(f32, &PulseReceiver)> = valid_receivers
|
|
||||||
.iter()
|
|
||||||
.filter(|receiver| receiver.get_field().is_some())
|
|
||||||
.filter(|receiver| mask_matches(&*sender.mask.lock(), &*receiver.mask.lock()))
|
|
||||||
.map(|receiver| {
|
|
||||||
(
|
|
||||||
receiver
|
|
||||||
.get_field()
|
|
||||||
.unwrap()
|
|
||||||
.distance(sender_spatial, vec3a(0_f32, 0_f32, 0_f32)),
|
|
||||||
receiver.as_ref(),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
distance_sorted_receivers.sort_by(|(d1, _), (d2, _)| d1.partial_cmp(d2).unwrap());
|
|
||||||
sender.aliases.clear();
|
|
||||||
let uids: Vec<String> = distance_sorted_receivers
|
|
||||||
.into_iter()
|
|
||||||
.map(|(_, receiver)| {
|
|
||||||
let receiver_alias = Alias::new(
|
|
||||||
&calling_client,
|
|
||||||
node.get_path(),
|
|
||||||
receiver.uid.as_str(),
|
|
||||||
receiver.node.upgrade().as_ref().unwrap(),
|
|
||||||
AliasInfo {
|
|
||||||
local_methods: vec!["sendData"],
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
);
|
);
|
||||||
sender.aliases.add(Arc::downgrade(&receiver_alias));
|
if let Ok(rx_field_alias) = rx_field_alias {
|
||||||
|
self.aliases
|
||||||
|
.add(receiver.uid.clone() + "-field", &rx_field_alias);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
receiver.uid.clone()
|
#[derive(Serialize)]
|
||||||
})
|
struct NewReceiverInfo<'a> {
|
||||||
.collect();
|
uid: &'a str,
|
||||||
|
distance: f32,
|
||||||
|
position: Vector3<f32>,
|
||||||
|
rotation: Quaternion<f32>,
|
||||||
|
}
|
||||||
|
|
||||||
serialize(uids).map_err(|e| e.into())
|
let (_, rotation, position) = Spatial::space_to_space_matrix(
|
||||||
|
rx_node.spatial.get().map(|s| s.as_ref()),
|
||||||
|
tx_node.spatial.get().map(|s| s.as_ref()),
|
||||||
|
)
|
||||||
|
.to_scale_rotation_translation();
|
||||||
|
|
||||||
|
let info = NewReceiverInfo {
|
||||||
|
uid: &receiver.uid,
|
||||||
|
distance: receiver
|
||||||
|
.field
|
||||||
|
.distance(tx_node.spatial.get().unwrap(), vec3a(0.0, 0.0, 0.0)),
|
||||||
|
position: position.into(),
|
||||||
|
rotation: rotation.into(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let Ok(data) = serialize(info) else {return};
|
||||||
|
let _ = tx_node.send_remote_signal("new_receiver", data);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_drop_receiver(&self, receiver: &PulseReceiver) {
|
||||||
|
let uid = receiver.uid.as_str();
|
||||||
|
self.aliases.remove(uid);
|
||||||
|
self.aliases.remove(&(uid.to_string() + "-field"));
|
||||||
|
let Some(tx_node) = self.node.upgrade() else {return};
|
||||||
|
let Ok(data) = serialize(&uid) else {return};
|
||||||
|
let _ = tx_node.send_remote_signal("drop_receiver", data);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_data_flex(node: &Node, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
|
let info: SendDataInfo = deserialize(message.as_ref())?;
|
||||||
|
let receiver_node = calling_client.get_node("Pulse receiver", info.uid)?;
|
||||||
|
let receiver =
|
||||||
|
receiver_node.get_aspect("Pulse Receiver", "pulse receiver", |n| &n.pulse_receiver)?;
|
||||||
|
let receiver_mask = &receiver_node
|
||||||
|
.get_aspect("Pulse receiver", "pulse receiver", |node| {
|
||||||
|
&node.pulse_receiver
|
||||||
|
})?
|
||||||
|
.mask;
|
||||||
|
|
||||||
|
let data_mask = Mask(info.data);
|
||||||
|
data_mask.get_mask()?;
|
||||||
|
ensure!(
|
||||||
|
mask_matches(receiver_mask, &data_mask),
|
||||||
|
"Message ({}) does not contain the same keys as the receiver's mask ({})",
|
||||||
|
data_mask,
|
||||||
|
receiver_mask
|
||||||
|
);
|
||||||
|
receiver.send_data(&node.pulse_sender.get().unwrap().uid, data_mask.0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Drop for PulseSender {
|
impl Drop for PulseSender {
|
||||||
@@ -156,62 +210,36 @@ impl Drop for PulseSender {
|
|||||||
|
|
||||||
pub struct PulseReceiver {
|
pub struct PulseReceiver {
|
||||||
uid: String,
|
uid: String,
|
||||||
node: Weak<Node>,
|
pub node: Weak<Node>,
|
||||||
pub mask: Mutex<Mask>,
|
pub field: Arc<Field>,
|
||||||
field: Weak<Field>,
|
pub mask: Mask,
|
||||||
}
|
}
|
||||||
impl PulseReceiver {
|
impl PulseReceiver {
|
||||||
pub fn add_to(node: &Arc<Node>, field: Arc<Field>) -> Result<()> {
|
pub fn add_to(node: &Arc<Node>, field: Arc<Field>, mask: Mask) -> Result<Arc<PulseReceiver>> {
|
||||||
ensure!(
|
ensure!(
|
||||||
node.spatial.get().is_some(),
|
node.spatial.get().is_some(),
|
||||||
"Internal: Node does not have a spatial attached!"
|
"Internal: Node does not have a spatial attached!"
|
||||||
);
|
);
|
||||||
|
|
||||||
let receiver = PulseReceiver {
|
let receiver = PulseReceiver {
|
||||||
uid: node.uid.clone(),
|
uid: nanoid!(),
|
||||||
node: Arc::downgrade(node),
|
node: Arc::downgrade(node),
|
||||||
field: Arc::downgrade(&field),
|
field,
|
||||||
mask: Default::default(),
|
mask,
|
||||||
};
|
};
|
||||||
let receiver = PULSE_RECEIVER_REGISTRY.add(receiver);
|
let receiver = PULSE_RECEIVER_REGISTRY.add(receiver);
|
||||||
let _ = node.pulse_receiver.set(receiver);
|
|
||||||
node.add_local_signal("setMask", PulseReceiver::set_mask_flex);
|
for sender in PULSE_SENDER_REGISTRY.get_valid_contents() {
|
||||||
node.add_local_signal("sendData", PulseReceiver::send_data_flex);
|
sender.handle_new_receiver(&receiver);
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
fn get_field(&self) -> Option<Arc<Field>> {
|
|
||||||
self.field.upgrade()
|
|
||||||
}
|
|
||||||
fn send_data_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
|
||||||
ensure!(
|
|
||||||
node.pulse_receiver.get().is_some(),
|
|
||||||
"Internal: Node does not have a pulse receiver aspect"
|
|
||||||
);
|
|
||||||
let receiver_mask = node.pulse_receiver.get().unwrap().mask.lock();
|
|
||||||
let data_mask = Mask {
|
|
||||||
binary: data.to_vec(),
|
|
||||||
get_fn: mask_get_map_at_root,
|
|
||||||
};
|
|
||||||
if !mask_matches(&receiver_mask, &data_mask) {
|
|
||||||
return Err(anyhow!(
|
|
||||||
"Message does not contain the same keys as the receiver mask"
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
drop(receiver_mask);
|
let _ = node.pulse_receiver.set(receiver.clone());
|
||||||
node.send_remote_signal("pulse", data)?;
|
Ok(receiver)
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
fn set_mask_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
|
||||||
ensure!(
|
pub fn send_data(&self, uid: &str, data: Vec<u8>) -> Result<()> {
|
||||||
node.pulse_receiver.get().is_some(),
|
if let Some(node) = self.node.upgrade() {
|
||||||
"Internal: Node does not have a pulse receiver aspect"
|
node.send_remote_signal("data", serialize(SendDataInfo { uid, data })?)?;
|
||||||
);
|
}
|
||||||
node.pulse_receiver
|
|
||||||
.get()
|
|
||||||
.unwrap()
|
|
||||||
.mask
|
|
||||||
.lock()
|
|
||||||
.set_mask(data.to_vec(), mask_get_map_at_root);
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -219,59 +247,51 @@ impl PulseReceiver {
|
|||||||
impl Drop for PulseReceiver {
|
impl Drop for PulseReceiver {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
PULSE_RECEIVER_REGISTRY.remove(self);
|
PULSE_RECEIVER_REGISTRY.remove(self);
|
||||||
|
for sender in PULSE_SENDER_REGISTRY.get_valid_contents() {
|
||||||
|
sender.handle_drop_receiver(self);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_interface(client: &Arc<Client>) {
|
pub fn create_interface(client: &Arc<Client>) -> Result<()> {
|
||||||
let node = Node::create(client, "", "data", false);
|
let node = Node::create(client, "", "data", false);
|
||||||
node.add_local_signal("createPulseSender", create_pulse_sender_flex);
|
node.add_local_signal("create_pulse_sender", create_pulse_sender_flex);
|
||||||
node.add_local_signal("createPulseReceiver", create_pulse_receiver_flex);
|
node.add_local_signal("create_pulse_receiver", create_pulse_receiver_flex);
|
||||||
node.add_to_scenegraph();
|
node.add_local_method("register_keymap", register_keymap_flex);
|
||||||
|
node.add_local_method("get_keymap", get_keymap_flex);
|
||||||
|
node.add_to_scenegraph().map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
||||||
// pub fn mask_get_map_pulse_sender_create_args(mask: &Mask) -> Result<flexbuffers::MapReader<&[u8]>> {
|
|
||||||
// flexbuffers::Reader::get_root(mask.binary.as_slice())
|
|
||||||
// .map_err(|_| anyhow!("Mask is not a valid flexbuffer"))?
|
|
||||||
// .get_vector()?
|
|
||||||
// .index(4)?
|
|
||||||
// .get_map()
|
|
||||||
// .map_err(|_| anyhow!("Mask is not a valid map"))
|
|
||||||
// }
|
|
||||||
pub fn create_pulse_sender_flex(
|
pub fn create_pulse_sender_flex(
|
||||||
_node: &Node,
|
_node: &Node,
|
||||||
calling_client: Arc<Client>,
|
calling_client: Arc<Client>,
|
||||||
data: &[u8],
|
message: Message,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CreatePulseSenderInfo<'a> {
|
struct CreatePulseSenderInfo<'a> {
|
||||||
name: &'a str,
|
name: &'a str,
|
||||||
parent_path: &'a str,
|
parent_path: &'a str,
|
||||||
transform: Transform,
|
transform: Transform,
|
||||||
|
mask: Vec<u8>,
|
||||||
}
|
}
|
||||||
let info: CreatePulseSenderInfo = deserialize(data)?;
|
let info: CreatePulseSenderInfo = deserialize(message.as_ref())?;
|
||||||
let node = Node::create(&calling_client, "/data/sender", info.name, true);
|
let node = Node::create(&calling_client, "/data/sender", info.name, true);
|
||||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
let transform = parse_transform(info.transform, true, true, false)?;
|
let transform = parse_transform(info.transform, true, true, false);
|
||||||
let node = node.add_to_scenegraph();
|
|
||||||
Spatial::add_to(&node, Some(parent), transform)?;
|
let mask = Mask(info.mask);
|
||||||
PulseSender::add_to(&node)?;
|
mask.get_mask()?;
|
||||||
|
|
||||||
|
let node = node.add_to_scenegraph()?;
|
||||||
|
Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
|
PulseSender::add_to(&node, mask)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// pub fn mask_get_map_pulse_receiver_create_args(
|
|
||||||
// mask: &Mask,
|
|
||||||
// ) -> Result<flexbuffers::MapReader<&[u8]>> {
|
|
||||||
// flexbuffers::Reader::get_root(mask.binary.as_slice())
|
|
||||||
// .map_err(|_| anyhow!("Mask is not a valid flexbuffer"))?
|
|
||||||
// .get_vector()?
|
|
||||||
// .index(5)?
|
|
||||||
// .get_map()
|
|
||||||
// .map_err(|_| anyhow!("Mask is not a valid map"))
|
|
||||||
// }
|
|
||||||
pub fn create_pulse_receiver_flex(
|
pub fn create_pulse_receiver_flex(
|
||||||
_node: &Node,
|
_node: &Node,
|
||||||
calling_client: Arc<Client>,
|
calling_client: Arc<Client>,
|
||||||
data: &[u8],
|
message: Message,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CreatePulseReceiverInfo<'a> {
|
struct CreatePulseReceiverInfo<'a> {
|
||||||
@@ -279,15 +299,57 @@ pub fn create_pulse_receiver_flex(
|
|||||||
parent_path: &'a str,
|
parent_path: &'a str,
|
||||||
transform: Transform,
|
transform: Transform,
|
||||||
field_path: &'a str,
|
field_path: &'a str,
|
||||||
|
mask: Vec<u8>,
|
||||||
}
|
}
|
||||||
let info: CreatePulseReceiverInfo = deserialize(data)?;
|
let info: CreatePulseReceiverInfo = deserialize(message.as_ref())?;
|
||||||
let node = Node::create(&calling_client, "/data/sender", info.name, true);
|
let node = Node::create(&calling_client, "/data/receiver", info.name, true);
|
||||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
let transform = parse_transform(info.transform, true, true, false)?;
|
let transform = parse_transform(info.transform, true, true, false);
|
||||||
let field = find_field(&calling_client, info.field_path)?;
|
let field = find_field(&calling_client, info.field_path)?;
|
||||||
|
let mask = Mask(info.mask);
|
||||||
|
mask.get_mask()?;
|
||||||
|
|
||||||
let node = node.add_to_scenegraph();
|
let node = node.add_to_scenegraph()?;
|
||||||
Spatial::add_to(&node, Some(parent), transform)?;
|
Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
PulseReceiver::add_to(&node, field)?;
|
PulseReceiver::add_to(&node, field, mask)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn register_keymap_flex(
|
||||||
|
_node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
response.wrap_sync(move || {
|
||||||
|
let keymap: String = deserialize(message.as_ref())?;
|
||||||
|
let mut keymaps = KEYMAPS.lock();
|
||||||
|
if let Some(found_keymap_id) = keymaps
|
||||||
|
.iter()
|
||||||
|
.filter(|(_k, v)| *v == &keymap)
|
||||||
|
.map(|(k, _v)| k)
|
||||||
|
.last()
|
||||||
|
{
|
||||||
|
return Ok(serialize(found_keymap_id)?.into());
|
||||||
|
}
|
||||||
|
|
||||||
|
let generated_id = nanoid!();
|
||||||
|
keymaps.insert(generated_id.clone(), keymap);
|
||||||
|
|
||||||
|
Ok(serialize(generated_id)?.into())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
pub fn get_keymap_flex(
|
||||||
|
_node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
response.wrap_sync(move || {
|
||||||
|
let keymap_id: &str = deserialize(message.as_ref())?;
|
||||||
|
let keymaps = KEYMAPS.lock();
|
||||||
|
let Some(keymap) = keymaps.get(keymap_id) else {bail!("Could not find keymap. Try registering it")};
|
||||||
|
|
||||||
|
Ok(serialize(keymap)?.into())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
165
src/nodes/drawable/lines.rs
Normal file
165
src/nodes/drawable/lines.rs
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
use crate::{
|
||||||
|
core::{client::Client, registry::Registry},
|
||||||
|
nodes::{
|
||||||
|
spatial::{find_spatial_parent, parse_transform, Spatial},
|
||||||
|
Message, Node,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use color_eyre::eyre::{bail, ensure, Result};
|
||||||
|
use glam::Vec3A;
|
||||||
|
use mint::Vector3;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use portable_atomic::{AtomicBool, Ordering};
|
||||||
|
use prisma::{Flatten, Lerp, Rgba};
|
||||||
|
use serde::Deserialize;
|
||||||
|
use stardust_xr::{schemas::flex::deserialize, values::Transform};
|
||||||
|
use std::{collections::VecDeque, sync::Arc};
|
||||||
|
use stereokit::{bounds_grow_to_fit_pt, Bounds, Color128, LinePoint as SkLinePoint, StereoKitDraw};
|
||||||
|
|
||||||
|
use super::Drawable;
|
||||||
|
|
||||||
|
static LINES_REGISTRY: Registry<Lines> = Registry::new();
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize)]
|
||||||
|
struct LinePointRaw {
|
||||||
|
point: Vector3<f32>,
|
||||||
|
thickness: f32,
|
||||||
|
color: [f32; 4],
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct LineData {
|
||||||
|
points: Vec<LinePointRaw>,
|
||||||
|
cyclic: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Lines {
|
||||||
|
enabled: Arc<AtomicBool>,
|
||||||
|
space: Arc<Spatial>,
|
||||||
|
data: Mutex<LineData>,
|
||||||
|
}
|
||||||
|
impl Lines {
|
||||||
|
fn add_to(node: &Arc<Node>, points: Vec<LinePointRaw>, cyclic: bool) -> Result<Arc<Lines>> {
|
||||||
|
ensure!(
|
||||||
|
node.drawable.get().is_none(),
|
||||||
|
"Internal: Node already has a drawable attached!"
|
||||||
|
);
|
||||||
|
|
||||||
|
let _ = node.spatial.get().unwrap().bounding_box_calc.set(|node| {
|
||||||
|
let mut bounds = Bounds::default();
|
||||||
|
let Some(Drawable::Lines(lines)) = node.drawable.get() else {return bounds};
|
||||||
|
for point in &lines.data.lock().points {
|
||||||
|
bounds = bounds_grow_to_fit_pt(bounds, point.point);
|
||||||
|
}
|
||||||
|
|
||||||
|
bounds
|
||||||
|
});
|
||||||
|
|
||||||
|
let lines = LINES_REGISTRY.add(Lines {
|
||||||
|
enabled: node.enabled.clone(),
|
||||||
|
space: node.get_aspect("Lines", "spatial", |n| &n.spatial)?.clone(),
|
||||||
|
data: Mutex::new(LineData { points, cyclic }),
|
||||||
|
});
|
||||||
|
node.add_local_signal("set_points", Lines::set_points_flex);
|
||||||
|
node.add_local_signal("set_cyclic", Lines::set_cyclic_flex);
|
||||||
|
let _ = node.drawable.set(Drawable::Lines(lines.clone()));
|
||||||
|
|
||||||
|
Ok(lines)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw(&self, draw_ctx: &impl StereoKitDraw) {
|
||||||
|
let transform_mat = self.space.global_transform();
|
||||||
|
let data = self.data.lock().clone();
|
||||||
|
let mut points: VecDeque<SkLinePoint> = data
|
||||||
|
.points
|
||||||
|
.iter()
|
||||||
|
.map(|p| SkLinePoint {
|
||||||
|
pt: transform_mat.transform_point3a(Vec3A::from(p.point)).into(),
|
||||||
|
thickness: p.thickness,
|
||||||
|
color: p.color.map(|c| (c * 255.0) as u8).into(),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if data.cyclic && !points.is_empty() {
|
||||||
|
let first = data.points.first().unwrap();
|
||||||
|
let last = data.points.last().unwrap();
|
||||||
|
let color = Rgba::from_slice(&first.color).lerp(&Rgba::from_slice(&last.color), 0.5);
|
||||||
|
let connect_point = SkLinePoint {
|
||||||
|
pt: transform_mat
|
||||||
|
.transform_point3a(Vec3A::from(first.point).lerp(Vec3A::from(last.point), 0.5))
|
||||||
|
.into(),
|
||||||
|
thickness: (first.thickness + last.thickness) * 0.5,
|
||||||
|
color: Color128::from([color.red(), color.green(), color.blue(), color.alpha()])
|
||||||
|
.into(),
|
||||||
|
};
|
||||||
|
points.push_front(connect_point.clone());
|
||||||
|
points.push_back(connect_point);
|
||||||
|
}
|
||||||
|
draw_ctx.line_add_listv(points.make_contiguous());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_points_flex(
|
||||||
|
node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let Some(Drawable::Lines(lines)) = node.drawable.get() else {bail!("Not a drawable??")};
|
||||||
|
|
||||||
|
let mut points: Vec<LinePointRaw> = deserialize(message.as_ref())?;
|
||||||
|
for p in &mut points {
|
||||||
|
p.color[0] = p.color[0].powf(2.2);
|
||||||
|
p.color[1] = p.color[1].powf(2.2);
|
||||||
|
p.color[2] = p.color[2].powf(2.2);
|
||||||
|
}
|
||||||
|
lines.data.lock().points = points;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
pub fn set_cyclic_flex(
|
||||||
|
node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let Some(Drawable::Lines(lines)) = node.drawable.get() else {bail!("Not a drawable??")};
|
||||||
|
|
||||||
|
lines.data.lock().cyclic = deserialize(message.as_ref())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for Lines {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
LINES_REGISTRY.remove(self);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn draw_all(draw_ctx: &impl StereoKitDraw) {
|
||||||
|
for lines in LINES_REGISTRY.get_valid_contents() {
|
||||||
|
if lines.enabled.load(Ordering::Relaxed) {
|
||||||
|
lines.draw(draw_ctx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_flex(_node: &Node, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct CreateTextInfo<'a> {
|
||||||
|
name: &'a str,
|
||||||
|
parent_path: &'a str,
|
||||||
|
transform: Transform,
|
||||||
|
points: Vec<LinePointRaw>,
|
||||||
|
cyclic: bool,
|
||||||
|
}
|
||||||
|
let mut info: CreateTextInfo = deserialize(message.as_ref())?;
|
||||||
|
let node = Node::create(&calling_client, "/drawable/lines", info.name, true);
|
||||||
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
|
let transform = parse_transform(info.transform, true, true, true);
|
||||||
|
|
||||||
|
for p in &mut info.points {
|
||||||
|
p.color[0] = p.color[0].powf(2.2);
|
||||||
|
p.color[1] = p.color[1].powf(2.2);
|
||||||
|
p.color[2] = p.color[2].powf(2.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
let node = node.add_to_scenegraph()?;
|
||||||
|
Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
|
Lines::add_to(&node, info.points, info.cyclic)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -1,47 +1,54 @@
|
|||||||
|
pub mod lines;
|
||||||
pub mod model;
|
pub mod model;
|
||||||
|
pub mod shaders;
|
||||||
pub mod text;
|
pub mod text;
|
||||||
|
|
||||||
use super::Node;
|
use self::{
|
||||||
|
lines::Lines,
|
||||||
|
model::{Model, ModelPart},
|
||||||
|
text::Text,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::{Message, Node};
|
||||||
use crate::core::client::Client;
|
use crate::core::client::Client;
|
||||||
use anyhow::Result;
|
use color_eyre::eyre::Result;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use stardust_xr::schemas::flex::deserialize;
|
use stardust_xr::schemas::flex::deserialize;
|
||||||
use std::{path::PathBuf, sync::Arc};
|
use std::{path::PathBuf, sync::Arc};
|
||||||
use stereokit::{lifecycle::DrawContext, texture::Texture, StereoKit};
|
use stereokit::StereoKitDraw;
|
||||||
|
use tracing::instrument;
|
||||||
|
|
||||||
pub fn create_interface(client: &Arc<Client>) {
|
pub fn create_interface(client: &Arc<Client>) -> Result<()> {
|
||||||
let node = Node::create(client, "", "drawable", false);
|
let node = Node::create(client, "", "drawable", false);
|
||||||
node.add_local_signal("createModel", model::create_flex);
|
node.add_local_signal("create_lines", lines::create_flex);
|
||||||
node.add_local_signal("createText", text::create_flex);
|
node.add_local_signal("create_model", model::create_flex);
|
||||||
node.add_local_signal("setSkyFile", set_sky_file_flex);
|
node.add_local_signal("create_text", text::create_flex);
|
||||||
node.add_to_scenegraph();
|
node.add_local_signal("set_sky_file", set_sky_file_flex);
|
||||||
|
node.add_to_scenegraph().map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn draw(sk: &mut StereoKit, draw_ctx: &DrawContext) {
|
pub enum Drawable {
|
||||||
model::draw_all(sk, draw_ctx);
|
Lines(Arc<Lines>),
|
||||||
text::draw_all(sk, draw_ctx);
|
Model(Arc<Model>),
|
||||||
|
ModelPart(Arc<ModelPart>),
|
||||||
|
Text(Arc<Text>),
|
||||||
|
}
|
||||||
|
|
||||||
let new_skytex = QUEUED_SKYTEX.lock().take();
|
#[instrument(level = "debug", skip(sk))]
|
||||||
let mut new_skylight = QUEUED_SKYLIGHT.lock().take();
|
pub fn draw(sk: &impl StereoKitDraw) {
|
||||||
let same_file = new_skytex == new_skylight;
|
lines::draw_all(sk);
|
||||||
|
model::draw_all(sk);
|
||||||
|
text::draw_all(sk);
|
||||||
|
|
||||||
if let Some(skytex) = new_skytex {
|
if let Some(skytex) = QUEUED_SKYTEX.lock().take() {
|
||||||
if let Some((skytex, skylight)) =
|
if let Ok((_skylight, skytex)) = sk.tex_create_cubemap_file(&skytex, true, i32::MAX) {
|
||||||
Texture::from_cubemap_equirectangular(sk, &skytex, true, i32::MAX)
|
sk.render_set_skytex(&skytex);
|
||||||
{
|
|
||||||
sk.set_skytex(&skytex);
|
|
||||||
if same_file {
|
|
||||||
sk.set_skylight(&skylight);
|
|
||||||
new_skylight = None;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if let Some(skylight) = new_skylight {
|
if let Some(skylight) = QUEUED_SKYLIGHT.lock().take() {
|
||||||
if let Some((_, skylight)) =
|
if let Ok((skylight, _)) = sk.tex_create_cubemap_file(&skylight, true, i32::MAX) {
|
||||||
Texture::from_cubemap_equirectangular(sk, &skylight, true, i32::MAX)
|
sk.render_set_skylight(skylight);
|
||||||
{
|
|
||||||
sk.set_skylight(&skylight);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -49,14 +56,14 @@ pub fn draw(sk: &mut StereoKit, draw_ctx: &DrawContext) {
|
|||||||
static QUEUED_SKYLIGHT: Mutex<Option<PathBuf>> = Mutex::new(None);
|
static QUEUED_SKYLIGHT: Mutex<Option<PathBuf>> = Mutex::new(None);
|
||||||
static QUEUED_SKYTEX: Mutex<Option<PathBuf>> = Mutex::new(None);
|
static QUEUED_SKYTEX: Mutex<Option<PathBuf>> = Mutex::new(None);
|
||||||
|
|
||||||
fn set_sky_file_flex(_node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
fn set_sky_file_flex(_node: &Node, _calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct SkyFileInfo {
|
struct SkyFileInfo {
|
||||||
path: PathBuf,
|
path: PathBuf,
|
||||||
skytex: Option<bool>,
|
skytex: Option<bool>,
|
||||||
skylight: Option<bool>,
|
skylight: Option<bool>,
|
||||||
}
|
}
|
||||||
let info: SkyFileInfo = deserialize(data)?;
|
let info: SkyFileInfo = deserialize(message.as_ref())?;
|
||||||
info.path.metadata()?;
|
info.path.metadata()?;
|
||||||
if info.skytex.unwrap_or_default() {
|
if info.skytex.unwrap_or_default() {
|
||||||
QUEUED_SKYTEX.lock().replace(info.path.clone());
|
QUEUED_SKYTEX.lock().replace(info.path.clone());
|
||||||
|
|||||||
@@ -1,44 +1,273 @@
|
|||||||
use super::Node;
|
use super::Node;
|
||||||
use crate::core::client::Client;
|
use crate::core::client::Client;
|
||||||
use crate::core::destroy_queue;
|
use crate::core::node_collections::LifeLinkedNodeMap;
|
||||||
use crate::core::registry::Registry;
|
use crate::core::registry::Registry;
|
||||||
use crate::core::resource::ResourceID;
|
use crate::core::resource::ResourceID;
|
||||||
|
use crate::nodes::drawable::Drawable;
|
||||||
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||||
use anyhow::{anyhow, ensure, Result};
|
use crate::nodes::Message;
|
||||||
|
use crate::SK_MULTITHREAD;
|
||||||
|
use color_eyre::eyre::{bail, ensure, eyre, Result};
|
||||||
|
use glam::Mat4;
|
||||||
|
use mint::{ColumnMatrix4, Vector2, Vector3, Vector4};
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use prisma::{Rgb, Rgba};
|
use portable_atomic::{AtomicBool, Ordering};
|
||||||
use rustc_hash::FxHashMap;
|
use rustc_hash::FxHashMap;
|
||||||
use send_wrapper::SendWrapper;
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use stardust_xr::schemas::flex::deserialize;
|
use stardust_xr::schemas::flex::deserialize;
|
||||||
use stardust_xr::values::Transform;
|
use stardust_xr::values::Transform;
|
||||||
use std::fmt::Error;
|
use std::ffi::OsStr;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::Arc;
|
use std::sync::{Arc, Weak};
|
||||||
use stereokit::lifecycle::DrawContext;
|
use stereokit::named_colors::WHITE;
|
||||||
use stereokit::material::Material;
|
use stereokit::{
|
||||||
use stereokit::model::Model as SKModel;
|
Bounds, Color128, Material, Model as SKModel, RenderLayer, Shader, StereoKitDraw,
|
||||||
use stereokit::render::RenderLayer;
|
StereoKitMultiThread,
|
||||||
use stereokit::texture::Texture;
|
};
|
||||||
use stereokit::StereoKit;
|
|
||||||
|
|
||||||
static MODEL_REGISTRY: Registry<Model> = Registry::new();
|
static MODEL_REGISTRY: Registry<Model> = Registry::new();
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
#[derive(Deserialize, Debug)]
|
||||||
#[serde(untagged)]
|
#[serde(tag = "t", content = "c")]
|
||||||
pub enum MaterialParameter {
|
pub enum MaterialParameter {
|
||||||
Texture(PathBuf),
|
Float(f32),
|
||||||
|
Vector2(Vector2<f32>),
|
||||||
|
Vector3(Vector3<f32>),
|
||||||
|
Vector4(Vector4<f32>),
|
||||||
|
Color([f32; 4]),
|
||||||
|
Int(i32),
|
||||||
|
Int2(Vector2<i32>),
|
||||||
|
Int3(Vector3<i32>),
|
||||||
|
Int4(Vector4<i32>),
|
||||||
|
Bool(bool),
|
||||||
|
UInt(u32),
|
||||||
|
UInt2(Vector2<u32>),
|
||||||
|
UInt3(Vector3<u32>),
|
||||||
|
UInt4(Vector4<u32>),
|
||||||
|
Matrix(ColumnMatrix4<f32>),
|
||||||
|
Texture(ResourceID),
|
||||||
|
}
|
||||||
|
impl MaterialParameter {
|
||||||
|
fn apply_to_material(
|
||||||
|
&self,
|
||||||
|
client: &Client,
|
||||||
|
sk: &impl StereoKitMultiThread,
|
||||||
|
material: &Material,
|
||||||
|
parameter_name: &str,
|
||||||
|
) {
|
||||||
|
match self {
|
||||||
|
MaterialParameter::Float(val) => {
|
||||||
|
sk.material_set_float(material, parameter_name, *val);
|
||||||
|
}
|
||||||
|
MaterialParameter::Vector2(val) => {
|
||||||
|
sk.material_set_vector2(material, parameter_name, *val);
|
||||||
|
}
|
||||||
|
MaterialParameter::Vector3(val) => {
|
||||||
|
sk.material_set_vector3(material, parameter_name, *val);
|
||||||
|
}
|
||||||
|
MaterialParameter::Vector4(val) => {
|
||||||
|
sk.material_set_vector4(material, parameter_name, *val);
|
||||||
|
}
|
||||||
|
MaterialParameter::Color(val) => {
|
||||||
|
sk.material_set_color(material, parameter_name, Color128::from(val.clone()));
|
||||||
|
}
|
||||||
|
MaterialParameter::Int(val) => {
|
||||||
|
sk.material_set_int(material, parameter_name, *val);
|
||||||
|
}
|
||||||
|
MaterialParameter::Int2(val) => {
|
||||||
|
sk.material_set_int2(material, parameter_name, val.x, val.y);
|
||||||
|
}
|
||||||
|
MaterialParameter::Int3(val) => {
|
||||||
|
sk.material_set_int3(material, parameter_name, val.x, val.y, val.z);
|
||||||
|
}
|
||||||
|
MaterialParameter::Int4(val) => {
|
||||||
|
sk.material_set_int4(material, parameter_name, val.w, val.x, val.y, val.z);
|
||||||
|
}
|
||||||
|
MaterialParameter::Bool(val) => {
|
||||||
|
sk.material_set_bool(material, parameter_name, *val);
|
||||||
|
}
|
||||||
|
MaterialParameter::UInt(val) => {
|
||||||
|
sk.material_set_uint(material, parameter_name, *val);
|
||||||
|
}
|
||||||
|
MaterialParameter::UInt2(val) => {
|
||||||
|
sk.material_set_uint2(material, parameter_name, val.x, val.y);
|
||||||
|
}
|
||||||
|
MaterialParameter::UInt3(val) => {
|
||||||
|
sk.material_set_uint3(material, parameter_name, val.x, val.y, val.z);
|
||||||
|
}
|
||||||
|
MaterialParameter::UInt4(val) => {
|
||||||
|
sk.material_set_uint4(material, parameter_name, val.w, val.x, val.y, val.z);
|
||||||
|
}
|
||||||
|
MaterialParameter::Matrix(val) => {
|
||||||
|
sk.material_set_matrix(material, parameter_name, Mat4::from(*val));
|
||||||
|
}
|
||||||
|
MaterialParameter::Texture(resource) => {
|
||||||
|
let Some(texture_path) = resource.get_file(
|
||||||
|
&client.base_resource_prefixes.lock().clone(),
|
||||||
|
&[OsStr::new("png"), OsStr::new("jpg")],
|
||||||
|
) else {return};
|
||||||
|
if let Ok(tex) = sk.tex_create_file(texture_path, true, 0) {
|
||||||
|
sk.material_set_texture(material, parameter_name, &tex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ModelPart {
|
||||||
|
id: i32,
|
||||||
|
path: PathBuf,
|
||||||
|
space: Arc<Spatial>,
|
||||||
|
model: Weak<Model>,
|
||||||
|
pending_material_parameters: Mutex<FxHashMap<String, MaterialParameter>>,
|
||||||
|
pending_material_replacement: Mutex<Option<Arc<Material>>>,
|
||||||
|
}
|
||||||
|
impl ModelPart {
|
||||||
|
fn create_for_model(sk: &impl StereoKitMultiThread, model: &Arc<Model>, sk_model: &SKModel) {
|
||||||
|
let first_root_part = sk.model_node_get_root(sk_model);
|
||||||
|
let mut current_option_part = Some(first_root_part);
|
||||||
|
|
||||||
|
while let Some(current_part) = &mut current_option_part {
|
||||||
|
ModelPart::create(sk, model, sk_model, *current_part);
|
||||||
|
|
||||||
|
if let Some(child) = sk.model_node_child(sk_model, *current_part) {
|
||||||
|
*current_part = child;
|
||||||
|
} else if let Some(sibling) = sk.model_node_sibling(sk_model, *current_part) {
|
||||||
|
*current_part = sibling;
|
||||||
|
} else {
|
||||||
|
while let Some(current_part) = &mut current_option_part {
|
||||||
|
if let Some(sibling) = sk.model_node_sibling(sk_model, *current_part) {
|
||||||
|
*current_part = sibling;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
current_option_part = sk.model_node_parent(sk_model, *current_part);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create(
|
||||||
|
sk: &impl StereoKitMultiThread,
|
||||||
|
model: &Arc<Model>,
|
||||||
|
sk_model: &SKModel,
|
||||||
|
id: i32,
|
||||||
|
) -> Option<Arc<Self>> {
|
||||||
|
let parent_node = sk
|
||||||
|
.model_node_parent(sk_model, id)
|
||||||
|
.and_then(|id| model.parts.get(&id));
|
||||||
|
let parent_part = parent_node
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|node| match node.drawable.get() {
|
||||||
|
Some(Drawable::ModelPart(model_part)) => Some(model_part),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
|
||||||
|
let stardust_model_part = model.space.node()?;
|
||||||
|
let client = stardust_model_part.get_client()?;
|
||||||
|
let mut part_path = parent_part.map(|n| n.path.clone()).unwrap_or_default();
|
||||||
|
part_path.push(sk.model_node_get_name(sk_model, id)?);
|
||||||
|
let node = client.scenegraph.add_node(Node::create(
|
||||||
|
&client,
|
||||||
|
stardust_model_part.get_path(),
|
||||||
|
part_path.to_str()?,
|
||||||
|
false,
|
||||||
|
));
|
||||||
|
let spatial_parent = parent_node
|
||||||
|
.and_then(|n| n.spatial.get().cloned())
|
||||||
|
.unwrap_or_else(|| model.space.clone());
|
||||||
|
let space = Spatial::add_to(
|
||||||
|
&node,
|
||||||
|
Some(spatial_parent),
|
||||||
|
sk.model_node_get_transform_local(sk_model, id),
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
.ok()?;
|
||||||
|
|
||||||
|
let _ = node.spatial.get().unwrap().bounding_box_calc.set(|node| {
|
||||||
|
let Some(Drawable::ModelPart(model_part)) = node.drawable.get() else {return Bounds::default()};
|
||||||
|
let Some(sk) = SK_MULTITHREAD.get() else {return Bounds::default()};
|
||||||
|
let Some(model) = model_part.model.upgrade() else {return Bounds::default()};
|
||||||
|
let Some(sk_model) = model.sk_model.get() else {return Bounds::default()};
|
||||||
|
let Some(sk_mesh) = sk.model_node_get_mesh(sk_model, model_part.id) else {return Bounds::default()};
|
||||||
|
sk.mesh_get_bounds(sk_mesh)
|
||||||
|
});
|
||||||
|
|
||||||
|
let model_part = Arc::new(ModelPart {
|
||||||
|
id,
|
||||||
|
path: part_path,
|
||||||
|
space,
|
||||||
|
model: Arc::downgrade(model),
|
||||||
|
pending_material_parameters: Mutex::new(FxHashMap::default()),
|
||||||
|
pending_material_replacement: Mutex::new(None),
|
||||||
|
});
|
||||||
|
node.add_local_signal(
|
||||||
|
"set_material_parameter",
|
||||||
|
ModelPart::set_material_parameter_flex,
|
||||||
|
);
|
||||||
|
let _ = node.drawable.set(Drawable::ModelPart(model_part.clone()));
|
||||||
|
model.parts.add(id, &node);
|
||||||
|
Some(model_part)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_material_parameter_flex(
|
||||||
|
node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let Some(Drawable::ModelPart(model_part)) = node.drawable.get() else {bail!("Not a drawable??")};
|
||||||
|
|
||||||
|
let (name, value): (String, MaterialParameter) = deserialize(message.as_ref())?;
|
||||||
|
|
||||||
|
model_part
|
||||||
|
.pending_material_parameters
|
||||||
|
.lock()
|
||||||
|
.insert(name, value);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn replace_material(&self, replacement: Arc<Material>) {
|
||||||
|
self.pending_material_replacement
|
||||||
|
.lock()
|
||||||
|
.replace(replacement);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update(&self, sk: &impl StereoKitDraw) {
|
||||||
|
let Some(model) = self.model.upgrade() else {return};
|
||||||
|
let Some(sk_model) = model.sk_model.get() else {return};
|
||||||
|
let Some(node) = model.space.node() else {return};
|
||||||
|
let Some(client) = node.get_client() else {return};
|
||||||
|
if let Some(material_replacement) = self.pending_material_replacement.lock().take() {
|
||||||
|
sk.model_node_set_material(sk_model, self.id, material_replacement.as_ref().as_ref());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut material_parameters = self.pending_material_parameters.lock();
|
||||||
|
for (parameter_name, parameter_value) in material_parameters.drain() {
|
||||||
|
let Some(material) = sk.model_node_get_material(sk_model, self.id) else {continue};
|
||||||
|
let new_material = sk.material_copy(material);
|
||||||
|
parameter_value.apply_to_material(&client, sk, &new_material, parameter_name.as_str());
|
||||||
|
sk.model_node_set_material(sk_model, self.id, &new_material);
|
||||||
|
}
|
||||||
|
|
||||||
|
sk.model_node_set_transform_model(
|
||||||
|
sk_model,
|
||||||
|
self.id,
|
||||||
|
Spatial::space_to_space_matrix(Some(&self.space), Some(&model.space)),
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Model {
|
pub struct Model {
|
||||||
|
self_ref: Weak<Model>,
|
||||||
|
enabled: Arc<AtomicBool>,
|
||||||
space: Arc<Spatial>,
|
space: Arc<Spatial>,
|
||||||
resource_id: ResourceID,
|
_resource_id: ResourceID,
|
||||||
pending_model_path: OnceCell<PathBuf>,
|
sk_model: OnceCell<SKModel>,
|
||||||
pending_material_parameters: Mutex<FxHashMap<(u32, String), MaterialParameter>>,
|
parts: LifeLinkedNodeMap<i32>,
|
||||||
pub pending_material_replacements: Mutex<FxHashMap<u32, Arc<SendWrapper<Material>>>>,
|
|
||||||
sk_model: OnceCell<SendWrapper<SKModel>>,
|
|
||||||
}
|
}
|
||||||
|
unsafe impl Send for Model {}
|
||||||
|
unsafe impl Sync for Model {}
|
||||||
|
|
||||||
impl Model {
|
impl Model {
|
||||||
pub fn add_to(node: &Arc<Node>, resource_id: ResourceID) -> Result<Arc<Model>> {
|
pub fn add_to(node: &Arc<Node>, resource_id: ResourceID) -> Result<Arc<Model>> {
|
||||||
@@ -47,125 +276,73 @@ impl Model {
|
|||||||
"Internal: Node does not have a spatial attached!"
|
"Internal: Node does not have a spatial attached!"
|
||||||
);
|
);
|
||||||
ensure!(
|
ensure!(
|
||||||
node.model.get().is_none(),
|
node.drawable.get().is_none(),
|
||||||
"Internal: Node already has a model attached!"
|
"Internal: Node already has a drawable attached!"
|
||||||
);
|
);
|
||||||
let model = Model {
|
|
||||||
|
let pending_model_path = resource_id
|
||||||
|
.get_file(
|
||||||
|
&node
|
||||||
|
.get_client()
|
||||||
|
.ok_or_else(|| eyre!("Client not found"))?
|
||||||
|
.base_resource_prefixes
|
||||||
|
.lock()
|
||||||
|
.clone(),
|
||||||
|
&[OsStr::new("glb"), OsStr::new("gltf")],
|
||||||
|
)
|
||||||
|
.ok_or_else(|| eyre!("Resource not found"))?;
|
||||||
|
|
||||||
|
let model = Arc::new_cyclic(|self_ref| Model {
|
||||||
|
self_ref: self_ref.clone(),
|
||||||
|
enabled: node.enabled.clone(),
|
||||||
space: node.spatial.get().unwrap().clone(),
|
space: node.spatial.get().unwrap().clone(),
|
||||||
resource_id,
|
_resource_id: resource_id,
|
||||||
pending_model_path: OnceCell::new(),
|
|
||||||
pending_material_parameters: Mutex::new(FxHashMap::default()),
|
|
||||||
pending_material_replacements: Mutex::new(FxHashMap::default()),
|
|
||||||
sk_model: OnceCell::new(),
|
sk_model: OnceCell::new(),
|
||||||
};
|
parts: LifeLinkedNodeMap::default(),
|
||||||
node.add_local_signal("setMaterialParameter", Model::set_material_parameter);
|
});
|
||||||
let model_arc = MODEL_REGISTRY.add(model);
|
MODEL_REGISTRY.add_raw(&model);
|
||||||
let _ = model_arc.pending_model_path.set(
|
|
||||||
model_arc
|
let sk = SK_MULTITHREAD.get().unwrap();
|
||||||
.resource_id
|
let sk_model = sk.model_copy(
|
||||||
.get_file(
|
sk.model_create_file(pending_model_path.to_str().unwrap(), None::<Shader>)?,
|
||||||
&node
|
|
||||||
.get_client()
|
|
||||||
.ok_or_else(|| anyhow!("Client not found"))?
|
|
||||||
.base_resource_prefixes
|
|
||||||
.lock()
|
|
||||||
.clone(),
|
|
||||||
)
|
|
||||||
.ok_or_else(|| anyhow!("Resource not found"))?,
|
|
||||||
);
|
);
|
||||||
let _ = node.model.set(model_arc.clone());
|
ModelPart::create_for_model(sk, &model.self_ref.upgrade().unwrap(), &sk_model);
|
||||||
Ok(model_arc)
|
let _ = model.sk_model.set(sk_model);
|
||||||
|
let _ = node.drawable.set(Drawable::Model(model.clone()));
|
||||||
|
Ok(model)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_material_parameter(
|
fn draw(&self, sk: &impl StereoKitDraw) {
|
||||||
node: &Node,
|
let Some(sk_model) = self.sk_model.get() else {return};
|
||||||
_calling_client: Arc<Client>,
|
for model_node_node in self.parts.nodes() {
|
||||||
data: &[u8],
|
let Some(Drawable::ModelPart(model_node)) = model_node_node.drawable.get() else {continue};
|
||||||
) -> Result<()> {
|
model_node.update(sk);
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct MaterialParameterInfo {
|
|
||||||
idx: u32,
|
|
||||||
name: String,
|
|
||||||
value: MaterialParameter,
|
|
||||||
}
|
}
|
||||||
let info: MaterialParameterInfo = deserialize(data)?;
|
|
||||||
|
|
||||||
node.model
|
sk.model_draw(
|
||||||
.get()
|
sk_model,
|
||||||
.unwrap()
|
self.space.global_transform(),
|
||||||
.pending_material_parameters
|
WHITE,
|
||||||
.lock()
|
RenderLayer::LAYER0,
|
||||||
.insert((info.idx, info.name), info.value);
|
);
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw(&self, sk: &StereoKit, draw_ctx: &DrawContext) {
|
|
||||||
let sk_model = self
|
|
||||||
.sk_model
|
|
||||||
.get_or_try_init(|| {
|
|
||||||
self.pending_model_path
|
|
||||||
.get()
|
|
||||||
.and_then(|path| SKModel::from_file(sk, path.as_path(), None))
|
|
||||||
.as_ref()
|
|
||||||
.cloned()
|
|
||||||
.map(SendWrapper::new)
|
|
||||||
.ok_or(Error)
|
|
||||||
})
|
|
||||||
.ok();
|
|
||||||
|
|
||||||
if let Some(sk_model) = sk_model {
|
|
||||||
{
|
|
||||||
let mut material_replacements = self.pending_material_replacements.lock();
|
|
||||||
for (material_idx, replacement_material) in material_replacements.iter() {
|
|
||||||
sk_model.set_material(*material_idx as i32, replacement_material);
|
|
||||||
}
|
|
||||||
material_replacements.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
{
|
|
||||||
let mut material_parameters = self.pending_material_parameters.lock();
|
|
||||||
for ((material_idx, parameter_name), parameter_value) in material_parameters.iter()
|
|
||||||
{
|
|
||||||
if let Some(material) = sk_model.get_material(sk, *material_idx as i32) {
|
|
||||||
match parameter_value {
|
|
||||||
MaterialParameter::Texture(path) => {
|
|
||||||
if let Some(tex) = Texture::from_file(sk, path.as_path(), true, 0) {
|
|
||||||
material.set_parameter(parameter_name.as_str(), &tex);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
material_parameters.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
let global_transform = self.space.global_transform().into();
|
|
||||||
sk_model.draw(
|
|
||||||
draw_ctx,
|
|
||||||
global_transform,
|
|
||||||
Rgba::new(Rgb::new(1_f32, 1_f32, 1_f32), 1_f32),
|
|
||||||
RenderLayer::Layer0,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Model {
|
impl Drop for Model {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
if let Some(model) = self.sk_model.take() {
|
|
||||||
destroy_queue::add(model);
|
|
||||||
}
|
|
||||||
MODEL_REGISTRY.remove(self);
|
MODEL_REGISTRY.remove(self);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn draw_all(sk: &StereoKit, draw_ctx: &DrawContext) {
|
pub fn draw_all(sk: &impl StereoKitDraw) {
|
||||||
for model in MODEL_REGISTRY.get_valid_contents() {
|
for model in MODEL_REGISTRY.get_valid_contents() {
|
||||||
model.draw(sk, draw_ctx);
|
if model.enabled.load(Ordering::Relaxed) {
|
||||||
|
model.draw(sk);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
pub fn create_flex(_node: &Node, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CreateModelInfo<'a> {
|
struct CreateModelInfo<'a> {
|
||||||
name: &'a str,
|
name: &'a str,
|
||||||
@@ -173,12 +350,12 @@ pub fn create_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Re
|
|||||||
transform: Transform,
|
transform: Transform,
|
||||||
resource: ResourceID,
|
resource: ResourceID,
|
||||||
}
|
}
|
||||||
let info: CreateModelInfo = deserialize(data)?;
|
let info: CreateModelInfo = deserialize(message.as_ref())?;
|
||||||
let node = Node::create(&calling_client, "/drawable/model", info.name, true);
|
let node = Node::create(&calling_client, "/drawable/model", info.name, true);
|
||||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
let transform = parse_transform(info.transform, true, true, true)?;
|
let transform = parse_transform(info.transform, true, true, true);
|
||||||
let node = node.add_to_scenegraph();
|
let node = node.add_to_scenegraph()?;
|
||||||
Spatial::add_to(&node, Some(parent), transform)?;
|
Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
Model::add_to(&node, info.resource)?;
|
Model::add_to(&node, info.resource)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
144
src/nodes/drawable/shaders/mod.rs
Normal file
144
src/nodes/drawable/shaders/mod.rs
Normal file
@@ -0,0 +1,144 @@
|
|||||||
|
#![allow(dead_code)]
|
||||||
|
use smithay::backend::renderer::gles::{
|
||||||
|
ffi::{self, Gles2, FRAGMENT_SHADER, VERTEX_SHADER},
|
||||||
|
GlesError,
|
||||||
|
};
|
||||||
|
use std::mem::transmute;
|
||||||
|
use stereokit::Shader;
|
||||||
|
use tracing::error;
|
||||||
|
|
||||||
|
// Simula shader with fancy lanzcos sampling
|
||||||
|
pub const UNLIT_SHADER_BYTES: &[u8] = include_bytes!("shader_unlit_gamma.sks");
|
||||||
|
|
||||||
|
// Simula shader with fancy lanzcos sampling
|
||||||
|
pub const PANEL_SHADER_BYTES: &[u8] = include_bytes!("shader_unlit_simula.sks");
|
||||||
|
|
||||||
|
struct FfiAssetHeader {
|
||||||
|
asset_type: i32,
|
||||||
|
asset_state: i32,
|
||||||
|
id: u64,
|
||||||
|
index: u64,
|
||||||
|
refs: i32,
|
||||||
|
debug: *mut u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FfiSkgShader {
|
||||||
|
meta: *mut u8,
|
||||||
|
vertex: u32,
|
||||||
|
pixel: u32,
|
||||||
|
program: u32,
|
||||||
|
compute: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FfiShader {
|
||||||
|
header: FfiAssetHeader,
|
||||||
|
shader: FfiSkgShader,
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn compile_shader(
|
||||||
|
gl: &ffi::Gles2,
|
||||||
|
variant: ffi::types::GLuint,
|
||||||
|
src: &str,
|
||||||
|
) -> Result<ffi::types::GLuint, GlesError> {
|
||||||
|
let shader = gl.CreateShader(variant);
|
||||||
|
if shader == 0 {
|
||||||
|
return Err(GlesError::CreateShaderObject);
|
||||||
|
}
|
||||||
|
|
||||||
|
gl.ShaderSource(
|
||||||
|
shader,
|
||||||
|
1,
|
||||||
|
&src.as_ptr() as *const *const u8 as *const *const ffi::types::GLchar,
|
||||||
|
&(src.len() as i32) as *const _,
|
||||||
|
);
|
||||||
|
gl.CompileShader(shader);
|
||||||
|
|
||||||
|
let mut status = ffi::FALSE as i32;
|
||||||
|
gl.GetShaderiv(shader, ffi::COMPILE_STATUS, &mut status as *mut _);
|
||||||
|
if status == ffi::FALSE as i32 {
|
||||||
|
let mut max_len = 0;
|
||||||
|
gl.GetShaderiv(shader, ffi::INFO_LOG_LENGTH, &mut max_len as *mut _);
|
||||||
|
|
||||||
|
let mut error = Vec::with_capacity(max_len as usize);
|
||||||
|
let mut len = 0;
|
||||||
|
gl.GetShaderInfoLog(
|
||||||
|
shader,
|
||||||
|
max_len as _,
|
||||||
|
&mut len as *mut _,
|
||||||
|
error.as_mut_ptr() as *mut _,
|
||||||
|
);
|
||||||
|
error.set_len(len as usize);
|
||||||
|
|
||||||
|
error!(
|
||||||
|
"[GL] {}",
|
||||||
|
std::str::from_utf8(&error).unwrap_or("<Error Message no utf8>")
|
||||||
|
);
|
||||||
|
|
||||||
|
gl.DeleteShader(shader);
|
||||||
|
return Err(GlesError::ShaderCompileError);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(shader)
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn link_program(
|
||||||
|
gl: &ffi::Gles2,
|
||||||
|
vert: ffi::types::GLuint,
|
||||||
|
frag: ffi::types::GLuint,
|
||||||
|
) -> Result<ffi::types::GLuint, GlesError> {
|
||||||
|
let program = gl.CreateProgram();
|
||||||
|
gl.AttachShader(program, vert);
|
||||||
|
gl.AttachShader(program, frag);
|
||||||
|
gl.LinkProgram(program);
|
||||||
|
// gl.DetachShader(program, vert);
|
||||||
|
// gl.DetachShader(program, frag);
|
||||||
|
// gl.DeleteShader(vert);
|
||||||
|
// gl.DeleteShader(frag);
|
||||||
|
|
||||||
|
let mut status = ffi::FALSE as i32;
|
||||||
|
gl.GetProgramiv(program, ffi::LINK_STATUS, &mut status as *mut _);
|
||||||
|
if status == ffi::FALSE as i32 {
|
||||||
|
let mut max_len = 0;
|
||||||
|
gl.GetProgramiv(program, ffi::INFO_LOG_LENGTH, &mut max_len as *mut _);
|
||||||
|
|
||||||
|
let mut error = Vec::with_capacity(max_len as usize);
|
||||||
|
let mut len = 0;
|
||||||
|
gl.GetProgramInfoLog(
|
||||||
|
program,
|
||||||
|
max_len as _,
|
||||||
|
&mut len as *mut _,
|
||||||
|
error.as_mut_ptr() as *mut _,
|
||||||
|
);
|
||||||
|
error.set_len(len as usize);
|
||||||
|
|
||||||
|
error!(
|
||||||
|
"[GL] {}",
|
||||||
|
std::str::from_utf8(&error).unwrap_or("<Error Message no utf8>")
|
||||||
|
);
|
||||||
|
|
||||||
|
gl.DeleteProgram(program);
|
||||||
|
return Err(GlesError::ProgramLinkError);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(program)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub unsafe fn shader_inject(
|
||||||
|
c: &Gles2,
|
||||||
|
sk_shader: &mut Shader,
|
||||||
|
vert_str: &str,
|
||||||
|
frag_str: &str,
|
||||||
|
) -> Result<(), GlesError> {
|
||||||
|
let gl_vert = compile_shader(c, VERTEX_SHADER, vert_str)?;
|
||||||
|
let gl_frag = compile_shader(c, FRAGMENT_SHADER, frag_str)?;
|
||||||
|
let gl_prog = link_program(c, gl_vert, gl_frag)?;
|
||||||
|
|
||||||
|
let shader: *mut FfiShader = transmute(sk_shader.0.as_mut());
|
||||||
|
if let Some(shader) = shader.as_mut() {
|
||||||
|
shader.shader.vertex = gl_vert;
|
||||||
|
shader.shader.pixel = gl_frag;
|
||||||
|
shader.shader.program = gl_prog;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -28,7 +28,7 @@ psIn vs(vsIn input, uint id : SV_InstanceID) {
|
|||||||
float3 world = mul(float4(input.pos.xyz, 1), sk_inst[id].world).xyz;
|
float3 world = mul(float4(input.pos.xyz, 1), sk_inst[id].world).xyz;
|
||||||
o.pos = mul(float4(world, 1), sk_viewproj[o.view_id]);
|
o.pos = mul(float4(world, 1), sk_viewproj[o.view_id]);
|
||||||
|
|
||||||
o.uv = (input.uv) + uv_offset * uv_scale;
|
o.uv = (input.uv + uv_offset) * uv_scale;
|
||||||
return o;
|
return o;
|
||||||
}
|
}
|
||||||
float4 ps(psIn input) : SV_TARGET {
|
float4 ps(psIn input) : SV_TARGET {
|
||||||
Binary file not shown.
@@ -4,19 +4,19 @@
|
|||||||
|
|
||||||
//--name = stardust/text_shader
|
//--name = stardust/text_shader
|
||||||
//--diffuse = white
|
//--diffuse = white
|
||||||
//--fcFactor = 1.0
|
|
||||||
//--ripple = 4.0
|
|
||||||
//--uv_offset = 0.0, 0.0
|
//--uv_offset = 0.0, 0.0
|
||||||
//--uv_scale = 1.0, 1.0
|
//--uv_scale = 1.0, 1.0
|
||||||
|
//--fcFactor = 1.0
|
||||||
|
//--ripple = 4.0
|
||||||
//--alpha_min = 0.0
|
//--alpha_min = 0.0
|
||||||
//--alpha_max = 1.0
|
//--alpha_max = 1.0
|
||||||
Texture2D diffuse : register(t0);
|
Texture2D diffuse : register(t0);
|
||||||
SamplerState diffuse_s : register(s0);
|
SamplerState diffuse_s : register(s0);
|
||||||
float4 diffuse_i;
|
float4 diffuse_i;
|
||||||
float fcFactor;
|
|
||||||
float ripple;
|
|
||||||
float2 uv_scale;
|
float2 uv_scale;
|
||||||
float2 uv_offset;
|
float2 uv_offset;
|
||||||
|
float fcFactor;
|
||||||
|
float ripple;
|
||||||
float alpha_min;
|
float alpha_min;
|
||||||
float alpha_max;
|
float alpha_max;
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ psIn vs(vsIn input, uint id : SV_InstanceID) {
|
|||||||
float3 world = mul(float4(input.pos.xyz, 1), sk_inst[id].world).xyz;
|
float3 world = mul(float4(input.pos.xyz, 1), sk_inst[id].world).xyz;
|
||||||
o.pos = mul(float4(world, 1), sk_viewproj[o.view_id]);
|
o.pos = mul(float4(world, 1), sk_viewproj[o.view_id]);
|
||||||
|
|
||||||
o.uv = (input.uv) + uv_offset * uv_scale;
|
o.uv = (input.uv + uv_offset) * uv_scale;
|
||||||
return o;
|
return o;
|
||||||
}
|
}
|
||||||
|
|
||||||
Binary file not shown.
@@ -1,26 +1,22 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
core::{client::Client, destroy_queue, registry::Registry, resource::ResourceID},
|
core::{client::Client, destroy_queue, registry::Registry, resource::ResourceID},
|
||||||
nodes::{
|
nodes::{
|
||||||
|
drawable::Drawable,
|
||||||
spatial::{find_spatial_parent, parse_transform, Spatial},
|
spatial::{find_spatial_parent, parse_transform, Spatial},
|
||||||
Node,
|
Message, Node,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use anyhow::{anyhow, ensure, Result};
|
use color_eyre::eyre::{bail, ensure, eyre, Result};
|
||||||
use glam::{vec3, Mat4, Vec2};
|
use glam::{vec3, Mat4, Vec2};
|
||||||
use mint::Vector2;
|
use mint::Vector2;
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use prisma::{Flatten, Rgb, Rgba};
|
use portable_atomic::{AtomicBool, Ordering};
|
||||||
use send_wrapper::SendWrapper;
|
use prisma::{Flatten, Rgba};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use stardust_xr::{schemas::flex::deserialize, values::Transform};
|
use stardust_xr::{schemas::flex::deserialize, values::Transform};
|
||||||
use std::{path::PathBuf, sync::Arc};
|
use std::{ffi::OsStr, path::PathBuf, sync::Arc};
|
||||||
use stereokit::{
|
use stereokit::{named_colors::WHITE, Color128, StereoKitDraw, TextAlign, TextFit, TextStyle};
|
||||||
font::Font,
|
|
||||||
lifecycle::DrawContext,
|
|
||||||
text::{self, TextAlign, TextFit, TextStyle},
|
|
||||||
StereoKit,
|
|
||||||
};
|
|
||||||
|
|
||||||
static TEXT_REGISTRY: Registry<Text> = Registry::new();
|
static TEXT_REGISTRY: Registry<Text> = Registry::new();
|
||||||
|
|
||||||
@@ -35,9 +31,10 @@ struct TextData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct Text {
|
pub struct Text {
|
||||||
|
enabled: Arc<AtomicBool>,
|
||||||
space: Arc<Spatial>,
|
space: Arc<Spatial>,
|
||||||
font_path: Option<PathBuf>,
|
font_path: Option<PathBuf>,
|
||||||
style: OnceCell<SendWrapper<TextStyle>>,
|
style: OnceCell<TextStyle>,
|
||||||
|
|
||||||
data: Mutex<TextData>,
|
data: Mutex<TextData>,
|
||||||
}
|
}
|
||||||
@@ -59,17 +56,20 @@ impl Text {
|
|||||||
"Internal: Node does not have a spatial attached!"
|
"Internal: Node does not have a spatial attached!"
|
||||||
);
|
);
|
||||||
ensure!(
|
ensure!(
|
||||||
node.model.get().is_none(),
|
node.drawable.get().is_none(),
|
||||||
"Internal: Node already has text attached!"
|
"Internal: Node already has a drawable attached!"
|
||||||
);
|
);
|
||||||
|
|
||||||
let client = node
|
let client = node.get_client().ok_or_else(|| eyre!("Client not found"))?;
|
||||||
.get_client()
|
|
||||||
.ok_or_else(|| anyhow!("Client not found"))?;
|
|
||||||
let text = TEXT_REGISTRY.add(Text {
|
let text = TEXT_REGISTRY.add(Text {
|
||||||
|
enabled: node.enabled.clone(),
|
||||||
space: node.spatial.get().unwrap().clone(),
|
space: node.spatial.get().unwrap().clone(),
|
||||||
font_path: font_resource_id
|
font_path: font_resource_id.and_then(|res| {
|
||||||
.and_then(|res| res.get_file(&client.base_resource_prefixes.lock().clone())),
|
res.get_file(
|
||||||
|
&client.base_resource_prefixes.lock().clone(),
|
||||||
|
&[OsStr::new("ttf"), OsStr::new("otf")],
|
||||||
|
)
|
||||||
|
}),
|
||||||
style: OnceCell::new(),
|
style: OnceCell::new(),
|
||||||
|
|
||||||
data: Mutex::new(TextData {
|
data: Mutex::new(TextData {
|
||||||
@@ -82,29 +82,24 @@ impl Text {
|
|||||||
color,
|
color,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
node.add_local_signal("setCharacterHeight", Text::set_character_height_flex);
|
node.add_local_signal("set_character_height", Text::set_character_height_flex);
|
||||||
node.add_local_signal("setText", Text::set_text_flex);
|
node.add_local_signal("set_text", Text::set_text_flex);
|
||||||
let _ = node.text.set(text.clone());
|
let _ = node.drawable.set(Drawable::Text(text.clone()));
|
||||||
|
|
||||||
Ok(text)
|
Ok(text)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn draw(&self, sk: &StereoKit, draw_ctx: &DrawContext) {
|
fn draw(&self, sk: &impl StereoKitDraw) {
|
||||||
let style =
|
let style = self
|
||||||
self.style
|
.style
|
||||||
.get_or_try_init(|| -> Result<SendWrapper<TextStyle>, anyhow::Error> {
|
.get_or_try_init(|| -> Result<TextStyle, color_eyre::eyre::Error> {
|
||||||
let font = if let Some(path) = self.font_path.as_deref() {
|
let font = self
|
||||||
Font::from_file(sk, path)
|
.font_path
|
||||||
} else {
|
.as_deref()
|
||||||
Some(Font::default(sk))
|
.and_then(|path| sk.font_create(path).ok())
|
||||||
};
|
.unwrap_or_else(|| sk.font_find("default/font").unwrap());
|
||||||
Ok(SendWrapper::new(TextStyle::new(
|
Ok(unsafe { sk.text_make_style(font, 1.0, WHITE) })
|
||||||
sk,
|
});
|
||||||
font.ok_or(std::fmt::Error)?,
|
|
||||||
1.0,
|
|
||||||
Rgba::new(Rgb::new(1.0, 1.0, 1.0), 1.0),
|
|
||||||
)))
|
|
||||||
});
|
|
||||||
|
|
||||||
if let Ok(style) = style {
|
if let Ok(style) = style {
|
||||||
let data = self.data.lock();
|
let data = self.data.lock();
|
||||||
@@ -115,28 +110,36 @@ impl Text {
|
|||||||
data.character_height,
|
data.character_height,
|
||||||
));
|
));
|
||||||
if let Some(bounds) = data.bounds {
|
if let Some(bounds) = data.bounds {
|
||||||
text::draw_in(
|
sk.text_add_in(
|
||||||
draw_ctx,
|
|
||||||
&data.text,
|
&data.text,
|
||||||
transform,
|
transform,
|
||||||
bounds / data.character_height,
|
bounds / data.character_height,
|
||||||
data.fit,
|
data.fit,
|
||||||
style,
|
*style,
|
||||||
data.bounds_align,
|
data.bounds_align,
|
||||||
data.text_align,
|
data.text_align,
|
||||||
vec3(0.0, 0.0, 0.0),
|
vec3(0.0, 0.0, 0.0),
|
||||||
data.color,
|
Color128::from([
|
||||||
|
data.color.red(),
|
||||||
|
data.color.green(),
|
||||||
|
data.color.blue(),
|
||||||
|
data.color.alpha(),
|
||||||
|
]),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
text::draw_at(
|
sk.text_add_at(
|
||||||
draw_ctx,
|
|
||||||
&data.text,
|
&data.text,
|
||||||
transform,
|
transform,
|
||||||
style,
|
*style,
|
||||||
data.bounds_align,
|
data.bounds_align,
|
||||||
data.text_align,
|
data.text_align,
|
||||||
vec3(0.0, 0.0, 0.0),
|
vec3(0.0, 0.0, 0.0),
|
||||||
data.color,
|
Color128::from([
|
||||||
|
data.color.red(),
|
||||||
|
data.color.green(),
|
||||||
|
data.color.blue(),
|
||||||
|
data.color.alpha(),
|
||||||
|
]),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -145,16 +148,22 @@ impl Text {
|
|||||||
pub fn set_character_height_flex(
|
pub fn set_character_height_flex(
|
||||||
node: &Node,
|
node: &Node,
|
||||||
_calling_client: Arc<Client>,
|
_calling_client: Arc<Client>,
|
||||||
data: &[u8],
|
message: Message,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let height = flexbuffers::Reader::get_root(data)?.get_f64()? as f32;
|
let Some(Drawable::Text(text)) = node.drawable.get() else {bail!("Not a drawable??")};
|
||||||
node.text.get().unwrap().data.lock().character_height = height;
|
|
||||||
|
text.data.lock().character_height = deserialize(message.as_ref())?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_text_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
pub fn set_text_flex(
|
||||||
let text = flexbuffers::Reader::get_root(data)?.get_str()?.to_string();
|
node: &Node,
|
||||||
node.text.get().unwrap().data.lock().text = text;
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let Some(Drawable::Text(text)) = node.drawable.get() else {bail!("Not a drawable??")};
|
||||||
|
|
||||||
|
text.data.lock().text = deserialize(message.as_ref())?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -167,13 +176,15 @@ impl Drop for Text {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn draw_all(sk: &StereoKit, draw_ctx: &DrawContext) {
|
pub fn draw_all(sk: &impl StereoKitDraw) {
|
||||||
for text in TEXT_REGISTRY.get_valid_contents() {
|
for text in TEXT_REGISTRY.get_valid_contents() {
|
||||||
text.draw(sk, draw_ctx);
|
if text.enabled.load(Ordering::Relaxed) {
|
||||||
|
text.draw(sk);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
pub fn create_flex(_node: &Node, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CreateTextInfo<'a> {
|
struct CreateTextInfo<'a> {
|
||||||
name: &'a str,
|
name: &'a str,
|
||||||
@@ -188,14 +199,14 @@ pub fn create_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Re
|
|||||||
bounds_align: TextAlign,
|
bounds_align: TextAlign,
|
||||||
color: [f32; 4],
|
color: [f32; 4],
|
||||||
}
|
}
|
||||||
let info: CreateTextInfo = deserialize(data)?;
|
let info: CreateTextInfo = deserialize(message.as_ref())?;
|
||||||
let node = Node::create(&calling_client, "/drawable/text", info.name, true);
|
let node = Node::create(&calling_client, "/drawable/text", info.name, true);
|
||||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
let transform = parse_transform(info.transform, true, true, true)?;
|
let transform = parse_transform(info.transform, true, true, true);
|
||||||
let color = Rgba::from_slice(&info.color);
|
let color = Rgba::from_slice(&info.color);
|
||||||
|
|
||||||
let node = node.add_to_scenegraph();
|
let node = node.add_to_scenegraph()?;
|
||||||
Spatial::add_to(&node, Some(parent), transform)?;
|
Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
Text::add_to(
|
Text::add_to(
|
||||||
&node,
|
&node,
|
||||||
info.font_resource,
|
info.font_resource,
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
use super::{Field, FieldTrait, Node};
|
use super::{Field, FieldTrait, Node};
|
||||||
use crate::core::client::Client;
|
use crate::core::client::Client;
|
||||||
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||||
use anyhow::{ensure, Result};
|
use crate::nodes::Message;
|
||||||
|
use color_eyre::eyre::{ensure, Result};
|
||||||
use glam::{vec3, vec3a, Vec3, Vec3A};
|
use glam::{vec3, vec3a, Vec3, Vec3A};
|
||||||
use mint::Vector3;
|
use mint::Vector3;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
@@ -16,7 +17,7 @@ pub struct BoxField {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl BoxField {
|
impl BoxField {
|
||||||
pub fn add_to(node: &Arc<Node>, size: Vector3<f32>) -> Result<()> {
|
pub fn add_to(node: &Arc<Node>, size: Vector3<f32>) -> Result<Arc<Field>> {
|
||||||
ensure!(
|
ensure!(
|
||||||
node.spatial.get().is_some(),
|
node.spatial.get().is_some(),
|
||||||
"Internal: Node does not have a spatial attached!"
|
"Internal: Node does not have a spatial attached!"
|
||||||
@@ -30,19 +31,24 @@ impl BoxField {
|
|||||||
size: Mutex::new(size.into()),
|
size: Mutex::new(size.into()),
|
||||||
};
|
};
|
||||||
box_field.add_field_methods(node);
|
box_field.add_field_methods(node);
|
||||||
node.add_local_signal("setSize", BoxField::set_size_flex);
|
node.add_local_signal("set_size", BoxField::set_size_flex);
|
||||||
let _ = node.field.set(Arc::new(Field::Box(box_field)));
|
let field = Arc::new(Field::Box(box_field));
|
||||||
Ok(())
|
let _ = node.field.set(field.clone());
|
||||||
|
Ok(field)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_size(&self, size: Vector3<f32>) {
|
pub fn set_size(&self, size: Vector3<f32>) {
|
||||||
*self.size.lock() = size.into();
|
*self.size.lock() = size.into();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_size_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
pub fn set_size_flex(
|
||||||
if let Field::Box(box_field) = node.field.get().unwrap().as_ref() {
|
node: &Node,
|
||||||
box_field.set_size(deserialize(data)?);
|
_calling_client: Arc<Client>,
|
||||||
}
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let Field::Box(box_field) = node.field.get().unwrap().as_ref() else { return Ok(()) };
|
||||||
|
box_field.set_size(deserialize(message.as_ref())?);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -63,7 +69,11 @@ impl FieldTrait for BoxField {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_box_field_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
pub fn create_box_field_flex(
|
||||||
|
_node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CreateFieldInfo<'a> {
|
struct CreateFieldInfo<'a> {
|
||||||
name: &'a str,
|
name: &'a str,
|
||||||
@@ -71,12 +81,12 @@ pub fn create_box_field_flex(_node: &Node, calling_client: Arc<Client>, data: &[
|
|||||||
transform: Transform,
|
transform: Transform,
|
||||||
size: Vector3<f32>,
|
size: Vector3<f32>,
|
||||||
}
|
}
|
||||||
let info: CreateFieldInfo = deserialize(data)?;
|
let info: CreateFieldInfo = deserialize(message.as_ref())?;
|
||||||
let node = Node::create(&calling_client, "/field", info.name, true);
|
let node = Node::create(&calling_client, "/field", info.name, true);
|
||||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
let transform = parse_transform(info.transform, true, true, false)?;
|
let transform = parse_transform(info.transform, true, true, false);
|
||||||
let node = node.add_to_scenegraph();
|
let node = node.add_to_scenegraph()?;
|
||||||
Spatial::add_to(&node, Some(parent), transform)?;
|
Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
BoxField::add_to(&node, info.size)?;
|
BoxField::add_to(&node, info.size)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
use super::{Field, FieldTrait, Node};
|
use super::{Field, FieldTrait, Node};
|
||||||
use crate::core::client::Client;
|
use crate::core::client::Client;
|
||||||
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||||
use anyhow::{ensure, Result};
|
use crate::nodes::Message;
|
||||||
|
use color_eyre::eyre::{ensure, Result};
|
||||||
use glam::{swizzles::*, vec2, Vec3A};
|
use glam::{swizzles::*, vec2, Vec3A};
|
||||||
use portable_atomic::AtomicF32;
|
use portable_atomic::AtomicF32;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
@@ -33,7 +34,7 @@ impl CylinderField {
|
|||||||
radius: AtomicF32::new(radius.abs()),
|
radius: AtomicF32::new(radius.abs()),
|
||||||
};
|
};
|
||||||
cylinder_field.add_field_methods(node);
|
cylinder_field.add_field_methods(node);
|
||||||
node.add_local_signal("setSize", CylinderField::set_size_flex);
|
node.add_local_signal("set_size", CylinderField::set_size_flex);
|
||||||
let _ = node.field.set(Arc::new(Field::Cylinder(cylinder_field)));
|
let _ = node.field.set(Arc::new(Field::Cylinder(cylinder_field)));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -43,11 +44,14 @@ impl CylinderField {
|
|||||||
self.radius.store(radius.abs(), Ordering::Relaxed);
|
self.radius.store(radius.abs(), Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_size_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
pub fn set_size_flex(
|
||||||
if let Field::Cylinder(cylinder_field) = node.field.get().unwrap().as_ref() {
|
node: &Node,
|
||||||
let (length, radius) = deserialize(data)?;
|
_calling_client: Arc<Client>,
|
||||||
cylinder_field.set_size(length, radius);
|
message: Message,
|
||||||
}
|
) -> Result<()> {
|
||||||
|
let Field::Cylinder(cylinder_field) = node.field.get().unwrap().as_ref() else { return Ok(()) };
|
||||||
|
let (length, radius) = deserialize(message.as_ref())?;
|
||||||
|
cylinder_field.set_size(length, radius);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -68,7 +72,7 @@ impl FieldTrait for CylinderField {
|
|||||||
pub fn create_cylinder_field_flex(
|
pub fn create_cylinder_field_flex(
|
||||||
_node: &Node,
|
_node: &Node,
|
||||||
calling_client: Arc<Client>,
|
calling_client: Arc<Client>,
|
||||||
data: &[u8],
|
message: Message,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CreateFieldInfo<'a> {
|
struct CreateFieldInfo<'a> {
|
||||||
@@ -78,12 +82,12 @@ pub fn create_cylinder_field_flex(
|
|||||||
length: f32,
|
length: f32,
|
||||||
radius: f32,
|
radius: f32,
|
||||||
}
|
}
|
||||||
let info: CreateFieldInfo = deserialize(data)?;
|
let info: CreateFieldInfo = deserialize(message.as_ref())?;
|
||||||
let node = Node::create(&calling_client, "/field", info.name, true);
|
let node = Node::create(&calling_client, "/field", info.name, true);
|
||||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
let transform = parse_transform(info.transform, true, true, false)?;
|
let transform = parse_transform(info.transform, true, true, false);
|
||||||
let node = node.add_to_scenegraph();
|
let node = node.add_to_scenegraph()?;
|
||||||
Spatial::add_to(&node, Some(parent), transform)?;
|
Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
CylinderField::add_to(&node, dbg!(info.length), dbg!(info.radius))?;
|
CylinderField::add_to(&node, info.length, info.radius)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,43 @@
|
|||||||
mod r#box;
|
pub mod r#box;
|
||||||
mod cylinder;
|
mod cylinder;
|
||||||
mod sphere;
|
mod sphere;
|
||||||
|
mod torus;
|
||||||
|
|
||||||
use self::cylinder::{create_cylinder_field_flex, CylinderField};
|
use self::cylinder::{create_cylinder_field_flex, CylinderField};
|
||||||
use self::r#box::{create_box_field_flex, BoxField};
|
use self::r#box::{create_box_field_flex, BoxField};
|
||||||
use self::sphere::{create_sphere_field_flex, SphereField};
|
use self::sphere::{create_sphere_field_flex, SphereField};
|
||||||
|
use self::torus::{create_torus_field_flex, TorusField};
|
||||||
|
|
||||||
|
use super::alias::AliasInfo;
|
||||||
use super::spatial::Spatial;
|
use super::spatial::Spatial;
|
||||||
use super::Node;
|
use super::{Message, Node};
|
||||||
use crate::core::client::Client;
|
use crate::core::client::Client;
|
||||||
|
use crate::core::scenegraph::MethodResponseSender;
|
||||||
use crate::nodes::spatial::find_reference_space;
|
use crate::nodes::spatial::find_reference_space;
|
||||||
use anyhow::Result;
|
use color_eyre::eyre::Result;
|
||||||
use glam::{vec2, vec3a, Vec3, Vec3A};
|
use glam::{vec2, vec3a, Vec3, Vec3A};
|
||||||
use mint::Vector3;
|
use mint::Vector3;
|
||||||
use serde::Deserialize;
|
use once_cell::sync::Lazy;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||||
|
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
pub static FIELD_ALIAS_INFO: Lazy<AliasInfo> = Lazy::new(|| AliasInfo {
|
||||||
|
server_methods: vec!["distance", "normal", "closest_point", "ray_march"],
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
|
||||||
pub trait FieldTrait {
|
pub trait FieldTrait {
|
||||||
|
fn add_field_methods(&self, node: &Arc<Node>) {
|
||||||
|
node.add_local_method("distance", field_distance_flex);
|
||||||
|
node.add_local_method("normal", field_normal_flex);
|
||||||
|
node.add_local_method("closest_point", field_closest_point_flex);
|
||||||
|
node.add_local_method("ray_march", field_ray_march_flex);
|
||||||
|
}
|
||||||
|
fn spatial_ref(&self) -> &Spatial;
|
||||||
|
|
||||||
fn local_distance(&self, p: Vec3A) -> f32;
|
fn local_distance(&self, p: Vec3A) -> f32;
|
||||||
fn local_normal(&self, p: Vec3A, r: f32) -> Vec3A {
|
fn local_normal(&self, p: Vec3A, r: f32) -> Vec3A {
|
||||||
let d = self.local_distance(p);
|
let d = self.local_distance(p);
|
||||||
@@ -61,93 +79,36 @@ pub trait FieldTrait {
|
|||||||
.transform_point3a(self.local_closest_point(local_p, r))
|
.transform_point3a(self.local_closest_point(local_p, r))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_field_methods(&self, node: &Arc<Node>) {
|
fn ray_march(&self, ray: Ray) -> RayMarchResult {
|
||||||
node.add_local_method("distance", field_distance_flex);
|
let mut result = RayMarchResult {
|
||||||
node.add_local_method("normal", field_normal_flex);
|
min_distance: f32::MAX,
|
||||||
node.add_local_method("closest_point", field_closest_point_flex);
|
deepest_point_distance: 0_f32,
|
||||||
}
|
ray_length: 0_f32,
|
||||||
|
ray_steps: 0,
|
||||||
|
};
|
||||||
|
|
||||||
fn spatial_ref(&self) -> &Spatial;
|
let ray_to_field_matrix =
|
||||||
}
|
Spatial::space_to_space_matrix(Some(&ray.space), Some(self.spatial_ref()));
|
||||||
|
let mut ray_point = ray_to_field_matrix.transform_point3a(ray.origin.into());
|
||||||
|
let ray_direction = ray_to_field_matrix.transform_vector3a(ray.direction.into());
|
||||||
|
|
||||||
fn field_distance_flex(node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<Vec<u8>> {
|
while result.ray_steps < MAX_RAY_STEPS && result.ray_length < MAX_RAY_LENGTH {
|
||||||
#[derive(Deserialize)]
|
let distance = self.local_distance(ray_point);
|
||||||
struct FieldInfoArgs<'a> {
|
let march_distance = distance.clamp(MIN_RAY_MARCH, MAX_RAY_MARCH);
|
||||||
reference_space_path: &'a str,
|
|
||||||
point: Vector3<f32>,
|
|
||||||
}
|
|
||||||
let args: FieldInfoArgs = deserialize(data)?;
|
|
||||||
let reference_space = find_reference_space(&calling_client, args.reference_space_path)?;
|
|
||||||
|
|
||||||
let distance = node
|
result.ray_length += march_distance;
|
||||||
.field
|
ray_point += ray_direction * march_distance;
|
||||||
.get()
|
|
||||||
.unwrap()
|
|
||||||
.distance(reference_space.as_ref(), args.point.into());
|
|
||||||
Ok(serialize(distance)?)
|
|
||||||
}
|
|
||||||
fn field_normal_flex(node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<Vec<u8>> {
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct FieldInfoArgs<'a> {
|
|
||||||
reference_space_path: &'a str,
|
|
||||||
point: Vector3<f32>,
|
|
||||||
radius: Option<f32>,
|
|
||||||
}
|
|
||||||
let args: FieldInfoArgs = deserialize(data)?;
|
|
||||||
let reference_space = find_reference_space(&calling_client, args.reference_space_path)?;
|
|
||||||
|
|
||||||
let normal = node.field.get().as_ref().unwrap().normal(
|
if result.min_distance > distance {
|
||||||
reference_space.as_ref(),
|
result.deepest_point_distance = result.ray_length;
|
||||||
args.point.into(),
|
result.min_distance = distance;
|
||||||
args.radius.unwrap_or(0.001),
|
}
|
||||||
);
|
|
||||||
Ok(serialize(mint::Vector3::from(normal))?)
|
|
||||||
}
|
|
||||||
fn field_closest_point_flex(
|
|
||||||
node: &Node,
|
|
||||||
calling_client: Arc<Client>,
|
|
||||||
data: &[u8],
|
|
||||||
) -> Result<Vec<u8>> {
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct FieldInfoArgs<'a> {
|
|
||||||
reference_space_path: &'a str,
|
|
||||||
point: Vector3<f32>,
|
|
||||||
radius: Option<f32>,
|
|
||||||
}
|
|
||||||
let args: FieldInfoArgs = deserialize(data)?;
|
|
||||||
let reference_space = find_reference_space(&calling_client, args.reference_space_path)?;
|
|
||||||
|
|
||||||
let closest_point = node.field.get().as_ref().unwrap().closest_point(
|
result.ray_steps += 1;
|
||||||
reference_space.as_ref(),
|
|
||||||
args.point.into(),
|
|
||||||
args.radius.unwrap_or(0.001),
|
|
||||||
);
|
|
||||||
Ok(serialize(mint::Vector3::from(closest_point))?)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub enum Field {
|
|
||||||
Box(BoxField),
|
|
||||||
Cylinder(CylinderField),
|
|
||||||
Sphere(SphereField),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Deref for Field {
|
|
||||||
type Target = dyn FieldTrait;
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
match self {
|
|
||||||
Field::Box(field) => field,
|
|
||||||
Field::Cylinder(field) => field,
|
|
||||||
Field::Sphere(field) => field,
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn create_interface(client: &Arc<Client>) {
|
result
|
||||||
let node = Node::create(client, "", "field", false);
|
}
|
||||||
node.add_local_signal("createBoxField", create_box_field_flex);
|
|
||||||
node.add_local_signal("createCylinderField", create_cylinder_field_flex);
|
|
||||||
node.add_local_signal("createSphereField", create_sphere_field_flex);
|
|
||||||
node.add_to_scenegraph();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Ray {
|
pub struct Ray {
|
||||||
@@ -156,9 +117,9 @@ pub struct Ray {
|
|||||||
pub space: Arc<Spatial>,
|
pub space: Arc<Spatial>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Serialize)]
|
||||||
pub struct RayMarchResult {
|
pub struct RayMarchResult {
|
||||||
pub ray: Ray,
|
pub min_distance: f32,
|
||||||
pub distance: f32,
|
|
||||||
pub deepest_point_distance: f32,
|
pub deepest_point_distance: f32,
|
||||||
pub ray_length: f32,
|
pub ray_length: f32,
|
||||||
pub ray_steps: u32,
|
pub ray_steps: u32,
|
||||||
@@ -173,40 +134,131 @@ const MAX_RAY_MARCH: f32 = f32::MAX;
|
|||||||
// const MIN_RAY_LENGTH: f32 = 0_f32;
|
// const MIN_RAY_LENGTH: f32 = 0_f32;
|
||||||
const MAX_RAY_LENGTH: f32 = 1000_f32;
|
const MAX_RAY_LENGTH: f32 = 1000_f32;
|
||||||
|
|
||||||
pub fn ray_march(ray: Ray, field: &Field) -> RayMarchResult {
|
fn field_distance_flex(
|
||||||
let mut result = RayMarchResult {
|
node: &Node,
|
||||||
ray,
|
calling_client: Arc<Client>,
|
||||||
distance: f32::MAX,
|
message: Message,
|
||||||
deepest_point_distance: 0_f32,
|
response: MethodResponseSender,
|
||||||
ray_length: 0_f32,
|
) {
|
||||||
ray_steps: 0,
|
response.wrap_sync(move || {
|
||||||
};
|
#[derive(Deserialize)]
|
||||||
|
struct FieldInfoArgs<'a> {
|
||||||
let ray_to_field_matrix =
|
reference_space_path: &'a str,
|
||||||
Spatial::space_to_space_matrix(Some(&result.ray.space), Some(field.spatial_ref()));
|
point: Vector3<f32>,
|
||||||
let mut ray_point = ray_to_field_matrix.transform_point3a(result.ray.origin.into());
|
|
||||||
let ray_direction = ray_to_field_matrix.transform_vector3a(result.ray.direction.into());
|
|
||||||
|
|
||||||
while result.ray_steps < MAX_RAY_STEPS && result.ray_length < MAX_RAY_LENGTH {
|
|
||||||
let distance = field.local_distance(ray_point);
|
|
||||||
let march_distance = distance.clamp(MIN_RAY_MARCH, MAX_RAY_MARCH);
|
|
||||||
|
|
||||||
result.ray_length += march_distance;
|
|
||||||
ray_point += ray_direction * march_distance;
|
|
||||||
|
|
||||||
if result.distance > distance {
|
|
||||||
result.deepest_point_distance = result.ray_length;
|
|
||||||
}
|
}
|
||||||
result.distance = distance.min(result.distance);
|
let args: FieldInfoArgs = deserialize(message.as_ref())?;
|
||||||
|
let reference_space = find_reference_space(&calling_client, args.reference_space_path)?;
|
||||||
|
|
||||||
result.ray_steps += 1;
|
let distance = node
|
||||||
|
.field
|
||||||
|
.get()
|
||||||
|
.unwrap()
|
||||||
|
.distance(reference_space.as_ref(), args.point.into());
|
||||||
|
Ok(serialize(distance)?.into())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
fn field_normal_flex(
|
||||||
|
node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
response.wrap_sync(move || {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct FieldInfoArgs<'a> {
|
||||||
|
reference_space_path: &'a str,
|
||||||
|
point: Vector3<f32>,
|
||||||
|
}
|
||||||
|
let args: FieldInfoArgs = deserialize(message.as_ref())?;
|
||||||
|
let reference_space = find_reference_space(&calling_client, args.reference_space_path)?;
|
||||||
|
|
||||||
|
let normal = node.field.get().as_ref().unwrap().normal(
|
||||||
|
reference_space.as_ref(),
|
||||||
|
args.point.into(),
|
||||||
|
0.001,
|
||||||
|
);
|
||||||
|
Ok(serialize(mint::Vector3::from(normal))?.into())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
fn field_closest_point_flex(
|
||||||
|
node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
response.wrap_sync(move || {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct FieldInfoArgs<'a> {
|
||||||
|
reference_space_path: &'a str,
|
||||||
|
point: Vector3<f32>,
|
||||||
|
}
|
||||||
|
let args: FieldInfoArgs = deserialize(message.as_ref())?;
|
||||||
|
let reference_space = find_reference_space(&calling_client, args.reference_space_path)?;
|
||||||
|
|
||||||
|
let closest_point = node.field.get().as_ref().unwrap().closest_point(
|
||||||
|
reference_space.as_ref(),
|
||||||
|
args.point.into(),
|
||||||
|
0.001,
|
||||||
|
);
|
||||||
|
Ok(serialize(mint::Vector3::from(closest_point))?.into())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
fn field_ray_march_flex(
|
||||||
|
node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
response.wrap_sync(move || {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct FieldInfoArgs<'a> {
|
||||||
|
reference_space_path: &'a str,
|
||||||
|
ray_origin: Vector3<f32>,
|
||||||
|
ray_direction: Vector3<f32>,
|
||||||
|
}
|
||||||
|
let args: FieldInfoArgs = deserialize(message.as_ref())?;
|
||||||
|
let reference_space = find_reference_space(&calling_client, args.reference_space_path)?;
|
||||||
|
|
||||||
|
let ray_march_result = node.field.get().unwrap().ray_march(Ray {
|
||||||
|
origin: args.ray_origin.into(),
|
||||||
|
direction: args.ray_direction.into(),
|
||||||
|
space: reference_space,
|
||||||
|
});
|
||||||
|
Ok(serialize(ray_march_result)?.into())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum Field {
|
||||||
|
Box(BoxField),
|
||||||
|
Cylinder(CylinderField),
|
||||||
|
Sphere(SphereField),
|
||||||
|
Torus(TorusField),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Deref for Field {
|
||||||
|
type Target = dyn FieldTrait;
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
match self {
|
||||||
|
Field::Box(field) => field,
|
||||||
|
Field::Cylinder(field) => field,
|
||||||
|
Field::Sphere(field) => field,
|
||||||
|
Field::Torus(field) => field,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
result
|
pub fn create_interface(client: &Arc<Client>) -> Result<()> {
|
||||||
|
let node = Node::create(client, "", "field", false);
|
||||||
|
node.add_local_signal("create_box_field", create_box_field_flex);
|
||||||
|
node.add_local_signal("create_cylinder_field", create_cylinder_field_flex);
|
||||||
|
node.add_local_signal("create_sphere_field", create_sphere_field_flex);
|
||||||
|
node.add_local_signal("create_torus_field", create_torus_field_flex);
|
||||||
|
node.add_to_scenegraph().map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn find_field(client: &Client, path: &str) -> Result<Arc<Field>> {
|
pub fn find_field(client: &Client, path: &str) -> Result<Arc<Field>> {
|
||||||
Ok(client
|
client
|
||||||
.get_node("Field", path)?
|
.get_node("Field", path)?
|
||||||
.get_aspect("Field", "info", |n| &n.field)?)
|
.get_aspect("Field", "info", |n| &n.field)
|
||||||
|
.cloned()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
use super::{Field, FieldTrait, Node};
|
use super::{Field, FieldTrait, Node};
|
||||||
use crate::core::client::Client;
|
use crate::core::client::Client;
|
||||||
use crate::nodes::spatial::{find_spatial_parent, Spatial};
|
use crate::nodes::spatial::{find_spatial_parent, Spatial};
|
||||||
use anyhow::{ensure, Result};
|
use crate::nodes::Message;
|
||||||
|
use color_eyre::eyre::{ensure, Result};
|
||||||
use glam::{Mat4, Vec3A};
|
use glam::{Mat4, Vec3A};
|
||||||
use mint::Vector3;
|
use mint::Vector3;
|
||||||
use portable_atomic::AtomicF32;
|
use portable_atomic::AtomicF32;
|
||||||
@@ -30,7 +31,7 @@ impl SphereField {
|
|||||||
radius: AtomicF32::new(radius),
|
radius: AtomicF32::new(radius),
|
||||||
};
|
};
|
||||||
sphere_field.add_field_methods(node);
|
sphere_field.add_field_methods(node);
|
||||||
node.add_local_signal("setRadius", SphereField::set_radius_flex);
|
node.add_local_signal("set_radius", SphereField::set_radius_flex);
|
||||||
let _ = node.field.set(Arc::new(Field::Sphere(sphere_field)));
|
let _ = node.field.set(Arc::new(Field::Sphere(sphere_field)));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -39,11 +40,13 @@ impl SphereField {
|
|||||||
self.radius.store(radius, Ordering::Relaxed);
|
self.radius.store(radius, Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_radius_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
pub fn set_radius_flex(
|
||||||
let radius = flexbuffers::Reader::get_root(data)?.get_f64()? as f32;
|
node: &Node,
|
||||||
if let Field::Sphere(sphere_field) = node.field.get().unwrap().as_ref() {
|
_calling_client: Arc<Client>,
|
||||||
sphere_field.set_radius(radius);
|
message: Message,
|
||||||
}
|
) -> Result<()> {
|
||||||
|
let Field::Sphere(sphere_field) = node.field.get().unwrap().as_ref() else { return Ok(()) };
|
||||||
|
sphere_field.set_radius(deserialize(message.as_ref())?);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -66,7 +69,7 @@ impl FieldTrait for SphereField {
|
|||||||
pub fn create_sphere_field_flex(
|
pub fn create_sphere_field_flex(
|
||||||
_node: &Node,
|
_node: &Node,
|
||||||
calling_client: Arc<Client>,
|
calling_client: Arc<Client>,
|
||||||
data: &[u8],
|
message: Message,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CreateFieldInfo<'a> {
|
struct CreateFieldInfo<'a> {
|
||||||
@@ -75,7 +78,7 @@ pub fn create_sphere_field_flex(
|
|||||||
origin: Option<Vector3<f32>>,
|
origin: Option<Vector3<f32>>,
|
||||||
radius: f32,
|
radius: f32,
|
||||||
}
|
}
|
||||||
let info: CreateFieldInfo = deserialize(data)?;
|
let info: CreateFieldInfo = deserialize(message.as_ref())?;
|
||||||
let node = Node::create(&calling_client, "/field", info.name, true);
|
let node = Node::create(&calling_client, "/field", info.name, true);
|
||||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
let transform = Mat4::from_translation(
|
let transform = Mat4::from_translation(
|
||||||
@@ -83,8 +86,8 @@ pub fn create_sphere_field_flex(
|
|||||||
.unwrap_or_else(|| Vector3::from([0.0; 3]))
|
.unwrap_or_else(|| Vector3::from([0.0; 3]))
|
||||||
.into(),
|
.into(),
|
||||||
);
|
);
|
||||||
let node = node.add_to_scenegraph();
|
let node = node.add_to_scenegraph()?;
|
||||||
Spatial::add_to(&node, Some(parent), transform)?;
|
Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
SphereField::add_to(&node, info.radius)?;
|
SphereField::add_to(&node, info.radius)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
93
src/nodes/fields/torus.rs
Normal file
93
src/nodes/fields/torus.rs
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
use super::{Field, FieldTrait, Node};
|
||||||
|
use crate::core::client::Client;
|
||||||
|
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||||
|
use crate::nodes::Message;
|
||||||
|
use color_eyre::eyre::{ensure, Result};
|
||||||
|
use glam::{swizzles::*, vec2, Vec3A};
|
||||||
|
use portable_atomic::AtomicF32;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use stardust_xr::schemas::flex::deserialize;
|
||||||
|
use stardust_xr::values::Transform;
|
||||||
|
|
||||||
|
use std::sync::atomic::Ordering;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
pub struct TorusField {
|
||||||
|
space: Arc<Spatial>,
|
||||||
|
radius_a: AtomicF32,
|
||||||
|
radius_b: AtomicF32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TorusField {
|
||||||
|
pub fn add_to(node: &Arc<Node>, radius_a: f32, radius_b: f32) -> Result<()> {
|
||||||
|
ensure!(
|
||||||
|
node.spatial.get().is_some(),
|
||||||
|
"Internal: Node does not have a spatial attached!"
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
node.field.get().is_none(),
|
||||||
|
"Internal: Node already has a field attached!"
|
||||||
|
);
|
||||||
|
let torus_field = TorusField {
|
||||||
|
space: node.spatial.get().unwrap().clone(),
|
||||||
|
radius_a: AtomicF32::new(radius_a.abs()),
|
||||||
|
radius_b: AtomicF32::new(radius_b.abs()),
|
||||||
|
};
|
||||||
|
torus_field.add_field_methods(node);
|
||||||
|
node.add_local_signal("set_size", TorusField::set_size_flex);
|
||||||
|
let _ = node.field.set(Arc::new(Field::Torus(torus_field)));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_size(&self, radius_a: f32, radius_b: f32) {
|
||||||
|
self.radius_a.store(radius_a.abs(), Ordering::Relaxed);
|
||||||
|
self.radius_b.store(radius_b.abs(), Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_size_flex(
|
||||||
|
node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let Field::Torus(torus_field) = node.field.get().unwrap().as_ref() else { return Ok(()) };
|
||||||
|
let (radius_a, radius_b) = deserialize(message.as_ref())?;
|
||||||
|
torus_field.set_size(radius_a, radius_b);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FieldTrait for TorusField {
|
||||||
|
fn local_distance(&self, p: Vec3A) -> f32 {
|
||||||
|
let radius_a = self.radius_a.load(Ordering::Relaxed);
|
||||||
|
let radius_b = self.radius_b.load(Ordering::Relaxed);
|
||||||
|
let q = vec2(p.xz().length() - radius_a, p.y);
|
||||||
|
q.length() - radius_b
|
||||||
|
}
|
||||||
|
fn spatial_ref(&self) -> &Spatial {
|
||||||
|
self.space.as_ref()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_torus_field_flex(
|
||||||
|
_node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct CreateFieldInfo<'a> {
|
||||||
|
name: &'a str,
|
||||||
|
parent_path: &'a str,
|
||||||
|
transform: Transform,
|
||||||
|
radius_a: f32,
|
||||||
|
radius_b: f32,
|
||||||
|
}
|
||||||
|
let info: CreateFieldInfo = deserialize(message.as_ref())?;
|
||||||
|
let node = Node::create(&calling_client, "/field", info.name, true);
|
||||||
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
|
let transform = parse_transform(info.transform, true, true, false);
|
||||||
|
let node = node.add_to_scenegraph()?;
|
||||||
|
Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
|
TorusField::add_to(&node, info.radius_a, info.radius_b)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -3,9 +3,10 @@ use crate::{
|
|||||||
core::client::{Client, INTERNAL_CLIENT},
|
core::client::{Client, INTERNAL_CLIENT},
|
||||||
nodes::alias::AliasInfo,
|
nodes::alias::AliasInfo,
|
||||||
};
|
};
|
||||||
|
use color_eyre::eyre::Result;
|
||||||
use glam::{vec3, Mat4};
|
use glam::{vec3, Mat4};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use stereokit::StereoKit;
|
use stereokit::StereoKitMultiThread;
|
||||||
|
|
||||||
lazy_static::lazy_static! {
|
lazy_static::lazy_static! {
|
||||||
static ref HMD: Arc<Node> = create();
|
static ref HMD: Arc<Node> = create();
|
||||||
@@ -13,13 +14,16 @@ lazy_static::lazy_static! {
|
|||||||
|
|
||||||
fn create() -> Arc<Node> {
|
fn create() -> Arc<Node> {
|
||||||
let node = Arc::new(Node::create(&INTERNAL_CLIENT, "", "hmd", false));
|
let node = Arc::new(Node::create(&INTERNAL_CLIENT, "", "hmd", false));
|
||||||
Spatial::add_to(&node, None, Mat4::IDENTITY).unwrap();
|
Spatial::add_to(&node, None, Mat4::IDENTITY, false).expect("Unable to make spatial for HMD");
|
||||||
|
|
||||||
node
|
node
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn frame(sk: &StereoKit) {
|
pub fn frame(sk: &impl StereoKitMultiThread) {
|
||||||
let spatial = HMD.spatial.get().unwrap();
|
let spatial = HMD
|
||||||
|
.spatial
|
||||||
|
.get()
|
||||||
|
.expect("Unable to get spatial to update HMD");
|
||||||
let hmd_pose = sk.input_head();
|
let hmd_pose = sk.input_head();
|
||||||
*spatial.transform.lock() = Mat4::from_scale_rotation_translation(
|
*spatial.transform.lock() = Mat4::from_scale_rotation_translation(
|
||||||
vec3(1.0, 1.0, 1.0),
|
vec3(1.0, 1.0, 1.0),
|
||||||
@@ -28,14 +32,14 @@ pub fn frame(sk: &StereoKit) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn make_alias(client: &Arc<Client>) -> Arc<Node> {
|
pub fn make_alias(client: &Arc<Client>) -> Result<Arc<Node>> {
|
||||||
Alias::new(
|
Alias::create(
|
||||||
client,
|
client,
|
||||||
"",
|
"",
|
||||||
"hmd",
|
"hmd",
|
||||||
&HMD,
|
&HMD,
|
||||||
AliasInfo {
|
AliasInfo {
|
||||||
local_signals: vec!["getTransform"],
|
server_signals: vec!["get_bounds", "get_transform"],
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -11,7 +11,10 @@ pub struct Hand {
|
|||||||
pub base: FlatHand,
|
pub base: FlatHand,
|
||||||
}
|
}
|
||||||
impl InputSpecialization for Hand {
|
impl InputSpecialization for Hand {
|
||||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
fn compare_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||||
|
self.true_distance(space, field).abs()
|
||||||
|
}
|
||||||
|
fn true_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||||
let mut min_distance = f32::MAX;
|
let mut min_distance = f32::MAX;
|
||||||
|
|
||||||
for tip in [
|
for tip in [
|
||||||
@@ -28,7 +31,7 @@ impl InputSpecialization for Hand {
|
|||||||
}
|
}
|
||||||
fn serialize(
|
fn serialize(
|
||||||
&self,
|
&self,
|
||||||
_distance_link: &DistanceLink,
|
distance_link: &DistanceLink,
|
||||||
local_to_handler_matrix: Mat4,
|
local_to_handler_matrix: Mat4,
|
||||||
) -> InputDataType {
|
) -> InputDataType {
|
||||||
let mut hand = self.base;
|
let mut hand = self.base;
|
||||||
@@ -60,12 +63,15 @@ impl InputSpecialization for Hand {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
for joint in joints {
|
for joint in joints {
|
||||||
let joint_matrix =
|
let joint_matrix = local_to_handler_matrix
|
||||||
Mat4::from_rotation_translation(joint.rotation.into(), joint.position.into())
|
* Mat4::from_rotation_translation(joint.rotation.into(), joint.position.into());
|
||||||
* local_to_handler_matrix;
|
|
||||||
let (_, rotation, position) = joint_matrix.to_scale_rotation_translation();
|
let (_, rotation, position) = joint_matrix.to_scale_rotation_translation();
|
||||||
joint.position = position.into();
|
joint.position = position.into();
|
||||||
joint.rotation = rotation.into();
|
joint.rotation = rotation.into();
|
||||||
|
joint.distance = distance_link
|
||||||
|
.handler
|
||||||
|
.field
|
||||||
|
.distance(&distance_link.handler.spatial, position.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
InputDataType::Hand(Box::new(hand))
|
InputDataType::Hand(Box::new(hand))
|
||||||
|
|||||||
@@ -6,30 +6,37 @@ use self::hand::Hand;
|
|||||||
use self::pointer::Pointer;
|
use self::pointer::Pointer;
|
||||||
use self::tip::Tip;
|
use self::tip::Tip;
|
||||||
|
|
||||||
use super::fields::Field;
|
use super::{
|
||||||
use super::spatial::{find_spatial_parent, parse_transform, Spatial};
|
alias::{Alias, AliasInfo},
|
||||||
use super::Node;
|
fields::{find_field, Field, FIELD_ALIAS_INFO},
|
||||||
use crate::core::client::Client;
|
spatial::{find_spatial_parent, parse_transform, Spatial},
|
||||||
use crate::core::eventloop::FRAME;
|
Message, Node,
|
||||||
|
};
|
||||||
use crate::core::registry::Registry;
|
use crate::core::registry::Registry;
|
||||||
use crate::nodes::fields::find_field;
|
use crate::core::{client::Client, node_collections::LifeLinkedNodeMap};
|
||||||
use anyhow::{ensure, Result};
|
use color_eyre::eyre::{ensure, Result};
|
||||||
use glam::Mat4;
|
use glam::Mat4;
|
||||||
use nanoid::nanoid;
|
use once_cell::sync::OnceCell;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
use portable_atomic::AtomicBool;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use stardust_xr::schemas::flat::{Datamap, InputDataType};
|
|
||||||
use stardust_xr::schemas::{flat::InputData, flex::deserialize};
|
use stardust_xr::schemas::{flat::InputData, flex::deserialize};
|
||||||
|
use stardust_xr::schemas::{
|
||||||
|
flat::{Datamap, InputDataType},
|
||||||
|
flex::serialize,
|
||||||
|
};
|
||||||
use stardust_xr::values::Transform;
|
use stardust_xr::values::Transform;
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
use std::sync::atomic::Ordering;
|
use std::sync::atomic::Ordering;
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::{Arc, Weak};
|
||||||
|
use tracing::{debug_span, instrument};
|
||||||
|
|
||||||
static INPUT_METHOD_REGISTRY: Registry<InputMethod> = Registry::new();
|
static INPUT_METHOD_REGISTRY: Registry<InputMethod> = Registry::new();
|
||||||
static INPUT_HANDLER_REGISTRY: Registry<InputHandler> = Registry::new();
|
static INPUT_HANDLER_REGISTRY: Registry<InputHandler> = Registry::new();
|
||||||
|
|
||||||
pub trait InputSpecialization: Send + Sync {
|
pub trait InputSpecialization: Send + Sync {
|
||||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32;
|
fn compare_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32;
|
||||||
|
fn true_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32;
|
||||||
fn serialize(
|
fn serialize(
|
||||||
&self,
|
&self,
|
||||||
distance_link: &DistanceLink,
|
distance_link: &DistanceLink,
|
||||||
@@ -53,63 +60,154 @@ impl Deref for InputType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct InputMethod {
|
pub struct InputMethod {
|
||||||
pub uid: String,
|
node: Weak<Node>,
|
||||||
|
uid: String,
|
||||||
pub enabled: Mutex<bool>,
|
pub enabled: Mutex<bool>,
|
||||||
pub spatial: Arc<Spatial>,
|
pub spatial: Arc<Spatial>,
|
||||||
pub specialization: Mutex<InputType>,
|
pub specialization: Mutex<InputType>,
|
||||||
pub captures: Registry<InputHandler>,
|
captures: Registry<InputHandler>,
|
||||||
pub datamap: Mutex<Option<Datamap>>,
|
pub datamap: Mutex<Option<Datamap>>,
|
||||||
|
handler_aliases: LifeLinkedNodeMap<String>,
|
||||||
|
handler_order: OnceCell<Mutex<Vec<Weak<InputHandler>>>>,
|
||||||
}
|
}
|
||||||
impl InputMethod {
|
impl InputMethod {
|
||||||
pub fn new(spatial: Arc<Spatial>, specialization: InputType) -> Arc<InputMethod> {
|
|
||||||
let method = InputMethod {
|
|
||||||
uid: nanoid!(),
|
|
||||||
enabled: Mutex::new(true),
|
|
||||||
spatial,
|
|
||||||
specialization: Mutex::new(specialization),
|
|
||||||
captures: Registry::new(),
|
|
||||||
datamap: Mutex::new(None),
|
|
||||||
};
|
|
||||||
INPUT_METHOD_REGISTRY.add(method)
|
|
||||||
}
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn add_to(
|
pub fn add_to(
|
||||||
node: &Arc<Node>,
|
node: &Arc<Node>,
|
||||||
specialization: InputType,
|
specialization: InputType,
|
||||||
datamap: Option<Datamap>,
|
datamap: Option<Datamap>,
|
||||||
) -> Result<()> {
|
) -> Result<Arc<InputMethod>> {
|
||||||
ensure!(
|
ensure!(
|
||||||
node.spatial.get().is_some(),
|
node.spatial.get().is_some(),
|
||||||
"Internal: Node does not have a spatial attached!"
|
"Internal: Node does not have a spatial attached!"
|
||||||
);
|
);
|
||||||
|
|
||||||
node.add_local_signal("setDatamap", InputMethod::set_datamap);
|
node.add_local_signal("capture", InputMethod::capture_flex);
|
||||||
|
node.add_local_signal("set_datamap", InputMethod::set_datamap_flex);
|
||||||
|
node.add_local_signal("set_handlers", InputMethod::set_handlers_flex);
|
||||||
|
|
||||||
let method = InputMethod {
|
let method = InputMethod {
|
||||||
|
node: Arc::downgrade(node),
|
||||||
uid: node.uid.clone(),
|
uid: node.uid.clone(),
|
||||||
enabled: Mutex::new(true),
|
enabled: Mutex::new(true),
|
||||||
spatial: node.spatial.get().unwrap().clone(),
|
spatial: node.spatial.get().unwrap().clone(),
|
||||||
specialization: Mutex::new(specialization),
|
specialization: Mutex::new(specialization),
|
||||||
captures: Registry::new(),
|
captures: Registry::new(),
|
||||||
datamap: Mutex::new(datamap),
|
datamap: Mutex::new(datamap),
|
||||||
|
handler_aliases: LifeLinkedNodeMap::default(),
|
||||||
|
handler_order: OnceCell::new(),
|
||||||
};
|
};
|
||||||
|
for handler in INPUT_HANDLER_REGISTRY.get_valid_contents() {
|
||||||
|
method.handle_new_handler(&handler);
|
||||||
|
method.make_alias(&handler);
|
||||||
|
}
|
||||||
let method = INPUT_METHOD_REGISTRY.add(method);
|
let method = INPUT_METHOD_REGISTRY.add(method);
|
||||||
let _ = node.input_method.set(method);
|
let _ = node.input_method.set(method.clone());
|
||||||
|
Ok(method)
|
||||||
|
}
|
||||||
|
fn get(node: &Node) -> Result<Arc<Self>> {
|
||||||
|
node.get_aspect("Input Method", "input method", |n| &n.input_method)
|
||||||
|
.cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capture_flex(node: &Node, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
|
let method = InputMethod::get(node)?;
|
||||||
|
let handler = InputHandler::find(&calling_client, deserialize(message.as_ref())?)?;
|
||||||
|
|
||||||
|
method.captures.add_raw(&handler);
|
||||||
|
node.send_remote_signal("capture", message)
|
||||||
|
}
|
||||||
|
fn set_datamap_flex(node: &Node, _calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
|
let method = InputMethod::get(node)?;
|
||||||
|
method.datamap.lock().replace(Datamap::new(message.data)?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn set_handlers_flex(node: &Node, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
|
let method = InputMethod::get(node)?;
|
||||||
|
let handler_paths: Vec<&str> = deserialize(message.as_ref())?;
|
||||||
|
let handlers: Vec<Weak<InputHandler>> = handler_paths
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|p| InputHandler::find(&calling_client, p).ok())
|
||||||
|
.map(|h| Arc::downgrade(&h))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
*method
|
||||||
|
.handler_order
|
||||||
|
.get_or_init(|| Mutex::new(Vec::new()))
|
||||||
|
.lock() = handlers;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_datamap(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
fn make_alias(&self, handler: &InputHandler) {
|
||||||
node.input_method
|
let Some(method_node) = self.node.upgrade() else {return};
|
||||||
.get()
|
let Some(handler_node) = handler.node.upgrade() else {return};
|
||||||
.unwrap()
|
let Some(client) = handler_node.get_client() else {return};
|
||||||
.datamap
|
let Ok(method_alias) = Alias::create(
|
||||||
|
&client,
|
||||||
|
handler_node.get_path(),
|
||||||
|
&self.uid,
|
||||||
|
&method_node,
|
||||||
|
AliasInfo {
|
||||||
|
server_signals: vec!["capture"],
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
) else {return};
|
||||||
|
method_alias.enabled.store(false, Ordering::Relaxed);
|
||||||
|
handler
|
||||||
|
.method_aliases
|
||||||
|
.add(self as *const InputMethod as usize, &method_alias);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compare_distance(&self, to: &Field) -> f32 {
|
||||||
|
self.specialization
|
||||||
.lock()
|
.lock()
|
||||||
.replace(Datamap::new(data.to_vec())?);
|
.compare_distance(&self.spatial, to)
|
||||||
Ok(())
|
}
|
||||||
|
fn true_distance(&self, to: &Field) -> f32 {
|
||||||
|
self.specialization.lock().true_distance(&self.spatial, to)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn distance(&self, to: &Field) -> f32 {
|
fn handle_new_handler(&self, handler: &InputHandler) {
|
||||||
self.specialization.lock().distance(&self.spatial, to)
|
let Some(method_node) = self.node.upgrade() else {return};
|
||||||
|
let Some(method_client) = method_node.get_client() else {return};
|
||||||
|
let Some(handler_node) = handler.node.upgrade() else {return};
|
||||||
|
// Receiver itself
|
||||||
|
let Ok(handler_alias) = Alias::create(
|
||||||
|
&method_client,
|
||||||
|
method_node.get_path(),
|
||||||
|
handler.uid.as_str(),
|
||||||
|
&handler_node,
|
||||||
|
AliasInfo {
|
||||||
|
server_methods: vec!["getTransform"],
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
) else {return};
|
||||||
|
self.handler_aliases
|
||||||
|
.add(handler.uid.clone(), &handler_alias);
|
||||||
|
|
||||||
|
if let Some(handler_field_node) = handler.field.spatial_ref().node.upgrade() {
|
||||||
|
// Handler's field
|
||||||
|
let Ok(rx_field_alias) = Alias::create(
|
||||||
|
&method_client,
|
||||||
|
handler_alias.get_path(),
|
||||||
|
"field",
|
||||||
|
&handler_field_node,
|
||||||
|
FIELD_ALIAS_INFO.clone(),
|
||||||
|
) else {return};
|
||||||
|
self.handler_aliases
|
||||||
|
.add(handler.uid.clone() + "-field", &rx_field_alias);
|
||||||
|
}
|
||||||
|
|
||||||
|
let Ok(data) = serialize(&handler.uid) else {return};
|
||||||
|
let _ = method_node.send_remote_signal("handler_created", data);
|
||||||
|
}
|
||||||
|
fn handle_drop_handler(&self, handler: &InputHandler) {
|
||||||
|
let uid = handler.uid.as_str();
|
||||||
|
self.handler_aliases.remove(uid);
|
||||||
|
self.handler_aliases.remove(&(uid.to_string() + "-field"));
|
||||||
|
let Some(tx_node) = self.node.upgrade() else {return};
|
||||||
|
let Ok(data) = serialize(&uid) else {return};
|
||||||
|
let _ = tx_node.send_remote_signal("handler_destroyed", data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Drop for InputMethod {
|
impl Drop for InputMethod {
|
||||||
@@ -119,26 +217,24 @@ impl Drop for InputMethod {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct DistanceLink {
|
pub struct DistanceLink {
|
||||||
pub distance: f32,
|
distance: f32,
|
||||||
pub method: Arc<InputMethod>,
|
method: Arc<InputMethod>,
|
||||||
pub handler: Arc<InputHandler>,
|
handler: Arc<InputHandler>,
|
||||||
pub handler_field: Arc<Field>,
|
|
||||||
}
|
}
|
||||||
impl DistanceLink {
|
impl DistanceLink {
|
||||||
fn from(method: Arc<InputMethod>, handler: Arc<InputHandler>) -> Option<Self> {
|
fn from(method: Arc<InputMethod>, handler: Arc<InputHandler>) -> Self {
|
||||||
let handler_field = handler.field.upgrade()?;
|
DistanceLink {
|
||||||
Some(DistanceLink {
|
distance: method.compare_distance(&handler.field),
|
||||||
distance: method.distance(&handler_field),
|
|
||||||
method,
|
method,
|
||||||
handler,
|
handler,
|
||||||
handler_field,
|
}
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn send_input(&self, frame: u64, datamap: Datamap) {
|
fn send_input(&self, order: u32, datamap: Datamap) {
|
||||||
self.handler.send_input(frame, self, datamap);
|
self.handler.send_input(order, self, datamap);
|
||||||
}
|
}
|
||||||
fn serialize(&self, datamap: Datamap) -> Vec<u8> {
|
#[instrument(level = "debug", skip(self))]
|
||||||
|
fn serialize(&self, order: u32, datamap: Datamap) -> Vec<u8> {
|
||||||
let input = self.method.specialization.lock().serialize(
|
let input = self.method.specialization.lock().serialize(
|
||||||
self,
|
self,
|
||||||
Spatial::space_to_space_matrix(Some(&self.method.spatial), Some(&self.handler.spatial)),
|
Spatial::space_to_space_matrix(Some(&self.method.spatial), Some(&self.handler.spatial)),
|
||||||
@@ -147,17 +243,21 @@ impl DistanceLink {
|
|||||||
let root = InputData {
|
let root = InputData {
|
||||||
uid: self.method.uid.clone(),
|
uid: self.method.uid.clone(),
|
||||||
input,
|
input,
|
||||||
distance: self.distance,
|
distance: self.method.true_distance(&self.handler.field),
|
||||||
datamap,
|
datamap,
|
||||||
|
order,
|
||||||
};
|
};
|
||||||
root.serialize()
|
root.serialize()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct InputHandler {
|
pub struct InputHandler {
|
||||||
|
enabled: Arc<AtomicBool>,
|
||||||
|
uid: String,
|
||||||
node: Weak<Node>,
|
node: Weak<Node>,
|
||||||
spatial: Arc<Spatial>,
|
spatial: Arc<Spatial>,
|
||||||
pub field: Weak<Field>,
|
field: Arc<Field>,
|
||||||
|
method_aliases: LifeLinkedNodeMap<usize>,
|
||||||
}
|
}
|
||||||
impl InputHandler {
|
impl InputHandler {
|
||||||
pub fn add_to(node: &Arc<Node>, field: &Arc<Field>) -> Result<()> {
|
pub fn add_to(node: &Arc<Node>, field: &Arc<Field>) -> Result<()> {
|
||||||
@@ -167,58 +267,61 @@ impl InputHandler {
|
|||||||
);
|
);
|
||||||
|
|
||||||
let handler = InputHandler {
|
let handler = InputHandler {
|
||||||
|
enabled: node.enabled.clone(),
|
||||||
|
uid: node.uid.clone(),
|
||||||
node: Arc::downgrade(node),
|
node: Arc::downgrade(node),
|
||||||
spatial: node.spatial.get().unwrap().clone(),
|
spatial: node.spatial.get().unwrap().clone(),
|
||||||
field: Arc::downgrade(field),
|
field: field.clone(),
|
||||||
|
method_aliases: LifeLinkedNodeMap::default(),
|
||||||
};
|
};
|
||||||
|
for method in INPUT_METHOD_REGISTRY.get_valid_contents() {
|
||||||
|
method.make_alias(&handler);
|
||||||
|
method.handle_new_handler(&handler);
|
||||||
|
}
|
||||||
let handler = INPUT_HANDLER_REGISTRY.add(handler);
|
let handler = INPUT_HANDLER_REGISTRY.add(handler);
|
||||||
let _ = node.input_handler.set(handler);
|
let _ = node.input_handler.set(handler);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
fn find(client: &Client, path: &str) -> Result<Arc<Self>> {
|
||||||
|
InputHandler::get(&*client.get_node("Input Handler", path)?)
|
||||||
|
}
|
||||||
|
fn get(node: &Node) -> Result<Arc<Self>> {
|
||||||
|
node.get_aspect("Input Handler", "input handler", |n| &n.input_handler)
|
||||||
|
.cloned()
|
||||||
|
}
|
||||||
|
|
||||||
fn send_input(&self, frame: u64, distance_link: &DistanceLink, datamap: Datamap) {
|
#[instrument(level = "debug", skip(self, distance_link))]
|
||||||
let data = distance_link.serialize(datamap);
|
fn send_input(&self, order: u32, distance_link: &DistanceLink, datamap: Datamap) {
|
||||||
let node = self.node.upgrade().unwrap();
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
let method = Arc::downgrade(&distance_link.method);
|
let _ = node.send_remote_signal("input", distance_link.serialize(order, datamap));
|
||||||
let handler = Arc::downgrade(&distance_link.handler);
|
}
|
||||||
|
}
|
||||||
tokio::spawn(async move {
|
impl PartialEq for InputHandler {
|
||||||
let data = node.execute_remote_method("input", data).await;
|
fn eq(&self, other: &Self) -> bool {
|
||||||
if frame == FRAME.load(Ordering::Relaxed) {
|
self.spatial == other.spatial
|
||||||
if let Ok(data) = data {
|
|
||||||
let capture = flexbuffers::Reader::get_root(data.as_slice())
|
|
||||||
.and_then(|data| data.get_bool())
|
|
||||||
.unwrap_or(false);
|
|
||||||
|
|
||||||
if let Some(method) = method.upgrade() {
|
|
||||||
if let Some(handler) = handler.upgrade() {
|
|
||||||
if capture {
|
|
||||||
method.captures.add_raw(&handler);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Drop for InputHandler {
|
impl Drop for InputHandler {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
INPUT_HANDLER_REGISTRY.remove(self);
|
INPUT_HANDLER_REGISTRY.remove(self);
|
||||||
|
for method in INPUT_METHOD_REGISTRY.get_valid_contents() {
|
||||||
|
method.handle_drop_handler(self);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_interface(client: &Arc<Client>) {
|
pub fn create_interface(client: &Arc<Client>) -> Result<()> {
|
||||||
let node = Node::create(client, "", "input", false);
|
let node = Node::create(client, "", "input", false);
|
||||||
node.add_local_signal("createInputHandler", create_input_handler_flex);
|
node.add_local_signal("create_input_handler", create_input_handler_flex);
|
||||||
node.add_local_signal("createInputMethodTip", tip::create_tip_flex);
|
node.add_local_signal("create_input_method_pointer", pointer::create_pointer_flex);
|
||||||
node.add_to_scenegraph();
|
node.add_local_signal("create_input_method_tip", tip::create_tip_flex);
|
||||||
|
node.add_to_scenegraph().map(|_| ())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_input_handler_flex(
|
pub fn create_input_handler_flex(
|
||||||
_node: &Node,
|
_node: &Node,
|
||||||
calling_client: Arc<Client>,
|
calling_client: Arc<Client>,
|
||||||
data: &[u8],
|
message: Message,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CreateInputHandlerInfo<'a> {
|
struct CreateInputHandlerInfo<'a> {
|
||||||
@@ -227,52 +330,92 @@ pub fn create_input_handler_flex(
|
|||||||
transform: Transform,
|
transform: Transform,
|
||||||
field_path: &'a str,
|
field_path: &'a str,
|
||||||
}
|
}
|
||||||
let info: CreateInputHandlerInfo = deserialize(data)?;
|
let info: CreateInputHandlerInfo = deserialize(message.as_ref())?;
|
||||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
let transform = parse_transform(info.transform, true, true, false)?;
|
let transform = parse_transform(info.transform, true, true, true);
|
||||||
let field = find_field(&calling_client, info.field_path)?;
|
let field = find_field(&calling_client, info.field_path)?;
|
||||||
|
|
||||||
let node = Node::create(&calling_client, "/input/handler", info.name, true).add_to_scenegraph();
|
let node =
|
||||||
Spatial::add_to(&node, Some(parent), transform)?;
|
Node::create(&calling_client, "/input/handler", info.name, true).add_to_scenegraph()?;
|
||||||
|
Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
InputHandler::add_to(&node, &field)?;
|
InputHandler::add_to(&node, &field)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
#[tracing::instrument(level = "debug")]
|
||||||
pub fn process_input() {
|
pub fn process_input() {
|
||||||
for method in INPUT_METHOD_REGISTRY
|
// Iterate over all valid input methods
|
||||||
.get_valid_contents()
|
let methods = debug_span!("Get valid methods").in_scope(|| {
|
||||||
.into_iter()
|
INPUT_METHOD_REGISTRY
|
||||||
.filter(|method| *method.enabled.lock())
|
|
||||||
.filter(|method| method.datamap.lock().is_some())
|
|
||||||
{
|
|
||||||
let mut distance_links: Vec<DistanceLink> = INPUT_HANDLER_REGISTRY
|
|
||||||
.get_valid_contents()
|
.get_valid_contents()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|handler| handler.field.upgrade().is_some())
|
.filter(|method| *method.enabled.lock())
|
||||||
.filter_map(|handler| DistanceLink::from(method.clone(), handler))
|
.filter(|method| method.datamap.lock().is_some())
|
||||||
.collect();
|
});
|
||||||
distance_links.sort_unstable_by(|a, b| {
|
let handlers = INPUT_HANDLER_REGISTRY.get_valid_contents();
|
||||||
a.distance
|
const LIMIT: usize = 50;
|
||||||
.abs()
|
for method in methods {
|
||||||
.partial_cmp(&b.distance.abs())
|
for alias in method.node.upgrade().unwrap().aliases.get_valid_contents() {
|
||||||
.unwrap()
|
alias.enabled.store(false, Ordering::Relaxed);
|
||||||
.reverse()
|
|
||||||
});
|
|
||||||
|
|
||||||
let mut last_distance = 0.0;
|
|
||||||
let frame = FRAME.load(Ordering::Relaxed);
|
|
||||||
let captures = method.captures.get_valid_contents();
|
|
||||||
for distance_link in distance_links {
|
|
||||||
distance_link.send_input(frame, method.datamap.lock().clone().unwrap());
|
|
||||||
if last_distance != distance_link.distance
|
|
||||||
&& captures
|
|
||||||
.iter()
|
|
||||||
.any(|c| Arc::ptr_eq(c, &distance_link.handler))
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
last_distance = distance_link.distance;
|
|
||||||
}
|
}
|
||||||
method.captures.clear();
|
|
||||||
|
debug_span!("Process input method").in_scope(|| {
|
||||||
|
// Get all valid input handlers and convert them to DistanceLink objects
|
||||||
|
let distance_links: Vec<DistanceLink> = debug_span!("Generate distance links")
|
||||||
|
.in_scope(|| {
|
||||||
|
if let Some(handler_order) = method.handler_order.get() {
|
||||||
|
let handler_order = handler_order.lock();
|
||||||
|
handler_order
|
||||||
|
.iter()
|
||||||
|
.filter_map(|h| h.upgrade())
|
||||||
|
.filter(|handler| handler.enabled.load(Ordering::Relaxed))
|
||||||
|
.map(|handler| DistanceLink::from(method.clone(), handler))
|
||||||
|
.collect()
|
||||||
|
} else {
|
||||||
|
let mut distance_links: Vec<_> = handlers
|
||||||
|
.iter()
|
||||||
|
.filter(|handler| handler.enabled.load(Ordering::Relaxed))
|
||||||
|
.map(|handler| {
|
||||||
|
debug_span!("Create distance link").in_scope(|| {
|
||||||
|
DistanceLink::from(method.clone(), handler.clone())
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// Sort the distance links by their distance in ascending order
|
||||||
|
debug_span!("Sort distance links").in_scope(|| {
|
||||||
|
distance_links.sort_unstable_by(|a, b| {
|
||||||
|
a.distance.abs().partial_cmp(&b.distance.abs()).unwrap()
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
distance_links.truncate(LIMIT);
|
||||||
|
distance_links
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let captures = method.captures.take_valid_contents();
|
||||||
|
// Iterate over the distance links and send input to them
|
||||||
|
for (i, distance_link) in distance_links.into_iter().enumerate() {
|
||||||
|
if i > LIMIT {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(method_alias) = distance_link
|
||||||
|
.handler
|
||||||
|
.method_aliases
|
||||||
|
.get(&(Arc::as_ptr(&distance_link.method) as usize))
|
||||||
|
.and_then(|a| a.alias.get().cloned())
|
||||||
|
{
|
||||||
|
method_alias.enabled.store(true, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
distance_link.send_input(i as u32, method.datamap.lock().clone().unwrap());
|
||||||
|
|
||||||
|
// If the current distance link is in the list of captured input handlers,
|
||||||
|
// break out of the loop to avoid sending input to the remaining distance links
|
||||||
|
if captures.contains(&distance_link.handler) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,18 @@
|
|||||||
use super::{DistanceLink, InputSpecialization};
|
use super::{DistanceLink, InputSpecialization};
|
||||||
use crate::nodes::fields::{ray_march, Field, Ray, RayMarchResult};
|
use crate::core::client::Client;
|
||||||
use crate::nodes::spatial::Spatial;
|
use crate::nodes::fields::{Field, Ray, RayMarchResult};
|
||||||
|
use crate::nodes::input::{InputMethod, InputType};
|
||||||
|
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||||
|
use crate::nodes::{Message, Node};
|
||||||
use glam::{vec3, Mat4};
|
use glam::{vec3, Mat4};
|
||||||
use stardust_xr::schemas::flat::{InputDataType, Pointer as FlatPointer};
|
use serde::Deserialize;
|
||||||
|
use stardust_xr::schemas::flat::{Datamap, InputDataType, Pointer as FlatPointer};
|
||||||
|
use stardust_xr::schemas::flex::deserialize;
|
||||||
|
use stardust_xr::values::Transform;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct Pointer {}
|
pub struct Pointer;
|
||||||
// impl Default for Pointer {
|
// impl Default for Pointer {
|
||||||
// fn default() -> Self {
|
// fn default() -> Self {
|
||||||
// Pointer {
|
// Pointer {
|
||||||
@@ -17,20 +23,28 @@ pub struct Pointer {}
|
|||||||
// }
|
// }
|
||||||
impl Pointer {
|
impl Pointer {
|
||||||
fn ray_march(&self, space: &Arc<Spatial>, field: &Field) -> RayMarchResult {
|
fn ray_march(&self, space: &Arc<Spatial>, field: &Field) -> RayMarchResult {
|
||||||
ray_march(
|
field.ray_march(Ray {
|
||||||
Ray {
|
origin: vec3(0.0, 0.0, 0.0),
|
||||||
origin: vec3(0_f32, 0_f32, 0_f32),
|
direction: vec3(0.0, 0.0, -1.0),
|
||||||
direction: vec3(0_f32, 0_f32, 1_f32),
|
space: space.clone(),
|
||||||
space: space.clone(),
|
})
|
||||||
},
|
|
||||||
field,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl InputSpecialization for Pointer {
|
impl InputSpecialization for Pointer {
|
||||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
fn compare_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||||
self.ray_march(space, field).distance
|
let ray_info = self.ray_march(space, field);
|
||||||
|
if ray_info.min_distance > 0.0 {
|
||||||
|
ray_info.deepest_point_distance + 1000.0
|
||||||
|
} else {
|
||||||
|
ray_info
|
||||||
|
.deepest_point_distance
|
||||||
|
.hypot(0.001 / ray_info.min_distance)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn true_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||||
|
let ray_info = self.ray_march(space, field);
|
||||||
|
ray_info.min_distance
|
||||||
}
|
}
|
||||||
fn serialize(
|
fn serialize(
|
||||||
&self,
|
&self,
|
||||||
@@ -38,11 +52,8 @@ impl InputSpecialization for Pointer {
|
|||||||
local_to_handler_matrix: Mat4,
|
local_to_handler_matrix: Mat4,
|
||||||
) -> InputDataType {
|
) -> InputDataType {
|
||||||
let (_, orientation, origin) = local_to_handler_matrix.to_scale_rotation_translation();
|
let (_, orientation, origin) = local_to_handler_matrix.to_scale_rotation_translation();
|
||||||
let direction = local_to_handler_matrix.transform_vector3(vec3(0_f32, 0_f32, 1_f32));
|
let direction = local_to_handler_matrix.transform_vector3(vec3(0.0, 0.0, -1.0));
|
||||||
let ray_march = self.ray_march(
|
let ray_march = self.ray_march(&distance_link.method.spatial, &distance_link.handler.field);
|
||||||
&distance_link.method.spatial,
|
|
||||||
&distance_link.handler.field.upgrade().unwrap(),
|
|
||||||
);
|
|
||||||
let deepest_point = (direction * ray_march.deepest_point_distance) + origin;
|
let deepest_point = (direction * ray_march.deepest_point_distance) + origin;
|
||||||
|
|
||||||
InputDataType::Pointer(FlatPointer {
|
InputDataType::Pointer(FlatPointer {
|
||||||
@@ -52,3 +63,30 @@ impl InputSpecialization for Pointer {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn create_pointer_flex(
|
||||||
|
_node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> color_eyre::eyre::Result<()> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct CreatePointerInfo<'a> {
|
||||||
|
name: &'a str,
|
||||||
|
parent_path: &'a str,
|
||||||
|
transform: Transform,
|
||||||
|
datamap: Option<Vec<u8>>,
|
||||||
|
}
|
||||||
|
let info: CreatePointerInfo = deserialize(message.as_ref())?;
|
||||||
|
let node = Node::create(&calling_client, "/input/method/pointer", info.name, true);
|
||||||
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
|
let transform = parse_transform(info.transform, true, true, false);
|
||||||
|
|
||||||
|
let node = node.add_to_scenegraph()?;
|
||||||
|
Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
|
InputMethod::add_to(
|
||||||
|
&node,
|
||||||
|
InputType::Pointer(Pointer),
|
||||||
|
info.datamap.and_then(|datamap| Datamap::new(datamap).ok()),
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ use crate::core::client::Client;
|
|||||||
use crate::nodes::fields::Field;
|
use crate::nodes::fields::Field;
|
||||||
use crate::nodes::input::{InputMethod, InputType};
|
use crate::nodes::input::{InputMethod, InputType};
|
||||||
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||||
use crate::nodes::Node;
|
use crate::nodes::{Message, Node};
|
||||||
use anyhow::Result;
|
use color_eyre::eyre::Result;
|
||||||
use glam::{vec3a, Mat4};
|
use glam::{vec3a, Mat4};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use stardust_xr::schemas::flat::{Datamap, InputDataType, Tip as FlatTip};
|
use stardust_xr::schemas::flat::{Datamap, InputDataType, Tip as FlatTip};
|
||||||
@@ -17,15 +17,18 @@ pub struct Tip {
|
|||||||
pub radius: f32,
|
pub radius: f32,
|
||||||
}
|
}
|
||||||
impl Tip {
|
impl Tip {
|
||||||
fn set_radius(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
fn set_radius(node: &Node, _calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
if let InputType::Tip(tip) = &mut *node.input_method.get().unwrap().specialization.lock() {
|
if let InputType::Tip(tip) = &mut *node.input_method.get().unwrap().specialization.lock() {
|
||||||
tip.radius = deserialize(data)?;
|
tip.radius = deserialize(message.as_ref())?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl InputSpecialization for Tip {
|
impl InputSpecialization for Tip {
|
||||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
fn compare_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||||
|
field.distance(space, vec3a(0.0, 0.0, 0.0)).abs()
|
||||||
|
}
|
||||||
|
fn true_distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||||
field.distance(space, vec3a(0.0, 0.0, 0.0))
|
field.distance(space, vec3a(0.0, 0.0, 0.0))
|
||||||
}
|
}
|
||||||
fn serialize(
|
fn serialize(
|
||||||
@@ -42,7 +45,7 @@ impl InputSpecialization for Tip {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_tip_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
pub fn create_tip_flex(_node: &Node, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CreateTipInfo<'a> {
|
struct CreateTipInfo<'a> {
|
||||||
name: &'a str,
|
name: &'a str,
|
||||||
@@ -51,13 +54,13 @@ pub fn create_tip_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -
|
|||||||
radius: f32,
|
radius: f32,
|
||||||
datamap: Option<Vec<u8>>,
|
datamap: Option<Vec<u8>>,
|
||||||
}
|
}
|
||||||
let info: CreateTipInfo = deserialize(data)?;
|
let info: CreateTipInfo = deserialize(message.as_ref())?;
|
||||||
let node = Node::create(&calling_client, "/input/method/tip", info.name, true);
|
let node = Node::create(&calling_client, "/input/method/tip", info.name, true);
|
||||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
let transform = parse_transform(info.transform, true, true, false)?;
|
let transform = parse_transform(info.transform, true, true, false);
|
||||||
|
|
||||||
let node = node.add_to_scenegraph();
|
let node = node.add_to_scenegraph()?;
|
||||||
Spatial::add_to(&node, Some(parent), transform)?;
|
Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
InputMethod::add_to(
|
InputMethod::add_to(
|
||||||
&node,
|
&node,
|
||||||
InputType::Tip(Tip {
|
InputType::Tip(Tip {
|
||||||
@@ -65,6 +68,6 @@ pub fn create_tip_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -
|
|||||||
}),
|
}),
|
||||||
info.datamap.and_then(|datamap| Datamap::new(datamap).ok()),
|
info.datamap.and_then(|datamap| Datamap::new(datamap).ok()),
|
||||||
)?;
|
)?;
|
||||||
node.add_local_signal("setRadius", Tip::set_radius);
|
node.add_local_signal("set_radius", Tip::set_radius);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
380
src/nodes/items/camera.rs
Normal file
380
src/nodes/items/camera.rs
Normal file
@@ -0,0 +1,380 @@
|
|||||||
|
use super::{Item, ItemType};
|
||||||
|
use crate::{
|
||||||
|
core::{
|
||||||
|
buffers::BufferManager,
|
||||||
|
client::{Client, INTERNAL_CLIENT},
|
||||||
|
registry::Registry,
|
||||||
|
scenegraph::MethodResponseSender,
|
||||||
|
},
|
||||||
|
nodes::{
|
||||||
|
drawable::{model::ModelPart, shaders::UNLIT_SHADER_BYTES, Drawable},
|
||||||
|
items::TypeInfo,
|
||||||
|
spatial::{find_spatial_parent, parse_transform, Spatial},
|
||||||
|
Message, Node,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use color_eyre::eyre::{bail, Result};
|
||||||
|
use glam::Mat4;
|
||||||
|
use lazy_static::lazy_static;
|
||||||
|
use mint::{RowMatrix4, Vector2};
|
||||||
|
use nanoid::nanoid;
|
||||||
|
use once_cell::sync::OnceCell;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use smithay::backend::{
|
||||||
|
allocator::{
|
||||||
|
dmabuf::{Dmabuf, DmabufFlags},
|
||||||
|
Buffer,
|
||||||
|
},
|
||||||
|
renderer::{gles, ImportDma},
|
||||||
|
};
|
||||||
|
use stardust_xr::{
|
||||||
|
scenegraph::ScenegraphError,
|
||||||
|
schemas::flex::{deserialize, serialize},
|
||||||
|
values::{BufferColorspace, BufferInfo, Transform},
|
||||||
|
};
|
||||||
|
use std::{ffi::c_void, sync::Arc};
|
||||||
|
use stereokit::{
|
||||||
|
Color128, Material, Rect, RenderLayer, StereoKitDraw, Tex, TextureFormat, TextureType,
|
||||||
|
Transparency,
|
||||||
|
};
|
||||||
|
use tokio::sync::mpsc::{self, error::SendError};
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
pub(super) static ref ITEM_TYPE_INFO_CAMERA: TypeInfo = TypeInfo {
|
||||||
|
type_name: "camera",
|
||||||
|
aliased_local_signals: vec!["apply_preview_material"],
|
||||||
|
aliased_local_methods: vec!["render"],
|
||||||
|
aliased_remote_signals: vec![],
|
||||||
|
ui: Default::default(),
|
||||||
|
items: Registry::new(),
|
||||||
|
acceptors: Registry::new(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
struct FrameInfo {
|
||||||
|
proj_matrix: Mat4,
|
||||||
|
preview_size: Vector2<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct CameraItem {
|
||||||
|
space: Arc<Spatial>,
|
||||||
|
frame_info: Mutex<FrameInfo>,
|
||||||
|
sk_tex: OnceCell<Tex>,
|
||||||
|
sk_mat: OnceCell<Arc<Material>>,
|
||||||
|
render_requests_tx: mpsc::UnboundedSender<(Dmabuf, BufferColorspace, MethodResponseSender)>,
|
||||||
|
render_requests_rx:
|
||||||
|
Mutex<mpsc::UnboundedReceiver<(Dmabuf, BufferColorspace, MethodResponseSender)>>,
|
||||||
|
rendered_notifiers: Mutex<Vec<MethodResponseSender>>,
|
||||||
|
applied_preview_to: Registry<ModelPart>,
|
||||||
|
apply_preview_to: Registry<ModelPart>,
|
||||||
|
}
|
||||||
|
impl CameraItem {
|
||||||
|
pub fn add_to(node: &Arc<Node>, proj_matrix: Mat4, preview_size: Vector2<u32>) {
|
||||||
|
let (render_requests_tx, render_requests_rx) = mpsc::unbounded_channel();
|
||||||
|
let camera_specialization = CameraItem {
|
||||||
|
space: node.spatial.get().unwrap().clone(),
|
||||||
|
frame_info: Mutex::new(FrameInfo {
|
||||||
|
proj_matrix,
|
||||||
|
preview_size,
|
||||||
|
}),
|
||||||
|
sk_tex: OnceCell::new(),
|
||||||
|
sk_mat: OnceCell::new(),
|
||||||
|
render_requests_tx,
|
||||||
|
render_requests_rx: Mutex::new(render_requests_rx),
|
||||||
|
rendered_notifiers: Mutex::new(Vec::new()),
|
||||||
|
applied_preview_to: Registry::new(),
|
||||||
|
apply_preview_to: Registry::new(),
|
||||||
|
};
|
||||||
|
Item::add_to(
|
||||||
|
node,
|
||||||
|
nanoid!(),
|
||||||
|
&ITEM_TYPE_INFO_CAMERA,
|
||||||
|
ItemType::Camera(camera_specialization),
|
||||||
|
);
|
||||||
|
node.add_local_method("render", CameraItem::render_flex);
|
||||||
|
node.add_local_signal(
|
||||||
|
"apply_preview_material",
|
||||||
|
CameraItem::apply_preview_material_flex,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_flex(
|
||||||
|
node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
let Some(item) = node.item.get() else {
|
||||||
|
let _ = response.send(Err(ScenegraphError::MethodError {
|
||||||
|
error: "Item not found".to_string(),
|
||||||
|
}));
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let ItemType::Camera(camera) = &item.specialization else {
|
||||||
|
let _ = response.send(Err(ScenegraphError::MethodError {
|
||||||
|
error: "Wrong item type?".to_string(),
|
||||||
|
}));
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let buffer_info: BufferInfo = match deserialize(&message.data) {
|
||||||
|
Ok(i) => i,
|
||||||
|
Err(e) => {
|
||||||
|
let _ = response.send(Err(ScenegraphError::MethodError {
|
||||||
|
error: e.to_string(),
|
||||||
|
}));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut builder = Dmabuf::builder(
|
||||||
|
(buffer_info.width as i32, buffer_info.height as i32),
|
||||||
|
buffer_info.fourcc.try_into().unwrap(),
|
||||||
|
DmabufFlags::from_bits_truncate(buffer_info.flags),
|
||||||
|
);
|
||||||
|
for (fd, plane) in message.fds.into_iter().zip(buffer_info.planes) {
|
||||||
|
builder.add_plane(
|
||||||
|
fd,
|
||||||
|
plane.idx,
|
||||||
|
plane.offset,
|
||||||
|
plane.stride,
|
||||||
|
plane.modifier.try_into().unwrap(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let buffer_to_render = builder.build().unwrap();
|
||||||
|
|
||||||
|
if let Err(SendError((_dmabuf, _colorspace, sender))) =
|
||||||
|
camera
|
||||||
|
.render_requests_tx
|
||||||
|
.send((buffer_to_render, buffer_info.colorspace, response))
|
||||||
|
{
|
||||||
|
sender.send(Err(ScenegraphError::MethodError {
|
||||||
|
error: "Internal: sender broke????".to_string(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_preview_material_flex(
|
||||||
|
node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let Some(item) = node.item.get() else {
|
||||||
|
bail!("Item not found?")
|
||||||
|
};
|
||||||
|
let ItemType::Camera(camera) = &item.specialization else {
|
||||||
|
bail!("Wrong item type?")
|
||||||
|
};
|
||||||
|
|
||||||
|
let model_part_path = deserialize(&message.data)?;
|
||||||
|
let model_part_node = calling_client.get_node("Model part", model_part_path)?;
|
||||||
|
let Drawable::ModelPart(model_part) =
|
||||||
|
model_part_node.get_aspect("Model part", "model part", |n| &n.drawable)?
|
||||||
|
else {
|
||||||
|
bail!("Drawable is not a model node")
|
||||||
|
};
|
||||||
|
|
||||||
|
camera.applied_preview_to.add_raw(model_part);
|
||||||
|
camera.apply_preview_to.add_raw(model_part);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn serialize_start_data(&self, id: &str) -> Result<Message> {
|
||||||
|
Ok(serialize(id)?.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(&self, sk: &impl StereoKitDraw, buffer_manager: &mut BufferManager) {
|
||||||
|
let frame_info = self.frame_info.lock();
|
||||||
|
self.render_preview(sk, &*frame_info);
|
||||||
|
self.render_dmabuf(sk, buffer_manager, &*frame_info);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_preview(&self, sk: &impl StereoKitDraw, frame_info: &FrameInfo) {
|
||||||
|
if !self.apply_preview_to.is_empty() {
|
||||||
|
let sk_tex = self.sk_tex.get_or_init(|| {
|
||||||
|
sk.tex_gen_color(
|
||||||
|
Color128::default(),
|
||||||
|
frame_info.preview_size.x as i32,
|
||||||
|
frame_info.preview_size.y as i32,
|
||||||
|
TextureType::RENDER_TARGET,
|
||||||
|
TextureFormat::RGBA32Linear,
|
||||||
|
)
|
||||||
|
});
|
||||||
|
let sk_mat = self.sk_mat.get_or_init(|| {
|
||||||
|
let shader = sk.shader_create_mem(&UNLIT_SHADER_BYTES).unwrap();
|
||||||
|
let mat = sk.material_create(&shader);
|
||||||
|
sk.material_set_texture(&mat, "diffuse", sk_tex.as_ref());
|
||||||
|
sk.material_set_transparency(&mat, Transparency::Blend);
|
||||||
|
Arc::new(mat)
|
||||||
|
});
|
||||||
|
for model_part in self.apply_preview_to.take_valid_contents() {
|
||||||
|
model_part.replace_material(sk_mat.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !self.applied_preview_to.is_empty() {
|
||||||
|
sk.render_to(
|
||||||
|
self.sk_tex.get().unwrap(),
|
||||||
|
self.space.global_transform(),
|
||||||
|
frame_info.proj_matrix,
|
||||||
|
RenderLayer::all(),
|
||||||
|
stereokit::RenderClear::All,
|
||||||
|
Rect {
|
||||||
|
x: 0.0,
|
||||||
|
y: 0.0,
|
||||||
|
w: 0.0,
|
||||||
|
h: 0.0,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_dmabuf(
|
||||||
|
&self,
|
||||||
|
sk: &impl StereoKitDraw,
|
||||||
|
buffer_manager: &mut BufferManager,
|
||||||
|
frame_info: &FrameInfo,
|
||||||
|
) {
|
||||||
|
let mut render_notifiers = self.rendered_notifiers.lock();
|
||||||
|
let mut render_requests_rx = self.render_requests_rx.lock();
|
||||||
|
while let Ok((buffer_to_render, colorspace, render_response_sender)) =
|
||||||
|
render_requests_rx.try_recv()
|
||||||
|
{
|
||||||
|
let imported_dmabuf = buffer_manager
|
||||||
|
.renderer
|
||||||
|
.import_dmabuf(&buffer_to_render, None);
|
||||||
|
let smithay_tex = match imported_dmabuf {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => {
|
||||||
|
let _ = render_response_sender.send(Err(ScenegraphError::MethodError {
|
||||||
|
error: e.to_string(),
|
||||||
|
}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let texture_format;
|
||||||
|
let native_format;
|
||||||
|
|
||||||
|
match colorspace {
|
||||||
|
BufferColorspace::SRGB => match buffer_to_render.format().code {
|
||||||
|
drm_fourcc::DrmFourcc::Argb8888 => {
|
||||||
|
texture_format = TextureFormat::RGBA32;
|
||||||
|
native_format = gles::ffi::SRGB8_ALPHA8;
|
||||||
|
}
|
||||||
|
drm_fourcc::DrmFourcc::Abgr8888 => {
|
||||||
|
texture_format = TextureFormat::BGRA32;
|
||||||
|
native_format = gles::ffi::SRGB8_ALPHA8;
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let _ = render_response_sender.send(Err(ScenegraphError::MethodError {
|
||||||
|
error: "Unsupported pixel format".to_string(),
|
||||||
|
}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
BufferColorspace::Linear => match buffer_to_render.format().code {
|
||||||
|
drm_fourcc::DrmFourcc::Argb8888 => {
|
||||||
|
texture_format = TextureFormat::RGBA32Linear;
|
||||||
|
native_format = gles::ffi::RGBA8;
|
||||||
|
}
|
||||||
|
drm_fourcc::DrmFourcc::Abgr8888 => {
|
||||||
|
texture_format = TextureFormat::BGRA32Linear;
|
||||||
|
native_format = gles::ffi::RGBA8;
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let _ = render_response_sender.send(Err(ScenegraphError::MethodError {
|
||||||
|
error: "Unsupported pixel format".to_string(),
|
||||||
|
}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: This doesn't seem to care about the texture format, it seems to always output with sRGB.
|
||||||
|
let sk_tex = sk.tex_create(TextureType::IMAGE_NO_MIPS, texture_format);
|
||||||
|
unsafe {
|
||||||
|
sk.tex_set_surface(
|
||||||
|
&sk_tex,
|
||||||
|
smithay_tex.tex_id() as usize as *mut c_void,
|
||||||
|
TextureType::RENDER_TARGET,
|
||||||
|
native_format.into(),
|
||||||
|
buffer_to_render.size().w,
|
||||||
|
buffer_to_render.size().h,
|
||||||
|
1,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
sk.render_to(
|
||||||
|
sk_tex,
|
||||||
|
self.space.global_transform(),
|
||||||
|
frame_info.proj_matrix,
|
||||||
|
RenderLayer::all(),
|
||||||
|
stereokit::RenderClear::All,
|
||||||
|
Rect {
|
||||||
|
x: 0.0,
|
||||||
|
y: 0.0,
|
||||||
|
w: 0.0,
|
||||||
|
h: 0.0,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
render_notifiers.push(render_response_sender);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_rendered(&self) {
|
||||||
|
for notifier in self.rendered_notifiers.lock().drain(..) {
|
||||||
|
let _ = notifier.send(Ok(Vec::new().into()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(sk: &impl StereoKitDraw, buffer_manager: &mut BufferManager) {
|
||||||
|
for camera in ITEM_TYPE_INFO_CAMERA.items.get_valid_contents() {
|
||||||
|
let ItemType::Camera(camera) = &camera.specialization else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
camera.update(sk, buffer_manager);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn send_rendered() {
|
||||||
|
for camera in ITEM_TYPE_INFO_CAMERA.items.get_valid_contents() {
|
||||||
|
let ItemType::Camera(camera) = &camera.specialization else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
camera.send_rendered();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn create_camera_item_flex(
|
||||||
|
_node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct CreateCameraItemInfo<'a> {
|
||||||
|
name: &'a str,
|
||||||
|
parent_path: &'a str,
|
||||||
|
transform: Transform,
|
||||||
|
proj_matrix: RowMatrix4<f32>,
|
||||||
|
preview_size: Vector2<u32>,
|
||||||
|
}
|
||||||
|
let info: CreateCameraItemInfo = deserialize(message.as_ref())?;
|
||||||
|
let parent_name = format!("/item/{}/item", ITEM_TYPE_INFO_CAMERA.type_name);
|
||||||
|
let space = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
|
let transform = parse_transform(info.transform, true, true, false);
|
||||||
|
|
||||||
|
let node =
|
||||||
|
Node::create(&INTERNAL_CLIENT, &parent_name, info.name, false).add_to_scenegraph()?;
|
||||||
|
Spatial::add_to(&node, None, transform * space.global_transform(), false)?;
|
||||||
|
CameraItem::add_to(&node, info.proj_matrix.into(), info.preview_size);
|
||||||
|
// TODO: this means ANY client can render anywhere with no limits, this needs to be changed!!
|
||||||
|
node.item
|
||||||
|
.get()
|
||||||
|
.unwrap()
|
||||||
|
.make_alias_named(&calling_client, &parent_name, info.name)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -1,12 +1,19 @@
|
|||||||
use super::{Item, ItemSpecialization, ItemType, ITEM_TYPE_INFO_ENVIRONMENT};
|
use super::{Item, ItemType};
|
||||||
use crate::{
|
use crate::{
|
||||||
core::client::{Client, INTERNAL_CLIENT},
|
core::{
|
||||||
|
client::{Client, INTERNAL_CLIENT},
|
||||||
|
registry::Registry,
|
||||||
|
scenegraph::MethodResponseSender,
|
||||||
|
},
|
||||||
nodes::{
|
nodes::{
|
||||||
|
items::TypeInfo,
|
||||||
spatial::{find_spatial_parent, parse_transform, Spatial},
|
spatial::{find_spatial_parent, parse_transform, Spatial},
|
||||||
Node,
|
Message, Node,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use anyhow::{anyhow, Result};
|
use color_eyre::eyre::{eyre, Result};
|
||||||
|
use lazy_static::lazy_static;
|
||||||
|
use nanoid::nanoid;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use stardust_xr::{
|
use stardust_xr::{
|
||||||
schemas::flex::{deserialize, serialize},
|
schemas::flex::{deserialize, serialize},
|
||||||
@@ -14,6 +21,18 @@ use stardust_xr::{
|
|||||||
};
|
};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
pub(super) static ref ITEM_TYPE_INFO_ENVIRONMENT: TypeInfo = TypeInfo {
|
||||||
|
type_name: "environment",
|
||||||
|
aliased_local_signals: vec!["apply_sky_tex", "apply_sky_light"],
|
||||||
|
aliased_local_methods: vec![],
|
||||||
|
aliased_remote_signals: vec![],
|
||||||
|
ui: Default::default(),
|
||||||
|
items: Registry::new(),
|
||||||
|
acceptors: Registry::new(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
pub struct EnvironmentItem {
|
pub struct EnvironmentItem {
|
||||||
path: String,
|
path: String,
|
||||||
}
|
}
|
||||||
@@ -21,30 +40,36 @@ impl EnvironmentItem {
|
|||||||
pub fn add_to(node: &Arc<Node>, path: String) {
|
pub fn add_to(node: &Arc<Node>, path: String) {
|
||||||
Item::add_to(
|
Item::add_to(
|
||||||
node,
|
node,
|
||||||
|
nanoid!(),
|
||||||
&ITEM_TYPE_INFO_ENVIRONMENT,
|
&ITEM_TYPE_INFO_ENVIRONMENT,
|
||||||
ItemType::Environment(EnvironmentItem { path }),
|
ItemType::Environment(EnvironmentItem { path }),
|
||||||
);
|
);
|
||||||
node.add_local_method("getPath", EnvironmentItem::get_path_flex);
|
node.add_local_method("get_path", EnvironmentItem::get_path_flex);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_path_flex(node: &Node, _calling_client: Arc<Client>, _data: &[u8]) -> Result<Vec<u8>> {
|
fn get_path_flex(
|
||||||
let path: Result<String> = match &node.item.get().unwrap().specialization {
|
node: &Node,
|
||||||
ItemType::Environment(env) => Ok(env.path.clone()),
|
_calling_client: Arc<Client>,
|
||||||
_ => Err(anyhow!("")),
|
_message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
response.wrap_sync(move || {
|
||||||
|
let ItemType::Environment(environment_item) = &node.item.get().unwrap().specialization else {
|
||||||
|
return Err(eyre!("Wrong item type?"))
|
||||||
};
|
};
|
||||||
Ok(flexbuffers::singleton(path?.as_str()))
|
Ok(serialize(environment_item.path.as_str())?.into())
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
|
||||||
impl ItemSpecialization for EnvironmentItem {
|
pub fn serialize_start_data(&self, id: &str) -> Result<Message> {
|
||||||
fn serialize_start_data(&self, id: &str) -> Vec<u8> {
|
Ok(serialize((id, self.path.as_str()))?.into())
|
||||||
serialize((id, self.path.as_str())).unwrap()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn create_environment_item_flex(
|
pub(super) fn create_environment_item_flex(
|
||||||
_node: &Node,
|
_node: &Node,
|
||||||
calling_client: Arc<Client>,
|
calling_client: Arc<Client>,
|
||||||
data: &[u8],
|
message: Message,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CreateEnvironmentItemInfo<'a> {
|
struct CreateEnvironmentItemInfo<'a> {
|
||||||
@@ -53,33 +78,18 @@ pub(super) fn create_environment_item_flex(
|
|||||||
transform: Transform,
|
transform: Transform,
|
||||||
item_data: String,
|
item_data: String,
|
||||||
}
|
}
|
||||||
let info: CreateEnvironmentItemInfo = deserialize(data)?;
|
let info: CreateEnvironmentItemInfo = deserialize(message.as_ref())?;
|
||||||
let parent_name = format!("/item/{}/item/", ITEM_TYPE_INFO_ENVIRONMENT.type_name);
|
let parent_name = format!("/item/{}/item", ITEM_TYPE_INFO_ENVIRONMENT.type_name);
|
||||||
let node = Node::create(&INTERNAL_CLIENT, &parent_name, info.name, true);
|
|
||||||
let space = find_spatial_parent(&calling_client, info.parent_path)?;
|
let space = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
let transform = parse_transform(info.transform, true, true, false)?;
|
let transform = parse_transform(info.transform, true, true, false);
|
||||||
let node = node.add_to_scenegraph();
|
|
||||||
Spatial::add_to(&node, None, transform * space.global_transform())?;
|
let node =
|
||||||
|
Node::create(&INTERNAL_CLIENT, &parent_name, info.name, false).add_to_scenegraph()?;
|
||||||
|
Spatial::add_to(&node, None, transform * space.global_transform(), false)?;
|
||||||
EnvironmentItem::add_to(&node, info.item_data);
|
EnvironmentItem::add_to(&node, info.item_data);
|
||||||
node.item
|
node.item
|
||||||
.get()
|
.get()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.make_alias(&calling_client, &parent_name);
|
.make_alias_named(&calling_client, &parent_name, info.name)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn create_environment_item_acceptor_flex(
|
|
||||||
_node: &Node,
|
|
||||||
calling_client: Arc<Client>,
|
|
||||||
data: &[u8],
|
|
||||||
) -> Result<()> {
|
|
||||||
super::create_item_acceptor_flex(calling_client, data, &ITEM_TYPE_INFO_ENVIRONMENT)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn register_environment_item_ui_flex(
|
|
||||||
_node: &Node,
|
|
||||||
calling_client: Arc<Client>,
|
|
||||||
_data: &[u8],
|
|
||||||
) -> Result<()> {
|
|
||||||
super::register_item_ui_flex(calling_client, &ITEM_TYPE_INFO_ENVIRONMENT)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,66 +1,60 @@
|
|||||||
|
pub mod camera;
|
||||||
mod environment;
|
mod environment;
|
||||||
|
pub mod panel;
|
||||||
|
|
||||||
use self::environment::EnvironmentItem;
|
use self::camera::CameraItem;
|
||||||
|
use self::environment::{EnvironmentItem, ITEM_TYPE_INFO_ENVIRONMENT};
|
||||||
|
use self::panel::{PanelItemTrait, ITEM_TYPE_INFO_PANEL};
|
||||||
use super::fields::Field;
|
use super::fields::Field;
|
||||||
use super::spatial::{find_spatial_parent, parse_transform, Spatial};
|
use super::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||||
use super::{Alias, Node};
|
use super::{Alias, Message, Node};
|
||||||
use crate::core::client::{Client, INTERNAL_CLIENT};
|
use crate::core::client::Client;
|
||||||
use crate::core::nodelist::LifeLinkedNodeList;
|
use crate::core::node_collections::LifeLinkedNodeMap;
|
||||||
use crate::core::registry::Registry;
|
use crate::core::registry::Registry;
|
||||||
use crate::nodes::alias::AliasInfo;
|
use crate::nodes::alias::AliasInfo;
|
||||||
use crate::nodes::fields::find_field;
|
use crate::nodes::fields::find_field;
|
||||||
use crate::wayland::panel_item::{register_panel_item_ui_flex, PanelItem};
|
use color_eyre::eyre::{ensure, eyre, Result};
|
||||||
use anyhow::{anyhow, ensure, Result};
|
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use nanoid::nanoid;
|
use nanoid::nanoid;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
use portable_atomic::Ordering;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use stardust_xr::schemas::flex::deserialize;
|
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||||
use stardust_xr::values::Transform;
|
use stardust_xr::values::Transform;
|
||||||
|
use std::hash::Hash;
|
||||||
use std::ops::Deref;
|
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::{Arc, Weak};
|
||||||
|
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref ITEM_ALIAS_LOCAL_SIGNALS: Vec<&'static str> = vec![
|
static ref ITEM_ALIAS_LOCAL_SIGNALS: Vec<&'static str> = vec![
|
||||||
"getTransform",
|
"get_bounds",
|
||||||
"setTransform",
|
"get_transform",
|
||||||
"setSpatialParent",
|
"set_transform",
|
||||||
"setSpatialParentInPlace",
|
"set_spatial_parent",
|
||||||
"setZoneable",
|
"set_spatial_parent_in_place",
|
||||||
|
"set_zoneable",
|
||||||
"release",
|
"release",
|
||||||
];
|
];
|
||||||
static ref ITEM_ALIAS_LOCAL_METHODS: Vec<&'static str> = vec!["captureInto"];
|
static ref ITEM_ALIAS_LOCAL_METHODS: Vec<&'static str> = vec![];
|
||||||
static ref ITEM_ALIAS_REMOTE_SIGNALS: Vec<&'static str> = vec![];
|
static ref ITEM_ALIAS_REMOTE_SIGNALS: Vec<&'static str> = vec![];
|
||||||
static ref ITEM_ALIAS_REMOTE_METHODS: Vec<&'static str> = vec![];
|
|
||||||
static ref ITEM_TYPE_INFO_ENVIRONMENT: TypeInfo = TypeInfo {
|
|
||||||
type_name: "environment",
|
|
||||||
aliased_local_signals: vec!["applySkyTex", "applySkyLight"],
|
|
||||||
aliased_local_methods: vec![],
|
|
||||||
aliased_remote_signals: vec![],
|
|
||||||
aliased_remote_methods: vec![],
|
|
||||||
ui: Default::default(),
|
|
||||||
items: Registry::new(),
|
|
||||||
acceptors: Registry::new(),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn capture(item: &Arc<Item>, acceptor: &Arc<ItemAcceptor>) {
|
pub fn capture(item: &Arc<Item>, acceptor: &Arc<ItemAcceptor>) {
|
||||||
if item.captured_acceptor.lock().upgrade().is_some() {
|
if item.captured_acceptor.lock().strong_count() > 0 {
|
||||||
release(item);
|
release(item);
|
||||||
}
|
}
|
||||||
*item.captured_acceptor.lock() = Arc::downgrade(acceptor);
|
*item.captured_acceptor.lock() = Arc::downgrade(acceptor);
|
||||||
acceptor.handle_capture(item);
|
acceptor.handle_capture(item);
|
||||||
if let Some(ui) = item.type_info.ui.lock().upgrade() {
|
if let Some(ui) = item.type_info.ui.lock().upgrade() {
|
||||||
ui.handle_capture(item);
|
ui.handle_capture_item(item, acceptor);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn release(item: &Arc<Item>) {
|
fn release(item: &Item) {
|
||||||
if let Some(acceptor) = item.captured_acceptor.lock().upgrade() {
|
let mut captured_acceptor = item.captured_acceptor.lock();
|
||||||
*item.captured_acceptor.lock() = Weak::default();
|
if let Some(acceptor) = captured_acceptor.upgrade().as_ref() {
|
||||||
|
*captured_acceptor = Weak::default();
|
||||||
acceptor.handle_release(item);
|
acceptor.handle_release(item);
|
||||||
if let Some(ui) = item.type_info.ui.lock().upgrade() {
|
if let Some(ui) = item.type_info.ui.lock().upgrade() {
|
||||||
ui.handle_release(item);
|
ui.handle_release_item(item, &acceptor);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -70,27 +64,21 @@ pub struct TypeInfo {
|
|||||||
pub aliased_local_signals: Vec<&'static str>,
|
pub aliased_local_signals: Vec<&'static str>,
|
||||||
pub aliased_local_methods: Vec<&'static str>,
|
pub aliased_local_methods: Vec<&'static str>,
|
||||||
pub aliased_remote_signals: Vec<&'static str>,
|
pub aliased_remote_signals: Vec<&'static str>,
|
||||||
pub aliased_remote_methods: Vec<&'static str>,
|
|
||||||
pub ui: Mutex<Weak<ItemUI>>,
|
pub ui: Mutex<Weak<ItemUI>>,
|
||||||
pub items: Registry<Item>,
|
pub items: Registry<Item>,
|
||||||
pub acceptors: Registry<ItemAcceptor>,
|
pub acceptors: Registry<ItemAcceptor>,
|
||||||
}
|
}
|
||||||
|
impl Hash for TypeInfo {
|
||||||
fn capture_into_flex(node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||||
let acceptor_path = flexbuffers::Reader::get_root(data)?
|
self.type_name.hash(state);
|
||||||
.get_str()
|
}
|
||||||
.map_err(|_| anyhow!("Acceptor path is not a string"))?;
|
|
||||||
let acceptor = calling_client
|
|
||||||
.scenegraph
|
|
||||||
.get_node(acceptor_path)
|
|
||||||
.ok_or_else(|| anyhow!("Acceptor node not found"))?;
|
|
||||||
let acceptor = acceptor
|
|
||||||
.item_acceptor
|
|
||||||
.get()
|
|
||||||
.ok_or_else(|| anyhow!("Acceptor node is not an acceptor!"))?;
|
|
||||||
capture(node.item.get().unwrap(), acceptor);
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
impl PartialEq for TypeInfo {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.type_name == other.type_name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Eq for TypeInfo {}
|
||||||
|
|
||||||
pub struct Item {
|
pub struct Item {
|
||||||
node: Weak<Node>,
|
node: Weak<Node>,
|
||||||
@@ -102,84 +90,119 @@ pub struct Item {
|
|||||||
impl Item {
|
impl Item {
|
||||||
pub fn add_to(
|
pub fn add_to(
|
||||||
node: &Arc<Node>,
|
node: &Arc<Node>,
|
||||||
|
uid: String,
|
||||||
type_info: &'static TypeInfo,
|
type_info: &'static TypeInfo,
|
||||||
specialization: ItemType,
|
specialization: ItemType,
|
||||||
) -> Arc<Self> {
|
) -> Arc<Self> {
|
||||||
node.add_local_signal("captureInto", capture_into_flex);
|
|
||||||
let item = Item {
|
let item = Item {
|
||||||
node: Arc::downgrade(node),
|
node: Arc::downgrade(node),
|
||||||
uid: nanoid!(),
|
uid,
|
||||||
type_info,
|
type_info,
|
||||||
captured_acceptor: Default::default(),
|
captured_acceptor: Default::default(),
|
||||||
specialization,
|
specialization,
|
||||||
};
|
};
|
||||||
let item = type_info.items.add(item);
|
let item = type_info.items.add(item);
|
||||||
|
|
||||||
|
node.add_local_signal("release", Item::release_flex);
|
||||||
if let Some(ui) = type_info.ui.lock().upgrade() {
|
if let Some(ui) = type_info.ui.lock().upgrade() {
|
||||||
ui.handle_create_item(&item);
|
ui.handle_create_item(&item);
|
||||||
}
|
}
|
||||||
let _ = node.item.set(item.clone());
|
let _ = node.item.set(item.clone());
|
||||||
|
|
||||||
|
// if let Some(auto_acceptor) = node.get_client().and_then(|client| {
|
||||||
|
// client
|
||||||
|
// .state
|
||||||
|
// .as_ref()
|
||||||
|
// .and_then(|settings| settings.acceptors.get(type_info))
|
||||||
|
// .and_then(|acceptor| acceptor.upgrade())
|
||||||
|
// }) {
|
||||||
|
// capture(&item, &auto_acceptor);
|
||||||
|
// }
|
||||||
|
|
||||||
item
|
item
|
||||||
}
|
}
|
||||||
fn make_alias(&self, client: &Arc<Client>, parent: &str) -> (Arc<Node>, Arc<Alias>) {
|
fn make_alias_named(
|
||||||
let node = Alias::new(
|
&self,
|
||||||
|
client: &Arc<Client>,
|
||||||
|
parent: &str,
|
||||||
|
name: &str,
|
||||||
|
) -> Result<Arc<Node>> {
|
||||||
|
Alias::create(
|
||||||
client,
|
client,
|
||||||
parent,
|
parent,
|
||||||
&self.uid,
|
name,
|
||||||
&self.node.upgrade().unwrap(),
|
&self.node.upgrade().unwrap(),
|
||||||
AliasInfo {
|
AliasInfo {
|
||||||
local_signals: [
|
server_signals: [
|
||||||
&self.type_info.aliased_local_signals,
|
&self.type_info.aliased_local_signals,
|
||||||
ITEM_ALIAS_LOCAL_SIGNALS.as_slice(),
|
ITEM_ALIAS_LOCAL_SIGNALS.as_slice(),
|
||||||
]
|
]
|
||||||
.concat(),
|
.concat(),
|
||||||
local_methods: [
|
server_methods: [
|
||||||
&self.type_info.aliased_local_methods,
|
&self.type_info.aliased_local_methods,
|
||||||
ITEM_ALIAS_LOCAL_METHODS.as_slice(),
|
ITEM_ALIAS_LOCAL_METHODS.as_slice(),
|
||||||
]
|
]
|
||||||
.concat(),
|
.concat(),
|
||||||
remote_signals: [
|
client_signals: [
|
||||||
&self.type_info.aliased_remote_signals,
|
&self.type_info.aliased_remote_signals,
|
||||||
ITEM_ALIAS_REMOTE_SIGNALS.as_slice(),
|
ITEM_ALIAS_REMOTE_SIGNALS.as_slice(),
|
||||||
]
|
]
|
||||||
.concat(),
|
.concat(),
|
||||||
},
|
},
|
||||||
);
|
)
|
||||||
let alias = node.alias.get().unwrap().clone();
|
}
|
||||||
(node, alias)
|
fn make_alias(&self, client: &Arc<Client>, parent: &str) -> Result<Arc<Node>> {
|
||||||
|
self.make_alias_named(client, parent, &self.uid)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn release_flex(node: &Node, _calling_client: Arc<Client>, _message: Message) -> Result<()> {
|
||||||
|
let item = node.get_aspect("Item", "item", |n| &n.item)?;
|
||||||
|
release(item);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Drop for Item {
|
impl Drop for Item {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.type_info.items.remove(self);
|
self.type_info.items.remove(self);
|
||||||
|
release(self);
|
||||||
if let Some(ui) = self.type_info.ui.lock().upgrade() {
|
if let Some(ui) = self.type_info.ui.lock().upgrade() {
|
||||||
ui.handle_destroy_item(self);
|
ui.handle_destroy_item(self);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait ItemSpecialization {
|
|
||||||
fn serialize_start_data(&self, id: &str) -> Vec<u8>;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub enum ItemType {
|
pub enum ItemType {
|
||||||
|
Camera(CameraItem),
|
||||||
Environment(EnvironmentItem),
|
Environment(EnvironmentItem),
|
||||||
Panel(PanelItem),
|
Panel(Arc<dyn PanelItemTrait>),
|
||||||
}
|
}
|
||||||
impl Deref for ItemType {
|
impl ItemType {
|
||||||
type Target = dyn ItemSpecialization;
|
fn serialize_start_data(&self, id: &str) -> Result<Message> {
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
match self {
|
match self {
|
||||||
ItemType::Environment(item) => item,
|
ItemType::Camera(c) => c.serialize_start_data(id),
|
||||||
ItemType::Panel(item) => item,
|
ItemType::Environment(e) => e.serialize_start_data(id),
|
||||||
|
ItemType::Panel(p) => p.serialize_start_data(id),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// impl Deref for ItemType {
|
||||||
|
// type Target = dyn ItemSpecialization;
|
||||||
|
|
||||||
|
// fn deref(&self) -> &Self::Target {
|
||||||
|
// match self {
|
||||||
|
// ItemType::Environment(item) => item,
|
||||||
|
// ItemType::Panel(item) => item.as_ref(),
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
pub struct ItemUI {
|
pub struct ItemUI {
|
||||||
node: Weak<Node>,
|
node: Weak<Node>,
|
||||||
type_info: &'static TypeInfo,
|
type_info: &'static TypeInfo,
|
||||||
aliases: LifeLinkedNodeList,
|
item_aliases: LifeLinkedNodeMap<String>,
|
||||||
|
acceptor_aliases: LifeLinkedNodeMap<String>,
|
||||||
|
acceptor_field_aliases: LifeLinkedNodeMap<String>,
|
||||||
}
|
}
|
||||||
impl ItemUI {
|
impl ItemUI {
|
||||||
fn add_to(node: &Arc<Node>, type_info: &'static TypeInfo) -> Result<()> {
|
fn add_to(node: &Arc<Node>, type_info: &'static TypeInfo) -> Result<()> {
|
||||||
@@ -191,7 +214,9 @@ impl ItemUI {
|
|||||||
let ui = Arc::new(ItemUI {
|
let ui = Arc::new(ItemUI {
|
||||||
node: Arc::downgrade(node),
|
node: Arc::downgrade(node),
|
||||||
type_info,
|
type_info,
|
||||||
aliases: Default::default(),
|
item_aliases: Default::default(),
|
||||||
|
acceptor_aliases: Default::default(),
|
||||||
|
acceptor_field_aliases: Default::default(),
|
||||||
});
|
});
|
||||||
*type_info.ui.lock() = Arc::downgrade(&ui);
|
*type_info.ui.lock() = Arc::downgrade(&ui);
|
||||||
let _ = node.item_ui.set(ui.clone());
|
let _ = node.item_ui.set(ui.clone());
|
||||||
@@ -199,51 +224,66 @@ impl ItemUI {
|
|||||||
for item in type_info.items.get_valid_contents() {
|
for item in type_info.items.get_valid_contents() {
|
||||||
ui.handle_create_item(&item);
|
ui.handle_create_item(&item);
|
||||||
}
|
}
|
||||||
|
for acceptor in type_info.acceptors.get_valid_contents() {
|
||||||
|
ui.handle_create_acceptor(&acceptor);
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
fn send_state(&self, state: &str, name: &str) {
|
fn send_state(&self, state: &str, name: &str) {
|
||||||
|
let Ok(serialized_data) = serialize(name) else {return};
|
||||||
let _ = self
|
let _ = self
|
||||||
.node
|
.node
|
||||||
.upgrade()
|
.upgrade()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.send_remote_signal(state, flexbuffers::singleton(name).as_slice());
|
.send_remote_signal(state, serialized_data);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle_create_item(&self, item: &Item) {
|
fn handle_create_item(&self, item: &Item) {
|
||||||
let node = self.node.upgrade().unwrap();
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
if let Some(client) = node.get_client() {
|
let Some(client) = node.get_client() else {return};
|
||||||
let (alias_node, _) =
|
|
||||||
item.make_alias(&client, &(node.get_path().to_string() + "/item"));
|
|
||||||
self.aliases.add(Arc::downgrade(&alias_node));
|
|
||||||
|
|
||||||
let _ = node.send_remote_signal(
|
if let Ok(alias_node) = item.make_alias(&client, &(node.get_path().to_string() + "/item")) {
|
||||||
"create",
|
self.item_aliases.add(item.uid.clone(), &alias_node);
|
||||||
&item.specialization.serialize_start_data(&item.uid),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let Ok(serialized_data) = item.specialization.serialize_start_data(&item.uid) else {return};
|
||||||
|
let _ = node.send_remote_signal("create_item", serialized_data);
|
||||||
}
|
}
|
||||||
fn handle_destroy_item(&self, item: &Item) {
|
fn handle_destroy_item(&self, item: &Item) {
|
||||||
self.send_state("destroy", item.uid.as_str());
|
self.item_aliases.remove(&item.uid);
|
||||||
|
self.send_state("destroy_item", item.uid.as_str());
|
||||||
}
|
}
|
||||||
fn handle_capture(&self, item: &Item) {
|
fn handle_capture_item(&self, item: &Item, acceptor: &ItemAcceptor) {
|
||||||
self.send_state("capture", item.uid.as_str());
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
|
||||||
|
let Ok(message) = serialize((item.uid.as_str(), acceptor.uid.as_str())) else {return};
|
||||||
|
let _ = node.send_remote_signal("capture_item", message);
|
||||||
}
|
}
|
||||||
fn handle_release(&self, item: &Item) {
|
fn handle_release_item(&self, item: &Item, acceptor: &ItemAcceptor) {
|
||||||
self.send_state("release", item.uid.as_str());
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
|
||||||
|
let Ok(message) = serialize((item.uid.as_str(), acceptor.uid.as_str())) else {return};
|
||||||
|
let _ = node.send_remote_signal("release_item", message);
|
||||||
}
|
}
|
||||||
fn handle_create_acceptor(&self, acceptor: &ItemAcceptor) {
|
fn handle_create_acceptor(&self, acceptor: &ItemAcceptor) {
|
||||||
let node = self.node.upgrade().unwrap();
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
if let Some(client) = node.get_client() {
|
let Some(client) = node.get_client() else {return};
|
||||||
let aliases = acceptor.make_aliases(
|
|
||||||
&client,
|
let Ok((alias, field_alias)) = acceptor.make_aliases(
|
||||||
&format!("/item/{}/acceptor", self.type_info.type_name),
|
&client,
|
||||||
);
|
&format!("/item/{}/acceptor", self.type_info.type_name),
|
||||||
aliases
|
) else {return};
|
||||||
.iter()
|
self.acceptor_aliases.add(acceptor.uid.clone(), &alias);
|
||||||
.for_each(|alias| self.aliases.add(Arc::downgrade(alias)));
|
self.acceptor_field_aliases
|
||||||
}
|
.add(acceptor.uid.clone(), &field_alias);
|
||||||
|
let Ok(message) = serialize(&acceptor.uid) else {return};
|
||||||
|
let _ = node.send_remote_signal("create_acceptor", message);
|
||||||
|
}
|
||||||
|
fn handle_destroy_acceptor(&self, acceptor: &ItemAcceptor) {
|
||||||
|
self.send_state("destroy_acceptor", acceptor.uid.as_str());
|
||||||
|
self.acceptor_aliases.remove(&acceptor.uid);
|
||||||
|
self.acceptor_field_aliases.remove(&acceptor.uid);
|
||||||
}
|
}
|
||||||
fn handle_destroy_acceptor(&self, _acceptor: &ItemAcceptor) {}
|
|
||||||
}
|
}
|
||||||
impl Drop for ItemUI {
|
impl Drop for ItemUI {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
@@ -252,98 +292,142 @@ impl Drop for ItemUI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct ItemAcceptor {
|
pub struct ItemAcceptor {
|
||||||
|
uid: String,
|
||||||
node: Weak<Node>,
|
node: Weak<Node>,
|
||||||
type_info: &'static TypeInfo,
|
pub type_info: &'static TypeInfo,
|
||||||
field: Mutex<Weak<Field>>,
|
field: Arc<Field>,
|
||||||
accepted: Registry<Item>,
|
accepted_aliases: LifeLinkedNodeMap<String>,
|
||||||
|
accepted_registry: Registry<Item>,
|
||||||
}
|
}
|
||||||
impl ItemAcceptor {
|
impl ItemAcceptor {
|
||||||
fn add_to(node: &Arc<Node>, type_info: &'static TypeInfo, field: Weak<Field>) {
|
fn add_to(node: &Arc<Node>, type_info: &'static TypeInfo, field: Arc<Field>) {
|
||||||
let acceptor = type_info.acceptors.add(ItemAcceptor {
|
let acceptor = type_info.acceptors.add(ItemAcceptor {
|
||||||
|
uid: nanoid!(),
|
||||||
node: Arc::downgrade(node),
|
node: Arc::downgrade(node),
|
||||||
type_info,
|
type_info,
|
||||||
field: Mutex::new(field),
|
field,
|
||||||
accepted: Registry::new(),
|
accepted_aliases: Default::default(),
|
||||||
|
accepted_registry: Registry::new(),
|
||||||
});
|
});
|
||||||
|
node.add_local_signal("capture", ItemAcceptor::capture_flex);
|
||||||
if let Some(ui) = type_info.ui.lock().upgrade() {
|
if let Some(ui) = type_info.ui.lock().upgrade() {
|
||||||
ui.handle_create_acceptor(&acceptor);
|
ui.handle_create_acceptor(&acceptor);
|
||||||
}
|
}
|
||||||
let _ = node.item_acceptor.set(acceptor);
|
let _ = node.item_acceptor.set(acceptor);
|
||||||
}
|
}
|
||||||
fn make_aliases(&self, client: &Arc<Client>, parent: &str) -> Vec<Arc<Node>> {
|
|
||||||
let mut aliases = Vec::new();
|
fn capture_flex(node: &Node, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
|
if !node.enabled.load(Ordering::Relaxed) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let acceptor = node.item_acceptor.get().unwrap();
|
||||||
|
let item_path: &str = deserialize(message.as_ref())?;
|
||||||
|
let item_node = calling_client.get_node("Item", item_path)?;
|
||||||
|
let item = item_node.get_aspect("Item", "item", |n| &n.item)?;
|
||||||
|
capture(item, acceptor);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_aliases(&self, client: &Arc<Client>, parent: &str) -> Result<(Arc<Node>, Arc<Node>)> {
|
||||||
let acceptor_node = &self.node.upgrade().unwrap();
|
let acceptor_node = &self.node.upgrade().unwrap();
|
||||||
let acceptor_alias = Alias::new(
|
let acceptor_alias = Alias::create(
|
||||||
client,
|
client,
|
||||||
parent,
|
parent,
|
||||||
acceptor_node.uid.as_str(),
|
&self.uid,
|
||||||
acceptor_node,
|
acceptor_node,
|
||||||
AliasInfo {
|
AliasInfo {
|
||||||
local_signals: vec!["release"],
|
server_signals: vec!["capture"],
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
);
|
)?;
|
||||||
if let Some(field) = self.field.lock().upgrade() {
|
|
||||||
let acceptor_field_alias = Alias::new(
|
|
||||||
client,
|
|
||||||
acceptor_alias.get_path(),
|
|
||||||
"field",
|
|
||||||
&field.spatial_ref().node.upgrade().unwrap(),
|
|
||||||
AliasInfo::default(),
|
|
||||||
);
|
|
||||||
|
|
||||||
aliases.push(acceptor_field_alias);
|
let acceptor_field_alias = Alias::create(
|
||||||
}
|
client,
|
||||||
aliases.push(acceptor_alias);
|
acceptor_alias.get_path(),
|
||||||
aliases
|
"field",
|
||||||
}
|
&self.field.spatial_ref().node.upgrade().unwrap(),
|
||||||
fn send_event(&self, state: &str, name: &str) {
|
AliasInfo::default(),
|
||||||
let _ = self
|
)?;
|
||||||
.node
|
|
||||||
.upgrade()
|
Ok((acceptor_alias, acceptor_field_alias))
|
||||||
.unwrap()
|
|
||||||
.send_remote_signal(state, flexbuffers::singleton(name).as_slice());
|
|
||||||
}
|
}
|
||||||
fn handle_capture(&self, item: &Arc<Item>) {
|
fn handle_capture(&self, item: &Arc<Item>) {
|
||||||
self.accepted.add_raw(item);
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
self.send_event("capture", item.uid.as_str());
|
let Some(client) = node.get_client() else {return};
|
||||||
|
|
||||||
|
self.accepted_registry.add_raw(item);
|
||||||
|
if let Ok(alias_node) = item.make_alias(&client, &node.path) {
|
||||||
|
self.accepted_aliases.add(item.uid.clone(), &alias_node);
|
||||||
|
}
|
||||||
|
|
||||||
|
let Ok(serialized_data) = item.specialization.serialize_start_data(&item.uid) else {return};
|
||||||
|
let _ = node.send_remote_signal("capture", serialized_data);
|
||||||
}
|
}
|
||||||
fn handle_release(&self, item: &Item) {
|
fn handle_release(&self, item: &Item) {
|
||||||
self.accepted.remove(item);
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
self.send_event("release", item.uid.as_str());
|
|
||||||
|
self.accepted_registry.remove(item);
|
||||||
|
self.accepted_aliases.remove(&item.uid);
|
||||||
|
let Ok(message) = serialize(&item.uid) else {return};
|
||||||
|
let _ = node.send_remote_signal("release", message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Drop for ItemAcceptor {
|
impl Drop for ItemAcceptor {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.type_info.acceptors.remove(self);
|
self.type_info.acceptors.remove(self);
|
||||||
|
for item in self.accepted_registry.get_valid_contents() {
|
||||||
|
release(&item);
|
||||||
|
}
|
||||||
if let Some(ui) = self.type_info.ui.lock().upgrade() {
|
if let Some(ui) = self.type_info.ui.lock().upgrade() {
|
||||||
ui.handle_destroy_acceptor(self);
|
ui.handle_destroy_acceptor(self);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn create_interface(client: &Arc<Client>) {
|
pub fn create_interface(client: &Arc<Client>) -> Result<()> {
|
||||||
let node = Node::create(client, "", "item", false);
|
let node = Node::create(client, "", "item", false);
|
||||||
|
node.add_local_signal("create_camera_item", camera::create_camera_item_flex);
|
||||||
node.add_local_signal(
|
node.add_local_signal(
|
||||||
"createEnvironmentItem",
|
"create_environment_item",
|
||||||
environment::create_environment_item_flex,
|
environment::create_environment_item_flex,
|
||||||
);
|
);
|
||||||
node.add_local_signal(
|
node.add_local_signal("register_item_ui", register_item_ui_flex);
|
||||||
"registerEnvironmentItemUI",
|
node.add_local_signal("create_item_acceptor", create_item_acceptor_flex);
|
||||||
environment::register_environment_item_ui_flex,
|
node.add_to_scenegraph().map(|_| ())
|
||||||
);
|
|
||||||
node.add_local_signal("registerPanelItemUI", register_panel_item_ui_flex);
|
|
||||||
node.add_local_signal(
|
|
||||||
"createEnvironmentItemAcceptor",
|
|
||||||
environment::create_environment_item_acceptor_flex,
|
|
||||||
);
|
|
||||||
node.add_to_scenegraph();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(self) fn create_item_acceptor_flex(
|
fn type_info(name: &str) -> Result<&'static TypeInfo> {
|
||||||
|
match name {
|
||||||
|
"environment" => Ok(&ITEM_TYPE_INFO_ENVIRONMENT),
|
||||||
|
#[cfg(feature = "wayland")]
|
||||||
|
"panel" => Ok(&ITEM_TYPE_INFO_PANEL),
|
||||||
|
_ => Err(eyre!("Invalid item type")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn register_item_ui_flex(
|
||||||
|
_node: &Node,
|
||||||
calling_client: Arc<Client>,
|
calling_client: Arc<Client>,
|
||||||
data: &[u8],
|
message: Message,
|
||||||
type_info: &'static TypeInfo,
|
) -> Result<()> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct RegisterItemUIInfo<'a> {
|
||||||
|
item_type: &'a str,
|
||||||
|
}
|
||||||
|
let info: RegisterItemUIInfo = deserialize(message.as_ref())?;
|
||||||
|
let type_info = type_info(info.item_type)?;
|
||||||
|
let ui =
|
||||||
|
Node::create(&calling_client, "/item", type_info.type_name, true).add_to_scenegraph()?;
|
||||||
|
ItemUI::add_to(&ui, type_info)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_item_acceptor_flex(
|
||||||
|
_node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct CreateItemAcceptorInfo<'a> {
|
struct CreateItemAcceptorInfo<'a> {
|
||||||
@@ -351,28 +435,22 @@ pub(self) fn create_item_acceptor_flex(
|
|||||||
parent_path: &'a str,
|
parent_path: &'a str,
|
||||||
transform: Transform,
|
transform: Transform,
|
||||||
field_path: &'a str,
|
field_path: &'a str,
|
||||||
|
item_type: &'a str,
|
||||||
}
|
}
|
||||||
let info: CreateItemAcceptorInfo = deserialize(data)?;
|
let info: CreateItemAcceptorInfo = deserialize(message.as_ref())?;
|
||||||
let parent_name = format!("/item/{}/acceptor/", ITEM_TYPE_INFO_ENVIRONMENT.type_name);
|
|
||||||
let space = find_spatial_parent(&calling_client, info.parent_path)?;
|
let space = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
let transform = parse_transform(info.transform, true, true, false)?;
|
let transform = parse_transform(info.transform, true, true, false);
|
||||||
let field = find_field(&calling_client, info.field_path)?;
|
let field = find_field(&calling_client, info.field_path)?;
|
||||||
|
let type_info = type_info(info.item_type)?;
|
||||||
|
|
||||||
let node = Node::create(&INTERNAL_CLIENT, &parent_name, info.name, true).add_to_scenegraph();
|
let node = Node::create(
|
||||||
Spatial::add_to(&node, Some(space), transform)?;
|
&calling_client,
|
||||||
ItemAcceptor::add_to(&node, type_info, Arc::downgrade(&field));
|
&format!("/item/{}/acceptor", type_info.type_name),
|
||||||
node.item
|
info.name,
|
||||||
.get()
|
true,
|
||||||
.unwrap()
|
)
|
||||||
.make_alias(&calling_client, &parent_name);
|
.add_to_scenegraph()?;
|
||||||
Ok(())
|
Spatial::add_to(&node, Some(space), transform, false)?;
|
||||||
}
|
ItemAcceptor::add_to(&node, type_info, field);
|
||||||
|
|
||||||
pub fn register_item_ui_flex(
|
|
||||||
calling_client: Arc<Client>,
|
|
||||||
type_info: &'static TypeInfo,
|
|
||||||
) -> Result<()> {
|
|
||||||
let ui = Node::create(&calling_client, "/item", type_info.type_name, true).add_to_scenegraph();
|
|
||||||
ItemUI::add_to(&ui, type_info)?;
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
542
src/nodes/items/panel.rs
Normal file
542
src/nodes/items/panel.rs
Normal file
@@ -0,0 +1,542 @@
|
|||||||
|
use crate::{
|
||||||
|
core::{
|
||||||
|
client::{get_env, state, Client, INTERNAL_CLIENT},
|
||||||
|
registry::Registry,
|
||||||
|
},
|
||||||
|
nodes::{
|
||||||
|
drawable::{model::ModelPart, Drawable},
|
||||||
|
items::{Item, ItemType, TypeInfo},
|
||||||
|
spatial::Spatial,
|
||||||
|
Message, Node,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use color_eyre::eyre::{bail, eyre, Result};
|
||||||
|
use glam::Mat4;
|
||||||
|
use lazy_static::lazy_static;
|
||||||
|
use mint::Vector2;
|
||||||
|
use nanoid::nanoid;
|
||||||
|
use rustc_hash::FxHashMap;
|
||||||
|
use serde::{
|
||||||
|
de::{Deserializer, Error, SeqAccess, Visitor},
|
||||||
|
ser::Serializer,
|
||||||
|
Deserialize, Serialize,
|
||||||
|
};
|
||||||
|
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||||
|
use std::sync::{Arc, Weak};
|
||||||
|
use tracing::debug;
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
pub static ref ITEM_TYPE_INFO_PANEL: TypeInfo = TypeInfo {
|
||||||
|
type_name: "panel",
|
||||||
|
aliased_local_signals: vec![
|
||||||
|
"apply_surface_material",
|
||||||
|
"close_toplevel",
|
||||||
|
"auto_size_toplevel",
|
||||||
|
"set_toplevel_size",
|
||||||
|
"set_toplevel_focused_visuals",
|
||||||
|
"pointer_motion",
|
||||||
|
"pointer_button",
|
||||||
|
"pointer_scroll",
|
||||||
|
"keyboard_keymap",
|
||||||
|
"keyboard_key",
|
||||||
|
"touch_down",
|
||||||
|
"touch_move",
|
||||||
|
"touch_up",
|
||||||
|
"reset_touches",
|
||||||
|
],
|
||||||
|
aliased_local_methods: vec![],
|
||||||
|
aliased_remote_signals: vec![
|
||||||
|
"toplevel_parent_changed",
|
||||||
|
"toplevel_title_changed",
|
||||||
|
"toplevel_app_id_changed",
|
||||||
|
"toplevel_fullscreen_active",
|
||||||
|
"toplevel_move_request",
|
||||||
|
"toplevel_resize_request",
|
||||||
|
"toplevel_size_changed",
|
||||||
|
"set_cursor",
|
||||||
|
"new_child",
|
||||||
|
"reposition_child",
|
||||||
|
"drop_child",
|
||||||
|
],
|
||||||
|
ui: Default::default(),
|
||||||
|
items: Registry::new(),
|
||||||
|
acceptors: Registry::new(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An ID for a surface inside this panel item
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub enum SurfaceID {
|
||||||
|
Cursor,
|
||||||
|
Toplevel,
|
||||||
|
Child(String),
|
||||||
|
}
|
||||||
|
impl Default for SurfaceID {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::Toplevel
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'de> serde::Deserialize<'de> for SurfaceID {
|
||||||
|
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||||
|
deserializer.deserialize_seq(SurfaceIDVisitor)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SurfaceIDVisitor;
|
||||||
|
|
||||||
|
impl<'de> Visitor<'de> for SurfaceIDVisitor {
|
||||||
|
type Value = SurfaceID;
|
||||||
|
|
||||||
|
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||||
|
f.write_str("idk")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
|
||||||
|
let Some(discrim) = seq.next_element()? else {
|
||||||
|
return Err(A::Error::missing_field("discrim"));
|
||||||
|
};
|
||||||
|
|
||||||
|
// idk if you wanna check for extraneous elements
|
||||||
|
// I didn't bother
|
||||||
|
|
||||||
|
match discrim {
|
||||||
|
"Cursor" => Ok(SurfaceID::Cursor),
|
||||||
|
"Toplevel" => Ok(SurfaceID::Toplevel),
|
||||||
|
"Child" => {
|
||||||
|
let Some(text) = seq.next_element()? else {
|
||||||
|
return Err(A::Error::missing_field("child_text"));
|
||||||
|
};
|
||||||
|
Ok(SurfaceID::Child(text))
|
||||||
|
}
|
||||||
|
_ => Err(A::Error::unknown_variant(
|
||||||
|
discrim,
|
||||||
|
&["Cursor", "Toplevel", "Child"],
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl serde::Serialize for SurfaceID {
|
||||||
|
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||||
|
match self {
|
||||||
|
Self::Cursor => ["Cursor"].serialize(serializer),
|
||||||
|
Self::Toplevel => ["Toplevel"].serialize(serializer),
|
||||||
|
Self::Child(text) => ["Child", text].serialize(serializer),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The origin and size of the surface's "solid" part.
|
||||||
|
#[derive(Debug, Serialize, Clone, Copy)]
|
||||||
|
pub struct Geometry {
|
||||||
|
pub origin: Vector2<i32>,
|
||||||
|
pub size: Vector2<u32>,
|
||||||
|
}
|
||||||
|
/// The state of the panel item's toplevel.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct ToplevelInfo {
|
||||||
|
/// The UID of the panel item of the parent of this toplevel, if it exists
|
||||||
|
pub parent: Option<String>,
|
||||||
|
/// Equivalent to the window title
|
||||||
|
pub title: Option<String>,
|
||||||
|
/// Application identifier, see <https://standards.freedesktop.org/desktop-entry-spec/>
|
||||||
|
pub app_id: Option<String>,
|
||||||
|
/// Current size in pixels
|
||||||
|
pub size: Vector2<u32>,
|
||||||
|
/// Recommended minimum size in pixels
|
||||||
|
pub min_size: Option<Vector2<u32>>,
|
||||||
|
/// Recommended maximum size in pixels
|
||||||
|
pub max_size: Option<Vector2<u32>>,
|
||||||
|
/// Surface geometry
|
||||||
|
pub logical_rectangle: Geometry,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Data on positioning a child
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct ChildInfo {
|
||||||
|
pub parent: SurfaceID,
|
||||||
|
pub geometry: Geometry,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The init data for the panel item.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct PanelItemInitData {
|
||||||
|
/// The cursor, if applicable.
|
||||||
|
pub cursor: Option<Geometry>,
|
||||||
|
/// Size of the toplevel surface in pixels.
|
||||||
|
pub toplevel: ToplevelInfo,
|
||||||
|
/// Vector of childs that already exist
|
||||||
|
pub children: FxHashMap<String, ChildInfo>,
|
||||||
|
/// The surface, if any, that has exclusive input to the pointer.
|
||||||
|
pub pointer_grab: Option<SurfaceID>,
|
||||||
|
/// The surface, if any, that has exclusive input to the keyboard.
|
||||||
|
pub keyboard_grab: Option<SurfaceID>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait Backend: Send + Sync + 'static {
|
||||||
|
fn start_data(&self) -> Result<PanelItemInitData>;
|
||||||
|
|
||||||
|
fn apply_surface_material(&self, surface: SurfaceID, model_part: &Arc<ModelPart>);
|
||||||
|
|
||||||
|
fn close_toplevel(&self);
|
||||||
|
fn auto_size_toplevel(&self);
|
||||||
|
fn set_toplevel_size(&self, size: Vector2<u32>);
|
||||||
|
fn set_toplevel_focused_visuals(&self, focused: bool);
|
||||||
|
|
||||||
|
fn pointer_motion(&self, surface: &SurfaceID, position: Vector2<f32>);
|
||||||
|
fn pointer_button(&self, surface: &SurfaceID, button: u32, pressed: bool);
|
||||||
|
fn pointer_scroll(
|
||||||
|
&self,
|
||||||
|
surface: &SurfaceID,
|
||||||
|
scroll_distance: Option<Vector2<f32>>,
|
||||||
|
scroll_steps: Option<Vector2<f32>>,
|
||||||
|
);
|
||||||
|
|
||||||
|
fn keyboard_keys(&self, surface: &SurfaceID, keymap_id: &str, keys: Vec<i32>);
|
||||||
|
|
||||||
|
fn touch_down(&self, surface: &SurfaceID, id: u32, position: Vector2<f32>);
|
||||||
|
fn touch_move(&self, id: u32, position: Vector2<f32>);
|
||||||
|
fn touch_up(&self, id: u32);
|
||||||
|
fn reset_touches(&self);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn panel_item_from_node(node: &Node) -> Option<Arc<dyn PanelItemTrait>> {
|
||||||
|
let ItemType::Panel(panel_item) = &node.item.get()?.specialization else {return None};
|
||||||
|
Some(panel_item.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub trait PanelItemTrait: Backend + Send + Sync + 'static {
|
||||||
|
fn uid(&self) -> &str;
|
||||||
|
fn serialize_start_data(&self, id: &str) -> Result<Message>;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PanelItem<B: Backend + ?Sized> {
|
||||||
|
pub uid: String,
|
||||||
|
node: Weak<Node>,
|
||||||
|
pub backend: Box<B>,
|
||||||
|
}
|
||||||
|
impl<B: Backend + ?Sized> PanelItem<B> {
|
||||||
|
pub fn create(backend: Box<B>, pid: Option<i32>) -> Arc<PanelItem<B>> {
|
||||||
|
debug!(?pid, "Create panel item");
|
||||||
|
|
||||||
|
let startup_settings = pid
|
||||||
|
.and_then(|pid| get_env(pid).ok())
|
||||||
|
.and_then(|env| state(&env));
|
||||||
|
|
||||||
|
let uid = nanoid!();
|
||||||
|
let node = Node::create(&INTERNAL_CLIENT, "/item/panel/item", &uid, true)
|
||||||
|
.add_to_scenegraph()
|
||||||
|
.unwrap();
|
||||||
|
let spatial = Spatial::add_to(&node, None, Mat4::IDENTITY, false).unwrap();
|
||||||
|
if let Some(startup_settings) = &startup_settings {
|
||||||
|
spatial.set_local_transform(startup_settings.root);
|
||||||
|
}
|
||||||
|
|
||||||
|
let panel_item = Arc::new(PanelItem {
|
||||||
|
uid: uid.clone(),
|
||||||
|
node: Arc::downgrade(&node),
|
||||||
|
backend,
|
||||||
|
});
|
||||||
|
|
||||||
|
let generic_panel_item: Arc<dyn PanelItemTrait> = panel_item.clone();
|
||||||
|
Item::add_to(
|
||||||
|
&node,
|
||||||
|
uid,
|
||||||
|
&ITEM_TYPE_INFO_PANEL,
|
||||||
|
ItemType::Panel(generic_panel_item),
|
||||||
|
);
|
||||||
|
|
||||||
|
node.add_local_signal("apply_surface_material", Self::apply_surface_material_flex);
|
||||||
|
node.add_local_signal("close_toplevel", Self::close_toplevel_flex);
|
||||||
|
node.add_local_signal("auto_size_toplevel", Self::auto_size_toplevel_flex);
|
||||||
|
node.add_local_signal(
|
||||||
|
"set_toplevel_size_changed",
|
||||||
|
Self::set_toplevel_size_changed_flex,
|
||||||
|
);
|
||||||
|
|
||||||
|
node.add_local_signal("pointer_motion", Self::pointer_motion_flex);
|
||||||
|
node.add_local_signal("pointer_button", Self::pointer_button_flex);
|
||||||
|
node.add_local_signal("pointer_scroll", Self::pointer_scroll_flex);
|
||||||
|
|
||||||
|
node.add_local_signal("keyboard_key", Self::keyboard_keys_flex);
|
||||||
|
|
||||||
|
node.add_local_signal("touch_down", Self::touch_down_flex);
|
||||||
|
node.add_local_signal("touch_move", Self::touch_move_flex);
|
||||||
|
node.add_local_signal("touch_up", Self::touch_up_flex);
|
||||||
|
node.add_local_signal("reset_touches", Self::reset_touches_flex);
|
||||||
|
|
||||||
|
panel_item
|
||||||
|
}
|
||||||
|
pub fn drop_toplevel(&self) {
|
||||||
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
node.destroy();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remote signals
|
||||||
|
impl<B: Backend + ?Sized> PanelItem<B> {
|
||||||
|
pub fn toplevel_parent_changed(&self, parent: &str) {
|
||||||
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
let _ = node.send_remote_signal("toplevel_parent_changed", serialize(parent).unwrap());
|
||||||
|
}
|
||||||
|
pub fn toplevel_title_changed(&self, title: &str) {
|
||||||
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
let _ = node.send_remote_signal("toplevel_title_changed", serialize(title).unwrap());
|
||||||
|
}
|
||||||
|
pub fn toplevel_app_id_changed(&self, app_id: &str) {
|
||||||
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
let _ = node.send_remote_signal("toplevel_app_id_changed", serialize(app_id).unwrap());
|
||||||
|
}
|
||||||
|
pub fn toplevel_fullscreen_active(&self, active: bool) {
|
||||||
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
let _ = node.send_remote_signal("toplevel_fullscreen_active", serialize(active).unwrap());
|
||||||
|
}
|
||||||
|
pub fn toplevel_move_request(&self) {
|
||||||
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
let _ = node.send_remote_signal("toplevel_move_request", Vec::<u8>::new());
|
||||||
|
}
|
||||||
|
pub fn toplevel_resize_request(&self, up: bool, down: bool, left: bool, right: bool) {
|
||||||
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
let _ = node.send_remote_signal(
|
||||||
|
"toplevel_resize_request",
|
||||||
|
serialize((up, down, left, right)).unwrap(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
pub fn toplevel_size_changed(&self, size: Vector2<u32>) {
|
||||||
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
let _ = node.send_remote_signal("toplevel_size_changed", serialize(size).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_cursor(&self, geometry: Option<Geometry>) {
|
||||||
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
let _ = node.send_remote_signal("set_cursor", serialize(geometry).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_child(&self, uid: &str, info: ChildInfo) {
|
||||||
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
let _ = node.send_remote_signal("new_child", serialize((uid, info)).unwrap());
|
||||||
|
}
|
||||||
|
pub fn reposition_child(&self, uid: &str, geometry: Geometry) {
|
||||||
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
let _ = node.send_remote_signal("reposition_child", serialize((uid, geometry)).unwrap());
|
||||||
|
}
|
||||||
|
pub fn drop_child(&self, uid: &str) {
|
||||||
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
let _ = node.send_remote_signal("drop_child", serialize(uid).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Local signals
|
||||||
|
macro_rules! flex_no_args {
|
||||||
|
($fn_name: ident, $trait_fn: ident) => {
|
||||||
|
fn $fn_name(node: &Node, _calling_client: Arc<Client>, _message: Message) -> Result<()> {
|
||||||
|
let Some(panel_item) = panel_item_from_node(node) else { return Ok(()) };
|
||||||
|
panel_item.$trait_fn();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
macro_rules! flex_deserialize {
|
||||||
|
($fn_name: ident, $trait_fn: ident) => {
|
||||||
|
fn $fn_name(node: &Node, _calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
|
let Some(panel_item) = panel_item_from_node(node) else { return Ok(()) };
|
||||||
|
panel_item.$trait_fn(deserialize(message.as_ref())?);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
impl<B: Backend + ?Sized> PanelItem<B> {
|
||||||
|
fn apply_surface_material_flex(
|
||||||
|
node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let Some(panel_item) = panel_item_from_node(node) else { return Ok(()) };
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct SurfaceMaterialInfo<'a> {
|
||||||
|
surface: SurfaceID,
|
||||||
|
model_node_path: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
let info: SurfaceMaterialInfo = deserialize(message.as_ref())?;
|
||||||
|
|
||||||
|
let model_node = calling_client
|
||||||
|
.scenegraph
|
||||||
|
.get_node(info.model_node_path)
|
||||||
|
.ok_or_else(|| eyre!("Model node not found"))?;
|
||||||
|
let Some(Drawable::ModelPart(model_part)) = model_node.drawable.get() else {bail!("Node is not a model")};
|
||||||
|
debug!(?info, "Apply surface material");
|
||||||
|
|
||||||
|
panel_item.apply_surface_material(info.surface, model_part);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
flex_no_args!(close_toplevel_flex, close_toplevel);
|
||||||
|
flex_no_args!(auto_size_toplevel_flex, auto_size_toplevel);
|
||||||
|
flex_deserialize!(set_toplevel_size_changed_flex, set_toplevel_size);
|
||||||
|
|
||||||
|
fn pointer_motion_flex(
|
||||||
|
node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let Some(panel_item) = panel_item_from_node(node) else { return Ok(()) };
|
||||||
|
|
||||||
|
let (surface_id, position): (SurfaceID, Vector2<f32>) = deserialize(message.as_ref())?;
|
||||||
|
debug!(?surface_id, ?position, "Pointer deactivate");
|
||||||
|
|
||||||
|
panel_item.pointer_motion(&surface_id, position);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn pointer_button_flex(
|
||||||
|
node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let Some(panel_item) = panel_item_from_node(node) else { return Ok(()) };
|
||||||
|
|
||||||
|
let (surface_id, button, state): (SurfaceID, u32, u32) = deserialize(message.as_ref())?;
|
||||||
|
debug!(?surface_id, button, state, "Pointer button");
|
||||||
|
|
||||||
|
panel_item.pointer_button(&surface_id, button, state != 0);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn pointer_scroll_flex(
|
||||||
|
node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let Some(panel_item) = panel_item_from_node(node) else { return Ok(()) };
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct PointerScrollInfo {
|
||||||
|
surface_id: SurfaceID,
|
||||||
|
axis_continuous: Option<Vector2<f32>>,
|
||||||
|
axis_discrete: Option<Vector2<f32>>,
|
||||||
|
}
|
||||||
|
let info: PointerScrollInfo = deserialize(message.as_ref())?;
|
||||||
|
debug!(?info, "Pointer scroll");
|
||||||
|
|
||||||
|
panel_item.pointer_scroll(&info.surface_id, info.axis_continuous, info.axis_discrete);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyboard_keys_flex(
|
||||||
|
node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let Some(panel_item) = panel_item_from_node(node) else { return Ok(()) };
|
||||||
|
let (surface_id, keymap_id, keys): (SurfaceID, &str, Vec<i32>) =
|
||||||
|
deserialize(message.as_ref())?;
|
||||||
|
debug!(?keys, "Set keyboard key state");
|
||||||
|
|
||||||
|
panel_item.keyboard_keys(&surface_id, keymap_id, keys);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
pub fn grab_keyboard(&self, sid: Option<SurfaceID>) {
|
||||||
|
let Some(node) = self.node.upgrade() else {return};
|
||||||
|
|
||||||
|
let Ok(message) = serialize(sid) else {return};
|
||||||
|
let _ = node.send_remote_signal("grab_keyboard", message);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn touch_down_flex(node: &Node, _calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
|
let Some(panel_item) = panel_item_from_node(node) else { return Ok(()) };
|
||||||
|
|
||||||
|
let (surface_id, id, position): (SurfaceID, u32, Vector2<f32>) =
|
||||||
|
deserialize(message.as_ref())?;
|
||||||
|
debug!(?surface_id, id, ?position, "Touch down");
|
||||||
|
|
||||||
|
panel_item.touch_down(&surface_id, id, position);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn touch_move_flex(node: &Node, _calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
|
let Some(panel_item) = panel_item_from_node(node) else { return Ok(()) };
|
||||||
|
|
||||||
|
let (id, position): (u32, Vector2<f32>) = deserialize(message.as_ref())?;
|
||||||
|
debug!(?position, "Touch move");
|
||||||
|
|
||||||
|
panel_item.touch_move(id, position);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
flex_deserialize!(touch_up_flex, touch_up);
|
||||||
|
flex_no_args!(reset_touches_flex, reset_touches);
|
||||||
|
}
|
||||||
|
impl<B: Backend + ?Sized> PanelItemTrait for PanelItem<B> {
|
||||||
|
fn uid(&self) -> &str {
|
||||||
|
&self.uid
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize_start_data(&self, id: &str) -> Result<Message> {
|
||||||
|
Ok(serialize((id, self.start_data()?))?.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<B: Backend + ?Sized> Backend for PanelItem<B> {
|
||||||
|
fn start_data(&self) -> Result<PanelItemInitData> {
|
||||||
|
self.backend.start_data()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_surface_material(&self, surface: SurfaceID, model_part: &Arc<ModelPart>) {
|
||||||
|
self.backend.apply_surface_material(surface, model_part)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close_toplevel(&self) {
|
||||||
|
self.backend.close_toplevel()
|
||||||
|
}
|
||||||
|
fn auto_size_toplevel(&self) {
|
||||||
|
self.backend.auto_size_toplevel()
|
||||||
|
}
|
||||||
|
fn set_toplevel_size(&self, size: Vector2<u32>) {
|
||||||
|
self.backend.set_toplevel_size(size)
|
||||||
|
}
|
||||||
|
fn set_toplevel_focused_visuals(&self, focused: bool) {
|
||||||
|
self.backend.set_toplevel_focused_visuals(focused)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pointer_motion(&self, surface: &SurfaceID, position: Vector2<f32>) {
|
||||||
|
self.backend.pointer_motion(surface, position)
|
||||||
|
}
|
||||||
|
fn pointer_button(&self, surface: &SurfaceID, button: u32, pressed: bool) {
|
||||||
|
self.backend.pointer_button(surface, button, pressed)
|
||||||
|
}
|
||||||
|
fn pointer_scroll(
|
||||||
|
&self,
|
||||||
|
surface: &SurfaceID,
|
||||||
|
scroll_distance: Option<Vector2<f32>>,
|
||||||
|
scroll_steps: Option<Vector2<f32>>,
|
||||||
|
) {
|
||||||
|
self.backend
|
||||||
|
.pointer_scroll(surface, scroll_distance, scroll_steps)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyboard_keys(&self, surface: &SurfaceID, keymap_id: &str, keys: Vec<i32>) {
|
||||||
|
self.backend.keyboard_keys(surface, keymap_id, keys)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn touch_down(&self, surface: &SurfaceID, id: u32, position: Vector2<f32>) {
|
||||||
|
self.backend.touch_down(surface, id, position)
|
||||||
|
}
|
||||||
|
fn touch_move(&self, id: u32, position: Vector2<f32>) {
|
||||||
|
self.backend.touch_move(id, position)
|
||||||
|
}
|
||||||
|
fn touch_up(&self, id: u32) {
|
||||||
|
self.backend.touch_up(id)
|
||||||
|
}
|
||||||
|
fn reset_touches(&self) {
|
||||||
|
self.backend.reset_touches()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<B: Backend + ?Sized> Drop for PanelItem<B> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// Dropped panel item, basically just a debug breakpoint place
|
||||||
|
}
|
||||||
|
}
|
||||||
260
src/nodes/mod.rs
260
src/nodes/mod.rs
@@ -1,4 +1,5 @@
|
|||||||
pub mod alias;
|
pub mod alias;
|
||||||
|
pub mod audio;
|
||||||
pub mod data;
|
pub mod data;
|
||||||
pub mod drawable;
|
pub mod drawable;
|
||||||
pub mod fields;
|
pub mod fields;
|
||||||
@@ -7,59 +8,82 @@ pub mod input;
|
|||||||
pub mod items;
|
pub mod items;
|
||||||
pub mod root;
|
pub mod root;
|
||||||
pub mod spatial;
|
pub mod spatial;
|
||||||
pub mod startup;
|
|
||||||
|
|
||||||
use anyhow::{anyhow, Result};
|
use color_eyre::eyre::{eyre, Result};
|
||||||
use nanoid::nanoid;
|
use nanoid::nanoid;
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
use portable_atomic::{AtomicBool, Ordering};
|
||||||
|
use rustc_hash::FxHashMap;
|
||||||
|
use stardust_xr::messenger::MessageSenderHandle;
|
||||||
use stardust_xr::scenegraph::ScenegraphError;
|
use stardust_xr::scenegraph::ScenegraphError;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use stardust_xr::schemas::flex::deserialize;
|
||||||
|
use std::fmt::Debug;
|
||||||
|
use std::future::Future;
|
||||||
|
use std::os::fd::OwnedFd;
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::{Arc, Weak};
|
||||||
use std::vec::Vec;
|
use std::vec::Vec;
|
||||||
|
|
||||||
use core::hash::BuildHasherDefault;
|
|
||||||
use dashmap::DashMap;
|
|
||||||
use rustc_hash::FxHasher;
|
|
||||||
|
|
||||||
use crate::core::client::Client;
|
use crate::core::client::Client;
|
||||||
use crate::core::registry::Registry;
|
use crate::core::registry::Registry;
|
||||||
|
use crate::core::scenegraph::MethodResponseSender;
|
||||||
|
|
||||||
use self::alias::Alias;
|
use self::alias::Alias;
|
||||||
|
use self::audio::Sound;
|
||||||
use self::data::{PulseReceiver, PulseSender};
|
use self::data::{PulseReceiver, PulseSender};
|
||||||
|
use self::drawable::Drawable;
|
||||||
use self::drawable::model::Model;
|
|
||||||
use self::drawable::text::Text;
|
|
||||||
use self::fields::Field;
|
use self::fields::Field;
|
||||||
use self::input::{InputHandler, InputMethod};
|
use self::input::{InputHandler, InputMethod};
|
||||||
use self::items::{Item, ItemAcceptor, ItemUI};
|
use self::items::{Item, ItemAcceptor, ItemUI};
|
||||||
|
use self::spatial::zone::Zone;
|
||||||
use self::spatial::Spatial;
|
use self::spatial::Spatial;
|
||||||
use self::startup::StartupSettings;
|
|
||||||
|
|
||||||
pub type Signal = fn(&Node, Arc<Client>, &[u8]) -> Result<()>;
|
#[derive(Default)]
|
||||||
pub type Method = fn(&Node, Arc<Client>, &[u8]) -> Result<Vec<u8>>;
|
pub struct Message {
|
||||||
|
pub data: Vec<u8>,
|
||||||
|
pub fds: Vec<OwnedFd>,
|
||||||
|
}
|
||||||
|
impl From<Vec<u8>> for Message {
|
||||||
|
fn from(data: Vec<u8>) -> Self {
|
||||||
|
Message {
|
||||||
|
data,
|
||||||
|
fds: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl AsRef<[u8]> for Message {
|
||||||
|
fn as_ref(&self) -> &[u8] {
|
||||||
|
&self.data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type Signal = fn(&Node, Arc<Client>, Message) -> Result<()>;
|
||||||
|
pub type Method = fn(&Node, Arc<Client>, Message, MethodResponseSender);
|
||||||
|
|
||||||
pub struct Node {
|
pub struct Node {
|
||||||
|
pub enabled: Arc<AtomicBool>,
|
||||||
pub(super) uid: String,
|
pub(super) uid: String,
|
||||||
path: String,
|
path: String,
|
||||||
|
client: Weak<Client>,
|
||||||
|
message_sender_handle: Option<MessageSenderHandle>,
|
||||||
// trailing_slash_pos: usize,
|
// trailing_slash_pos: usize,
|
||||||
local_signals: DashMap<String, Signal, BuildHasherDefault<FxHasher>>,
|
local_signals: Mutex<FxHashMap<String, Signal>>,
|
||||||
local_methods: DashMap<String, Method, BuildHasherDefault<FxHasher>>,
|
local_methods: Mutex<FxHashMap<String, Method>>,
|
||||||
destroyable: AtomicBool,
|
destroyable: bool,
|
||||||
|
|
||||||
pub alias: OnceCell<Arc<Alias>>,
|
pub alias: OnceCell<Arc<Alias>>,
|
||||||
aliases: Registry<Alias>,
|
aliases: Registry<Alias>,
|
||||||
|
|
||||||
pub spatial: OnceCell<Arc<Spatial>>,
|
pub spatial: OnceCell<Arc<Spatial>>,
|
||||||
pub field: OnceCell<Arc<Field>>,
|
pub field: OnceCell<Arc<Field>>,
|
||||||
|
pub zone: OnceCell<Arc<Zone>>,
|
||||||
|
|
||||||
// Data
|
// Data
|
||||||
pub pulse_sender: OnceCell<Arc<PulseSender>>,
|
pub pulse_sender: OnceCell<Arc<PulseSender>>,
|
||||||
pub pulse_receiver: OnceCell<Arc<PulseReceiver>>,
|
pub pulse_receiver: OnceCell<Arc<PulseReceiver>>,
|
||||||
|
|
||||||
// Drawable
|
// Drawable
|
||||||
pub model: OnceCell<Arc<Model>>,
|
pub drawable: OnceCell<Drawable>,
|
||||||
pub text: OnceCell<Arc<Text>>,
|
|
||||||
|
|
||||||
// Input
|
// Input
|
||||||
pub input_method: OnceCell<Arc<InputMethod>>,
|
pub input_method: OnceCell<Arc<InputMethod>>,
|
||||||
@@ -70,10 +94,8 @@ pub struct Node {
|
|||||||
pub item_acceptor: OnceCell<Arc<ItemAcceptor>>,
|
pub item_acceptor: OnceCell<Arc<ItemAcceptor>>,
|
||||||
pub item_ui: OnceCell<Arc<ItemUI>>,
|
pub item_ui: OnceCell<Arc<ItemUI>>,
|
||||||
|
|
||||||
// Startup
|
// Sound
|
||||||
pub startup_settings: OnceCell<Mutex<StartupSettings>>,
|
pub sound: OnceCell<Arc<Sound>>,
|
||||||
|
|
||||||
pub(crate) client: Weak<Client>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Node {
|
impl Node {
|
||||||
@@ -86,63 +108,93 @@ impl Node {
|
|||||||
pub fn get_path(&self) -> &str {
|
pub fn get_path(&self) -> &str {
|
||||||
self.path.as_str()
|
self.path.as_str()
|
||||||
}
|
}
|
||||||
pub fn is_destroyable(&self) -> bool {
|
|
||||||
self.destroyable.load(Ordering::Relaxed)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn create(client: &Arc<Client>, parent: &str, name: &str, destroyable: bool) -> Self {
|
pub fn create(client: &Arc<Client>, parent: &str, name: &str, destroyable: bool) -> Self {
|
||||||
let mut path = parent.to_string();
|
let mut path = parent.to_string();
|
||||||
path.push('/');
|
path.push('/');
|
||||||
path.push_str(name);
|
path.push_str(name);
|
||||||
let node = Node {
|
let node = Node {
|
||||||
|
enabled: Arc::new(AtomicBool::new(true)),
|
||||||
uid: nanoid!(),
|
uid: nanoid!(),
|
||||||
client: Arc::downgrade(client),
|
client: Arc::downgrade(client),
|
||||||
|
message_sender_handle: client.message_sender_handle.clone(),
|
||||||
path,
|
path,
|
||||||
// trailing_slash_pos: parent.len(),
|
// trailing_slash_pos: parent.len(),
|
||||||
local_signals: Default::default(),
|
local_signals: Default::default(),
|
||||||
local_methods: Default::default(),
|
local_methods: Default::default(),
|
||||||
destroyable: AtomicBool::from(destroyable),
|
destroyable,
|
||||||
|
|
||||||
alias: OnceCell::new(),
|
alias: OnceCell::new(),
|
||||||
aliases: Registry::new(),
|
aliases: Registry::new(),
|
||||||
|
|
||||||
spatial: OnceCell::new(),
|
spatial: OnceCell::new(),
|
||||||
field: OnceCell::new(),
|
field: OnceCell::new(),
|
||||||
|
zone: OnceCell::new(),
|
||||||
pulse_sender: OnceCell::new(),
|
pulse_sender: OnceCell::new(),
|
||||||
pulse_receiver: OnceCell::new(),
|
pulse_receiver: OnceCell::new(),
|
||||||
model: OnceCell::new(),
|
drawable: OnceCell::new(),
|
||||||
text: OnceCell::new(),
|
|
||||||
input_method: OnceCell::new(),
|
input_method: OnceCell::new(),
|
||||||
input_handler: OnceCell::new(),
|
input_handler: OnceCell::new(),
|
||||||
item: OnceCell::new(),
|
item: OnceCell::new(),
|
||||||
item_acceptor: OnceCell::new(),
|
item_acceptor: OnceCell::new(),
|
||||||
item_ui: OnceCell::new(),
|
item_ui: OnceCell::new(),
|
||||||
startup_settings: OnceCell::new(),
|
sound: OnceCell::new(),
|
||||||
};
|
};
|
||||||
|
node.add_local_signal("set_enabled", Node::set_enabled_flex);
|
||||||
node.add_local_signal("destroy", Node::destroy_flex);
|
node.add_local_signal("destroy", Node::destroy_flex);
|
||||||
node
|
node
|
||||||
}
|
}
|
||||||
pub fn add_to_scenegraph(self) -> Arc<Node> {
|
pub fn add_to_scenegraph(self) -> Result<Arc<Node>> {
|
||||||
self.get_client().unwrap().scenegraph.add_node(self)
|
Ok(self
|
||||||
|
.get_client()
|
||||||
|
.ok_or_else(|| eyre!("Internal: Unable to get client"))?
|
||||||
|
.scenegraph
|
||||||
|
.add_node(self))
|
||||||
}
|
}
|
||||||
pub fn destroy(&self) {
|
pub fn destroy(&self) {
|
||||||
let _ = self
|
if let Some(client) = self.get_client() {
|
||||||
.get_client()
|
client.scenegraph.remove_node(self.get_path());
|
||||||
.map(|c| c.scenegraph.remove_node(self.get_path()));
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn destroy_flex(node: &Node, _calling_client: Arc<Client>, _data: &[u8]) -> Result<()> {
|
pub fn set_enabled_flex(
|
||||||
if node.is_destroyable() {
|
node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
node.enabled
|
||||||
|
.store(deserialize(message.as_ref())?, Ordering::Relaxed);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
// very much up for debate if we should allow this, as you can match objects using this
|
||||||
|
// pub fn get_client_pid_flex(
|
||||||
|
// node: &Node,
|
||||||
|
// _calling_client: Arc<Client>,
|
||||||
|
// _message: Message,
|
||||||
|
// ) -> Result<Message> {
|
||||||
|
// let client = node
|
||||||
|
// .client
|
||||||
|
// .upgrade()
|
||||||
|
// .ok_or_else(|| eyre!("Could not get client for node?"))?;
|
||||||
|
// let pid = client.pid.ok_or_else(|| eyre!("Client PID is unknown"))?;
|
||||||
|
// Ok(serialize(pid)?.into())
|
||||||
|
// }
|
||||||
|
pub fn destroy_flex(
|
||||||
|
node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
_message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
if node.destroyable {
|
||||||
node.destroy();
|
node.destroy();
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_local_signal(&self, name: &str, signal: Signal) {
|
pub fn add_local_signal(&self, name: &str, signal: Signal) {
|
||||||
self.local_signals.insert(name.to_string(), signal);
|
self.local_signals.lock().insert(name.to_string(), signal);
|
||||||
}
|
}
|
||||||
pub fn add_local_method(&self, name: &str, method: Method) {
|
pub fn add_local_method(&self, name: &str, method: Method) {
|
||||||
self.local_methods.insert(name.to_string(), method);
|
self.local_methods.lock().insert(name.to_string(), method);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_aspect<F, T>(
|
pub fn get_aspect<F, T>(
|
||||||
@@ -150,98 +202,134 @@ impl Node {
|
|||||||
node_name: &'static str,
|
node_name: &'static str,
|
||||||
aspect_type: &'static str,
|
aspect_type: &'static str,
|
||||||
aspect_fn: F,
|
aspect_fn: F,
|
||||||
) -> Result<Arc<T>>
|
) -> Result<&T>
|
||||||
where
|
where
|
||||||
F: FnOnce(&Node) -> &OnceCell<Arc<T>>,
|
F: FnOnce(&Node) -> &OnceCell<T>,
|
||||||
{
|
{
|
||||||
aspect_fn(self)
|
aspect_fn(self)
|
||||||
.get()
|
.get()
|
||||||
.ok_or_else(|| anyhow!("{} is not a {} node", node_name, aspect_type))
|
.ok_or_else(|| eyre!("{} is not a {} node", node_name, aspect_type))
|
||||||
.cloned()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn send_local_signal(
|
pub fn send_local_signal(
|
||||||
&self,
|
&self,
|
||||||
calling_client: Arc<Client>,
|
calling_client: Arc<Client>,
|
||||||
method: &str,
|
method: &str,
|
||||||
data: &[u8],
|
message: Message,
|
||||||
) -> Result<(), ScenegraphError> {
|
) -> Result<(), ScenegraphError> {
|
||||||
if let Some(alias) = self.alias.get() {
|
if let Some(alias) = self.alias.get() {
|
||||||
if !alias.info.local_signals.iter().any(|e| e == &method) {
|
if !alias.info.server_signals.iter().any(|e| e == &method) {
|
||||||
return Err(ScenegraphError::SignalNotFound);
|
return Err(ScenegraphError::SignalNotFound);
|
||||||
}
|
}
|
||||||
alias
|
alias
|
||||||
.original
|
.original
|
||||||
.upgrade()
|
.upgrade()
|
||||||
.ok_or(ScenegraphError::BrokenAlias)?
|
.ok_or(ScenegraphError::BrokenAlias)?
|
||||||
.send_local_signal(calling_client, method, data)
|
.send_local_signal(calling_client, method, message)
|
||||||
} else {
|
} else {
|
||||||
let signal = self
|
let signal = self
|
||||||
.local_signals
|
.local_signals
|
||||||
|
.lock()
|
||||||
.get(method)
|
.get(method)
|
||||||
|
.cloned()
|
||||||
.ok_or(ScenegraphError::SignalNotFound)?;
|
.ok_or(ScenegraphError::SignalNotFound)?;
|
||||||
signal(self, calling_client, data)
|
signal(self, calling_client, message).map_err(|error| ScenegraphError::SignalError {
|
||||||
.map_err(|error| ScenegraphError::SignalError { error })
|
error: error.to_string(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn execute_local_method(
|
pub fn execute_local_method(
|
||||||
&self,
|
&self,
|
||||||
calling_client: Arc<Client>,
|
calling_client: Arc<Client>,
|
||||||
method: &str,
|
method: &str,
|
||||||
data: &[u8],
|
message: Message,
|
||||||
) -> Result<Vec<u8>, ScenegraphError> {
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
if let Some(alias) = self.alias.get() {
|
if let Some(alias) = self.alias.get() {
|
||||||
if !alias.info.local_methods.iter().any(|e| e == &method) {
|
if !alias.info.server_methods.iter().any(|e| e == &method) {
|
||||||
return Err(ScenegraphError::MethodNotFound);
|
response.send(Err(ScenegraphError::MethodNotFound));
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
alias
|
let Some(alias) = alias.original.upgrade() else {
|
||||||
.original
|
response.send(Err(ScenegraphError::BrokenAlias));
|
||||||
.upgrade()
|
return;
|
||||||
.ok_or(ScenegraphError::BrokenAlias)?
|
};
|
||||||
.execute_local_method(calling_client, method, data)
|
alias.execute_local_method(
|
||||||
|
calling_client,
|
||||||
|
method,
|
||||||
|
Message {
|
||||||
|
data: message.data.clone(),
|
||||||
|
fds: Vec::new(),
|
||||||
|
},
|
||||||
|
response,
|
||||||
|
)
|
||||||
} else {
|
} else {
|
||||||
let method = self
|
let Some(method) = self.local_methods.lock().get(method).cloned() else {
|
||||||
.local_methods
|
response.send(Err(ScenegraphError::MethodNotFound));
|
||||||
.get(method)
|
return;
|
||||||
.ok_or(ScenegraphError::MethodNotFound)?;
|
};
|
||||||
method(self, calling_client, data)
|
method(self, calling_client, message, response);
|
||||||
.map_err(|error| ScenegraphError::MethodError { error })
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn send_remote_signal(&self, method: &str, data: &[u8]) -> Result<()> {
|
pub fn send_remote_signal(&self, method: &str, message: impl Into<Message>) -> Result<()> {
|
||||||
|
let message = message.into();
|
||||||
self.aliases
|
self.aliases
|
||||||
.get_valid_contents()
|
.get_valid_contents()
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|alias| alias.info.remote_signals.iter().any(|e| e == &method))
|
.filter(|alias| alias.info.client_signals.iter().any(|e| e == &method))
|
||||||
.for_each(|alias| {
|
.filter_map(|alias| alias.node.upgrade())
|
||||||
let _ = alias
|
.for_each(|node| {
|
||||||
.node
|
// Beware! file descriptors will not be sent to aliases!!!
|
||||||
.upgrade()
|
let _ = node.send_remote_signal(
|
||||||
.unwrap()
|
method,
|
||||||
.send_remote_signal(method, data);
|
Message {
|
||||||
|
data: message.data.clone(),
|
||||||
|
fds: Vec::new(),
|
||||||
|
},
|
||||||
|
);
|
||||||
});
|
});
|
||||||
let path = self.path.clone();
|
let path = self.path.clone();
|
||||||
let method = method.to_string();
|
let method = method.to_string();
|
||||||
let data = data.to_vec();
|
if let Some(handle) = self.message_sender_handle.as_ref() {
|
||||||
if let Some(client) = self.get_client() {
|
handle.signal(path.as_str(), method.as_str(), &message.data, message.fds)?;
|
||||||
if let Some(messenger) = client.messenger.as_ref() {
|
|
||||||
messenger.send_remote_signal(path.as_str(), method.as_str(), data.as_slice());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
pub async fn execute_remote_method(&self, method: &str, data: Vec<u8>) -> Result<Vec<u8>> {
|
pub fn execute_remote_method(
|
||||||
if let Some(client) = self.get_client() {
|
&self,
|
||||||
match client.messenger.as_ref() {
|
method: &str,
|
||||||
None => Err(anyhow!("Messenger does not exist for this node's client")),
|
message: impl Into<Message>,
|
||||||
Some(messenger) => {
|
) -> Result<impl Future<Output = Result<Message>>> {
|
||||||
messenger
|
let message = message.into();
|
||||||
.execute_remote_method(self.path.as_str(), method, &data)
|
let message_sender_handle = self
|
||||||
.await
|
.message_sender_handle
|
||||||
|
.as_ref()
|
||||||
|
.ok_or(eyre!("Messenger does not exist for this node"))?;
|
||||||
|
|
||||||
|
let future =
|
||||||
|
message_sender_handle.method(self.path.as_str(), method, &message.data, message.fds)?;
|
||||||
|
|
||||||
|
Ok(async {
|
||||||
|
match future.await {
|
||||||
|
Ok(m) => {
|
||||||
|
let (data, fds) = m.into_components();
|
||||||
|
Ok(Message { data, fds })
|
||||||
}
|
}
|
||||||
|
Err(e) => Err(eyre!(e)),
|
||||||
}
|
}
|
||||||
} else {
|
})
|
||||||
Err(anyhow!("Client does not exist somehow?"))
|
}
|
||||||
}
|
}
|
||||||
|
impl Debug for Node {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("Node")
|
||||||
|
.field("uid", &self.uid)
|
||||||
|
.field("path", &self.path)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for Node {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// Debug breakpoint
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,77 +1,104 @@
|
|||||||
use super::spatial::Spatial;
|
use super::spatial::Spatial;
|
||||||
use super::startup::DESKTOP_STARTUP_IDS;
|
use super::{Message, Node};
|
||||||
use super::Node;
|
|
||||||
use crate::core::client::Client;
|
use crate::core::client::Client;
|
||||||
|
use crate::core::client_state::{ClientState, ClientStateInternal};
|
||||||
use crate::core::registry::Registry;
|
use crate::core::registry::Registry;
|
||||||
use anyhow::{anyhow, Result};
|
use crate::core::scenegraph::MethodResponseSender;
|
||||||
|
use crate::wayland::WAYLAND_DISPLAY;
|
||||||
|
use crate::STARDUST_INSTANCE;
|
||||||
|
use color_eyre::eyre::Result;
|
||||||
use glam::Mat4;
|
use glam::Mat4;
|
||||||
|
use rustc_hash::FxHashMap;
|
||||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||||
|
use tracing::instrument;
|
||||||
|
|
||||||
|
use std::future::Future;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
static ROOT_REGISTRY: Registry<Root> = Registry::new();
|
static ROOT_REGISTRY: Registry<Root> = Registry::new();
|
||||||
|
|
||||||
pub struct Root {
|
pub struct Root {
|
||||||
node: Arc<Node>,
|
pub node: Arc<Node>,
|
||||||
logic_step: AtomicBool,
|
send_frame_event: AtomicBool,
|
||||||
}
|
}
|
||||||
impl Root {
|
impl Root {
|
||||||
pub fn create(client: &Arc<Client>) -> Arc<Self> {
|
pub fn create(client: &Arc<Client>) -> Result<Arc<Self>> {
|
||||||
let node = Node::create(client, "", "", false);
|
let node = Node::create(client, "", "", false);
|
||||||
node.add_local_signal("applyDesktopStartupID", Root::apply_desktop_startup_id);
|
node.add_local_signal("subscribe_frame", Root::subscribe_frame_flex);
|
||||||
node.add_local_signal("subscribeLogicStep", Root::subscribe_logic_step);
|
node.add_local_signal("set_base_prefixes", Root::set_base_prefixes_flex);
|
||||||
node.add_local_signal("setBasePrefixes", Root::set_base_prefixes);
|
node.add_local_method("state_token", Root::state_token_flex);
|
||||||
let node = node.add_to_scenegraph();
|
node.add_local_method(
|
||||||
let _ = Spatial::add_to(&node, None, Mat4::IDENTITY);
|
"get_connection_environment",
|
||||||
|
get_connection_environment_flex,
|
||||||
|
);
|
||||||
|
let node = node.add_to_scenegraph()?;
|
||||||
|
let _ = Spatial::add_to(&node, None, client.state.root, false);
|
||||||
|
|
||||||
ROOT_REGISTRY.add(Root {
|
Ok(ROOT_REGISTRY.add(Root {
|
||||||
node,
|
node,
|
||||||
logic_step: AtomicBool::from(false),
|
send_frame_event: AtomicBool::from(false),
|
||||||
})
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn apply_desktop_startup_id(
|
fn subscribe_frame_flex(
|
||||||
node: &Node,
|
_node: &Node,
|
||||||
_calling_client: Arc<Client>,
|
calling_client: Arc<Client>,
|
||||||
data: &[u8],
|
_message: Message,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let startup_settings = DESKTOP_STARTUP_IDS
|
|
||||||
.lock()
|
|
||||||
.remove(flexbuffers::Reader::get_root(data)?.get_str()?)
|
|
||||||
.ok_or_else(|| anyhow!("Desktop startup ID not found in the list!"))?;
|
|
||||||
node.spatial
|
|
||||||
.get()
|
|
||||||
.unwrap()
|
|
||||||
.set_local_transform(startup_settings.transform);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn subscribe_logic_step(_node: &Node, calling_client: Arc<Client>, _data: &[u8]) -> Result<()> {
|
|
||||||
calling_client
|
calling_client
|
||||||
.root
|
.root
|
||||||
.get()
|
.get()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.logic_step
|
.send_frame_event
|
||||||
.store(true, Ordering::Relaxed);
|
.store(true, Ordering::Relaxed);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn logic_step(delta: f64) {
|
#[instrument(level = "debug")]
|
||||||
|
pub fn send_frame_events(delta: f64) {
|
||||||
if let Ok(data) = serialize((delta, 0.0)) {
|
if let Ok(data) = serialize((delta, 0.0)) {
|
||||||
for root in ROOT_REGISTRY.get_valid_contents() {
|
for root in ROOT_REGISTRY.get_valid_contents() {
|
||||||
if root.logic_step.load(Ordering::Relaxed) {
|
if root.send_frame_event.load(Ordering::Relaxed) {
|
||||||
let _ = root.node.send_remote_signal("logicStep", &data);
|
let _ = root.node.send_remote_signal("frame", data.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_base_prefixes(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
fn set_base_prefixes_flex(
|
||||||
*calling_client.base_resource_prefixes.lock() = deserialize(data)?;
|
_node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
*calling_client.base_resource_prefixes.lock() = deserialize(message.as_ref())?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn state_token_flex(
|
||||||
|
_node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
response.wrap_sync(|| {
|
||||||
|
let state: ClientStateInternal = deserialize(message.as_ref())?;
|
||||||
|
let token = ClientState::from_deserialized(&calling_client, state).token();
|
||||||
|
Ok(serialize(token)?.into())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_transform(&self, transform: Mat4) {
|
||||||
|
let spatial = self.node.spatial.get().unwrap();
|
||||||
|
spatial.set_spatial_parent(None).unwrap();
|
||||||
|
spatial.set_local_transform(transform);
|
||||||
|
}
|
||||||
|
pub fn save_state(&self) -> impl Future<Output = Result<ClientStateInternal>> {
|
||||||
|
let future = self
|
||||||
|
.node
|
||||||
|
.execute_remote_method("save_state", Message::default());
|
||||||
|
async move { Ok(deserialize(&future?.await?.data)?) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for Root {
|
impl Drop for Root {
|
||||||
@@ -79,3 +106,33 @@ impl Drop for Root {
|
|||||||
ROOT_REGISTRY.remove(self);
|
ROOT_REGISTRY.remove(self);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
macro_rules! var_env_insert {
|
||||||
|
($env:ident, $name:ident) => {
|
||||||
|
$env.insert(stringify!($name).to_string(), $name.get().unwrap().clone());
|
||||||
|
};
|
||||||
|
}
|
||||||
|
pub fn get_connection_environment_flex(
|
||||||
|
_node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
_message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
response.wrap_sync(move || {
|
||||||
|
let mut env: FxHashMap<String, String> = FxHashMap::default();
|
||||||
|
var_env_insert!(env, STARDUST_INSTANCE);
|
||||||
|
#[cfg(feature = "wayland")]
|
||||||
|
{
|
||||||
|
var_env_insert!(env, WAYLAND_DISPLAY);
|
||||||
|
#[cfg(feature = "xwayland")]
|
||||||
|
var_env_insert!(env, DISPLAY);
|
||||||
|
env.insert("GDK_BACKEND".to_string(), "wayland".to_string());
|
||||||
|
env.insert("QT_QPA_PLATFORM".to_string(), "wayland".to_string());
|
||||||
|
env.insert("MOZ_ENABLE_WAYLAND".to_string(), "1".to_string());
|
||||||
|
env.insert("CLUTTER_BACKEND".to_string(), "wayland".to_string());
|
||||||
|
env.insert("SDL_VIDEODRIVER".to_string(), "wayland".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(serialize(env)?.into())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,291 +0,0 @@
|
|||||||
use super::Node;
|
|
||||||
use crate::core::client::Client;
|
|
||||||
use anyhow::{anyhow, ensure, Result};
|
|
||||||
use glam::{Mat4, Quat};
|
|
||||||
use mint::Vector3;
|
|
||||||
use parking_lot::Mutex;
|
|
||||||
|
|
||||||
use serde::Deserialize;
|
|
||||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
|
||||||
use stardust_xr::values::Transform;
|
|
||||||
use std::ptr;
|
|
||||||
use std::sync::{Arc, Weak};
|
|
||||||
|
|
||||||
pub struct Spatial {
|
|
||||||
pub(super) node: Weak<Node>,
|
|
||||||
parent: Mutex<Option<Arc<Spatial>>>,
|
|
||||||
pub(super) transform: Mutex<Mat4>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Spatial {
|
|
||||||
pub fn new(node: Weak<Node>, parent: Option<Arc<Spatial>>, transform: Mat4) -> Arc<Self> {
|
|
||||||
Arc::new(Spatial {
|
|
||||||
node,
|
|
||||||
parent: Mutex::new(parent),
|
|
||||||
transform: Mutex::new(transform),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
pub fn add_to(
|
|
||||||
node: &Arc<Node>,
|
|
||||||
parent: Option<Arc<Spatial>>,
|
|
||||||
transform: Mat4,
|
|
||||||
) -> Result<Arc<Spatial>> {
|
|
||||||
ensure!(
|
|
||||||
node.spatial.get().is_none(),
|
|
||||||
"Internal: Node already has a Spatial aspect!"
|
|
||||||
);
|
|
||||||
let spatial = Spatial {
|
|
||||||
node: Arc::downgrade(node),
|
|
||||||
parent: Mutex::new(parent),
|
|
||||||
transform: Mutex::new(transform),
|
|
||||||
};
|
|
||||||
node.add_local_method("getTransform", Spatial::get_transform_flex);
|
|
||||||
node.add_local_signal("setTransform", Spatial::set_transform_flex);
|
|
||||||
node.add_local_signal("setSpatialParent", Spatial::set_spatial_parent_flex);
|
|
||||||
node.add_local_signal(
|
|
||||||
"setSpatialParentInPlace",
|
|
||||||
Spatial::set_spatial_parent_in_place_flex,
|
|
||||||
);
|
|
||||||
let spatial_arc = Arc::new(spatial);
|
|
||||||
let _ = node.spatial.set(spatial_arc.clone());
|
|
||||||
Ok(spatial_arc)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn space_to_space_matrix(from: Option<&Spatial>, to: Option<&Spatial>) -> Mat4 {
|
|
||||||
let space_to_world_matrix = from.map_or(Mat4::IDENTITY, |from| from.global_transform());
|
|
||||||
let world_to_space_matrix = to.map_or(Mat4::IDENTITY, |to| to.global_transform().inverse());
|
|
||||||
world_to_space_matrix * space_to_world_matrix
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn local_transform(&self) -> Mat4 {
|
|
||||||
*self.transform.lock()
|
|
||||||
}
|
|
||||||
pub fn global_transform(&self) -> Mat4 {
|
|
||||||
match self.parent.lock().clone() {
|
|
||||||
Some(value) => value.global_transform() * *self.transform.lock(),
|
|
||||||
None => *self.transform.lock(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn set_local_transform(&self, transform: Mat4) {
|
|
||||||
*self.transform.lock() = transform;
|
|
||||||
}
|
|
||||||
pub fn set_local_transform_components(
|
|
||||||
&self,
|
|
||||||
reference_space: Option<&Spatial>,
|
|
||||||
transform: Transform,
|
|
||||||
) {
|
|
||||||
let reference_to_parent_transform = reference_space
|
|
||||||
.map(|reference_space| {
|
|
||||||
Spatial::space_to_space_matrix(Some(reference_space), self.parent.lock().as_deref())
|
|
||||||
})
|
|
||||||
.unwrap_or(Mat4::IDENTITY);
|
|
||||||
let mut local_transform_in_reference_space =
|
|
||||||
reference_to_parent_transform.inverse() * self.local_transform();
|
|
||||||
let (mut reference_space_scl, mut reference_space_rot, mut reference_space_pos) =
|
|
||||||
local_transform_in_reference_space.to_scale_rotation_translation();
|
|
||||||
|
|
||||||
if let Some(pos) = transform.position {
|
|
||||||
reference_space_pos = pos.into()
|
|
||||||
}
|
|
||||||
if let Some(rot) = transform.rotation {
|
|
||||||
reference_space_rot = rot.into()
|
|
||||||
} else if reference_space_rot.is_nan() {
|
|
||||||
reference_space_rot = Quat::IDENTITY;
|
|
||||||
}
|
|
||||||
if let Some(scl) = transform.scale {
|
|
||||||
reference_space_scl = scl.into()
|
|
||||||
}
|
|
||||||
|
|
||||||
local_transform_in_reference_space = Mat4::from_scale_rotation_translation(
|
|
||||||
reference_space_scl,
|
|
||||||
reference_space_rot,
|
|
||||||
reference_space_pos,
|
|
||||||
);
|
|
||||||
self.set_local_transform(
|
|
||||||
reference_to_parent_transform * local_transform_in_reference_space,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn is_ancestor_of(&self, spatial: Arc<Spatial>) -> bool {
|
|
||||||
let mut current_ancestor = spatial;
|
|
||||||
loop {
|
|
||||||
if Arc::as_ptr(¤t_ancestor) == ptr::addr_of!(*self) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
let current_ancestor_parent = current_ancestor.parent.lock().clone();
|
|
||||||
if let Some(parent) = current_ancestor_parent {
|
|
||||||
current_ancestor = parent;
|
|
||||||
} else {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_spatial_parent(&self, parent: Option<&Arc<Spatial>>) -> Result<()> {
|
|
||||||
let is_ancestor = parent
|
|
||||||
.map(|parent| self.is_ancestor_of(parent.clone()))
|
|
||||||
.unwrap_or(false);
|
|
||||||
if is_ancestor {
|
|
||||||
return Err(anyhow!("Setting spatial parent would cause a loop"));
|
|
||||||
}
|
|
||||||
|
|
||||||
*self.parent.lock() = parent.cloned();
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_spatial_parent_in_place(&self, parent: Option<&Arc<Spatial>>) -> Result<()> {
|
|
||||||
let is_ancestor = parent
|
|
||||||
.map(|parent| self.is_ancestor_of(parent.clone()))
|
|
||||||
.unwrap_or(false);
|
|
||||||
if is_ancestor {
|
|
||||||
return Err(anyhow!("Setting spatial parent would cause a loop"));
|
|
||||||
}
|
|
||||||
|
|
||||||
self.set_local_transform(Spatial::space_to_space_matrix(
|
|
||||||
Some(self),
|
|
||||||
parent.cloned().as_deref(),
|
|
||||||
));
|
|
||||||
*self.parent.lock() = parent.cloned();
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_transform_flex(
|
|
||||||
node: &Node,
|
|
||||||
calling_client: Arc<Client>,
|
|
||||||
data: &[u8],
|
|
||||||
) -> Result<Vec<u8>> {
|
|
||||||
let this_spatial = node
|
|
||||||
.spatial
|
|
||||||
.get()
|
|
||||||
.ok_or_else(|| anyhow!("Node doesn't have a spatial?"))?;
|
|
||||||
let relative_spatial = find_reference_space(&calling_client, deserialize(data)?)?;
|
|
||||||
|
|
||||||
let (scale, rotation, position) = Spatial::space_to_space_matrix(
|
|
||||||
Some(this_spatial.as_ref()),
|
|
||||||
Some(relative_spatial.as_ref()),
|
|
||||||
)
|
|
||||||
.to_scale_rotation_translation();
|
|
||||||
|
|
||||||
serialize((
|
|
||||||
mint::Vector3::from(position),
|
|
||||||
mint::Quaternion::from(rotation),
|
|
||||||
mint::Vector3::from(scale),
|
|
||||||
))
|
|
||||||
.map_err(|e| e.into())
|
|
||||||
}
|
|
||||||
pub fn set_transform_flex(node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct TransformArgs<'a> {
|
|
||||||
reference_space_path: Option<&'a str>,
|
|
||||||
transform: Transform,
|
|
||||||
}
|
|
||||||
let transform_args: TransformArgs = deserialize(data)?;
|
|
||||||
let reference_space_transform = transform_args
|
|
||||||
.reference_space_path
|
|
||||||
.map(|path| find_reference_space(&calling_client, path))
|
|
||||||
.transpose()?;
|
|
||||||
|
|
||||||
node.spatial.get().unwrap().set_local_transform_components(
|
|
||||||
reference_space_transform.as_deref(),
|
|
||||||
transform_args.transform,
|
|
||||||
);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
pub fn set_spatial_parent_flex(
|
|
||||||
node: &Node,
|
|
||||||
calling_client: Arc<Client>,
|
|
||||||
data: &[u8],
|
|
||||||
) -> Result<()> {
|
|
||||||
let parent = find_spatial_parent(&calling_client, deserialize(data)?)?;
|
|
||||||
node.spatial
|
|
||||||
.get()
|
|
||||||
.unwrap()
|
|
||||||
.set_spatial_parent(Some(&parent))
|
|
||||||
}
|
|
||||||
pub fn set_spatial_parent_in_place_flex(
|
|
||||||
node: &Node,
|
|
||||||
calling_client: Arc<Client>,
|
|
||||||
data: &[u8],
|
|
||||||
) -> Result<()> {
|
|
||||||
let parent = find_spatial_parent(&calling_client, deserialize(data)?)?;
|
|
||||||
node.spatial
|
|
||||||
.get()
|
|
||||||
.unwrap()
|
|
||||||
.set_spatial_parent_in_place(Some(&parent))?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn parse_transform(
|
|
||||||
transform: Transform,
|
|
||||||
translation: bool,
|
|
||||||
rotation: bool,
|
|
||||||
scale: bool,
|
|
||||||
) -> Result<Mat4> {
|
|
||||||
let translation = translation
|
|
||||||
.then_some(transform.position)
|
|
||||||
.flatten()
|
|
||||||
.unwrap_or_else(|| Vector3::from([0.0; 3]));
|
|
||||||
let rotation = rotation
|
|
||||||
.then_some(transform.rotation)
|
|
||||||
.flatten()
|
|
||||||
.unwrap_or_else(|| Quat::IDENTITY.into());
|
|
||||||
let scale = scale
|
|
||||||
.then_some(transform.scale)
|
|
||||||
.flatten()
|
|
||||||
.unwrap_or_else(|| Vector3::from([1.0; 3]));
|
|
||||||
|
|
||||||
Ok(Mat4::from_scale_rotation_translation(
|
|
||||||
scale.into(),
|
|
||||||
rotation.into(),
|
|
||||||
translation.into(),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn find_spatial(
|
|
||||||
calling_client: &Arc<Client>,
|
|
||||||
node_name: &'static str,
|
|
||||||
node_path: &str,
|
|
||||||
) -> anyhow::Result<Arc<Spatial>> {
|
|
||||||
Ok(calling_client
|
|
||||||
.get_node(node_name, node_path)?
|
|
||||||
.get_aspect(node_name, "spatial", |n| &n.spatial)?
|
|
||||||
.clone())
|
|
||||||
}
|
|
||||||
pub fn find_spatial_parent(
|
|
||||||
calling_client: &Arc<Client>,
|
|
||||||
node_path: &str,
|
|
||||||
) -> anyhow::Result<Arc<Spatial>> {
|
|
||||||
find_spatial(calling_client, "Spatial parent", node_path)
|
|
||||||
}
|
|
||||||
pub fn find_reference_space(
|
|
||||||
calling_client: &Arc<Client>,
|
|
||||||
node_path: &str,
|
|
||||||
) -> anyhow::Result<Arc<Spatial>> {
|
|
||||||
find_spatial(calling_client, "Reference space", node_path)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn create_interface(client: &Arc<Client>) {
|
|
||||||
let node = Node::create(client, "", "spatial", false);
|
|
||||||
node.add_local_signal("createSpatial", create_spatial_flex);
|
|
||||||
node.add_to_scenegraph();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn create_spatial_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct CreateSpatialInfo<'a> {
|
|
||||||
name: &'a str,
|
|
||||||
parent_path: &'a str,
|
|
||||||
transform: Transform,
|
|
||||||
}
|
|
||||||
let info: CreateSpatialInfo = deserialize(data)?;
|
|
||||||
let node = Node::create(&calling_client, "/spatial/spatial", info.name, true);
|
|
||||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
|
||||||
let transform = parse_transform(info.transform, true, true, true)?;
|
|
||||||
let node = node.add_to_scenegraph();
|
|
||||||
Spatial::add_to(&node, Some(parent), transform)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
528
src/nodes/spatial/mod.rs
Normal file
528
src/nodes/spatial/mod.rs
Normal file
@@ -0,0 +1,528 @@
|
|||||||
|
pub mod zone;
|
||||||
|
|
||||||
|
use self::zone::{create_zone_flex, Zone};
|
||||||
|
use super::{Message, Node};
|
||||||
|
use crate::core::client::Client;
|
||||||
|
use crate::core::registry::Registry;
|
||||||
|
use crate::core::scenegraph::MethodResponseSender;
|
||||||
|
use color_eyre::eyre::{ensure, eyre, Result};
|
||||||
|
use glam::{vec3a, Mat4, Quat};
|
||||||
|
use mint::Vector3;
|
||||||
|
use nanoid::nanoid;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||||
|
use stardust_xr::values::Transform;
|
||||||
|
use std::fmt::Debug;
|
||||||
|
use std::ptr;
|
||||||
|
use std::sync::{Arc, OnceLock, Weak};
|
||||||
|
use stereokit::{bounds_grow_to_fit_box, Bounds};
|
||||||
|
|
||||||
|
static ZONEABLE_REGISTRY: Registry<Spatial> = Registry::new();
|
||||||
|
|
||||||
|
pub struct Spatial {
|
||||||
|
uid: String,
|
||||||
|
pub(super) node: Weak<Node>,
|
||||||
|
self_ref: Weak<Spatial>,
|
||||||
|
parent: Mutex<Option<Arc<Spatial>>>,
|
||||||
|
old_parent: Mutex<Option<Arc<Spatial>>>,
|
||||||
|
pub(super) transform: Mutex<Mat4>,
|
||||||
|
zone: Mutex<Weak<Zone>>,
|
||||||
|
children: Registry<Spatial>,
|
||||||
|
pub(super) bounding_box_calc: OnceLock<fn(&Node) -> Bounds>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Spatial {
|
||||||
|
pub fn new(node: Weak<Node>, parent: Option<Arc<Spatial>>, transform: Mat4) -> Arc<Self> {
|
||||||
|
Arc::new_cyclic(|self_ref| Spatial {
|
||||||
|
uid: nanoid!(),
|
||||||
|
node,
|
||||||
|
self_ref: self_ref.clone(),
|
||||||
|
parent: Mutex::new(parent),
|
||||||
|
old_parent: Mutex::new(None),
|
||||||
|
transform: Mutex::new(transform),
|
||||||
|
zone: Mutex::new(Weak::new()),
|
||||||
|
children: Registry::new(),
|
||||||
|
bounding_box_calc: OnceLock::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
pub fn add_to(
|
||||||
|
node: &Arc<Node>,
|
||||||
|
parent: Option<Arc<Spatial>>,
|
||||||
|
transform: Mat4,
|
||||||
|
zoneable: bool,
|
||||||
|
) -> Result<Arc<Spatial>> {
|
||||||
|
ensure!(
|
||||||
|
node.spatial.get().is_none(),
|
||||||
|
"Internal: Node already has a Spatial aspect!"
|
||||||
|
);
|
||||||
|
let spatial = Spatial::new(Arc::downgrade(node), parent, transform);
|
||||||
|
node.add_local_method("get_bounding_box", Spatial::get_bounding_box_flex);
|
||||||
|
node.add_local_method("get_transform", Spatial::get_transform_flex);
|
||||||
|
node.add_local_signal("set_transform", Spatial::set_transform_flex);
|
||||||
|
node.add_local_signal("set_spatial_parent", Spatial::set_spatial_parent_flex);
|
||||||
|
node.add_local_signal(
|
||||||
|
"set_spatial_parent_in_place",
|
||||||
|
Spatial::set_spatial_parent_in_place_flex,
|
||||||
|
);
|
||||||
|
node.add_local_signal("set_zoneable", Spatial::set_zoneable_flex);
|
||||||
|
node.add_local_method("field_distance", Spatial::field_distance_flex);
|
||||||
|
node.add_local_method("field_normal", Spatial::field_normal_flex);
|
||||||
|
node.add_local_method("field_closest_point", Spatial::field_closest_point_flex);
|
||||||
|
if zoneable {
|
||||||
|
ZONEABLE_REGISTRY.add_raw(&spatial);
|
||||||
|
}
|
||||||
|
let _ = node.spatial.set(spatial.clone());
|
||||||
|
Ok(spatial)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn node(&self) -> Option<Arc<Node>> {
|
||||||
|
self.node.upgrade()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn space_to_space_matrix(from: Option<&Spatial>, to: Option<&Spatial>) -> Mat4 {
|
||||||
|
let space_to_world_matrix = from.map_or(Mat4::IDENTITY, |from| from.global_transform());
|
||||||
|
let world_to_space_matrix = to.map_or(Mat4::IDENTITY, |to| to.global_transform().inverse());
|
||||||
|
world_to_space_matrix * space_to_world_matrix
|
||||||
|
}
|
||||||
|
|
||||||
|
// the output bounds are probably way bigger than they need to be
|
||||||
|
pub fn get_bounding_box(&self) -> Bounds {
|
||||||
|
let Some(node) = self.node() else {return Bounds::default()};
|
||||||
|
let mut bounds = self
|
||||||
|
.bounding_box_calc
|
||||||
|
.get()
|
||||||
|
.map(|b| (b)(&node))
|
||||||
|
.unwrap_or_default();
|
||||||
|
for child in self.children.get_valid_contents() {
|
||||||
|
bounds = bounds_grow_to_fit_box(
|
||||||
|
bounds,
|
||||||
|
child.get_bounding_box(),
|
||||||
|
Some(child.local_transform()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
bounds
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn local_transform(&self) -> Mat4 {
|
||||||
|
*self.transform.lock()
|
||||||
|
}
|
||||||
|
pub fn global_transform(&self) -> Mat4 {
|
||||||
|
match self.get_parent() {
|
||||||
|
Some(value) => value.global_transform() * *self.transform.lock(),
|
||||||
|
None => *self.transform.lock(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn set_local_transform(&self, transform: Mat4) {
|
||||||
|
*self.transform.lock() = transform;
|
||||||
|
}
|
||||||
|
pub fn set_local_transform_components(
|
||||||
|
&self,
|
||||||
|
reference_space: Option<&Spatial>,
|
||||||
|
transform: Transform,
|
||||||
|
) {
|
||||||
|
if reference_space == Some(self) {
|
||||||
|
self.set_local_transform(
|
||||||
|
parse_transform(transform, true, true, true) * self.local_transform(),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let reference_to_parent_transform = reference_space
|
||||||
|
.map(|reference_space| {
|
||||||
|
Spatial::space_to_space_matrix(Some(reference_space), self.get_parent().as_deref())
|
||||||
|
})
|
||||||
|
.unwrap_or(Mat4::IDENTITY);
|
||||||
|
let mut local_transform_in_reference_space =
|
||||||
|
reference_to_parent_transform.inverse() * self.local_transform();
|
||||||
|
let (mut reference_space_scl, mut reference_space_rot, mut reference_space_pos) =
|
||||||
|
local_transform_in_reference_space.to_scale_rotation_translation();
|
||||||
|
|
||||||
|
if let Some(pos) = transform.position {
|
||||||
|
reference_space_pos = pos.into()
|
||||||
|
}
|
||||||
|
if let Some(rot) = transform.rotation {
|
||||||
|
reference_space_rot = rot.into()
|
||||||
|
} else if reference_space_rot.is_nan() {
|
||||||
|
reference_space_rot = Quat::IDENTITY;
|
||||||
|
}
|
||||||
|
if let Some(scl) = transform.scale {
|
||||||
|
reference_space_scl = scl.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
local_transform_in_reference_space = Mat4::from_scale_rotation_translation(
|
||||||
|
reference_space_scl,
|
||||||
|
reference_space_rot,
|
||||||
|
reference_space_pos,
|
||||||
|
);
|
||||||
|
self.set_local_transform(
|
||||||
|
reference_to_parent_transform * local_transform_in_reference_space,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_ancestor_of(&self, spatial: Arc<Spatial>) -> bool {
|
||||||
|
let mut current_ancestor = spatial;
|
||||||
|
loop {
|
||||||
|
if Arc::as_ptr(¤t_ancestor) == ptr::addr_of!(*self) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(parent) = current_ancestor.get_parent() {
|
||||||
|
current_ancestor = parent;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_parent(&self) -> Option<Arc<Spatial>> {
|
||||||
|
self.parent.lock().clone()
|
||||||
|
}
|
||||||
|
fn set_parent(&self, new_parent: Option<Arc<Spatial>>) {
|
||||||
|
if let Some(parent) = self.get_parent() {
|
||||||
|
parent.children.remove(self);
|
||||||
|
}
|
||||||
|
if let Some(new_parent) = &new_parent {
|
||||||
|
new_parent
|
||||||
|
.children
|
||||||
|
.add_raw(&self.self_ref.upgrade().unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
*self.parent.lock() = new_parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_spatial_parent(&self, parent: Option<Arc<Spatial>>) -> Result<()> {
|
||||||
|
let is_ancestor = parent
|
||||||
|
.as_ref()
|
||||||
|
.map(|parent| self.is_ancestor_of(parent.clone()))
|
||||||
|
.unwrap_or(false);
|
||||||
|
if is_ancestor {
|
||||||
|
return Err(eyre!("Setting spatial parent would cause a loop"));
|
||||||
|
}
|
||||||
|
self.set_parent(parent);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_spatial_parent_in_place(&self, parent: Option<Arc<Spatial>>) -> Result<()> {
|
||||||
|
let is_ancestor = parent
|
||||||
|
.as_ref()
|
||||||
|
.map(|parent| self.is_ancestor_of(parent.clone()))
|
||||||
|
.unwrap_or(false);
|
||||||
|
if is_ancestor {
|
||||||
|
return Err(eyre!("Setting spatial parent would cause a loop"));
|
||||||
|
}
|
||||||
|
|
||||||
|
self.set_local_transform(Spatial::space_to_space_matrix(
|
||||||
|
Some(self),
|
||||||
|
parent.as_deref(),
|
||||||
|
));
|
||||||
|
self.set_parent(parent);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_bounding_box_flex(
|
||||||
|
node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
response.wrap_sync(move || {
|
||||||
|
let this_spatial = node
|
||||||
|
.spatial
|
||||||
|
.get()
|
||||||
|
.ok_or_else(|| eyre!("Node doesn't have a spatial?"))?;
|
||||||
|
let relative_spatial_path: Option<&str> = deserialize(message.as_ref())?;
|
||||||
|
let bounds = if let Some(relative_spatial_path) = relative_spatial_path {
|
||||||
|
let relative_spatial =
|
||||||
|
find_reference_space(&calling_client, relative_spatial_path)?;
|
||||||
|
let center =
|
||||||
|
Spatial::space_to_space_matrix(Some(&this_spatial), Some(&relative_spatial))
|
||||||
|
.transform_point3([0.0; 3].into());
|
||||||
|
let bounds: Bounds = Bounds {
|
||||||
|
center,
|
||||||
|
dimensions: [0.0; 3].into(),
|
||||||
|
};
|
||||||
|
bounds_grow_to_fit_box(
|
||||||
|
bounds,
|
||||||
|
this_spatial.get_bounding_box(),
|
||||||
|
Some(Spatial::space_to_space_matrix(
|
||||||
|
Some(&this_spatial),
|
||||||
|
Some(&relative_spatial),
|
||||||
|
)),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
this_spatial.get_bounding_box()
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(serialize((
|
||||||
|
mint::Vector3::from(bounds.center),
|
||||||
|
mint::Vector3::from(bounds.dimensions),
|
||||||
|
))?
|
||||||
|
.into())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_transform_flex(
|
||||||
|
node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
response.wrap_sync(move || {
|
||||||
|
let this_spatial = node
|
||||||
|
.spatial
|
||||||
|
.get()
|
||||||
|
.ok_or_else(|| eyre!("Node doesn't have a spatial?"))?;
|
||||||
|
let relative_spatial =
|
||||||
|
find_reference_space(&calling_client, deserialize(message.as_ref())?)?;
|
||||||
|
|
||||||
|
let (scale, rotation, position) = Spatial::space_to_space_matrix(
|
||||||
|
Some(this_spatial.as_ref()),
|
||||||
|
Some(relative_spatial.as_ref()),
|
||||||
|
)
|
||||||
|
.to_scale_rotation_translation();
|
||||||
|
|
||||||
|
Ok(serialize((
|
||||||
|
mint::Vector3::from(position),
|
||||||
|
mint::Quaternion::from(rotation),
|
||||||
|
mint::Vector3::from(scale),
|
||||||
|
))?
|
||||||
|
.into())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
pub fn set_transform_flex(
|
||||||
|
node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct TransformArgs<'a> {
|
||||||
|
reference_space_path: Option<&'a str>,
|
||||||
|
transform: Transform,
|
||||||
|
}
|
||||||
|
let transform_args: TransformArgs = deserialize(message.as_ref())?;
|
||||||
|
let reference_space_transform = transform_args
|
||||||
|
.reference_space_path
|
||||||
|
.map(|path| find_reference_space(&calling_client, path))
|
||||||
|
.transpose()?;
|
||||||
|
|
||||||
|
node.spatial.get().unwrap().set_local_transform_components(
|
||||||
|
reference_space_transform.as_deref(),
|
||||||
|
transform_args.transform,
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
pub fn set_spatial_parent_flex(
|
||||||
|
node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let parent = find_spatial_parent(&calling_client, deserialize(message.as_ref())?)?;
|
||||||
|
node.spatial.get().unwrap().set_spatial_parent(Some(parent))
|
||||||
|
}
|
||||||
|
pub fn set_spatial_parent_in_place_flex(
|
||||||
|
node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let parent = find_spatial_parent(&calling_client, deserialize(message.as_ref())?)?;
|
||||||
|
node.spatial
|
||||||
|
.get()
|
||||||
|
.unwrap()
|
||||||
|
.set_spatial_parent_in_place(Some(parent))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
pub fn set_zoneable_flex(
|
||||||
|
node: &Node,
|
||||||
|
_calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
let zoneable: bool = deserialize(message.as_ref())?;
|
||||||
|
let spatial = node.spatial.get().unwrap();
|
||||||
|
if zoneable {
|
||||||
|
ZONEABLE_REGISTRY.add_raw(spatial);
|
||||||
|
} else {
|
||||||
|
ZONEABLE_REGISTRY.remove(spatial);
|
||||||
|
zone::release(spatial);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn field_distance_flex(
|
||||||
|
node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
response.wrap_sync(move || {
|
||||||
|
let (point, fields): (Vector3<f32>, Vec<Option<&str>>) = deserialize(message.as_ref())?;
|
||||||
|
let spatial = node.spatial.get().unwrap();
|
||||||
|
|
||||||
|
let output = fields
|
||||||
|
.into_iter()
|
||||||
|
.map(|f| {
|
||||||
|
calling_client
|
||||||
|
.get_node("Field", f?)
|
||||||
|
.ok()?
|
||||||
|
.get_aspect("Field", "field", |n| &n.field)
|
||||||
|
.ok()
|
||||||
|
.cloned()
|
||||||
|
})
|
||||||
|
.map(|f| f.map(|f| f.distance(spatial, point.into())))
|
||||||
|
.collect::<Vec<Option<f32>>>();
|
||||||
|
|
||||||
|
Ok(serialize(output)?.into())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
pub fn field_normal_flex(
|
||||||
|
node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
response.wrap_sync(move || {
|
||||||
|
let (point, fields): (Vector3<f32>, Vec<Option<&str>>) = deserialize(message.as_ref())?;
|
||||||
|
let spatial = node.spatial.get().unwrap();
|
||||||
|
|
||||||
|
let output = fields
|
||||||
|
.into_iter()
|
||||||
|
.map(|f| {
|
||||||
|
calling_client
|
||||||
|
.get_node("Field", f?)
|
||||||
|
.ok()?
|
||||||
|
.get_aspect("Field", "field", |n| &n.field)
|
||||||
|
.ok()
|
||||||
|
.cloned()
|
||||||
|
})
|
||||||
|
.map(|f| f.map(|f| Vector3::from(f.normal(spatial, point.into(), 0.001))))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
Ok(serialize(output)?.into())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
pub fn field_closest_point_flex(
|
||||||
|
node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
response: MethodResponseSender,
|
||||||
|
) {
|
||||||
|
response.wrap_sync(move || {
|
||||||
|
let (point, fields): (Vector3<f32>, Vec<Option<&str>>) = deserialize(message.as_ref())?;
|
||||||
|
let spatial = node.spatial.get().unwrap();
|
||||||
|
|
||||||
|
let output = fields
|
||||||
|
.into_iter()
|
||||||
|
.map(|f| {
|
||||||
|
calling_client
|
||||||
|
.get_node("Field", f?)
|
||||||
|
.ok()?
|
||||||
|
.get_aspect("Field", "field", |n| &n.field)
|
||||||
|
.ok()
|
||||||
|
.cloned()
|
||||||
|
})
|
||||||
|
.map(|f| f.map(|f| Vector3::from(f.closest_point(spatial, point.into(), 0.001))))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
Ok(serialize(output)?.into())
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(self) fn zone_distance(&self) -> f32 {
|
||||||
|
self.zone
|
||||||
|
.lock()
|
||||||
|
.upgrade()
|
||||||
|
.and_then(|zone| zone.field.upgrade())
|
||||||
|
.map(|field| field.distance(self, vec3a(0.0, 0.0, 0.0)))
|
||||||
|
.unwrap_or(f32::MAX)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl PartialEq for Spatial {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.uid == other.uid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Debug for Spatial {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("Spatial")
|
||||||
|
.field("uid", &self.uid)
|
||||||
|
.field("parent", &self.parent)
|
||||||
|
.field("old_parent", &self.old_parent)
|
||||||
|
.field("transform", &self.transform)
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for Spatial {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
ZONEABLE_REGISTRY.remove(self);
|
||||||
|
zone::release(self);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse_transform(transform: Transform, position: bool, rotation: bool, scale: bool) -> Mat4 {
|
||||||
|
let position = position
|
||||||
|
.then_some(transform.position)
|
||||||
|
.flatten()
|
||||||
|
.unwrap_or_else(|| Vector3::from([0.0; 3]));
|
||||||
|
let rotation = rotation
|
||||||
|
.then_some(transform.rotation)
|
||||||
|
.flatten()
|
||||||
|
.unwrap_or_else(|| Quat::IDENTITY.into());
|
||||||
|
let scale = scale
|
||||||
|
.then_some(transform.scale)
|
||||||
|
.flatten()
|
||||||
|
.unwrap_or_else(|| Vector3::from([1.0; 3]));
|
||||||
|
|
||||||
|
Mat4::from_scale_rotation_translation(scale.into(), rotation.into(), position.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn find_spatial(
|
||||||
|
calling_client: &Arc<Client>,
|
||||||
|
node_name: &'static str,
|
||||||
|
node_path: &str,
|
||||||
|
) -> color_eyre::eyre::Result<Arc<Spatial>> {
|
||||||
|
calling_client
|
||||||
|
.get_node(node_name, node_path)?
|
||||||
|
.get_aspect(node_name, "spatial", |n| &n.spatial)
|
||||||
|
.cloned()
|
||||||
|
}
|
||||||
|
pub fn find_spatial_parent(
|
||||||
|
calling_client: &Arc<Client>,
|
||||||
|
node_path: &str,
|
||||||
|
) -> color_eyre::eyre::Result<Arc<Spatial>> {
|
||||||
|
find_spatial(calling_client, "Spatial parent", node_path)
|
||||||
|
}
|
||||||
|
pub fn find_reference_space(
|
||||||
|
calling_client: &Arc<Client>,
|
||||||
|
node_path: &str,
|
||||||
|
) -> color_eyre::eyre::Result<Arc<Spatial>> {
|
||||||
|
find_spatial(calling_client, "Reference space", node_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_interface(client: &Arc<Client>) -> Result<()> {
|
||||||
|
let node = Node::create(client, "", "spatial", false);
|
||||||
|
node.add_local_signal("create_spatial", create_spatial_flex);
|
||||||
|
node.add_local_signal("create_zone", create_zone_flex);
|
||||||
|
node.add_to_scenegraph().map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_spatial_flex(
|
||||||
|
_node: &Node,
|
||||||
|
calling_client: Arc<Client>,
|
||||||
|
message: Message,
|
||||||
|
) -> Result<()> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct CreateSpatialInfo<'a> {
|
||||||
|
name: &'a str,
|
||||||
|
parent_path: &'a str,
|
||||||
|
transform: Transform,
|
||||||
|
zoneable: bool,
|
||||||
|
}
|
||||||
|
let info: CreateSpatialInfo = deserialize(message.as_ref())?;
|
||||||
|
let node = Node::create(&calling_client, "/spatial/spatial", info.name, true);
|
||||||
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
|
let transform = parse_transform(info.transform, true, true, true);
|
||||||
|
let node = node.add_to_scenegraph()?;
|
||||||
|
Spatial::add_to(&node, Some(parent), transform, info.zoneable)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
171
src/nodes/spatial/zone.rs
Normal file
171
src/nodes/spatial/zone.rs
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
use super::{find_spatial, Spatial, ZONEABLE_REGISTRY};
|
||||||
|
use crate::{
|
||||||
|
core::{client::Client, registry::Registry},
|
||||||
|
nodes::{
|
||||||
|
alias::{Alias, AliasInfo},
|
||||||
|
fields::{find_field, Field},
|
||||||
|
spatial::{find_spatial_parent, parse_transform},
|
||||||
|
Message, Node,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use color_eyre::eyre::Result;
|
||||||
|
use glam::vec3a;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use rustc_hash::FxHashMap;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use stardust_xr::{
|
||||||
|
schemas::flex::{deserialize, serialize},
|
||||||
|
values::Transform,
|
||||||
|
};
|
||||||
|
use std::sync::{Arc, Weak};
|
||||||
|
|
||||||
|
pub fn capture(spatial: &Arc<Spatial>, zone: &Arc<Zone>) {
|
||||||
|
let old_distance = spatial.zone_distance();
|
||||||
|
let new_distance = zone
|
||||||
|
.field
|
||||||
|
.upgrade()
|
||||||
|
.map(|field| field.distance(spatial, vec3a(0.0, 0.0, 0.0)))
|
||||||
|
.unwrap_or(f32::MAX);
|
||||||
|
if new_distance.abs() < old_distance.abs() {
|
||||||
|
release(spatial);
|
||||||
|
*spatial.old_parent.lock() = spatial.get_parent();
|
||||||
|
*spatial.zone.lock() = Arc::downgrade(zone);
|
||||||
|
zone.captured.add_raw(spatial);
|
||||||
|
let Some(node) = zone.spatial.node.upgrade() else {return};
|
||||||
|
let Ok(message) = serialize(&spatial.uid) else {return};
|
||||||
|
let _ = node.send_remote_signal("capture", message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn release(spatial: &Spatial) {
|
||||||
|
let _ = spatial.set_spatial_parent_in_place(spatial.old_parent.lock().take());
|
||||||
|
let mut spatial_zone = spatial.zone.lock();
|
||||||
|
if let Some(spatial_zone) = spatial_zone.upgrade() {
|
||||||
|
let Some(node) = spatial_zone.spatial.node.upgrade() else {return};
|
||||||
|
spatial_zone.captured.remove(spatial);
|
||||||
|
let Ok(message) = serialize(&spatial.uid) else {return};
|
||||||
|
let _ = node.send_remote_signal("release", message);
|
||||||
|
}
|
||||||
|
*spatial_zone = Weak::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Zone {
|
||||||
|
spatial: Arc<Spatial>,
|
||||||
|
pub field: Weak<Field>,
|
||||||
|
zoneables: Mutex<FxHashMap<String, Arc<Node>>>,
|
||||||
|
captured: Registry<Spatial>,
|
||||||
|
}
|
||||||
|
impl Zone {
|
||||||
|
pub fn add_to(node: &Arc<Node>, spatial: Arc<Spatial>, field: &Arc<Field>) -> Arc<Zone> {
|
||||||
|
let zone = Arc::new(Zone {
|
||||||
|
spatial,
|
||||||
|
field: Arc::downgrade(field),
|
||||||
|
zoneables: Mutex::new(FxHashMap::default()),
|
||||||
|
captured: Registry::new(),
|
||||||
|
});
|
||||||
|
node.add_local_signal("capture", Zone::capture_flex);
|
||||||
|
node.add_local_signal("release", Zone::release_flex);
|
||||||
|
node.add_local_signal("update", Zone::update);
|
||||||
|
let _ = node.zone.set(zone.clone());
|
||||||
|
zone
|
||||||
|
}
|
||||||
|
fn capture_flex(node: &Node, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
|
let zone = node.zone.get().unwrap();
|
||||||
|
let capture_path: &str = deserialize(message.as_ref())?;
|
||||||
|
let spatial = find_spatial(&calling_client, "Spatial", capture_path)?;
|
||||||
|
capture(&spatial, zone);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn release_flex(_node: &Node, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
|
let capture_path: &str = deserialize(message.as_ref())?;
|
||||||
|
let spatial = find_spatial(&calling_client, "Spatial", capture_path)?;
|
||||||
|
release(&spatial);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn update(node: &Node, _calling_client: Arc<Client>, _message: Message) -> Result<()> {
|
||||||
|
let zone = node.zone.get().unwrap();
|
||||||
|
let Some(field) = zone.field.upgrade() else { return Err(color_eyre::eyre::eyre!("Zone's field has been destroyed")) };
|
||||||
|
let Some((zone_client, zone_node)) = zone
|
||||||
|
.spatial
|
||||||
|
.node
|
||||||
|
.upgrade()
|
||||||
|
.and_then(|n| n.get_client().zip(Some(n))) else { return Err(color_eyre::eyre::eyre!("No client on node?")) };
|
||||||
|
let mut old_zoneables = zone.zoneables.lock();
|
||||||
|
for (_uid, zoneable) in old_zoneables.iter() {
|
||||||
|
zoneable.destroy();
|
||||||
|
}
|
||||||
|
let captured = zone.captured.get_valid_contents();
|
||||||
|
let zoneables = ZONEABLE_REGISTRY
|
||||||
|
.get_valid_contents()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|zoneable| zoneable.node.upgrade().is_some())
|
||||||
|
.filter(|zoneable| {
|
||||||
|
if captured
|
||||||
|
.iter()
|
||||||
|
.any(|captured| Arc::ptr_eq(captured, zoneable))
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let spatial_zone_distance = zoneable.zone_distance();
|
||||||
|
let self_zone_distance = field.distance(zoneable, vec3a(0.0, 0.0, 0.0));
|
||||||
|
self_zone_distance < 0.0 && spatial_zone_distance > self_zone_distance
|
||||||
|
})
|
||||||
|
.filter_map(|zoneable| {
|
||||||
|
let alias = Alias::create(
|
||||||
|
&zone_client,
|
||||||
|
zone_node.get_path(),
|
||||||
|
&zoneable.uid,
|
||||||
|
&zoneable.node.upgrade().unwrap(),
|
||||||
|
AliasInfo {
|
||||||
|
server_signals: vec![
|
||||||
|
"set_transform",
|
||||||
|
"set_spatial_parent",
|
||||||
|
"set_spatial_parent_in_place",
|
||||||
|
],
|
||||||
|
server_methods: vec!["get_bounds", "get_transform"],
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.ok()?;
|
||||||
|
Some((zoneable.uid.clone(), alias))
|
||||||
|
})
|
||||||
|
.collect::<FxHashMap<String, Arc<Node>>>();
|
||||||
|
|
||||||
|
for entered_uid in zoneables.keys().filter(|k| !old_zoneables.contains_key(*k)) {
|
||||||
|
node.send_remote_signal("enter", serialize(entered_uid)?)?;
|
||||||
|
}
|
||||||
|
for left_uid in old_zoneables.keys().filter(|k| !zoneables.contains_key(*k)) {
|
||||||
|
node.send_remote_signal("leave", serialize(left_uid)?)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
*old_zoneables = zoneables;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for Zone {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
for captured in self.captured.get_valid_contents() {
|
||||||
|
release(&captured);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_zone_flex(_node: &Node, calling_client: Arc<Client>, message: Message) -> Result<()> {
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
struct CreateZoneInfo<'a> {
|
||||||
|
name: &'a str,
|
||||||
|
parent_path: &'a str,
|
||||||
|
transform: Transform,
|
||||||
|
field_path: &'a str,
|
||||||
|
}
|
||||||
|
let info: CreateZoneInfo = deserialize(message.as_ref())?;
|
||||||
|
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||||
|
let transform = parse_transform(info.transform, true, true, false);
|
||||||
|
let field = find_field(&calling_client, info.field_path)?;
|
||||||
|
|
||||||
|
let node =
|
||||||
|
Node::create(&calling_client, "/spatial/zone", info.name, true).add_to_scenegraph()?;
|
||||||
|
let space = Spatial::add_to(&node, Some(parent), transform, false)?;
|
||||||
|
Zone::add_to(&node, space, &field);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
use crate::core::client::Client;
|
|
||||||
|
|
||||||
use super::Node;
|
|
||||||
use anyhow::{anyhow, Result};
|
|
||||||
use glam::Mat4;
|
|
||||||
use parking_lot::Mutex;
|
|
||||||
use rustc_hash::FxHashMap;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
lazy_static::lazy_static! {
|
|
||||||
pub static ref DESKTOP_STARTUP_IDS: Mutex<FxHashMap<String, StartupSettings>> = Default::default();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default, Clone)]
|
|
||||||
pub struct StartupSettings {
|
|
||||||
pub transform: Mat4,
|
|
||||||
}
|
|
||||||
impl StartupSettings {
|
|
||||||
pub fn add_to(node: &Arc<Node>) {
|
|
||||||
node.startup_settings
|
|
||||||
.set(Mutex::new(StartupSettings::default()))
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_root_flex(node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
|
||||||
let startup_id = flexbuffers::Reader::get_root(data)?.get_str()?;
|
|
||||||
let spatial_node = calling_client
|
|
||||||
.scenegraph
|
|
||||||
.get_node(startup_id)
|
|
||||||
.ok_or_else(|| anyhow!("Root spatial node does not exist"))?;
|
|
||||||
let spatial = spatial_node
|
|
||||||
.spatial
|
|
||||||
.get()
|
|
||||||
.ok_or_else(|| anyhow!("Root spatial node is not a spatial"))?;
|
|
||||||
node.startup_settings.get().unwrap().lock().transform = spatial.global_transform();
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn generate_desktop_startup_id_flex(
|
|
||||||
node: &Node,
|
|
||||||
_calling_client: Arc<Client>,
|
|
||||||
_data: &[u8],
|
|
||||||
) -> Result<Vec<u8>> {
|
|
||||||
let id = nanoid::nanoid!();
|
|
||||||
let data = flexbuffers::singleton(id.as_str());
|
|
||||||
DESKTOP_STARTUP_IDS
|
|
||||||
.lock()
|
|
||||||
.insert(id, node.startup_settings.get().unwrap().lock().clone());
|
|
||||||
Ok(data)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn create_interface(client: &Arc<Client>) {
|
|
||||||
let node = Node::create(client, "", "startup", false);
|
|
||||||
node.add_local_signal("createStartupSettings", create_startup_settings_flex);
|
|
||||||
node.add_to_scenegraph();
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn create_startup_settings_flex(
|
|
||||||
_node: &Node,
|
|
||||||
calling_client: Arc<Client>,
|
|
||||||
data: &[u8],
|
|
||||||
) -> Result<()> {
|
|
||||||
let name = flexbuffers::Reader::get_root(data)?.get_str()?;
|
|
||||||
let node = Node::create(&calling_client, "/startup/settings", name, true).add_to_scenegraph();
|
|
||||||
StartupSettings::add_to(&node);
|
|
||||||
|
|
||||||
node.add_local_signal("setRoot", StartupSettings::set_root_flex);
|
|
||||||
node.add_local_method(
|
|
||||||
"generateDesktopStartupID",
|
|
||||||
StartupSettings::generate_desktop_startup_id_flex,
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
BIN
src/objects/input/cursor.blend
Normal file
BIN
src/objects/input/cursor.blend
Normal file
Binary file not shown.
BIN
src/objects/input/cursor.glb
Normal file
BIN
src/objects/input/cursor.glb
Normal file
Binary file not shown.
54
src/objects/input/eye_pointer.rs
Normal file
54
src/objects/input/eye_pointer.rs
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
use crate::{
|
||||||
|
core::client::INTERNAL_CLIENT,
|
||||||
|
nodes::{
|
||||||
|
input::{pointer::Pointer, InputMethod, InputType},
|
||||||
|
spatial::Spatial,
|
||||||
|
Node,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use color_eyre::eyre::Result;
|
||||||
|
use glam::Mat4;
|
||||||
|
use nanoid::nanoid;
|
||||||
|
use serde::Serialize;
|
||||||
|
use stardust_xr::schemas::{flat::Datamap, flex::flexbuffers};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use stereokit::StereoKitMultiThread;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct KeyboardEvent {
|
||||||
|
pub keyboard: String,
|
||||||
|
pub keymap: Option<String>,
|
||||||
|
pub keys_up: Option<Vec<u32>>,
|
||||||
|
pub keys_down: Option<Vec<u32>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct EyePointer {
|
||||||
|
spatial: Arc<Spatial>,
|
||||||
|
pointer: Arc<InputMethod>,
|
||||||
|
}
|
||||||
|
impl EyePointer {
|
||||||
|
pub fn new() -> Result<Self> {
|
||||||
|
let node = Node::create(&INTERNAL_CLIENT, "", &nanoid!(), false).add_to_scenegraph()?;
|
||||||
|
let spatial = Spatial::add_to(&node, None, Mat4::IDENTITY, false).unwrap();
|
||||||
|
let pointer =
|
||||||
|
InputMethod::add_to(&node, InputType::Pointer(Pointer::default()), None).unwrap();
|
||||||
|
|
||||||
|
Ok(EyePointer { spatial, pointer })
|
||||||
|
}
|
||||||
|
pub fn update(&self, sk: &impl StereoKitMultiThread) {
|
||||||
|
let ray = sk.input_eyes();
|
||||||
|
self.spatial
|
||||||
|
.set_local_transform(Mat4::from_rotation_translation(
|
||||||
|
ray.orientation,
|
||||||
|
ray.position,
|
||||||
|
));
|
||||||
|
{
|
||||||
|
// Set pointer input datamap
|
||||||
|
let mut fbb = flexbuffers::Builder::default();
|
||||||
|
let mut map = fbb.start_map();
|
||||||
|
map.push("eye", 2);
|
||||||
|
map.end_map();
|
||||||
|
*self.pointer.datamap.lock() = Datamap::new(fbb.take_buffer()).ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
pub mod eye_pointer;
|
||||||
pub mod mouse_pointer;
|
pub mod mouse_pointer;
|
||||||
pub mod sk_controller;
|
pub mod sk_controller;
|
||||||
pub mod sk_hand;
|
pub mod sk_hand;
|
||||||
|
|||||||
@@ -1,59 +1,261 @@
|
|||||||
use crate::nodes::{
|
use crate::{
|
||||||
input::{pointer::Pointer, InputMethod, InputType},
|
core::{client::INTERNAL_CLIENT, typed_datamap::TypedDatamap},
|
||||||
spatial::Spatial,
|
nodes::{
|
||||||
};
|
data::{mask_matches, Mask, PulseSender, KEYMAPS, PULSE_RECEIVER_REGISTRY},
|
||||||
use glam::{vec3, Mat4};
|
fields::Ray,
|
||||||
use stardust_xr::{schemas::flat::Datamap, values::Transform};
|
input::{pointer::Pointer, InputMethod, InputType},
|
||||||
use std::sync::{Arc, Weak};
|
spatial::Spatial,
|
||||||
use stereokit::{
|
Node,
|
||||||
input::{ButtonState, Key, Ray},
|
},
|
||||||
StereoKit,
|
|
||||||
};
|
};
|
||||||
|
use color_eyre::eyre::Result;
|
||||||
|
use glam::{vec2, vec3, Mat4, Vec2, Vec3};
|
||||||
|
use nanoid::nanoid;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::{convert::TryFrom, sync::Arc};
|
||||||
|
use stereokit::{ray_from_mouse, ButtonState, Key, StereoKitMultiThread};
|
||||||
|
use xkbcommon::xkb::{Context, Keymap, FORMAT_TEXT_V1};
|
||||||
|
|
||||||
|
#[derive(Default, Deserialize, Serialize)]
|
||||||
|
struct MouseEvent {
|
||||||
|
select: f32,
|
||||||
|
grab: f32,
|
||||||
|
scroll_continuous: Vec2,
|
||||||
|
scroll_discrete: Vec2,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||||
|
pub struct KeyboardEvent {
|
||||||
|
pub keyboard: (),
|
||||||
|
pub xkbv1: (),
|
||||||
|
pub keymap_id: String,
|
||||||
|
pub keys: Vec<i32>,
|
||||||
|
}
|
||||||
|
impl Default for KeyboardEvent {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
keyboard: (),
|
||||||
|
xkbv1: (),
|
||||||
|
keymap_id: "flatscreen".to_string(),
|
||||||
|
keys: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct MousePointer {
|
pub struct MousePointer {
|
||||||
|
node: Arc<Node>,
|
||||||
|
spatial: Arc<Spatial>,
|
||||||
pointer: Arc<InputMethod>,
|
pointer: Arc<InputMethod>,
|
||||||
|
mouse_datamap: TypedDatamap<MouseEvent>,
|
||||||
|
keyboard_datamap: TypedDatamap<KeyboardEvent>,
|
||||||
|
keyboard_sender: Arc<PulseSender>,
|
||||||
}
|
}
|
||||||
impl MousePointer {
|
impl MousePointer {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Result<Self> {
|
||||||
MousePointer {
|
let node = Node::create(&INTERNAL_CLIENT, "", &nanoid!(), false).add_to_scenegraph()?;
|
||||||
pointer: InputMethod::new(
|
let spatial = Spatial::add_to(&node, None, Mat4::IDENTITY, false).unwrap();
|
||||||
Spatial::new(Weak::new(), None, Mat4::IDENTITY),
|
let pointer =
|
||||||
InputType::Pointer(Pointer::default()),
|
InputMethod::add_to(&node, InputType::Pointer(Pointer::default()), None).unwrap();
|
||||||
),
|
|
||||||
}
|
KEYMAPS.lock().insert(
|
||||||
|
"flatscreen".to_string(),
|
||||||
|
Keymap::new_from_names(&Context::new(0), "evdev", "", "", "", None, 0)
|
||||||
|
.unwrap()
|
||||||
|
.get_as_string(FORMAT_TEXT_V1),
|
||||||
|
);
|
||||||
|
|
||||||
|
let keyboard_sender =
|
||||||
|
PulseSender::add_to(&node, Mask::from_struct::<KeyboardEvent>()).unwrap();
|
||||||
|
|
||||||
|
Ok(MousePointer {
|
||||||
|
node,
|
||||||
|
spatial,
|
||||||
|
pointer,
|
||||||
|
mouse_datamap: Default::default(),
|
||||||
|
keyboard_datamap: Default::default(),
|
||||||
|
keyboard_sender,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
pub fn update(&self, sk: &StereoKit) {
|
pub fn update(&mut self, sk: &impl StereoKitMultiThread) {
|
||||||
if let Some(ray) = Ray::from_mouse(sk.input_mouse()) {
|
let mouse = sk.input_mouse();
|
||||||
self.pointer.spatial.set_local_transform_components(
|
|
||||||
None,
|
let ray = ray_from_mouse(mouse.pos).unwrap();
|
||||||
Transform {
|
self.spatial.set_local_transform(
|
||||||
position: Some(ray.pos),
|
Mat4::look_to_rh(
|
||||||
rotation: Some(
|
Vec3::from(ray.pos),
|
||||||
glam::Quat::from_rotation_arc(vec3(0.0, 0.0, 1.0), ray.dir.into()).into(),
|
Vec3::from(ray.dir),
|
||||||
),
|
vec3(0.0, 1.0, 0.0),
|
||||||
scale: None,
|
)
|
||||||
},
|
.inverse(),
|
||||||
);
|
);
|
||||||
|
{
|
||||||
|
// Set pointer input datamap
|
||||||
|
self.mouse_datamap.select =
|
||||||
|
if sk.input_key(Key::MouseLeft).contains(ButtonState::ACTIVE) {
|
||||||
|
1.0f32
|
||||||
|
} else {
|
||||||
|
0.0f32
|
||||||
|
};
|
||||||
|
self.mouse_datamap.grab = if sk.input_key(Key::MouseRight).contains(ButtonState::ACTIVE)
|
||||||
|
{
|
||||||
|
1.0f32
|
||||||
|
} else {
|
||||||
|
0.0f32
|
||||||
|
};
|
||||||
|
self.mouse_datamap.scroll_continuous = vec2(0.0, mouse.scroll_change / 120.0);
|
||||||
|
self.mouse_datamap.scroll_discrete = vec2(0.0, mouse.scroll_change / 120.0);
|
||||||
|
*self.pointer.datamap.lock() = self.mouse_datamap.to_datamap().ok();
|
||||||
|
}
|
||||||
|
self.send_keyboard_input(sk);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_keyboard_input(&mut self, sk: &impl StereoKitMultiThread) {
|
||||||
|
let rx = PULSE_RECEIVER_REGISTRY
|
||||||
|
.get_valid_contents()
|
||||||
|
.into_iter()
|
||||||
|
.filter(|rx| mask_matches(&rx.mask, &self.keyboard_sender.mask))
|
||||||
|
.map(|rx| {
|
||||||
|
let result = rx.field.ray_march(Ray {
|
||||||
|
origin: vec3(0.0, 0.0, 0.0),
|
||||||
|
direction: vec3(0.0, 0.0, -1.0),
|
||||||
|
space: self.spatial.clone(),
|
||||||
|
});
|
||||||
|
(rx, result)
|
||||||
|
})
|
||||||
|
.filter(|(_rx, result)| {
|
||||||
|
result.deepest_point_distance > 0.0 && result.min_distance < 0.05
|
||||||
|
})
|
||||||
|
.reduce(|(rx_a, result_a), (rx_b, result_b)| {
|
||||||
|
if result_a.deepest_point_distance < result_b.deepest_point_distance {
|
||||||
|
(rx_a, result_a)
|
||||||
|
} else {
|
||||||
|
(rx_b, result_b)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.map(|(rx, _)| rx);
|
||||||
|
|
||||||
|
if let Some(rx) = rx {
|
||||||
|
let keys = (8_u32..254)
|
||||||
|
.filter_map(|i| Key::try_from(i).ok())
|
||||||
|
.filter_map(|k| Some((map_key(k)?, sk.input_key(k))))
|
||||||
|
.filter_map(|(i, k)| {
|
||||||
|
if k.contains(ButtonState::JUST_ACTIVE) {
|
||||||
|
Some(i as i32)
|
||||||
|
} else if k.contains(ButtonState::JUST_INACTIVE) {
|
||||||
|
Some(-(i as i32))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
self.keyboard_datamap.keys = keys;
|
||||||
|
if !self.keyboard_datamap.keys.is_empty() {
|
||||||
|
rx.send_data(&self.node.uid, self.keyboard_datamap.serialize().unwrap())
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let mut fbb = flexbuffers::Builder::default();
|
}
|
||||||
let mut map = fbb.start_map();
|
}
|
||||||
map.push(
|
|
||||||
"select",
|
fn map_key(key: Key) -> Option<u32> {
|
||||||
if sk.input_key(Key::MouseLeft).contains(ButtonState::Active) {
|
match key {
|
||||||
1.0f32
|
Key::Backspace => Some(input_event_codes::KEY_BACKSPACE!()),
|
||||||
} else {
|
Key::Tab => Some(input_event_codes::KEY_TAB!()),
|
||||||
0.0f32
|
Key::Return => Some(input_event_codes::KEY_ENTER!()),
|
||||||
},
|
Key::Shift => Some(input_event_codes::KEY_LEFTSHIFT!()),
|
||||||
);
|
Key::Ctrl => Some(input_event_codes::KEY_LEFTCTRL!()),
|
||||||
map.push(
|
Key::Alt => Some(input_event_codes::KEY_LEFTALT!()),
|
||||||
"grab",
|
Key::CapsLock => Some(input_event_codes::KEY_CAPSLOCK!()),
|
||||||
if sk.input_key(Key::MouseRight).contains(ButtonState::Active) {
|
Key::Esc => Some(input_event_codes::KEY_ESC!()),
|
||||||
1.0f32
|
Key::Space => Some(input_event_codes::KEY_SPACE!()),
|
||||||
} else {
|
Key::End => Some(input_event_codes::KEY_END!()),
|
||||||
0.0f32
|
Key::Home => Some(input_event_codes::KEY_HOME!()),
|
||||||
},
|
Key::Left => Some(input_event_codes::KEY_LEFT!()),
|
||||||
);
|
Key::Right => Some(input_event_codes::KEY_RIGHT!()),
|
||||||
map.end_map();
|
Key::Up => Some(input_event_codes::KEY_UP!()),
|
||||||
*self.pointer.datamap.lock() = Datamap::new(fbb.take_buffer()).ok();
|
Key::Down => Some(input_event_codes::KEY_DOWN!()),
|
||||||
|
Key::PageUp => Some(input_event_codes::KEY_PAGEUP!()),
|
||||||
|
Key::PageDown => Some(input_event_codes::KEY_PAGEDOWN!()),
|
||||||
|
Key::PrintScreen => Some(input_event_codes::KEY_PRINT!()),
|
||||||
|
Key::KeyInsert => Some(input_event_codes::KEY_INSERT!()),
|
||||||
|
Key::Del => Some(input_event_codes::KEY_DELETE!()),
|
||||||
|
Key::Key0 => Some(input_event_codes::KEY_0!()),
|
||||||
|
Key::Key1 => Some(input_event_codes::KEY_1!()),
|
||||||
|
Key::Key2 => Some(input_event_codes::KEY_2!()),
|
||||||
|
Key::Key3 => Some(input_event_codes::KEY_3!()),
|
||||||
|
Key::Key4 => Some(input_event_codes::KEY_4!()),
|
||||||
|
Key::Key5 => Some(input_event_codes::KEY_5!()),
|
||||||
|
Key::Key6 => Some(input_event_codes::KEY_6!()),
|
||||||
|
Key::Key7 => Some(input_event_codes::KEY_7!()),
|
||||||
|
Key::Key8 => Some(input_event_codes::KEY_8!()),
|
||||||
|
Key::Key9 => Some(input_event_codes::KEY_9!()),
|
||||||
|
Key::A => Some(input_event_codes::KEY_A!()),
|
||||||
|
Key::B => Some(input_event_codes::KEY_B!()),
|
||||||
|
Key::C => Some(input_event_codes::KEY_C!()),
|
||||||
|
Key::D => Some(input_event_codes::KEY_D!()),
|
||||||
|
Key::E => Some(input_event_codes::KEY_E!()),
|
||||||
|
Key::F => Some(input_event_codes::KEY_F!()),
|
||||||
|
Key::G => Some(input_event_codes::KEY_G!()),
|
||||||
|
Key::H => Some(input_event_codes::KEY_H!()),
|
||||||
|
Key::I => Some(input_event_codes::KEY_I!()),
|
||||||
|
Key::J => Some(input_event_codes::KEY_J!()),
|
||||||
|
Key::K => Some(input_event_codes::KEY_K!()),
|
||||||
|
Key::L => Some(input_event_codes::KEY_L!()),
|
||||||
|
Key::M => Some(input_event_codes::KEY_M!()),
|
||||||
|
Key::N => Some(input_event_codes::KEY_N!()),
|
||||||
|
Key::O => Some(input_event_codes::KEY_O!()),
|
||||||
|
Key::P => Some(input_event_codes::KEY_P!()),
|
||||||
|
Key::Q => Some(input_event_codes::KEY_Q!()),
|
||||||
|
Key::R => Some(input_event_codes::KEY_R!()),
|
||||||
|
Key::S => Some(input_event_codes::KEY_S!()),
|
||||||
|
Key::T => Some(input_event_codes::KEY_T!()),
|
||||||
|
Key::U => Some(input_event_codes::KEY_U!()),
|
||||||
|
Key::V => Some(input_event_codes::KEY_V!()),
|
||||||
|
Key::W => Some(input_event_codes::KEY_W!()),
|
||||||
|
Key::X => Some(input_event_codes::KEY_X!()),
|
||||||
|
Key::Y => Some(input_event_codes::KEY_Y!()),
|
||||||
|
Key::Z => Some(input_event_codes::KEY_Z!()),
|
||||||
|
Key::Numpad0 => Some(input_event_codes::KEY_NUMERIC_0!()),
|
||||||
|
Key::Numpad1 => Some(input_event_codes::KEY_NUMERIC_1!()),
|
||||||
|
Key::Numpad2 => Some(input_event_codes::KEY_NUMERIC_2!()),
|
||||||
|
Key::Numpad3 => Some(input_event_codes::KEY_NUMERIC_3!()),
|
||||||
|
Key::Numpad4 => Some(input_event_codes::KEY_NUMERIC_4!()),
|
||||||
|
Key::Numpad5 => Some(input_event_codes::KEY_NUMERIC_5!()),
|
||||||
|
Key::Numpad6 => Some(input_event_codes::KEY_NUMERIC_6!()),
|
||||||
|
Key::Numpad7 => Some(input_event_codes::KEY_NUMERIC_7!()),
|
||||||
|
Key::Numpad8 => Some(input_event_codes::KEY_NUMERIC_8!()),
|
||||||
|
Key::Numpad9 => Some(input_event_codes::KEY_NUMERIC_9!()),
|
||||||
|
Key::F1 => Some(input_event_codes::KEY_F1!()),
|
||||||
|
Key::F2 => Some(input_event_codes::KEY_F2!()),
|
||||||
|
Key::F3 => Some(input_event_codes::KEY_F3!()),
|
||||||
|
Key::F4 => Some(input_event_codes::KEY_F4!()),
|
||||||
|
Key::F5 => Some(input_event_codes::KEY_F5!()),
|
||||||
|
Key::F6 => Some(input_event_codes::KEY_F6!()),
|
||||||
|
Key::F7 => Some(input_event_codes::KEY_F7!()),
|
||||||
|
Key::F8 => Some(input_event_codes::KEY_F8!()),
|
||||||
|
Key::F9 => Some(input_event_codes::KEY_F9!()),
|
||||||
|
Key::F10 => Some(input_event_codes::KEY_F10!()),
|
||||||
|
Key::F11 => Some(input_event_codes::KEY_F11!()),
|
||||||
|
Key::F12 => Some(input_event_codes::KEY_F12!()),
|
||||||
|
Key::Comma => Some(input_event_codes::KEY_COMMA!()),
|
||||||
|
Key::Period => Some(input_event_codes::KEY_DOT!()),
|
||||||
|
Key::SlashFwd => Some(input_event_codes::KEY_SLASH!()),
|
||||||
|
Key::SlashBack => Some(input_event_codes::KEY_BACKSLASH!()),
|
||||||
|
Key::Semicolon => Some(input_event_codes::KEY_SEMICOLON!()),
|
||||||
|
Key::Apostrophe => Some(input_event_codes::KEY_APOSTROPHE!()),
|
||||||
|
Key::BracketOpen => Some(input_event_codes::KEY_LEFTBRACE!()),
|
||||||
|
Key::BracketClose => Some(input_event_codes::KEY_RIGHTBRACE!()),
|
||||||
|
Key::Minus => Some(input_event_codes::KEY_MINUS!()),
|
||||||
|
Key::Equals => Some(input_event_codes::KEY_EQUAL!()),
|
||||||
|
Key::Backtick => None,
|
||||||
|
Key::LCmd => Some(input_event_codes::KEY_LEFTMETA!()),
|
||||||
|
Key::RCmd => Some(input_event_codes::KEY_RIGHTMETA!()),
|
||||||
|
Key::Multiply => Some(input_event_codes::KEY_NUMERIC_STAR!()),
|
||||||
|
Key::Add => Some(input_event_codes::KEY_KPPLUS!()),
|
||||||
|
Key::Subtract => Some(input_event_codes::KEY_MINUS!()),
|
||||||
|
Key::Decimal => Some(input_event_codes::KEY_DOT!()),
|
||||||
|
Key::Divide => Some(input_event_codes::KEY_SLASH!()),
|
||||||
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,47 +1,78 @@
|
|||||||
use crate::nodes::{
|
use crate::{
|
||||||
input::{tip::Tip, InputMethod, InputType},
|
core::{client::INTERNAL_CLIENT, typed_datamap::TypedDatamap},
|
||||||
spatial::Spatial,
|
nodes::{
|
||||||
|
input::{tip::Tip, InputMethod, InputType},
|
||||||
|
spatial::Spatial,
|
||||||
|
Node,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
use glam::Mat4;
|
use color_eyre::eyre::Result;
|
||||||
use stardust_xr::{schemas::flat::Datamap, values::Transform};
|
use glam::{Mat4, Vec2, Vec3};
|
||||||
use std::sync::{Arc, Weak};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::sync::Arc;
|
||||||
use stereokit::{
|
use stereokit::{
|
||||||
input::{ButtonState, Handed},
|
named_colors::WHITE, ButtonState, Handed, Model, RenderLayer, StereoKitDraw,
|
||||||
StereoKit,
|
StereoKitMultiThread,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[derive(Default, Deserialize, Serialize)]
|
||||||
|
struct ControllerDatamap {
|
||||||
|
select: f32,
|
||||||
|
grab: f32,
|
||||||
|
scroll: Vec2,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct SkController {
|
pub struct SkController {
|
||||||
tip: Arc<InputMethod>,
|
_node: Arc<Node>,
|
||||||
|
input: Arc<InputMethod>,
|
||||||
|
model: Model,
|
||||||
handed: Handed,
|
handed: Handed,
|
||||||
|
datamap: TypedDatamap<ControllerDatamap>,
|
||||||
}
|
}
|
||||||
impl SkController {
|
impl SkController {
|
||||||
pub fn new(handed: Handed) -> Self {
|
pub fn new(sk: &impl StereoKitMultiThread, handed: Handed) -> Result<Self> {
|
||||||
SkController {
|
let _node = Node::create(
|
||||||
tip: InputMethod::new(
|
&INTERNAL_CLIENT,
|
||||||
Spatial::new(Weak::new(), None, Mat4::IDENTITY),
|
"",
|
||||||
InputType::Tip(Tip::default()),
|
if handed == Handed::Left {
|
||||||
),
|
"controller_left"
|
||||||
|
} else {
|
||||||
|
"controller_right"
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
.add_to_scenegraph()?;
|
||||||
|
Spatial::add_to(&_node, None, Mat4::IDENTITY, false)?;
|
||||||
|
let model = sk.model_create_mem("cursor.glb", include_bytes!("cursor.glb"), None)?;
|
||||||
|
let tip = InputType::Tip(Tip::default());
|
||||||
|
let input = InputMethod::add_to(&_node, tip, None)?;
|
||||||
|
Ok(SkController {
|
||||||
|
_node,
|
||||||
|
input,
|
||||||
handed,
|
handed,
|
||||||
}
|
model,
|
||||||
|
datamap: Default::default(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
pub fn update(&mut self, sk: &StereoKit) {
|
pub fn update(&mut self, sk: &impl StereoKitDraw) {
|
||||||
let controller = sk.input_controller(self.handed);
|
let controller = sk.input_controller(self.handed);
|
||||||
*self.tip.enabled.lock() = controller.tracked.contains(ButtonState::Active);
|
*self.input.enabled.lock() = controller.tracked.contains(ButtonState::ACTIVE);
|
||||||
if *self.tip.enabled.lock() {
|
if *self.input.enabled.lock() {
|
||||||
self.tip.spatial.set_local_transform_components(
|
let world_transform = Mat4::from_rotation_translation(
|
||||||
None,
|
controller.aim.orientation,
|
||||||
Transform {
|
controller.aim.position,
|
||||||
position: Some(controller.pose.position),
|
|
||||||
rotation: Some(controller.pose.orientation),
|
|
||||||
scale: None,
|
|
||||||
},
|
|
||||||
);
|
);
|
||||||
|
sk.model_draw(
|
||||||
|
&self.model,
|
||||||
|
world_transform * Mat4::from_scale(Vec3::ONE * 0.02),
|
||||||
|
WHITE,
|
||||||
|
RenderLayer::LAYER0,
|
||||||
|
);
|
||||||
|
self.input.spatial.set_local_transform(world_transform);
|
||||||
}
|
}
|
||||||
let mut fbb = flexbuffers::Builder::default();
|
self.datamap.select = controller.trigger;
|
||||||
let mut map = fbb.start_map();
|
self.datamap.grab = controller.grip;
|
||||||
map.push("select", controller.trigger);
|
self.datamap.scroll = controller.stick;
|
||||||
map.push("grab", controller.grip);
|
*self.input.datamap.lock() = self.datamap.to_datamap().ok();
|
||||||
map.end_map();
|
|
||||||
*self.tip.datamap.lock() = Datamap::new(fbb.take_buffer()).ok();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,49 +1,70 @@
|
|||||||
use crate::nodes::{
|
use crate::{
|
||||||
input::{hand::Hand, InputMethod, InputType},
|
core::{client::INTERNAL_CLIENT, typed_datamap::TypedDatamap},
|
||||||
spatial::Spatial,
|
nodes::{
|
||||||
|
input::{hand::Hand, InputMethod, InputType},
|
||||||
|
spatial::Spatial,
|
||||||
|
Node,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
use color_eyre::eyre::Result;
|
||||||
use glam::Mat4;
|
use glam::Mat4;
|
||||||
use stardust_xr::schemas::flat::{Datamap, Hand as FlatHand, Joint};
|
use nanoid::nanoid;
|
||||||
use std::sync::{Arc, Weak};
|
use serde::{Deserialize, Serialize};
|
||||||
use stereokit::{
|
use stardust_xr::schemas::flat::{Hand as FlatHand, Joint};
|
||||||
input::{ButtonState, Handed, Joint as SkJoint},
|
use std::sync::Arc;
|
||||||
StereoKit,
|
use stereokit::{ButtonState, HandJoint, Handed, StereoKitMultiThread};
|
||||||
};
|
|
||||||
|
|
||||||
fn convert_joint(joint: SkJoint) -> Joint {
|
fn convert_joint(joint: HandJoint) -> Joint {
|
||||||
Joint {
|
Joint {
|
||||||
position: joint.position,
|
position: joint.position.into(),
|
||||||
rotation: joint.orientation,
|
rotation: joint.orientation.into(),
|
||||||
radius: joint.radius,
|
radius: joint.radius,
|
||||||
|
distance: 0.0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Deserialize, Serialize)]
|
||||||
|
struct HandDatamap {
|
||||||
|
pinch_strength: f32,
|
||||||
|
grab_strength: f32,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct SkHand {
|
pub struct SkHand {
|
||||||
hand: Arc<InputMethod>,
|
_node: Arc<Node>,
|
||||||
|
input: Arc<InputMethod>,
|
||||||
handed: Handed,
|
handed: Handed,
|
||||||
|
datamap: TypedDatamap<HandDatamap>,
|
||||||
}
|
}
|
||||||
impl SkHand {
|
impl SkHand {
|
||||||
pub fn new(handed: Handed) -> Self {
|
pub fn new(handed: Handed) -> Result<Self> {
|
||||||
SkHand {
|
let _node = Node::create(&INTERNAL_CLIENT, "", &nanoid!(), false).add_to_scenegraph()?;
|
||||||
hand: InputMethod::new(
|
Spatial::add_to(&_node, None, Mat4::IDENTITY, false)?;
|
||||||
Spatial::new(Weak::new(), None, Mat4::IDENTITY),
|
let hand = InputType::Hand(Box::new(Hand {
|
||||||
InputType::Hand(Box::new(Hand {
|
base: FlatHand {
|
||||||
base: FlatHand {
|
right: handed == Handed::Right,
|
||||||
right: handed == Handed::Right,
|
..Default::default()
|
||||||
..Default::default()
|
},
|
||||||
},
|
}));
|
||||||
})),
|
let input = InputMethod::add_to(&_node, hand, None)?;
|
||||||
),
|
Ok(SkHand {
|
||||||
|
_node,
|
||||||
|
input,
|
||||||
handed,
|
handed,
|
||||||
}
|
datamap: Default::default(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
pub fn update(&mut self, sk: &StereoKit) {
|
pub fn update(&mut self, controller_enabled: bool, sk: &impl StereoKitMultiThread) {
|
||||||
let sk_hand = sk.input_hand(self.handed);
|
let sk_hand = sk.input_hand(self.handed);
|
||||||
if let InputType::Hand(hand) = &mut *self.hand.specialization.lock() {
|
if let InputType::Hand(hand) = &mut *self.input.specialization.lock() {
|
||||||
let controller = sk.input_controller(self.handed);
|
let controller_active = controller_enabled
|
||||||
*self.hand.enabled.lock() = controller.tracked.contains(ButtonState::Inactive)
|
&& sk
|
||||||
&& sk_hand.tracked_state.contains(ButtonState::Active);
|
.input_controller(self.handed)
|
||||||
if *self.hand.enabled.lock() {
|
.tracked
|
||||||
|
.contains(ButtonState::ACTIVE);
|
||||||
|
*self.input.enabled.lock() =
|
||||||
|
!controller_active && sk_hand.tracked_state.contains(ButtonState::ACTIVE);
|
||||||
|
sk.input_hand_visible(self.handed, *self.input.enabled.lock());
|
||||||
|
if *self.input.enabled.lock() {
|
||||||
hand.base.thumb.tip = convert_joint(sk_hand.fingers[0][4]);
|
hand.base.thumb.tip = convert_joint(sk_hand.fingers[0][4]);
|
||||||
hand.base.thumb.distal = convert_joint(sk_hand.fingers[0][3]);
|
hand.base.thumb.distal = convert_joint(sk_hand.fingers[0][3]);
|
||||||
hand.base.thumb.proximal = convert_joint(sk_hand.fingers[0][2]);
|
hand.base.thumb.proximal = convert_joint(sk_hand.fingers[0][2]);
|
||||||
@@ -62,24 +83,21 @@ impl SkHand {
|
|||||||
finger.metacarpal = convert_joint(sk_finger[0]);
|
finger.metacarpal = convert_joint(sk_finger[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
hand.base.palm.position = sk_hand.palm.position;
|
hand.base.palm.position = sk_hand.palm.position.into();
|
||||||
hand.base.palm.rotation = sk_hand.palm.orientation;
|
hand.base.palm.rotation = sk_hand.palm.orientation.into();
|
||||||
hand.base.palm.radius =
|
hand.base.palm.radius =
|
||||||
(sk_hand.fingers[2][0].radius + sk_hand.fingers[2][1].radius) * 0.5;
|
(sk_hand.fingers[2][0].radius + sk_hand.fingers[2][1].radius) * 0.5;
|
||||||
|
|
||||||
hand.base.wrist.position = sk_hand.wrist.position;
|
hand.base.wrist.position = sk_hand.wrist.position.into();
|
||||||
hand.base.wrist.rotation = sk_hand.wrist.orientation;
|
hand.base.wrist.rotation = sk_hand.wrist.orientation.into();
|
||||||
hand.base.wrist.radius =
|
hand.base.wrist.radius =
|
||||||
(sk_hand.fingers[0][0].radius + sk_hand.fingers[4][0].radius) * 0.5;
|
(sk_hand.fingers[0][0].radius + sk_hand.fingers[4][0].radius) * 0.5;
|
||||||
|
|
||||||
hand.base.elbow = None;
|
hand.base.elbow = None;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut fbb = flexbuffers::Builder::default();
|
self.datamap.pinch_strength = sk_hand.pinch_activation;
|
||||||
let mut map = fbb.start_map();
|
self.datamap.grab_strength = sk_hand.grip_activation;
|
||||||
map.push("grabStrength", sk_hand.grip_activation);
|
*self.input.datamap.lock() = self.datamap.to_datamap().ok();
|
||||||
map.push("pinchStrength", sk_hand.pinch_activation);
|
|
||||||
map.end_map();
|
|
||||||
*self.hand.datamap.lock() = Datamap::new(fbb.take_buffer()).ok();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1 +1,2 @@
|
|||||||
pub mod input;
|
pub mod input;
|
||||||
|
pub mod play_space;
|
||||||
|
|||||||
73
src/objects/play_space.rs
Normal file
73
src/objects/play_space.rs
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use color_eyre::eyre::Result;
|
||||||
|
use glam::Mat4;
|
||||||
|
use mint::Vector2;
|
||||||
|
use nanoid::nanoid;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use stereokit::StereoKitMultiThread;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
core::client::INTERNAL_CLIENT,
|
||||||
|
nodes::{
|
||||||
|
data::{Mask, PulseReceiver},
|
||||||
|
fields::{r#box::BoxField, Field},
|
||||||
|
spatial::Spatial,
|
||||||
|
Node,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
struct PlaySpaceMap {
|
||||||
|
play_space: (),
|
||||||
|
size: Vector2<f32>,
|
||||||
|
}
|
||||||
|
impl Default for PlaySpaceMap {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
play_space: (),
|
||||||
|
size: [0.0; 2].into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct PlaySpace {
|
||||||
|
_node: Arc<Node>,
|
||||||
|
spatial: Arc<Spatial>,
|
||||||
|
field: Arc<Field>,
|
||||||
|
_pulse_rx: Arc<PulseReceiver>,
|
||||||
|
}
|
||||||
|
impl PlaySpace {
|
||||||
|
pub fn new() -> Result<Self> {
|
||||||
|
let node = Node::create(&INTERNAL_CLIENT, "", &nanoid!(), false).add_to_scenegraph()?;
|
||||||
|
let spatial = Spatial::add_to(&node, None, Mat4::IDENTITY, false)?;
|
||||||
|
let field = BoxField::add_to(&node, [0.0; 3].into())?;
|
||||||
|
|
||||||
|
let pulse_rx =
|
||||||
|
PulseReceiver::add_to(&node, field.clone(), Mask::from_struct::<PlaySpaceMap>())?;
|
||||||
|
|
||||||
|
Ok(PlaySpace {
|
||||||
|
_node: node,
|
||||||
|
spatial,
|
||||||
|
field,
|
||||||
|
_pulse_rx: pulse_rx,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
pub fn update(&self, sk: &impl StereoKitMultiThread) {
|
||||||
|
let pose = sk.world_get_bounds_pose();
|
||||||
|
self.spatial
|
||||||
|
.set_local_transform(Mat4::from_rotation_translation(
|
||||||
|
pose.orientation,
|
||||||
|
pose.position,
|
||||||
|
));
|
||||||
|
let Field::Box(box_field) = self.field.as_ref() else {return};
|
||||||
|
box_field.set_size(
|
||||||
|
[
|
||||||
|
sk.world_get_bounds_size().x,
|
||||||
|
0.0,
|
||||||
|
sk.world_get_bounds_size().y,
|
||||||
|
]
|
||||||
|
.into(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,16 @@
|
|||||||
use super::{state::WaylandState, surface::CoreSurface};
|
use crate::wayland::surface::CoreSurface;
|
||||||
|
|
||||||
|
use super::state::{ClientState, WaylandState};
|
||||||
|
use portable_atomic::{AtomicU32, Ordering};
|
||||||
|
#[cfg(feature = "xwayland")]
|
||||||
|
use smithay::xwayland::XWaylandClientData;
|
||||||
use smithay::{
|
use smithay::{
|
||||||
delegate_compositor,
|
delegate_compositor,
|
||||||
reexports::wayland_server::protocol::wl_surface::WlSurface,
|
reexports::wayland_server::{protocol::wl_surface::WlSurface, Client},
|
||||||
wayland::compositor::{self, CompositorHandler, CompositorState},
|
wayland::compositor::{self, CompositorClientState, CompositorHandler, CompositorState},
|
||||||
};
|
};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tracing::debug;
|
||||||
|
|
||||||
impl CompositorHandler for WaylandState {
|
impl CompositorHandler for WaylandState {
|
||||||
fn compositor_state(&mut self) -> &mut CompositorState {
|
fn compositor_state(&mut self) -> &mut CompositorState {
|
||||||
@@ -11,16 +18,35 @@ impl CompositorHandler for WaylandState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn commit(&mut self, surface: &WlSurface) {
|
fn commit(&mut self, surface: &WlSurface) {
|
||||||
compositor::with_states(surface, |data| {
|
debug!(?surface, "Surface commit");
|
||||||
data.data_map.insert_if_missing_threadsafe(|| {
|
let mut count = 0;
|
||||||
CoreSurface::new(
|
let core_surface = compositor::with_states(surface, |data| {
|
||||||
&self.weak_ref.upgrade().unwrap(),
|
let count_new = data
|
||||||
&self.display,
|
.data_map
|
||||||
self.display_handle.clone(),
|
.insert_if_missing_threadsafe(|| AtomicU32::new(0));
|
||||||
surface,
|
if !count_new {
|
||||||
)
|
if let Some(stored_count) = data.data_map.get::<AtomicU32>() {
|
||||||
})
|
count = stored_count.fetch_add(1, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data.data_map.get::<Arc<CoreSurface>>().cloned()
|
||||||
});
|
});
|
||||||
|
if let Some(core_surface) = core_surface {
|
||||||
|
core_surface.commit(count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_compositor_state<'a>(&self, client: &'a Client) -> &'a CompositorClientState {
|
||||||
|
if let Some(client_state) = client.get_data::<ClientState>() {
|
||||||
|
&client_state.compositor_state
|
||||||
|
} else {
|
||||||
|
#[cfg(feature = "xwayland")]
|
||||||
|
if let Some(xwayland_client_data) = client.get_data::<XWaylandClientData>() {
|
||||||
|
return &xwayland_client_data.compositor_state;
|
||||||
|
}
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,34 +1,97 @@
|
|||||||
use super::state::WaylandState;
|
use super::state::WaylandState;
|
||||||
use smithay::{
|
use smithay::{
|
||||||
delegate_kde_decoration, delegate_xdg_decoration,
|
delegate_kde_decoration,
|
||||||
reexports::wayland_protocols::xdg::decoration::zv1::server::zxdg_toplevel_decoration_v1::Mode,
|
reexports::{
|
||||||
wayland::shell::{
|
wayland_protocols::xdg::{
|
||||||
self, kde::decoration::KdeDecorationHandler, xdg::decoration::XdgDecorationHandler,
|
decoration::zv1::server::{
|
||||||
|
zxdg_decoration_manager_v1::{self, ZxdgDecorationManagerV1},
|
||||||
|
zxdg_toplevel_decoration_v1::{self, Mode, ZxdgToplevelDecorationV1},
|
||||||
|
},
|
||||||
|
shell::server::xdg_toplevel::XdgToplevel,
|
||||||
|
},
|
||||||
|
wayland_protocols_misc::server_decoration::server::org_kde_kwin_server_decoration::{
|
||||||
|
Mode as KdeMode, OrgKdeKwinServerDecoration,
|
||||||
|
},
|
||||||
|
wayland_server::{
|
||||||
|
protocol::wl_surface::WlSurface, Client, DataInit, Dispatch, DisplayHandle,
|
||||||
|
GlobalDispatch, New, Resource, WEnum, Weak,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
|
wayland::shell::{self, kde::decoration::KdeDecorationHandler},
|
||||||
};
|
};
|
||||||
|
|
||||||
impl XdgDecorationHandler for WaylandState {
|
impl GlobalDispatch<ZxdgDecorationManagerV1, (), WaylandState> for WaylandState {
|
||||||
fn new_decoration(&mut self, toplevel: smithay::wayland::shell::xdg::ToplevelSurface) {
|
fn bind(
|
||||||
toplevel.with_pending_state(|state| {
|
_state: &mut WaylandState,
|
||||||
state.decoration_mode = Some(Mode::ServerSide);
|
_handle: &DisplayHandle,
|
||||||
});
|
_client: &Client,
|
||||||
toplevel.send_configure();
|
resource: New<ZxdgDecorationManagerV1>,
|
||||||
}
|
_global_data: &(),
|
||||||
|
data_init: &mut DataInit<'_, WaylandState>,
|
||||||
fn request_mode(
|
|
||||||
&mut self,
|
|
||||||
_toplevel: smithay::wayland::shell::xdg::ToplevelSurface,
|
|
||||||
_mode: smithay::reexports::wayland_protocols::xdg::decoration::zv1::server::zxdg_toplevel_decoration_v1::Mode,
|
|
||||||
) {
|
) {
|
||||||
|
data_init.init(resource, ());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Dispatch<ZxdgDecorationManagerV1, (), WaylandState> for WaylandState {
|
||||||
|
fn request(
|
||||||
|
_state: &mut WaylandState,
|
||||||
|
_client: &Client,
|
||||||
|
_resource: &ZxdgDecorationManagerV1,
|
||||||
|
request: zxdg_decoration_manager_v1::Request,
|
||||||
|
_data: &(),
|
||||||
|
_dhandle: &DisplayHandle,
|
||||||
|
data_init: &mut DataInit<'_, WaylandState>,
|
||||||
|
) {
|
||||||
|
match request {
|
||||||
|
zxdg_decoration_manager_v1::Request::Destroy => (),
|
||||||
|
zxdg_decoration_manager_v1::Request::GetToplevelDecoration { id, toplevel } => {
|
||||||
|
data_init.init(id, toplevel.downgrade());
|
||||||
|
}
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Dispatch<ZxdgToplevelDecorationV1, Weak<XdgToplevel>, WaylandState> for WaylandState {
|
||||||
|
fn request(
|
||||||
|
_state: &mut WaylandState,
|
||||||
|
_client: &Client,
|
||||||
|
resource: &ZxdgToplevelDecorationV1,
|
||||||
|
request: zxdg_toplevel_decoration_v1::Request,
|
||||||
|
_data: &Weak<XdgToplevel>,
|
||||||
|
_dhandle: &DisplayHandle,
|
||||||
|
_data_init: &mut DataInit<'_, WaylandState>,
|
||||||
|
) {
|
||||||
|
match request {
|
||||||
|
zxdg_toplevel_decoration_v1::Request::SetMode { mode: _ } => {
|
||||||
|
resource.configure(Mode::ServerSide);
|
||||||
|
}
|
||||||
|
zxdg_toplevel_decoration_v1::Request::UnsetMode => {
|
||||||
|
resource.configure(Mode::ServerSide);
|
||||||
|
}
|
||||||
|
zxdg_toplevel_decoration_v1::Request::Destroy => (),
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unset_mode(&mut self, _toplevel: smithay::wayland::shell::xdg::ToplevelSurface) {}
|
|
||||||
}
|
}
|
||||||
delegate_xdg_decoration!(WaylandState);
|
|
||||||
|
|
||||||
impl KdeDecorationHandler for WaylandState {
|
impl KdeDecorationHandler for WaylandState {
|
||||||
fn kde_decoration_state(&self) -> &shell::kde::decoration::KdeDecorationState {
|
fn kde_decoration_state(&self) -> &shell::kde::decoration::KdeDecorationState {
|
||||||
&self.kde_decoration_state
|
&self.kde_decoration_state
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn new_decoration(&mut self, _surface: &WlSurface, decoration: &OrgKdeKwinServerDecoration) {
|
||||||
|
decoration.mode(KdeMode::Server);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_mode(
|
||||||
|
&mut self,
|
||||||
|
_surface: &WlSurface,
|
||||||
|
decoration: &OrgKdeKwinServerDecoration,
|
||||||
|
mode: WEnum<KdeMode>,
|
||||||
|
) {
|
||||||
|
let Ok(mode) = mode.into_result() else {return};
|
||||||
|
decoration.mode(mode);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
delegate_kde_decoration!(WaylandState);
|
delegate_kde_decoration!(WaylandState);
|
||||||
|
|||||||
@@ -1,176 +1,170 @@
|
|||||||
pub mod compositor;
|
mod compositor;
|
||||||
mod data_device;
|
mod data_device;
|
||||||
pub mod decoration;
|
mod decoration;
|
||||||
pub mod panel_item;
|
mod seat;
|
||||||
pub mod seat;
|
mod state;
|
||||||
pub mod shaders;
|
mod surface;
|
||||||
pub mod state;
|
// mod xdg_activation;
|
||||||
pub mod surface;
|
mod xdg_shell;
|
||||||
pub mod xdg_activation;
|
#[cfg(feature = "xwayland")]
|
||||||
pub mod xdg_shell;
|
pub mod xwayland;
|
||||||
|
|
||||||
use self::{panel_item::PanelItem, state::WaylandState, surface::CORE_SURFACES};
|
use self::{state::WaylandState, surface::CORE_SURFACES};
|
||||||
use crate::wayland::state::ClientState;
|
use crate::core::buffers::BufferManager;
|
||||||
use anyhow::{ensure, Result};
|
use crate::wayland::seat::SeatData;
|
||||||
|
use crate::{core::task, wayland::state::ClientState};
|
||||||
|
use color_eyre::eyre::Result;
|
||||||
|
use global_counter::primitive::exact::CounterU32;
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use slog::Logger;
|
use sk::StereoKitDraw;
|
||||||
use smithay::{
|
use smithay::backend::allocator::dmabuf::Dmabuf;
|
||||||
backend::{egl::EGLContext, renderer::gles2::Gles2Renderer},
|
use smithay::backend::renderer::ImportDma;
|
||||||
reexports::wayland_server::{backend::GlobalId, Display, ListeningSocket, Resource},
|
use smithay::reexports::wayland_server::backend::ClientId;
|
||||||
};
|
use smithay::reexports::wayland_server::DisplayHandle;
|
||||||
|
use smithay::reexports::wayland_server::{Display, ListeningSocket};
|
||||||
|
use std::ffi::OsStr;
|
||||||
|
use std::os::fd::OwnedFd;
|
||||||
use std::os::unix::prelude::AsRawFd;
|
use std::os::unix::prelude::AsRawFd;
|
||||||
use std::{
|
use std::{
|
||||||
ffi::c_void,
|
os::unix::{net::UnixListener, prelude::FromRawFd},
|
||||||
os::unix::{
|
|
||||||
net::UnixListener,
|
|
||||||
prelude::{FromRawFd, RawFd},
|
|
||||||
},
|
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
};
|
};
|
||||||
use stereokit as sk;
|
use stereokit as sk;
|
||||||
use stereokit::StereoKit;
|
use tokio::sync::mpsc::UnboundedReceiver;
|
||||||
use tokio::{
|
use tokio::{
|
||||||
io::unix::AsyncFd, net::UnixListener as AsyncUnixListener, sync::mpsc, task::JoinHandle,
|
io::unix::AsyncFd, net::UnixListener as AsyncUnixListener, sync::mpsc, task::JoinHandle,
|
||||||
};
|
};
|
||||||
|
use tracing::{debug_span, info, instrument};
|
||||||
|
|
||||||
struct EGLRawHandles {
|
pub static WAYLAND_DISPLAY: OnceCell<String> = OnceCell::new();
|
||||||
display: *const c_void,
|
pub static SERIAL_COUNTER: CounterU32 = CounterU32::new(0);
|
||||||
config: *const c_void,
|
|
||||||
context: *const c_void,
|
|
||||||
}
|
|
||||||
fn get_sk_egl() -> Result<EGLRawHandles> {
|
|
||||||
ensure!(
|
|
||||||
unsafe { sk::sys::backend_graphics_get() }
|
|
||||||
== sk::sys::backend_graphics__backend_graphics_opengles_egl,
|
|
||||||
"StereoKit is not running using EGL!"
|
|
||||||
);
|
|
||||||
|
|
||||||
Ok(unsafe {
|
pub struct DisplayWrapper(Mutex<Display<WaylandState>>, DisplayHandle);
|
||||||
EGLRawHandles {
|
impl DisplayWrapper {
|
||||||
display: sk::sys::backend_opengl_egl_get_display() as *const c_void,
|
pub fn handle(&self) -> DisplayHandle {
|
||||||
config: sk::sys::backend_opengl_egl_get_config() as *const c_void,
|
self.1.clone()
|
||||||
context: sk::sys::backend_opengl_egl_get_context() as *const c_void,
|
}
|
||||||
|
pub fn dispatch_clients(&self, state: &mut WaylandState) -> Result<usize, std::io::Error> {
|
||||||
|
self.0.lock().dispatch_clients(state)
|
||||||
|
}
|
||||||
|
pub fn flush_clients(&self, client: Option<ClientId>) {
|
||||||
|
if let Some(mut lock) = self.0.try_lock() {
|
||||||
|
let _ = lock.backend().flush(client);
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
|
pub fn poll_fd(&self) -> Result<OwnedFd, std::io::Error> {
|
||||||
|
self.0.lock().backend().poll_fd().try_clone_to_owned()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static GLOBAL_DESTROY_QUEUE: OnceCell<mpsc::Sender<GlobalId>> = OnceCell::new();
|
|
||||||
|
|
||||||
pub struct Wayland {
|
pub struct Wayland {
|
||||||
log: slog::Logger,
|
display: Arc<DisplayWrapper>,
|
||||||
|
pub socket_name: Option<String>,
|
||||||
display: Arc<Mutex<Display<WaylandState>>>,
|
|
||||||
join_handle: JoinHandle<Result<()>>,
|
join_handle: JoinHandle<Result<()>>,
|
||||||
renderer: Gles2Renderer,
|
dmabuf_rx: UnboundedReceiver<Dmabuf>,
|
||||||
state: Arc<Mutex<WaylandState>>,
|
wayland_state: Arc<Mutex<WaylandState>>,
|
||||||
|
#[cfg(feature = "xwayland")]
|
||||||
|
pub xwayland_state: xwayland::XWaylandState,
|
||||||
}
|
}
|
||||||
impl Wayland {
|
impl Wayland {
|
||||||
pub fn new(log: Logger) -> Result<Self> {
|
pub fn new(buffer_manager: &BufferManager) -> Result<Self> {
|
||||||
let egl_raw_handles = get_sk_egl()?;
|
|
||||||
let renderer = unsafe {
|
|
||||||
Gles2Renderer::new(
|
|
||||||
EGLContext::from_raw(
|
|
||||||
egl_raw_handles.display,
|
|
||||||
egl_raw_handles.config,
|
|
||||||
egl_raw_handles.context,
|
|
||||||
log.clone(),
|
|
||||||
)?,
|
|
||||||
log.clone(),
|
|
||||||
)?
|
|
||||||
};
|
|
||||||
|
|
||||||
let display: Display<WaylandState> = Display::new()?;
|
let display: Display<WaylandState> = Display::new()?;
|
||||||
let display_handle = display.handle();
|
let display_handle = display.handle();
|
||||||
|
|
||||||
let display = Arc::new(Mutex::new(display));
|
let (dmabuf_tx, dmabuf_rx) = mpsc::unbounded_channel();
|
||||||
let state = WaylandState::new(log.clone(), display.clone(), display_handle);
|
let display = Arc::new(DisplayWrapper(Mutex::new(display), display_handle.clone()));
|
||||||
|
#[cfg(feature = "xwayland")]
|
||||||
|
let xwayland_state = xwayland::XWaylandState::create(&display_handle)?;
|
||||||
|
let wayland_state = WaylandState::new(display_handle, &buffer_manager.renderer, dmabuf_tx);
|
||||||
|
|
||||||
let (global_destroy_queue_in, global_destroy_queue) = mpsc::channel(8);
|
let socket = ListeningSocket::bind_auto("wayland", 0..33)?;
|
||||||
GLOBAL_DESTROY_QUEUE.set(global_destroy_queue_in).unwrap();
|
let socket_name = socket
|
||||||
|
.socket_name()
|
||||||
|
.and_then(OsStr::to_str)
|
||||||
|
.map(ToString::to_string);
|
||||||
|
if let Some(socket_name) = &socket_name {
|
||||||
|
let _ = WAYLAND_DISPLAY.set(socket_name.clone());
|
||||||
|
}
|
||||||
|
info!(socket_name, "Wayland active");
|
||||||
|
|
||||||
let join_handle =
|
let join_handle = Wayland::start_loop(display.clone(), socket, wayland_state.clone())?;
|
||||||
Wayland::start_loop(display.clone(), state.clone(), global_destroy_queue)?;
|
|
||||||
|
|
||||||
Ok(Wayland {
|
Ok(Wayland {
|
||||||
log,
|
|
||||||
display,
|
display,
|
||||||
|
socket_name,
|
||||||
join_handle,
|
join_handle,
|
||||||
renderer,
|
dmabuf_rx,
|
||||||
state,
|
wayland_state,
|
||||||
|
#[cfg(feature = "xwayland")]
|
||||||
|
xwayland_state,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn start_loop(
|
fn start_loop(
|
||||||
display: Arc<Mutex<Display<WaylandState>>>,
|
display: Arc<DisplayWrapper>,
|
||||||
|
socket: ListeningSocket,
|
||||||
state: Arc<Mutex<WaylandState>>,
|
state: Arc<Mutex<WaylandState>>,
|
||||||
mut global_destroy_queue: mpsc::Receiver<GlobalId>,
|
|
||||||
) -> Result<JoinHandle<Result<()>>> {
|
) -> Result<JoinHandle<Result<()>>> {
|
||||||
let socket = ListeningSocket::bind_auto("wayland", 0..33)?;
|
|
||||||
if let Some(socket_name) = socket.socket_name() {
|
|
||||||
println!("Wayland compositor {:?} active", socket_name);
|
|
||||||
}
|
|
||||||
|
|
||||||
let listen_async =
|
let listen_async =
|
||||||
AsyncUnixListener::from_std(unsafe { UnixListener::from_raw_fd(socket.as_raw_fd()) })?;
|
AsyncUnixListener::from_std(unsafe { UnixListener::from_raw_fd(socket.as_raw_fd()) })?;
|
||||||
|
|
||||||
let dispatch_poll_fd: RawFd = display.lock().backend().poll_fd();
|
let dispatch_poll_fd = display.poll_fd()?;
|
||||||
let dispatch_poll_listener = AsyncFd::new(dispatch_poll_fd)?;
|
let dispatch_poll_listener = AsyncFd::new(dispatch_poll_fd)?;
|
||||||
|
|
||||||
let dh1 = display.lock().handle();
|
let dh1 = display.handle();
|
||||||
let mut dh2 = dh1.clone();
|
let mut dh2 = dh1.clone();
|
||||||
|
|
||||||
Ok(tokio::task::spawn(async move {
|
Ok(task::new(|| "wayland loop", async move {
|
||||||
let _socket = socket; // Keep the socket alive
|
let _socket = socket; // Keep the socket alive
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
e = global_destroy_queue.recv() => { // New global to destroy
|
|
||||||
dh1.remove_global::<WaylandState>(e.unwrap());
|
|
||||||
}
|
|
||||||
acc = listen_async.accept() => { // New client connected
|
acc = listen_async.accept() => { // New client connected
|
||||||
let (stream, _) = acc?;
|
let (stream, _) = acc?;
|
||||||
let client = dh2.insert_client(stream.into_std()?, Arc::new(ClientState))?;
|
let client_state = Arc::new(ClientState {
|
||||||
|
id: OnceCell::new(),
|
||||||
state.lock().new_client(client.id(), &dh2);
|
compositor_state: Default::default(),
|
||||||
|
display: Arc::downgrade(&display),
|
||||||
|
seat: SeatData::new(&dh1)
|
||||||
|
});
|
||||||
|
let client = dh2.insert_client(stream.into_std()?, client_state.clone())?;
|
||||||
|
let _ = client_state.seat.client.set(client.id());
|
||||||
}
|
}
|
||||||
e = dispatch_poll_listener.readable() => { // Dispatch
|
e = dispatch_poll_listener.readable() => { // Dispatch
|
||||||
let mut guard = e?;
|
let mut guard = e?;
|
||||||
let mut display = display.lock();
|
debug_span!("Dispatch wayland event").in_scope(|| -> Result<(), color_eyre::Report> {
|
||||||
display.dispatch_clients(&mut *state.lock())?;
|
display.dispatch_clients(&mut *state.lock())?;
|
||||||
display.flush_clients()?;
|
display.flush_clients(None);
|
||||||
|
Ok(())
|
||||||
|
})?;
|
||||||
guard.clear_ready();
|
guard.clear_ready();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}))
|
})?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn frame(&mut self, sk: &StereoKit) {
|
#[instrument(
|
||||||
let time_ms = (sk.time_getf() * 1000.) as u32;
|
level = "debug",
|
||||||
|
name = "Wayland frame",
|
||||||
|
skip(self, sk, buffer_manager)
|
||||||
|
)]
|
||||||
|
pub fn update(&mut self, sk: &impl StereoKitDraw, buffer_manager: &mut BufferManager) {
|
||||||
|
while let Ok(dmabuf) = self.dmabuf_rx.try_recv() {
|
||||||
|
let _ = buffer_manager.renderer.import_dmabuf(&dmabuf, None);
|
||||||
|
}
|
||||||
for core_surface in CORE_SURFACES.get_valid_contents() {
|
for core_surface in CORE_SURFACES.get_valid_contents() {
|
||||||
let client_id = core_surface.wl_surface().client_id().unwrap();
|
core_surface.process(sk, &mut buffer_manager.renderer);
|
||||||
let seat_data = self.state.lock().seats.get(&client_id).unwrap().clone();
|
|
||||||
core_surface.process(
|
|
||||||
sk,
|
|
||||||
&mut self.renderer,
|
|
||||||
time_ms,
|
|
||||||
&self.log,
|
|
||||||
|data| {
|
|
||||||
PanelItem::on_mapped(&core_surface, data, seat_data);
|
|
||||||
},
|
|
||||||
|data| {
|
|
||||||
PanelItem::if_mapped(&core_surface, data);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
self.display.lock().flush_clients().unwrap();
|
self.display.flush_clients(None);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn make_context_current(&self) {
|
pub fn frame_event(&self, sk: &impl StereoKitDraw) {
|
||||||
unsafe {
|
let output = self.wayland_state.lock().output.clone();
|
||||||
self.renderer.egl_context().make_current().unwrap();
|
|
||||||
|
for core_surface in CORE_SURFACES.get_valid_contents() {
|
||||||
|
core_surface.frame(sk, output.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,506 +0,0 @@
|
|||||||
use super::{
|
|
||||||
seat::{KeyboardInfo, SeatData},
|
|
||||||
surface::CoreSurface,
|
|
||||||
};
|
|
||||||
use crate::{
|
|
||||||
core::{
|
|
||||||
client::{Client, INTERNAL_CLIENT},
|
|
||||||
registry::Registry,
|
|
||||||
},
|
|
||||||
nodes::{
|
|
||||||
items::{register_item_ui_flex, Item, ItemSpecialization, ItemType, TypeInfo},
|
|
||||||
spatial::Spatial,
|
|
||||||
Node,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
use anyhow::{anyhow, bail, Result};
|
|
||||||
use glam::Mat4;
|
|
||||||
use lazy_static::lazy_static;
|
|
||||||
use mint::Vector2;
|
|
||||||
use nanoid::nanoid;
|
|
||||||
use serde::Deserialize;
|
|
||||||
use smithay::{
|
|
||||||
reexports::wayland_server::protocol::wl_pointer::{Axis, ButtonState},
|
|
||||||
utils::Size,
|
|
||||||
wayland::{compositor::SurfaceData, shell::xdg::XdgToplevelSurfaceData},
|
|
||||||
};
|
|
||||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
|
||||||
use std::sync::{Arc, Weak};
|
|
||||||
use xkbcommon::xkb::{self, ffi::XKB_KEYMAP_FORMAT_TEXT_V1, Keymap};
|
|
||||||
|
|
||||||
lazy_static! {
|
|
||||||
static ref ITEM_TYPE_INFO_PANEL: TypeInfo = TypeInfo {
|
|
||||||
type_name: "panel",
|
|
||||||
aliased_local_signals: vec![
|
|
||||||
"applySurfaceMaterial",
|
|
||||||
"applyCursorMaterial",
|
|
||||||
"pointerDeactivate",
|
|
||||||
"pointerScroll",
|
|
||||||
"pointerButton",
|
|
||||||
"pointerMotion",
|
|
||||||
"keyboardSetActive",
|
|
||||||
"keyboardSetKeyState",
|
|
||||||
"keyboardSetModifiers",
|
|
||||||
"resize",
|
|
||||||
"close",
|
|
||||||
],
|
|
||||||
aliased_local_methods: vec![],
|
|
||||||
aliased_remote_signals: vec!["resize", "setCursor",],
|
|
||||||
aliased_remote_methods: vec![],
|
|
||||||
ui: Default::default(),
|
|
||||||
items: Registry::new(),
|
|
||||||
acceptors: Registry::new(),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct PanelItem {
|
|
||||||
node: Weak<Node>,
|
|
||||||
core_surface: Weak<CoreSurface>,
|
|
||||||
seat_data: SeatData,
|
|
||||||
}
|
|
||||||
impl PanelItem {
|
|
||||||
pub fn create(core_surface: &Arc<CoreSurface>, seat_data: SeatData) -> Arc<Node> {
|
|
||||||
let node = Arc::new(Node::create(
|
|
||||||
&INTERNAL_CLIENT,
|
|
||||||
"/item/panel/item",
|
|
||||||
&nanoid!(),
|
|
||||||
true,
|
|
||||||
));
|
|
||||||
Spatial::add_to(&node, None, Mat4::IDENTITY).unwrap();
|
|
||||||
|
|
||||||
let specialization = ItemType::Panel(PanelItem {
|
|
||||||
node: Arc::downgrade(&node),
|
|
||||||
core_surface: Arc::downgrade(core_surface),
|
|
||||||
seat_data,
|
|
||||||
});
|
|
||||||
let item = Item::add_to(&node, &ITEM_TYPE_INFO_PANEL, specialization);
|
|
||||||
if let ItemType::Panel(panel) = &item.specialization {
|
|
||||||
let _ = panel.seat_data.panel_item.set(Arc::downgrade(&item));
|
|
||||||
}
|
|
||||||
|
|
||||||
node.add_local_signal(
|
|
||||||
"applySurfaceMaterial",
|
|
||||||
PanelItem::apply_surface_material_flex,
|
|
||||||
);
|
|
||||||
node.add_local_signal("applyCursorMaterial", PanelItem::apply_cursor_material_flex);
|
|
||||||
node.add_local_signal("pointerDeactivate", PanelItem::pointer_deactivate_flex);
|
|
||||||
node.add_local_signal("pointerScroll", PanelItem::pointer_scroll_flex);
|
|
||||||
node.add_local_signal("pointerButton", PanelItem::pointer_button_flex);
|
|
||||||
node.add_local_signal("pointerMotion", PanelItem::pointer_motion_flex);
|
|
||||||
node.add_local_signal(
|
|
||||||
"keyboardActivateString",
|
|
||||||
PanelItem::keyboard_activate_string_flex,
|
|
||||||
);
|
|
||||||
node.add_local_signal(
|
|
||||||
"keyboardActivateNames",
|
|
||||||
PanelItem::keyboard_activate_names_flex,
|
|
||||||
);
|
|
||||||
node.add_local_signal("keyboardDeactivate", PanelItem::keyboard_deactivate_flex);
|
|
||||||
node.add_local_signal("keyboardKeyState", PanelItem::keyboard_key_state_flex);
|
|
||||||
node.add_local_signal("resize", PanelItem::resize_flex);
|
|
||||||
node
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn from_node(node: &Node) -> &PanelItem {
|
|
||||||
match &node.item.get().unwrap().specialization {
|
|
||||||
ItemType::Panel(panel_item) => panel_item,
|
|
||||||
_ => unreachable!(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn apply_surface_material_flex(
|
|
||||||
node: &Node,
|
|
||||||
calling_client: Arc<Client>,
|
|
||||||
data: &[u8],
|
|
||||||
) -> Result<()> {
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct SurfaceMaterialInfo<'a> {
|
|
||||||
model_path: &'a str,
|
|
||||||
idx: u32,
|
|
||||||
}
|
|
||||||
let info: SurfaceMaterialInfo = deserialize(data)?;
|
|
||||||
let model_node = calling_client
|
|
||||||
.scenegraph
|
|
||||||
.get_node(info.model_path)
|
|
||||||
.ok_or_else(|| anyhow!("Model node not found"))?;
|
|
||||||
let model = model_node
|
|
||||||
.model
|
|
||||||
.get()
|
|
||||||
.ok_or_else(|| anyhow!("Node is not a model"))?;
|
|
||||||
|
|
||||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
|
||||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
|
||||||
core_surface.apply_material(model.clone(), info.idx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn apply_cursor_material_flex(
|
|
||||||
node: &Node,
|
|
||||||
calling_client: Arc<Client>,
|
|
||||||
data: &[u8],
|
|
||||||
) -> Result<()> {
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct SurfaceMaterialInfo<'a> {
|
|
||||||
model_path: &'a str,
|
|
||||||
idx: u32,
|
|
||||||
}
|
|
||||||
let info: SurfaceMaterialInfo = deserialize(data)?;
|
|
||||||
let model_node = calling_client
|
|
||||||
.scenegraph
|
|
||||||
.get_node(info.model_path)
|
|
||||||
.ok_or_else(|| anyhow!("Model node not found"))?;
|
|
||||||
let model = model_node
|
|
||||||
.model
|
|
||||||
.get()
|
|
||||||
.ok_or_else(|| anyhow!("Node is not a model"))?;
|
|
||||||
|
|
||||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
|
||||||
if let Some(cursor) = &*panel_item.seat_data.cursor.lock() {
|
|
||||||
if let Some(core_surface) = cursor.lock().core_surface.upgrade() {
|
|
||||||
core_surface.apply_material(model.clone(), info.idx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn on_mapped(
|
|
||||||
core_surface: &Arc<CoreSurface>,
|
|
||||||
surface_data: &SurfaceData,
|
|
||||||
seat_data: SeatData,
|
|
||||||
) {
|
|
||||||
if surface_data
|
|
||||||
.data_map
|
|
||||||
.get::<XdgToplevelSurfaceData>()
|
|
||||||
.is_some()
|
|
||||||
{
|
|
||||||
surface_data
|
|
||||||
.data_map
|
|
||||||
.insert_if_missing_threadsafe(|| PanelItem::create(core_surface, seat_data));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn if_mapped(_core_surface: &Arc<CoreSurface>, surface_data: &SurfaceData) {
|
|
||||||
if let Some(panel_node) = surface_data.data_map.get::<Arc<Node>>() {
|
|
||||||
let panel_item = PanelItem::from_node(panel_node);
|
|
||||||
|
|
||||||
// core_surface.with_data(|core_surface_data| {
|
|
||||||
// panel_item.resize();
|
|
||||||
// });
|
|
||||||
|
|
||||||
panel_item.set_cursor();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resize(&self) {
|
|
||||||
self.core_surface.upgrade().unwrap().with_data(|data| {
|
|
||||||
let _ = self
|
|
||||||
.node
|
|
||||||
.upgrade()
|
|
||||||
.unwrap()
|
|
||||||
.send_remote_signal("resize", &serialize(data.size).unwrap());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_cursor(&self) {
|
|
||||||
let mut cursor_changed = self.seat_data.cursor_changed.lock();
|
|
||||||
if !*cursor_changed {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let mut data = serialize(()).unwrap();
|
|
||||||
|
|
||||||
if let Some(cursor) = &*self.seat_data.cursor.lock() {
|
|
||||||
let cursor = cursor.lock();
|
|
||||||
if let Some(core_surface) = cursor.core_surface.upgrade() {
|
|
||||||
if let Some(mapped_data) = &*core_surface.mapped_data.lock() {
|
|
||||||
data = serialize((mapped_data.size, cursor.hotspot)).unwrap();
|
|
||||||
} else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let _ = self
|
|
||||||
.node
|
|
||||||
.upgrade()
|
|
||||||
.unwrap()
|
|
||||||
.send_remote_signal("setCursor", &data);
|
|
||||||
*cursor_changed = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pointer_deactivate_flex(
|
|
||||||
node: &Node,
|
|
||||||
_calling_client: Arc<Client>,
|
|
||||||
_data: &[u8],
|
|
||||||
) -> Result<()> {
|
|
||||||
let panel_item = PanelItem::from_node(node);
|
|
||||||
if *panel_item.seat_data.pointer_active.lock() {
|
|
||||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
|
||||||
if let Some(pointer) = panel_item.seat_data.pointer() {
|
|
||||||
pointer.leave(0, &core_surface.wl_surface());
|
|
||||||
*panel_item.seat_data.pointer_active.lock() = false;
|
|
||||||
pointer.frame();
|
|
||||||
core_surface.flush_clients();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pointer_motion_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
|
||||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
|
||||||
if let Some(pointer) = panel_item.seat_data.pointer() {
|
|
||||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
|
||||||
if let Some(size) = core_surface.with_data(|data| data.size) {
|
|
||||||
let mut position: Vector2<f64> = deserialize(data)?;
|
|
||||||
position.x = position.x.clamp(0.0, size.x as f64);
|
|
||||||
position.y = position.y.clamp(0.0, size.y as f64);
|
|
||||||
let mut pointer_active = panel_item.seat_data.pointer_active.lock();
|
|
||||||
if *pointer_active {
|
|
||||||
pointer.motion(0, position.x, position.y);
|
|
||||||
} else {
|
|
||||||
pointer.enter(0, &core_surface.wl_surface(), position.x, position.y);
|
|
||||||
*pointer_active = true;
|
|
||||||
}
|
|
||||||
pointer.frame();
|
|
||||||
core_surface.flush_clients();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pointer_button_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
|
||||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
|
||||||
if let Some(pointer) = panel_item.seat_data.pointer() {
|
|
||||||
if *panel_item.seat_data.pointer_active.lock() {
|
|
||||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
|
||||||
let (button, state): (u32, u32) = deserialize(data)?;
|
|
||||||
pointer.button(
|
|
||||||
0,
|
|
||||||
0,
|
|
||||||
button,
|
|
||||||
match state {
|
|
||||||
0 => ButtonState::Released,
|
|
||||||
1 => ButtonState::Pressed,
|
|
||||||
_ => {
|
|
||||||
bail!("Button state is out of bounds")
|
|
||||||
}
|
|
||||||
},
|
|
||||||
);
|
|
||||||
pointer.frame();
|
|
||||||
core_surface.flush_clients();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn pointer_scroll_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct PointerScrollArgs {
|
|
||||||
axis_continuous: Vector2<f32>,
|
|
||||||
axis_discrete: Option<Vector2<f32>>,
|
|
||||||
}
|
|
||||||
let args: PointerScrollArgs = deserialize(data)?;
|
|
||||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
|
||||||
if let Some(pointer) = panel_item.seat_data.pointer() {
|
|
||||||
if *panel_item.seat_data.pointer_active.lock() {
|
|
||||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
|
||||||
let flex = flexbuffers::Reader::get_root(data)?;
|
|
||||||
if flex.flexbuffer_type().is_null() {
|
|
||||||
pointer.axis_stop(0, Axis::HorizontalScroll);
|
|
||||||
pointer.axis_stop(0, Axis::VerticalScroll);
|
|
||||||
} else {
|
|
||||||
pointer.axis(0, Axis::HorizontalScroll, args.axis_continuous.x as f64);
|
|
||||||
pointer.axis(0, Axis::VerticalScroll, args.axis_continuous.y as f64);
|
|
||||||
if let Some(axis_discrete_vec) = args.axis_discrete {
|
|
||||||
pointer.axis_discrete(
|
|
||||||
Axis::HorizontalScroll,
|
|
||||||
axis_discrete_vec.x as i32,
|
|
||||||
);
|
|
||||||
pointer.axis_discrete(
|
|
||||||
Axis::VerticalScroll,
|
|
||||||
axis_discrete_vec.y as i32,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pointer.frame();
|
|
||||||
core_surface.flush_clients();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn keyboard_activate_string_flex(
|
|
||||||
node: &Node,
|
|
||||||
_calling_client: Arc<Client>,
|
|
||||||
data: &[u8],
|
|
||||||
) -> Result<()> {
|
|
||||||
let context = xkb::Context::new(0);
|
|
||||||
let keymap =
|
|
||||||
Keymap::new_from_string(&context, deserialize(data)?, XKB_KEYMAP_FORMAT_TEXT_V1, 0)
|
|
||||||
.ok_or_else(|| anyhow!("Keymap is not valid"))?;
|
|
||||||
|
|
||||||
PanelItem::keyboard_activate_flex(node, &keymap)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn keyboard_activate_names_flex(
|
|
||||||
node: &Node,
|
|
||||||
_calling_client: Arc<Client>,
|
|
||||||
data: &[u8],
|
|
||||||
) -> Result<()> {
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Names<'a> {
|
|
||||||
rules: &'a str,
|
|
||||||
model: &'a str,
|
|
||||||
layout: &'a str,
|
|
||||||
variant: &'a str,
|
|
||||||
options: Option<String>,
|
|
||||||
}
|
|
||||||
let names: Names = deserialize(data)?;
|
|
||||||
let context = xkb::Context::new(0);
|
|
||||||
let keymap = Keymap::new_from_names(
|
|
||||||
&context,
|
|
||||||
names.rules,
|
|
||||||
names.model,
|
|
||||||
names.layout,
|
|
||||||
names.variant,
|
|
||||||
names.options,
|
|
||||||
XKB_KEYMAP_FORMAT_TEXT_V1,
|
|
||||||
)
|
|
||||||
.ok_or_else(|| anyhow!("Keymap is not valid"))?;
|
|
||||||
|
|
||||||
PanelItem::keyboard_activate_flex(node, &keymap)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn keyboard_activate_flex(node: &Node, keymap: &Keymap) -> Result<()> {
|
|
||||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
|
||||||
if let Some(keyboard) = panel_item.seat_data.keyboard() {
|
|
||||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
|
||||||
let mut keyboard_info = panel_item.seat_data.keyboard_info.lock();
|
|
||||||
if keyboard_info.is_none() {
|
|
||||||
keyboard.enter(0, &core_surface.wl_surface(), vec![]);
|
|
||||||
keyboard.repeat_info(0, 0);
|
|
||||||
}
|
|
||||||
keyboard_info.replace(KeyboardInfo::new(keymap));
|
|
||||||
keyboard_info.as_ref().unwrap().keymap.send(keyboard)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn keyboard_deactivate_flex(
|
|
||||||
node: &Node,
|
|
||||||
_calling_client: Arc<Client>,
|
|
||||||
_data: &[u8],
|
|
||||||
) -> Result<()> {
|
|
||||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
|
||||||
if let Some(keyboard) = panel_item.seat_data.keyboard() {
|
|
||||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
|
||||||
let mut keyboard_info = panel_item.seat_data.keyboard_info.lock();
|
|
||||||
if keyboard_info.is_some() {
|
|
||||||
keyboard.leave(0, &core_surface.wl_surface());
|
|
||||||
*keyboard_info = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn keyboard_key_state_flex(
|
|
||||||
node: &Node,
|
|
||||||
_calling_client: Arc<Client>,
|
|
||||||
data: &[u8],
|
|
||||||
) -> Result<()> {
|
|
||||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
|
||||||
if let Some(keyboard) = panel_item.seat_data.keyboard() {
|
|
||||||
let mut keyboard_info = panel_item.seat_data.keyboard_info.lock();
|
|
||||||
if let Some(keyboard_info) = &mut *keyboard_info {
|
|
||||||
let (key, state): (u32, u32) = deserialize(data)?;
|
|
||||||
keyboard_info.process(key, state, keyboard)?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resize_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
|
||||||
if let ItemType::Panel(panel_item) = &node.item.get().unwrap().specialization {
|
|
||||||
if let Some(core_surface) = panel_item.core_surface.upgrade() {
|
|
||||||
let size: Vector2<u32> = deserialize(data)?;
|
|
||||||
|
|
||||||
let toplevel_surface = core_surface
|
|
||||||
.wayland_state()
|
|
||||||
.lock()
|
|
||||||
.xdg_shell_state
|
|
||||||
.toplevel_surfaces(|surfaces| {
|
|
||||||
surfaces
|
|
||||||
.iter()
|
|
||||||
.find(|surf| surf.wl_surface().clone() == core_surface.wl_surface())
|
|
||||||
.cloned()
|
|
||||||
});
|
|
||||||
|
|
||||||
if let Some(toplevel_surface) = toplevel_surface {
|
|
||||||
let mut size_set = false;
|
|
||||||
toplevel_surface.with_pending_state(|state| {
|
|
||||||
state.size = Some(Size::default());
|
|
||||||
state.size.as_mut().unwrap().w = size.x as i32;
|
|
||||||
state.size.as_mut().unwrap().h = size.y as i32;
|
|
||||||
size_set = true;
|
|
||||||
});
|
|
||||||
if size_set {
|
|
||||||
toplevel_surface.send_configure();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl ItemSpecialization for PanelItem {
|
|
||||||
fn serialize_start_data(&self, id: &str) -> Vec<u8> {
|
|
||||||
// Panel size
|
|
||||||
let panel_size = self
|
|
||||||
.core_surface
|
|
||||||
.upgrade()
|
|
||||||
.unwrap()
|
|
||||||
.with_data(|data| data.size);
|
|
||||||
|
|
||||||
let cursor_lock = (*self.seat_data.cursor.lock()).clone();
|
|
||||||
let cursor_size = cursor_lock
|
|
||||||
.clone()
|
|
||||||
.and_then(|cursor| cursor.lock().core_surface.upgrade())
|
|
||||||
.and_then(|surf| surf.with_data(|data| data.size));
|
|
||||||
let cursor_hotspot = cursor_lock.map(|cursor| cursor.lock().hotspot);
|
|
||||||
|
|
||||||
serialize((id, (panel_size, cursor_size.zip(cursor_hotspot)))).unwrap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn register_panel_item_ui_flex(
|
|
||||||
_node: &Node,
|
|
||||||
calling_client: Arc<Client>,
|
|
||||||
_data: &[u8],
|
|
||||||
) -> Result<()> {
|
|
||||||
register_item_ui_flex(calling_client, &ITEM_TYPE_INFO_PANEL)
|
|
||||||
}
|
|
||||||
@@ -1,59 +1,81 @@
|
|||||||
use super::{state::WaylandState, surface::CoreSurface, GLOBAL_DESTROY_QUEUE};
|
use super::{
|
||||||
use crate::nodes::items::Item;
|
state::{ClientState, WaylandState},
|
||||||
use anyhow::Result;
|
surface::CoreSurface,
|
||||||
|
SERIAL_COUNTER,
|
||||||
|
};
|
||||||
|
use crate::{
|
||||||
|
core::task,
|
||||||
|
nodes::items::panel::{Backend, Geometry, PanelItem},
|
||||||
|
};
|
||||||
|
use color_eyre::eyre::{bail, eyre, Result};
|
||||||
use mint::Vector2;
|
use mint::Vector2;
|
||||||
use nanoid::nanoid;
|
use nanoid::nanoid;
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::OnceCell;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
use rand::{seq::IteratorRandom, thread_rng};
|
||||||
|
use rustc_hash::{FxHashMap, FxHashSet};
|
||||||
use smithay::{
|
use smithay::{
|
||||||
input::keyboard::{KeymapFile, ModifiersState},
|
input::keyboard::{KeymapFile, ModifiersState},
|
||||||
reexports::wayland_server::{
|
reexports::wayland_server::{
|
||||||
backend::{ClientId, GlobalId},
|
backend::{ClientId, GlobalId, ObjectId},
|
||||||
delegate_dispatch, delegate_global_dispatch,
|
|
||||||
protocol::{
|
protocol::{
|
||||||
wl_keyboard::{self, KeyState, WlKeyboard},
|
wl_keyboard::{self, KeyState, WlKeyboard},
|
||||||
wl_pointer::{self, WlPointer},
|
wl_pointer::{self, Axis, ButtonState, WlPointer},
|
||||||
wl_seat::{self, Capability, WlSeat, EVT_NAME_SINCE},
|
wl_seat::{self, Capability, WlSeat, EVT_NAME_SINCE},
|
||||||
|
wl_surface::WlSurface,
|
||||||
wl_touch::{self, WlTouch},
|
wl_touch::{self, WlTouch},
|
||||||
},
|
},
|
||||||
Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource,
|
Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource, Weak as WlWeak,
|
||||||
},
|
},
|
||||||
wayland::compositor,
|
wayland::compositor,
|
||||||
};
|
};
|
||||||
use std::sync::Arc;
|
use std::{
|
||||||
use std::{ops::Deref, sync::Weak};
|
collections::VecDeque,
|
||||||
use xkbcommon::xkb::{self, Keymap};
|
sync::Arc,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
use tokio::sync::watch;
|
||||||
|
use tracing::{debug, warn};
|
||||||
|
use xkbcommon::xkb::{self, ffi::XKB_KEYMAP_FORMAT_TEXT_V1, Keycode, Keymap};
|
||||||
|
|
||||||
pub struct Cursor {
|
pub fn handle_cursor<B: Backend>(
|
||||||
pub core_surface: Weak<CoreSurface>,
|
panel_item: &Arc<PanelItem<B>>,
|
||||||
pub hotspot: Vector2<i32>,
|
mut cursor: watch::Receiver<Option<CursorInfo>>,
|
||||||
|
) {
|
||||||
|
let panel_item_weak = Arc::downgrade(panel_item);
|
||||||
|
let _ = task::new(|| "cursor handler", async move {
|
||||||
|
while cursor.changed().await.is_ok() {
|
||||||
|
let Some(panel_item) = panel_item_weak.upgrade() else {continue};
|
||||||
|
let cursor_info = cursor.borrow();
|
||||||
|
panel_item.set_cursor(cursor_info.as_ref().and_then(CursorInfo::cursor_data));
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct KeyboardInfo {
|
pub struct KeyboardInfo {
|
||||||
pub keymap: KeymapFile,
|
keymap_string: String,
|
||||||
pub state: xkb::State,
|
keymap: KeymapFile,
|
||||||
pub mods: ModifiersState,
|
state: xkb::State,
|
||||||
|
mods: ModifiersState,
|
||||||
|
keys: FxHashSet<u32>,
|
||||||
}
|
}
|
||||||
impl KeyboardInfo {
|
impl KeyboardInfo {
|
||||||
pub fn new(keymap: &Keymap) -> Self {
|
pub fn new(keymap_string: String, keymap: &Keymap) -> Self {
|
||||||
KeyboardInfo {
|
KeyboardInfo {
|
||||||
|
keymap_string,
|
||||||
state: xkb::State::new(keymap),
|
state: xkb::State::new(keymap),
|
||||||
keymap: KeymapFile::new(keymap, None),
|
keymap: KeymapFile::new(keymap),
|
||||||
mods: ModifiersState::default(),
|
mods: ModifiersState::default(),
|
||||||
|
keys: FxHashSet::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn process(&mut self, key: u32, state: u32, keyboard: &WlKeyboard) -> Result<()> {
|
pub fn process(&mut self, key: u32, pressed: bool, keyboard: &WlKeyboard) -> Result<usize> {
|
||||||
let wl_key_state = match state {
|
let xkb_key_state = if pressed {
|
||||||
0 => KeyState::Released,
|
xkb::KeyDirection::Down
|
||||||
1 => KeyState::Pressed,
|
} else {
|
||||||
_ => anyhow::bail!("Invalid key state!"),
|
xkb::KeyDirection::Up
|
||||||
};
|
};
|
||||||
let xkb_key_state = match state {
|
let state_components = self.state.update_key(Keycode::new(key + 8), xkb_key_state);
|
||||||
0 => xkb::KeyDirection::Up,
|
|
||||||
1 => xkb::KeyDirection::Down,
|
|
||||||
_ => anyhow::bail!("Invalid key state!"),
|
|
||||||
};
|
|
||||||
let state_components = self.state.update_key(key + 8, xkb_key_state);
|
|
||||||
if state_components != 0 {
|
if state_components != 0 {
|
||||||
self.mods.update_with(&self.state);
|
self.mods.update_with(&self.state);
|
||||||
keyboard.modifiers(
|
keyboard.modifiers(
|
||||||
@@ -64,85 +86,400 @@ impl KeyboardInfo {
|
|||||||
0,
|
0,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
keyboard.key(0, 0, key, wl_key_state);
|
// if pressed {
|
||||||
Ok(())
|
// println!("Key {key} is being pressed with {state_components} modifiers");
|
||||||
|
// } else {
|
||||||
|
// println!("Key {key} is being released with {state_components} modifiers");
|
||||||
|
// }
|
||||||
|
|
||||||
|
let wl_key_state = if pressed {
|
||||||
|
KeyState::Pressed
|
||||||
|
} else {
|
||||||
|
KeyState::Released
|
||||||
|
};
|
||||||
|
keyboard.key(SERIAL_COUNTER.inc(), 0, key, wl_key_state);
|
||||||
|
match wl_key_state {
|
||||||
|
KeyState::Pressed => {
|
||||||
|
self.keys.insert(key);
|
||||||
|
}
|
||||||
|
KeyState::Released => {
|
||||||
|
self.keys.remove(&key);
|
||||||
|
}
|
||||||
|
_ => unimplemented!(),
|
||||||
|
}
|
||||||
|
Ok(self.keys.len())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
unsafe impl Send for KeyboardInfo {}
|
unsafe impl Send for KeyboardInfo {}
|
||||||
|
|
||||||
pub struct SeatDelegate;
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub enum PointerEvent {
|
||||||
#[derive(Clone)]
|
Motion(Vector2<f32>),
|
||||||
pub struct SeatData(Arc<SeatDataInner>);
|
Button {
|
||||||
impl SeatData {
|
button: u32,
|
||||||
pub fn new(dh: &DisplayHandle, client: ClientId) -> Self {
|
state: u32,
|
||||||
let seat_data = SeatData(Arc::new(SeatDataInner {
|
},
|
||||||
client,
|
Scroll {
|
||||||
global_id: OnceCell::new(),
|
axis_continuous: Option<Vector2<f32>>,
|
||||||
panel_item: OnceCell::new(),
|
axis_discrete: Option<Vector2<f32>>,
|
||||||
cursor: Mutex::new(None),
|
},
|
||||||
cursor_changed: Mutex::new(false),
|
}
|
||||||
pointer: OnceCell::new(),
|
#[derive(Debug, Clone)]
|
||||||
pointer_active: Mutex::new(false),
|
pub enum KeyboardEvent {
|
||||||
keyboard: OnceCell::new(),
|
Keymap,
|
||||||
keyboard_info: Mutex::new(None),
|
Key { key: u32, state: bool },
|
||||||
touch: OnceCell::new(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
seat_data
|
|
||||||
.global_id
|
|
||||||
.set(dh.create_global::<WaylandState, _, _>(7, seat_data.clone()))
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
seat_data
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
impl Deref for SeatData {
|
|
||||||
type Target = SeatDataInner;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
const POINTER_EVENT_TIMEOUT: Duration = Duration::from_millis(50);
|
||||||
&self.0
|
struct SurfaceInfo {
|
||||||
|
wl_surface: WlWeak<WlSurface>,
|
||||||
|
cursor_sender: watch::Sender<Option<CursorInfo>>,
|
||||||
|
pointer_queue: VecDeque<PointerEvent>,
|
||||||
|
pointer_latest_event: Instant,
|
||||||
|
keyboard_queue: VecDeque<KeyboardEvent>,
|
||||||
|
keyboard_info: Option<KeyboardInfo>,
|
||||||
|
}
|
||||||
|
impl SurfaceInfo {
|
||||||
|
fn new(wl_surface: &WlSurface, cursor_sender: watch::Sender<Option<CursorInfo>>) -> Self {
|
||||||
|
SurfaceInfo {
|
||||||
|
wl_surface: wl_surface.downgrade(),
|
||||||
|
cursor_sender,
|
||||||
|
pointer_queue: VecDeque::new(),
|
||||||
|
pointer_latest_event: Instant::now(),
|
||||||
|
keyboard_queue: VecDeque::new(),
|
||||||
|
keyboard_info: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn flush(&self) {
|
||||||
|
if let Some(client) = self.wl_surface.upgrade().ok().and_then(|s| s.client()) {
|
||||||
|
if let Some(client_data) = client.get_data::<ClientState>() {
|
||||||
|
client_data.flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn handle_pointer_events(&mut self, pointer: &WlPointer, mut locked: bool) -> bool {
|
||||||
|
let Ok(focus) = self.wl_surface.upgrade() else { return false; };
|
||||||
|
let Some(core_surface) = CoreSurface::from_wl_surface(&focus) else { return false; };
|
||||||
|
let Some(focus_size) = core_surface.size() else { return false; };
|
||||||
|
|
||||||
|
if !self.pointer_queue.is_empty() {
|
||||||
|
self.pointer_latest_event = Instant::now();
|
||||||
|
}
|
||||||
|
while let Some(event) = self.pointer_queue.pop_front() {
|
||||||
|
match (locked, event) {
|
||||||
|
(false, PointerEvent::Motion(pos)) => {
|
||||||
|
pointer.enter(
|
||||||
|
SERIAL_COUNTER.inc(),
|
||||||
|
&focus,
|
||||||
|
(pos.x as f64).clamp(0.0, focus_size.x as f64),
|
||||||
|
(pos.y as f64).clamp(0.0, focus_size.y as f64),
|
||||||
|
);
|
||||||
|
locked = true;
|
||||||
|
}
|
||||||
|
(true, PointerEvent::Motion(pos)) => {
|
||||||
|
pointer.motion(
|
||||||
|
0,
|
||||||
|
(pos.x as f64).clamp(0.0, focus_size.x as f64),
|
||||||
|
(pos.y as f64).clamp(0.0, focus_size.y as f64),
|
||||||
|
);
|
||||||
|
if pointer.version() >= wl_pointer::EVT_FRAME_SINCE {
|
||||||
|
pointer.frame();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(true, PointerEvent::Button { button, state }) => {
|
||||||
|
pointer.button(
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
button,
|
||||||
|
match state {
|
||||||
|
0 => ButtonState::Released,
|
||||||
|
1 => ButtonState::Pressed,
|
||||||
|
_ => continue,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if pointer.version() >= wl_pointer::EVT_FRAME_SINCE {
|
||||||
|
pointer.frame();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(
|
||||||
|
true,
|
||||||
|
PointerEvent::Scroll {
|
||||||
|
axis_continuous,
|
||||||
|
axis_discrete,
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
if let Some(axis_continuous) = axis_continuous {
|
||||||
|
pointer.axis(0, Axis::HorizontalScroll, axis_continuous.x as f64);
|
||||||
|
pointer.axis(0, Axis::VerticalScroll, -axis_continuous.y as f64);
|
||||||
|
}
|
||||||
|
if pointer.version() >= wl_pointer::EVT_AXIS_DISCRETE_SINCE {
|
||||||
|
if let Some(axis_discrete) = axis_discrete {
|
||||||
|
pointer.axis_discrete(Axis::HorizontalScroll, axis_discrete.x as i32);
|
||||||
|
pointer.axis_discrete(Axis::VerticalScroll, -axis_discrete.y as i32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if pointer.version() >= wl_pointer::EVT_AXIS_STOP_SINCE
|
||||||
|
&& axis_discrete.is_none()
|
||||||
|
&& axis_continuous.is_none()
|
||||||
|
{
|
||||||
|
pointer.axis_stop(0, Axis::HorizontalScroll);
|
||||||
|
pointer.axis_stop(0, Axis::VerticalScroll);
|
||||||
|
}
|
||||||
|
if pointer.version() >= wl_pointer::EVT_FRAME_SINCE {
|
||||||
|
pointer.frame();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(locked, event) => {
|
||||||
|
warn!(locked, ?event, "Invalid pointer event!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.pointer_latest_event.elapsed() > POINTER_EVENT_TIMEOUT {
|
||||||
|
pointer.leave(SERIAL_COUNTER.inc(), &focus);
|
||||||
|
locked = false;
|
||||||
|
}
|
||||||
|
self.flush();
|
||||||
|
|
||||||
|
locked
|
||||||
|
}
|
||||||
|
fn handle_keyboard_events(&mut self, keyboard: &WlKeyboard, mut locked: bool) -> bool {
|
||||||
|
let Ok(focus) = self.wl_surface.upgrade() else { return false; };
|
||||||
|
let Some(info) = self.keyboard_info.as_mut() else { return true; };
|
||||||
|
|
||||||
|
if !locked {
|
||||||
|
keyboard.enter(0, &focus, vec![]);
|
||||||
|
if keyboard.version() >= wl_keyboard::EVT_REPEAT_INFO_SINCE {
|
||||||
|
keyboard.repeat_info(0, 0);
|
||||||
|
}
|
||||||
|
locked = info.keymap.send(keyboard).is_ok();
|
||||||
|
}
|
||||||
|
while let Some(event) = self.keyboard_queue.pop_front() {
|
||||||
|
debug!(locked, ?event, "Process keyboard event");
|
||||||
|
match (locked, event) {
|
||||||
|
(true, KeyboardEvent::Keymap) => {
|
||||||
|
let _ = info.keymap.send(keyboard);
|
||||||
|
}
|
||||||
|
(true, KeyboardEvent::Key { key, state }) => {
|
||||||
|
if let Ok(key_count) = info.process(key, state, keyboard) {
|
||||||
|
if key_count == 0 {
|
||||||
|
keyboard.leave(SERIAL_COUNTER.inc(), &focus);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(locked, event) => {
|
||||||
|
warn!(locked, ?event, "Invalid keyboard event!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.flush();
|
||||||
|
locked
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct SeatDataInner {
|
pub struct SeatData {
|
||||||
client: ClientId,
|
pub client: OnceCell<ClientId>,
|
||||||
pub global_id: OnceCell<GlobalId>,
|
global_id: OnceCell<GlobalId>,
|
||||||
pub panel_item: OnceCell<Weak<Item>>,
|
surfaces: Mutex<FxHashMap<ObjectId, SurfaceInfo>>,
|
||||||
pub cursor: Mutex<Option<Arc<Mutex<Cursor>>>>,
|
pointer: OnceCell<(WlPointer, Mutex<ObjectId>)>,
|
||||||
pub cursor_changed: Mutex<bool>,
|
keyboard: OnceCell<(WlKeyboard, Mutex<ObjectId>)>,
|
||||||
pointer: OnceCell<WlPointer>,
|
|
||||||
pub pointer_active: Mutex<bool>,
|
|
||||||
keyboard: OnceCell<WlKeyboard>,
|
|
||||||
pub keyboard_info: Mutex<Option<KeyboardInfo>>,
|
|
||||||
touch: OnceCell<WlTouch>,
|
touch: OnceCell<WlTouch>,
|
||||||
|
touches: Mutex<FxHashMap<ObjectId, u32>>,
|
||||||
}
|
}
|
||||||
impl SeatDataInner {
|
impl SeatData {
|
||||||
pub fn pointer(&self) -> Option<&WlPointer> {
|
pub fn new(dh: &DisplayHandle) -> Arc<Self> {
|
||||||
self.pointer.get()
|
let seat_data = Arc::new(SeatData {
|
||||||
|
client: OnceCell::new(),
|
||||||
|
global_id: OnceCell::new(),
|
||||||
|
surfaces: Mutex::new(FxHashMap::default()),
|
||||||
|
pointer: OnceCell::new(),
|
||||||
|
keyboard: OnceCell::new(),
|
||||||
|
touch: OnceCell::new(),
|
||||||
|
touches: Mutex::new(FxHashMap::default()),
|
||||||
|
});
|
||||||
|
|
||||||
|
let _ = seat_data
|
||||||
|
.global_id
|
||||||
|
.set(dh.create_global::<WaylandState, _, _>(7, seat_data.clone()));
|
||||||
|
|
||||||
|
seat_data
|
||||||
}
|
}
|
||||||
pub fn keyboard(&self) -> Option<&WlKeyboard> {
|
|
||||||
self.keyboard.get()
|
pub fn set_keymap(&self, keymap_str: String, surfaces: Vec<WlSurface>) -> Result<()> {
|
||||||
|
let context = xkb::Context::new(0);
|
||||||
|
let keymap =
|
||||||
|
Keymap::new_from_string(&context, keymap_str.clone(), XKB_KEYMAP_FORMAT_TEXT_V1, 0)
|
||||||
|
.ok_or_else(|| eyre!("Keymap is not valid"))?;
|
||||||
|
let mut panels = self.surfaces.lock();
|
||||||
|
let Some((_, focus)) = self.keyboard.get() else {bail!("Could not get keyboard")};
|
||||||
|
for surface in surfaces {
|
||||||
|
let Some(surface_info) = panels.get_mut(&surface.id()) else {continue};
|
||||||
|
if let Some(keyboard_info) = &mut surface_info.keyboard_info {
|
||||||
|
if &keyboard_info.keymap_string == &keymap_str {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
surface_info
|
||||||
|
.keyboard_info
|
||||||
|
.replace(KeyboardInfo::new(keymap_str.clone(), &keymap));
|
||||||
|
|
||||||
|
if *focus.lock() == surface.id() {
|
||||||
|
surface_info.keyboard_queue.push_back(KeyboardEvent::Keymap);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
#[allow(dead_code)]
|
|
||||||
pub fn touch(&self) -> Option<&WlTouch> {
|
pub fn pointer_event(&self, surface: &WlSurface, event: PointerEvent) {
|
||||||
self.touch.get()
|
let mut surfaces = self.surfaces.lock();
|
||||||
|
let Some(surface_info) = surfaces.get_mut(&surface.id()) else {return};
|
||||||
|
surface_info.pointer_queue.push_back(event);
|
||||||
|
drop(surfaces);
|
||||||
|
self.handle_pointer_events();
|
||||||
}
|
}
|
||||||
}
|
pub fn keyboard_event(&self, surface: &WlSurface, event: KeyboardEvent) {
|
||||||
impl Drop for SeatDataInner {
|
let mut surfaces = self.surfaces.lock();
|
||||||
fn drop(&mut self) {
|
let Some(surface_info) = surfaces.get_mut(&surface.id()) else {return};
|
||||||
let id = self.global_id.take().unwrap();
|
surface_info.keyboard_queue.push_back(event);
|
||||||
tokio::spawn(async move { GLOBAL_DESTROY_QUEUE.get().unwrap().send(id).await });
|
drop(surfaces);
|
||||||
|
self.handle_keyboard_events();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle_pointer_events(&self) {
|
||||||
|
let mut surfaces = self.surfaces.lock();
|
||||||
|
let Some((pointer, pointer_focus)) = self.pointer.get() else {return};
|
||||||
|
let mut pointer_focus = pointer_focus.lock();
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let locked = !pointer_focus.is_null();
|
||||||
|
// Pick a pointer to focus on if there is none
|
||||||
|
if pointer_focus.is_null() {
|
||||||
|
*pointer_focus = surfaces
|
||||||
|
.iter()
|
||||||
|
.filter(|(_k, v)| !v.pointer_queue.is_empty())
|
||||||
|
.map(|(k, _v)| k)
|
||||||
|
.choose(&mut thread_rng())
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or(ObjectId::null());
|
||||||
|
}
|
||||||
|
if pointer_focus.is_null() {
|
||||||
|
// If there's still none, guess we're done with pointer events for the time being
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let Some(surface_info) = surfaces.get_mut(&pointer_focus) else {break};
|
||||||
|
if surface_info.handle_pointer_events(pointer, locked) {
|
||||||
|
// We haven't gotten to a point where we can switch the focus
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
*pointer_focus = ObjectId::null();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn handle_keyboard_events(&self) {
|
||||||
|
let mut surfaces = self.surfaces.lock();
|
||||||
|
let Some((keyboard, keyboard_focus)) = self.keyboard.get() else {return};
|
||||||
|
let mut keyboard_focus = keyboard_focus.lock();
|
||||||
|
loop {
|
||||||
|
let locked = !keyboard_focus.is_null();
|
||||||
|
// Pick a keyboard to focus on if there is none
|
||||||
|
if keyboard_focus.is_null() {
|
||||||
|
*keyboard_focus = surfaces
|
||||||
|
.iter()
|
||||||
|
.filter(|(_k, v)| v.keyboard_info.is_some())
|
||||||
|
.filter(|(_k, v)| !v.keyboard_queue.is_empty())
|
||||||
|
.map(|(k, _v)| k)
|
||||||
|
.choose(&mut thread_rng())
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or(ObjectId::null());
|
||||||
|
}
|
||||||
|
// If there's still none, guess we're done with keyboard events for the time being
|
||||||
|
let Some(surface_info) = surfaces.get_mut(&keyboard_focus) else {break};
|
||||||
|
if surface_info.handle_keyboard_events(keyboard, locked) {
|
||||||
|
// We haven't gotten to a point where we can switch the focus
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
*keyboard_focus = ObjectId::null();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_surface(&self, surface: &WlSurface) -> watch::Receiver<Option<CursorInfo>> {
|
||||||
|
let (tx, rx) = watch::channel(None);
|
||||||
|
self.surfaces
|
||||||
|
.lock()
|
||||||
|
.insert(surface.id(), SurfaceInfo::new(surface, tx));
|
||||||
|
|
||||||
|
rx
|
||||||
|
}
|
||||||
|
pub fn drop_surface(&self, surface: &WlSurface) {
|
||||||
|
self.surfaces.lock().remove(&surface.id());
|
||||||
|
if let Some((_, pointer_focus)) = self.pointer.get() {
|
||||||
|
let mut pointer_focus = pointer_focus.lock();
|
||||||
|
if *pointer_focus == surface.id() {
|
||||||
|
*pointer_focus = ObjectId::null();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some((_, keyboard_focus)) = self.keyboard.get() {
|
||||||
|
let mut keyboard_focus = keyboard_focus.lock();
|
||||||
|
if *keyboard_focus == surface.id() {
|
||||||
|
*keyboard_focus = ObjectId::null();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.touches.lock().remove(&surface.id());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn touch_down(&self, surface: &WlSurface, id: u32, position: Vector2<f32>) {
|
||||||
|
let Some(touch) = self.touch.get() else {return};
|
||||||
|
touch.down(
|
||||||
|
SERIAL_COUNTER.inc(),
|
||||||
|
0,
|
||||||
|
surface,
|
||||||
|
id as i32,
|
||||||
|
position.x as f64,
|
||||||
|
position.y as f64,
|
||||||
|
);
|
||||||
|
self.touches.lock().insert(surface.id(), id);
|
||||||
|
}
|
||||||
|
pub fn touch_move(&self, id: u32, position: Vector2<f32>) {
|
||||||
|
let Some(touch) = self.touch.get() else {return};
|
||||||
|
touch.motion(0, id as i32, position.x as f64, position.y as f64);
|
||||||
|
}
|
||||||
|
pub fn touch_up(&self, id: u32) {
|
||||||
|
let Some(touch) = self.touch.get() else {return};
|
||||||
|
touch.up(SERIAL_COUNTER.inc(), 0, id as i32);
|
||||||
|
let mut touches = self.touches.lock();
|
||||||
|
touches.retain(|_, tid| *tid != id);
|
||||||
|
}
|
||||||
|
pub fn reset_touches(&self) {
|
||||||
|
let Some(touch) = self.touch.get() else {return};
|
||||||
|
for (_, touch_id) in self.touches.lock().drain() {
|
||||||
|
touch.up(SERIAL_COUNTER.inc(), 0, touch_id as i32);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GlobalDispatch<WlSeat, SeatData, WaylandState> for SeatDelegate {
|
pub struct CursorInfo {
|
||||||
|
pub surface: WlWeak<WlSurface>,
|
||||||
|
pub hotspot_x: i32,
|
||||||
|
pub hotspot_y: i32,
|
||||||
|
}
|
||||||
|
impl CursorInfo {
|
||||||
|
pub fn cursor_data(&self) -> Option<Geometry> {
|
||||||
|
let cursor_size = CoreSurface::from_wl_surface(&self.surface.upgrade().ok()?)?.size()?;
|
||||||
|
Some(Geometry {
|
||||||
|
origin: [self.hotspot_x, self.hotspot_y].into(),
|
||||||
|
size: cursor_size,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GlobalDispatch<WlSeat, Arc<SeatData>, WaylandState> for WaylandState {
|
||||||
fn bind(
|
fn bind(
|
||||||
_state: &mut WaylandState,
|
_state: &mut WaylandState,
|
||||||
_handle: &DisplayHandle,
|
_handle: &DisplayHandle,
|
||||||
_client: &Client,
|
_client: &Client,
|
||||||
resource: New<WlSeat>,
|
resource: New<WlSeat>,
|
||||||
data: &SeatData,
|
data: &Arc<SeatData>,
|
||||||
data_init: &mut DataInit<'_, WaylandState>,
|
data_init: &mut DataInit<'_, WaylandState>,
|
||||||
) {
|
) {
|
||||||
let resource = data_init.init(resource, data.clone());
|
let resource = data_init.init(resource, data.clone());
|
||||||
@@ -151,51 +488,53 @@ impl GlobalDispatch<WlSeat, SeatData, WaylandState> for SeatDelegate {
|
|||||||
resource.name(nanoid!());
|
resource.name(nanoid!());
|
||||||
}
|
}
|
||||||
|
|
||||||
resource.capabilities(Capability::Pointer | Capability::Keyboard);
|
resource.capabilities(Capability::Pointer | Capability::Keyboard | Capability::Touch);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn can_view(client: Client, data: &SeatData) -> bool {
|
fn can_view(client: Client, data: &Arc<SeatData>) -> bool {
|
||||||
client.id() == data.0.client
|
let Some(seat_client) = data.client.get().cloned() else {return false};
|
||||||
|
client.id() == seat_client
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
delegate_global_dispatch!(WaylandState: [WlSeat: SeatData] => SeatDelegate);
|
|
||||||
|
|
||||||
impl Dispatch<WlSeat, SeatData, WaylandState> for SeatDelegate {
|
impl Dispatch<WlSeat, Arc<SeatData>, WaylandState> for WaylandState {
|
||||||
fn request(
|
fn request(
|
||||||
_state: &mut WaylandState,
|
_state: &mut WaylandState,
|
||||||
_client: &Client,
|
_client: &Client,
|
||||||
_resource: &WlSeat,
|
_resource: &WlSeat,
|
||||||
request: <WlSeat as Resource>::Request,
|
request: wl_seat::Request,
|
||||||
data: &SeatData,
|
data: &Arc<SeatData>,
|
||||||
_dh: &DisplayHandle,
|
_dh: &DisplayHandle,
|
||||||
data_init: &mut DataInit<'_, WaylandState>,
|
data_init: &mut DataInit<'_, WaylandState>,
|
||||||
) {
|
) {
|
||||||
match request {
|
match request {
|
||||||
wl_seat::Request::GetPointer { id } => {
|
wl_seat::Request::GetPointer { id } => {
|
||||||
let _ = data.0.pointer.set(data_init.init(id, data.clone()));
|
let pointer = data_init.init(id, data.clone());
|
||||||
|
let _ = data.pointer.set((pointer, Mutex::new(ObjectId::null())));
|
||||||
}
|
}
|
||||||
wl_seat::Request::GetKeyboard { id } => {
|
wl_seat::Request::GetKeyboard { id } => {
|
||||||
let keyboard = data_init.init(id, data.clone());
|
let keyboard = data_init.init(id, data.clone());
|
||||||
keyboard.repeat_info(0, 0);
|
if keyboard.version() >= wl_keyboard::EVT_REPEAT_INFO_SINCE {
|
||||||
let _ = data.0.keyboard.set(keyboard);
|
keyboard.repeat_info(0, 0);
|
||||||
|
}
|
||||||
|
let _ = data.keyboard.set((keyboard, Mutex::new(ObjectId::null())));
|
||||||
}
|
}
|
||||||
wl_seat::Request::GetTouch { id } => {
|
wl_seat::Request::GetTouch { id } => {
|
||||||
let _ = data.0.touch.set(data_init.init(id, data.clone()));
|
let _ = data.touch.set(data_init.init(id, data.clone()));
|
||||||
}
|
}
|
||||||
wl_seat::Request::Release => (),
|
wl_seat::Request::Release => (),
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
delegate_dispatch!(WaylandState: [WlSeat: SeatData] => SeatDelegate);
|
|
||||||
|
|
||||||
impl Dispatch<WlPointer, SeatData, WaylandState> for SeatDelegate {
|
impl Dispatch<WlPointer, Arc<SeatData>, WaylandState> for WaylandState {
|
||||||
fn request(
|
fn request(
|
||||||
state: &mut WaylandState,
|
_state: &mut WaylandState,
|
||||||
_client: &Client,
|
_client: &Client,
|
||||||
_resource: &WlPointer,
|
_resource: &WlPointer,
|
||||||
request: <WlPointer as Resource>::Request,
|
request: wl_pointer::Request,
|
||||||
seat_data: &SeatData,
|
seat_data: &Arc<SeatData>,
|
||||||
dh: &DisplayHandle,
|
dh: &DisplayHandle,
|
||||||
_data_init: &mut DataInit<'_, WaylandState>,
|
_data_init: &mut DataInit<'_, WaylandState>,
|
||||||
) {
|
) {
|
||||||
@@ -206,54 +545,39 @@ impl Dispatch<WlPointer, SeatData, WaylandState> for SeatDelegate {
|
|||||||
hotspot_x,
|
hotspot_x,
|
||||||
hotspot_y,
|
hotspot_y,
|
||||||
} => {
|
} => {
|
||||||
if !*seat_data.pointer_active.lock() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
*seat_data.0.cursor_changed.lock() = true;
|
|
||||||
if let Some(surface) = surface.as_ref() {
|
if let Some(surface) = surface.as_ref() {
|
||||||
|
CoreSurface::add_to(dh.clone(), surface, || (), |_| ());
|
||||||
compositor::with_states(surface, |data| {
|
compositor::with_states(surface, |data| {
|
||||||
data.data_map.insert_if_missing_threadsafe(|| {
|
if let Some(core_surface) = data.data_map.get::<Arc<CoreSurface>>() {
|
||||||
CoreSurface::new(
|
core_surface.set_material_offset(1);
|
||||||
&state.weak_ref.upgrade().unwrap(),
|
|
||||||
&state.display,
|
|
||||||
dh.clone(),
|
|
||||||
surface,
|
|
||||||
)
|
|
||||||
});
|
|
||||||
if !data.data_map.insert_if_missing_threadsafe(|| {
|
|
||||||
Arc::new(Mutex::new(Cursor {
|
|
||||||
core_surface: Arc::downgrade(
|
|
||||||
data.data_map.get::<Arc<CoreSurface>>().unwrap(),
|
|
||||||
),
|
|
||||||
hotspot: Vector2::from([hotspot_x, hotspot_y]),
|
|
||||||
}))
|
|
||||||
}) {
|
|
||||||
let mut cursor =
|
|
||||||
data.data_map.get::<Arc<Mutex<Cursor>>>().unwrap().lock();
|
|
||||||
cursor.hotspot = Vector2::from([hotspot_x, hotspot_y]);
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
*seat_data.cursor.lock() = surface.and_then(|surf| {
|
|
||||||
compositor::with_states(&surf, |data| {
|
let Some((_, focus)) = seat_data.pointer.get() else {return};
|
||||||
data.data_map.get::<Arc<Mutex<Cursor>>>().cloned()
|
let focus = focus.lock();
|
||||||
})
|
let surfaces = seat_data.surfaces.lock();
|
||||||
|
let Some(surface_info) = surfaces.get(&focus) else {return};
|
||||||
|
let cursor_info = surface.map(|surface| CursorInfo {
|
||||||
|
surface: surface.downgrade(),
|
||||||
|
hotspot_x,
|
||||||
|
hotspot_y,
|
||||||
});
|
});
|
||||||
|
let _ = surface_info.cursor_sender.send_replace(cursor_info);
|
||||||
}
|
}
|
||||||
wl_pointer::Request::Release => (),
|
wl_pointer::Request::Release => (),
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
delegate_dispatch!(WaylandState: [WlPointer: SeatData] => SeatDelegate);
|
|
||||||
|
|
||||||
impl Dispatch<WlKeyboard, SeatData, WaylandState> for SeatDelegate {
|
impl Dispatch<WlKeyboard, Arc<SeatData>, WaylandState> for WaylandState {
|
||||||
fn request(
|
fn request(
|
||||||
_state: &mut WaylandState,
|
_state: &mut WaylandState,
|
||||||
_client: &Client,
|
_client: &Client,
|
||||||
_resource: &WlKeyboard,
|
_resource: &WlKeyboard,
|
||||||
request: <WlKeyboard as Resource>::Request,
|
request: <WlKeyboard as Resource>::Request,
|
||||||
_data: &SeatData,
|
_data: &Arc<SeatData>,
|
||||||
_dh: &DisplayHandle,
|
_dh: &DisplayHandle,
|
||||||
_data_init: &mut DataInit<'_, WaylandState>,
|
_data_init: &mut DataInit<'_, WaylandState>,
|
||||||
) {
|
) {
|
||||||
@@ -263,15 +587,14 @@ impl Dispatch<WlKeyboard, SeatData, WaylandState> for SeatDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
delegate_dispatch!(WaylandState: [WlKeyboard: SeatData] => SeatDelegate);
|
|
||||||
|
|
||||||
impl Dispatch<WlTouch, SeatData, WaylandState> for SeatDelegate {
|
impl Dispatch<WlTouch, Arc<SeatData>, WaylandState> for WaylandState {
|
||||||
fn request(
|
fn request(
|
||||||
_state: &mut WaylandState,
|
_state: &mut WaylandState,
|
||||||
_client: &Client,
|
_client: &Client,
|
||||||
_resource: &WlTouch,
|
_resource: &WlTouch,
|
||||||
request: <WlTouch as Resource>::Request,
|
request: <WlTouch as Resource>::Request,
|
||||||
_data: &SeatData,
|
_data: &Arc<SeatData>,
|
||||||
_dh: &DisplayHandle,
|
_dh: &DisplayHandle,
|
||||||
_data_init: &mut DataInit<'_, WaylandState>,
|
_data_init: &mut DataInit<'_, WaylandState>,
|
||||||
) {
|
) {
|
||||||
@@ -281,4 +604,3 @@ impl Dispatch<WlTouch, SeatData, WaylandState> for SeatDelegate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
delegate_dispatch!(WaylandState: [WlTouch: SeatData] => SeatDelegate);
|
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
#![allow(dead_code)]
|
|
||||||
|
|
||||||
// Basic gamma correction shader
|
|
||||||
// pub const PANEL_SHADER_BYTES: &[u8] = include_bytes!("shader_unlit_gamma.sks");
|
|
||||||
|
|
||||||
// Simula shader with fancy lanzcos sampling
|
|
||||||
pub const PANEL_SHADER_BYTES: &[u8] = include_bytes!("shader_unlit_simula.sks");
|
|
||||||
@@ -1,41 +1,60 @@
|
|||||||
use crate::wayland::seat::SeatData;
|
use crate::wayland::seat::SeatData;
|
||||||
|
use once_cell::sync::OnceCell;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use rustc_hash::FxHashMap;
|
|
||||||
use slog::Logger;
|
|
||||||
use smithay::{
|
use smithay::{
|
||||||
delegate_output, delegate_shm,
|
backend::{allocator::dmabuf::Dmabuf, egl::EGLDevice, renderer::gles::GlesRenderer},
|
||||||
output::{Output, Scale, Subpixel},
|
delegate_dmabuf, delegate_output, delegate_shm,
|
||||||
|
output::{Mode, Output, Scale, Subpixel},
|
||||||
reexports::{
|
reexports::{
|
||||||
wayland_protocols_misc::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode,
|
wayland_protocols::xdg::{
|
||||||
|
decoration::zv1::server::zxdg_decoration_manager_v1::ZxdgDecorationManagerV1,
|
||||||
|
shell::server::xdg_wm_base::XdgWmBase,
|
||||||
|
},
|
||||||
|
wayland_protocols_misc::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode as DecorationMode,
|
||||||
wayland_server::{
|
wayland_server::{
|
||||||
backend::{ClientData, ClientId, DisconnectReason},
|
backend::{ClientData, ClientId, DisconnectReason},
|
||||||
protocol::wl_data_device_manager::WlDataDeviceManager,
|
protocol::{wl_buffer::WlBuffer, wl_data_device_manager::WlDataDeviceManager},
|
||||||
Display, DisplayHandle,
|
DisplayHandle,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
utils::Size,
|
utils::{Size, Transform},
|
||||||
wayland::{
|
wayland::{
|
||||||
buffer::BufferHandler,
|
buffer::BufferHandler,
|
||||||
compositor::CompositorState,
|
compositor::{CompositorClientState, CompositorState},
|
||||||
output::OutputManagerState,
|
dmabuf::{
|
||||||
shell::{
|
self, DmabufFeedback, DmabufFeedbackBuilder, DmabufGlobal, DmabufHandler, DmabufState,
|
||||||
kde::decoration::KdeDecorationState,
|
ImportError,
|
||||||
xdg::{decoration::XdgDecorationState, XdgShellState},
|
|
||||||
},
|
},
|
||||||
|
shell::kde::decoration::KdeDecorationState,
|
||||||
shm::{ShmHandler, ShmState},
|
shm::{ShmHandler, ShmState},
|
||||||
xdg_activation::XdgActivationState,
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use std::sync::{Arc, Weak};
|
use std::sync::{Arc, Weak};
|
||||||
|
use tokio::sync::mpsc::UnboundedSender;
|
||||||
|
use tracing::{info, warn};
|
||||||
|
|
||||||
pub struct ClientState;
|
use super::DisplayWrapper;
|
||||||
|
|
||||||
|
pub struct ClientState {
|
||||||
|
pub id: OnceCell<ClientId>,
|
||||||
|
pub compositor_state: CompositorClientState,
|
||||||
|
pub display: Weak<DisplayWrapper>,
|
||||||
|
pub seat: Arc<SeatData>,
|
||||||
|
}
|
||||||
|
impl ClientState {
|
||||||
|
pub fn flush(&self) {
|
||||||
|
let Some(display) = self.display.upgrade() else {return};
|
||||||
|
let _ = display.flush_clients(self.id.get().cloned());
|
||||||
|
}
|
||||||
|
}
|
||||||
impl ClientData for ClientState {
|
impl ClientData for ClientState {
|
||||||
fn initialized(&self, client_id: ClientId) {
|
fn initialized(&self, client_id: ClientId) {
|
||||||
println!("Wayland client {:?} connected", client_id);
|
info!("Wayland client {:?} connected", client_id);
|
||||||
|
let _ = self.id.set(client_id);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn disconnected(&self, client_id: ClientId, reason: DisconnectReason) {
|
fn disconnected(&self, client_id: ClientId, reason: DisconnectReason) {
|
||||||
println!(
|
info!(
|
||||||
"Wayland client {:?} disconnected because {:#?}",
|
"Wayland client {:?} disconnected because {:#?}",
|
||||||
client_id, reason
|
client_id, reason
|
||||||
);
|
);
|
||||||
@@ -44,34 +63,66 @@ impl ClientData for ClientState {
|
|||||||
|
|
||||||
pub struct WaylandState {
|
pub struct WaylandState {
|
||||||
pub weak_ref: Weak<Mutex<WaylandState>>,
|
pub weak_ref: Weak<Mutex<WaylandState>>,
|
||||||
pub display: Arc<Mutex<Display<WaylandState>>>,
|
|
||||||
pub display_handle: DisplayHandle,
|
pub display_handle: DisplayHandle,
|
||||||
|
|
||||||
pub compositor_state: CompositorState,
|
pub compositor_state: CompositorState,
|
||||||
pub xdg_activation_state: XdgActivationState,
|
// pub xdg_activation_state: XdgActivationState,
|
||||||
pub xdg_decoration_state: XdgDecorationState,
|
|
||||||
pub kde_decoration_state: KdeDecorationState,
|
pub kde_decoration_state: KdeDecorationState,
|
||||||
pub xdg_shell_state: XdgShellState,
|
|
||||||
pub shm_state: ShmState,
|
pub shm_state: ShmState,
|
||||||
pub output_manager_state: OutputManagerState,
|
dmabuf_state: (DmabufState, DmabufGlobal, Option<DmabufFeedback>),
|
||||||
|
dmabuf_tx: UnboundedSender<Dmabuf>,
|
||||||
pub output: Output,
|
pub output: Output,
|
||||||
pub seats: FxHashMap<ClientId, SeatData>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WaylandState {
|
impl WaylandState {
|
||||||
pub fn new(
|
pub fn new(
|
||||||
log: Logger,
|
|
||||||
display: Arc<Mutex<Display<WaylandState>>>,
|
|
||||||
display_handle: DisplayHandle,
|
display_handle: DisplayHandle,
|
||||||
|
renderer: &GlesRenderer,
|
||||||
|
dmabuf_tx: UnboundedSender<Dmabuf>,
|
||||||
) -> Arc<Mutex<Self>> {
|
) -> Arc<Mutex<Self>> {
|
||||||
let compositor_state = CompositorState::new::<Self, _>(&display_handle, log.clone());
|
let compositor_state = CompositorState::new::<Self>(&display_handle);
|
||||||
let xdg_activation_state = XdgActivationState::new::<Self, _>(&display_handle, log.clone());
|
// let xdg_activation_state = XdgActivationState::new::<Self, _>(&display_handle);
|
||||||
let xdg_shell_state = XdgShellState::new::<Self, _>(&display_handle, log.clone());
|
|
||||||
let xdg_decoration_state = XdgDecorationState::new::<Self, _>(&display_handle, log.clone());
|
|
||||||
let kde_decoration_state =
|
let kde_decoration_state =
|
||||||
KdeDecorationState::new::<Self, _>(&display_handle, Mode::Server, log.clone());
|
KdeDecorationState::new::<Self>(&display_handle, DecorationMode::Server);
|
||||||
let shm_state = ShmState::new::<Self, _>(&display_handle, vec![], log.clone());
|
let shm_state = ShmState::new::<Self>(&display_handle, vec![]);
|
||||||
let output_manager_state = OutputManagerState::new_with_xdg_output::<Self>(&display_handle);
|
let render_node = EGLDevice::device_for_display(renderer.egl_context().display())
|
||||||
|
.and_then(|device| device.try_get_render_node());
|
||||||
|
|
||||||
|
let dmabuf_formats = renderer
|
||||||
|
.egl_context()
|
||||||
|
.dmabuf_render_formats()
|
||||||
|
.iter()
|
||||||
|
.cloned()
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let dmabuf_default_feedback = match render_node {
|
||||||
|
Ok(Some(node)) => DmabufFeedbackBuilder::new(node.dev_id(), dmabuf_formats.clone())
|
||||||
|
.build()
|
||||||
|
.ok(),
|
||||||
|
Ok(None) => {
|
||||||
|
warn!("failed to query render node, dmabuf will use v3");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
warn!(?err, "failed to egl device for display, dmabuf will use v3");
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// if we failed to build dmabuf feedback we fall back to dmabuf v3
|
||||||
|
// Note: egl on Mesa requires either v4 or wl_drm (initialized with bind_wl_display)
|
||||||
|
let dmabuf_state = if let Some(default_feedback) = dmabuf_default_feedback {
|
||||||
|
let mut dmabuf_state = DmabufState::new();
|
||||||
|
let dmabuf_global = dmabuf_state.create_global_with_default_feedback::<WaylandState>(
|
||||||
|
&display_handle,
|
||||||
|
&default_feedback,
|
||||||
|
);
|
||||||
|
(dmabuf_state, dmabuf_global, Some(default_feedback))
|
||||||
|
} else {
|
||||||
|
let mut dmabuf_state = DmabufState::new();
|
||||||
|
let dmabuf_global =
|
||||||
|
dmabuf_state.create_global::<WaylandState>(&display_handle, dmabuf_formats.clone());
|
||||||
|
(dmabuf_state, dmabuf_global, None)
|
||||||
|
};
|
||||||
|
|
||||||
let output = Output::new(
|
let output = Output::new(
|
||||||
"1x".to_owned(),
|
"1x".to_owned(),
|
||||||
smithay::output::PhysicalProperties {
|
smithay::output::PhysicalProperties {
|
||||||
@@ -80,54 +131,67 @@ impl WaylandState {
|
|||||||
make: "Virtual XR Display".to_owned(),
|
make: "Virtual XR Display".to_owned(),
|
||||||
model: "Your Headset Name Here".to_owned(),
|
model: "Your Headset Name Here".to_owned(),
|
||||||
},
|
},
|
||||||
log.clone(),
|
|
||||||
);
|
);
|
||||||
let _global = output.create_global::<Self>(&display_handle);
|
let _output_global = output.create_global::<Self>(&display_handle);
|
||||||
output.change_current_state(None, None, Some(Scale::Integer(2)), None);
|
let mode = Mode {
|
||||||
|
size: (2048, 2048).into(),
|
||||||
|
refresh: 60000,
|
||||||
|
};
|
||||||
|
output.change_current_state(
|
||||||
|
Some(mode),
|
||||||
|
Some(Transform::Normal),
|
||||||
|
Some(Scale::Integer(2)),
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
output.set_preferred(mode);
|
||||||
display_handle.create_global::<Self, WlDataDeviceManager, _>(3, ());
|
display_handle.create_global::<Self, WlDataDeviceManager, _>(3, ());
|
||||||
|
display_handle.create_global::<Self, XdgWmBase, _>(5, ());
|
||||||
|
display_handle.create_global::<Self, ZxdgDecorationManagerV1, _>(1, ());
|
||||||
|
|
||||||
println!("Init Wayland compositor");
|
info!("Init Wayland compositor");
|
||||||
|
|
||||||
Arc::new_cyclic(|weak| {
|
Arc::new_cyclic(|weak| {
|
||||||
Mutex::new(WaylandState {
|
Mutex::new(WaylandState {
|
||||||
weak_ref: weak.clone(),
|
weak_ref: weak.clone(),
|
||||||
display,
|
|
||||||
display_handle,
|
display_handle,
|
||||||
|
|
||||||
compositor_state,
|
compositor_state,
|
||||||
xdg_activation_state,
|
// xdg_activation_state,
|
||||||
xdg_decoration_state,
|
|
||||||
kde_decoration_state,
|
kde_decoration_state,
|
||||||
xdg_shell_state,
|
|
||||||
shm_state,
|
shm_state,
|
||||||
output_manager_state,
|
dmabuf_state,
|
||||||
|
dmabuf_tx,
|
||||||
output,
|
output,
|
||||||
seats: FxHashMap::default(),
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn new_client(&mut self, client: ClientId, dh: &DisplayHandle) {
|
|
||||||
let seat_data = SeatData::new(dh, client.clone());
|
|
||||||
self.seats.insert(client, seat_data);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
impl Drop for WaylandState {
|
impl Drop for WaylandState {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
println!("Cleanly shut down the Wayland compositor");
|
info!("Cleanly shut down the Wayland compositor");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl BufferHandler for WaylandState {
|
impl BufferHandler for WaylandState {
|
||||||
fn buffer_destroyed(
|
fn buffer_destroyed(&mut self, _buffer: &WlBuffer) {}
|
||||||
&mut self,
|
|
||||||
_buffer: &smithay::reexports::wayland_server::protocol::wl_buffer::WlBuffer,
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
impl ShmHandler for WaylandState {
|
impl ShmHandler for WaylandState {
|
||||||
fn shm_state(&self) -> &smithay::wayland::shm::ShmState {
|
fn shm_state(&self) -> &ShmState {
|
||||||
&self.shm_state
|
&self.shm_state
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
impl DmabufHandler for WaylandState {
|
||||||
|
fn dmabuf_state(&mut self) -> &mut DmabufState {
|
||||||
|
&mut self.dmabuf_state.0
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dmabuf_imported(
|
||||||
|
&mut self,
|
||||||
|
_global: &DmabufGlobal,
|
||||||
|
dmabuf: Dmabuf,
|
||||||
|
) -> Result<(), dmabuf::ImportError> {
|
||||||
|
self.dmabuf_tx.send(dmabuf).map_err(|_| ImportError::Failed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
delegate_dmabuf!(WaylandState);
|
||||||
delegate_shm!(WaylandState);
|
delegate_shm!(WaylandState);
|
||||||
delegate_output!(WaylandState);
|
delegate_output!(WaylandState);
|
||||||
|
|||||||
@@ -1,137 +1,116 @@
|
|||||||
use super::{shaders::PANEL_SHADER_BYTES, state::WaylandState};
|
use super::state::WaylandState;
|
||||||
use crate::{
|
use crate::{
|
||||||
core::{destroy_queue, registry::Registry},
|
core::{delta::Delta, destroy_queue, registry::Registry},
|
||||||
nodes::drawable::model::Model,
|
nodes::drawable::{model::ModelPart, shaders::PANEL_SHADER_BYTES},
|
||||||
};
|
};
|
||||||
use mint::Vector2;
|
use mint::Vector2;
|
||||||
|
use once_cell::sync::OnceCell;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use send_wrapper::SendWrapper;
|
use send_wrapper::SendWrapper;
|
||||||
use slog::Logger;
|
|
||||||
use smithay::{
|
use smithay::{
|
||||||
backend::renderer::{
|
backend::renderer::{
|
||||||
gles2::{Gles2Renderer, Gles2Texture},
|
gles::{GlesRenderer, GlesTexture},
|
||||||
utils::{import_surface_tree, on_commit_buffer_handler, RendererSurfaceStateUserData},
|
utils::{import_surface_tree, on_commit_buffer_handler, RendererSurfaceStateUserData},
|
||||||
Texture,
|
Renderer, Texture,
|
||||||
},
|
},
|
||||||
desktop::utils::send_frames_surface_tree,
|
desktop::utils::send_frames_surface_tree,
|
||||||
reexports::wayland_server::{
|
output::Output,
|
||||||
backend::ObjectId, protocol::wl_surface::WlSurface, Display, DisplayHandle, Resource,
|
reexports::wayland_server::{self, protocol::wl_surface::WlSurface, DisplayHandle, Resource},
|
||||||
},
|
|
||||||
wayland::compositor::{self, SurfaceData},
|
wayland::compositor::{self, SurfaceData},
|
||||||
};
|
};
|
||||||
use std::sync::{Arc, Weak};
|
use std::{cell::RefCell, ffi::c_void, sync::Arc, time::Duration};
|
||||||
use stereokit::{
|
use stereokit::{
|
||||||
material::{Material, Transparency},
|
Material, Shader, StereoKitDraw, Tex, TextureAddress, TextureFormat, TextureSample,
|
||||||
shader::Shader,
|
TextureType, Transparency,
|
||||||
texture::{Texture as SKTexture, TextureAddress, TextureFormat, TextureSample, TextureType},
|
|
||||||
StereoKit,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub static CORE_SURFACES: Registry<CoreSurface> = Registry::new();
|
pub static CORE_SURFACES: Registry<CoreSurface> = Registry::new();
|
||||||
|
|
||||||
pub struct CoreSurfaceData {
|
pub struct CoreSurfaceData {
|
||||||
wl_tex: Option<SendWrapper<Gles2Texture>>,
|
wl_tex: Option<SendWrapper<GlesTexture>>,
|
||||||
sk_tex: Option<SendWrapper<SKTexture>>,
|
|
||||||
sk_mat: Option<Arc<SendWrapper<Material>>>,
|
|
||||||
pub size: Vector2<u32>,
|
pub size: Vector2<u32>,
|
||||||
}
|
}
|
||||||
impl CoreSurfaceData {
|
|
||||||
fn new(sk: &StereoKit) -> Self {
|
|
||||||
let sk_tex = SendWrapper::new(
|
|
||||||
SKTexture::create(sk, TextureType::ImageNoMips, TextureFormat::RGBA32).unwrap(),
|
|
||||||
);
|
|
||||||
let sk_mat = {
|
|
||||||
let shader = Shader::from_mem(sk, PANEL_SHADER_BYTES).unwrap();
|
|
||||||
let mat = Material::create(sk, &shader).unwrap();
|
|
||||||
mat.set_parameter("diffuse", &*sk_tex);
|
|
||||||
mat.set_transparency(Transparency::Blend);
|
|
||||||
Arc::new(SendWrapper::new(mat))
|
|
||||||
};
|
|
||||||
CoreSurfaceData {
|
|
||||||
wl_tex: None,
|
|
||||||
sk_tex: Some(sk_tex),
|
|
||||||
sk_mat: Some(sk_mat),
|
|
||||||
size: Vector2::from([0, 0]),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn update_tex(&mut self, data: &RendererSurfaceStateUserData, renderer: &Gles2Renderer) {
|
|
||||||
if let Some(surface_size) = data.borrow().surface_size() {
|
|
||||||
self.size = Vector2::from([surface_size.w as u32, surface_size.h as u32]);
|
|
||||||
}
|
|
||||||
self.wl_tex = data
|
|
||||||
.borrow()
|
|
||||||
.texture(renderer)
|
|
||||||
.cloned()
|
|
||||||
.map(SendWrapper::new);
|
|
||||||
if let Some(smithay_tex) = self.wl_tex.as_ref() {
|
|
||||||
let sk_tex = self.sk_tex.as_ref().unwrap();
|
|
||||||
unsafe {
|
|
||||||
sk_tex.set_native(
|
|
||||||
smithay_tex.tex_id() as usize,
|
|
||||||
smithay::backend::renderer::gles2::ffi::RGBA8.into(),
|
|
||||||
TextureType::Image,
|
|
||||||
smithay_tex.width(),
|
|
||||||
smithay_tex.height(),
|
|
||||||
false,
|
|
||||||
);
|
|
||||||
sk_tex.set_sample(TextureSample::Point);
|
|
||||||
sk_tex.set_address_mode(TextureAddress::Clamp);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
impl Drop for CoreSurfaceData {
|
impl Drop for CoreSurfaceData {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
destroy_queue::add(self.wl_tex.take());
|
destroy_queue::add(self.wl_tex.take());
|
||||||
destroy_queue::add(self.sk_tex.take());
|
|
||||||
destroy_queue::add(self.sk_mat.take());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct CoreSurface {
|
pub struct CoreSurface {
|
||||||
display: Weak<Mutex<Display<WaylandState>>>,
|
|
||||||
pub state: Weak<Mutex<WaylandState>>,
|
|
||||||
pub dh: DisplayHandle,
|
pub dh: DisplayHandle,
|
||||||
pub surface_id: ObjectId,
|
pub weak_surface: wayland_server::Weak<WlSurface>,
|
||||||
pub mapped_data: Mutex<Option<CoreSurfaceData>>,
|
mapped_data: Mutex<Option<CoreSurfaceData>>,
|
||||||
pub pending_material_applications: Mutex<Vec<(Arc<Model>, u32)>>,
|
sk_tex: OnceCell<Tex>,
|
||||||
|
sk_mat: OnceCell<Arc<Material>>,
|
||||||
|
material_offset: Mutex<Delta<u32>>,
|
||||||
|
on_mapped: Box<dyn Fn() + Send + Sync>,
|
||||||
|
on_commit: Box<dyn Fn(u32) + Send + Sync>,
|
||||||
|
pub pending_material_applications: Registry<ModelPart>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CoreSurface {
|
impl CoreSurface {
|
||||||
pub fn new(
|
pub fn add_to(
|
||||||
state: &Arc<Mutex<WaylandState>>,
|
|
||||||
display: &Arc<Mutex<Display<WaylandState>>>,
|
|
||||||
dh: DisplayHandle,
|
dh: DisplayHandle,
|
||||||
surface: &WlSurface,
|
surface: &WlSurface,
|
||||||
) -> Arc<Self> {
|
on_mapped: impl Fn() + Send + Sync + 'static,
|
||||||
CORE_SURFACES.add(CoreSurface {
|
on_commit: impl Fn(u32) + Send + Sync + 'static,
|
||||||
display: Arc::downgrade(display),
|
) {
|
||||||
state: Arc::downgrade(state),
|
compositor::with_states(surface, |data| {
|
||||||
dh,
|
data.data_map.insert_if_missing_threadsafe(|| {
|
||||||
surface_id: surface.id(),
|
CORE_SURFACES.add(CoreSurface {
|
||||||
mapped_data: Mutex::new(None),
|
dh,
|
||||||
pending_material_applications: Mutex::new(Vec::new()),
|
weak_surface: surface.downgrade(),
|
||||||
|
mapped_data: Mutex::new(None),
|
||||||
|
sk_tex: OnceCell::new(),
|
||||||
|
sk_mat: OnceCell::new(),
|
||||||
|
material_offset: Mutex::new(Delta::new(0)),
|
||||||
|
on_mapped: Box::new(on_mapped) as Box<dyn Fn() + Send + Sync>,
|
||||||
|
on_commit: Box::new(on_commit) as Box<dyn Fn(u32) + Send + Sync>,
|
||||||
|
pending_material_applications: Registry::new(),
|
||||||
|
})
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn commit(&self, count: u32) {
|
||||||
|
(self.on_commit)(count);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_wl_surface(surf: &WlSurface) -> Option<Arc<CoreSurface>> {
|
||||||
|
compositor::with_states(surf, |data| {
|
||||||
|
data.data_map.get::<Arc<CoreSurface>>().cloned()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn process<F: FnOnce(&SurfaceData), M: FnOnce(&SurfaceData)>(
|
pub fn process(&self, sk: &impl StereoKitDraw, renderer: &mut GlesRenderer) {
|
||||||
&self,
|
let Some(wl_surface) = self.wl_surface() else {return};
|
||||||
sk: &StereoKit,
|
|
||||||
renderer: &mut Gles2Renderer,
|
|
||||||
time_ms: u32,
|
|
||||||
log: &Logger,
|
|
||||||
on_mapped: F,
|
|
||||||
if_mapped: M,
|
|
||||||
) {
|
|
||||||
// Let Smithay handle all the buffer maintenance
|
|
||||||
on_commit_buffer_handler(&self.wl_surface());
|
|
||||||
// Import all surface buffers into textures
|
|
||||||
import_surface_tree(renderer, &self.wl_surface(), log).unwrap();
|
|
||||||
|
|
||||||
let mapped = compositor::with_states(&self.wl_surface(), |data| {
|
let sk_tex = self
|
||||||
|
.sk_tex
|
||||||
|
.get_or_init(|| sk.tex_create(TextureType::IMAGE_NO_MIPS, TextureFormat::RGBA32));
|
||||||
|
self.sk_mat.get_or_init(|| {
|
||||||
|
let shader = sk.shader_create_mem(&PANEL_SHADER_BYTES);
|
||||||
|
// let _ = renderer.with_context(|c| unsafe {
|
||||||
|
// shader_inject(c, &mut shader, SIMULA_VERT_STR, SIMULA_FRAG_STR)
|
||||||
|
// });
|
||||||
|
|
||||||
|
let mat = sk.material_create(shader.as_ref().unwrap_or(Shader::UI.as_ref()));
|
||||||
|
sk.material_set_texture(&mat, "diffuse", sk_tex.as_ref());
|
||||||
|
sk.material_set_transparency(&mat, Transparency::Blend);
|
||||||
|
Arc::new(mat)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Let smithay handle buffer management (has to be done here as RendererSurfaceStates is not thread safe)
|
||||||
|
on_commit_buffer_handler::<WaylandState>(&wl_surface);
|
||||||
|
// Import all surface buffers into textures
|
||||||
|
if import_surface_tree(renderer, &wl_surface).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mapped = compositor::with_states(&wl_surface, |data| {
|
||||||
data.data_map
|
data.data_map
|
||||||
.get::<RendererSurfaceStateUserData>()
|
.get::<RendererSurfaceStateUserData>()
|
||||||
.map(|surface_states| surface_states.borrow().wl_buffer().is_some())
|
.map(|surface_states| surface_states.borrow().buffer().is_some())
|
||||||
.unwrap_or(false)
|
.unwrap_or(false)
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -141,80 +120,99 @@ impl CoreSurface {
|
|||||||
|
|
||||||
let mut mapped_data = self.mapped_data.lock();
|
let mut mapped_data = self.mapped_data.lock();
|
||||||
let just_mapped = mapped_data.is_none();
|
let just_mapped = mapped_data.is_none();
|
||||||
if just_mapped {
|
|
||||||
*mapped_data = Some(CoreSurfaceData::new(sk));
|
|
||||||
}
|
|
||||||
drop(mapped_data);
|
|
||||||
self.with_states(|data| {
|
self.with_states(|data| {
|
||||||
self.with_data(|mapped_data| {
|
let Some(renderer_surface_state) = data
|
||||||
mapped_data.update_tex(
|
.data_map
|
||||||
data.data_map.get::<RendererSurfaceStateUserData>().unwrap(),
|
.get::<RendererSurfaceStateUserData>()
|
||||||
renderer,
|
.map(RefCell::borrow) else {return};
|
||||||
|
let Some(smithay_tex) = renderer_surface_state
|
||||||
|
.texture::<GlesRenderer>(renderer.id())
|
||||||
|
.cloned() else {return};
|
||||||
|
|
||||||
|
let Some(sk_tex) = self.sk_tex.get() else {return};
|
||||||
|
let Some(sk_mat) = self.sk_mat.get() else {return};
|
||||||
|
unsafe {
|
||||||
|
sk.tex_set_surface(
|
||||||
|
sk_tex.as_ref(),
|
||||||
|
smithay_tex.tex_id() as usize as *mut c_void,
|
||||||
|
TextureType::IMAGE_NO_MIPS,
|
||||||
|
smithay::backend::renderer::gles::ffi::RGBA8.into(),
|
||||||
|
smithay_tex.width() as i32,
|
||||||
|
smithay_tex.height() as i32,
|
||||||
|
1,
|
||||||
|
false,
|
||||||
);
|
);
|
||||||
});
|
sk.tex_set_sample(sk_tex.as_ref(), TextureSample::Point);
|
||||||
self.apply_surface_materials();
|
sk.tex_set_address(sk_tex.as_ref(), TextureAddress::Clamp);
|
||||||
|
}
|
||||||
if just_mapped {
|
if let Some(material_offset) = self.material_offset.lock().delta() {
|
||||||
on_mapped(data);
|
sk.material_set_queue_offset(sk_mat.as_ref().as_ref(), *material_offset as i32);
|
||||||
}
|
}
|
||||||
if_mapped(data);
|
|
||||||
});
|
|
||||||
|
|
||||||
send_frames_surface_tree(&self.wl_surface(), time_ms);
|
let Some(surface_size) = renderer_surface_state.surface_size() else {return};
|
||||||
|
let new_mapped_data = CoreSurfaceData {
|
||||||
|
size: Vector2::from([surface_size.w as u32, surface_size.h as u32]),
|
||||||
|
wl_tex: Some(SendWrapper::new(smithay_tex)),
|
||||||
|
};
|
||||||
|
*mapped_data = Some(new_mapped_data);
|
||||||
|
});
|
||||||
|
drop(mapped_data);
|
||||||
|
if just_mapped {
|
||||||
|
(self.on_mapped)();
|
||||||
|
}
|
||||||
|
self.apply_surface_materials();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn apply_material(&self, model: Arc<Model>, material_idx: u32) {
|
pub fn frame(&self, sk: &impl StereoKitDraw, output: Output) {
|
||||||
self.pending_material_applications
|
let Some(wl_surface) = self.wl_surface() else {return};
|
||||||
.lock()
|
|
||||||
.push((model, material_idx));
|
send_frames_surface_tree(
|
||||||
|
&wl_surface,
|
||||||
|
&output,
|
||||||
|
Duration::from_secs_f64(sk.time_get()),
|
||||||
|
None,
|
||||||
|
|_, _| Some(output.clone()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_material_offset(&self, material_offset: u32) {
|
||||||
|
*self.material_offset.lock().value_mut() = material_offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn apply_material(&self, model_part: &Arc<ModelPart>) {
|
||||||
|
self.pending_material_applications.add_raw(model_part)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn apply_surface_materials(&self) {
|
fn apply_surface_materials(&self) {
|
||||||
self.with_data(|mapped_data| {
|
if let Some(sk_mat) = self.sk_mat.get() {
|
||||||
let mut pending_material_applications = self.pending_material_applications.lock();
|
for model_node in self.pending_material_applications.get_valid_contents() {
|
||||||
for (model, material_idx) in &*pending_material_applications {
|
model_node.replace_material(sk_mat.clone());
|
||||||
model
|
|
||||||
.pending_material_replacements
|
|
||||||
.lock()
|
|
||||||
.insert(*material_idx, mapped_data.sk_mat.clone().unwrap());
|
|
||||||
}
|
}
|
||||||
pending_material_applications.clear();
|
self.pending_material_applications.clear();
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn wayland_state(&self) -> Arc<Mutex<WaylandState>> {
|
pub fn wl_surface(&self) -> Option<WlSurface> {
|
||||||
self.state.upgrade().unwrap()
|
self.weak_surface.upgrade().ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn wl_surface(&self) -> WlSurface {
|
pub fn with_states<F, T>(&self, f: F) -> Option<T>
|
||||||
WlSurface::from_id(&self.dh, self.surface_id.clone()).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_states<F, T>(&self, f: F) -> T
|
|
||||||
where
|
where
|
||||||
F: FnOnce(&SurfaceData) -> T,
|
F: FnOnce(&SurfaceData) -> T,
|
||||||
{
|
{
|
||||||
compositor::with_states(&self.wl_surface(), f)
|
self.wl_surface()
|
||||||
|
.map(|wl_surface| compositor::with_states(&wl_surface, f))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_data<F, T>(&self, f: F) -> Option<T>
|
pub fn size(&self) -> Option<Vector2<u32>> {
|
||||||
where
|
self.mapped_data.lock().as_ref().map(|d| d.size)
|
||||||
F: FnOnce(&mut CoreSurfaceData) -> T,
|
|
||||||
{
|
|
||||||
self.mapped_data.lock().as_mut().map(f)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn flush_clients(&self) {
|
|
||||||
self.display
|
|
||||||
.upgrade()
|
|
||||||
.unwrap()
|
|
||||||
.lock()
|
|
||||||
.flush_clients()
|
|
||||||
.unwrap();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl Drop for CoreSurface {
|
impl Drop for CoreSurface {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
CORE_SURFACES.remove(self);
|
CORE_SURFACES.remove(self);
|
||||||
|
|
||||||
|
destroy_queue::add(self.sk_tex.take());
|
||||||
|
destroy_queue::add(self.sk_mat.take());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
437
src/wayland/xwayland.rs
Normal file
437
src/wayland/xwayland.rs
Normal file
@@ -0,0 +1,437 @@
|
|||||||
|
use super::{
|
||||||
|
seat::{KeyboardEvent, PointerEvent, SeatData},
|
||||||
|
state::ClientState,
|
||||||
|
};
|
||||||
|
use crate::{
|
||||||
|
nodes::{
|
||||||
|
data::KEYMAPS,
|
||||||
|
drawable::model::ModelPart,
|
||||||
|
items::panel::{Backend, Geometry, PanelItem, PanelItemInitData, SurfaceID, ToplevelInfo},
|
||||||
|
},
|
||||||
|
wayland::surface::CoreSurface,
|
||||||
|
};
|
||||||
|
use color_eyre::eyre::Result;
|
||||||
|
use mint::Vector2;
|
||||||
|
use once_cell::sync::OnceCell;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use rustc_hash::FxHashMap;
|
||||||
|
use smithay::{
|
||||||
|
reexports::{
|
||||||
|
calloop::{EventLoop, LoopSignal},
|
||||||
|
wayland_server::{protocol::wl_surface::WlSurface, DisplayHandle, Resource},
|
||||||
|
x11rb::protocol::xproto::Window,
|
||||||
|
},
|
||||||
|
utils::{Logical, Rectangle},
|
||||||
|
wayland::compositor,
|
||||||
|
xwayland::{
|
||||||
|
xwm::{Reorder, ResizeEdge, XwmId},
|
||||||
|
X11Surface, X11Wm, XWayland, XWaylandEvent, XwmHandler,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use std::{ffi::OsStr, iter::empty, sync::Arc, time::Duration};
|
||||||
|
use tokio::sync::oneshot;
|
||||||
|
use tracing::debug;
|
||||||
|
|
||||||
|
pub static DISPLAY: OnceCell<String> = OnceCell::new();
|
||||||
|
|
||||||
|
pub struct XWaylandState {
|
||||||
|
pub display: u32,
|
||||||
|
event_loop_signal: LoopSignal,
|
||||||
|
}
|
||||||
|
impl XWaylandState {
|
||||||
|
pub fn create(dh: &DisplayHandle) -> Result<Self> {
|
||||||
|
let dh = dh.clone();
|
||||||
|
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let mut event_loop: EventLoop<XWaylandHandler> = EventLoop::try_new()?;
|
||||||
|
let (xwayland, connection) = XWayland::new(&dh);
|
||||||
|
let handle = event_loop.handle();
|
||||||
|
event_loop
|
||||||
|
.handle()
|
||||||
|
.insert_source(connection, {
|
||||||
|
let dh = dh.clone();
|
||||||
|
move |event, _, handler| match event {
|
||||||
|
XWaylandEvent::Ready {
|
||||||
|
connection,
|
||||||
|
client,
|
||||||
|
client_fd: _,
|
||||||
|
display: _,
|
||||||
|
} => {
|
||||||
|
handler.seat = client.get_data::<ClientState>().map(|s| s.seat.clone());
|
||||||
|
handler.wm =
|
||||||
|
X11Wm::start_wm(handle.clone(), dh.clone(), connection, client)
|
||||||
|
.ok();
|
||||||
|
}
|
||||||
|
XWaylandEvent::Exited => (),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.map_err(|e| e.error)?;
|
||||||
|
|
||||||
|
let display = xwayland.start(
|
||||||
|
event_loop.handle(),
|
||||||
|
None,
|
||||||
|
empty::<(&OsStr, &OsStr)>(),
|
||||||
|
true,
|
||||||
|
|_| (),
|
||||||
|
)?;
|
||||||
|
let _ = tx.send(XWaylandState {
|
||||||
|
display,
|
||||||
|
event_loop_signal: event_loop.get_signal(),
|
||||||
|
});
|
||||||
|
let mut handler = XWaylandHandler {
|
||||||
|
wayland_display_handle: dh,
|
||||||
|
wm: None,
|
||||||
|
seat: None,
|
||||||
|
};
|
||||||
|
event_loop.run(Duration::from_millis(100), &mut handler, |_| ())
|
||||||
|
});
|
||||||
|
|
||||||
|
let state = rx.blocking_recv()?;
|
||||||
|
let _ = DISPLAY.set(format!(":{}", state.display));
|
||||||
|
|
||||||
|
Ok(state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl Drop for XWaylandState {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.event_loop_signal.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct XWaylandHandler {
|
||||||
|
wayland_display_handle: DisplayHandle,
|
||||||
|
wm: Option<X11Wm>,
|
||||||
|
seat: Option<Arc<SeatData>>,
|
||||||
|
}
|
||||||
|
impl XWaylandHandler {
|
||||||
|
fn panel_item(&self, window: &X11Surface) -> Option<Arc<PanelItem<X11Backend>>> {
|
||||||
|
compositor::with_states(&window.wl_surface()?, |s| {
|
||||||
|
s.data_map.get::<Arc<PanelItem<X11Backend>>>().cloned()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl XwmHandler for XWaylandHandler {
|
||||||
|
fn xwm_state(&mut self, _xwm: XwmId) -> &mut X11Wm {
|
||||||
|
self.wm.as_mut().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_window(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||||
|
debug!(?window, "New X window");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn new_override_redirect_window(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||||
|
debug!(?window, "New X override redirect window");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn map_window_request(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||||
|
debug!(?window, "X map window request");
|
||||||
|
window.set_mapped(true).unwrap();
|
||||||
|
}
|
||||||
|
fn map_window_notify(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||||
|
debug!(?window, "X map window notify");
|
||||||
|
|
||||||
|
let _ = window.set_maximized(true);
|
||||||
|
|
||||||
|
let dh = self.wayland_display_handle.clone();
|
||||||
|
let seat = self.seat.clone().unwrap();
|
||||||
|
CoreSurface::add_to(
|
||||||
|
self.wayland_display_handle.clone(),
|
||||||
|
&window.wl_surface().unwrap(),
|
||||||
|
{
|
||||||
|
let window = window.clone();
|
||||||
|
move || {
|
||||||
|
let Some(wl_surface) = window.wl_surface() else {return};
|
||||||
|
let seat = seat.clone();
|
||||||
|
window.user_data().insert_if_missing_threadsafe(|| {
|
||||||
|
let panel_item = PanelItem::create(
|
||||||
|
Box::new(X11Backend {
|
||||||
|
toplevel_parent: None,
|
||||||
|
toplevel: window.clone(),
|
||||||
|
seat,
|
||||||
|
_pointer_grab: Mutex::new(None),
|
||||||
|
_keyboard_grab: Mutex::new(None),
|
||||||
|
}),
|
||||||
|
wl_surface
|
||||||
|
.client()
|
||||||
|
.and_then(|c| c.get_credentials(&dh).ok())
|
||||||
|
.map(|c| c.pid),
|
||||||
|
);
|
||||||
|
panel_item
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
move |_| {
|
||||||
|
let Some(panel_item) = window.user_data().get::<Arc<PanelItem<X11Backend>>>() else {return};
|
||||||
|
panel_item.toplevel_size_changed(
|
||||||
|
[
|
||||||
|
window.geometry().size.w as u32,
|
||||||
|
window.geometry().size.h as u32,
|
||||||
|
]
|
||||||
|
.into(),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
fn mapped_override_redirect_window(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||||
|
debug!(?window, "X map override redirect window");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unmapped_window(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||||
|
debug!(?window, "Unmap X window");
|
||||||
|
}
|
||||||
|
fn destroyed_window(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||||
|
debug!(?window, "Destroy X window");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn configure_request(
|
||||||
|
&mut self,
|
||||||
|
_xwm: XwmId,
|
||||||
|
window: X11Surface,
|
||||||
|
x: Option<i32>,
|
||||||
|
y: Option<i32>,
|
||||||
|
w: Option<u32>,
|
||||||
|
h: Option<u32>,
|
||||||
|
reorder: Option<Reorder>,
|
||||||
|
) {
|
||||||
|
debug!(?window, x, y, w, h, ?reorder, "Configure X window");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn configure_notify(
|
||||||
|
&mut self,
|
||||||
|
_xwm: XwmId,
|
||||||
|
window: X11Surface,
|
||||||
|
geometry: Rectangle<i32, Logical>,
|
||||||
|
above: Option<Window>,
|
||||||
|
) {
|
||||||
|
debug!(?window, ?geometry, above, "Configure X window");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn move_request(&mut self, _xwm: XwmId, window: X11Surface, button: u32) {
|
||||||
|
let Some(panel_item) = self.panel_item(&window) else {return};
|
||||||
|
debug!(?window, button, "X window requests move");
|
||||||
|
panel_item.toplevel_move_request();
|
||||||
|
}
|
||||||
|
fn resize_request(
|
||||||
|
&mut self,
|
||||||
|
_xwm: XwmId,
|
||||||
|
window: X11Surface,
|
||||||
|
button: u32,
|
||||||
|
resize_edge: ResizeEdge,
|
||||||
|
) {
|
||||||
|
let Some(panel_item) = self.panel_item(&window) else {return};
|
||||||
|
debug!(?window, button, ?resize_edge, "X window requests resize");
|
||||||
|
let (up, down, left, right) = match resize_edge {
|
||||||
|
ResizeEdge::Top => (true, false, false, false),
|
||||||
|
ResizeEdge::Bottom => (false, true, false, false),
|
||||||
|
ResizeEdge::Left => (false, false, true, false),
|
||||||
|
ResizeEdge::TopLeft => (true, false, true, false),
|
||||||
|
ResizeEdge::BottomLeft => (false, true, true, false),
|
||||||
|
ResizeEdge::Right => (false, false, false, true),
|
||||||
|
ResizeEdge::TopRight => (true, false, false, true),
|
||||||
|
ResizeEdge::BottomRight => (false, true, false, true),
|
||||||
|
// _ => (false, false, false, false),
|
||||||
|
};
|
||||||
|
panel_item.toplevel_resize_request(up, down, left, right)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fullscreen_request(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||||
|
let _ = window.set_fullscreen(true);
|
||||||
|
let Some(panel_item) = self.panel_item(&window) else {return};
|
||||||
|
panel_item.toplevel_fullscreen_active(true);
|
||||||
|
}
|
||||||
|
fn unfullscreen_request(&mut self, _xwm: XwmId, window: X11Surface) {
|
||||||
|
let _ = window.set_fullscreen(false);
|
||||||
|
let Some(panel_item) = self.panel_item(&window) else {return};
|
||||||
|
panel_item.toplevel_fullscreen_active(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct X11Backend {
|
||||||
|
pub toplevel_parent: Option<X11Surface>,
|
||||||
|
pub toplevel: X11Surface,
|
||||||
|
pub seat: Arc<SeatData>,
|
||||||
|
_pointer_grab: Mutex<Option<SurfaceID>>,
|
||||||
|
_keyboard_grab: Mutex<Option<SurfaceID>>,
|
||||||
|
}
|
||||||
|
impl X11Backend {
|
||||||
|
fn wl_surface_from_id(&self, id: &SurfaceID) -> Option<WlSurface> {
|
||||||
|
match id {
|
||||||
|
SurfaceID::Cursor => None,
|
||||||
|
SurfaceID::Toplevel => self.toplevel.wl_surface(),
|
||||||
|
SurfaceID::Child(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fn flush_client(&self) {
|
||||||
|
// let Some(client) = self.toplevel.wl_surface().and_then(|s| s.client()) else {return};
|
||||||
|
// if let Some(client_state) = client.get_data::<ClientState>() {
|
||||||
|
// client_state.flush();
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
impl Backend for X11Backend {
|
||||||
|
// fn start_data(&self, id: &str) -> Result<Message> {
|
||||||
|
// let size = (
|
||||||
|
// self.toplevel.geometry().size.w as u32,
|
||||||
|
// self.toplevel.geometry().size.h as u32,
|
||||||
|
// );
|
||||||
|
// let toplevel_state = (
|
||||||
|
// None::<String>,
|
||||||
|
// self.toplevel.title(),
|
||||||
|
// None::<String>,
|
||||||
|
// (
|
||||||
|
// self.toplevel.geometry().size.w as u32,
|
||||||
|
// self.toplevel.geometry().size.h as u32,
|
||||||
|
// ),
|
||||||
|
// self.toplevel.min_size().map(|s| (s.w as u32, s.h as u32)),
|
||||||
|
// self.toplevel.max_size().map(|s| (s.w as u32, s.w as u32)),
|
||||||
|
// ((0_i32, 0_i32), size),
|
||||||
|
// vec![0_u32; 0],
|
||||||
|
// );
|
||||||
|
// let info = (
|
||||||
|
// None::<(Vector2<u32>, Vector2<i32>)>,
|
||||||
|
// toplevel_state,
|
||||||
|
// Vec::<PopupData>::new(),
|
||||||
|
// None::<SurfaceID>,
|
||||||
|
// None::<SurfaceID>,
|
||||||
|
// );
|
||||||
|
// Ok(serialize((id, info))?.into())
|
||||||
|
// }
|
||||||
|
// fn serialize_toplevel(&self) -> Result<Message> {
|
||||||
|
// let toplevel_state = (
|
||||||
|
// None::<String>,
|
||||||
|
// self.toplevel.title(),
|
||||||
|
// None::<String>,
|
||||||
|
// (
|
||||||
|
// self.toplevel.geometry().size.w,
|
||||||
|
// self.toplevel.geometry().size.h,
|
||||||
|
// ),
|
||||||
|
// self.toplevel.min_size().map(|s| (s.w, s.h)),
|
||||||
|
// self.toplevel.max_size().map(|s| (s.w, s.w)),
|
||||||
|
// );
|
||||||
|
// let data = serialize(&toplevel_state)?;
|
||||||
|
// Ok(data.into())
|
||||||
|
// }
|
||||||
|
|
||||||
|
// fn set_toplevel_capabilities(&self, _capabilities: Vec<u8>) {}
|
||||||
|
|
||||||
|
// fn set_toplevel_size(
|
||||||
|
// &self,
|
||||||
|
// size: Option<Vector2<u32>>,
|
||||||
|
// states: Vec<u32>,
|
||||||
|
// _bounds: Option<Vector2<u32>>,
|
||||||
|
// ) {
|
||||||
|
// let _ = self.toplevel.configure(
|
||||||
|
// size.map(|s| Rectangle::from_loc_and_size((0, 0), (s.x as i32, s.y as i32))),
|
||||||
|
// );
|
||||||
|
// let _ = self.toplevel.set_maximized(states.contains(&1));
|
||||||
|
// }
|
||||||
|
|
||||||
|
fn start_data(&self) -> Result<PanelItemInitData> {
|
||||||
|
Ok(PanelItemInitData {
|
||||||
|
cursor: None,
|
||||||
|
toplevel: ToplevelInfo {
|
||||||
|
parent: None,
|
||||||
|
title: Some(self.toplevel.title()),
|
||||||
|
app_id: Some(self.toplevel.instance()),
|
||||||
|
size: [
|
||||||
|
self.toplevel.geometry().size.w as u32,
|
||||||
|
self.toplevel.geometry().size.h as u32,
|
||||||
|
]
|
||||||
|
.into(),
|
||||||
|
min_size: self
|
||||||
|
.toplevel
|
||||||
|
.min_size()
|
||||||
|
.map(|s| [s.w as u32, s.h as u32].into()),
|
||||||
|
max_size: self
|
||||||
|
.toplevel
|
||||||
|
.max_size()
|
||||||
|
.map(|s| [s.w as u32, s.h as u32].into()),
|
||||||
|
logical_rectangle: Geometry {
|
||||||
|
origin: [0, 0].into(),
|
||||||
|
size: [
|
||||||
|
self.toplevel.geometry().size.w as u32,
|
||||||
|
self.toplevel.geometry().size.h as u32,
|
||||||
|
]
|
||||||
|
.into(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
children: FxHashMap::default(),
|
||||||
|
pointer_grab: self._pointer_grab.lock().clone(),
|
||||||
|
keyboard_grab: self._keyboard_grab.lock().clone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn close_toplevel(&self) {}
|
||||||
|
|
||||||
|
fn auto_size_toplevel(&self) {
|
||||||
|
let _ = self.toplevel.configure(None);
|
||||||
|
}
|
||||||
|
fn set_toplevel_size(&self, size: Vector2<u32>) {
|
||||||
|
let _ = self.toplevel.configure(Some(Rectangle {
|
||||||
|
loc: self.toplevel.geometry().loc,
|
||||||
|
size: (size.x as i32, size.y as i32).into(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
fn set_toplevel_focused_visuals(&self, focused: bool) {
|
||||||
|
let _ = self.toplevel.set_activated(focused);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_surface_material(&self, surface: SurfaceID, model_part: &Arc<ModelPart>) {
|
||||||
|
let Some(wl_surface) = self.wl_surface_from_id(&surface) else {return};
|
||||||
|
let Some(core_surface) = CoreSurface::from_wl_surface(&wl_surface) else {return};
|
||||||
|
|
||||||
|
core_surface.apply_material(model_part);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pointer_motion(&self, surface: &SurfaceID, position: Vector2<f32>) {
|
||||||
|
let Some(surface) = self.wl_surface_from_id(surface) else {return};
|
||||||
|
self.seat
|
||||||
|
.pointer_event(&surface, PointerEvent::Motion(position));
|
||||||
|
}
|
||||||
|
fn pointer_button(&self, surface: &SurfaceID, button: u32, pressed: bool) {
|
||||||
|
let Some(surface) = self.wl_surface_from_id(surface) else {return};
|
||||||
|
self.seat.pointer_event(
|
||||||
|
&surface,
|
||||||
|
PointerEvent::Button {
|
||||||
|
button,
|
||||||
|
state: if pressed { 1 } else { 0 },
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
fn pointer_scroll(
|
||||||
|
&self,
|
||||||
|
surface: &SurfaceID,
|
||||||
|
scroll_distance: Option<Vector2<f32>>,
|
||||||
|
scroll_steps: Option<Vector2<f32>>,
|
||||||
|
) {
|
||||||
|
let Some(surface) = self.wl_surface_from_id(surface) else {return};
|
||||||
|
self.seat.pointer_event(
|
||||||
|
&surface,
|
||||||
|
PointerEvent::Scroll {
|
||||||
|
axis_continuous: scroll_distance,
|
||||||
|
axis_discrete: scroll_steps,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keyboard_keys(&self, surface: &SurfaceID, keymap_id: &str, keys: Vec<i32>) {
|
||||||
|
let Some(surface) = self.wl_surface_from_id(surface) else {return};
|
||||||
|
let keymaps = KEYMAPS.lock();
|
||||||
|
let Some(keymap) = keymaps.get(keymap_id).cloned() else {return};
|
||||||
|
if self.seat.set_keymap(keymap, vec![surface.clone()]).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for key in keys {
|
||||||
|
self.seat.keyboard_event(
|
||||||
|
&surface,
|
||||||
|
KeyboardEvent::Key {
|
||||||
|
key: key.abs() as u32,
|
||||||
|
state: if key < 0 { 1 } else { 0 },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
5
stardust-xr-server.desktop
Normal file
5
stardust-xr-server.desktop
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
[Desktop Entry]
|
||||||
|
Name=Stardust XR
|
||||||
|
Comment=FOSS XR system UI (display server) project
|
||||||
|
Exec=stardust-xr-server
|
||||||
|
Type=Application
|
||||||
Reference in New Issue
Block a user