Compare commits
434 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e31905b5b | ||
|
|
c830becbff | ||
|
|
e8e485b472 | ||
|
|
bf68b87813 | ||
|
|
9546a36200 | ||
|
|
c12300e756 | ||
|
|
4683710f09 | ||
|
|
1ca054c2b3 | ||
|
|
5f7e9d4eb6 | ||
|
|
c9fe1be10b | ||
|
|
f58c748f80 | ||
|
|
499aa2be28 | ||
|
|
7ba710e8b7 | ||
|
|
62802367eb | ||
|
|
853f779930 | ||
|
|
21d10a15ee | ||
|
|
6146a5b63a | ||
|
|
01485e2020 | ||
|
|
6e77c3667d | ||
|
|
003dd9fcc1 | ||
|
|
42738b739f | ||
|
|
fe83a69bb9 | ||
|
|
e0a7d4f44a | ||
|
|
14ebe85493 | ||
|
|
08135b03a2 | ||
|
|
4827561f88 | ||
|
|
72f7fd8e9d | ||
|
|
827c630a70 | ||
|
|
98a6ad6f32 | ||
|
|
c09afba366 | ||
|
|
48f15e848d | ||
|
|
78912c8f1b | ||
|
|
13815d4d20 | ||
|
|
36d91fd999 | ||
|
|
b7191c3183 | ||
|
|
796ee1a34e | ||
|
|
de10a7101e | ||
|
|
41d22da691 | ||
|
|
73ed1210ed | ||
|
|
a8e16a8411 | ||
|
|
4d8d38e4e5 | ||
|
|
01f4a8fbcd | ||
|
|
f639a1662a | ||
|
|
6350444559 | ||
|
|
ecc7d7b912 | ||
|
|
ae40158dec | ||
|
|
1b28290cbb | ||
|
|
a3bcff035a | ||
|
|
71ca32a560 | ||
|
|
d28b477c8a | ||
|
|
643697ea33 | ||
|
|
f5259f2977 | ||
|
|
7bedd2c27f | ||
|
|
707b81871c | ||
|
|
1fddcd9033 | ||
|
|
7ff470e1db | ||
|
|
a7df6d8a08 | ||
|
|
a9ff97e39c | ||
|
|
126e9f4ca6 | ||
|
|
e379dae4ad | ||
|
|
b3fa529f77 | ||
|
|
1e8d3a3d4c | ||
|
|
2988ae3c28 | ||
|
|
9c04b5710e | ||
|
|
1324c26c74 | ||
|
|
0b9f79158c | ||
|
|
e5d0906d73 | ||
|
|
f08f3e4e4b | ||
|
|
d17841ec7a | ||
|
|
ebaf113d94 | ||
|
|
5be25da46f | ||
|
|
f5e8156400 | ||
|
|
02bf210c51 | ||
|
|
eba317ace9 | ||
|
|
84e42499e7 | ||
|
|
9b6b450d18 | ||
|
|
53979ce167 | ||
|
|
e2c9e06cd3 | ||
|
|
65a9957be1 | ||
|
|
fbe941749a | ||
|
|
36fd3216c7 | ||
|
|
f73c8f968d | ||
|
|
83e3a913c5 | ||
|
|
de56aa53d6 | ||
|
|
9f0043f406 | ||
|
|
99eb0ea547 | ||
|
|
04535895e8 | ||
|
|
69311125ba | ||
|
|
45b832455b | ||
|
|
b590e82b05 | ||
|
|
f770357010 | ||
|
|
3cbc10d91e | ||
|
|
9425d30cb3 | ||
|
|
8d2aac12d6 | ||
|
|
5f9d9d4714 | ||
|
|
eda50b7d51 | ||
|
|
01c5ad3b04 | ||
|
|
d7fba79be9 | ||
|
|
89fcc55cca | ||
|
|
a831fcb99f | ||
|
|
8e37d27130 | ||
|
|
149131f322 | ||
|
|
4a90b936b1 | ||
|
|
ab6998407b | ||
|
|
be2f5b8e37 | ||
|
|
226554fadc | ||
|
|
47cbc2b8fc | ||
|
|
90f60c9178 | ||
|
|
49253567cb | ||
|
|
350007cbaf | ||
|
|
7318d5317c | ||
|
|
15f771ff93 | ||
|
|
302a64785d | ||
|
|
34aab266a3 | ||
|
|
fba4e10611 | ||
|
|
807928a8d3 | ||
|
|
f74c891907 | ||
|
|
2dc0fdadfd | ||
|
|
8e317a8e08 | ||
|
|
c41179a437 | ||
|
|
43910cce78 | ||
|
|
643986e03d | ||
|
|
a2b061ed43 | ||
|
|
c458624157 | ||
|
|
1d2b149395 | ||
|
|
c84848ea9c | ||
|
|
b34e5f7a19 | ||
|
|
af3d49c9ef | ||
|
|
d5d63b2f89 | ||
|
|
d4b7c3f61a | ||
|
|
36dacb3322 | ||
|
|
eec38dd60f | ||
|
|
1e0ea6ae92 | ||
|
|
31f45760f0 | ||
|
|
f76863a79b | ||
|
|
43b3499ed7 | ||
|
|
dfaaa2a3a9 | ||
|
|
b8d17ac7ca | ||
|
|
ed28914f86 | ||
|
|
f8fab6bf5a | ||
|
|
1b37d77304 | ||
|
|
6eb36516b0 | ||
|
|
f0200be990 | ||
|
|
cfd3d0016b | ||
|
|
fbf0f4f672 | ||
|
|
387fa96a60 | ||
|
|
d549018024 | ||
|
|
5cd92f2c03 | ||
|
|
2450411e21 | ||
|
|
b53bfde23b | ||
|
|
15eb73af41 | ||
|
|
3c82ae309c | ||
|
|
4adcfca2fe | ||
|
|
f893491bed | ||
|
|
9d1181aaca | ||
|
|
b0f9bf24cf | ||
|
|
3527ce2507 | ||
|
|
f045bfb93d | ||
|
|
3d4ab27a14 | ||
|
|
54ff87c146 | ||
|
|
2bc988fe3d | ||
|
|
051893858b | ||
|
|
1ac211c23f | ||
|
|
4874f010dd | ||
|
|
da894143f9 | ||
|
|
109affec81 | ||
|
|
665e6b034f | ||
|
|
fc45b4e400 | ||
|
|
af75d2a451 | ||
|
|
3136a8f2b7 | ||
|
|
e97368f3e2 | ||
|
|
4da7ed1ccf | ||
|
|
bf248e192f | ||
|
|
167c3d1cbf | ||
|
|
b39d8f37f4 | ||
|
|
1198797db8 | ||
|
|
823a71a286 | ||
|
|
f78da4b198 | ||
|
|
558fb1aa4e | ||
|
|
abe32a8dbd | ||
|
|
d9e040bf8b | ||
|
|
0b8da1d280 | ||
|
|
455f3a0e9c | ||
|
|
411b30294b | ||
|
|
1d54b75a53 | ||
|
|
4c56c31bfc | ||
|
|
b21e031668 | ||
|
|
7c6b2f5949 | ||
|
|
1f66d7dee4 | ||
|
|
53b035ef92 | ||
|
|
237b084a65 | ||
|
|
707e56cb6f | ||
|
|
6f4da69e36 | ||
|
|
5634729445 | ||
|
|
b9603dc0a1 | ||
|
|
0323fbfb86 | ||
|
|
433568da63 | ||
|
|
4e199dd43f | ||
|
|
a4430b9a95 | ||
|
|
136383326e | ||
|
|
5a86f11beb | ||
|
|
6ab2bb2d52 | ||
|
|
ce8877b67e | ||
|
|
74a2f7a249 | ||
|
|
11ecb0aebe | ||
|
|
281f5e91ff | ||
|
|
5dc7cfbe83 | ||
|
|
3432c63a6e | ||
|
|
02ac96b0dc | ||
|
|
0736f99631 | ||
|
|
4bbe3ad8d0 | ||
|
|
1cf9d0f8c5 | ||
|
|
51d0cab832 | ||
|
|
062c63af2b | ||
|
|
3ce3fadb8d | ||
|
|
f0e39195b7 | ||
|
|
0d639760e9 | ||
|
|
6109a6bde6 | ||
|
|
000b633767 | ||
|
|
e3b1276d77 | ||
|
|
1cb8e1b7a4 | ||
|
|
e879b724ec | ||
|
|
08010efa46 | ||
|
|
e682931e3e | ||
|
|
bf89b73e8f | ||
|
|
2e252279bb | ||
|
|
9cf43ec535 | ||
|
|
f15578f7df | ||
|
|
f63ca4a25b | ||
|
|
89741508e3 | ||
|
|
81be807749 | ||
|
|
fcdb8a7edf | ||
|
|
90ce185f29 | ||
|
|
d6353035ae | ||
|
|
ceb1b23264 | ||
|
|
199e6f70b3 | ||
|
|
641db4face | ||
|
|
80d292b511 | ||
|
|
7fbcc92d02 | ||
|
|
de46726d01 | ||
|
|
6efa3a909e | ||
|
|
ea0f174da7 | ||
|
|
444146fa21 | ||
|
|
a7930760e8 | ||
|
|
668c32f583 | ||
|
|
927e1c48e2 | ||
|
|
8cc20e054c | ||
|
|
b12b171b53 | ||
|
|
0e61d51072 | ||
|
|
e61c04960e | ||
|
|
5dc82be1a3 | ||
|
|
6861b92972 | ||
|
|
f68f350cd2 | ||
|
|
2820415373 | ||
|
|
f721a57604 | ||
|
|
fb4149eaa7 | ||
|
|
d3746ef787 | ||
|
|
9d4b4bee4d | ||
|
|
5390b0effb | ||
|
|
13da4c8d60 | ||
|
|
1740d55f9c | ||
|
|
52d5e97de6 | ||
|
|
633df045d4 | ||
|
|
415bf5bb04 | ||
|
|
4e2d4a15c9 | ||
|
|
ef0142183d | ||
|
|
e5dfd9d3df | ||
|
|
6773fe2cf3 | ||
|
|
5a6e7e02ca | ||
|
|
c5d8ec2ef1 | ||
|
|
a31781146e | ||
|
|
cb9368cb8e | ||
|
|
629c05e507 | ||
|
|
9123153bf3 | ||
|
|
f3dc632ffc | ||
|
|
c369100d8a | ||
|
|
e10d40ef5e | ||
|
|
d6ca367187 | ||
|
|
88ac8a8b86 | ||
|
|
70fef89e2d | ||
|
|
4d79a59b20 | ||
|
|
c776c1b712 | ||
|
|
d4de15e0b3 | ||
|
|
9d220ec235 | ||
|
|
09c6c010e2 | ||
|
|
c9e185e9f3 | ||
|
|
4737149c85 | ||
|
|
648451b47e | ||
|
|
a9ef2d6f4b | ||
|
|
d6ffcadd76 | ||
|
|
448b7489e8 | ||
|
|
622cf60a65 | ||
|
|
1ab11f1660 | ||
|
|
9654e6cc59 | ||
|
|
44d177858f | ||
|
|
be41f11b83 | ||
|
|
dd2bffc2b1 | ||
|
|
d2ef508607 | ||
|
|
0cc7c7bc24 | ||
|
|
8d65e304cb | ||
|
|
b0dbccbd18 | ||
|
|
a823fbfb57 | ||
|
|
4a864e6519 | ||
|
|
e23d847449 | ||
|
|
8ba199f053 | ||
|
|
23925b4475 | ||
|
|
7ea0220f33 | ||
|
|
969e4de882 | ||
|
|
e5acb3013f | ||
|
|
3d57bed1c0 | ||
|
|
45839ebf60 | ||
|
|
0bb5b53e02 | ||
|
|
4f966b6d71 | ||
|
|
2687a393b5 | ||
|
|
5c605932ef | ||
|
|
bccdc8221e | ||
|
|
bddf17bbef | ||
|
|
e8511e8759 | ||
|
|
85296f538b | ||
|
|
f8ff80b781 | ||
|
|
932fef87f5 | ||
|
|
742780e34e | ||
|
|
41ede661f7 | ||
|
|
8d85460803 | ||
|
|
ac71581db8 | ||
|
|
2f894c4058 | ||
|
|
2b97c98a6e | ||
|
|
98d9f491ba | ||
|
|
16d710e106 | ||
|
|
9ad202e778 | ||
|
|
b3747d623c | ||
|
|
d5ff9281e6 | ||
|
|
18ebd8c522 | ||
|
|
411f71c217 | ||
|
|
3027ae20a9 | ||
|
|
fbce321426 | ||
|
|
74bc3a306e | ||
|
|
a950ad59f1 | ||
|
|
cf840da444 | ||
|
|
173fba35fa | ||
|
|
97fbbec0fe | ||
|
|
400f3a23bf | ||
|
|
1ad3336b6f | ||
|
|
8e9956abe1 | ||
|
|
6ca93ea24c | ||
|
|
49810e8fd1 | ||
|
|
afd0946558 | ||
|
|
fd31d0cd99 | ||
|
|
2f380da62f | ||
|
|
1c6971cd11 | ||
|
|
da4cf084d2 | ||
|
|
ca95ed5461 | ||
|
|
1b06cb6952 | ||
|
|
df89c826bb | ||
|
|
21f7f66440 | ||
|
|
3f1bad18c8 | ||
|
|
0c190cc833 | ||
|
|
5f0df8e7c1 | ||
|
|
d715f2f9ed | ||
|
|
d7fa4e62b8 | ||
|
|
568ebb0060 | ||
|
|
42efc67625 | ||
|
|
dd4b0097a1 | ||
|
|
a483cdbc7d | ||
|
|
84a7546442 | ||
|
|
dd43f238ff | ||
|
|
4f057358c8 | ||
|
|
e20971aef7 | ||
|
|
eb0d3c5bcf | ||
|
|
a18222e3df | ||
|
|
93ca932da9 | ||
|
|
c512b2fef5 | ||
|
|
f53c684377 | ||
|
|
3552166207 | ||
|
|
0b6eb147c5 | ||
|
|
1833ed50f3 | ||
|
|
6cdbfb3bad | ||
|
|
a5e0cb19c9 | ||
|
|
519ab94312 | ||
|
|
f2a8c0ed13 | ||
|
|
b3998f315d | ||
|
|
40bcd61b98 | ||
|
|
7a4d557c61 | ||
|
|
303b3f3ca2 | ||
|
|
ac5e949614 | ||
|
|
60baabb850 | ||
|
|
248e48fd8e | ||
|
|
b9baee7e5f | ||
|
|
3598ffdbb1 | ||
|
|
c171d9e6db | ||
|
|
d7a607a663 | ||
|
|
03ccf9127d | ||
|
|
6a3024657f | ||
|
|
a0058fcc2e | ||
|
|
410cc13c4f | ||
|
|
bc259dbe01 | ||
|
|
3730e20248 | ||
|
|
1be413065d | ||
|
|
2721c20c8b | ||
|
|
80130f6ffd | ||
|
|
8da778eaba | ||
|
|
3c708d1aaf | ||
|
|
1ae1bef3c1 | ||
|
|
7fd0c1fddb | ||
|
|
fd9957b784 | ||
|
|
57da02dbad | ||
|
|
83a5b36ddc | ||
|
|
8c36d73775 | ||
|
|
8396b98f67 | ||
|
|
46d989ce7f | ||
|
|
75ac570486 | ||
|
|
242def9d06 | ||
|
|
959f32009b | ||
|
|
57796c217d | ||
|
|
cea3390e36 | ||
|
|
a756e80064 | ||
|
|
1f61d32877 | ||
|
|
da7e2c5e6e | ||
|
|
fd0940bfe9 | ||
|
|
2b4a495c07 | ||
|
|
cffb968d2e | ||
|
|
201ab3aee8 | ||
|
|
cfa3584dda | ||
|
|
f19ba93958 | ||
|
|
09a2572c3b | ||
|
|
c6316b4e8b | ||
|
|
9cd900b23f | ||
|
|
a6d30cb366 | ||
|
|
3e94a3f62a | ||
|
|
060f8264ff | ||
|
|
b7b3907647 | ||
|
|
1550555df1 | ||
|
|
c42a29a034 | ||
|
|
621bf6b82a |
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'
|
||||
12
.gitignore
vendored
12
.gitignore
vendored
@@ -2,11 +2,15 @@
|
||||
# will have compiled files and executables
|
||||
/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
|
||||
**/*.rs.bk
|
||||
|
||||
.vscode/
|
||||
|
||||
# Ignore build results from Nix
|
||||
*result*
|
||||
|
||||
/libs/
|
||||
*.AppImage
|
||||
*.blend1
|
||||
anchors.txt
|
||||
|
||||
29
.lapce/run.toml
Normal file
29
.lapce/run.toml
Normal file
@@ -0,0 +1,29 @@
|
||||
# The run config is used for both run mode and debug mode
|
||||
|
||||
[[configs]]
|
||||
# the name of this task
|
||||
name = "task"
|
||||
|
||||
# the type of the debugger. If not set, it can't be debugged but can still be run
|
||||
# type = "lldb"
|
||||
|
||||
# the program to run
|
||||
program = "./target/debug/stardust-xr-server"
|
||||
|
||||
# the program arguments, e.g. args = ["arg1", "arg2"], optional
|
||||
# args = []
|
||||
|
||||
# current working directory, optional
|
||||
cwd = "${workspace}"
|
||||
|
||||
# enviroment variables, optional
|
||||
# [configs.env]
|
||||
# VAR1 = "VAL1"
|
||||
# VAR2 = "VAL2"
|
||||
|
||||
# task to run before the run/debug session is started, optional
|
||||
# [configs.prelaunch]
|
||||
# program = "cargo"
|
||||
# args = [
|
||||
# "build",
|
||||
# ]
|
||||
3929
Cargo.lock
generated
Normal file
3929
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
146
Cargo.toml
146
Cargo.toml
@@ -1,51 +1,119 @@
|
||||
[package]
|
||||
edition = "2018"
|
||||
edition = "2021"
|
||||
rust-version = "1.75"
|
||||
name = "stardust-xr-server"
|
||||
version = "0.10.1"
|
||||
version = "0.45.0"
|
||||
authors = ["Nova King <technobaboo@proton.me>"]
|
||||
description = "Stardust XR reference display server"
|
||||
license = "GPLv2"
|
||||
repository = "https://github.com/StardustXR/stardust-xr-server/"
|
||||
homepage = "https://stardustxr.org"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.57"
|
||||
clap = { version = "4.0.8", features = ["derive"] }
|
||||
ctrlc = "3.2.2"
|
||||
dashmap = "5.3.4"
|
||||
flatbuffers = "2.1.2"
|
||||
flexbuffers = "2.0.0"
|
||||
glam = {version = "0.21.3", features = ["mint"]}
|
||||
lazy_static = "1.4.0"
|
||||
mint = "0.5.9"
|
||||
nanoid = "0.4.0"
|
||||
once_cell = "1.12.0"
|
||||
parking_lot = "0.12.1"
|
||||
portable-atomic = {version = "0.3.0", features = ["float", "std"]}
|
||||
rccell = "0.1.3"
|
||||
rustc-hash = "1.1.0"
|
||||
slab = "0.4.6"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
thiserror = "1.0.31"
|
||||
send_wrapper = "0.6.0"
|
||||
prisma = "0.1.1"
|
||||
slog = "2.7.0"
|
||||
slog-stdlog = "4.1.1"
|
||||
xkbcommon = { version = "0.5.0", default-features = false }
|
||||
stardust-xr = "0.5.2"
|
||||
wayland-backend = "=0.1.0-beta.9"
|
||||
wayland-scanner = "=0.30.0-beta.9"
|
||||
directories = "4.0.1"
|
||||
serde = { version = "1.0.145", features = ["derive"] }
|
||||
[workspace]
|
||||
members = ["codegen"]
|
||||
|
||||
[dependencies.stereokit]
|
||||
default-features = false
|
||||
features = ["linux-egl"]
|
||||
version = "0.5.0"
|
||||
[workspace.dependencies.stardust-xr]
|
||||
git = "https://github.com/StardustXR/core.git"
|
||||
|
||||
[[bin]]
|
||||
name = "stardust-xr-server"
|
||||
path = "src/main.rs"
|
||||
|
||||
[features]
|
||||
default = ["wayland"]
|
||||
wayland = ["dep:smithay", "dep:wayland-scanner", "dep:wayland-backend"]
|
||||
profile_tokio = ["dep:console-subscriber", "tokio/tracing"]
|
||||
profile_app = ["dep:tracing-tracy"]
|
||||
local_deps = ["stereokit-rust/force-local-deps"]
|
||||
|
||||
[package.metadata.appimage]
|
||||
auto_link = true
|
||||
auto_link_exclude_list = [
|
||||
"libc*",
|
||||
"libdl*",
|
||||
"libpthread*",
|
||||
"ld-linux*",
|
||||
"libGL*",
|
||||
"libEGL*",
|
||||
]
|
||||
|
||||
[profile.dev.package."*"]
|
||||
opt-level = 3
|
||||
debug = true
|
||||
strip = "none"
|
||||
debug-assertions = true
|
||||
overflow-checks = true
|
||||
|
||||
[profile.release]
|
||||
opt-level = 3
|
||||
debug = "line-tables-only"
|
||||
strip = "none"
|
||||
debug-assertions = true
|
||||
overflow-checks = false
|
||||
|
||||
[dependencies]
|
||||
# small utility thingys
|
||||
once_cell = "1.19.0"
|
||||
nanoid = "0.4.0"
|
||||
lazy_static = "1.5.0"
|
||||
rand = "0.8.5"
|
||||
rustc-hash = "2.0.0"
|
||||
portable-atomic = { version = "1.7.0", features = ["float", "std"] }
|
||||
send_wrapper = "0.6.0"
|
||||
slotmap = "1.0.7"
|
||||
global_counter = "=0.2.2"
|
||||
parking_lot = "0.12.3"
|
||||
|
||||
# rust errors/logging
|
||||
color-eyre = { version = "0.6.3", default-features = false }
|
||||
clap = { version = "4.5.13", features = ["derive"] }
|
||||
console-subscriber = { version = "0.4.0", optional = true }
|
||||
tracing = "0.1.40"
|
||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
|
||||
tracing-tracy = { version = "0.11.1", optional = true }
|
||||
|
||||
# (de)serialization
|
||||
serde = { version = "1.0.205", features = ["derive"] }
|
||||
serde_repr = "0.1.19"
|
||||
toml = "0.8.19"
|
||||
|
||||
# mathy stuffs
|
||||
glam = { version = "0.29.0", features = ["mint", "serde"] }
|
||||
mint = "0.5.9"
|
||||
tokio = { version = "1.39.2", features = ["rt-multi-thread", "signal", "time"] }
|
||||
prisma = "0.1.1"
|
||||
|
||||
# linux stuffs
|
||||
libc = "0.2.155"
|
||||
nix = "0.29.0"
|
||||
input-event-codes = "6.2.0"
|
||||
zbus = { version = "4.4.0", default-features = false, features = ["tokio"] }
|
||||
directories = "5.0.1"
|
||||
xkbcommon-rs = "0.1.0"
|
||||
|
||||
# wayland
|
||||
wayland-backend = { version = "0.3.7", optional = true, default-features = false }
|
||||
wayland-scanner = { version = "0.31.4", optional = true }
|
||||
|
||||
[dependencies.smithay]
|
||||
git = "https://github.com/technobaboo/smithay.git"
|
||||
branch = "feature/public_input"
|
||||
# git = "https://github.com/technobaboo/smithay.git"
|
||||
# git = "https://github.com/colinmarc/smithay.git"
|
||||
git = "https://github.com/smithay/smithay.git"
|
||||
# path = "../smithay"
|
||||
default-features = false
|
||||
features = ["desktop", "renderer_gl", "wayland_frontend"]
|
||||
version = "*"
|
||||
features = ["desktop", "backend_drm", "renderer_gl", "wayland_frontend"]
|
||||
optional = true
|
||||
|
||||
|
||||
[dependencies.stereokit-rust]
|
||||
# path = "../StereoKit-rust"
|
||||
git = "https://github.com/mvvvv/StereoKit-rust.git"
|
||||
# git = "https://github.com/technobaboo/StereoKit-rust.git"
|
||||
features = ["no-event-loop"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.stardust-xr]
|
||||
workspace = true
|
||||
|
||||
[dependencies.stardust-xr-server-codegen]
|
||||
path = "codegen"
|
||||
|
||||
172
README.md
172
README.md
@@ -1,22 +1,164 @@
|
||||
# Stardust XR Reference Server
|
||||
# Stardust XR Server
|
||||
|
||||
This project is a usable Linux display server that reinvents human-computer interaction for all kinds of XR, from putting 2D/XR apps into various 3D shells for varying uses to SDF-based interaction.
|
||||
Stardust XR is a display server for VR and AR headsets on Linux-based systems. [Stardust provides a 3D environment](https://www.youtube.com/watch?v=v2WblwbaLaA), where anything from 2D windows (including your existing apps!), to 3D apps built from objects, can exist together in physical space.
|
||||
|
||||
## Prerequisites
|
||||
1. Cargo
|
||||
2. CMake
|
||||
3. EGL+GLES 3.2
|
||||
4. GLX+Xlib
|
||||
5. fontconfig
|
||||
6. dlopen
|
||||
7. OpenXR Loader (required even if run in flatscreen mode)
|
||||

|
||||
|
||||
## Build
|
||||
## Core Dependencies
|
||||
| **Dependency** | **Ubuntu/Debian** | **Arch Linux** | **Fedora** |
|
||||
|-----------------------------|-------------------------------------------------------------------------------------------------|---------------------------------------------------|-------------------------------------------------------------|
|
||||
| **Cargo** | `cargo` | `cargo` | `cargo` |
|
||||
| **CMake** | `cmake` | `cmake` | `cmake` |
|
||||
| **EGL+GLES 3.2** | `libegl1-mesa-dev`, `libgles2-mesa-dev` | `mesa` *(provides EGL/GLES libraries and headers)* | `mesa-libEGL-devel`, `mesa-libGLES-devel` |
|
||||
| **GLX+Xlib** | `libx11-dev`, `libxfixes-dev`, `libxcb1-dev`, `libgl1-mesa-dev`, `libxkbcommon-dev` | `libx11`, `libxfixes`, `libxcb` *(and GLX via mesa)*| `libX11-devel`, `libXfixes-devel`, `libxcb-devel`, `mesa-libGL-devel` *(or equivalent)* |
|
||||
| **fontconfig** | `libfontconfig1-dev` | `fontconfig` | `fontconfig-devel` |
|
||||
| **dlopen** (glibc function) | Provided by `libc6-dev` (part of the core C library) | Provided by `glibc` *(included in base-devel)* | Provided by `glibc-devel` |
|
||||
| **OpenXR Loader** | `libopenxr-loader1`, `libopenxr-dev`, `libopenxr1-monado` | `openxr` | `openxr-devel` |
|
||||
|
||||
Command line installation of core & dynamic dependencies are provided below:
|
||||
<details>
|
||||
<summary>Ubuntu/Debian</summary>
|
||||
<pre><code class="language-bash">
|
||||
sudo apt-get update && sudo apt-get install -y \
|
||||
build-essential \
|
||||
cargo \
|
||||
cmake \
|
||||
libegl1-mesa-dev libgles2-mesa-dev \
|
||||
libx11-dev libxfixes-dev libxcb1-dev libxau-dev libgl1-mesa-dev libxkbcommon-dev \
|
||||
libfontconfig1-dev libfreetype6-dev libharfbuzz-dev libgraphite2-dev \
|
||||
libc6-dev \
|
||||
libopenxr-loader1 libopenxr-dev libopenxr1-monado libwayland-dev \
|
||||
libjsoncpp-dev libdrm-dev libexpat1-dev libxcb-randr0-dev \
|
||||
libxml2-dev libffi-dev libbz2-dev libpng-dev libbrotli-dev liblzma-dev libglib2.0-dev libpcre2-dev
|
||||
</code></pre>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Arch Linux</summary>
|
||||
<pre><code class="language-bash">
|
||||
sudo pacman -Syu --needed \
|
||||
base-devel \
|
||||
rust \
|
||||
cmake \
|
||||
mesa \
|
||||
libx11 \
|
||||
libxfixes \
|
||||
libxcb \
|
||||
libxkbcommon \
|
||||
fontconfig \
|
||||
freetype2 \
|
||||
openxr \
|
||||
jsoncpp \
|
||||
libffi \
|
||||
wayland \
|
||||
expat \
|
||||
libxml2 \
|
||||
libxau \
|
||||
bzip2 \
|
||||
xz \
|
||||
libpng \
|
||||
brotli \
|
||||
pcre2 \
|
||||
glib2 \
|
||||
libdrm
|
||||
</code></pre>
|
||||
</details>
|
||||
<details>
|
||||
<summary>Fedora</summary>
|
||||
<pre><code class="language-bash">
|
||||
sudo dnf group install development-tools && \
|
||||
sudo dnf install -y \
|
||||
cargo \
|
||||
cmake \
|
||||
mesa-libEGL-devel \
|
||||
mesa-libGLES-devel \
|
||||
libX11-devel \
|
||||
libXfixes-devel \
|
||||
libxcb-devel \
|
||||
libxkbcommon-devel \
|
||||
fontconfig-devel \
|
||||
freetype-devel \
|
||||
harfbuzz-devel \
|
||||
graphite2-devel \
|
||||
openxr-devel \
|
||||
wayland-devel \
|
||||
jsoncpp-devel \
|
||||
libdrm-devel \
|
||||
expat-devel \
|
||||
xcb-util-devel \
|
||||
libxml2-devel \
|
||||
libXau-devel \
|
||||
bzip2-devel \
|
||||
xz-devel \
|
||||
libpng-devel \
|
||||
brotli-devel \
|
||||
pcre2-devel \
|
||||
glib2-devel
|
||||
</code></pre>
|
||||
</details>
|
||||
|
||||
## Installation
|
||||
|
||||
More detailed instructions and walkthroughs are provided at https://www.stardustxr.org
|
||||
|
||||
The [Terra Repository](https://terra.fyralabs.com/) is required, and comes pre-installed with [Ultramarine Linux](https://ultramarine-linux.org/). Other Fedora Editions and derivatives can directly install terra-release:
|
||||
|
||||
```bash
|
||||
sudo dnf install --nogpgcheck --repofrompath 'terra,https://repos.fyralabs.com/terra$releasever' terra-release
|
||||
```
|
||||
|
||||
For a full installation of the Stardust XR server *and* a selected group of clients, run:
|
||||
|
||||
```bash
|
||||
sudo dnf group install stardust-xr
|
||||
```
|
||||
|
||||
## Manual Build
|
||||
We've provided a manual installation script [here](https://github.com/cyberneticmelon/usefulscripts/blob/main/stardustxr_setup.sh) that clones and builds the Stardust XR server along with a number of other clients from their respective repositories, and provides a startup script for automatically launching some clients.
|
||||
|
||||
After cloning the repository
|
||||
```bash
|
||||
cargo build
|
||||
```
|
||||
|
||||
## Install
|
||||
```bash
|
||||
cargo install
|
||||
```
|
||||
## Usage
|
||||
> [!NOTE]
|
||||
> For help with setting up an XR headset on linux, visit https://stardustxr.org/docs/get-started/setup-openxr
|
||||
|
||||
|
||||
The **Stardust XR Server** is a server that runs clients, so without any running, you will see a black screen. If you only have the server installed, we recommend also cloning and building the following clients to start: [Flatland](https://github.com/StardustXR/flatland), which allows normal 2D apps to run in Stardust, [Protostar](https://github.com/StardustXR/protostar), which contains Hexagon Launcher, an app launcher menu, and [Black Hole](https://github.com/StardustXR/black-hole) to quickly tuck away your objects and apps (kind of like desktop peek on Windows).
|
||||
|
||||
First, try running `cargo run -- -f` in a terminal window to check out flatscreen mode, (or `stardust-xr-server -f` / `stardust-xr-server_dev -f` if you installed via dnf or the manual installation script, respectively, as they provide symlinks.)
|
||||
|
||||
If there aren't already any clients running, you'll need to manually launch them by either navigating to their repositories and running `cargo run`, or running them via their names if you installed via dnf or the manual installation script, such as `flatland`, `hexagon_launcher`, etc.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> [Flatland](https://github.com/StardustXR/flatland) must be running for 2D apps to launch.
|
||||
|
||||
### Startup Script
|
||||
A startup script can be created at `~/.config/stardust/startup` that will launch specified settings and clients/applications, an example of which is shown [here](https://github.com/cyberneticmelon/usefulscripts/blob/main/startup). If you used the [installation script](https://github.com/cyberneticmelon/usefulscripts/blob/main/stardustxr_setup.sh), one will have already been made for you. This allows wide flexibility of what clients to launch upon startup (and, for example, *where*, using the [Gravity](https://github.com/StardustXR/gravity) client to specify X Y and Z co-ordinates).
|
||||
|
||||
### Flatscreen Navigation
|
||||
A video guide showcasing flatscreen controls is available [here](https://www.youtube.com/watch?v=JCYecSlKlDI)
|
||||
|
||||
To move around, hold down `Shift + W A S D`, with `Q` for moving down and `E` for moving up.
|
||||

|
||||
|
||||
To look around, hold down `Shift + Right` Click while moving the mouse.
|
||||

|
||||
|
||||
To drag applications out of the app launcher, hold down `Shift + ~`
|
||||

|
||||
|
||||
### XR Navigation
|
||||
A video guide showcasing XR controls is available [here](https://www.youtube.com/watch?v=RbxFq6JjliA)
|
||||
|
||||
**Quest 3 Hand tracking**:
|
||||
Pinch to drag and drop, grasp with full hand for grabbing, point and click with pointer finger to click or pinch from a distance
|
||||
|
||||

|
||||
|
||||
**Quest 3 Controller**:
|
||||
Grab with the grip buttons, click by touching the tip of the cones or by using the trigger from a distance
|
||||
|
||||

|
||||
|
||||
16
codegen/Cargo.toml
Normal file
16
codegen/Cargo.toml
Normal file
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
edition = "2021"
|
||||
name = "stardust-xr-server-codegen"
|
||||
version = "0.1.0"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
convert_case = "0.6.0"
|
||||
quote = "1.0.33"
|
||||
mint = "0.5.9"
|
||||
proc-macro2 = "1.0.71"
|
||||
split-iter = "0.1.0"
|
||||
|
||||
stardust-xr = { workspace = true }
|
||||
617
codegen/src/lib.rs
Normal file
617
codegen/src/lib.rs
Normal file
@@ -0,0 +1,617 @@
|
||||
use convert_case::{Case, Casing};
|
||||
use proc_macro2::{Ident, Span, TokenStream};
|
||||
use quote::{quote, ToTokens};
|
||||
use split_iter::Splittable;
|
||||
use stardust_xr::schemas::protocol::*;
|
||||
|
||||
fn fold_tokens(a: TokenStream, b: TokenStream) -> TokenStream {
|
||||
quote!(#a #b)
|
||||
}
|
||||
|
||||
#[proc_macro]
|
||||
pub fn codegen_root_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(ROOT_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_node_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(NODE_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_spatial_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(SPATIAL_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_field_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(FIELD_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_data_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(DATA_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_audio_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(AUDIO_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_drawable_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(DRAWABLE_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_input_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(INPUT_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_item_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(ITEM_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_item_camera_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(ITEM_CAMERA_PROTOCOL)
|
||||
}
|
||||
#[proc_macro]
|
||||
pub fn codegen_item_panel_protocol(_input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
codegen_protocol(ITEM_PANEL_PROTOCOL)
|
||||
}
|
||||
|
||||
fn codegen_protocol(protocol: &'static str) -> proc_macro::TokenStream {
|
||||
let protocol = Protocol::parse(protocol).unwrap();
|
||||
let interface = protocol
|
||||
.interface
|
||||
.map(|p| {
|
||||
let node_id = p.node_id;
|
||||
let node_id = quote! {
|
||||
const INTERFACE_NODE_ID: u64 = #node_id;
|
||||
};
|
||||
let aspect = generate_aspect(&Aspect {
|
||||
name: "interface".to_string(),
|
||||
description: protocol.description.clone(),
|
||||
inherits: vec![],
|
||||
members: p.members,
|
||||
});
|
||||
quote!(#node_id #aspect)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let custom_enums = protocol
|
||||
.custom_enums
|
||||
.iter()
|
||||
.map(generate_custom_enum)
|
||||
.reduce(fold_tokens)
|
||||
.unwrap_or_default();
|
||||
let custom_unions = protocol
|
||||
.custom_unions
|
||||
.iter()
|
||||
.map(generate_custom_union)
|
||||
.reduce(fold_tokens)
|
||||
.unwrap_or_default();
|
||||
let custom_structs = protocol
|
||||
.custom_structs
|
||||
.iter()
|
||||
.map(generate_custom_struct)
|
||||
.reduce(fold_tokens)
|
||||
.unwrap_or_default();
|
||||
let aspects = protocol
|
||||
.aspects
|
||||
.iter()
|
||||
.map(generate_aspect)
|
||||
.reduce(fold_tokens)
|
||||
.unwrap_or_default();
|
||||
quote!(#custom_enums #custom_unions #custom_structs #aspects #interface).into()
|
||||
}
|
||||
|
||||
fn generate_custom_enum(custom_enum: &CustomEnum) -> TokenStream {
|
||||
let name = Ident::new(&custom_enum.name.to_case(Case::Pascal), Span::call_site());
|
||||
let description = &custom_enum.description;
|
||||
|
||||
let argument_decls = custom_enum
|
||||
.variants
|
||||
.iter()
|
||||
.map(|a| Ident::new(&a.to_case(Case::Pascal), Span::call_site()).to_token_stream())
|
||||
.reduce(|a, b| quote!(#a, #b))
|
||||
.unwrap_or_default();
|
||||
|
||||
quote! {
|
||||
#[doc = #description]
|
||||
#[derive(Debug, Clone, Copy, serde_repr::Deserialize_repr, serde_repr::Serialize_repr)]
|
||||
#[repr(u32)]
|
||||
pub enum #name {#argument_decls}
|
||||
}
|
||||
}
|
||||
fn generate_custom_union(custom_union: &CustomUnion) -> TokenStream {
|
||||
let name = Ident::new(&custom_union.name.to_case(Case::Pascal), Span::call_site());
|
||||
let description = &custom_union.description;
|
||||
|
||||
let option_decls = custom_union
|
||||
.options
|
||||
.iter()
|
||||
.map(generate_union_option)
|
||||
.reduce(|a, b| quote!(#a, #b))
|
||||
.unwrap_or_default();
|
||||
|
||||
quote! {
|
||||
#[doc = #description]
|
||||
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum #name {#option_decls}
|
||||
}
|
||||
}
|
||||
fn generate_union_option(union_option: &UnionOption) -> TokenStream {
|
||||
let name = union_option
|
||||
.name
|
||||
.as_ref()
|
||||
.map(|n| n.to_case(Case::Pascal))
|
||||
.unwrap_or_else(|| argument_type_option_name(&union_option._type));
|
||||
let description = union_option
|
||||
.description
|
||||
.as_ref()
|
||||
.map(|d| quote!(#[doc = #d]))
|
||||
.unwrap_or_default();
|
||||
let identifier = Ident::new(&name, Span::call_site());
|
||||
let _type = generate_argument_type(&union_option._type, false, true);
|
||||
quote! (#description #identifier(#_type))
|
||||
}
|
||||
fn generate_custom_struct(custom_struct: &CustomStruct) -> TokenStream {
|
||||
let name = Ident::new(&custom_struct.name.to_case(Case::Pascal), Span::call_site());
|
||||
let description = &custom_struct.description;
|
||||
|
||||
let argument_decls = custom_struct
|
||||
.fields
|
||||
.iter()
|
||||
.map(|a| generate_argument_decl(a, true))
|
||||
.map(|d| quote!(pub #d))
|
||||
.reduce(|a, b| quote!(#a, #b))
|
||||
.unwrap_or_default();
|
||||
|
||||
quote! {
|
||||
#[doc = #description]
|
||||
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
|
||||
pub struct #name {#argument_decls}
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_aspect(aspect: &Aspect) -> TokenStream {
|
||||
let description = &aspect.description;
|
||||
let (client_members, server_members) = aspect.members.iter().split(|m| m.side == Side::Server);
|
||||
|
||||
let client_mod_name = Ident::new(
|
||||
&format!("{}_client", &aspect.name.to_case(Case::Snake)),
|
||||
Span::call_site(),
|
||||
);
|
||||
let client_side_members = client_members
|
||||
.map(generate_member)
|
||||
.reduce(fold_tokens)
|
||||
.map(|t| {
|
||||
// TODO: properly import all dependencies
|
||||
quote! {
|
||||
pub mod #client_mod_name {
|
||||
use super::*;
|
||||
#t
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let aspect_trait_name = Ident::new(
|
||||
&format!("{}Aspect", &aspect.name.to_case(Case::Pascal)),
|
||||
Span::call_site(),
|
||||
);
|
||||
|
||||
let opcodes = aspect
|
||||
.members
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let aspect_name = aspect.name.to_case(Case::ScreamingSnake);
|
||||
let member_name = m.name.to_case(Case::ScreamingSnake);
|
||||
let name_type = if m.side == Side::Client {
|
||||
"CLIENT"
|
||||
} else {
|
||||
"SERVER"
|
||||
};
|
||||
let name = Ident::new(
|
||||
&format!("{aspect_name}_{member_name}_{name_type}_OPCODE"),
|
||||
Span::call_site(),
|
||||
);
|
||||
let opcode = m.opcode;
|
||||
|
||||
quote!(pub(crate) const #name: u64 = #opcode;)
|
||||
})
|
||||
.reduce(fold_tokens)
|
||||
.unwrap_or_default();
|
||||
let alias_info = generate_alias_info(aspect);
|
||||
|
||||
let server_side_members = server_members
|
||||
.map(generate_member)
|
||||
.reduce(fold_tokens)
|
||||
.unwrap_or_default();
|
||||
let add_node_members = aspect
|
||||
.members
|
||||
.iter()
|
||||
.filter(|m| m.side == Side::Server)
|
||||
.map(generate_handler)
|
||||
.reduce(fold_tokens)
|
||||
.map(|members| {
|
||||
quote! {
|
||||
fn add_node_members(node: &crate::nodes::Node) {
|
||||
#members
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let server_side_members = quote! {
|
||||
#[doc = #description]
|
||||
pub trait #aspect_trait_name {
|
||||
#add_node_members
|
||||
#server_side_members
|
||||
}
|
||||
};
|
||||
quote!(#opcodes #alias_info #client_side_members #server_side_members)
|
||||
}
|
||||
|
||||
fn generate_alias_opcodes(aspect: &Aspect, side: Side, _type: MemberType) -> TokenStream {
|
||||
aspect
|
||||
.members
|
||||
.iter()
|
||||
.filter(|m| m.side == side)
|
||||
.filter(|m| m._type == _type)
|
||||
.map(|m| m.opcode)
|
||||
.map(|o| quote!(#o))
|
||||
.reduce(|a, b| quote!(#a, #b))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
fn generate_alias_info(aspect: &Aspect) -> TokenStream {
|
||||
let aspect_alias_info_name = Ident::new(
|
||||
&format!(
|
||||
"{}_ASPECT_ALIAS_INFO",
|
||||
aspect.name.to_case(Case::ScreamingSnake)
|
||||
),
|
||||
Span::call_site(),
|
||||
);
|
||||
let local_signals = generate_alias_opcodes(aspect, Side::Server, MemberType::Signal);
|
||||
let local_methods = generate_alias_opcodes(aspect, Side::Server, MemberType::Method);
|
||||
let remote_signals = generate_alias_opcodes(aspect, Side::Client, MemberType::Signal);
|
||||
|
||||
let inherits = aspect
|
||||
.inherits
|
||||
.iter()
|
||||
.map(|a| {
|
||||
Ident::new(
|
||||
&format!("{}_ASPECT_ALIAS_INFO", a.to_case(Case::ScreamingSnake)),
|
||||
Span::call_site(),
|
||||
)
|
||||
})
|
||||
.map(|a| quote!(#a.clone()))
|
||||
.fold(quote!(), |a, b| quote!(#a + #b));
|
||||
|
||||
quote! {
|
||||
lazy_static::lazy_static! {
|
||||
pub static ref #aspect_alias_info_name: crate::nodes::alias::AliasInfo = crate::nodes::alias::AliasInfo {
|
||||
server_signals: vec![#local_signals],
|
||||
server_methods: vec![#local_methods],
|
||||
client_signals: vec![#remote_signals],
|
||||
}
|
||||
#inherits;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_member(member: &Member) -> TokenStream {
|
||||
let id = member.opcode;
|
||||
let name = Ident::new(&member.name.to_case(Case::Snake), Span::call_site());
|
||||
let description = &member.description;
|
||||
|
||||
let side = member.side;
|
||||
let _type = member._type;
|
||||
|
||||
let first_args = match member.side {
|
||||
Side::Server => {
|
||||
quote!(_node: std::sync::Arc<crate::nodes::Node>, _calling_client: std::sync::Arc<crate::core::client::Client>)
|
||||
}
|
||||
Side::Client => quote!(_node: &crate::nodes::Node),
|
||||
};
|
||||
let argument_decls = member
|
||||
.arguments
|
||||
.iter()
|
||||
.map(|a| generate_argument_decl(a, member.side == Side::Server))
|
||||
.fold(first_args, |a, b| quote!(#a, #b));
|
||||
|
||||
let argument_uses = member
|
||||
.arguments
|
||||
.iter()
|
||||
.map(|a| generate_argument_serialize(&a.name, &a._type, a.optional))
|
||||
.reduce(|a, b| quote!(#a, #b))
|
||||
.unwrap_or_default();
|
||||
let return_type = member
|
||||
.return_type
|
||||
.as_ref()
|
||||
.map(|r| generate_argument_type(r, false, true))
|
||||
.unwrap_or_else(|| quote!(()));
|
||||
|
||||
match (side, _type) {
|
||||
(Side::Client, MemberType::Method) => {
|
||||
quote! {
|
||||
#[doc = #description]
|
||||
pub async fn #name(#argument_decls) -> color_eyre::eyre::Result<(#return_type, Vec<std::os::fd::OwnedFd>)> {
|
||||
_node.execute_remote_method_typed(#id, &(#argument_uses), vec![]).await
|
||||
}
|
||||
}
|
||||
}
|
||||
(Side::Client, MemberType::Signal) => {
|
||||
quote! {
|
||||
#[doc = #description]
|
||||
pub fn #name(#argument_decls) -> color_eyre::eyre::Result<()> {
|
||||
let serialized = stardust_xr::schemas::flex::serialize((#argument_uses))?;
|
||||
_node.send_remote_signal(#id, serialized)
|
||||
}
|
||||
}
|
||||
}
|
||||
(Side::Server, MemberType::Method) => {
|
||||
quote! {
|
||||
#[doc = #description]
|
||||
fn #name(#argument_decls) -> impl std::future::Future<Output = color_eyre::eyre::Result<#return_type>> + Send + 'static;
|
||||
}
|
||||
}
|
||||
(Side::Server, MemberType::Signal) => {
|
||||
quote! {
|
||||
#[doc = #description]
|
||||
fn #name(#argument_decls) -> color_eyre::eyre::Result<()>;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn generate_handler(member: &Member) -> TokenStream {
|
||||
let opcode = member.opcode;
|
||||
let member_name_ident = Ident::new(&member.name, Span::call_site());
|
||||
|
||||
let argument_names = member
|
||||
.arguments
|
||||
.iter()
|
||||
.map(generate_argument_name)
|
||||
.reduce(|a, b| quote!(#a, #b));
|
||||
let argument_types = member
|
||||
.arguments
|
||||
.iter()
|
||||
.map(|a| {
|
||||
let _type = convert_deserializeable_argument_type(&a._type);
|
||||
generate_argument_type(&_type, a.optional, true)
|
||||
})
|
||||
.reduce(|a, b| quote!(#a, #b));
|
||||
// dbg!(&argument_types);
|
||||
let deserialize = argument_names
|
||||
.clone()
|
||||
.zip(argument_types)
|
||||
.map(|(argument_names, argument_types)| {
|
||||
quote!(let (#argument_names): (#argument_types) = stardust_xr::schemas::flex::deserialize(_message.as_ref())?;)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let serialize = generate_argument_serialize(
|
||||
"result",
|
||||
&member.return_type.clone().unwrap_or(ArgumentType::Empty),
|
||||
false,
|
||||
);
|
||||
let argument_uses = member
|
||||
.arguments
|
||||
.iter()
|
||||
.map(|a| generate_argument_deserialize(&a.name, &a._type, a.optional))
|
||||
.reduce(|a, b| quote!(#a, #b))
|
||||
.unwrap_or_default();
|
||||
match member._type {
|
||||
MemberType::Signal => quote! {
|
||||
node.add_local_signal(#opcode, |_node, _calling_client, _message| {
|
||||
#deserialize
|
||||
Self::#member_name_ident(_node, _calling_client.clone(), #argument_uses)
|
||||
});
|
||||
},
|
||||
MemberType::Method => quote! {
|
||||
node.add_local_method(#opcode, |_node, _calling_client, _message, _method_response| {
|
||||
_method_response.wrap_async(async move {
|
||||
#deserialize
|
||||
let result = Self::#member_name_ident(_node, _calling_client.clone(), #argument_uses).await?;
|
||||
Ok((#serialize, Vec::new()))
|
||||
});
|
||||
});
|
||||
},
|
||||
}
|
||||
}
|
||||
fn generate_argument_name(argument: &Argument) -> TokenStream {
|
||||
Ident::new(&argument.name.to_case(Case::Snake), Span::call_site()).to_token_stream()
|
||||
}
|
||||
|
||||
fn convert_deserializeable_argument_type(argument_type: &ArgumentType) -> ArgumentType {
|
||||
match argument_type {
|
||||
ArgumentType::Node { .. } => ArgumentType::NodeID,
|
||||
ArgumentType::Vec(v) => {
|
||||
ArgumentType::Vec(Box::new(convert_deserializeable_argument_type(v.as_ref())))
|
||||
}
|
||||
ArgumentType::Map(v) => {
|
||||
ArgumentType::Map(Box::new(convert_deserializeable_argument_type(v.as_ref())))
|
||||
}
|
||||
f => f.clone(),
|
||||
}
|
||||
}
|
||||
fn generate_argument_deserialize(
|
||||
argument_name: &str,
|
||||
argument_type: &ArgumentType,
|
||||
optional: bool,
|
||||
) -> TokenStream {
|
||||
let name = Ident::new(&argument_name.to_case(Case::Snake), Span::call_site());
|
||||
if let ArgumentType::Node { .. } = argument_type {
|
||||
return match optional {
|
||||
true => quote!(#name.map(|n| _calling_client.get_node(#argument_name, n)?)),
|
||||
false => quote!(_calling_client.get_node(#argument_name, #name)?),
|
||||
};
|
||||
}
|
||||
if optional {
|
||||
let mapping = generate_argument_deserialize("o", argument_type, false);
|
||||
return quote!(#name.map(|o| Ok::<_, color_eyre::eyre::Report>(#mapping)).transpose()?);
|
||||
}
|
||||
|
||||
match argument_type {
|
||||
ArgumentType::Color => quote!(color::rgba_linear!(#name[0], #name[1], #name[2], #name[3])),
|
||||
ArgumentType::Vec(v) => {
|
||||
let mapping = generate_argument_deserialize("a", v, false);
|
||||
quote!(#name.into_iter().map(|a| Ok(#mapping)).collect::<color_eyre::eyre::Result<Vec<_>>>()?)
|
||||
}
|
||||
ArgumentType::Map(v) => {
|
||||
let mapping = generate_argument_deserialize("a", v, false);
|
||||
quote!(#name.into_iter().map(|(k, a)| Ok((k, #mapping))).collect::<color_eyre::eyre::Result<rustc_hash::FxHashMap<String, _>>>()?)
|
||||
}
|
||||
_ => quote!(#name),
|
||||
}
|
||||
}
|
||||
fn generate_argument_serialize(
|
||||
argument_name: &str,
|
||||
argument_type: &ArgumentType,
|
||||
optional: bool,
|
||||
) -> TokenStream {
|
||||
let name = Ident::new(&argument_name.to_case(Case::Snake), Span::call_site());
|
||||
match argument_type {
|
||||
ArgumentType::Node {
|
||||
_type,
|
||||
return_id_parameter_name: _,
|
||||
} => match optional {
|
||||
true => quote!(#name.map(|n| n.get_id())),
|
||||
false => quote!(#name.get_id()),
|
||||
},
|
||||
ArgumentType::Color => quote!([#name.c.r, #name.c.g, #name.c.b, #name.a]),
|
||||
ArgumentType::Vec(v) => {
|
||||
let mapping = generate_argument_serialize("a", v, false);
|
||||
quote!(#name.into_iter().map(|a| Ok(#mapping)).collect::<color_eyre::eyre::Result<Vec<_>>>()?)
|
||||
}
|
||||
ArgumentType::Map(v) => {
|
||||
let mapping = generate_argument_serialize("a", v, false);
|
||||
quote!(#name.into_iter().map(|(k, a)| Ok((k, #mapping))).collect::<color_eyre::eyre::Result<rustc_hash::FxHashMap<String, _>>>()?)
|
||||
}
|
||||
_ => quote!(#name),
|
||||
}
|
||||
}
|
||||
fn generate_argument_decl(argument: &Argument, owned_values: bool) -> TokenStream {
|
||||
let name = Ident::new(&argument.name.to_case(Case::Snake), Span::call_site());
|
||||
let mut _type = generate_argument_type(&argument._type, argument.optional, owned_values);
|
||||
quote!(#name: #_type)
|
||||
}
|
||||
fn argument_type_option_name(argument_type: &ArgumentType) -> String {
|
||||
match argument_type {
|
||||
ArgumentType::Empty => "Empty".to_string(),
|
||||
ArgumentType::Bool => "Bool".to_string(),
|
||||
ArgumentType::Int => "Int".to_string(),
|
||||
ArgumentType::UInt => "UInt".to_string(),
|
||||
ArgumentType::Float => "Float".to_string(),
|
||||
ArgumentType::Vec2(_) => "Vec2".to_string(),
|
||||
ArgumentType::Vec3(_) => "Vec3".to_string(),
|
||||
ArgumentType::Quat => "Quat".to_string(),
|
||||
ArgumentType::Mat4 => "Mat4".to_string(),
|
||||
ArgumentType::Color => "Color".to_string(),
|
||||
ArgumentType::String => "String".to_string(),
|
||||
ArgumentType::Bytes => "Bytes".to_string(),
|
||||
ArgumentType::Vec(v) => format!("{}Vector", argument_type_option_name(v)),
|
||||
ArgumentType::Map(m) => format!("{}Map", argument_type_option_name(m)),
|
||||
ArgumentType::NodeID => "Node ID".to_string(),
|
||||
ArgumentType::Datamap => "Datamap".to_string(),
|
||||
ArgumentType::ResourceID => "ResourceID".to_string(),
|
||||
ArgumentType::Enum(e) => e.clone(),
|
||||
ArgumentType::Union(u) => u.clone(),
|
||||
ArgumentType::Struct(s) => s.clone(),
|
||||
ArgumentType::Node { _type, .. } => _type.clone(),
|
||||
}
|
||||
}
|
||||
fn generate_argument_type(
|
||||
argument_type: &ArgumentType,
|
||||
optional: bool,
|
||||
owned: bool,
|
||||
) -> TokenStream {
|
||||
let _type = match argument_type {
|
||||
ArgumentType::Empty => quote!(()),
|
||||
ArgumentType::Bool => quote!(bool),
|
||||
ArgumentType::Int => quote!(i32),
|
||||
ArgumentType::UInt => quote!(u32),
|
||||
ArgumentType::Float => quote!(f32),
|
||||
ArgumentType::Vec2(t) => {
|
||||
let t = generate_argument_type(t, false, true);
|
||||
quote!(stardust_xr::values::Vector2<#t>)
|
||||
}
|
||||
ArgumentType::Vec3(t) => {
|
||||
let t = generate_argument_type(t, false, true);
|
||||
quote!(stardust_xr::values::Vector3<#t>)
|
||||
}
|
||||
ArgumentType::Quat => quote!(stardust_xr::values::Quaternion),
|
||||
ArgumentType::Mat4 => quote!(stardust_xr::values::Mat4),
|
||||
ArgumentType::Color => quote!(stardust_xr::values::Color),
|
||||
ArgumentType::Bytes => {
|
||||
if !owned {
|
||||
quote!(&[u8])
|
||||
} else {
|
||||
quote!(Vec<u8>)
|
||||
}
|
||||
}
|
||||
ArgumentType::String => {
|
||||
if !owned {
|
||||
quote!(&str)
|
||||
} else {
|
||||
quote!(String)
|
||||
}
|
||||
}
|
||||
ArgumentType::Vec(t) => {
|
||||
let t = generate_argument_type(t, false, true);
|
||||
if !owned {
|
||||
quote!(&[#t])
|
||||
} else {
|
||||
quote!(Vec<#t>)
|
||||
}
|
||||
}
|
||||
ArgumentType::Map(t) => {
|
||||
let t = generate_argument_type(t, false, true);
|
||||
|
||||
if !owned {
|
||||
quote!(&stardust_xr::values::Map<String, #t>)
|
||||
} else {
|
||||
quote!(stardust_xr::values::Map<String, #t>)
|
||||
}
|
||||
}
|
||||
ArgumentType::NodeID => quote!(u64),
|
||||
ArgumentType::Datamap => {
|
||||
if !owned {
|
||||
quote!(&stardust_xr::values::Datamap)
|
||||
} else {
|
||||
quote!(stardust_xr::values::Datamap)
|
||||
}
|
||||
}
|
||||
ArgumentType::ResourceID => {
|
||||
if !owned {
|
||||
quote!(&stardust_xr::values::ResourceID)
|
||||
} else {
|
||||
quote!(stardust_xr::values::ResourceID)
|
||||
}
|
||||
}
|
||||
ArgumentType::Enum(e) => {
|
||||
let enum_name = Ident::new(&e.to_case(Case::Pascal), Span::call_site());
|
||||
quote!(#enum_name)
|
||||
}
|
||||
ArgumentType::Union(u) => {
|
||||
let union_name = Ident::new(&u.to_case(Case::Pascal), Span::call_site());
|
||||
quote!(#union_name)
|
||||
}
|
||||
ArgumentType::Struct(s) => {
|
||||
let struct_name = Ident::new(&s.to_case(Case::Pascal), Span::call_site());
|
||||
if !owned {
|
||||
quote!(&#struct_name)
|
||||
} else {
|
||||
quote!(#struct_name)
|
||||
}
|
||||
}
|
||||
ArgumentType::Node {
|
||||
_type,
|
||||
return_id_parameter_name: _,
|
||||
} => {
|
||||
if !owned {
|
||||
quote!(&std::sync::Arc<crate::nodes::Node>)
|
||||
} else {
|
||||
quote!(std::sync::Arc<crate::nodes::Node>)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if optional {
|
||||
quote!(Option<#_type>)
|
||||
} else {
|
||||
_type
|
||||
}
|
||||
}
|
||||
171
flake.lock
generated
Normal file
171
flake.lock
generated
Normal file
@@ -0,0 +1,171 @@
|
||||
{
|
||||
"nodes": {
|
||||
"crane": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"flatland",
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1712681629,
|
||||
"narHash": "sha256-bMDXn4AkTXLCpoZbII6pDGoSeSe9gI87jxPsHRXgu/E=",
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"rev": "220387ac8e99cbee0ca4c95b621c4bc782b6a235",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"flake-parts": {
|
||||
"inputs": {
|
||||
"nixpkgs-lib": "nixpkgs-lib"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1722555600,
|
||||
"narHash": "sha256-XOQkdLafnb/p9ij77byFQjDf5m5QYl9b2REiVClC+x4=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"rev": "8471fe90ad337a8074e957b69ca4d0089218391d",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"flake-parts_2": {
|
||||
"inputs": {
|
||||
"nixpkgs-lib": [
|
||||
"hercules-ci-effects",
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1712014858,
|
||||
"narHash": "sha256-sB4SWl2lX95bExY2gMFG5HIzvva5AVMJd4Igm+GpZNw=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"rev": "9126214d0a59633752a136528f5f3b9aa8565b7d",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"id": "flake-parts",
|
||||
"type": "indirect"
|
||||
}
|
||||
},
|
||||
"flatland": {
|
||||
"inputs": {
|
||||
"crane": "crane",
|
||||
"nixpkgs": "nixpkgs"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1713050562,
|
||||
"narHash": "sha256-m7c6XpmpTM1URuqMG2KqtaWbL2Vt8vJFJtmvq123BmY=",
|
||||
"owner": "StardustXR",
|
||||
"repo": "flatland",
|
||||
"rev": "b3b0f29c4ea1b82c96cf9de507837bf15a5e4c0e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "StardustXR",
|
||||
"repo": "flatland",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"hercules-ci-effects": {
|
||||
"inputs": {
|
||||
"flake-parts": "flake-parts_2",
|
||||
"nixpkgs": "nixpkgs_2"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1719226092,
|
||||
"narHash": "sha256-YNkUMcCUCpnULp40g+svYsaH1RbSEj6s4WdZY/SHe38=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "hercules-ci-effects",
|
||||
"rev": "11e4b8dc112e2f485d7c97e1cee77f9958f498f5",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "hercules-ci",
|
||||
"repo": "hercules-ci-effects",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1712791164,
|
||||
"narHash": "sha256-3sbWO1mbpWsLepZGbWaMovSO7ndZeFqDSdX0hZ9nVyw=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "1042fd8b148a9105f3c0aca3a6177fd1d9360ba5",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs-lib": {
|
||||
"locked": {
|
||||
"lastModified": 1722555339,
|
||||
"narHash": "sha256-uFf2QeW7eAHlYXuDktm9c25OxOyCoUOQmh5SZ9amE5Q=",
|
||||
"type": "tarball",
|
||||
"url": "https://github.com/NixOS/nixpkgs/archive/a5d394176e64ab29c852d03346c1fc9b0b7d33eb.tar.gz"
|
||||
},
|
||||
"original": {
|
||||
"type": "tarball",
|
||||
"url": "https://github.com/NixOS/nixpkgs/archive/a5d394176e64ab29c852d03346c1fc9b0b7d33eb.tar.gz"
|
||||
}
|
||||
},
|
||||
"nixpkgs_2": {
|
||||
"locked": {
|
||||
"lastModified": 1713714899,
|
||||
"narHash": "sha256-+z/XjO3QJs5rLE5UOf015gdVauVRQd2vZtsFkaXBq2Y=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "6143fc5eeb9c4f00163267708e26191d1e918932",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs_3": {
|
||||
"locked": {
|
||||
"lastModified": 1723991338,
|
||||
"narHash": "sha256-Grh5PF0+gootJfOJFenTTxDTYPidA3V28dqJ/WV7iis=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "8a3354191c0d7144db9756a74755672387b702ba",
|
||||
"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_3"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
91
flake.nix
Normal file
91
flake.nix
Normal file
@@ -0,0 +1,91 @@
|
||||
{
|
||||
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 = let sk_gpu = pkgs.callPackage ./nix/sk_gpu.nix { };
|
||||
in {
|
||||
default = self'.packages.${name};
|
||||
gnome-graphical-test = self'.checks.gnome-graphical-test;
|
||||
"${name}" = pkgs.callPackage ./nix/stardust-xr-server.nix {
|
||||
inherit name src sk_gpu;
|
||||
};
|
||||
};
|
||||
apps.default = {
|
||||
type = "app";
|
||||
program = self'.packages.${name} + "/bin/stardust-xr-server";
|
||||
};
|
||||
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 { ref, 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 "Ref;${ref}" \
|
||||
--field "Commit ID;${rev}" \
|
||||
--field "Flatland Revision;${flatland.rev}" \
|
||||
--field "Reproducer;\`nix build github:stardustxr/server/${rev}#gnome-graphical-test\`" \
|
||||
--image "$ADDRESS"
|
||||
'';
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
BIN
img/workflow.png
Normal file
BIN
img/workflow.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 872 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")
|
||||
'';
|
||||
}
|
||||
27
nix/meshoptimizer.nix
Normal file
27
nix/meshoptimizer.nix
Normal file
@@ -0,0 +1,27 @@
|
||||
{ lib, stdenv, fetchFromGitHub, cmake }:
|
||||
|
||||
stdenv.mkDerivation rec {
|
||||
pname = "meshoptimizer";
|
||||
version = "0.20";
|
||||
|
||||
src = fetchFromGitHub {
|
||||
owner = "zeux";
|
||||
repo = "meshoptimizer";
|
||||
rev = "c21d3be6ddf627f8ca852ba4b6db9903b0557858";
|
||||
sha256 = "sha256-QCxpM2g8WtYSZHkBzLTJNQ/oHb5j/n9rjaVmZJcCZIA=";
|
||||
};
|
||||
|
||||
nativeBuildInputs = [ cmake ];
|
||||
|
||||
cmakeFlags = [
|
||||
"-DCMAKE_POSITION_INDEPENDENT_CODE=ON"
|
||||
];
|
||||
|
||||
meta = with lib; {
|
||||
description = "Mesh optimization library that makes meshes smaller and faster to render";
|
||||
homepage = "https://github.com/zeux/meshoptimizer";
|
||||
license = licenses.mit;
|
||||
platforms = platforms.all;
|
||||
};
|
||||
}
|
||||
|
||||
16
nix/sk_gpu.nix
Normal file
16
nix/sk_gpu.nix
Normal file
@@ -0,0 +1,16 @@
|
||||
{ stdenv, fetchurl, unzip }:
|
||||
|
||||
let
|
||||
sk_gpu_zip = fetchurl {
|
||||
url =
|
||||
"https://github.com/StereoKit/sk_gpu/releases/download/v2024.8.16/sk_gpu.v2024.8.16.zip";
|
||||
sha256 = "sha256-Wk3PZFlWqhrsQ8xG0sQaV2xSasdg2D7TMiPvl/CgtGU=";
|
||||
};
|
||||
in stdenv.mkDerivation rec {
|
||||
name = "sk_gpu";
|
||||
src = sk_gpu_zip;
|
||||
unpackPhase = ''
|
||||
unzip -d $out ${sk_gpu_zip}
|
||||
'';
|
||||
nativeBuildInputs = [ unzip ];
|
||||
}
|
||||
86
nix/stardust-xr-server.nix
Normal file
86
nix/stardust-xr-server.nix
Normal file
@@ -0,0 +1,86 @@
|
||||
{ rustPlatform
|
||||
, src
|
||||
, name
|
||||
, libGL
|
||||
, mesa
|
||||
, xorg
|
||||
, fontconfig
|
||||
, libxkbcommon
|
||||
, libclang
|
||||
|
||||
, cmake
|
||||
, cpm-cmake
|
||||
, pkg-config
|
||||
, llvmPackages
|
||||
, fetchFromGitHub
|
||||
, sk_gpu
|
||||
, libXau
|
||||
|
||||
, libXdmcp
|
||||
, stdenv
|
||||
, lib
|
||||
, openxr-loader
|
||||
}:
|
||||
|
||||
rustPlatform.buildRustPackage rec {
|
||||
inherit src name;
|
||||
cargoLock = {
|
||||
lockFile = (src + "/Cargo.lock");
|
||||
allowBuiltinFetchGit = true;
|
||||
};
|
||||
buildFeatures = [ "local_deps" ];
|
||||
FORCE_LOCAL_DEPS = true;
|
||||
CPM_LOCAL_PACKAGES_ONLY = true;
|
||||
CPM_SOURCE_CACHE = "./build";
|
||||
CPM_USE_LOCAL_PACKAGES = true;
|
||||
CPM_DOWNLOAD_ALL = false;
|
||||
|
||||
meshoptimizer = fetchFromGitHub {
|
||||
owner = "zeux";
|
||||
repo = "meshoptimizer";
|
||||
rev = "c21d3be6ddf627f8ca852ba4b6db9903b0557858";
|
||||
sha256 = "sha256-QCxpM2g8WtYSZHkBzLTJNQ/oHb5j/n9rjaVmZJcCZIA=";
|
||||
};
|
||||
basis_universal = fetchFromGitHub {
|
||||
owner = "BinomialLLC";
|
||||
repo = "basis_universal";
|
||||
rev = "900e40fb5d2502927360fe2f31762bdbb624455f";
|
||||
sha256 = "sha256-zBRAXgG5Fi6+5uPQCI/RCGatY6O4ELuYBoKrPNn4K+8=";
|
||||
};
|
||||
|
||||
DEP_MESHOPTIMIZER_SOURCE = "${meshoptimizer}";
|
||||
DEP_BASIS_UNIVERSAL_SOURCE = "${basis_universal}";
|
||||
DEP_SK_GPU_SOURCE = "${sk_gpu}";
|
||||
|
||||
postPatch = let libPath = lib.makeLibraryPath [ stdenv.cc.cc.lib ];
|
||||
in ''
|
||||
sk=$(echo $cargoDepsCopy/stereokit-rust-*/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.38.7.cmake
|
||||
mkdir -p $sk/sk_gpu
|
||||
cp -R ${sk_gpu}/* $sk/sk_gpu
|
||||
chmod -R 755 $sk/sk_gpu/tools/linux_x64/*
|
||||
export DEP_SK_GPU_SOURCE=$sk/sk_gpu
|
||||
export LD_LIBRARY_PATH="${stdenv.cc.cc.lib}/lib";
|
||||
patchelf --set-interpreter "$(cat $NIX_CC/nix-support/dynamic-linker)" \
|
||||
--set-rpath "${libPath}" \
|
||||
$sk/sk_gpu/tools/linux_x64/skshaderc
|
||||
'';
|
||||
nativeBuildInputs = [ cmake pkg-config llvmPackages.libcxxClang ];
|
||||
buildInputs = [
|
||||
libGL
|
||||
mesa
|
||||
xorg.libX11.dev
|
||||
xorg.libXft
|
||||
xorg.libXfixes
|
||||
fontconfig
|
||||
libxkbcommon
|
||||
libXau
|
||||
libXdmcp
|
||||
openxr-loader
|
||||
];
|
||||
LIBCLANG_PATH = "${libclang.lib}/lib";
|
||||
}
|
||||
@@ -1,136 +1,245 @@
|
||||
use super::{eventloop::EventLoop, scenegraph::Scenegraph};
|
||||
use crate::{
|
||||
core::registry::Registry,
|
||||
nodes::{data, drawable, fields, hmd, input, items, root::Root, spatial, startup, Node},
|
||||
use super::{
|
||||
client_state::{ClientStateParsed, CLIENT_STATES},
|
||||
destroy_queue,
|
||||
scenegraph::Scenegraph,
|
||||
};
|
||||
use anyhow::{anyhow, Result};
|
||||
use crate::{
|
||||
core::{registry::OwnedRegistry, task},
|
||||
nodes::{
|
||||
audio, data, drawable, fields, input, items,
|
||||
root::{ClientState, Root},
|
||||
spatial, Node,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use global_counter::primitive::exact::CounterU32;
|
||||
use lazy_static::lazy_static;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use stardust_xr::messenger::Messenger;
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::{Arc, Weak},
|
||||
};
|
||||
use tokio::{net::UnixStream, sync::Notify, task::JoinHandle};
|
||||
use rustc_hash::FxHashMap;
|
||||
use stardust_xr::messenger::{self, MessageSenderHandle};
|
||||
use std::{fmt::Debug, fs, iter::FromIterator, path::PathBuf, sync::Arc};
|
||||
use tokio::{net::UnixStream, task::JoinHandle};
|
||||
use tracing::info;
|
||||
|
||||
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 {
|
||||
event_loop: Weak::new(),
|
||||
index: 0,
|
||||
pid: None,
|
||||
// env: None,
|
||||
exe: None,
|
||||
|
||||
stop_notifier: Default::default(),
|
||||
join_handle: OnceCell::new(),
|
||||
dispatch_join_handle: OnceCell::new(),
|
||||
flush_join_handle: OnceCell::new(),
|
||||
disconnect_status: OnceCell::new(),
|
||||
|
||||
messenger: None,
|
||||
message_sender_handle: None,
|
||||
id_counter: CounterU32::new(0),
|
||||
scenegraph: Default::default(),
|
||||
root: OnceCell::new(),
|
||||
base_resource_prefixes: Default::default(),
|
||||
state: OnceCell::default(),
|
||||
});
|
||||
}
|
||||
|
||||
pub struct Client {
|
||||
event_loop: Weak<EventLoop>,
|
||||
index: usize,
|
||||
stop_notifier: Arc<Notify>,
|
||||
join_handle: OnceCell<JoinHandle<Result<()>>>,
|
||||
pub fn get_env(pid: i32) -> Result<FxHashMap<String, String>, std::io::Error> {
|
||||
let env = fs::read_to_string(format!("/proc/{pid}/environ"))?;
|
||||
Ok(FxHashMap::from_iter(
|
||||
env.split('\0')
|
||||
.filter_map(|var| var.split_once('='))
|
||||
.map(|(k, v)| (k.to_string(), v.to_string())),
|
||||
))
|
||||
}
|
||||
pub fn state(env: &FxHashMap<String, String>) -> Option<Arc<ClientStateParsed>> {
|
||||
let token = env.get("STARDUST_STARTUP_TOKEN")?;
|
||||
CLIENT_STATES.lock().get(token).cloned()
|
||||
}
|
||||
|
||||
pub messenger: Option<Messenger>,
|
||||
pub scenegraph: Scenegraph,
|
||||
pub struct Client {
|
||||
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<()>>,
|
||||
|
||||
id_counter: CounterU32,
|
||||
pub message_sender_handle: Option<MessageSenderHandle>,
|
||||
pub scenegraph: Arc<Scenegraph>,
|
||||
pub root: OnceCell<Arc<Root>>,
|
||||
pub base_resource_prefixes: Mutex<Vec<PathBuf>>,
|
||||
pub state: OnceCell<ClientState>,
|
||||
}
|
||||
impl Client {
|
||||
pub fn from_connection(
|
||||
index: usize,
|
||||
event_loop: &Arc<EventLoop>,
|
||||
connection: UnixStream,
|
||||
) -> Arc<Self> {
|
||||
println!("New client connected");
|
||||
let client = CLIENTS.add(Client {
|
||||
event_loop: Arc::downgrade(event_loop),
|
||||
index,
|
||||
stop_notifier: Default::default(),
|
||||
join_handle: OnceCell::new(),
|
||||
pub fn from_connection(connection: UnixStream) -> Result<Arc<Self>> {
|
||||
let pid = connection.peer_cred().ok().and_then(|c| c.pid());
|
||||
let env = pid.and_then(|pid| get_env(pid).ok());
|
||||
let exe = pid.and_then(|pid| fs::read_link(format!("/proc/{}/exe", pid)).ok());
|
||||
info!(
|
||||
pid,
|
||||
exe = exe
|
||||
.as_ref()
|
||||
.and_then(|exe| exe.to_str().map(|s| s.to_string())),
|
||||
"New client connected"
|
||||
);
|
||||
|
||||
messenger: Some(Messenger::new(
|
||||
tokio::runtime::Handle::current(),
|
||||
connection,
|
||||
)),
|
||||
scenegraph: Default::default(),
|
||||
let (mut messenger_tx, mut messenger_rx) = messenger::create(connection);
|
||||
let scenegraph = Arc::new(Scenegraph::default());
|
||||
let state = env
|
||||
.as_ref()
|
||||
.and_then(state)
|
||||
.unwrap_or_else(|| Arc::new(ClientStateParsed::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(),
|
||||
|
||||
id_counter: CounterU32::new(256),
|
||||
message_sender_handle: Some(messenger_tx.handle()),
|
||||
scenegraph: scenegraph.clone(),
|
||||
root: OnceCell::new(),
|
||||
base_resource_prefixes: Default::default(),
|
||||
state: OnceCell::default(),
|
||||
});
|
||||
let _ = client.scenegraph.client.set(Arc::downgrade(&client));
|
||||
let _ = client.root.set(Root::create(&client));
|
||||
hmd::make_alias(&client);
|
||||
spatial::create_interface(&client);
|
||||
fields::create_interface(&client);
|
||||
drawable::create_interface(&client);
|
||||
data::create_interface(&client);
|
||||
items::create_interface(&client);
|
||||
input::create_interface(&client);
|
||||
startup::create_interface(&client);
|
||||
let _ = client.root.set(Root::create(&client, state.root)?);
|
||||
spatial::create_interface(&client)?;
|
||||
fields::create_interface(&client)?;
|
||||
drawable::create_interface(&client)?;
|
||||
audio::create_interface(&client)?;
|
||||
data::create_interface(&client)?;
|
||||
input::create_interface(&client)?;
|
||||
items::camera::create_interface(&client)?;
|
||||
items::panel::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 _ = client.state.set(state.apply_to(&client));
|
||||
|
||||
let result = tokio::select! {
|
||||
_ = client.stop_notifier.notified() => Ok(()),
|
||||
e = dispatch_loop => e,
|
||||
e = flush_loop => e,
|
||||
};
|
||||
client.disconnect().await;
|
||||
result
|
||||
}
|
||||
}));
|
||||
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 {
|
||||
if let Err(e) = messenger_rx.dispatch(&*scenegraph).await {
|
||||
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 {
|
||||
if let Err(e) = messenger_tx.flush().await {
|
||||
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<ClientStateParsed> {
|
||||
let internal = self.root.get()?.save_state().await.ok()?;
|
||||
Some(ClientStateParsed::from_deserialized(self, internal))
|
||||
}
|
||||
|
||||
pub fn generate_id(&self) -> u64 {
|
||||
self.id_counter.inc() as u64
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_node(&self, name: &'static str, path: &str) -> Result<Arc<Node>> {
|
||||
pub fn get_node(&self, name: &'static str, id: u64) -> Result<Arc<Node>> {
|
||||
self.scenegraph
|
||||
.get_node(path)
|
||||
.ok_or_else(|| anyhow!("{} not found", name))
|
||||
.get_node(id)
|
||||
.ok_or_else(|| eyre!("{} not found", name))
|
||||
}
|
||||
|
||||
pub async fn dispatch(&self) -> Result<(), std::io::Error> {
|
||||
match &self.messenger {
|
||||
Some(messenger) => messenger.dispatch(&self.scenegraph).await,
|
||||
None => Err(std::io::Error::from(std::io::ErrorKind::Unsupported)),
|
||||
pub fn disconnect(&self, reason: Result<()>) {
|
||||
let _ = self.disconnect_status.set(reason);
|
||||
if let Some(dispatch_join_handle) = self.dispatch_join_handle.get() {
|
||||
dispatch_join_handle.abort();
|
||||
}
|
||||
if let Some(flush_join_handle) = self.flush_join_handle.get() {
|
||||
flush_join_handle.abort();
|
||||
}
|
||||
if let Some(client) = CLIENTS.remove(self) {
|
||||
destroy_queue::add(client);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
impl Debug for Client {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Client")
|
||||
.field("pid", &self.pid)
|
||||
.field("exe", &self.exe)
|
||||
.field("dispatch_join_handle", &self.dispatch_join_handle)
|
||||
.field("flush_join_handle", &self.flush_join_handle)
|
||||
.field("disconnect_status", &self.disconnect_status)
|
||||
.field("base_resource_prefixes", &self.base_resource_prefixes)
|
||||
.field("state", &self.state)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
impl Drop for Client {
|
||||
fn drop(&mut self) {
|
||||
self.stop_notifier.notify_one();
|
||||
CLIENTS.remove(self);
|
||||
println!("Client disconnected");
|
||||
info!(
|
||||
pid = self.pid,
|
||||
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"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
119
src/core/client_state.rs
Normal file
119
src/core/client_state.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
use super::client::{get_env, Client};
|
||||
use crate::nodes::{root::ClientState, spatial::Spatial, Node};
|
||||
use glam::Mat4;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
pub static ref CLIENT_STATES: Mutex<FxHashMap<String, Arc<ClientStateParsed>>> = 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 ClientStateParsed {
|
||||
pub launch_info: Option<LaunchInfo>,
|
||||
pub data: Vec<u8>,
|
||||
pub root: Mat4,
|
||||
pub spatial_anchors: FxHashMap<String, Mat4>,
|
||||
}
|
||||
impl ClientStateParsed {
|
||||
pub fn from_deserialized(client: &Client, state: ClientState) -> Self {
|
||||
ClientStateParsed {
|
||||
launch_info: LaunchInfo::from_client(client),
|
||||
data: state.data.unwrap_or_default(),
|
||||
root: Self::spatial_transform(client, state.root).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, id: u64) -> Option<Mat4> {
|
||||
let node = client.scenegraph.get_node(id)?;
|
||||
let spatial = node.get_aspect::<Spatial>().ok()?;
|
||||
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 from_file(file: &Path) -> Option<Self> {
|
||||
let file_string = std::fs::read_to_string(file).ok()?;
|
||||
toml::from_str(&file_string).ok()
|
||||
}
|
||||
pub fn to_file(&self, directory: &Path) {
|
||||
let app_name = self
|
||||
.launch_info
|
||||
.as_ref()
|
||||
.map(|l| l.cmdline.first().unwrap().split('/').last().unwrap())
|
||||
.unwrap_or("unknown");
|
||||
let state_file_path = directory
|
||||
.join(format!("{app_name}-{}", nanoid::nanoid!()))
|
||||
.with_extension("toml");
|
||||
|
||||
std::fs::write(state_file_path, toml::to_string(&self).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
pub fn apply_to(&self, client: &Arc<Client>) -> ClientState {
|
||||
if let Some(root) = client.root.get() {
|
||||
root.set_transform(self.root)
|
||||
}
|
||||
ClientState {
|
||||
data: Some(self.data.clone()),
|
||||
root: 0,
|
||||
spatial_anchors: self
|
||||
.spatial_anchors
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
let node = Node::generate(client, true).add_to_scenegraph().unwrap();
|
||||
Spatial::add_to(&node, None, *v, false);
|
||||
(k.clone(), node.get_id())
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
pub fn launch_command(self) -> Option<Command> {
|
||||
let launch_info = self.launch_info.as_ref()?;
|
||||
let mut cmdline = launch_info.cmdline.iter();
|
||||
let mut command = Command::new(cmdline.next()?);
|
||||
command.args(cmdline);
|
||||
command.current_dir(&launch_info.cwd);
|
||||
command.envs(launch_info.env.iter());
|
||||
command.env("STARDUST_STARTUP_TOKEN", self.token());
|
||||
Some(command)
|
||||
}
|
||||
}
|
||||
impl Default for ClientStateParsed {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
launch_info: None,
|
||||
data: Default::default(),
|
||||
root: Mat4::IDENTITY,
|
||||
spatial_anchors: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
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,12 +1,24 @@
|
||||
use once_cell::sync::Lazy;
|
||||
use parking_lot::Mutex;
|
||||
use std::any::Any;
|
||||
use tokio::sync::mpsc::{self, unbounded_channel};
|
||||
|
||||
static MAIN_DESTROY_QUEUE: Mutex<Vec<Box<dyn Any + Send + Sync>>> = Mutex::new(Vec::new());
|
||||
type Anything = Box<dyn Any + Send + Sync>;
|
||||
|
||||
static MAIN_DESTROY_QUEUE: Lazy<(
|
||||
mpsc::UnboundedSender<Anything>,
|
||||
Mutex<mpsc::UnboundedReceiver<Anything>>,
|
||||
)> = Lazy::new(|| {
|
||||
let (tx, rx) = unbounded_channel();
|
||||
(tx, Mutex::new(rx))
|
||||
});
|
||||
|
||||
pub fn add<T: Any + Sync + Send>(thing: T) {
|
||||
MAIN_DESTROY_QUEUE.lock().push(Box::new(thing));
|
||||
MAIN_DESTROY_QUEUE.0.send(Box::new(thing)).unwrap();
|
||||
}
|
||||
|
||||
pub fn clear() {
|
||||
MAIN_DESTROY_QUEUE.lock().clear();
|
||||
while let Ok(thing) = MAIN_DESTROY_QUEUE.1.lock().try_recv() {
|
||||
drop(thing)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
use super::client::Client;
|
||||
use anyhow::Result;
|
||||
use slab::Slab;
|
||||
use stardust_xr::server;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::Arc;
|
||||
use tokio::net::UnixListener;
|
||||
use tokio::sync::{Mutex, Notify};
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
pub static FRAME: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
pub struct EventLoop {
|
||||
pub socket_path: String,
|
||||
stop_notifier: Arc<Notify>,
|
||||
pub clients: Mutex<Slab<Arc<Client>>>,
|
||||
}
|
||||
|
||||
impl EventLoop {
|
||||
pub fn new() -> Result<(Arc<Self>, JoinHandle<Result<()>>)> {
|
||||
let socket_path = server::get_free_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 {
|
||||
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 {
|
||||
let (socket, _) = socket.accept().await?;
|
||||
let mut clients = event_loop.clients.lock().await;
|
||||
let vacant_client = clients.vacant_entry();
|
||||
let idx = vacant_client.key();
|
||||
vacant_client.insert(Client::from_connection(idx, &event_loop, socket));
|
||||
}
|
||||
};
|
||||
|
||||
tokio::select! {
|
||||
_ = event_loop.stop_notifier.notified() => Ok(()),
|
||||
e = event_loop_async => e,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for EventLoop {
|
||||
fn drop(&mut self) {
|
||||
self.stop_notifier.notify_one();
|
||||
}
|
||||
}
|
||||
11
src/core/idl_utils.rs
Normal file
11
src/core/idl_utils.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
#[macro_export]
|
||||
macro_rules! create_interface {
|
||||
($iface:ident) => {
|
||||
pub fn create_interface(client: &Arc<Client>) -> Result<()> {
|
||||
let node = Node::from_id(client, INTERFACE_NODE_ID, false);
|
||||
<$iface as self::InterfaceAspect>::add_node_members(&node);
|
||||
node.add_to_scenegraph()?;
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
pub mod client;
|
||||
pub mod client_state;
|
||||
pub mod delta;
|
||||
pub mod destroy_queue;
|
||||
pub mod eventloop;
|
||||
pub mod nodelist;
|
||||
pub mod idl_utils;
|
||||
pub mod registry;
|
||||
pub mod resource;
|
||||
pub mod scenegraph;
|
||||
pub mod task;
|
||||
|
||||
@@ -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,19 @@
|
||||
#![allow(dead_code)]
|
||||
|
||||
use parking_lot::{const_mutex, MappedMutexGuard, Mutex, MutexGuard};
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::ptr;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
|
||||
pub struct Registry<T: Send + Sync + ?Sized>(Lazy<Mutex<FxHashMap<usize, Weak<T>>>>);
|
||||
#[derive(Debug)]
|
||||
pub struct Registry<T: Send + Sync + ?Sized>(Mutex<Option<FxHashMap<usize, Weak<T>>>>);
|
||||
|
||||
impl<T: Send + Sync + ?Sized> Registry<T> {
|
||||
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>
|
||||
where
|
||||
@@ -22,23 +24,131 @@ impl<T: Send + Sync + ?Sized> Registry<T> {
|
||||
t_arc
|
||||
}
|
||||
pub fn add_raw(&self, t: &Arc<T>) {
|
||||
self.0
|
||||
.lock()
|
||||
self.lock()
|
||||
.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_changes(old: &Registry<T>, new: &Registry<T>) -> (Vec<Arc<T>>, Vec<Arc<T>>) {
|
||||
let old = old.lock();
|
||||
let new = new.lock();
|
||||
|
||||
let mut added = Vec::new();
|
||||
let mut removed = Vec::new();
|
||||
|
||||
for (id, entry) in new.iter() {
|
||||
if let Some(entry) = entry.upgrade() {
|
||||
if !old.contains_key(id) {
|
||||
added.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (id, entry) in old.iter() {
|
||||
if let Some(entry) = entry.upgrade() {
|
||||
if !new.contains_key(id) {
|
||||
removed.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
(added, removed)
|
||||
}
|
||||
pub fn get_valid_contents(&self) -> Vec<Arc<T>> {
|
||||
self.0
|
||||
.lock()
|
||||
self.lock()
|
||||
.iter()
|
||||
.filter_map(|pair| pair.1.upgrade())
|
||||
.collect()
|
||||
}
|
||||
pub fn remove(&self, t: &T) {
|
||||
pub fn set(&self, other: &Registry<T>) {
|
||||
self.lock().clone_from(&other.lock());
|
||||
}
|
||||
pub fn take_valid_contents(&self) -> Vec<Arc<T>> {
|
||||
self.0
|
||||
.lock()
|
||||
.take()
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|pair| pair.1.upgrade())
|
||||
.collect()
|
||||
}
|
||||
pub fn retain<F: Fn(&Arc<T>) -> bool>(&self, f: F) {
|
||||
self.lock().retain(|_, v| {
|
||||
let Some(v) = v.upgrade() else {
|
||||
return true;
|
||||
};
|
||||
(f)(&v)
|
||||
})
|
||||
}
|
||||
pub fn remove(&self, t: &T) {
|
||||
self.lock()
|
||||
.remove(&(ptr::addr_of!(*t) as *const () as usize));
|
||||
}
|
||||
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()))
|
||||
}
|
||||
}
|
||||
impl<T: Send + Sync + ?Sized> Default for Registry<T> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
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) -> Option<Arc<T>>
|
||||
where
|
||||
T: Sized,
|
||||
{
|
||||
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,71 +1,49 @@
|
||||
use anyhow::anyhow;
|
||||
use serde::{de::Visitor, Deserialize};
|
||||
use std::path::PathBuf;
|
||||
use stardust_xr::values::ResourceID;
|
||||
use std::{
|
||||
ffi::OsStr,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
pub enum ResourceID {
|
||||
File(PathBuf),
|
||||
Namespaced { namespace: String, path: PathBuf },
|
||||
use super::client::Client;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref THEMES: Vec<PathBuf> = std::env::var("STARDUST_THEMES").map(|s| s.split(':').map(PathBuf::from).collect()).unwrap_or_default();
|
||||
}
|
||||
impl ResourceID {
|
||||
pub fn get_file(&self, prefixes: &[PathBuf]) -> Option<PathBuf> {
|
||||
match self {
|
||||
ResourceID::File(file) => (file.is_absolute() && file.exists()).then_some(file.clone()),
|
||||
ResourceID::Namespaced { namespace, path } => {
|
||||
for prefix in prefixes {
|
||||
let mut test_path = prefix.clone();
|
||||
test_path.push(namespace.clone());
|
||||
test_path.push(path.clone());
|
||||
|
||||
if test_path.as_path().exists() {
|
||||
return Some(test_path);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
fn has_extension(path: &Path, extensions: &[&OsStr]) -> bool {
|
||||
if let Some(path_extension) = path.extension() {
|
||||
extensions.contains(&path_extension)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_resource_file(
|
||||
resource: &ResourceID,
|
||||
client: &Client,
|
||||
extensions: &[&OsStr],
|
||||
) -> Option<PathBuf> {
|
||||
match resource {
|
||||
ResourceID::Direct(file) => {
|
||||
(file.is_absolute() && file.exists() && has_extension(file, extensions))
|
||||
.then_some(file.clone())
|
||||
}
|
||||
ResourceID::Namespaced { namespace, path } => {
|
||||
let file_name = path.file_name()?;
|
||||
let base_prefixes = client.base_resource_prefixes.lock().clone();
|
||||
THEMES
|
||||
.iter()
|
||||
.chain(base_prefixes.iter())
|
||||
.filter_map(|prefix| {
|
||||
let prefixed_path = prefix.clone().join(namespace).join(path);
|
||||
let parent = prefixed_path.parent()?;
|
||||
std::fs::read_dir(parent).ok()
|
||||
})
|
||||
.flatten()
|
||||
.filter_map(|item| item.ok())
|
||||
.map(|dir_entry| dir_entry.path())
|
||||
.filter(|path| path.file_stem() == Some(file_name))
|
||||
.find(|path| has_extension(path, extensions))
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<'de> Deserialize<'de> for ResourceID {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
deserializer.deserialize_any(ResourceVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
struct ResourceVisitor;
|
||||
impl<'de> Visitor<'de> for ResourceVisitor {
|
||||
type Value = ResourceID;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
formatter.write_str("A string containing an absolute path to file or \"[namespace]:[path]\" for a namespaced resource")
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
|
||||
where
|
||||
E: serde::de::Error,
|
||||
{
|
||||
Ok(if v.starts_with('/') {
|
||||
let path = PathBuf::from(v);
|
||||
path.metadata().map_err(serde::de::Error::custom)?;
|
||||
ResourceID::File(path)
|
||||
} else if let Some((namespace, path)) = v.split_once(':') {
|
||||
ResourceID::Namespaced {
|
||||
namespace: namespace.to_string(),
|
||||
path: PathBuf::from(path),
|
||||
}
|
||||
} else {
|
||||
return Err(serde::de::Error::custom(anyhow!(
|
||||
"Invalid format for string"
|
||||
)));
|
||||
})
|
||||
}
|
||||
|
||||
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
|
||||
where
|
||||
E: serde::de::Error,
|
||||
{
|
||||
self.visit_str(&v)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,29 @@
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::alias::get_original;
|
||||
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 parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
use serde::Serialize;
|
||||
use stardust_xr::scenegraph;
|
||||
use stardust_xr::scenegraph::ScenegraphError;
|
||||
use stardust_xr::schemas::flex::serialize;
|
||||
use std::future::Future;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use core::hash::BuildHasherDefault;
|
||||
use dashmap::DashMap;
|
||||
use rustc_hash::FxHasher;
|
||||
use tokio::sync::oneshot;
|
||||
use tracing::{debug, debug_span};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Scenegraph {
|
||||
pub(super) client: OnceCell<Weak<Client>>,
|
||||
nodes: DashMap<String, Arc<Node>, BuildHasherDefault<FxHasher>>,
|
||||
nodes: Mutex<FxHashMap<u64, Arc<Node>>>,
|
||||
}
|
||||
|
||||
impl Scenegraph {
|
||||
pub fn get_client(&self) -> Arc<Client> {
|
||||
self.client.get().unwrap().upgrade().unwrap()
|
||||
pub fn get_client(&self) -> Option<Arc<Client>> {
|
||||
self.client.get()?.upgrade()
|
||||
}
|
||||
|
||||
pub fn add_node(&self, node: Node) -> Arc<Node> {
|
||||
@@ -27,38 +32,106 @@ impl Scenegraph {
|
||||
node_arc
|
||||
}
|
||||
pub fn add_node_raw(&self, node: Arc<Node>) {
|
||||
let path = node.get_path().to_string();
|
||||
self.nodes.insert(path, node);
|
||||
debug!(node = ?&*node, "Add node");
|
||||
self.nodes.lock().insert(node.get_id(), node);
|
||||
}
|
||||
|
||||
pub fn get_node(&self, path: &str) -> Option<Arc<Node>> {
|
||||
let mut node = self.nodes.get(path)?.clone();
|
||||
if let Some(alias) = node.alias.get() {
|
||||
node = alias.original.upgrade()?;
|
||||
}
|
||||
Some(node)
|
||||
pub fn get_node(&self, node: u64) -> Option<Arc<Node>> {
|
||||
let node = self.nodes.lock().get(&node)?.clone();
|
||||
get_original(node, true)
|
||||
}
|
||||
|
||||
pub fn remove_node(&self, path: &str) -> Option<Arc<Node>> {
|
||||
let (_, node) = self.nodes.remove(path)?;
|
||||
Some(node)
|
||||
pub fn remove_node(&self, node: u64) -> Option<Arc<Node>> {
|
||||
debug!(node, "Remove node");
|
||||
self.nodes.lock().remove(&node)
|
||||
}
|
||||
}
|
||||
|
||||
pub type MethodResponse = Result<(Vec<u8>, Vec<OwnedFd>), ScenegraphError>;
|
||||
pub struct MethodResponseSender(oneshot::Sender<MethodResponse>);
|
||||
impl MethodResponseSender {
|
||||
pub fn send(self, t: Result<Message, ScenegraphError>) {
|
||||
let _ = self.0.send(t.map(|m| (m.data, m.fds)));
|
||||
}
|
||||
// pub fn send_method_return<T: Serialize>(
|
||||
// self,
|
||||
// result: color_eyre::eyre::Result<(T, Vec<OwnedFd>)>,
|
||||
// ) {
|
||||
// let _ = self.0.send(map_method_return(result));
|
||||
// }
|
||||
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(),
|
||||
}))
|
||||
}
|
||||
pub fn wrap_async<T: Serialize>(
|
||||
self,
|
||||
f: impl Future<Output = color_eyre::eyre::Result<(T, Vec<OwnedFd>)>> + Send + 'static,
|
||||
) {
|
||||
tokio::task::spawn(async move { self.0.send(map_method_return(f.await)) });
|
||||
}
|
||||
}
|
||||
fn map_method_return<T: Serialize>(
|
||||
result: color_eyre::eyre::Result<(T, Vec<OwnedFd>)>,
|
||||
) -> Result<(Vec<u8>, Vec<OwnedFd>), ScenegraphError> {
|
||||
let (value, fds) = result.map_err(|e| ScenegraphError::MethodError {
|
||||
error: e.to_string(),
|
||||
})?;
|
||||
|
||||
let serialized_value = serialize(value).map_err(|e| ScenegraphError::MethodError {
|
||||
error: format!("Internal: Serialization failed: {e}"),
|
||||
})?;
|
||||
Ok((serialized_value, fds))
|
||||
}
|
||||
impl scenegraph::Scenegraph for Scenegraph {
|
||||
fn send_signal(&self, path: &str, method: &str, data: &[u8]) -> Result<(), ScenegraphError> {
|
||||
self.get_node(path)
|
||||
.ok_or(ScenegraphError::NodeNotFound)?
|
||||
.send_local_signal(self.get_client(), method, data)
|
||||
fn send_signal(
|
||||
&self,
|
||||
node: u64,
|
||||
method: u64,
|
||||
data: &[u8],
|
||||
fds: Vec<OwnedFd>,
|
||||
) -> Result<(), ScenegraphError> {
|
||||
let Some(client) = self.get_client() else {
|
||||
return Err(ScenegraphError::SignalNotFound);
|
||||
};
|
||||
debug_span!("Handle signal", node, method).in_scope(|| {
|
||||
self.get_node(node)
|
||||
.ok_or(ScenegraphError::NodeNotFound)?
|
||||
.send_local_signal(
|
||||
client,
|
||||
method,
|
||||
Message {
|
||||
data: data.to_vec(),
|
||||
fds,
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
fn execute_method(
|
||||
&self,
|
||||
path: &str,
|
||||
method: &str,
|
||||
node: u64,
|
||||
method: u64,
|
||||
data: &[u8],
|
||||
) -> Result<Vec<u8>, ScenegraphError> {
|
||||
self.get_node(path)
|
||||
.ok_or(ScenegraphError::NodeNotFound)?
|
||||
.execute_local_method(self.get_client(), method, data)
|
||||
fds: Vec<OwnedFd>,
|
||||
response: oneshot::Sender<Result<(Vec<u8>, Vec<OwnedFd>), ScenegraphError>>,
|
||||
) {
|
||||
let Some(client) = self.get_client() else {
|
||||
let _ = response.send(Err(ScenegraphError::MethodNotFound));
|
||||
return;
|
||||
};
|
||||
debug!(node, method, "Handle method");
|
||||
let Some(node) = self.get_node(node) 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
|
||||
}
|
||||
397
src/main.rs
397
src/main.rs
@@ -1,172 +1,289 @@
|
||||
#![allow(clippy::empty_docs)]
|
||||
mod core;
|
||||
mod nodes;
|
||||
mod objects;
|
||||
mod session;
|
||||
#[cfg(feature = "wayland")]
|
||||
mod wayland;
|
||||
|
||||
use crate::core::destroy_queue;
|
||||
use crate::nodes::{drawable, hmd, input};
|
||||
use crate::objects::input::mouse_pointer::MousePointer;
|
||||
use crate::objects::input::sk_controller::SkController;
|
||||
use crate::objects::input::sk_hand::SkHand;
|
||||
use crate::wayland::Wayland;
|
||||
use crate::nodes::items::camera;
|
||||
use crate::nodes::{audio, drawable, input};
|
||||
|
||||
use self::core::eventloop::EventLoop;
|
||||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use core::client::Client;
|
||||
use core::task;
|
||||
use directories::ProjectDirs;
|
||||
use slog::Drain;
|
||||
use objects::ServerObjects;
|
||||
use once_cell::sync::OnceCell;
|
||||
use session::{launch_start, save_session};
|
||||
use stardust_xr::server;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use stereokit::input::Handed;
|
||||
use stereokit::lifecycle::DepthMode;
|
||||
use stereokit::render::SphericalHarmonics;
|
||||
use stereokit::texture::Texture;
|
||||
use stereokit::{lifecycle::DisplayMode, Settings};
|
||||
use tokio::{runtime::Handle, sync::oneshot};
|
||||
use std::time::Duration;
|
||||
use stereokit_rust::material::Material;
|
||||
use stereokit_rust::shader::Shader;
|
||||
use stereokit_rust::sk::{sk_quit, AppMode, DepthMode, OriginMode, QuitReason, SkSettings};
|
||||
use stereokit_rust::system::{LogLevel, Renderer};
|
||||
use stereokit_rust::tex::{SHCubemap, Tex, TexFormat, TexType};
|
||||
use stereokit_rust::ui::Ui;
|
||||
use stereokit_rust::util::{Color128, Time};
|
||||
use tokio::net::UnixListener;
|
||||
use tokio::sync::Notify;
|
||||
use tracing::metadata::LevelFilter;
|
||||
use tracing::{debug_span, error, info};
|
||||
use tracing_subscriber::{fmt, prelude::*, EnvFilter};
|
||||
use zbus::fdo::ObjectManager;
|
||||
use zbus::Connection;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[clap(author, version, about, long_about = None)]
|
||||
struct CliArgs {
|
||||
/// Force flatscreen mode and use the mouse pointer as a 3D pointer
|
||||
#[clap(short, long, action)]
|
||||
flatscreen: bool,
|
||||
|
||||
/// If monado insists on emulating them, set this flag...we want the raw input
|
||||
#[clap(long)]
|
||||
disable_controllers: bool,
|
||||
/// If monado insists on emulating , set this flag...we want the raw input
|
||||
#[clap(long)]
|
||||
disable_hands: bool,
|
||||
|
||||
/// Run Stardust XR as an overlay with given priority
|
||||
#[clap(id = "PRIORITY", short = 'o', long = "overlay", action)]
|
||||
overlay_priority: Option<u32>,
|
||||
|
||||
/// Debug the clients started by the server
|
||||
#[clap(short = 'd', long = "debug", action)]
|
||||
debug_launched_clients: 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>,
|
||||
|
||||
/// Restore the session with the given ID (or `latest`), ignoring the startup script. Sessions are stored in directories at `~/.local/state/stardust/`.
|
||||
#[clap(id = "SESSION_ID", long = "restore", action)]
|
||||
restore: Option<String>,
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let project_dirs = ProjectDirs::from("", "", "stardust").unwrap();
|
||||
let cli_args = Arc::new(CliArgs::parse());
|
||||
let log = ::slog::Logger::root(::slog_stdlog::StdLog.fuse(), slog::o!());
|
||||
slog_stdlog::init()?;
|
||||
|
||||
let mut stereokit = Settings::default()
|
||||
.app_name("Stardust XR")
|
||||
.overlay_app(cli_args.overlay_priority.is_some())
|
||||
.overlay_priority(cli_args.overlay_priority.unwrap_or(u32::MAX))
|
||||
.disable_desktop_input_window(true)
|
||||
.display_preference(if cli_args.flatscreen {
|
||||
DisplayMode::Flatscreen
|
||||
} else {
|
||||
DisplayMode::MixedReality
|
||||
})
|
||||
.depth_mode(DepthMode::D32)
|
||||
.init()
|
||||
.expect("StereoKit failed to initialize");
|
||||
println!("Init StereoKit");
|
||||
|
||||
// Skytex/light stuff
|
||||
{
|
||||
let skytex_path = project_dirs.config_dir().join("skytex.hdr");
|
||||
if let Some((tex, light)) = skytex_path
|
||||
.exists()
|
||||
.then(|| Texture::from_cubemap_equirectangular(&stereokit, &skytex_path, true, 100))
|
||||
.flatten()
|
||||
{
|
||||
stereokit.set_skytex(&tex);
|
||||
stereokit.set_skylight(&light);
|
||||
} else if let Some(tex) = Texture::cubemap_from_spherical_harmonics(
|
||||
&stereokit,
|
||||
&SphericalHarmonics::default(),
|
||||
16,
|
||||
0.0,
|
||||
0.0,
|
||||
) {
|
||||
stereokit.set_skytex(&tex);
|
||||
}
|
||||
}
|
||||
|
||||
let mouse_pointer = cli_args.flatscreen.then(MousePointer::new);
|
||||
let mut hands =
|
||||
(!cli_args.flatscreen).then(|| [SkHand::new(Handed::Left), SkHand::new(Handed::Right)]);
|
||||
let mut controllers = (!cli_args.flatscreen).then(|| {
|
||||
[
|
||||
SkController::new(Handed::Left),
|
||||
SkController::new(Handed::Right),
|
||||
]
|
||||
});
|
||||
|
||||
if hands.is_none() {
|
||||
unsafe {
|
||||
stereokit::sys::input_hand_visible(stereokit::sys::handed__handed_left, false as i32);
|
||||
stereokit::sys::input_hand_visible(stereokit::sys::handed__handed_right, false as i32);
|
||||
}
|
||||
}
|
||||
|
||||
let (event_stop_tx, event_stop_rx) = oneshot::channel::<()>();
|
||||
let (handle_sender, handle_receiver) = oneshot::channel::<Handle>();
|
||||
let event_thread = std::thread::Builder::new()
|
||||
.name("event_loop".to_owned())
|
||||
.spawn(move || event_loop(handle_sender, event_stop_rx))?;
|
||||
let _tokio_handle = handle_receiver.blocking_recv()?.enter();
|
||||
|
||||
let mut wayland = Wayland::new(log)?;
|
||||
println!("Stardust ready!");
|
||||
stereokit.run(
|
||||
|sk, draw_ctx| {
|
||||
hmd::frame(sk);
|
||||
wayland.frame(sk);
|
||||
destroy_queue::clear();
|
||||
|
||||
if let Some(mouse_pointer) = &mouse_pointer {
|
||||
mouse_pointer.update(sk);
|
||||
}
|
||||
if let Some(hands) = &mut hands {
|
||||
hands[0].update(sk);
|
||||
hands[1].update(sk);
|
||||
}
|
||||
if let Some(controllers) = &mut controllers {
|
||||
controllers[0].update(sk);
|
||||
controllers[1].update(sk);
|
||||
}
|
||||
input::process_input();
|
||||
nodes::root::Root::logic_step(sk.time_elapsed());
|
||||
drawable::draw(sk, draw_ctx);
|
||||
|
||||
wayland.make_context_current();
|
||||
},
|
||||
|_| {
|
||||
println!("Cleanly shut down StereoKit");
|
||||
},
|
||||
);
|
||||
|
||||
drop(wayland);
|
||||
|
||||
let _ = event_stop_tx.send(());
|
||||
event_thread
|
||||
.join()
|
||||
.expect("Failed to cleanly shut down event loop")?;
|
||||
println!("Cleanly shut down Stardust");
|
||||
Ok(())
|
||||
}
|
||||
static STARDUST_INSTANCE: OnceCell<String> = OnceCell::new();
|
||||
|
||||
// #[tokio::main]
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn event_loop(
|
||||
handle_sender: oneshot::Sender<Handle>,
|
||||
stop_rx: oneshot::Receiver<()>,
|
||||
) -> anyhow::Result<()> {
|
||||
let _ = handle_sender.send(Handle::current());
|
||||
// console_subscriber::init();
|
||||
async fn main() {
|
||||
color_eyre::install().unwrap();
|
||||
|
||||
let (event_loop, event_loop_join_handle) =
|
||||
EventLoop::new().expect("Couldn't create server socket");
|
||||
println!("Init event loop");
|
||||
println!("Stardust socket created at {}", event_loop.socket_path);
|
||||
let registry = tracing_subscriber::registry();
|
||||
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = tokio::signal::ctrl_c() => Ok(()),
|
||||
_ = stop_rx => Ok(()),
|
||||
e = event_loop_join_handle => e?,
|
||||
};
|
||||
#[cfg(feature = "profile_app")]
|
||||
let registry = registry.with(
|
||||
tracing_tracy::TracyLayer::new(tracing_tracy::DefaultConfig::default())
|
||||
.with_filter(LevelFilter::DEBUG),
|
||||
);
|
||||
|
||||
println!("Cleanly shut down event loop");
|
||||
#[cfg(feature = "profile_tokio")]
|
||||
let (console_layer, _) = console_subscriber::ConsoleLayer::builder().build();
|
||||
#[cfg(feature = "profile_tokio")]
|
||||
let registry = registry.with(console_layer);
|
||||
|
||||
unsafe {
|
||||
stereokit::sys::sk_quit();
|
||||
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 cli_args = CliArgs::parse();
|
||||
|
||||
let socket_path =
|
||||
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");
|
||||
info!(
|
||||
socket_path = ?socket_path.display(),
|
||||
"Stardust socket created"
|
||||
);
|
||||
let socket =
|
||||
UnixListener::bind(socket_path).expect("Couldn't spawn stardust server at {socket_path}");
|
||||
task::new(|| "client join loop", async move {
|
||||
loop {
|
||||
let Ok((stream, _)) = socket.accept().await else {
|
||||
continue;
|
||||
};
|
||||
if let Err(e) = Client::from_connection(stream) {
|
||||
error!(?e, "Unable to create client from connection");
|
||||
}
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
info!("Init client join loop");
|
||||
|
||||
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.");
|
||||
}
|
||||
|
||||
result
|
||||
let dbus_connection = Connection::session()
|
||||
.await
|
||||
.expect("Could not open dbus session");
|
||||
dbus_connection
|
||||
.request_name("org.stardustxr.HMD")
|
||||
.await
|
||||
.expect("Another instance of the server is running. This is not supported currently (but is planned).");
|
||||
|
||||
dbus_connection
|
||||
.object_server()
|
||||
.at("/", ObjectManager)
|
||||
.await
|
||||
.expect("Couldn't add the object manager");
|
||||
|
||||
let sk_ready_notifier = Arc::new(Notify::new());
|
||||
let stereokit_loop = tokio::task::spawn_blocking({
|
||||
let sk_ready_notifier = sk_ready_notifier.clone();
|
||||
let project_dirs = project_dirs.clone();
|
||||
let cli_args = cli_args.clone();
|
||||
let dbus_connection = dbus_connection.clone();
|
||||
move || stereokit_loop(sk_ready_notifier, project_dirs, cli_args, dbus_connection)
|
||||
});
|
||||
sk_ready_notifier.notified().await;
|
||||
let mut startup_children = project_dirs
|
||||
.as_ref()
|
||||
.map(|project_dirs| launch_start(&cli_args, project_dirs))
|
||||
.unwrap_or_default();
|
||||
|
||||
tokio::select! {
|
||||
_ = stereokit_loop => (),
|
||||
_ = tokio::signal::ctrl_c() => unsafe {sk_quit(QuitReason::SystemClose)},
|
||||
}
|
||||
info!("Stopping...");
|
||||
if let Some(project_dirs) = project_dirs {
|
||||
save_session(&project_dirs).await;
|
||||
}
|
||||
for mut startup_child in startup_children.drain(..) {
|
||||
let _ = startup_child.kill();
|
||||
}
|
||||
|
||||
info!("Cleanly shut down Stardust");
|
||||
}
|
||||
|
||||
fn stereokit_loop(
|
||||
sk_ready_notifier: Arc<Notify>,
|
||||
project_dirs: Option<ProjectDirs>,
|
||||
args: CliArgs,
|
||||
dbus_connection: Connection,
|
||||
) {
|
||||
let sk = SkSettings::default()
|
||||
.app_name("Stardust XR")
|
||||
.mode(if args.flatscreen {
|
||||
AppMode::Simulator
|
||||
} else {
|
||||
AppMode::XR
|
||||
})
|
||||
.depth_mode(DepthMode::D32)
|
||||
.log_filter(match EnvFilter::from_default_env().max_level_hint() {
|
||||
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(args.overlay_priority.is_some())
|
||||
.overlay_priority(args.overlay_priority.unwrap_or(u32::MAX))
|
||||
.disable_desktop_input_window(true)
|
||||
.origin(OriginMode::Local)
|
||||
.init()
|
||||
.expect("StereoKit failed to initialize");
|
||||
info!("Init StereoKit");
|
||||
|
||||
Renderer::multisample(0);
|
||||
Material::default().shader(Shader::pbr_clip());
|
||||
Ui::enable_far_interact(false);
|
||||
|
||||
// Skytex/light stuff
|
||||
{
|
||||
if let Some(sky) = project_dirs
|
||||
.as_ref()
|
||||
.map(|dirs| dirs.config_dir().join("skytex.hdr"))
|
||||
.filter(|f| f.exists())
|
||||
.and_then(|p| SHCubemap::from_cubemap_equirectangular(p, true, 100).ok())
|
||||
{
|
||||
sky.render_as_sky();
|
||||
} else {
|
||||
Renderer::skytex(Tex::gen_color(
|
||||
Color128::BLACK,
|
||||
1,
|
||||
1,
|
||||
TexType::Cubemap,
|
||||
TexFormat::RGBA32,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "wayland")]
|
||||
let mut wayland = wayland::Wayland::new().expect("Could not initialize wayland");
|
||||
#[cfg(feature = "wayland")]
|
||||
wayland.make_context_current();
|
||||
sk_ready_notifier.notify_waiters();
|
||||
info!("Stardust ready!");
|
||||
|
||||
let mut objects = ServerObjects::new(
|
||||
dbus_connection.clone(),
|
||||
&sk,
|
||||
args.disable_controllers,
|
||||
args.disable_hands,
|
||||
);
|
||||
|
||||
let mut last_frame_delta = Duration::ZERO;
|
||||
let mut sleep_duration = Duration::ZERO;
|
||||
while let Some(token) = sk.step() {
|
||||
let _span = debug_span!("StereoKit step");
|
||||
let _span = _span.enter();
|
||||
|
||||
camera::update(token);
|
||||
#[cfg(feature = "wayland")]
|
||||
wayland.frame_event();
|
||||
destroy_queue::clear();
|
||||
|
||||
objects.update(&sk, token);
|
||||
input::process_input();
|
||||
nodes::root::Root::send_frame_events(Time::get_step_unscaled());
|
||||
adaptive_sleep(
|
||||
&mut last_frame_delta,
|
||||
&mut sleep_duration,
|
||||
Duration::from_micros(250),
|
||||
);
|
||||
|
||||
#[cfg(feature = "wayland")]
|
||||
wayland.update();
|
||||
drawable::draw(token);
|
||||
audio::update();
|
||||
}
|
||||
|
||||
info!("Cleanly shut down StereoKit");
|
||||
#[cfg(feature = "wayland")]
|
||||
drop(wayland);
|
||||
}
|
||||
|
||||
fn adaptive_sleep(
|
||||
last_frame_delta: &mut Duration,
|
||||
sleep_duration: &mut Duration,
|
||||
sleep_duration_increase: Duration,
|
||||
) {
|
||||
let frame_delta = Duration::from_secs_f64(Time::get_step_unscaled());
|
||||
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;
|
||||
}
|
||||
|
||||
debug_span!("Sleep", ?sleep_duration, ?frame_delta, ?last_frame_delta).in_scope(|| {
|
||||
*last_frame_delta = frame_delta;
|
||||
std::thread::sleep(*sleep_duration); // to give clients a chance to even update anything before drawing
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,38 +1,141 @@
|
||||
use crate::core::client::Client;
|
||||
|
||||
use super::Node;
|
||||
use std::sync::{Arc, Weak};
|
||||
use super::{Aspect, Node};
|
||||
use crate::core::{client::Client, registry::Registry};
|
||||
use color_eyre::eyre::Result;
|
||||
use std::{
|
||||
ops::Add,
|
||||
sync::{Arc, Weak},
|
||||
};
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct AliasInfo {
|
||||
pub(super) local_signals: Vec<&'static str>,
|
||||
pub(super) local_methods: Vec<&'static str>,
|
||||
pub(super) remote_signals: Vec<&'static str>,
|
||||
pub(super) server_signals: Vec<u64>,
|
||||
pub(super) server_methods: Vec<u64>,
|
||||
pub(super) client_signals: Vec<u64>,
|
||||
}
|
||||
impl Add for AliasInfo {
|
||||
type Output = AliasInfo;
|
||||
fn add(mut self, mut rhs: Self) -> Self::Output {
|
||||
self.server_signals.append(&mut rhs.server_signals);
|
||||
self.server_methods.append(&mut rhs.server_methods);
|
||||
self.client_signals.append(&mut rhs.client_signals);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub struct Alias {
|
||||
pub(super) node: Weak<Node>,
|
||||
pub original: Weak<Node>,
|
||||
|
||||
pub info: AliasInfo,
|
||||
pub(super) original: Weak<Node>,
|
||||
pub(super) info: AliasInfo,
|
||||
}
|
||||
impl Alias {
|
||||
pub fn new(
|
||||
client: &Arc<Client>,
|
||||
parent: &str,
|
||||
name: &str,
|
||||
pub fn create(
|
||||
original: &Arc<Node>,
|
||||
client: &Arc<Client>,
|
||||
info: AliasInfo,
|
||||
) -> Arc<Node> {
|
||||
let node = Node::create(client, parent, name, true).add_to_scenegraph();
|
||||
list: Option<&AliasList>,
|
||||
) -> Result<Arc<Node>> {
|
||||
let node = Node::generate(client, true).add_to_scenegraph()?;
|
||||
Self::add_to(&node, original, info)?;
|
||||
if let Some(list) = list {
|
||||
list.add(&node);
|
||||
}
|
||||
Ok(node)
|
||||
}
|
||||
pub fn create_with_id(
|
||||
original: &Arc<Node>,
|
||||
client: &Arc<Client>,
|
||||
new_id: u64,
|
||||
info: AliasInfo,
|
||||
list: Option<&AliasList>,
|
||||
) -> Result<Arc<Node>> {
|
||||
let node = Node::from_id(client, new_id, true).add_to_scenegraph()?;
|
||||
Self::add_to(&node, original, info)?;
|
||||
if let Some(list) = list {
|
||||
list.add(&node);
|
||||
}
|
||||
Ok(node)
|
||||
}
|
||||
|
||||
fn add_to(new_node: &Arc<Node>, original: &Arc<Node>, info: AliasInfo) -> Result<()> {
|
||||
let alias = Alias {
|
||||
node: Arc::downgrade(&node),
|
||||
node: Arc::downgrade(new_node),
|
||||
original: Arc::downgrade(original),
|
||||
info,
|
||||
};
|
||||
let alias = original.aliases.add(alias);
|
||||
let _ = node.alias.set(alias);
|
||||
node
|
||||
new_node.add_aspect_raw(alias);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Aspect for Alias {
|
||||
const NAME: &'static str = "Alias";
|
||||
}
|
||||
|
||||
pub fn get_original(node: Arc<Node>, stop_on_disabled: bool) -> Option<Arc<Node>> {
|
||||
let Ok(alias) = node.get_aspect::<Alias>() else {
|
||||
return Some(node);
|
||||
};
|
||||
if stop_on_disabled && !node.enabled() {
|
||||
return None;
|
||||
}
|
||||
get_original(alias.original.upgrade()?, stop_on_disabled)
|
||||
}
|
||||
pub fn links_to(alias: Arc<Node>, original: Weak<Node>) -> bool {
|
||||
let Ok(alias) = alias.get_aspect::<Alias>() else {
|
||||
return false;
|
||||
};
|
||||
if alias.original.ptr_eq(&original) {
|
||||
return true;
|
||||
}
|
||||
let Some(original_strong) = alias.original.upgrade() else {
|
||||
return false;
|
||||
};
|
||||
links_to(original_strong, original)
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct AliasList(Registry<Node>);
|
||||
impl AliasList {
|
||||
fn add(&self, node: &Arc<Node>) {
|
||||
self.0.add_raw(node);
|
||||
}
|
||||
pub fn get_from_original_node(&self, original: Weak<Node>) -> Option<Arc<Node>> {
|
||||
self.0
|
||||
.get_valid_contents()
|
||||
.into_iter()
|
||||
.find(move |node| links_to(node.clone(), original.clone()))
|
||||
}
|
||||
pub fn get_from_aspect<A: Aspect>(&self, aspect: &A) -> Option<Arc<Node>> {
|
||||
self.0.get_valid_contents().into_iter().find(|node| {
|
||||
let Some(node) = get_original(node.clone(), false) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(aspect2) = node.get_aspect::<A>() else {
|
||||
return false;
|
||||
};
|
||||
Arc::as_ptr(&aspect2) == (aspect as *const A)
|
||||
})
|
||||
}
|
||||
pub fn get_aliases(&self) -> Vec<Arc<Node>> {
|
||||
self.0.get_valid_contents()
|
||||
}
|
||||
pub fn remove_aspect<A: Aspect>(&self, aspect: &A) {
|
||||
self.0.retain(|node| {
|
||||
let Some(original) = get_original(node.clone(), false) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(aspect2) = original.get_aspect::<A>() else {
|
||||
return false;
|
||||
};
|
||||
Arc::as_ptr(&aspect2) != (aspect as *const A)
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Drop for AliasList {
|
||||
fn drop(&mut self) {
|
||||
for node in self.0.take_valid_contents() {
|
||||
node.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
124
src/nodes/audio.rs
Normal file
124
src/nodes/audio.rs
Normal file
@@ -0,0 +1,124 @@
|
||||
use super::{Aspect, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::core::destroy_queue;
|
||||
use crate::core::registry::Registry;
|
||||
use crate::core::resource::get_resource_file;
|
||||
use crate::create_interface;
|
||||
use crate::nodes::spatial::SPATIAL_ASPECT_ALIAS_INFO;
|
||||
use crate::nodes::spatial::{Spatial, Transform};
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use glam::{vec3, Vec4Swizzles};
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use stardust_xr::values::ResourceID;
|
||||
|
||||
use std::ops::DerefMut;
|
||||
use std::sync::Arc;
|
||||
use std::{ffi::OsStr, path::PathBuf};
|
||||
use stereokit_rust::sound::{Sound as SkSound, SoundInst};
|
||||
|
||||
static SOUND_REGISTRY: Registry<Sound> = Registry::new();
|
||||
|
||||
stardust_xr_server_codegen::codegen_audio_protocol!();
|
||||
pub struct Sound {
|
||||
space: Arc<Spatial>,
|
||||
|
||||
volume: f32,
|
||||
pending_audio_path: PathBuf,
|
||||
sk_sound: OnceCell<SkSound>,
|
||||
instance: Mutex<Option<SoundInst>>,
|
||||
stop: Mutex<Option<()>>,
|
||||
play: Mutex<Option<()>>,
|
||||
}
|
||||
impl Sound {
|
||||
pub fn add_to(node: &Arc<Node>, resource_id: ResourceID) -> Result<Arc<Sound>> {
|
||||
let pending_audio_path = get_resource_file(
|
||||
&resource_id,
|
||||
&*node.get_client().ok_or_else(|| eyre!("Client not found"))?,
|
||||
&[OsStr::new("wav"), OsStr::new("mp3")],
|
||||
)
|
||||
.ok_or_else(|| eyre!("Resource not found"))?;
|
||||
let sound = Sound {
|
||||
space: node.get_aspect::<Spatial>().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_aspect_raw(sound_arc.clone());
|
||||
<Sound as SoundAspect>::add_node_members(node);
|
||||
Ok(sound_arc)
|
||||
}
|
||||
|
||||
fn update(&self) {
|
||||
let sound = self
|
||||
.sk_sound
|
||||
.get_or_init(|| SkSound::from_file(self.pending_audio_path.clone()).unwrap());
|
||||
if self.stop.lock().take().is_some() {
|
||||
if let Some(instance) = self.instance.lock().take() {
|
||||
instance.stop();
|
||||
}
|
||||
}
|
||||
if self.instance.lock().is_none() && self.play.lock().take().is_some() {
|
||||
let instance = sound.play(vec3(0.0, 0.0, 0.0), Some(self.volume));
|
||||
self.instance.lock().replace(instance);
|
||||
}
|
||||
if let Some(instance) = self.instance.lock().deref_mut() {
|
||||
instance.position(self.space.global_transform().w_axis.xyz());
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Aspect for Sound {
|
||||
const NAME: &'static str = "Sound";
|
||||
}
|
||||
impl SoundAspect for Sound {
|
||||
fn play(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<()> {
|
||||
let sound = node.get_aspect::<Sound>().unwrap();
|
||||
sound.play.lock().replace(());
|
||||
Ok(())
|
||||
}
|
||||
fn stop(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<()> {
|
||||
let sound = node.get_aspect::<Sound>().unwrap();
|
||||
sound.stop.lock().replace(());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for Sound {
|
||||
fn drop(&mut self) {
|
||||
if let Some(sk_sound) = self.sk_sound.take() {
|
||||
destroy_queue::add(sk_sound);
|
||||
}
|
||||
SOUND_REGISTRY.remove(self);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update() {
|
||||
for sound in SOUND_REGISTRY.get_valid_contents() {
|
||||
sound.update()
|
||||
}
|
||||
}
|
||||
|
||||
create_interface!(AudioInterface);
|
||||
struct AudioInterface;
|
||||
impl InterfaceAspect for AudioInterface {
|
||||
#[doc = "Create a sound node. WAV and MP3 are supported."]
|
||||
fn create_sound(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
resource: ResourceID,
|
||||
) -> Result<()> {
|
||||
let node = Node::from_id(&calling_client, id, true);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = transform.to_mat4(true, true, true);
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
Sound::add_to(&node, resource)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,51 @@
|
||||
use super::alias::AliasInfo;
|
||||
use super::alias::AliasList;
|
||||
use super::fields::Field;
|
||||
use super::spatial::{parse_transform, Spatial};
|
||||
use super::{Alias, Node};
|
||||
use super::{Alias, Aspect, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::core::nodelist::LifeLinkedNodeList;
|
||||
use crate::core::registry::Registry;
|
||||
use crate::nodes::fields::find_field;
|
||||
use crate::nodes::spatial::find_spatial_parent;
|
||||
use anyhow::{anyhow, ensure, Result};
|
||||
use glam::vec3a;
|
||||
use crate::create_interface;
|
||||
use crate::nodes::fields::FIELD_ALIAS_INFO;
|
||||
use crate::nodes::spatial::Transform;
|
||||
use crate::nodes::spatial::SPATIAL_ASPECT_ALIAS_INFO;
|
||||
use color_eyre::eyre::{bail, ensure, eyre, Result};
|
||||
use lazy_static::lazy_static;
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
use stardust_xr::values::Transform;
|
||||
use slotmap::{DefaultKey, Key, KeyData, SlotMap};
|
||||
use stardust_xr::schemas::flex::flexbuffers;
|
||||
use stardust_xr::values::Datamap;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
static PULSE_SENDER_REGISTRY: Registry<PulseSender> = Registry::new();
|
||||
static PULSE_RECEIVER_REGISTRY: Registry<PulseReceiver> = Registry::new();
|
||||
lazy_static! {
|
||||
pub static ref KEYMAPS: Mutex<SlotMap<DefaultKey, String>> = Mutex::new(SlotMap::default());
|
||||
}
|
||||
|
||||
fn mask_matches(mask_map_lesser: &Mask, mask_map_greater: &Mask) -> bool {
|
||||
// TODO: probably just use d-bus for this stuff (custom protocol for exporting spatials as refs) because the mask stuff is just too confusing
|
||||
|
||||
static PULSE_SENDER_REGISTRY: Registry<PulseSender> = Registry::new();
|
||||
pub static PULSE_RECEIVER_REGISTRY: Registry<PulseReceiver> = Registry::new();
|
||||
|
||||
pub fn get_mask(datamap: &Datamap) -> Result<flexbuffers::MapReader<&[u8]>> {
|
||||
flexbuffers::Reader::get_root(datamap.raw().as_slice())
|
||||
.map_err(|_| eyre!("Mask is not a valid flexbuffer"))?
|
||||
.get_map()
|
||||
.map_err(|_| eyre!("Mask is not a valid map"))
|
||||
}
|
||||
pub fn mask_matches(mask_map_lesser: &Datamap, mask_map_greater: &Datamap) -> bool {
|
||||
(|| -> Result<_> {
|
||||
for key in mask_map_lesser.get_mask()?.iter_keys() {
|
||||
let lesser_key_type = mask_map_lesser.get_mask()?.index(key)?.flexbuffer_type();
|
||||
let greater_key_type = mask_map_greater.get_mask()?.index(key)?.flexbuffer_type();
|
||||
if lesser_key_type != greater_key_type {
|
||||
for key in get_mask(mask_map_lesser)?.iter_keys() {
|
||||
let lesser_key = get_mask(mask_map_lesser)?.index(key)?;
|
||||
let greater_key = get_mask(mask_map_greater)?.index(key)?;
|
||||
// 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().is_empty()
|
||||
&& 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());
|
||||
}
|
||||
}
|
||||
@@ -32,122 +54,89 @@ fn mask_matches(mask_map_lesser: &Mask, mask_map_greater: &Mask) -> bool {
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
type MaskMapGetFn = fn(&[u8]) -> Result<flexbuffers::MapReader<&[u8]>>;
|
||||
pub struct Mask {
|
||||
binary: Vec<u8>,
|
||||
get_fn: MaskMapGetFn,
|
||||
}
|
||||
impl Mask {
|
||||
pub fn get_mask(&self) -> Result<flexbuffers::MapReader<&[u8]>> {
|
||||
(self.get_fn)(self.binary.as_slice())
|
||||
}
|
||||
pub fn set_mask(&mut self, binary: Vec<u8>, get_fn: MaskMapGetFn) {
|
||||
self.binary = binary;
|
||||
self.get_fn = get_fn;
|
||||
}
|
||||
}
|
||||
impl Default for Mask {
|
||||
fn default() -> Self {
|
||||
Mask {
|
||||
binary: Default::default(),
|
||||
get_fn: mask_get_err,
|
||||
}
|
||||
}
|
||||
}
|
||||
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"))
|
||||
}
|
||||
stardust_xr_server_codegen::codegen_data_protocol!();
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct PulseSender {
|
||||
mask: Mutex<Mask>,
|
||||
aliases: LifeLinkedNodeList,
|
||||
node: Weak<Node>,
|
||||
pub mask: Datamap,
|
||||
aliases: AliasList,
|
||||
field_aliases: AliasList,
|
||||
}
|
||||
impl PulseSender {
|
||||
pub fn add_to(node: &Arc<Node>) -> Result<()> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
pub fn add_to(node: &Arc<Node>, mask: Datamap) -> Result<Arc<PulseSender>> {
|
||||
let sender = PulseSender {
|
||||
node: Arc::downgrade(node),
|
||||
mask,
|
||||
aliases: AliasList::default(),
|
||||
field_aliases: AliasList::default(),
|
||||
};
|
||||
|
||||
let sender = Default::default();
|
||||
// <PulseSender as PulseSenderAspect>::add_node_members(node);
|
||||
let sender = PULSE_SENDER_REGISTRY.add(sender);
|
||||
let _ = node.pulse_sender.set(sender);
|
||||
node.add_local_signal("setMask", PulseSender::set_mask_flex);
|
||||
node.add_local_method("getReceivers", PulseSender::get_receivers_flex);
|
||||
Ok(())
|
||||
node.add_aspect_raw(sender.clone());
|
||||
for receiver in PULSE_RECEIVER_REGISTRY.get_valid_contents() {
|
||||
sender.handle_new_receiver(&receiver);
|
||||
}
|
||||
Ok(sender.clone())
|
||||
}
|
||||
pub fn set_mask_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
ensure!(
|
||||
node.pulse_sender.get().is_some(),
|
||||
"Internal: Node does not have a pulse sender aspect"
|
||||
);
|
||||
node.pulse_sender
|
||||
.get()
|
||||
.unwrap()
|
||||
.mask
|
||||
.lock()
|
||||
.set_mask(data.to_vec(), mask_get_map_at_root);
|
||||
Ok(())
|
||||
fn handle_new_receiver(&self, receiver: &PulseReceiver) {
|
||||
if !mask_matches(&self.mask, &receiver.mask) {
|
||||
return;
|
||||
}
|
||||
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 Ok(rx_alias) = Alias::create(
|
||||
&rx_node,
|
||||
&tx_client,
|
||||
PULSE_RECEIVER_ASPECT_ALIAS_INFO.clone(),
|
||||
Some(&self.aliases),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Receiver's field
|
||||
let Ok(rx_field_alias) = Alias::create(
|
||||
&rx_node
|
||||
.get_aspect::<PulseReceiver>()
|
||||
.unwrap()
|
||||
.field
|
||||
.spatial
|
||||
.node()
|
||||
.unwrap(),
|
||||
&tx_client,
|
||||
FIELD_ALIAS_INFO.clone(),
|
||||
Some(&self.aliases),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let _ = pulse_sender_client::new_receiver(&tx_node, &rx_alias, &rx_field_alias);
|
||||
}
|
||||
fn get_receivers_flex(
|
||||
node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
_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));
|
||||
|
||||
receiver.uid.clone()
|
||||
})
|
||||
.collect();
|
||||
|
||||
serialize(uids).map_err(|e| e.into())
|
||||
fn handle_drop_receiver(&self, receiver: &PulseReceiver) {
|
||||
let Some(node) = receiver.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
self.aliases.remove_aspect(receiver);
|
||||
self.field_aliases.remove_aspect(receiver.field.as_ref());
|
||||
let Some(tx_node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = pulse_sender_client::drop_receiver(&tx_node, node.get_id());
|
||||
}
|
||||
}
|
||||
impl Aspect for PulseSender {
|
||||
const NAME: &'static str = "PulseSender";
|
||||
}
|
||||
impl PulseSenderAspect for PulseSender {}
|
||||
impl Drop for PulseSender {
|
||||
fn drop(&mut self) {
|
||||
PULSE_SENDER_REGISTRY.remove(self);
|
||||
@@ -155,139 +144,133 @@ impl Drop for PulseSender {
|
||||
}
|
||||
|
||||
pub struct PulseReceiver {
|
||||
uid: String,
|
||||
node: Weak<Node>,
|
||||
pub mask: Mutex<Mask>,
|
||||
field: Weak<Field>,
|
||||
pub node: Weak<Node>,
|
||||
pub field: Arc<Field>,
|
||||
pub mask: Datamap,
|
||||
}
|
||||
impl PulseReceiver {
|
||||
pub fn add_to(node: &Arc<Node>, field: Arc<Field>) -> Result<()> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
|
||||
pub fn add_to(
|
||||
node: &Arc<Node>,
|
||||
field: Arc<Field>,
|
||||
mask: Datamap,
|
||||
) -> Result<Arc<PulseReceiver>> {
|
||||
let receiver = PulseReceiver {
|
||||
uid: node.uid.clone(),
|
||||
node: Arc::downgrade(node),
|
||||
field: Arc::downgrade(&field),
|
||||
mask: Default::default(),
|
||||
field,
|
||||
mask,
|
||||
};
|
||||
let receiver = PULSE_RECEIVER_REGISTRY.add(receiver);
|
||||
let _ = node.pulse_receiver.set(receiver);
|
||||
node.add_local_signal("setMask", PulseReceiver::set_mask_flex);
|
||||
node.add_local_signal("sendData", PulseReceiver::send_data_flex);
|
||||
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"
|
||||
));
|
||||
|
||||
<PulseReceiver as PulseReceiverAspect>::add_node_members(node);
|
||||
node.add_aspect_raw(receiver.clone());
|
||||
for sender in PULSE_SENDER_REGISTRY.get_valid_contents() {
|
||||
sender.handle_new_receiver(&receiver);
|
||||
}
|
||||
drop(receiver_mask);
|
||||
node.send_remote_signal("pulse", data)?;
|
||||
Ok(())
|
||||
Ok(receiver)
|
||||
}
|
||||
fn set_mask_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
}
|
||||
impl Aspect for PulseReceiver {
|
||||
const NAME: &'static str = "PulseReceiver";
|
||||
}
|
||||
impl PulseReceiverAspect for PulseReceiver {
|
||||
fn send_data(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
sender: Arc<Node>,
|
||||
data: Datamap,
|
||||
) -> Result<()> {
|
||||
let this_receiver = node.get_aspect::<PulseReceiver>().unwrap();
|
||||
|
||||
ensure!(
|
||||
node.pulse_receiver.get().is_some(),
|
||||
"Internal: Node does not have a pulse receiver aspect"
|
||||
mask_matches(&this_receiver.mask, &data),
|
||||
"Message ({data:?}) does not contain the same keys as the receiver's mask ({:?})",
|
||||
this_receiver.mask
|
||||
);
|
||||
node.pulse_receiver
|
||||
.get()
|
||||
.unwrap()
|
||||
.mask
|
||||
.lock()
|
||||
.set_mask(data.to_vec(), mask_get_map_at_root);
|
||||
pulse_receiver_client::data(&node, &sender, &data)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PulseReceiver {
|
||||
fn drop(&mut 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>) {
|
||||
let node = Node::create(client, "", "data", false);
|
||||
node.add_local_signal("createPulseSender", create_pulse_sender_flex);
|
||||
node.add_local_signal("createPulseReceiver", create_pulse_receiver_flex);
|
||||
node.add_to_scenegraph();
|
||||
}
|
||||
|
||||
// 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(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreatePulseSenderInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
create_interface!(DataInterface);
|
||||
struct DataInterface;
|
||||
impl InterfaceAspect for DataInterface {
|
||||
fn create_pulse_sender(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
}
|
||||
let info: CreatePulseSenderInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/data/sender", 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)?;
|
||||
PulseSender::add_to(&node)?;
|
||||
Ok(())
|
||||
}
|
||||
mask: Datamap,
|
||||
) -> Result<()> {
|
||||
get_mask(&mask)?;
|
||||
let node = Node::from_id(&calling_client, id, true);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = transform.to_mat4(true, true, false);
|
||||
|
||||
// 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(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreatePulseReceiverInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
PulseSender::add_to(&node, mask)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_pulse_receiver(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
field_path: &'a str,
|
||||
}
|
||||
let info: CreatePulseReceiverInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/data/sender", info.name, true);
|
||||
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)?;
|
||||
field: Arc<Node>,
|
||||
mask: Datamap,
|
||||
) -> Result<()> {
|
||||
get_mask(&mask)?;
|
||||
let node = Node::from_id(&calling_client, id, true);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = parse_transform(transform, true, true, false);
|
||||
let field = field.get_aspect::<Field>()?;
|
||||
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
PulseReceiver::add_to(&node, field)?;
|
||||
Ok(())
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
PulseReceiver::add_to(&node, field, mask)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn register_keymap(
|
||||
_node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
keymap: String,
|
||||
) -> Result<u64> {
|
||||
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(found_keymap_id.data().as_ffi());
|
||||
}
|
||||
|
||||
let key = keymaps.insert(keymap);
|
||||
Ok(key.data().as_ffi())
|
||||
}
|
||||
|
||||
async fn get_keymap(
|
||||
_node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
keymap_id: u64,
|
||||
) -> Result<String> {
|
||||
let keymaps = KEYMAPS.lock();
|
||||
let Some(keymap) = keymaps.get(KeyData::from_ffi(keymap_id).into()) else {
|
||||
bail!("Could not find keymap. Try registering it")
|
||||
};
|
||||
|
||||
Ok(keymap.clone())
|
||||
}
|
||||
}
|
||||
|
||||
BIN
src/nodes/drawable/assets/shaders/shader_unlit_gamma.hlsl.sks
Normal file
BIN
src/nodes/drawable/assets/shaders/shader_unlit_gamma.hlsl.sks
Normal file
Binary file not shown.
BIN
src/nodes/drawable/assets/shaders/shader_unlit_simula.hlsl.sks
Normal file
BIN
src/nodes/drawable/assets/shaders/shader_unlit_simula.hlsl.sks
Normal file
Binary file not shown.
110
src/nodes/drawable/lines.rs
Normal file
110
src/nodes/drawable/lines.rs
Normal file
@@ -0,0 +1,110 @@
|
||||
use super::{Line, LinesAspect};
|
||||
use crate::{
|
||||
core::{client::Client, registry::Registry},
|
||||
nodes::{spatial::Spatial, Aspect, Node},
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::Vec3;
|
||||
use parking_lot::Mutex;
|
||||
use prisma::Lerp;
|
||||
use std::{collections::VecDeque, sync::Arc};
|
||||
use stereokit_rust::{
|
||||
maths::Bounds, sk::MainThreadToken, system::LinePoint as SkLinePoint, util::Color128,
|
||||
};
|
||||
|
||||
static LINES_REGISTRY: Registry<Lines> = Registry::new();
|
||||
|
||||
pub struct Lines {
|
||||
space: Arc<Spatial>,
|
||||
data: Mutex<Vec<Line>>,
|
||||
}
|
||||
impl Lines {
|
||||
pub fn add_to(node: &Arc<Node>, lines: Vec<Line>) -> Result<Arc<Lines>> {
|
||||
let _ = node
|
||||
.get_aspect::<Spatial>()
|
||||
.unwrap()
|
||||
.bounding_box_calc
|
||||
.set(|node| {
|
||||
let mut bounds = Bounds::default();
|
||||
if let Ok(lines) = node.get_aspect::<Lines>() {
|
||||
for line in &*lines.data.lock() {
|
||||
for point in &line.points {
|
||||
bounds.grown_point(Vec3::from(point.point));
|
||||
}
|
||||
}
|
||||
}
|
||||
bounds
|
||||
});
|
||||
|
||||
let lines = LINES_REGISTRY.add(Lines {
|
||||
space: node.get_aspect::<Spatial>()?.clone(),
|
||||
data: Mutex::new(lines),
|
||||
});
|
||||
<Lines as LinesAspect>::add_node_members(node);
|
||||
node.add_aspect_raw(lines.clone());
|
||||
|
||||
Ok(lines)
|
||||
}
|
||||
|
||||
fn draw(&self, token: &MainThreadToken) {
|
||||
let transform_mat = self.space.global_transform();
|
||||
let data = self.data.lock().clone();
|
||||
for line in &data {
|
||||
let mut points: VecDeque<SkLinePoint> = line
|
||||
.points
|
||||
.iter()
|
||||
.map(|p| SkLinePoint {
|
||||
pt: transform_mat.transform_point3(Vec3::from(p.point)).into(),
|
||||
thickness: p.thickness,
|
||||
color: Color128::new(p.color.c.r, p.color.c.g, p.color.c.b, p.color.a).into(),
|
||||
})
|
||||
.collect();
|
||||
if line.cyclic && !points.is_empty() {
|
||||
let first = line.points.first().unwrap();
|
||||
let last = line.points.last().unwrap();
|
||||
|
||||
let color = Color128 {
|
||||
r: first.color.c.r.lerp(&last.color.c.r, 0.5),
|
||||
g: first.color.c.g.lerp(&last.color.c.g, 0.5),
|
||||
b: first.color.c.b.lerp(&last.color.c.b, 0.5),
|
||||
a: first.color.a.lerp(&last.color.a, 0.5),
|
||||
};
|
||||
let connect_point = SkLinePoint {
|
||||
pt: transform_mat
|
||||
.transform_point3(Vec3::from(first.point).lerp(Vec3::from(last.point), 0.5))
|
||||
.into(),
|
||||
thickness: (first.thickness + last.thickness) * 0.5,
|
||||
color: color.into(),
|
||||
};
|
||||
points.push_front(connect_point);
|
||||
points.push_back(connect_point);
|
||||
}
|
||||
stereokit_rust::system::Lines::add_list(token, points.make_contiguous());
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Aspect for Lines {
|
||||
const NAME: &'static str = "Lines";
|
||||
}
|
||||
impl LinesAspect for Lines {
|
||||
fn set_lines(node: Arc<Node>, _calling_client: Arc<Client>, lines: Vec<Line>) -> Result<()> {
|
||||
let lines_aspect = node.get_aspect::<Lines>()?;
|
||||
*lines_aspect.data.lock() = lines;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for Lines {
|
||||
fn drop(&mut self) {
|
||||
LINES_REGISTRY.remove(self);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw_all(token: &MainThreadToken) {
|
||||
for lines in LINES_REGISTRY.get_valid_contents() {
|
||||
if let Some(node) = lines.space.node() {
|
||||
if node.enabled() {
|
||||
lines.draw(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,47 +1,40 @@
|
||||
pub mod lines;
|
||||
pub mod model;
|
||||
#[cfg(feature = "wayland")]
|
||||
pub mod shader_manipulation;
|
||||
pub mod shaders;
|
||||
pub mod text;
|
||||
|
||||
use super::Node;
|
||||
use crate::core::client::Client;
|
||||
use anyhow::Result;
|
||||
use self::{lines::Lines, model::Model, text::Text};
|
||||
use super::{
|
||||
spatial::{Spatial, Transform},
|
||||
Node,
|
||||
};
|
||||
use crate::nodes::spatial::SPATIAL_ASPECT_ALIAS_INFO;
|
||||
use crate::{
|
||||
core::{client::Client, resource::get_resource_file},
|
||||
create_interface,
|
||||
};
|
||||
use color_eyre::eyre::{self, Result};
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
use stereokit::{lifecycle::DrawContext, texture::Texture, StereoKit};
|
||||
use stardust_xr::values::ResourceID;
|
||||
use std::{ffi::OsStr, path::PathBuf, sync::Arc};
|
||||
use stereokit_rust::{sk::MainThreadToken, system::Renderer, tex::SHCubemap};
|
||||
|
||||
pub fn create_interface(client: &Arc<Client>) {
|
||||
let node = Node::create(client, "", "drawable", false);
|
||||
node.add_local_signal("createModel", model::create_flex);
|
||||
node.add_local_signal("createText", text::create_flex);
|
||||
node.add_local_signal("setSkyFile", set_sky_file_flex);
|
||||
node.add_to_scenegraph();
|
||||
}
|
||||
// #[instrument(level = "debug", skip(sk))]
|
||||
pub fn draw(token: &MainThreadToken) {
|
||||
lines::draw_all(token);
|
||||
model::draw_all(token);
|
||||
text::draw_all(token);
|
||||
|
||||
pub fn draw(sk: &mut StereoKit, draw_ctx: &DrawContext) {
|
||||
model::draw_all(sk, draw_ctx);
|
||||
text::draw_all(sk, draw_ctx);
|
||||
|
||||
let new_skytex = QUEUED_SKYTEX.lock().take();
|
||||
let mut new_skylight = QUEUED_SKYLIGHT.lock().take();
|
||||
let same_file = new_skytex == new_skylight;
|
||||
|
||||
if let Some(skytex) = new_skytex {
|
||||
if let Some((skytex, skylight)) =
|
||||
Texture::from_cubemap_equirectangular(sk, &skytex, true, i32::MAX)
|
||||
{
|
||||
sk.set_skytex(&skytex);
|
||||
if same_file {
|
||||
sk.set_skylight(&skylight);
|
||||
new_skylight = None;
|
||||
}
|
||||
if let Some(skytex) = QUEUED_SKYTEX.lock().take() {
|
||||
if let Ok(skytex) = SHCubemap::from_cubemap_equirectangular(skytex, true, 100) {
|
||||
Renderer::skytex(skytex.tex);
|
||||
}
|
||||
}
|
||||
if let Some(skylight) = new_skylight {
|
||||
if let Some((_, skylight)) =
|
||||
Texture::from_cubemap_equirectangular(sk, &skylight, true, i32::MAX)
|
||||
{
|
||||
sk.set_skylight(&skylight);
|
||||
if let Some(skylight) = QUEUED_SKYLIGHT.lock().take() {
|
||||
if let Ok(skylight) = SHCubemap::from_cubemap_equirectangular(skylight, true, 100) {
|
||||
Renderer::skylight(skylight.sh);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,21 +42,80 @@ pub fn draw(sk: &mut StereoKit, draw_ctx: &DrawContext) {
|
||||
static QUEUED_SKYLIGHT: 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<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct SkyFileInfo {
|
||||
path: PathBuf,
|
||||
skytex: Option<bool>,
|
||||
skylight: Option<bool>,
|
||||
}
|
||||
let info: SkyFileInfo = deserialize(data)?;
|
||||
info.path.metadata()?;
|
||||
if info.skytex.unwrap_or_default() {
|
||||
QUEUED_SKYTEX.lock().replace(info.path.clone());
|
||||
}
|
||||
if info.skylight.unwrap_or_default() {
|
||||
QUEUED_SKYLIGHT.lock().replace(info.path);
|
||||
stardust_xr_server_codegen::codegen_drawable_protocol!();
|
||||
create_interface!(DrawableInterface);
|
||||
|
||||
pub struct DrawableInterface;
|
||||
impl InterfaceAspect for DrawableInterface {
|
||||
fn set_sky_tex(_node: Arc<Node>, calling_client: Arc<Client>, tex: ResourceID) -> Result<()> {
|
||||
let resource_path = get_resource_file(&tex, &calling_client, &[OsStr::new("hdr")])
|
||||
.ok_or(eyre::eyre!("Could not find resource"))?;
|
||||
QUEUED_SKYTEX.lock().replace(resource_path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Ok(())
|
||||
fn set_sky_light(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
light: ResourceID,
|
||||
) -> Result<()> {
|
||||
let resource_path = get_resource_file(&light, &calling_client, &[OsStr::new("hdr")])
|
||||
.ok_or(eyre::eyre!("Could not find resource"))?;
|
||||
QUEUED_SKYLIGHT.lock().replace(resource_path);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_lines(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
lines: Vec<Line>,
|
||||
) -> Result<()> {
|
||||
let node = Node::from_id(&calling_client, id, true);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = transform.to_mat4(true, true, true);
|
||||
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
Lines::add_to(&node, lines)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_model(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
model: ResourceID,
|
||||
) -> Result<()> {
|
||||
let node = Node::from_id(&calling_client, id, true);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = transform.to_mat4(true, true, true);
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
Model::add_to(&node, model)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn create_text(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
text: String,
|
||||
style: TextStyle,
|
||||
) -> Result<()> {
|
||||
let node = Node::from_id(&calling_client, id, true);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = transform.to_mat4(true, true, true);
|
||||
|
||||
let node = node.add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
Text::add_to(&node, text, style)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,184 +1,401 @@
|
||||
use super::Node;
|
||||
use super::{MaterialParameter, ModelAspect, ModelPartAspect, MODEL_PART_ASPECT_ALIAS_INFO};
|
||||
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 anyhow::{anyhow, ensure, Result};
|
||||
use once_cell::sync::OnceCell;
|
||||
use crate::core::resource::get_resource_file;
|
||||
use crate::nodes::alias::{Alias, AliasList};
|
||||
use crate::nodes::spatial::Spatial;
|
||||
use crate::nodes::{Aspect, Node};
|
||||
use color_eyre::eyre::{bail, eyre, Result};
|
||||
use glam::{Mat4, Vec2, Vec3};
|
||||
use once_cell::sync::{Lazy, OnceCell};
|
||||
use parking_lot::Mutex;
|
||||
use prisma::{Rgb, Rgba};
|
||||
use rustc_hash::FxHashMap;
|
||||
use send_wrapper::SendWrapper;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use stardust_xr::values::Transform;
|
||||
use std::fmt::Error;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use stereokit::lifecycle::DrawContext;
|
||||
use stereokit::material::Material;
|
||||
use stereokit::model::Model as SKModel;
|
||||
use stereokit::render::RenderLayer;
|
||||
use stereokit::texture::Texture;
|
||||
use stereokit::StereoKit;
|
||||
use stardust_xr::values::ResourceID;
|
||||
use std::ffi::OsStr;
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::{Arc, Weak};
|
||||
use stereokit_rust::material::Transparency;
|
||||
use stereokit_rust::maths::Bounds;
|
||||
use stereokit_rust::sk::MainThreadToken;
|
||||
use stereokit_rust::{material::Material, model::Model as SKModel, tex::Tex, util::Color128};
|
||||
|
||||
pub struct MaterialWrapper(pub Material);
|
||||
impl Hash for MaterialWrapper {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.0.get_shader().0.as_ptr().hash(state);
|
||||
for param in self.0.get_all_param_info() {
|
||||
param.to_string().hash(state)
|
||||
}
|
||||
self.0.get_chain().map(MaterialWrapper).hash(state)
|
||||
}
|
||||
}
|
||||
impl PartialEq for MaterialWrapper {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
if self.0.get_shader().0.as_ptr() != other.0.get_shader().0.as_ptr() {
|
||||
return false;
|
||||
}
|
||||
if self.0.get_all_param_info().count() != other.0.get_all_param_info().count() {
|
||||
return false;
|
||||
}
|
||||
for self_param in self.0.get_all_param_info() {
|
||||
let Some(other_param) = other
|
||||
.0
|
||||
.get_all_param_info()
|
||||
.get_data(self_param.get_name(), self_param.get_type())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if self_param.to_string() != other_param.to_string() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
self.0.get_chain().map(MaterialWrapper) == other.0.get_chain().map(MaterialWrapper)
|
||||
}
|
||||
}
|
||||
impl Eq for MaterialWrapper {}
|
||||
unsafe impl Send for MaterialWrapper {}
|
||||
unsafe impl Sync for MaterialWrapper {}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MaterialRegistry(Mutex<FxHashMap<u64, String>>);
|
||||
impl MaterialRegistry {
|
||||
fn add_or_get(&self, material: Arc<MaterialWrapper>) -> Arc<MaterialWrapper> {
|
||||
let mut lock = self.0.lock();
|
||||
let hash = {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
material.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
};
|
||||
|
||||
if let Some(id) = lock.get(&hash) {
|
||||
if let Ok(existing) = Material::find(id) {
|
||||
return Arc::new(MaterialWrapper(existing));
|
||||
}
|
||||
}
|
||||
|
||||
lock.insert(hash, material.0.get_id().to_string());
|
||||
material
|
||||
}
|
||||
}
|
||||
|
||||
static MATERIAL_REGISTRY: Lazy<MaterialRegistry> = Lazy::new(MaterialRegistry::default);
|
||||
static MODEL_REGISTRY: Registry<Model> = Registry::new();
|
||||
static HOLDOUT_MATERIAL: OnceCell<Arc<MaterialWrapper>> = OnceCell::new();
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
#[serde(untagged)]
|
||||
pub enum MaterialParameter {
|
||||
Texture(PathBuf),
|
||||
impl MaterialParameter {
|
||||
fn apply_to_material(&self, client: &Client, material: &Material, parameter_name: &str) {
|
||||
let mut params = material.get_all_param_info();
|
||||
match self {
|
||||
MaterialParameter::Bool(val) => {
|
||||
params.set_bool(parameter_name, *val);
|
||||
}
|
||||
MaterialParameter::Int(val) => {
|
||||
params.set_int(parameter_name, &[*val]);
|
||||
}
|
||||
MaterialParameter::UInt(val) => {
|
||||
params.set_uint(parameter_name, &[*val]);
|
||||
}
|
||||
MaterialParameter::Float(val) => {
|
||||
params.set_float(parameter_name, *val);
|
||||
}
|
||||
MaterialParameter::Vec2(val) => {
|
||||
params.set_vec2(parameter_name, Vec2::from(*val));
|
||||
}
|
||||
MaterialParameter::Vec3(val) => {
|
||||
params.set_vec3(parameter_name, Vec3::from(*val));
|
||||
}
|
||||
MaterialParameter::Color(val) => {
|
||||
params.set_color(
|
||||
parameter_name,
|
||||
Color128::new(val.c.r, val.c.g, val.c.b, val.a),
|
||||
);
|
||||
}
|
||||
MaterialParameter::Texture(resource) => {
|
||||
let Some(texture_path) =
|
||||
get_resource_file(resource, client, &[OsStr::new("png"), OsStr::new("jpg")])
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if let Ok(tex) = Tex::from_file(texture_path, true, None) {
|
||||
params.set_texture(parameter_name, &tex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ModelPart {
|
||||
id: i32,
|
||||
path: String,
|
||||
space: Arc<Spatial>,
|
||||
model: Weak<Model>,
|
||||
pending_material_parameters: Mutex<FxHashMap<String, MaterialParameter>>,
|
||||
pending_material_replacement: Mutex<Option<Arc<MaterialWrapper>>>,
|
||||
aliases: AliasList,
|
||||
}
|
||||
impl ModelPart {
|
||||
fn create_for_model(model: &Arc<Model>, sk_model: &SKModel) {
|
||||
HOLDOUT_MATERIAL.get_or_init(|| {
|
||||
let mut mat = Material::copy(&Material::unlit());
|
||||
mat.transparency(Transparency::None);
|
||||
mat.color_tint(Color128::BLACK_TRANSPARENT);
|
||||
Arc::new(MaterialWrapper(mat))
|
||||
});
|
||||
|
||||
let nodes = sk_model.get_nodes();
|
||||
for part in nodes.all() {
|
||||
ModelPart::create(model, &part);
|
||||
}
|
||||
}
|
||||
|
||||
fn create(model: &Arc<Model>, part: &stereokit_rust::model::ModelNode) -> Option<Arc<Self>> {
|
||||
let mut parts = model.parts.lock();
|
||||
let parent_part = part
|
||||
.get_parent()
|
||||
.and_then(|part| parts.iter().find(|p| p.id == *part.get_id()));
|
||||
|
||||
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 += part.get_name().unwrap();
|
||||
|
||||
let node = client.scenegraph.add_node(Node::generate(&client, false));
|
||||
let spatial_parent = parent_part
|
||||
.map(|n| n.space.clone())
|
||||
.unwrap_or_else(|| model.space.clone());
|
||||
|
||||
let local_transform = unsafe { part.get_local_transform().m };
|
||||
let space = Spatial::add_to(
|
||||
&node,
|
||||
Some(spatial_parent),
|
||||
Mat4::from_cols_array(&local_transform),
|
||||
false,
|
||||
);
|
||||
|
||||
let _ = space.bounding_box_calc.set(|node| {
|
||||
let Ok(model_part) = node.get_aspect::<ModelPart>() 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 model_nodes = sk_model.get_nodes();
|
||||
let Some(model_node) = model_nodes.get_index(model_part.id) else {
|
||||
return Bounds::default();
|
||||
};
|
||||
let Some(sk_mesh) = model_node.get_mesh() else {
|
||||
return Bounds::default();
|
||||
};
|
||||
sk_mesh.get_bounds()
|
||||
});
|
||||
|
||||
let model_part = Arc::new(ModelPart {
|
||||
id: *part.get_id(),
|
||||
path: part_path,
|
||||
space,
|
||||
model: Arc::downgrade(model),
|
||||
pending_material_parameters: Mutex::new(FxHashMap::default()),
|
||||
pending_material_replacement: Mutex::new(None),
|
||||
aliases: AliasList::default(),
|
||||
});
|
||||
<ModelPart as ModelPartAspect>::add_node_members(&node);
|
||||
node.add_aspect_raw(model_part.clone());
|
||||
parts.push(model_part.clone());
|
||||
Some(model_part)
|
||||
}
|
||||
|
||||
pub fn replace_material(&self, replacement: Arc<MaterialWrapper>) {
|
||||
let shared_material = MATERIAL_REGISTRY.add_or_get(replacement);
|
||||
self.pending_material_replacement
|
||||
.lock()
|
||||
.replace(shared_material);
|
||||
}
|
||||
/// only to be run on the main thread
|
||||
pub fn replace_material_now(&self, replacement: &Material) {
|
||||
let Some(model) = self.model.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(sk_model) = model.sk_model.get() else {
|
||||
return;
|
||||
};
|
||||
let nodes = sk_model.get_nodes();
|
||||
let Some(mut part) = nodes.get_index(self.id) else {
|
||||
return;
|
||||
};
|
||||
let shared_material =
|
||||
MATERIAL_REGISTRY.add_or_get(Arc::new(MaterialWrapper(replacement.copy())));
|
||||
part.material(&shared_material.0);
|
||||
}
|
||||
|
||||
fn update(&self) {
|
||||
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 nodes = sk_model.get_nodes();
|
||||
let Some(mut part) = nodes.get_index(self.id) else {
|
||||
return;
|
||||
};
|
||||
part.model_transform(Spatial::space_to_space_matrix(
|
||||
Some(&self.space),
|
||||
Some(&model.space),
|
||||
));
|
||||
|
||||
let Some(client) = node.get_client() else {
|
||||
return;
|
||||
};
|
||||
|
||||
if let Some(material_replacement) = self.pending_material_replacement.lock().take() {
|
||||
part.material(&material_replacement.0);
|
||||
}
|
||||
|
||||
'mat_params: {
|
||||
let mut material_parameters = self.pending_material_parameters.lock();
|
||||
if !material_parameters.is_empty() {
|
||||
let Some(material) = part.get_material() else {
|
||||
break 'mat_params;
|
||||
};
|
||||
let new_material = material.copy();
|
||||
for (parameter_name, parameter_value) in material_parameters.drain() {
|
||||
parameter_value.apply_to_material(&client, &new_material, ¶meter_name);
|
||||
}
|
||||
|
||||
let shared_material =
|
||||
MATERIAL_REGISTRY.add_or_get(Arc::new(MaterialWrapper(new_material)));
|
||||
part.material(&shared_material.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Aspect for ModelPart {
|
||||
const NAME: &'static str = "ModelPart";
|
||||
}
|
||||
impl ModelPartAspect for ModelPart {
|
||||
#[doc = "Set this model part's material to one that cuts a hole in the world. Often used for overlays/passthrough where you want to show the background through an object."]
|
||||
fn apply_holdout_material(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<()> {
|
||||
let model_part = node.get_aspect::<ModelPart>()?;
|
||||
model_part.replace_material(HOLDOUT_MATERIAL.get().unwrap().clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Set the material parameter with `parameter_name` to `value`"]
|
||||
fn set_material_parameter(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
parameter_name: String,
|
||||
value: MaterialParameter,
|
||||
) -> Result<()> {
|
||||
let model_part = node.get_aspect::<ModelPart>()?;
|
||||
model_part
|
||||
.pending_material_parameters
|
||||
.lock()
|
||||
.insert(parameter_name, value);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Model {
|
||||
space: Arc<Spatial>,
|
||||
resource_id: ResourceID,
|
||||
pending_model_path: OnceCell<PathBuf>,
|
||||
pending_material_parameters: Mutex<FxHashMap<(u32, String), MaterialParameter>>,
|
||||
pub pending_material_replacements: Mutex<FxHashMap<u32, Arc<SendWrapper<Material>>>>,
|
||||
sk_model: OnceCell<SendWrapper<SKModel>>,
|
||||
_resource_id: ResourceID,
|
||||
sk_model: OnceCell<SKModel>,
|
||||
parts: Mutex<Vec<Arc<ModelPart>>>,
|
||||
}
|
||||
|
||||
impl Model {
|
||||
pub fn add_to(node: &Arc<Node>, resource_id: ResourceID) -> Result<Arc<Model>> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
ensure!(
|
||||
node.model.get().is_none(),
|
||||
"Internal: Node already has a model attached!"
|
||||
);
|
||||
let model = Model {
|
||||
space: node.spatial.get().unwrap().clone(),
|
||||
resource_id,
|
||||
pending_model_path: OnceCell::new(),
|
||||
pending_material_parameters: Mutex::new(FxHashMap::default()),
|
||||
pending_material_replacements: Mutex::new(FxHashMap::default()),
|
||||
let pending_model_path = get_resource_file(
|
||||
&resource_id,
|
||||
&*node.get_client().ok_or_else(|| eyre!("Client not found"))?,
|
||||
&[OsStr::new("glb"), OsStr::new("gltf")],
|
||||
)
|
||||
.ok_or_else(|| eyre!("Resource not found"))?;
|
||||
|
||||
let model = Arc::new(Model {
|
||||
space: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
_resource_id: resource_id,
|
||||
sk_model: OnceCell::new(),
|
||||
parts: Mutex::new(Vec::default()),
|
||||
});
|
||||
<Model as ModelAspect>::add_node_members(node);
|
||||
MODEL_REGISTRY.add_raw(&model);
|
||||
|
||||
// technically doing this in anything but the main thread isn't a good idea but dangit we need those model nodes ASAP
|
||||
let sk_model = SKModel::copy(SKModel::from_file(
|
||||
pending_model_path.to_str().unwrap(),
|
||||
None,
|
||||
)?);
|
||||
ModelPart::create_for_model(&model, &sk_model);
|
||||
let _ = model.sk_model.set(sk_model);
|
||||
node.add_aspect_raw(model.clone());
|
||||
Ok(model)
|
||||
}
|
||||
|
||||
fn draw(&self, token: &MainThreadToken) {
|
||||
let Some(sk_model) = self.sk_model.get() else {
|
||||
return;
|
||||
};
|
||||
node.add_local_signal("setMaterialParameter", Model::set_material_parameter);
|
||||
let model_arc = MODEL_REGISTRY.add(model);
|
||||
let _ = model_arc.pending_model_path.set(
|
||||
model_arc
|
||||
.resource_id
|
||||
.get_file(
|
||||
&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());
|
||||
Ok(model_arc)
|
||||
}
|
||||
|
||||
fn set_material_parameter(
|
||||
node: &Node,
|
||||
_calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct MaterialParameterInfo {
|
||||
idx: u32,
|
||||
name: String,
|
||||
value: MaterialParameter,
|
||||
let parts = self.parts.lock();
|
||||
for model_node in &*parts {
|
||||
model_node.update();
|
||||
}
|
||||
let info: MaterialParameterInfo = deserialize(data)?;
|
||||
|
||||
node.model
|
||||
.get()
|
||||
.unwrap()
|
||||
.pending_material_parameters
|
||||
.lock()
|
||||
.insert((info.idx, info.name), info.value);
|
||||
drop(parts);
|
||||
|
||||
if let Some(node) = self.space.node() {
|
||||
if node.enabled() {
|
||||
sk_model.draw(token, self.space.global_transform(), None, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// TODO: proper hread safety in stereokit_rust (probably just bind stereokit directly)
|
||||
unsafe impl Send for Model {}
|
||||
unsafe impl Sync for Model {}
|
||||
impl Aspect for Model {
|
||||
const NAME: &'static str = "Model";
|
||||
}
|
||||
impl ModelAspect for Model {
|
||||
#[doc = "Bind a model part to the node with the ID input."]
|
||||
fn bind_model_part(
|
||||
node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
part_path: String,
|
||||
) -> color_eyre::eyre::Result<()> {
|
||||
let model = node.get_aspect::<Model>()?;
|
||||
let parts = model.parts.lock();
|
||||
let Some(part) = parts.iter().find(|p| p.path == part_path) else {
|
||||
let paths = parts.iter().map(|p| &p.path).collect::<Vec<_>>();
|
||||
bail!("Couldn't find model part at path {part_path}, all available paths: {paths:?}",)
|
||||
};
|
||||
Alias::create_with_id(
|
||||
&part.space.node().unwrap(),
|
||||
&calling_client,
|
||||
id,
|
||||
MODEL_PART_ASPECT_ALIAS_INFO.clone(),
|
||||
Some(&part.aliases),
|
||||
)?;
|
||||
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 {
|
||||
fn drop(&mut self) {
|
||||
if let Some(model) = self.sk_model.take() {
|
||||
destroy_queue::add(model);
|
||||
}
|
||||
MODEL_REGISTRY.remove(self);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw_all(sk: &StereoKit, draw_ctx: &DrawContext) {
|
||||
pub fn draw_all(token: &MainThreadToken) {
|
||||
for model in MODEL_REGISTRY.get_valid_contents() {
|
||||
model.draw(sk, draw_ctx);
|
||||
model.draw(token);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateModelInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
resource: ResourceID,
|
||||
}
|
||||
let info: CreateModelInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/drawable/model", 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)?;
|
||||
Model::add_to(&node, info.resource)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
137
src/nodes/drawable/shader_manipulation.rs
Normal file
137
src/nodes/drawable/shader_manipulation.rs
Normal file
@@ -0,0 +1,137 @@
|
||||
#![allow(dead_code)]
|
||||
use smithay::backend::renderer::gles::{
|
||||
ffi::{self, Gles2, FRAGMENT_SHADER, VERTEX_SHADER},
|
||||
GlesError,
|
||||
};
|
||||
use stereokit_rust::shader::{Shader, _ShaderT};
|
||||
use tracing::error;
|
||||
|
||||
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 = sk_shader.0.as_mut() as *mut _ShaderT as *mut FfiShader;
|
||||
if let Some(shader) = shader.as_mut() {
|
||||
shader.shader.vertex = gl_vert;
|
||||
shader.shader.pixel = gl_frag;
|
||||
shader.shader.program = gl_prog;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
5
src/nodes/drawable/shaders.rs
Normal file
5
src/nodes/drawable/shaders.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
// Simula shader with fancy lanzcos sampling
|
||||
pub const UNLIT_SHADER_BYTES: &[u8] = include_bytes!("assets/shaders/shader_unlit_gamma.hlsl.sks");
|
||||
|
||||
// Simula shader with fancy lanzcos sampling
|
||||
pub const PANEL_SHADER_BYTES: &[u8] = include_bytes!("assets/shaders/shader_unlit_simula.hlsl.sks");
|
||||
@@ -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;
|
||||
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;
|
||||
}
|
||||
float4 ps(psIn input) : SV_TARGET {
|
||||
@@ -4,19 +4,19 @@
|
||||
|
||||
//--name = stardust/text_shader
|
||||
//--diffuse = white
|
||||
//--fcFactor = 1.0
|
||||
//--ripple = 4.0
|
||||
//--uv_offset = 0.0, 0.0
|
||||
//--uv_scale = 1.0, 1.0
|
||||
//--fcFactor = 1.0
|
||||
//--ripple = 4.0
|
||||
//--alpha_min = 0.0
|
||||
//--alpha_max = 1.0
|
||||
Texture2D diffuse : register(t0);
|
||||
SamplerState diffuse_s : register(s0);
|
||||
float4 diffuse_i;
|
||||
float fcFactor;
|
||||
float ripple;
|
||||
float2 uv_scale;
|
||||
float2 uv_offset;
|
||||
float fcFactor;
|
||||
float ripple;
|
||||
float alpha_min;
|
||||
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;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1,112 +1,78 @@
|
||||
use crate::{
|
||||
core::{client::Client, destroy_queue, registry::Registry, resource::ResourceID},
|
||||
nodes::{
|
||||
spatial::{find_spatial_parent, parse_transform, Spatial},
|
||||
Node,
|
||||
},
|
||||
core::{client::Client, destroy_queue, registry::Registry, resource::get_resource_file},
|
||||
nodes::{spatial::Spatial, Aspect, Node},
|
||||
};
|
||||
use anyhow::{anyhow, ensure, Result};
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use glam::{vec3, Mat4, Vec2};
|
||||
use mint::Vector2;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use prisma::{Flatten, Rgb, Rgba};
|
||||
use send_wrapper::SendWrapper;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::{schemas::flex::deserialize, values::Transform};
|
||||
use std::{path::PathBuf, sync::Arc};
|
||||
use stereokit::{
|
||||
use std::{ffi::OsStr, path::PathBuf, sync::Arc};
|
||||
use stereokit_rust::{
|
||||
font::Font,
|
||||
lifecycle::DrawContext,
|
||||
text::{self, TextAlign, TextFit, TextStyle},
|
||||
StereoKit,
|
||||
sk::MainThreadToken,
|
||||
system::{TextAlign, TextFit, TextStyle as SkTextStyle},
|
||||
util::{Color128, Color32},
|
||||
};
|
||||
|
||||
use super::{TextAspect, TextStyle};
|
||||
|
||||
static TEXT_REGISTRY: Registry<Text> = Registry::new();
|
||||
|
||||
struct TextData {
|
||||
text: String,
|
||||
character_height: f32,
|
||||
text_align: TextAlign,
|
||||
bounds: Option<Vec2>,
|
||||
fit: TextFit,
|
||||
bounds_align: TextAlign,
|
||||
color: Rgba<f32>,
|
||||
fn convert_align(x_align: super::XAlign, y_align: super::YAlign) -> TextAlign {
|
||||
match (x_align, y_align) {
|
||||
(super::XAlign::Left, super::YAlign::Top) => TextAlign::TopLeft,
|
||||
(super::XAlign::Left, super::YAlign::Center) => TextAlign::CenterLeft,
|
||||
(super::XAlign::Left, super::YAlign::Bottom) => TextAlign::BottomLeft,
|
||||
(super::XAlign::Center, super::YAlign::Top) => TextAlign::Center,
|
||||
(super::XAlign::Center, super::YAlign::Center) => TextAlign::Center,
|
||||
(super::XAlign::Center, super::YAlign::Bottom) => TextAlign::BottomCenter,
|
||||
(super::XAlign::Right, super::YAlign::Top) => TextAlign::TopRight,
|
||||
(super::XAlign::Right, super::YAlign::Center) => TextAlign::CenterRight,
|
||||
(super::XAlign::Right, super::YAlign::Bottom) => TextAlign::BottomRight,
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Text {
|
||||
space: Arc<Spatial>,
|
||||
font_path: Option<PathBuf>,
|
||||
style: OnceCell<SendWrapper<TextStyle>>,
|
||||
style: OnceCell<SkTextStyle>,
|
||||
|
||||
data: Mutex<TextData>,
|
||||
text: Mutex<String>,
|
||||
data: Mutex<TextStyle>,
|
||||
}
|
||||
impl Text {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn add_to(
|
||||
node: &Arc<Node>,
|
||||
font_resource_id: Option<ResourceID>,
|
||||
text: String,
|
||||
character_height: f32,
|
||||
text_align: TextAlign,
|
||||
bounds: Option<Vector2<f32>>,
|
||||
fit: TextFit,
|
||||
bounds_align: TextAlign,
|
||||
color: Rgba<f32>,
|
||||
) -> Result<Arc<Text>> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
ensure!(
|
||||
node.model.get().is_none(),
|
||||
"Internal: Node already has text attached!"
|
||||
);
|
||||
|
||||
let client = node
|
||||
.get_client()
|
||||
.ok_or_else(|| anyhow!("Client not found"))?;
|
||||
pub fn add_to(node: &Arc<Node>, text: String, style: TextStyle) -> Result<Arc<Text>> {
|
||||
let client = node.get_client().ok_or_else(|| eyre!("Client not found"))?;
|
||||
let text = TEXT_REGISTRY.add(Text {
|
||||
space: node.spatial.get().unwrap().clone(),
|
||||
font_path: font_resource_id
|
||||
.and_then(|res| res.get_file(&client.base_resource_prefixes.lock().clone())),
|
||||
space: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
font_path: style.font.as_ref().and_then(|res| {
|
||||
get_resource_file(res, &client, &[OsStr::new("ttf"), OsStr::new("otf")])
|
||||
}),
|
||||
style: OnceCell::new(),
|
||||
|
||||
data: Mutex::new(TextData {
|
||||
text,
|
||||
character_height,
|
||||
text_align,
|
||||
bounds: bounds.map(|b| b.into()),
|
||||
fit,
|
||||
bounds_align,
|
||||
color,
|
||||
}),
|
||||
text: Mutex::new(text),
|
||||
data: Mutex::new(style),
|
||||
});
|
||||
node.add_local_signal("setCharacterHeight", Text::set_character_height_flex);
|
||||
node.add_local_signal("setText", Text::set_text_flex);
|
||||
let _ = node.text.set(text.clone());
|
||||
<Text as TextAspect>::add_node_members(node);
|
||||
node.add_aspect_raw(text.clone());
|
||||
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
fn draw(&self, sk: &StereoKit, draw_ctx: &DrawContext) {
|
||||
fn draw(&self, token: &MainThreadToken) {
|
||||
let style =
|
||||
self.style
|
||||
.get_or_try_init(|| -> Result<SendWrapper<TextStyle>, anyhow::Error> {
|
||||
let font = if let Some(path) = self.font_path.as_deref() {
|
||||
Font::from_file(sk, path)
|
||||
} else {
|
||||
Some(Font::default(sk))
|
||||
};
|
||||
Ok(SendWrapper::new(TextStyle::new(
|
||||
sk,
|
||||
font.ok_or(std::fmt::Error)?,
|
||||
1.0,
|
||||
Rgba::new(Rgb::new(1.0, 1.0, 1.0), 1.0),
|
||||
)))
|
||||
.get_or_try_init(|| -> Result<SkTextStyle, color_eyre::eyre::Error> {
|
||||
let font = self
|
||||
.font_path
|
||||
.as_deref()
|
||||
.and_then(|path| Font::from_file(path).ok())
|
||||
.unwrap_or_default();
|
||||
Ok(SkTextStyle::from_font(font, 1.0, Color32::WHITE))
|
||||
});
|
||||
|
||||
if let Ok(style) = style {
|
||||
let text = self.text.lock();
|
||||
let data = self.data.lock();
|
||||
let transform = self.space.global_transform()
|
||||
* Mat4::from_scale(vec3(
|
||||
@@ -114,47 +80,75 @@ impl Text {
|
||||
data.character_height,
|
||||
data.character_height,
|
||||
));
|
||||
if let Some(bounds) = data.bounds {
|
||||
text::draw_in(
|
||||
draw_ctx,
|
||||
&data.text,
|
||||
if let Some(bounds) = &data.bounds {
|
||||
stereokit_rust::system::Text::add_in(
|
||||
token,
|
||||
&*text,
|
||||
transform,
|
||||
bounds / data.character_height,
|
||||
data.fit,
|
||||
style,
|
||||
data.bounds_align,
|
||||
data.text_align,
|
||||
vec3(0.0, 0.0, 0.0),
|
||||
data.color,
|
||||
Vec2::from(bounds.bounds) / data.character_height,
|
||||
match bounds.fit {
|
||||
super::TextFit::Wrap => TextFit::Wrap,
|
||||
super::TextFit::Clip => TextFit::Clip,
|
||||
super::TextFit::Squeeze => TextFit::Squeeze,
|
||||
super::TextFit::Exact => TextFit::Exact,
|
||||
super::TextFit::Overflow => TextFit::Overflow,
|
||||
},
|
||||
Some(*style),
|
||||
Some(Color128::new(
|
||||
data.color.c.r,
|
||||
data.color.c.g,
|
||||
data.color.c.b,
|
||||
data.color.a,
|
||||
)),
|
||||
data.bounds
|
||||
.as_ref()
|
||||
.map(|b| convert_align(b.anchor_align_x, b.anchor_align_y)),
|
||||
Some(convert_align(data.text_align_x, data.text_align_y)),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
} else {
|
||||
text::draw_at(
|
||||
draw_ctx,
|
||||
&data.text,
|
||||
stereokit_rust::system::Text::add_at(
|
||||
token,
|
||||
&*text,
|
||||
transform,
|
||||
style,
|
||||
data.bounds_align,
|
||||
data.text_align,
|
||||
vec3(0.0, 0.0, 0.0),
|
||||
data.color,
|
||||
Some(*style),
|
||||
Some(Color128::new(
|
||||
data.color.c.r,
|
||||
data.color.c.g,
|
||||
data.color.c.b,
|
||||
data.color.a,
|
||||
)),
|
||||
data.bounds
|
||||
.as_ref()
|
||||
.map(|b| convert_align(b.anchor_align_x, b.anchor_align_y)),
|
||||
Some(convert_align(data.text_align_x, data.text_align_y)),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_character_height_flex(
|
||||
node: &Node,
|
||||
}
|
||||
impl Aspect for Text {
|
||||
const NAME: &'static str = "Text";
|
||||
}
|
||||
impl TextAspect for Text {
|
||||
fn set_character_height(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
height: f32,
|
||||
) -> Result<()> {
|
||||
let height = flexbuffers::Reader::get_root(data)?.get_f64()? as f32;
|
||||
node.text.get().unwrap().data.lock().character_height = height;
|
||||
let this_text = node.get_aspect::<Text>()?;
|
||||
this_text.data.lock().character_height = height;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_text_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
let text = flexbuffers::Reader::get_root(data)?.get_str()?.to_string();
|
||||
node.text.get().unwrap().data.lock().text = text;
|
||||
fn set_text(node: Arc<Node>, _calling_client: Arc<Client>, text: String) -> Result<()> {
|
||||
let this_text = node.get_aspect::<Text>()?;
|
||||
*this_text.text.lock() = text;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -167,45 +161,12 @@ impl Drop for Text {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn draw_all(sk: &StereoKit, draw_ctx: &DrawContext) {
|
||||
pub fn draw_all(token: &MainThreadToken) {
|
||||
for text in TEXT_REGISTRY.get_valid_contents() {
|
||||
text.draw(sk, draw_ctx);
|
||||
if let Some(node) = text.space.node() {
|
||||
if node.enabled() {
|
||||
text.draw(token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateTextInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
text: String,
|
||||
font_resource: Option<ResourceID>,
|
||||
character_height: f32,
|
||||
text_align: TextAlign,
|
||||
bounds: Option<Vector2<f32>>,
|
||||
fit: TextFit,
|
||||
bounds_align: TextAlign,
|
||||
color: [f32; 4],
|
||||
}
|
||||
let info: CreateTextInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/drawable/text", info.name, true);
|
||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = parse_transform(info.transform, true, true, true)?;
|
||||
let color = Rgba::from_slice(&info.color);
|
||||
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
Text::add_to(
|
||||
&node,
|
||||
info.font_resource,
|
||||
info.text,
|
||||
info.character_height,
|
||||
info.text_align,
|
||||
info.bounds,
|
||||
info.fit,
|
||||
info.bounds_align,
|
||||
color,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
287
src/nodes/fields.rs
Normal file
287
src/nodes/fields.rs
Normal file
@@ -0,0 +1,287 @@
|
||||
use super::alias::{Alias, AliasInfo};
|
||||
use super::spatial::{
|
||||
Spatial, SPATIAL_REF_GET_LOCAL_BOUNDING_BOX_SERVER_OPCODE,
|
||||
SPATIAL_REF_GET_RELATIVE_BOUNDING_BOX_SERVER_OPCODE, SPATIAL_REF_GET_TRANSFORM_SERVER_OPCODE,
|
||||
};
|
||||
use super::{Aspect, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::create_interface;
|
||||
use crate::nodes::spatial::Transform;
|
||||
use crate::nodes::spatial::SPATIAL_ASPECT_ALIAS_INFO;
|
||||
use crate::nodes::spatial::SPATIAL_REF_ASPECT_ALIAS_INFO;
|
||||
use color_eyre::eyre::{OptionExt, Result};
|
||||
use glam::{vec2, vec3, vec3a, Vec3, Vec3A, Vec3Swizzles};
|
||||
use once_cell::sync::Lazy;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
use stardust_xr::values::Vector3;
|
||||
use std::sync::Arc;
|
||||
|
||||
// TODO: get SDFs working properly with non-uniform scale and so on, output distance relative to the spatial it's compared against
|
||||
|
||||
pub static FIELD_ALIAS_INFO: Lazy<AliasInfo> = Lazy::new(|| AliasInfo {
|
||||
server_methods: vec![
|
||||
SPATIAL_REF_GET_TRANSFORM_SERVER_OPCODE,
|
||||
SPATIAL_REF_GET_LOCAL_BOUNDING_BOX_SERVER_OPCODE,
|
||||
SPATIAL_REF_GET_RELATIVE_BOUNDING_BOX_SERVER_OPCODE,
|
||||
FIELD_REF_DISTANCE_SERVER_OPCODE,
|
||||
FIELD_REF_NORMAL_SERVER_OPCODE,
|
||||
FIELD_REF_CLOSEST_POINT_SERVER_OPCODE,
|
||||
FIELD_REF_RAY_MARCH_SERVER_OPCODE,
|
||||
],
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
stardust_xr_server_codegen::codegen_field_protocol!();
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
pub static ref EXPORTED_FIELDS: Mutex<FxHashMap<u64, Arc<Node>>> = Mutex::new(FxHashMap::default());
|
||||
}
|
||||
|
||||
pub trait FieldTrait: Send + Sync + 'static {
|
||||
fn spatial_ref(&self) -> &Spatial;
|
||||
|
||||
fn local_distance(&self, p: Vec3A) -> f32;
|
||||
fn local_normal(&self, p: Vec3A, r: f32) -> Vec3A {
|
||||
let d = self.local_distance(p);
|
||||
let e = vec2(r, 0_f32);
|
||||
|
||||
let n = vec3a(d, d, d)
|
||||
- vec3a(
|
||||
self.local_distance(vec3a(e.x, e.y, e.y)),
|
||||
self.local_distance(vec3a(e.y, e.x, e.y)),
|
||||
self.local_distance(vec3a(e.y, e.y, e.x)),
|
||||
);
|
||||
|
||||
n.normalize()
|
||||
}
|
||||
fn local_closest_point(&self, p: Vec3A, r: f32) -> Vec3A {
|
||||
p - (self.local_normal(p, r) * self.local_distance(p))
|
||||
}
|
||||
|
||||
fn distance(&self, reference_space: &Spatial, p: Vec3A) -> f32 {
|
||||
let reference_to_local_space =
|
||||
Spatial::space_to_space_matrix(Some(reference_space), Some(self.spatial_ref()));
|
||||
let local_p = reference_to_local_space.transform_point3a(p);
|
||||
self.local_distance(local_p)
|
||||
}
|
||||
fn normal(&self, reference_space: &Spatial, p: Vec3A, r: f32) -> Vec3A {
|
||||
let reference_to_local_space =
|
||||
Spatial::space_to_space_matrix(Some(reference_space), Some(self.spatial_ref()));
|
||||
let local_p = reference_to_local_space.transform_point3a(p);
|
||||
reference_to_local_space
|
||||
.inverse()
|
||||
.transform_vector3a(self.local_normal(local_p, r))
|
||||
}
|
||||
fn closest_point(&self, reference_space: &Spatial, p: Vec3A, r: f32) -> Vec3A {
|
||||
let reference_to_local_space =
|
||||
Spatial::space_to_space_matrix(Some(reference_space), Some(self.spatial_ref()));
|
||||
let local_p = reference_to_local_space.transform_point3a(p);
|
||||
reference_to_local_space
|
||||
.inverse()
|
||||
.transform_point3a(self.local_closest_point(local_p, r))
|
||||
}
|
||||
|
||||
fn ray_march(&self, ray: Ray) -> RayMarchResult {
|
||||
let mut result = RayMarchResult {
|
||||
ray_origin: ray.origin.into(),
|
||||
ray_direction: ray.direction.into(),
|
||||
min_distance: f32::MAX,
|
||||
deepest_point_distance: 0_f32,
|
||||
ray_length: 0_f32,
|
||||
ray_steps: 0,
|
||||
};
|
||||
|
||||
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())
|
||||
.normalize();
|
||||
|
||||
while result.ray_steps < MAX_RAY_STEPS && result.ray_length < MAX_RAY_LENGTH {
|
||||
let distance = self.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.min_distance > distance {
|
||||
result.deepest_point_distance = result.ray_length;
|
||||
result.min_distance = distance;
|
||||
}
|
||||
|
||||
result.ray_steps += 1;
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Ray {
|
||||
pub origin: Vec3,
|
||||
pub direction: Vec3,
|
||||
pub space: Arc<Spatial>,
|
||||
}
|
||||
|
||||
// const MIN_RAY_STEPS: u32 = 0;
|
||||
const MAX_RAY_STEPS: u32 = 1000;
|
||||
|
||||
const MIN_RAY_MARCH: f32 = 0.001_f32;
|
||||
const MAX_RAY_MARCH: f32 = f32::MAX;
|
||||
|
||||
// const MIN_RAY_LENGTH: f32 = 0_f32;
|
||||
const MAX_RAY_LENGTH: f32 = 1000_f32;
|
||||
|
||||
pub struct Field {
|
||||
pub spatial: Arc<Spatial>,
|
||||
pub shape: Mutex<Shape>,
|
||||
}
|
||||
impl Field {
|
||||
pub fn add_to(node: &Arc<Node>, shape: Shape) -> Result<Arc<Field>> {
|
||||
let spatial = node.get_aspect::<Spatial>()?;
|
||||
let field = Field {
|
||||
spatial,
|
||||
shape: Mutex::new(shape),
|
||||
};
|
||||
let field = node.add_aspect(field);
|
||||
<Field as FieldRefAspect>::add_node_members(node);
|
||||
<Field as FieldAspect>::add_node_members(node);
|
||||
Ok(field)
|
||||
}
|
||||
}
|
||||
impl Aspect for Field {
|
||||
const NAME: &'static str = "Field";
|
||||
}
|
||||
impl FieldRefAspect for Field {
|
||||
async fn distance(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
space: Arc<Node>,
|
||||
point: Vector3<f32>,
|
||||
) -> Result<f32> {
|
||||
let reference_space = space.get_aspect::<Spatial>()?;
|
||||
let field = node.get_aspect::<Field>()?;
|
||||
Ok(field.distance(&reference_space, point.into()))
|
||||
}
|
||||
|
||||
async fn normal(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
space: Arc<Node>,
|
||||
point: Vector3<f32>,
|
||||
) -> Result<Vector3<f32>> {
|
||||
let reference_space = space.get_aspect::<Spatial>()?;
|
||||
let field = node.get_aspect::<Field>()?;
|
||||
Ok(field.normal(&reference_space, point.into(), 0.0001).into())
|
||||
}
|
||||
|
||||
async fn closest_point(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
space: Arc<Node>,
|
||||
point: Vector3<f32>,
|
||||
) -> Result<Vector3<f32>> {
|
||||
let reference_space = space.get_aspect::<Spatial>()?;
|
||||
let field = node.get_aspect::<Field>()?;
|
||||
Ok(field
|
||||
.closest_point(&reference_space, point.into(), 0.0001)
|
||||
.into())
|
||||
}
|
||||
|
||||
async fn ray_march(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
space: Arc<Node>,
|
||||
ray_origin: Vector3<f32>,
|
||||
ray_direction: Vector3<f32>,
|
||||
) -> Result<RayMarchResult> {
|
||||
let space = space.get_aspect::<Spatial>()?;
|
||||
let field = node.get_aspect::<Field>()?;
|
||||
Ok(field.ray_march(Ray {
|
||||
origin: ray_origin.into(),
|
||||
direction: ray_direction.into(),
|
||||
space,
|
||||
}))
|
||||
}
|
||||
}
|
||||
impl FieldAspect for Field {
|
||||
fn set_shape(node: Arc<Node>, _calling_client: Arc<Client>, shape: Shape) -> Result<()> {
|
||||
let field = node.get_aspect::<Field>()?;
|
||||
*field.shape.lock() = shape;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn export_field(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<u64> {
|
||||
let id = rand::random();
|
||||
EXPORTED_FIELDS.lock().insert(id, node);
|
||||
Ok(id)
|
||||
}
|
||||
}
|
||||
impl FieldTrait for Field {
|
||||
fn spatial_ref(&self) -> &Spatial {
|
||||
&self.spatial
|
||||
}
|
||||
fn local_distance(&self, p: Vec3A) -> f32 {
|
||||
match self.shape.lock().clone() {
|
||||
Shape::Box(size) => {
|
||||
let q = vec3(
|
||||
p.x.abs() - (size.x * 0.5_f32),
|
||||
p.y.abs() - (size.y * 0.5_f32),
|
||||
p.z.abs() - (size.z * 0.5_f32),
|
||||
);
|
||||
let v = vec3a(q.x.max(0_f32), q.y.max(0_f32), q.z.max(0_f32));
|
||||
v.length() + q.x.max(q.y.max(q.z)).min(0_f32)
|
||||
}
|
||||
Shape::Cylinder(CylinderShape { length, radius }) => {
|
||||
let d = vec2(p.xy().length().abs() - radius, p.z.abs() - (length * 0.5));
|
||||
d.x.max(d.y).min(0.0) + d.max(vec2(0.0, 0.0)).length()
|
||||
}
|
||||
Shape::Sphere(radius) => p.length() - radius,
|
||||
Shape::Torus(TorusShape { radius_a, radius_b }) => {
|
||||
let q = vec2(p.xz().length() - radius_a, p.y);
|
||||
q.length() - radius_b
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
create_interface!(FieldInterface);
|
||||
pub struct FieldInterface;
|
||||
impl InterfaceAspect for FieldInterface {
|
||||
async fn import_field_ref(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
uid: u64,
|
||||
) -> Result<Arc<Node>> {
|
||||
EXPORTED_FIELDS
|
||||
.lock()
|
||||
.get(&uid)
|
||||
.map(|s| {
|
||||
Alias::create(
|
||||
s,
|
||||
&calling_client,
|
||||
FIELD_REF_ASPECT_ALIAS_INFO.clone(),
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
})
|
||||
.ok_or_eyre("Couldn't find spatial with that ID")
|
||||
}
|
||||
|
||||
fn create_field(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
shape: Shape,
|
||||
) -> Result<()> {
|
||||
let transform = transform.to_mat4(true, true, false);
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let node = Node::from_id(&calling_client, id, true).add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
Field::add_to(&node, shape)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
use super::{Field, FieldTrait, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||
use anyhow::{ensure, Result};
|
||||
use glam::{vec3, vec3a, Vec3, Vec3A};
|
||||
use mint::Vector3;
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use stardust_xr::values::Transform;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct BoxField {
|
||||
space: Arc<Spatial>,
|
||||
size: Mutex<Vec3>,
|
||||
}
|
||||
|
||||
impl BoxField {
|
||||
pub fn add_to(node: &Arc<Node>, size: Vector3<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 box_field = BoxField {
|
||||
space: node.spatial.get().unwrap().clone(),
|
||||
size: Mutex::new(size.into()),
|
||||
};
|
||||
box_field.add_field_methods(node);
|
||||
node.add_local_signal("setSize", BoxField::set_size_flex);
|
||||
let _ = node.field.set(Arc::new(Field::Box(box_field)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_size(&self, size: Vector3<f32>) {
|
||||
*self.size.lock() = size.into();
|
||||
}
|
||||
|
||||
pub fn set_size_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
if let Field::Box(box_field) = node.field.get().unwrap().as_ref() {
|
||||
box_field.set_size(deserialize(data)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl FieldTrait for BoxField {
|
||||
fn local_distance(&self, p: Vec3A) -> f32 {
|
||||
let size = self.size.lock();
|
||||
let q = vec3(
|
||||
p.x.abs() - (size.x * 0.5_f32),
|
||||
p.y.abs() - (size.y * 0.5_f32),
|
||||
p.z.abs() - (size.z * 0.5_f32),
|
||||
);
|
||||
let v = vec3a(q.x.max(0_f32), q.y.max(0_f32), q.z.max(0_f32));
|
||||
v.length() + q.x.max(q.y.max(q.z)).min(0_f32)
|
||||
}
|
||||
fn spatial_ref(&self) -> &Spatial {
|
||||
self.space.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_box_field_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateFieldInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
size: Vector3<f32>,
|
||||
}
|
||||
let info: CreateFieldInfo = deserialize(data)?;
|
||||
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)?;
|
||||
BoxField::add_to(&node, info.size)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
use super::{Field, FieldTrait, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||
use anyhow::{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 CylinderField {
|
||||
space: Arc<Spatial>,
|
||||
length: AtomicF32,
|
||||
radius: AtomicF32,
|
||||
}
|
||||
|
||||
impl CylinderField {
|
||||
pub fn add_to(node: &Arc<Node>, length: f32, radius: 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 cylinder_field = CylinderField {
|
||||
space: node.spatial.get().unwrap().clone(),
|
||||
length: AtomicF32::new(length.abs()),
|
||||
radius: AtomicF32::new(radius.abs()),
|
||||
};
|
||||
cylinder_field.add_field_methods(node);
|
||||
node.add_local_signal("setSize", CylinderField::set_size_flex);
|
||||
let _ = node.field.set(Arc::new(Field::Cylinder(cylinder_field)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_size(&self, length: f32, radius: f32) {
|
||||
self.length.store(length.abs(), Ordering::Relaxed);
|
||||
self.radius.store(radius.abs(), Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn set_size_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
if let Field::Cylinder(cylinder_field) = node.field.get().unwrap().as_ref() {
|
||||
let (length, radius) = deserialize(data)?;
|
||||
cylinder_field.set_size(length, radius);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl FieldTrait for CylinderField {
|
||||
fn local_distance(&self, p: Vec3A) -> f32 {
|
||||
let radius = self.radius.load(Ordering::Relaxed);
|
||||
let length = self.length.load(Ordering::Relaxed);
|
||||
let d = vec2(p.xy().length().abs() - radius, p.z.abs() - (length * 0.5));
|
||||
|
||||
d.x.max(d.y).min(0.0) + d.max(vec2(0.0, 0.0)).length()
|
||||
}
|
||||
fn spatial_ref(&self) -> &Spatial {
|
||||
self.space.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_cylinder_field_flex(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateFieldInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
length: f32,
|
||||
radius: f32,
|
||||
}
|
||||
let info: CreateFieldInfo = deserialize(data)?;
|
||||
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)?;
|
||||
CylinderField::add_to(&node, dbg!(info.length), dbg!(info.radius))?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
mod r#box;
|
||||
mod cylinder;
|
||||
mod sphere;
|
||||
|
||||
use self::cylinder::{create_cylinder_field_flex, CylinderField};
|
||||
use self::r#box::{create_box_field_flex, BoxField};
|
||||
use self::sphere::{create_sphere_field_flex, SphereField};
|
||||
|
||||
use super::spatial::Spatial;
|
||||
use super::Node;
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::spatial::find_reference_space;
|
||||
use anyhow::Result;
|
||||
use glam::{vec2, vec3a, Vec3, Vec3A};
|
||||
use mint::Vector3;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
|
||||
use std::ops::Deref;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub trait FieldTrait {
|
||||
fn local_distance(&self, p: Vec3A) -> f32;
|
||||
fn local_normal(&self, p: Vec3A, r: f32) -> Vec3A {
|
||||
let d = self.local_distance(p);
|
||||
let e = vec2(r, 0_f32);
|
||||
|
||||
let n = vec3a(d, d, d)
|
||||
- vec3a(
|
||||
self.local_distance(vec3a(e.x, e.y, e.y)),
|
||||
self.local_distance(vec3a(e.y, e.x, e.y)),
|
||||
self.local_distance(vec3a(e.y, e.y, e.x)),
|
||||
);
|
||||
|
||||
n.normalize()
|
||||
}
|
||||
fn local_closest_point(&self, p: Vec3A, r: f32) -> Vec3A {
|
||||
p - (self.local_normal(p, r) * self.local_distance(p))
|
||||
}
|
||||
|
||||
fn distance(&self, reference_space: &Spatial, p: Vec3A) -> f32 {
|
||||
let reference_to_local_space =
|
||||
Spatial::space_to_space_matrix(Some(reference_space), Some(self.spatial_ref()));
|
||||
let local_p = reference_to_local_space.transform_point3a(p);
|
||||
self.local_distance(local_p)
|
||||
}
|
||||
fn normal(&self, reference_space: &Spatial, p: Vec3A, r: f32) -> Vec3A {
|
||||
let reference_to_local_space =
|
||||
Spatial::space_to_space_matrix(Some(reference_space), Some(self.spatial_ref()));
|
||||
let local_p = reference_to_local_space.transform_point3a(p);
|
||||
reference_to_local_space
|
||||
.inverse()
|
||||
.transform_vector3a(self.local_normal(local_p, r))
|
||||
}
|
||||
fn closest_point(&self, reference_space: &Spatial, p: Vec3A, r: f32) -> Vec3A {
|
||||
let reference_to_local_space =
|
||||
Spatial::space_to_space_matrix(Some(reference_space), Some(self.spatial_ref()));
|
||||
let local_p = reference_to_local_space.transform_point3a(p);
|
||||
reference_to_local_space
|
||||
.inverse()
|
||||
.transform_point3a(self.local_closest_point(local_p, r))
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
fn spatial_ref(&self) -> &Spatial;
|
||||
}
|
||||
|
||||
fn field_distance_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>,
|
||||
}
|
||||
let args: FieldInfoArgs = deserialize(data)?;
|
||||
let reference_space = find_reference_space(&calling_client, args.reference_space_path)?;
|
||||
|
||||
let distance = node
|
||||
.field
|
||||
.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(
|
||||
reference_space.as_ref(),
|
||||
args.point.into(),
|
||||
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(
|
||||
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>) {
|
||||
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 origin: Vec3,
|
||||
pub direction: Vec3,
|
||||
pub space: Arc<Spatial>,
|
||||
}
|
||||
|
||||
pub struct RayMarchResult {
|
||||
pub ray: Ray,
|
||||
pub distance: f32,
|
||||
pub deepest_point_distance: f32,
|
||||
pub ray_length: f32,
|
||||
pub ray_steps: u32,
|
||||
}
|
||||
|
||||
// const MIN_RAY_STEPS: u32 = 0;
|
||||
const MAX_RAY_STEPS: u32 = 1000;
|
||||
|
||||
const MIN_RAY_MARCH: f32 = 0.001_f32;
|
||||
const MAX_RAY_MARCH: f32 = f32::MAX;
|
||||
|
||||
// const MIN_RAY_LENGTH: f32 = 0_f32;
|
||||
const MAX_RAY_LENGTH: f32 = 1000_f32;
|
||||
|
||||
pub fn ray_march(ray: Ray, field: &Field) -> RayMarchResult {
|
||||
let mut result = RayMarchResult {
|
||||
ray,
|
||||
distance: f32::MAX,
|
||||
deepest_point_distance: 0_f32,
|
||||
ray_length: 0_f32,
|
||||
ray_steps: 0,
|
||||
};
|
||||
|
||||
let ray_to_field_matrix =
|
||||
Spatial::space_to_space_matrix(Some(&result.ray.space), Some(field.spatial_ref()));
|
||||
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);
|
||||
|
||||
result.ray_steps += 1;
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
pub fn find_field(client: &Client, path: &str) -> Result<Arc<Field>> {
|
||||
Ok(client
|
||||
.get_node("Field", path)?
|
||||
.get_aspect("Field", "info", |n| &n.field)?)
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
use super::{Field, FieldTrait, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::spatial::{find_spatial_parent, Spatial};
|
||||
use anyhow::{ensure, Result};
|
||||
use glam::{Mat4, Vec3A};
|
||||
use mint::Vector3;
|
||||
use portable_atomic::AtomicF32;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct SphereField {
|
||||
space: Arc<Spatial>,
|
||||
radius: AtomicF32,
|
||||
}
|
||||
|
||||
impl SphereField {
|
||||
pub fn add_to(node: &Arc<Node>, radius: 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 sphere_field = SphereField {
|
||||
space: node.spatial.get().unwrap().clone(),
|
||||
radius: AtomicF32::new(radius),
|
||||
};
|
||||
sphere_field.add_field_methods(node);
|
||||
node.add_local_signal("setRadius", SphereField::set_radius_flex);
|
||||
let _ = node.field.set(Arc::new(Field::Sphere(sphere_field)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_radius(&self, radius: f32) {
|
||||
self.radius.store(radius, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn set_radius_flex(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
let radius = flexbuffers::Reader::get_root(data)?.get_f64()? as f32;
|
||||
if let Field::Sphere(sphere_field) = node.field.get().unwrap().as_ref() {
|
||||
sphere_field.set_radius(radius);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl FieldTrait for SphereField {
|
||||
fn local_distance(&self, p: Vec3A) -> f32 {
|
||||
p.length() - self.radius.load(Ordering::Relaxed)
|
||||
}
|
||||
fn local_normal(&self, p: Vec3A, _r: f32) -> Vec3A {
|
||||
-p.normalize()
|
||||
}
|
||||
fn local_closest_point(&self, p: Vec3A, _r: f32) -> Vec3A {
|
||||
p.normalize() * self.radius.load(Ordering::Relaxed)
|
||||
}
|
||||
fn spatial_ref(&self) -> &Spatial {
|
||||
self.space.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_sphere_field_flex(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateFieldInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
origin: Option<Vector3<f32>>,
|
||||
radius: f32,
|
||||
}
|
||||
let info: CreateFieldInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/field", info.name, true);
|
||||
let parent = find_spatial_parent(&calling_client, info.parent_path)?;
|
||||
let transform = Mat4::from_translation(
|
||||
info.origin
|
||||
.unwrap_or_else(|| Vector3::from([0.0; 3]))
|
||||
.into(),
|
||||
);
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
SphereField::add_to(&node, info.radius)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
use super::{alias::Alias, spatial::Spatial, Node};
|
||||
use crate::{
|
||||
core::client::{Client, INTERNAL_CLIENT},
|
||||
nodes::alias::AliasInfo,
|
||||
};
|
||||
use glam::{vec3, Mat4};
|
||||
use std::sync::Arc;
|
||||
use stereokit::StereoKit;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
static ref HMD: Arc<Node> = create();
|
||||
}
|
||||
|
||||
fn create() -> Arc<Node> {
|
||||
let node = Arc::new(Node::create(&INTERNAL_CLIENT, "", "hmd", false));
|
||||
Spatial::add_to(&node, None, Mat4::IDENTITY).unwrap();
|
||||
|
||||
node
|
||||
}
|
||||
|
||||
pub fn frame(sk: &StereoKit) {
|
||||
let spatial = HMD.spatial.get().unwrap();
|
||||
let hmd_pose = sk.input_head();
|
||||
*spatial.transform.lock() = Mat4::from_scale_rotation_translation(
|
||||
vec3(1.0, 1.0, 1.0),
|
||||
hmd_pose.orientation.into(),
|
||||
hmd_pose.position.into(),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn make_alias(client: &Arc<Client>) -> Arc<Node> {
|
||||
Alias::new(
|
||||
client,
|
||||
"",
|
||||
"hmd",
|
||||
&HMD,
|
||||
AliasInfo {
|
||||
local_signals: vec!["getTransform"],
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -1,48 +1,89 @@
|
||||
use crate::nodes::fields::Field;
|
||||
use super::{Finger, Hand, InputDataTrait, InputHandler, InputMethod, Joint, Thumb};
|
||||
use crate::nodes::fields::{Field, FieldTrait};
|
||||
use crate::nodes::spatial::Spatial;
|
||||
use glam::{vec3a, Mat4};
|
||||
use stardust_xr::schemas::flat::{Hand as FlatHand, InputDataType, Joint};
|
||||
use glam::{vec3a, Mat4, Quat};
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{DistanceLink, InputSpecialization};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Hand {
|
||||
pub base: FlatHand,
|
||||
impl Default for Joint {
|
||||
fn default() -> Self {
|
||||
Joint {
|
||||
position: [0.0; 3].into(),
|
||||
rotation: Quat::IDENTITY.into(),
|
||||
radius: 0.0,
|
||||
distance: 0.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl InputSpecialization for Hand {
|
||||
#[allow(clippy::derivable_impls)]
|
||||
impl Default for Finger {
|
||||
fn default() -> Self {
|
||||
Finger {
|
||||
tip: Default::default(),
|
||||
distal: Default::default(),
|
||||
intermediate: Default::default(),
|
||||
proximal: Default::default(),
|
||||
metacarpal: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[allow(clippy::derivable_impls)]
|
||||
impl Default for Thumb {
|
||||
fn default() -> Self {
|
||||
Thumb {
|
||||
tip: Default::default(),
|
||||
distal: Default::default(),
|
||||
proximal: Default::default(),
|
||||
metacarpal: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[allow(clippy::derivable_impls)]
|
||||
impl Default for Hand {
|
||||
fn default() -> Self {
|
||||
Hand {
|
||||
right: Default::default(),
|
||||
thumb: Default::default(),
|
||||
index: Default::default(),
|
||||
middle: Default::default(),
|
||||
ring: Default::default(),
|
||||
little: Default::default(),
|
||||
palm: Default::default(),
|
||||
wrist: Default::default(),
|
||||
elbow: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl InputDataTrait for Hand {
|
||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
let mut min_distance = f32::MAX;
|
||||
|
||||
for tip in [
|
||||
&self.base.thumb.tip.position,
|
||||
&self.base.index.tip.position,
|
||||
&self.base.middle.tip.position,
|
||||
&self.base.ring.tip.position,
|
||||
&self.base.little.tip.position,
|
||||
&self.thumb.tip.position,
|
||||
&self.index.tip.position,
|
||||
&self.middle.tip.position,
|
||||
&self.ring.tip.position,
|
||||
&self.little.tip.position,
|
||||
] {
|
||||
min_distance = min_distance.min(field.distance(space, vec3a(tip.x, tip.y, tip.z)));
|
||||
}
|
||||
|
||||
min_distance
|
||||
}
|
||||
fn serialize(
|
||||
&self,
|
||||
_distance_link: &DistanceLink,
|
||||
local_to_handler_matrix: Mat4,
|
||||
) -> InputDataType {
|
||||
let mut hand = self.base;
|
||||
fn transform(&mut self, method: &InputMethod, handler: &InputHandler) {
|
||||
let local_to_handler_matrix =
|
||||
Spatial::space_to_space_matrix(Some(&method.spatial), Some(&handler.spatial));
|
||||
let mut joints: Vec<&mut Joint> = Vec::new();
|
||||
|
||||
joints.extend([&mut hand.palm, &mut hand.wrist]);
|
||||
if let Some(elbow) = &mut hand.elbow {
|
||||
joints.extend([&mut self.palm, &mut self.wrist]);
|
||||
if let Some(elbow) = &mut self.elbow {
|
||||
joints.push(elbow);
|
||||
}
|
||||
for finger in [
|
||||
&mut hand.index,
|
||||
&mut hand.middle,
|
||||
&mut hand.ring,
|
||||
&mut hand.little,
|
||||
&mut self.index,
|
||||
&mut self.middle,
|
||||
&mut self.ring,
|
||||
&mut self.little,
|
||||
] {
|
||||
joints.extend([
|
||||
&mut finger.tip,
|
||||
@@ -53,21 +94,19 @@ impl InputSpecialization for Hand {
|
||||
]);
|
||||
}
|
||||
joints.extend([
|
||||
&mut hand.thumb.tip,
|
||||
&mut hand.thumb.distal,
|
||||
&mut hand.thumb.proximal,
|
||||
&mut hand.thumb.metacarpal,
|
||||
&mut self.thumb.tip,
|
||||
&mut self.thumb.distal,
|
||||
&mut self.thumb.proximal,
|
||||
&mut self.thumb.metacarpal,
|
||||
]);
|
||||
|
||||
for joint in joints {
|
||||
let joint_matrix =
|
||||
Mat4::from_rotation_translation(joint.rotation.into(), joint.position.into())
|
||||
* local_to_handler_matrix;
|
||||
let joint_matrix = local_to_handler_matrix
|
||||
* Mat4::from_rotation_translation(joint.rotation.into(), joint.position.into());
|
||||
let (_, rotation, position) = joint_matrix.to_scale_rotation_translation();
|
||||
joint.position = position.into();
|
||||
joint.rotation = rotation.into();
|
||||
joint.distance = handler.field.distance(&handler.spatial, position.into());
|
||||
}
|
||||
|
||||
InputDataType::Hand(Box::new(hand))
|
||||
}
|
||||
}
|
||||
|
||||
42
src/nodes/input/handler.rs
Normal file
42
src/nodes/input/handler.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use super::{InputHandlerAspect, INPUT_HANDLER_REGISTRY, INPUT_METHOD_REGISTRY};
|
||||
use crate::nodes::{alias::AliasList, fields::Field, spatial::Spatial, Aspect, Node};
|
||||
use color_eyre::eyre::Result;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct InputHandler {
|
||||
pub spatial: Arc<Spatial>,
|
||||
pub field: Arc<Field>,
|
||||
pub(super) method_aliases: AliasList,
|
||||
}
|
||||
impl InputHandler {
|
||||
pub fn add_to(node: &Arc<Node>, field: &Arc<Field>) -> Result<()> {
|
||||
let handler = InputHandler {
|
||||
spatial: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
field: field.clone(),
|
||||
method_aliases: AliasList::default(),
|
||||
};
|
||||
for method in INPUT_METHOD_REGISTRY.get_valid_contents() {
|
||||
method.handle_new_handler(&handler);
|
||||
}
|
||||
let handler = INPUT_HANDLER_REGISTRY.add(handler);
|
||||
node.add_aspect_raw(handler);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Aspect for InputHandler {
|
||||
const NAME: &'static str = "InputHandler";
|
||||
}
|
||||
impl InputHandlerAspect for InputHandler {}
|
||||
impl PartialEq for InputHandler {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.spatial == other.spatial
|
||||
}
|
||||
}
|
||||
impl Drop for InputHandler {
|
||||
fn drop(&mut self) {
|
||||
INPUT_HANDLER_REGISTRY.remove(self);
|
||||
for method in INPUT_METHOD_REGISTRY.get_valid_contents() {
|
||||
method.handle_drop_handler(self);
|
||||
}
|
||||
}
|
||||
}
|
||||
233
src/nodes/input/method.rs
Normal file
233
src/nodes/input/method.rs
Normal file
@@ -0,0 +1,233 @@
|
||||
use super::{
|
||||
input_method_client, InputData, InputDataTrait, InputDataType, InputHandler, InputMethodAspect,
|
||||
InputMethodRefAspect, INPUT_HANDLER_REGISTRY, INPUT_METHOD_REF_ASPECT_ALIAS_INFO,
|
||||
INPUT_METHOD_REGISTRY,
|
||||
};
|
||||
use crate::{
|
||||
core::{client::Client, registry::Registry},
|
||||
nodes::{
|
||||
alias::{Alias, AliasList},
|
||||
fields::{Field, FIELD_ALIAS_INFO},
|
||||
spatial::Spatial,
|
||||
Aspect, Node,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
use parking_lot::Mutex;
|
||||
use stardust_xr::values::Datamap;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
pub struct InputMethod {
|
||||
pub spatial: Arc<Spatial>,
|
||||
pub data: Mutex<InputDataType>,
|
||||
pub datamap: Mutex<Datamap>,
|
||||
|
||||
handler_aliases: AliasList,
|
||||
handler_field_aliases: AliasList,
|
||||
pub(super) handler_order: Mutex<Vec<Weak<InputHandler>>>,
|
||||
pub internal_capture_requests: Registry<InputHandler>,
|
||||
pub captures: Registry<InputHandler>,
|
||||
}
|
||||
impl InputMethod {
|
||||
pub fn add_to(
|
||||
node: &Arc<Node>,
|
||||
data: InputDataType,
|
||||
datamap: Datamap,
|
||||
) -> Result<Arc<InputMethod>> {
|
||||
let method = InputMethod {
|
||||
spatial: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
data: Mutex::new(data),
|
||||
datamap: Mutex::new(datamap),
|
||||
|
||||
handler_aliases: AliasList::default(),
|
||||
handler_field_aliases: AliasList::default(),
|
||||
handler_order: Mutex::new(Vec::new()),
|
||||
internal_capture_requests: Registry::new(),
|
||||
captures: Registry::new(),
|
||||
};
|
||||
<InputMethod as InputMethodRefAspect>::add_node_members(node);
|
||||
<InputMethod as InputMethodAspect>::add_node_members(node);
|
||||
for handler in INPUT_HANDLER_REGISTRY.get_valid_contents() {
|
||||
method.handle_new_handler(&handler);
|
||||
}
|
||||
let method = INPUT_METHOD_REGISTRY.add(method);
|
||||
node.add_aspect_raw(method.clone());
|
||||
Ok(method)
|
||||
}
|
||||
|
||||
pub fn distance(&self, to: &Field) -> f32 {
|
||||
self.data.lock().distance(&self.spatial, to)
|
||||
}
|
||||
|
||||
pub fn set_handler_order<'a>(&self, handlers: impl Iterator<Item = &'a Arc<InputHandler>>) {
|
||||
*self.handler_order.lock() = handlers.map(Arc::downgrade).collect();
|
||||
}
|
||||
|
||||
pub(super) fn make_alias(&self, handler: &InputHandler) {
|
||||
let Some(method_node) = self.spatial.node() else {
|
||||
return;
|
||||
};
|
||||
let Some(handler_node) = handler.spatial.node() else {
|
||||
return;
|
||||
};
|
||||
let Some(client) = handler_node.get_client() else {
|
||||
return;
|
||||
};
|
||||
let Ok(method_alias) = Alias::create(
|
||||
&method_node,
|
||||
&client,
|
||||
INPUT_METHOD_REF_ASPECT_ALIAS_INFO.clone(),
|
||||
Some(&handler.method_aliases),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
method_alias.set_enabled(false);
|
||||
}
|
||||
pub(super) fn handle_new_handler(&self, handler: &InputHandler) {
|
||||
self.make_alias(handler);
|
||||
|
||||
let Some(method_node) = self.spatial.node() else {
|
||||
return;
|
||||
};
|
||||
let Some(method_client) = method_node.get_client() else {
|
||||
return;
|
||||
};
|
||||
let Some(handler_node) = handler.spatial.node() else {
|
||||
return;
|
||||
};
|
||||
// Receiver itself
|
||||
let Ok(handler_alias) = Alias::create(
|
||||
&handler_node,
|
||||
&method_client,
|
||||
INPUT_METHOD_REF_ASPECT_ALIAS_INFO.clone(),
|
||||
Some(&self.handler_aliases),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(handler_field_node) = handler.field.spatial.node() else {
|
||||
return;
|
||||
};
|
||||
// Handler's field
|
||||
let Ok(rx_field_alias) = Alias::create(
|
||||
&handler_field_node,
|
||||
&method_client,
|
||||
FIELD_ALIAS_INFO.clone(),
|
||||
Some(&self.handler_field_aliases),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let _ = input_method_client::create_handler(&method_node, &handler_alias, &rx_field_alias);
|
||||
}
|
||||
pub(super) fn handle_drop_handler(&self, handler: &InputHandler) {
|
||||
let Some(tx_node) = self.spatial.node() else {
|
||||
return;
|
||||
};
|
||||
let Some(handler_alias) = self.handler_aliases.get_from_aspect(handler) else {
|
||||
return;
|
||||
};
|
||||
let _ = input_method_client::destroy_handler(&tx_node, handler_alias.id);
|
||||
self.handler_aliases.remove_aspect(handler);
|
||||
self.handler_field_aliases
|
||||
.remove_aspect(handler.field.as_ref());
|
||||
}
|
||||
|
||||
pub(super) fn serialize(&self, alias_id: u64, handler: &Arc<InputHandler>) -> InputData {
|
||||
let mut input = self.data.lock().clone();
|
||||
input.transform(self, handler);
|
||||
|
||||
InputData {
|
||||
id: alias_id,
|
||||
input,
|
||||
distance: self.distance(&handler.field),
|
||||
datamap: self.datamap.lock().clone(),
|
||||
order: self
|
||||
.handler_order
|
||||
.lock()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, h)| h.ptr_eq(&Arc::downgrade(handler)))
|
||||
.unwrap()
|
||||
.0 as u32,
|
||||
captured: self.captures.get_valid_contents().contains(handler),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Aspect for InputMethod {
|
||||
const NAME: &'static str = "InputMethod";
|
||||
}
|
||||
impl InputMethodRefAspect for InputMethod {
|
||||
#[doc = "Have the input handler that this method reference came from capture the method for the next frame."]
|
||||
fn request_capture(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
handler: Arc<Node>,
|
||||
) -> Result<()> {
|
||||
let input_method = node.get_aspect::<InputMethod>()?;
|
||||
let input_handler = handler.get_aspect::<InputHandler>()?;
|
||||
|
||||
input_method
|
||||
.internal_capture_requests
|
||||
.add_raw(&input_handler);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl InputMethodAspect for InputMethod {
|
||||
#[doc = "Set the spatial input component of this input method. You must keep the same input data type throughout the entire thing."]
|
||||
fn set_input(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
input: InputDataType,
|
||||
) -> Result<()> {
|
||||
let input_method = node.get_aspect::<InputMethod>()?;
|
||||
*input_method.data.lock() = input;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Set the datmap of this input method"]
|
||||
fn set_datamap(node: Arc<Node>, _calling_client: Arc<Client>, datamap: Datamap) -> Result<()> {
|
||||
let input_method = node.get_aspect::<InputMethod>()?;
|
||||
*input_method.datamap.lock() = datamap;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Manually set the order of handlers to propagate input to, or else let the server decide."]
|
||||
fn set_handler_order(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
handlers: Vec<Arc<Node>>,
|
||||
) -> Result<()> {
|
||||
let input_method = node.get_aspect::<InputMethod>()?;
|
||||
let handlers = handlers
|
||||
.into_iter()
|
||||
.filter_map(|p| p.get_aspect::<InputHandler>().ok())
|
||||
.map(|i| Arc::downgrade(&i))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
*input_method.handler_order.lock() = handlers;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Set which handlers are captured."]
|
||||
fn set_captures(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
handlers: Vec<Arc<Node>>,
|
||||
) -> Result<()> {
|
||||
let input_method = node.get_aspect::<InputMethod>()?;
|
||||
input_method.captures.clear();
|
||||
for handler in handlers {
|
||||
let Ok(handler) = handler.get_aspect::<InputHandler>() else {
|
||||
continue;
|
||||
};
|
||||
input_method.captures.add_raw(&handler);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for InputMethod {
|
||||
fn drop(&mut self) {
|
||||
INPUT_METHOD_REGISTRY.remove(self);
|
||||
}
|
||||
}
|
||||
@@ -1,278 +1,152 @@
|
||||
pub mod hand;
|
||||
pub mod pointer;
|
||||
pub mod tip;
|
||||
#![allow(clippy::needless_question_mark)]
|
||||
|
||||
use self::hand::Hand;
|
||||
use self::pointer::Pointer;
|
||||
use self::tip::Tip;
|
||||
mod hand;
|
||||
mod handler;
|
||||
mod method;
|
||||
mod pointer;
|
||||
mod tip;
|
||||
|
||||
pub use handler::*;
|
||||
pub use method::*;
|
||||
|
||||
use super::fields::Field;
|
||||
use super::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||
use super::Node;
|
||||
use crate::core::client::Client;
|
||||
use crate::core::eventloop::FRAME;
|
||||
use crate::core::registry::Registry;
|
||||
use crate::nodes::fields::find_field;
|
||||
use anyhow::{ensure, Result};
|
||||
use glam::Mat4;
|
||||
use nanoid::nanoid;
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flat::{Datamap, InputDataType};
|
||||
use stardust_xr::schemas::{flat::InputData, flex::deserialize};
|
||||
use stardust_xr::values::Transform;
|
||||
use std::ops::Deref;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::{Arc, Weak};
|
||||
use super::spatial::Spatial;
|
||||
use crate::create_interface;
|
||||
use crate::nodes::spatial::SPATIAL_ASPECT_ALIAS_INFO;
|
||||
use crate::nodes::spatial::SPATIAL_REF_ASPECT_ALIAS_INFO;
|
||||
use crate::{core::client::Client, nodes::Node};
|
||||
use crate::{core::registry::Registry, nodes::spatial::Transform};
|
||||
use color_eyre::eyre::Result;
|
||||
use stardust_xr::values::Datamap;
|
||||
use std::sync::Arc;
|
||||
|
||||
static INPUT_METHOD_REGISTRY: Registry<InputMethod> = Registry::new();
|
||||
static INPUT_HANDLER_REGISTRY: Registry<InputHandler> = Registry::new();
|
||||
pub static INPUT_HANDLER_REGISTRY: Registry<InputHandler> = Registry::new();
|
||||
|
||||
pub trait InputSpecialization: Send + Sync {
|
||||
stardust_xr_server_codegen::codegen_input_protocol!();
|
||||
|
||||
pub trait InputDataTrait {
|
||||
fn transform(&mut self, method: &InputMethod, handler: &InputHandler);
|
||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32;
|
||||
fn serialize(
|
||||
&self,
|
||||
distance_link: &DistanceLink,
|
||||
local_to_handler_matrix: Mat4,
|
||||
) -> InputDataType;
|
||||
}
|
||||
pub enum InputType {
|
||||
Pointer(Pointer),
|
||||
Hand(Box<Hand>),
|
||||
Tip(Tip),
|
||||
}
|
||||
impl Deref for InputType {
|
||||
type Target = dyn InputSpecialization;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
impl InputDataTrait for InputDataType {
|
||||
fn transform(&mut self, method: &InputMethod, handler: &InputHandler) {
|
||||
match self {
|
||||
InputType::Pointer(p) => p,
|
||||
InputType::Hand(h) => h.as_ref(),
|
||||
InputType::Tip(t) => t,
|
||||
InputDataType::Pointer(i) => i.transform(method, handler),
|
||||
InputDataType::Hand(i) => i.transform(method, handler),
|
||||
InputDataType::Tip(i) => i.transform(method, handler),
|
||||
}
|
||||
}
|
||||
|
||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
match self {
|
||||
InputDataType::Pointer(i) => i.distance(space, field),
|
||||
InputDataType::Hand(i) => i.distance(space, field),
|
||||
InputDataType::Tip(i) => i.distance(space, field),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InputMethod {
|
||||
pub uid: String,
|
||||
pub enabled: Mutex<bool>,
|
||||
pub spatial: Arc<Spatial>,
|
||||
pub specialization: Mutex<InputType>,
|
||||
pub captures: Registry<InputHandler>,
|
||||
pub datamap: Mutex<Option<Datamap>>,
|
||||
}
|
||||
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)]
|
||||
pub fn add_to(
|
||||
node: &Arc<Node>,
|
||||
specialization: InputType,
|
||||
datamap: Option<Datamap>,
|
||||
) -> Result<()> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
|
||||
node.add_local_signal("setDatamap", InputMethod::set_datamap);
|
||||
|
||||
let method = InputMethod {
|
||||
uid: node.uid.clone(),
|
||||
enabled: Mutex::new(true),
|
||||
spatial: node.spatial.get().unwrap().clone(),
|
||||
specialization: Mutex::new(specialization),
|
||||
captures: Registry::new(),
|
||||
datamap: Mutex::new(datamap),
|
||||
};
|
||||
let method = INPUT_METHOD_REGISTRY.add(method);
|
||||
let _ = node.input_method.set(method);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_datamap(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
node.input_method
|
||||
.get()
|
||||
.unwrap()
|
||||
.datamap
|
||||
.lock()
|
||||
.replace(Datamap::new(data.to_vec())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn distance(&self, to: &Field) -> f32 {
|
||||
self.specialization.lock().distance(&self.spatial, to)
|
||||
}
|
||||
}
|
||||
impl Drop for InputMethod {
|
||||
fn drop(&mut self) {
|
||||
INPUT_METHOD_REGISTRY.remove(self);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DistanceLink {
|
||||
pub distance: f32,
|
||||
pub method: Arc<InputMethod>,
|
||||
pub handler: Arc<InputHandler>,
|
||||
pub handler_field: Arc<Field>,
|
||||
}
|
||||
impl DistanceLink {
|
||||
fn from(method: Arc<InputMethod>, handler: Arc<InputHandler>) -> Option<Self> {
|
||||
let handler_field = handler.field.upgrade()?;
|
||||
Some(DistanceLink {
|
||||
distance: method.distance(&handler_field),
|
||||
method,
|
||||
handler,
|
||||
handler_field,
|
||||
})
|
||||
}
|
||||
|
||||
fn send_input(&self, frame: u64, datamap: Datamap) {
|
||||
self.handler.send_input(frame, self, datamap);
|
||||
}
|
||||
fn serialize(&self, datamap: Datamap) -> Vec<u8> {
|
||||
let input = self.method.specialization.lock().serialize(
|
||||
self,
|
||||
Spatial::space_to_space_matrix(Some(&self.method.spatial), Some(&self.handler.spatial)),
|
||||
);
|
||||
|
||||
let root = InputData {
|
||||
uid: self.method.uid.clone(),
|
||||
input,
|
||||
distance: self.distance,
|
||||
datamap,
|
||||
};
|
||||
root.serialize()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct InputHandler {
|
||||
node: Weak<Node>,
|
||||
spatial: Arc<Spatial>,
|
||||
pub field: Weak<Field>,
|
||||
}
|
||||
impl InputHandler {
|
||||
pub fn add_to(node: &Arc<Node>, field: &Arc<Field>) -> Result<()> {
|
||||
ensure!(
|
||||
node.spatial.get().is_some(),
|
||||
"Internal: Node does not have a spatial attached!"
|
||||
);
|
||||
|
||||
let handler = InputHandler {
|
||||
node: Arc::downgrade(node),
|
||||
spatial: node.spatial.get().unwrap().clone(),
|
||||
field: Arc::downgrade(field),
|
||||
};
|
||||
let handler = INPUT_HANDLER_REGISTRY.add(handler);
|
||||
let _ = node.input_handler.set(handler);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send_input(&self, frame: u64, distance_link: &DistanceLink, datamap: Datamap) {
|
||||
let data = distance_link.serialize(datamap);
|
||||
let node = self.node.upgrade().unwrap();
|
||||
let method = Arc::downgrade(&distance_link.method);
|
||||
let handler = Arc::downgrade(&distance_link.handler);
|
||||
|
||||
tokio::spawn(async move {
|
||||
let data = node.execute_remote_method("input", data).await;
|
||||
if frame == FRAME.load(Ordering::Relaxed) {
|
||||
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 {
|
||||
fn drop(&mut self) {
|
||||
INPUT_HANDLER_REGISTRY.remove(self);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_interface(client: &Arc<Client>) {
|
||||
let node = Node::create(client, "", "input", false);
|
||||
node.add_local_signal("createInputHandler", create_input_handler_flex);
|
||||
node.add_local_signal("createInputMethodTip", tip::create_tip_flex);
|
||||
node.add_to_scenegraph();
|
||||
}
|
||||
|
||||
pub fn create_input_handler_flex(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateInputHandlerInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
create_interface!(InputInterface);
|
||||
pub struct InputInterface;
|
||||
impl InterfaceAspect for InputInterface {
|
||||
#[doc = "Create an input method node"]
|
||||
fn create_input_method(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
field_path: &'a str,
|
||||
}
|
||||
let info: CreateInputHandlerInfo = deserialize(data)?;
|
||||
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)?;
|
||||
initial_data: InputDataType,
|
||||
datamap: Datamap,
|
||||
) -> Result<()> {
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = transform.to_mat4(true, true, true);
|
||||
|
||||
let node = Node::create(&calling_client, "/input/handler", info.name, true).add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(parent), transform)?;
|
||||
InputHandler::add_to(&node, &field)?;
|
||||
Ok(())
|
||||
let node = Node::from_id(&calling_client, id, true).add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
InputMethod::add_to(&node, initial_data, datamap)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Create an input handler node"]
|
||||
fn create_input_handler(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
field: Arc<Node>,
|
||||
) -> Result<()> {
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = transform.to_mat4(true, true, true);
|
||||
let field = field.get_aspect::<Field>()?;
|
||||
|
||||
let node = Node::from_id(&calling_client, id, true).add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
InputHandler::add_to(&node, &field)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug")]
|
||||
pub fn process_input() {
|
||||
for method in INPUT_METHOD_REGISTRY
|
||||
// Iterate over all valid input methods
|
||||
let methods = INPUT_METHOD_REGISTRY
|
||||
.get_valid_contents()
|
||||
.into_iter()
|
||||
.filter(|method| *method.enabled.lock())
|
||||
.filter(|method| method.datamap.lock().is_some())
|
||||
{
|
||||
let mut distance_links: Vec<DistanceLink> = INPUT_HANDLER_REGISTRY
|
||||
.get_valid_contents()
|
||||
.into_iter()
|
||||
.filter(|handler| handler.field.upgrade().is_some())
|
||||
.filter_map(|handler| DistanceLink::from(method.clone(), handler))
|
||||
.collect();
|
||||
distance_links.sort_unstable_by(|a, b| {
|
||||
a.distance
|
||||
.abs()
|
||||
.partial_cmp(&b.distance.abs())
|
||||
.unwrap()
|
||||
.reverse()
|
||||
.filter(|method| {
|
||||
let Some(node) = method.spatial.node() else {
|
||||
return false;
|
||||
};
|
||||
node.enabled()
|
||||
});
|
||||
|
||||
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;
|
||||
for handler in INPUT_HANDLER_REGISTRY.get_valid_contents() {
|
||||
for method_alias in handler.method_aliases.get_aliases() {
|
||||
method_alias.set_enabled(false);
|
||||
}
|
||||
method.captures.clear();
|
||||
|
||||
let Some(handler_node) = handler.spatial.node() else {
|
||||
continue;
|
||||
};
|
||||
if !handler_node.enabled() {
|
||||
continue;
|
||||
}
|
||||
if let Some(handler_field_node) = handler.field.spatial.node() {
|
||||
if !handler_field_node.enabled() {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let (methods, datas) = methods
|
||||
.clone()
|
||||
// filter out methods without the handler in their handler order
|
||||
.filter(|a| {
|
||||
a.handler_order
|
||||
.lock()
|
||||
.iter()
|
||||
.any(|h| h.ptr_eq(&Arc::downgrade(&handler)))
|
||||
})
|
||||
// filter out methods without the proper alias
|
||||
.filter_map(|m| {
|
||||
Some((
|
||||
handler
|
||||
.method_aliases
|
||||
.get_from_original_node(m.spatial.node.clone())?,
|
||||
m,
|
||||
))
|
||||
})
|
||||
// make sure the input method alias is enabled
|
||||
.inspect(|(a, _)| {
|
||||
a.set_enabled(true);
|
||||
})
|
||||
// serialize the data
|
||||
.map(|(a, m)| (a.clone(), m.serialize(a.get_id(), &handler)))
|
||||
.unzip::<_, _, Vec<_>, Vec<_>>();
|
||||
|
||||
let _ = input_handler_client::input(&handler_node, &methods, &datas);
|
||||
}
|
||||
for method in methods {
|
||||
method.internal_capture_requests.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,54 +1,52 @@
|
||||
use super::{DistanceLink, InputSpecialization};
|
||||
use crate::nodes::fields::{ray_march, Field, Ray, RayMarchResult};
|
||||
use crate::nodes::spatial::Spatial;
|
||||
use glam::{vec3, Mat4};
|
||||
use stardust_xr::schemas::flat::{InputDataType, Pointer as FlatPointer};
|
||||
use std::sync::Arc;
|
||||
use super::{InputDataTrait, InputHandler, InputMethod, Pointer};
|
||||
use crate::nodes::{
|
||||
fields::{Field, FieldTrait, Ray, RayMarchResult},
|
||||
spatial::Spatial,
|
||||
};
|
||||
use glam::{vec3, Mat4, Quat};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Pointer {}
|
||||
// impl Default for Pointer {
|
||||
// fn default() -> Self {
|
||||
// Pointer {
|
||||
// grab: Default::default(),
|
||||
// select: Default::default(),
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
impl Pointer {
|
||||
fn ray_march(&self, space: &Arc<Spatial>, field: &Field) -> RayMarchResult {
|
||||
ray_march(
|
||||
Ray {
|
||||
origin: vec3(0_f32, 0_f32, 0_f32),
|
||||
direction: vec3(0_f32, 0_f32, 1_f32),
|
||||
space: space.clone(),
|
||||
},
|
||||
field,
|
||||
)
|
||||
impl Default for Pointer {
|
||||
fn default() -> Self {
|
||||
Pointer {
|
||||
origin: [0.0; 3].into(),
|
||||
orientation: Quat::IDENTITY.into(),
|
||||
deepest_point: [0.0; 3].into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl InputSpecialization for Pointer {
|
||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
self.ray_march(space, field).distance
|
||||
}
|
||||
fn serialize(
|
||||
&self,
|
||||
distance_link: &DistanceLink,
|
||||
local_to_handler_matrix: Mat4,
|
||||
) -> InputDataType {
|
||||
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 ray_march = self.ray_march(
|
||||
&distance_link.method.spatial,
|
||||
&distance_link.handler.field.upgrade().unwrap(),
|
||||
);
|
||||
let deepest_point = (direction * ray_march.deepest_point_distance) + origin;
|
||||
|
||||
InputDataType::Pointer(FlatPointer {
|
||||
origin: origin.into(),
|
||||
orientation: orientation.into(),
|
||||
deepest_point: deepest_point.into(),
|
||||
impl Pointer {
|
||||
fn ray_march(&self, method_space: &Arc<Spatial>, field: &Field) -> RayMarchResult {
|
||||
field.ray_march(Ray {
|
||||
origin: vec3(0.0, 0.0, 0.0),
|
||||
direction: vec3(0.0, 0.0, -1.0),
|
||||
space: Spatial::new(
|
||||
Weak::new(),
|
||||
Some(method_space.clone()),
|
||||
Mat4::from_rotation_translation(self.orientation.into(), self.origin.into()),
|
||||
),
|
||||
})
|
||||
}
|
||||
}
|
||||
impl InputDataTrait for Pointer {
|
||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
let ray_info = self.ray_march(space, field);
|
||||
ray_info.min_distance
|
||||
}
|
||||
fn transform(&mut self, method: &InputMethod, handler: &InputHandler) {
|
||||
let local_to_handler_matrix =
|
||||
Mat4::from_rotation_translation(self.orientation.into(), self.origin.into())
|
||||
* Spatial::space_to_space_matrix(Some(&method.spatial), Some(&handler.spatial));
|
||||
let (_, orientation, origin) = local_to_handler_matrix.to_scale_rotation_translation();
|
||||
|
||||
let ray_march = self.ray_march(&method.spatial, &handler.field);
|
||||
let direction = local_to_handler_matrix
|
||||
.transform_vector3(vec3(0.0, 0.0, -1.0))
|
||||
.normalize();
|
||||
let deepest_point = (direction * ray_march.deepest_point_distance) + origin;
|
||||
|
||||
self.origin = origin.into();
|
||||
self.orientation = orientation.into();
|
||||
self.deepest_point = deepest_point.into();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,70 +1,29 @@
|
||||
use super::{DistanceLink, InputSpecialization};
|
||||
use crate::core::client::Client;
|
||||
use crate::nodes::fields::Field;
|
||||
use crate::nodes::input::{InputMethod, InputType};
|
||||
use crate::nodes::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||
use crate::nodes::Node;
|
||||
use anyhow::Result;
|
||||
use glam::{vec3a, Mat4};
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flat::{Datamap, InputDataType, Tip as FlatTip};
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use stardust_xr::values::Transform;
|
||||
use super::{InputDataTrait, InputHandler, InputMethod, Tip};
|
||||
use crate::nodes::{
|
||||
fields::{Field, FieldTrait},
|
||||
spatial::Spatial,
|
||||
};
|
||||
use glam::{Mat4, Quat};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Tip {
|
||||
pub radius: f32,
|
||||
}
|
||||
impl Tip {
|
||||
fn set_radius(node: &Node, _calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
if let InputType::Tip(tip) = &mut *node.input_method.get().unwrap().specialization.lock() {
|
||||
tip.radius = deserialize(data)?;
|
||||
impl Default for Tip {
|
||||
fn default() -> Self {
|
||||
Tip {
|
||||
origin: [0.0; 3].into(),
|
||||
orientation: Quat::IDENTITY.into(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl InputSpecialization for Tip {
|
||||
impl InputDataTrait for Tip {
|
||||
fn distance(&self, space: &Arc<Spatial>, field: &Field) -> f32 {
|
||||
field.distance(space, vec3a(0.0, 0.0, 0.0))
|
||||
field.distance(space, self.origin.into())
|
||||
}
|
||||
fn serialize(
|
||||
&self,
|
||||
_distance_link: &DistanceLink,
|
||||
local_to_handler_matrix: Mat4,
|
||||
) -> InputDataType {
|
||||
fn transform(&mut self, method: &InputMethod, handler: &InputHandler) {
|
||||
let local_to_handler_matrix =
|
||||
Spatial::space_to_space_matrix(Some(&method.spatial), Some(&handler.spatial))
|
||||
* Mat4::from_rotation_translation(self.orientation.into(), self.origin.into());
|
||||
let (_, orientation, origin) = local_to_handler_matrix.to_scale_rotation_translation();
|
||||
InputDataType::Tip(FlatTip {
|
||||
origin: origin.into(),
|
||||
orientation: orientation.into(),
|
||||
radius: self.radius,
|
||||
})
|
||||
self.origin = origin.into();
|
||||
self.orientation = orientation.into();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_tip_flex(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateTipInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
radius: f32,
|
||||
datamap: Option<Vec<u8>>,
|
||||
}
|
||||
let info: CreateTipInfo = deserialize(data)?;
|
||||
let node = Node::create(&calling_client, "/input/method/tip", 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)?;
|
||||
InputMethod::add_to(
|
||||
&node,
|
||||
InputType::Tip(Tip {
|
||||
radius: info.radius,
|
||||
}),
|
||||
info.datamap.and_then(|datamap| Datamap::new(datamap).ok()),
|
||||
)?;
|
||||
node.add_local_signal("setRadius", Tip::set_radius);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
231
src/nodes/items/camera.rs
Normal file
231
src/nodes/items/camera.rs
Normal file
@@ -0,0 +1,231 @@
|
||||
use super::{
|
||||
create_item_acceptor_flex, register_item_ui_flex, Item, ItemAcceptor, ItemInterface, ItemType,
|
||||
};
|
||||
use crate::nodes::items::ITEM_ACCEPTOR_ASPECT_ALIAS_INFO;
|
||||
use crate::nodes::items::ITEM_ASPECT_ALIAS_INFO;
|
||||
use crate::{
|
||||
core::{client::Client, registry::Registry, scenegraph::MethodResponseSender},
|
||||
create_interface,
|
||||
nodes::{
|
||||
drawable::{
|
||||
model::{MaterialWrapper, ModelPart},
|
||||
shaders::UNLIT_SHADER_BYTES,
|
||||
},
|
||||
items::TypeInfo,
|
||||
spatial::{Spatial, Transform},
|
||||
Message, Node,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::{bail, eyre, Result};
|
||||
use glam::Mat4;
|
||||
use lazy_static::lazy_static;
|
||||
use mint::{ColumnMatrix4, Vector2};
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
use std::sync::Arc;
|
||||
use stereokit_rust::{
|
||||
material::{Material, Transparency},
|
||||
shader::Shader,
|
||||
sk::MainThreadToken,
|
||||
system::Renderer,
|
||||
tex::{Tex, TexFormat, TexType},
|
||||
util::Color128,
|
||||
};
|
||||
use tracing::error;
|
||||
|
||||
pub struct TexWrapper(pub Tex);
|
||||
unsafe impl Send for TexWrapper {}
|
||||
unsafe impl Sync for TexWrapper {}
|
||||
|
||||
stardust_xr_server_codegen::codegen_item_camera_protocol!();
|
||||
lazy_static! {
|
||||
pub(super) static ref ITEM_TYPE_INFO_CAMERA: TypeInfo = TypeInfo {
|
||||
type_name: "camera",
|
||||
alias_info: CAMERA_ITEM_ASPECT_ALIAS_INFO.clone(),
|
||||
ui_node_id: INTERFACE_NODE_ID,
|
||||
ui: Default::default(),
|
||||
items: Registry::new(),
|
||||
acceptors: Registry::new(),
|
||||
new_acceptor_fn: |node, acceptor, acceptor_field| {
|
||||
let _ = camera_item_ui_client::create_acceptor(node, acceptor, acceptor_field);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
struct FrameInfo {
|
||||
proj_matrix: Mat4,
|
||||
px_size: Vector2<u32>,
|
||||
}
|
||||
|
||||
pub struct CameraItem {
|
||||
space: Arc<Spatial>,
|
||||
frame_info: Mutex<FrameInfo>,
|
||||
sk_tex: OnceCell<TexWrapper>,
|
||||
sk_mat: OnceCell<Arc<MaterialWrapper>>,
|
||||
applied_to: Registry<ModelPart>,
|
||||
apply_to: Registry<ModelPart>,
|
||||
}
|
||||
#[allow(unused)]
|
||||
impl CameraItem {
|
||||
pub fn add_to(node: &Arc<Node>, proj_matrix: Mat4, px_size: Vector2<u32>) {
|
||||
Item::add_to(
|
||||
node,
|
||||
&ITEM_TYPE_INFO_CAMERA,
|
||||
ItemType::Camera(CameraItem {
|
||||
space: node.get_aspect::<Spatial>().unwrap().clone(),
|
||||
frame_info: Mutex::new(FrameInfo {
|
||||
proj_matrix,
|
||||
px_size,
|
||||
}),
|
||||
sk_tex: OnceCell::new(),
|
||||
sk_mat: OnceCell::new(),
|
||||
applied_to: Registry::new(),
|
||||
apply_to: Registry::new(),
|
||||
}),
|
||||
);
|
||||
// <CameraItem as CameraItemAspect>::node_methods(node);
|
||||
}
|
||||
|
||||
fn frame_flex(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
_message: Message,
|
||||
response: MethodResponseSender,
|
||||
) {
|
||||
response.wrap_sync(move || {
|
||||
let ItemType::Camera(_camera) = &node.get_aspect::<Item>().unwrap().specialization
|
||||
else {
|
||||
return Err(eyre!("Wrong item type?"));
|
||||
};
|
||||
Ok(serialize(())?.into())
|
||||
});
|
||||
}
|
||||
|
||||
fn apply_preview_material_flex(
|
||||
node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
message: Message,
|
||||
) -> Result<()> {
|
||||
let ItemType::Camera(camera) = &node.get_aspect::<Item>().unwrap().specialization else {
|
||||
bail!("Wrong item type?")
|
||||
};
|
||||
let model_part_node =
|
||||
calling_client.get_node("Model part", deserialize(&message.data).unwrap())?;
|
||||
let model_part = model_part_node.get_aspect::<ModelPart>()?;
|
||||
camera.applied_to.add_raw(&model_part);
|
||||
camera.apply_to.add_raw(&model_part);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn send_ui_item_created(&self, node: &Node, item: &Arc<Node>) {
|
||||
let _ = camera_item_ui_client::create_item(node, item);
|
||||
}
|
||||
pub fn send_acceptor_item_created(&self, node: &Node, item: &Arc<Node>) {
|
||||
let _ = camera_item_acceptor_client::capture_item(node, item);
|
||||
}
|
||||
|
||||
pub fn update(&self, token: &MainThreadToken) {
|
||||
let frame_info = self.frame_info.lock();
|
||||
let sk_tex = self.sk_tex.get_or_init(|| {
|
||||
TexWrapper(Tex::gen_color(
|
||||
Color128::default(),
|
||||
frame_info.px_size.x as i32,
|
||||
frame_info.px_size.y as i32,
|
||||
TexType::Rendertarget,
|
||||
TexFormat::RGBA32Linear,
|
||||
))
|
||||
});
|
||||
let sk_mat = self
|
||||
.sk_mat
|
||||
.get_or_try_init(|| -> Result<Arc<MaterialWrapper>> {
|
||||
let shader = Shader::from_memory(UNLIT_SHADER_BYTES)?;
|
||||
let mut mat = Material::new(&shader, None);
|
||||
mat.get_all_param_info().set_texture("diffuse", &sk_tex.0);
|
||||
mat.transparency(Transparency::Blend);
|
||||
Ok(Arc::new(MaterialWrapper(mat)))
|
||||
});
|
||||
let Ok(sk_mat) = sk_mat else {
|
||||
error!("unable to make camera item stereokit texture");
|
||||
return;
|
||||
};
|
||||
for model_part in self.apply_to.take_valid_contents() {
|
||||
model_part.replace_material(sk_mat.clone())
|
||||
}
|
||||
|
||||
if !self.applied_to.is_empty() {
|
||||
Renderer::render_to(
|
||||
token,
|
||||
&sk_tex.0,
|
||||
self.space.global_transform(),
|
||||
frame_info.proj_matrix,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
impl CameraItemAspect for CameraItem {}
|
||||
|
||||
impl CameraItemAcceptorAspect for ItemAcceptor {
|
||||
fn capture_item(node: Arc<Node>, _calling_client: Arc<Client>, item: Arc<Node>) -> Result<()> {
|
||||
super::acceptor_capture_item_flex(node, item)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(token: &MainThreadToken) {
|
||||
for camera in ITEM_TYPE_INFO_CAMERA.items.get_valid_contents() {
|
||||
let ItemType::Camera(camera) = &camera.specialization else {
|
||||
continue;
|
||||
};
|
||||
camera.update(token);
|
||||
}
|
||||
}
|
||||
|
||||
create_interface!(ItemInterface);
|
||||
impl InterfaceAspect for ItemInterface {
|
||||
#[doc = "Create a camera item at a specific location"]
|
||||
fn create_camera_item(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
proj_matrix: ColumnMatrix4<f32>,
|
||||
px_size: Vector2<u32>,
|
||||
) -> Result<()> {
|
||||
let space = parent.get_aspect::<Spatial>()?;
|
||||
let transform = transform.to_mat4(true, true, false);
|
||||
|
||||
let node = Node::from_id(&calling_client, id, false).add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, None, transform * space.global_transform(), false);
|
||||
CameraItem::add_to(&node, proj_matrix.into(), px_size);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Register this client to manage camera items and create default 3D UI for them."]
|
||||
fn register_camera_item_ui(_node: Arc<Node>, calling_client: Arc<Client>) -> Result<()> {
|
||||
register_item_ui_flex(calling_client, &ITEM_TYPE_INFO_CAMERA)
|
||||
}
|
||||
|
||||
#[doc = "Create an item acceptor to allow temporary ownership of a given type of item. Creates a node at `/item/camera/acceptor/<name>`."]
|
||||
fn create_camera_item_acceptor(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
field: Arc<Node>,
|
||||
) -> Result<()> {
|
||||
create_item_acceptor_flex(
|
||||
calling_client,
|
||||
id,
|
||||
parent,
|
||||
transform,
|
||||
&ITEM_TYPE_INFO_CAMERA,
|
||||
field,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
use super::{Item, ItemSpecialization, ItemType, ITEM_TYPE_INFO_ENVIRONMENT};
|
||||
use crate::{
|
||||
core::client::{Client, INTERNAL_CLIENT},
|
||||
nodes::{
|
||||
spatial::{find_spatial_parent, parse_transform, Spatial},
|
||||
Node,
|
||||
},
|
||||
};
|
||||
use anyhow::{anyhow, Result};
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::{
|
||||
schemas::flex::{deserialize, serialize},
|
||||
values::Transform,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub struct EnvironmentItem {
|
||||
path: String,
|
||||
}
|
||||
impl EnvironmentItem {
|
||||
pub fn add_to(node: &Arc<Node>, path: String) {
|
||||
Item::add_to(
|
||||
node,
|
||||
&ITEM_TYPE_INFO_ENVIRONMENT,
|
||||
ItemType::Environment(EnvironmentItem { path }),
|
||||
);
|
||||
node.add_local_method("getPath", EnvironmentItem::get_path_flex);
|
||||
}
|
||||
|
||||
fn get_path_flex(node: &Node, _calling_client: Arc<Client>, _data: &[u8]) -> Result<Vec<u8>> {
|
||||
let path: Result<String> = match &node.item.get().unwrap().specialization {
|
||||
ItemType::Environment(env) => Ok(env.path.clone()),
|
||||
_ => Err(anyhow!("")),
|
||||
};
|
||||
Ok(flexbuffers::singleton(path?.as_str()))
|
||||
}
|
||||
}
|
||||
impl ItemSpecialization for EnvironmentItem {
|
||||
fn serialize_start_data(&self, id: &str) -> Vec<u8> {
|
||||
serialize((id, self.path.as_str())).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn create_environment_item_flex(
|
||||
_node: &Node,
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateEnvironmentItemInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
item_data: String,
|
||||
}
|
||||
let info: CreateEnvironmentItemInfo = deserialize(data)?;
|
||||
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 transform = parse_transform(info.transform, true, true, false)?;
|
||||
let node = node.add_to_scenegraph();
|
||||
Spatial::add_to(&node, None, transform * space.global_transform())?;
|
||||
EnvironmentItem::add_to(&node, info.item_data);
|
||||
node.item
|
||||
.get()
|
||||
.unwrap()
|
||||
.make_alias(&calling_client, &parent_name);
|
||||
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,100 +1,68 @@
|
||||
mod environment;
|
||||
pub mod camera;
|
||||
pub mod panel;
|
||||
|
||||
use self::environment::EnvironmentItem;
|
||||
use super::fields::Field;
|
||||
use super::spatial::{find_spatial_parent, parse_transform, Spatial};
|
||||
use super::{Alias, Node};
|
||||
use crate::core::client::{Client, INTERNAL_CLIENT};
|
||||
use crate::core::nodelist::LifeLinkedNodeList;
|
||||
use self::camera::CameraItem;
|
||||
use self::panel::PanelItemTrait;
|
||||
use super::alias::AliasList;
|
||||
use super::fields::{Field, FIELD_ALIAS_INFO};
|
||||
use super::spatial::Spatial;
|
||||
use super::{Alias, Aspect, Node};
|
||||
use crate::core::client::Client;
|
||||
use crate::core::registry::Registry;
|
||||
use crate::nodes::alias::AliasInfo;
|
||||
use crate::nodes::fields::find_field;
|
||||
use crate::wayland::panel_item::{register_panel_item_ui_flex, PanelItem};
|
||||
use anyhow::{anyhow, ensure, Result};
|
||||
use lazy_static::lazy_static;
|
||||
use nanoid::nanoid;
|
||||
use crate::nodes::spatial::Transform;
|
||||
use crate::nodes::spatial::SPATIAL_ASPECT_ALIAS_INFO;
|
||||
use color_eyre::eyre::{ensure, Result};
|
||||
use parking_lot::Mutex;
|
||||
use serde::Deserialize;
|
||||
use stardust_xr::schemas::flex::deserialize;
|
||||
use stardust_xr::values::Transform;
|
||||
|
||||
use std::ops::Deref;
|
||||
use std::hash::Hash;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
lazy_static! {
|
||||
static ref ITEM_ALIAS_LOCAL_SIGNALS: Vec<&'static str> = vec![
|
||||
"getTransform",
|
||||
"setTransform",
|
||||
"setSpatialParent",
|
||||
"setSpatialParentInPlace",
|
||||
"setZoneable",
|
||||
"release",
|
||||
];
|
||||
static ref ITEM_ALIAS_LOCAL_METHODS: Vec<&'static str> = vec!["captureInto"];
|
||||
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(),
|
||||
};
|
||||
}
|
||||
stardust_xr_server_codegen::codegen_item_protocol!();
|
||||
|
||||
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);
|
||||
}
|
||||
*item.captured_acceptor.lock() = Arc::downgrade(acceptor);
|
||||
acceptor.handle_capture(item);
|
||||
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>) {
|
||||
if let Some(acceptor) = item.captured_acceptor.lock().upgrade() {
|
||||
*item.captured_acceptor.lock() = Weak::default();
|
||||
fn release(item: &Item) {
|
||||
let mut captured_acceptor = item.captured_acceptor.lock();
|
||||
if let Some(acceptor) = captured_acceptor.upgrade().as_ref() {
|
||||
*captured_acceptor = Weak::default();
|
||||
acceptor.handle_release(item);
|
||||
if let Some(ui) = item.type_info.ui.lock().upgrade() {
|
||||
ui.handle_release(item);
|
||||
ui.handle_release_item(item, acceptor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TypeInfo {
|
||||
pub type_name: &'static str,
|
||||
pub aliased_local_signals: Vec<&'static str>,
|
||||
pub aliased_local_methods: Vec<&'static str>,
|
||||
pub aliased_remote_signals: Vec<&'static str>,
|
||||
pub aliased_remote_methods: Vec<&'static str>,
|
||||
pub alias_info: AliasInfo,
|
||||
pub ui_node_id: u64,
|
||||
pub ui: Mutex<Weak<ItemUI>>,
|
||||
pub items: Registry<Item>,
|
||||
pub acceptors: Registry<ItemAcceptor>,
|
||||
pub new_acceptor_fn: fn(node: &Node, acceptor: &Arc<Node>, acceptor_field: &Arc<Node>),
|
||||
}
|
||||
|
||||
fn capture_into_flex(node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
let acceptor_path = flexbuffers::Reader::get_root(data)?
|
||||
.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 Hash for TypeInfo {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.type_name.hash(state);
|
||||
}
|
||||
}
|
||||
impl PartialEq for TypeInfo {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.type_name == other.type_name
|
||||
}
|
||||
}
|
||||
impl Eq for TypeInfo {}
|
||||
|
||||
pub struct Item {
|
||||
node: Weak<Node>,
|
||||
uid: String,
|
||||
spatial: Arc<Spatial>,
|
||||
type_info: &'static TypeInfo,
|
||||
captured_acceptor: Mutex<Weak<ItemAcceptor>>,
|
||||
pub specialization: ItemType,
|
||||
@@ -105,81 +73,96 @@ impl Item {
|
||||
type_info: &'static TypeInfo,
|
||||
specialization: ItemType,
|
||||
) -> Arc<Self> {
|
||||
node.add_local_signal("captureInto", capture_into_flex);
|
||||
let item = Item {
|
||||
node: Arc::downgrade(node),
|
||||
uid: nanoid!(),
|
||||
spatial: node.aspects.get::<Spatial>().unwrap(),
|
||||
type_info,
|
||||
captured_acceptor: Default::default(),
|
||||
specialization,
|
||||
};
|
||||
let item = type_info.items.add(item);
|
||||
|
||||
<Item as ItemAspect>::add_node_members(node);
|
||||
if let Some(ui) = type_info.ui.lock().upgrade() {
|
||||
ui.handle_create_item(&item);
|
||||
}
|
||||
let _ = node.item.set(item.clone());
|
||||
node.add_aspect_raw(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
|
||||
}
|
||||
fn make_alias(&self, client: &Arc<Client>, parent: &str) -> (Arc<Node>, Arc<Alias>) {
|
||||
let node = Alias::new(
|
||||
fn make_alias(&self, client: &Arc<Client>, alias_list: &AliasList) -> Result<Arc<Node>> {
|
||||
Alias::create(
|
||||
&self.spatial.node().unwrap(),
|
||||
client,
|
||||
parent,
|
||||
&self.uid,
|
||||
&self.node.upgrade().unwrap(),
|
||||
AliasInfo {
|
||||
local_signals: [
|
||||
&self.type_info.aliased_local_signals,
|
||||
ITEM_ALIAS_LOCAL_SIGNALS.as_slice(),
|
||||
]
|
||||
.concat(),
|
||||
local_methods: [
|
||||
&self.type_info.aliased_local_methods,
|
||||
ITEM_ALIAS_LOCAL_METHODS.as_slice(),
|
||||
]
|
||||
.concat(),
|
||||
remote_signals: [
|
||||
&self.type_info.aliased_remote_signals,
|
||||
ITEM_ALIAS_REMOTE_SIGNALS.as_slice(),
|
||||
]
|
||||
.concat(),
|
||||
},
|
||||
);
|
||||
let alias = node.alias.get().unwrap().clone();
|
||||
(node, alias)
|
||||
self.type_info.alias_info.clone() + ITEM_ASPECT_ALIAS_INFO.clone(),
|
||||
Some(alias_list),
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Aspect for Item {
|
||||
const NAME: &'static str = "Item";
|
||||
}
|
||||
impl ItemAspect for Item {
|
||||
fn release(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<()> {
|
||||
let item = node.get_aspect::<Item>()?;
|
||||
release(&item);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for Item {
|
||||
fn drop(&mut self) {
|
||||
self.type_info.items.remove(self);
|
||||
release(self);
|
||||
if let Some(ui) = self.type_info.ui.lock().upgrade() {
|
||||
ui.handle_destroy_item(self);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ItemSpecialization {
|
||||
fn serialize_start_data(&self, id: &str) -> Vec<u8>;
|
||||
}
|
||||
|
||||
pub enum ItemType {
|
||||
Environment(EnvironmentItem),
|
||||
Panel(PanelItem),
|
||||
Camera(CameraItem),
|
||||
Panel(Arc<dyn PanelItemTrait>),
|
||||
}
|
||||
impl Deref for ItemType {
|
||||
type Target = dyn ItemSpecialization;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
impl ItemType {
|
||||
fn send_ui_item_created(&self, node: &Node, item: &Arc<Node>) {
|
||||
match self {
|
||||
ItemType::Environment(item) => item,
|
||||
ItemType::Panel(item) => item,
|
||||
ItemType::Camera(c) => c.send_ui_item_created(node, item),
|
||||
ItemType::Panel(p) => p.send_ui_item_created(node, item),
|
||||
}
|
||||
}
|
||||
fn send_acceptor_item_created(&self, node: &Node, item: &Arc<Node>) {
|
||||
match self {
|
||||
ItemType::Camera(c) => c.send_acceptor_item_created(node, item),
|
||||
ItemType::Panel(p) => p.send_acceptor_item_created(node, item),
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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 {
|
||||
node: Weak<Node>,
|
||||
type_info: &'static TypeInfo,
|
||||
aliases: LifeLinkedNodeList,
|
||||
item_aliases: AliasList,
|
||||
acceptor_aliases: AliasList,
|
||||
acceptor_field_aliases: AliasList,
|
||||
}
|
||||
impl ItemUI {
|
||||
fn add_to(node: &Arc<Node>, type_info: &'static TypeInfo) -> Result<()> {
|
||||
@@ -191,59 +174,118 @@ impl ItemUI {
|
||||
let ui = Arc::new(ItemUI {
|
||||
node: Arc::downgrade(node),
|
||||
type_info,
|
||||
aliases: Default::default(),
|
||||
item_aliases: AliasList::default(),
|
||||
acceptor_aliases: AliasList::default(),
|
||||
acceptor_field_aliases: AliasList::default(),
|
||||
});
|
||||
*type_info.ui.lock() = Arc::downgrade(&ui);
|
||||
let _ = node.item_ui.set(ui.clone());
|
||||
node.add_aspect_raw(ui.clone());
|
||||
|
||||
for item in type_info.items.get_valid_contents() {
|
||||
ui.handle_create_item(&item);
|
||||
}
|
||||
for acceptor in type_info.acceptors.get_valid_contents() {
|
||||
ui.handle_create_acceptor(&acceptor);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn send_state(&self, state: &str, name: &str) {
|
||||
let _ = self
|
||||
.node
|
||||
.upgrade()
|
||||
.unwrap()
|
||||
.send_remote_signal(state, flexbuffers::singleton(name).as_slice());
|
||||
}
|
||||
|
||||
fn handle_create_item(&self, item: &Item) {
|
||||
let node = self.node.upgrade().unwrap();
|
||||
if let Some(client) = node.get_client() {
|
||||
let (alias_node, _) =
|
||||
item.make_alias(&client, &(node.get_path().to_string() + "/item"));
|
||||
self.aliases.add(Arc::downgrade(&alias_node));
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(client) = node.get_client() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let _ = node.send_remote_signal(
|
||||
"create",
|
||||
&item.specialization.serialize_start_data(&item.uid),
|
||||
);
|
||||
}
|
||||
let Ok(item_alias) = item.make_alias(&client, &self.item_aliases) else {
|
||||
return;
|
||||
};
|
||||
|
||||
item.specialization.send_ui_item_created(&node, &item_alias);
|
||||
}
|
||||
fn handle_capture_item(&self, item: &Item, acceptor: &ItemAcceptor) {
|
||||
let Some(item_alias) = self.item_aliases.get_from_aspect(item) else {
|
||||
return;
|
||||
};
|
||||
let Some(acceptor_alias) = self.acceptor_aliases.get_from_aspect(acceptor) else {
|
||||
return;
|
||||
};
|
||||
let _ = item_ui_client::capture_item(
|
||||
&self.node.upgrade().unwrap(),
|
||||
item_alias.id,
|
||||
acceptor_alias.id,
|
||||
);
|
||||
}
|
||||
fn handle_release_item(&self, item: &Item, acceptor: &ItemAcceptor) {
|
||||
let Some(item_alias) = self.item_aliases.get_from_aspect(item) else {
|
||||
return;
|
||||
};
|
||||
let Some(acceptor_alias) = self.acceptor_aliases.get_from_aspect(acceptor) else {
|
||||
return;
|
||||
};
|
||||
let _ = item_ui_client::release_item(
|
||||
&self.node.upgrade().unwrap(),
|
||||
item_alias.id,
|
||||
acceptor_alias.id,
|
||||
);
|
||||
}
|
||||
fn handle_destroy_item(&self, item: &Item) {
|
||||
self.send_state("destroy", item.uid.as_str());
|
||||
}
|
||||
fn handle_capture(&self, item: &Item) {
|
||||
self.send_state("capture", item.uid.as_str());
|
||||
}
|
||||
fn handle_release(&self, item: &Item) {
|
||||
self.send_state("release", item.uid.as_str());
|
||||
let Some(item_alias) = self
|
||||
.item_aliases
|
||||
.get_from_original_node(item.spatial.node.clone())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let _ = item_ui_client::destroy_item(&self.node.upgrade().unwrap(), item_alias.id);
|
||||
self.item_aliases.remove_aspect(item);
|
||||
}
|
||||
fn handle_create_acceptor(&self, acceptor: &ItemAcceptor) {
|
||||
let node = self.node.upgrade().unwrap();
|
||||
if let Some(client) = node.get_client() {
|
||||
let aliases = acceptor.make_aliases(
|
||||
&client,
|
||||
&format!("/item/{}/acceptor", self.type_info.type_name),
|
||||
);
|
||||
aliases
|
||||
.iter()
|
||||
.for_each(|alias| self.aliases.add(Arc::downgrade(alias)));
|
||||
}
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(client) = node.get_client() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(acceptor_node) = acceptor.spatial.node() else {
|
||||
return;
|
||||
};
|
||||
let Ok(acceptor_alias) = Alias::create(
|
||||
&acceptor_node,
|
||||
&client,
|
||||
ITEM_ACCEPTOR_ASPECT_ALIAS_INFO.clone(),
|
||||
Some(&self.acceptor_aliases),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(acceptor_field_node) = acceptor.field.spatial.node() else {
|
||||
return;
|
||||
};
|
||||
let Ok(acceptor_field_alias) = Alias::create(
|
||||
&acceptor_field_node,
|
||||
&client,
|
||||
FIELD_ALIAS_INFO.clone(),
|
||||
Some(&self.acceptor_aliases),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
|
||||
(acceptor.type_info.new_acceptor_fn)(&node, &acceptor_alias, &acceptor_field_alias);
|
||||
}
|
||||
fn handle_destroy_acceptor(&self, _acceptor: &ItemAcceptor) {}
|
||||
fn handle_destroy_acceptor(&self, acceptor: &ItemAcceptor) {
|
||||
let acceptor_alias = self.acceptor_aliases.get_from_aspect(acceptor).unwrap();
|
||||
let _ = item_ui_client::destroy_acceptor(&self.node.upgrade().unwrap(), acceptor_alias.id);
|
||||
|
||||
self.acceptor_aliases
|
||||
.remove_aspect(acceptor.spatial.as_ref());
|
||||
self.acceptor_field_aliases
|
||||
.remove_aspect(acceptor.field.as_ref());
|
||||
}
|
||||
}
|
||||
impl Aspect for ItemUI {
|
||||
const NAME: &'static str = "Item";
|
||||
}
|
||||
impl Drop for ItemUI {
|
||||
fn drop(&mut self) {
|
||||
@@ -252,127 +294,103 @@ impl Drop for ItemUI {
|
||||
}
|
||||
|
||||
pub struct ItemAcceptor {
|
||||
node: Weak<Node>,
|
||||
type_info: &'static TypeInfo,
|
||||
field: Mutex<Weak<Field>>,
|
||||
accepted: Registry<Item>,
|
||||
spatial: Arc<Spatial>,
|
||||
pub type_info: &'static TypeInfo,
|
||||
field: Arc<Field>,
|
||||
accepted_aliases: AliasList,
|
||||
accepted_registry: Registry<Item>,
|
||||
}
|
||||
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 {
|
||||
node: Arc::downgrade(node),
|
||||
spatial: node.get_aspect::<Spatial>().unwrap(),
|
||||
type_info,
|
||||
field: Mutex::new(field),
|
||||
accepted: Registry::new(),
|
||||
field,
|
||||
accepted_aliases: AliasList::default(),
|
||||
accepted_registry: Registry::new(),
|
||||
});
|
||||
if let Some(ui) = type_info.ui.lock().upgrade() {
|
||||
ui.handle_create_acceptor(&acceptor);
|
||||
}
|
||||
let _ = node.item_acceptor.set(acceptor);
|
||||
node.add_aspect_raw(acceptor.clone());
|
||||
}
|
||||
fn make_aliases(&self, client: &Arc<Client>, parent: &str) -> Vec<Arc<Node>> {
|
||||
let mut aliases = Vec::new();
|
||||
let acceptor_node = &self.node.upgrade().unwrap();
|
||||
let acceptor_alias = Alias::new(
|
||||
client,
|
||||
parent,
|
||||
acceptor_node.uid.as_str(),
|
||||
acceptor_node,
|
||||
AliasInfo {
|
||||
local_signals: vec!["release"],
|
||||
..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);
|
||||
}
|
||||
aliases.push(acceptor_alias);
|
||||
aliases
|
||||
}
|
||||
fn send_event(&self, state: &str, name: &str) {
|
||||
let _ = self
|
||||
.node
|
||||
.upgrade()
|
||||
.unwrap()
|
||||
.send_remote_signal(state, flexbuffers::singleton(name).as_slice());
|
||||
}
|
||||
fn handle_capture(&self, item: &Arc<Item>) {
|
||||
self.accepted.add_raw(item);
|
||||
self.send_event("capture", item.uid.as_str());
|
||||
let Some(node) = self.spatial.node() else {
|
||||
return;
|
||||
};
|
||||
let Some(client) = node.get_client() else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.accepted_registry.add_raw(item);
|
||||
let Ok(alias_node) = item.make_alias(&client, &self.accepted_aliases) else {
|
||||
return;
|
||||
};
|
||||
|
||||
item.specialization
|
||||
.send_acceptor_item_created(&node, &alias_node);
|
||||
}
|
||||
fn handle_release(&self, item: &Item) {
|
||||
self.accepted.remove(item);
|
||||
self.send_event("release", item.uid.as_str());
|
||||
self.accepted_registry.remove(item);
|
||||
self.accepted_aliases.remove_aspect(item);
|
||||
|
||||
let Some(node) = self.spatial.node() else {
|
||||
return;
|
||||
};
|
||||
let alias = self.accepted_aliases.get_from_aspect(item).unwrap();
|
||||
let _ = item_acceptor_client::release_item(&node, alias.id);
|
||||
}
|
||||
}
|
||||
impl Aspect for ItemAcceptor {
|
||||
const NAME: &'static str = "ItemAcceptor";
|
||||
}
|
||||
impl ItemAcceptorAspect for ItemAcceptor {}
|
||||
impl Drop for ItemAcceptor {
|
||||
fn drop(&mut 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() {
|
||||
ui.handle_destroy_acceptor(self);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_interface(client: &Arc<Client>) {
|
||||
let node = Node::create(client, "", "item", false);
|
||||
node.add_local_signal(
|
||||
"createEnvironmentItem",
|
||||
environment::create_environment_item_flex,
|
||||
);
|
||||
node.add_local_signal(
|
||||
"registerEnvironmentItemUI",
|
||||
environment::register_environment_item_ui_flex,
|
||||
);
|
||||
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(
|
||||
calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
type_info: &'static TypeInfo,
|
||||
) -> Result<()> {
|
||||
#[derive(Deserialize)]
|
||||
struct CreateItemAcceptorInfo<'a> {
|
||||
name: &'a str,
|
||||
parent_path: &'a str,
|
||||
transform: Transform,
|
||||
field_path: &'a str,
|
||||
}
|
||||
let info: CreateItemAcceptorInfo = deserialize(data)?;
|
||||
let parent_name = format!("/item/{}/acceptor/", ITEM_TYPE_INFO_ENVIRONMENT.type_name);
|
||||
let space = 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(&INTERNAL_CLIENT, &parent_name, info.name, true).add_to_scenegraph();
|
||||
Spatial::add_to(&node, Some(space), transform)?;
|
||||
ItemAcceptor::add_to(&node, type_info, Arc::downgrade(&field));
|
||||
node.item
|
||||
.get()
|
||||
.unwrap()
|
||||
.make_alias(&calling_client, &parent_name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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();
|
||||
let ui = Node::from_id(&calling_client, type_info.ui_node_id, true).add_to_scenegraph()?;
|
||||
ItemUI::add_to(&ui, type_info)?;
|
||||
Ok(())
|
||||
}
|
||||
fn create_item_acceptor_flex(
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
type_info: &'static TypeInfo,
|
||||
field: Arc<Node>,
|
||||
) -> Result<()> {
|
||||
let space = parent.get_aspect::<Spatial>()?;
|
||||
let field = field.get_aspect::<Field>()?;
|
||||
let transform = transform.to_mat4(true, true, false);
|
||||
|
||||
let node = Node::from_id(&calling_client, id, true).add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(space.clone()), transform, false);
|
||||
ItemAcceptor::add_to(&node, type_info, field);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn acceptor_capture_item_flex(node: Arc<Node>, item: Arc<Node>) -> Result<()> {
|
||||
let acceptor = node.get_aspect::<ItemAcceptor>()?;
|
||||
let item = item.get_aspect::<Item>()?;
|
||||
capture(&item, &acceptor);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct ItemInterface;
|
||||
// create_interface!(ItemInterface);
|
||||
|
||||
463
src/nodes/items/panel.rs
Normal file
463
src/nodes/items/panel.rs
Normal file
@@ -0,0 +1,463 @@
|
||||
use super::{create_item_acceptor_flex, register_item_ui_flex, ItemAcceptor, ItemInterface};
|
||||
use crate::nodes::items::ITEM_ACCEPTOR_ASPECT_ALIAS_INFO;
|
||||
use crate::nodes::items::ITEM_ASPECT_ALIAS_INFO;
|
||||
use crate::{
|
||||
core::{
|
||||
client::{get_env, state, Client, INTERNAL_CLIENT},
|
||||
registry::Registry,
|
||||
},
|
||||
create_interface,
|
||||
nodes::{
|
||||
drawable::model::ModelPart,
|
||||
items::{Item, ItemType, TypeInfo},
|
||||
spatial::{Spatial, Transform},
|
||||
Node,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::Mat4;
|
||||
use lazy_static::lazy_static;
|
||||
use mint::Vector2;
|
||||
use std::sync::{Arc, Weak};
|
||||
use tracing::{debug, info};
|
||||
|
||||
stardust_xr_server_codegen::codegen_item_panel_protocol!();
|
||||
impl Default for Geometry {
|
||||
fn default() -> Self {
|
||||
Geometry {
|
||||
origin: [0, 0].into(),
|
||||
size: [0, 0].into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
pub static ref ITEM_TYPE_INFO_PANEL: TypeInfo = TypeInfo {
|
||||
type_name: "panel",
|
||||
alias_info: PANEL_ITEM_ASPECT_ALIAS_INFO.clone(),
|
||||
ui_node_id: INTERFACE_NODE_ID,
|
||||
ui: Default::default(),
|
||||
items: Registry::new(),
|
||||
acceptors: Registry::new(),
|
||||
new_acceptor_fn: |node, acceptor, acceptor_field| {
|
||||
let _ = panel_item_ui_client::create_acceptor(node, acceptor, acceptor_field);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub trait Backend: Send + Sync + 'static {
|
||||
fn start_data(&self) -> Result<PanelItemInitData>;
|
||||
|
||||
fn apply_cursor_material(&self, model_part: &Arc<ModelPart>);
|
||||
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: u64, 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_input(&self);
|
||||
}
|
||||
|
||||
pub fn panel_item_from_node(node: &Node) -> Option<Arc<dyn PanelItemTrait>> {
|
||||
let ItemType::Panel(panel_item) = &node.get_aspect::<Item>().ok()?.specialization else {
|
||||
return None;
|
||||
};
|
||||
Some(panel_item.clone())
|
||||
}
|
||||
|
||||
pub trait PanelItemTrait: Send + Sync + 'static {
|
||||
fn backend(&self) -> &dyn Backend;
|
||||
fn send_ui_item_created(&self, node: &Node, item: &Arc<Node>);
|
||||
fn send_acceptor_item_created(&self, node: &Node, item: &Arc<Node>);
|
||||
}
|
||||
|
||||
pub struct PanelItem<B: Backend> {
|
||||
pub node: Weak<Node>,
|
||||
pub backend: Box<B>,
|
||||
}
|
||||
impl<B: Backend> PanelItem<B> {
|
||||
pub fn create(backend: Box<B>, pid: Option<i32>) -> (Arc<Node>, 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 node = Arc::new(Node::generate(&INTERNAL_CLIENT, true));
|
||||
let spatial = Spatial::add_to(&node, None, Mat4::IDENTITY, false);
|
||||
if let Some(startup_settings) = &startup_settings {
|
||||
spatial.set_local_transform(startup_settings.root);
|
||||
}
|
||||
|
||||
let panel_item = Arc::new(PanelItem {
|
||||
node: Arc::downgrade(&node),
|
||||
backend,
|
||||
});
|
||||
|
||||
let generic_panel_item: Arc<dyn PanelItemTrait> = panel_item.clone();
|
||||
Item::add_to(
|
||||
&node,
|
||||
&ITEM_TYPE_INFO_PANEL,
|
||||
ItemType::Panel(generic_panel_item),
|
||||
);
|
||||
<Self as PanelItemAspect>::add_node_members(&node);
|
||||
|
||||
(node, panel_item)
|
||||
}
|
||||
}
|
||||
|
||||
// Remote signals
|
||||
#[allow(unused)]
|
||||
impl<B: Backend> PanelItem<B> {
|
||||
pub fn toplevel_parent_changed(&self, parent: u64) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
panel_item_client::toplevel_parent_changed(&node, parent);
|
||||
}
|
||||
pub fn toplevel_title_changed(&self, title: &str) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
panel_item_client::toplevel_title_changed(&node, title);
|
||||
}
|
||||
pub fn toplevel_app_id_changed(&self, app_id: &str) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
panel_item_client::toplevel_app_id_changed(&node, app_id);
|
||||
}
|
||||
pub fn toplevel_fullscreen_active(&self, active: bool) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
panel_item_client::toplevel_fullscreen_active(&node, active);
|
||||
}
|
||||
pub fn toplevel_move_request(&self) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
panel_item_client::toplevel_move_request(&node);
|
||||
}
|
||||
pub fn toplevel_resize_request(&self, up: bool, down: bool, left: bool, right: bool) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
panel_item_client::toplevel_resize_request(&node, up, down, left, right);
|
||||
}
|
||||
pub fn toplevel_size_changed(&self, size: Vector2<u32>) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
panel_item_client::toplevel_size_changed(&node, size);
|
||||
}
|
||||
|
||||
pub fn set_cursor(&self, geometry: Option<Geometry>) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
if let Some(geometry) = geometry {
|
||||
panel_item_client::set_cursor(&node, &geometry);
|
||||
} else {
|
||||
panel_item_client::hide_cursor(&node);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_child(&self, id: u64, info: &ChildInfo) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
panel_item_client::create_child(&node, id, info);
|
||||
}
|
||||
pub fn reposition_child(&self, id: u64, geometry: &Geometry) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
panel_item_client::reposition_child(&node, id, geometry);
|
||||
}
|
||||
pub fn destroy_child(&self, id: u64) {
|
||||
let Some(node) = self.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
panel_item_client::destroy_child(&node, id);
|
||||
}
|
||||
}
|
||||
|
||||
// make these stupid vectors u32 in the protocol somehow!!!!!!!1
|
||||
|
||||
#[allow(unused)]
|
||||
impl<B: Backend> PanelItemAspect for PanelItem<B> {
|
||||
#[doc = "Apply the cursor as a material to a model."]
|
||||
fn apply_cursor_material(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
model_part: Arc<Node>,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
let model_part = model_part.get_aspect::<ModelPart>()?;
|
||||
|
||||
panel_item.backend().apply_cursor_material(&model_part);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Apply a surface's visuals as a material to a model."]
|
||||
fn apply_surface_material(
|
||||
node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
surface: SurfaceId,
|
||||
model_part: Arc<Node>,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
let model_part = model_part.get_aspect::<ModelPart>()?;
|
||||
|
||||
panel_item
|
||||
.backend()
|
||||
.apply_surface_material(surface, &model_part);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Try to close the toplevel.\n \n The panel item UI handler or panel item acceptor will drop the panel item if this succeeds."]
|
||||
fn close_toplevel(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item.backend().close_toplevel();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Request a resize of the surface to whatever size the 2D app wants."]
|
||||
fn auto_size_toplevel(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item.backend().auto_size_toplevel();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Request a resize of the surface (in pixels)."]
|
||||
fn set_toplevel_size(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
size: mint::Vector2<u32>,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item.backend().set_toplevel_size(size);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Tell the toplevel to appear focused visually if true, or unfocused if false."]
|
||||
fn set_toplevel_focused_visuals(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
focused: bool,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item.backend().set_toplevel_focused_visuals(focused);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Send an event to set the pointer's position (in pixels, relative to top-left of surface). This will activate the pointer."]
|
||||
fn pointer_motion(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
surface: SurfaceId,
|
||||
position: mint::Vector2<f32>,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item.backend().pointer_motion(&surface, position);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Send an event to set a pointer button's state if the pointer's active. The `button` is from the `input_event_codes` crate (e.g. BTN_LEFT for left click)."]
|
||||
fn pointer_button(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
surface: SurfaceId,
|
||||
button: u32,
|
||||
pressed: bool,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item
|
||||
.backend()
|
||||
.pointer_button(&surface, button, pressed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Send an event to scroll the pointer if it's active.\nScroll distance is a value in pixels corresponding to the `distance` the surface should be scrolled.\nScroll steps is a value in columns/rows corresponding to the wheel clicks of a mouse or such. This also supports fractions of a wheel click."]
|
||||
fn pointer_scroll(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
surface: SurfaceId,
|
||||
scroll_distance: mint::Vector2<f32>,
|
||||
scroll_steps: mint::Vector2<f32>,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item
|
||||
.backend()
|
||||
.pointer_scroll(&surface, Some(scroll_distance), Some(scroll_steps));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Send an event to stop scrolling the pointer."]
|
||||
fn pointer_stop_scroll(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
surface: SurfaceId,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item.backend().pointer_scroll(&surface, None, None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Send a series of key presses and releases (positive keycode for pressed, negative for released)."]
|
||||
fn keyboard_keys(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
surface: SurfaceId,
|
||||
keymap_id: u64,
|
||||
keys: Vec<i32>,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item
|
||||
.backend()
|
||||
.keyboard_keys(&surface, keymap_id, keys);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Put a touch down on this surface with the unique ID `uid` at `position` (in pixels) from top left corner of the surface."]
|
||||
fn touch_down(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
surface: SurfaceId,
|
||||
uid: u32,
|
||||
position: mint::Vector2<f32>,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item.backend().touch_down(&surface, uid, position);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Move an existing touch point."]
|
||||
fn touch_move(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
uid: u32,
|
||||
position: mint::Vector2<f32>,
|
||||
) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item.backend().touch_move(uid, position);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Release a touch from its surface."]
|
||||
fn touch_up(node: Arc<Node>, _calling_client: Arc<Client>, uid: u32) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item.backend().touch_up(uid);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Reset all input, such as pressed keys and pointer clicks and touches. Useful for when it's newly captured into an item acceptor to make sure no input gets stuck."]
|
||||
fn reset_input(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<()> {
|
||||
let Some(panel_item) = panel_item_from_node(&node) else {
|
||||
return Ok(());
|
||||
};
|
||||
panel_item.backend().reset_input();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl PanelItemAcceptorAspect for ItemAcceptor {
|
||||
fn capture_item(node: Arc<Node>, _calling_client: Arc<Client>, item: Arc<Node>) -> Result<()> {
|
||||
super::acceptor_capture_item_flex(node, item)
|
||||
}
|
||||
}
|
||||
|
||||
impl<B: Backend> PanelItemTrait for PanelItem<B> {
|
||||
fn backend(&self) -> &dyn Backend {
|
||||
self.backend.as_ref()
|
||||
}
|
||||
fn send_ui_item_created(&self, node: &Node, item: &Arc<Node>) {
|
||||
let Ok(init_data) = self.backend.start_data() else {
|
||||
return;
|
||||
};
|
||||
let _ = panel_item_ui_client::create_item(node, item, init_data);
|
||||
}
|
||||
fn send_acceptor_item_created(&self, node: &Node, item: &Arc<Node>) {
|
||||
let Ok(init_data) = self.backend.start_data() else {
|
||||
return;
|
||||
};
|
||||
let _ = panel_item_acceptor_client::capture_item(node, item, init_data);
|
||||
}
|
||||
}
|
||||
impl<B: Backend> Drop for PanelItem<B> {
|
||||
fn drop(&mut self) {
|
||||
// Dropped panel item, basically just a debug breakpoint place
|
||||
info!("Dropped panel item");
|
||||
}
|
||||
}
|
||||
|
||||
create_interface!(ItemInterface);
|
||||
impl InterfaceAspect for ItemInterface {
|
||||
#[doc = "Register this client to manage the items of a certain type and create default 3D UI for them."]
|
||||
fn register_panel_item_ui(_node: Arc<Node>, calling_client: Arc<Client>) -> Result<()> {
|
||||
register_item_ui_flex(calling_client, &ITEM_TYPE_INFO_PANEL)
|
||||
}
|
||||
|
||||
#[doc = "Create an item acceptor to allow temporary ownership of a given type of item. Creates a node at `/item/<item_type>/acceptor/<name>`."]
|
||||
fn create_panel_item_acceptor(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
field: Arc<Node>,
|
||||
) -> Result<()> {
|
||||
create_item_acceptor_flex(
|
||||
calling_client,
|
||||
id,
|
||||
parent,
|
||||
transform,
|
||||
&ITEM_TYPE_INFO_PANEL,
|
||||
field,
|
||||
)
|
||||
}
|
||||
}
|
||||
440
src/nodes/mod.rs
440
src/nodes/mod.rs
@@ -1,247 +1,331 @@
|
||||
pub mod alias;
|
||||
pub mod audio;
|
||||
pub mod data;
|
||||
pub mod drawable;
|
||||
pub mod fields;
|
||||
pub mod hmd;
|
||||
pub mod input;
|
||||
pub mod items;
|
||||
pub mod root;
|
||||
pub mod spatial;
|
||||
pub mod startup;
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use nanoid::nanoid;
|
||||
use once_cell::sync::OnceCell;
|
||||
use self::alias::Alias;
|
||||
use crate::core::client::Client;
|
||||
use crate::core::registry::Registry;
|
||||
use crate::core::scenegraph::MethodResponseSender;
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use parking_lot::Mutex;
|
||||
use portable_atomic::{AtomicBool, Ordering};
|
||||
use rustc_hash::FxHashMap;
|
||||
use serde::{de::DeserializeOwned, Serialize};
|
||||
use spatial::Spatial;
|
||||
use stardust_xr::messenger::MessageSenderHandle;
|
||||
use stardust_xr::scenegraph::ScenegraphError;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
use std::any::{Any, TypeId};
|
||||
use std::fmt::Debug;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::vec::Vec;
|
||||
|
||||
use core::hash::BuildHasherDefault;
|
||||
use dashmap::DashMap;
|
||||
use rustc_hash::FxHasher;
|
||||
|
||||
use crate::core::client::Client;
|
||||
use crate::core::registry::Registry;
|
||||
|
||||
use self::alias::Alias;
|
||||
use self::data::{PulseReceiver, PulseSender};
|
||||
|
||||
use self::drawable::model::Model;
|
||||
use self::drawable::text::Text;
|
||||
use self::fields::Field;
|
||||
use self::input::{InputHandler, InputMethod};
|
||||
use self::items::{Item, ItemAcceptor, ItemUI};
|
||||
use self::spatial::Spatial;
|
||||
use self::startup::StartupSettings;
|
||||
|
||||
pub type Signal = fn(&Node, Arc<Client>, &[u8]) -> Result<()>;
|
||||
pub type Method = fn(&Node, Arc<Client>, &[u8]) -> Result<Vec<u8>>;
|
||||
|
||||
pub struct Node {
|
||||
pub(super) uid: String,
|
||||
path: String,
|
||||
// trailing_slash_pos: usize,
|
||||
local_signals: DashMap<String, Signal, BuildHasherDefault<FxHasher>>,
|
||||
local_methods: DashMap<String, Method, BuildHasherDefault<FxHasher>>,
|
||||
destroyable: AtomicBool,
|
||||
|
||||
pub alias: OnceCell<Arc<Alias>>,
|
||||
aliases: Registry<Alias>,
|
||||
|
||||
pub spatial: OnceCell<Arc<Spatial>>,
|
||||
pub field: OnceCell<Arc<Field>>,
|
||||
|
||||
// Data
|
||||
pub pulse_sender: OnceCell<Arc<PulseSender>>,
|
||||
pub pulse_receiver: OnceCell<Arc<PulseReceiver>>,
|
||||
|
||||
// Drawable
|
||||
pub model: OnceCell<Arc<Model>>,
|
||||
pub text: OnceCell<Arc<Text>>,
|
||||
|
||||
// Input
|
||||
pub input_method: OnceCell<Arc<InputMethod>>,
|
||||
pub input_handler: OnceCell<Arc<InputHandler>>,
|
||||
|
||||
// Item
|
||||
pub item: OnceCell<Arc<Item>>,
|
||||
pub item_acceptor: OnceCell<Arc<ItemAcceptor>>,
|
||||
pub item_ui: OnceCell<Arc<ItemUI>>,
|
||||
|
||||
// Startup
|
||||
pub startup_settings: OnceCell<Mutex<StartupSettings>>,
|
||||
|
||||
pub(crate) client: Weak<Client>,
|
||||
#[derive(Default)]
|
||||
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(Arc<Node>, Arc<Client>, Message) -> Result<()>;
|
||||
pub type Method = fn(Arc<Node>, Arc<Client>, Message, MethodResponseSender);
|
||||
|
||||
stardust_xr_server_codegen::codegen_node_protocol!();
|
||||
|
||||
pub struct OwnedNode(pub Arc<Node>);
|
||||
impl Drop for OwnedNode {
|
||||
fn drop(&mut self) {
|
||||
self.0.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Node {
|
||||
enabled: AtomicBool,
|
||||
id: u64,
|
||||
client: Weak<Client>,
|
||||
message_sender_handle: Option<MessageSenderHandle>,
|
||||
|
||||
local_signals: Mutex<FxHashMap<u64, Signal>>,
|
||||
local_methods: Mutex<FxHashMap<u64, Method>>,
|
||||
aliases: Registry<Alias>,
|
||||
aspects: Aspects,
|
||||
destroyable: bool,
|
||||
}
|
||||
impl Node {
|
||||
pub fn get_client(&self) -> Option<Arc<Client>> {
|
||||
self.client.upgrade()
|
||||
}
|
||||
// pub fn get_name(&self) -> &str {
|
||||
// &self.path[self.trailing_slash_pos + 1..]
|
||||
// }
|
||||
pub fn get_path(&self) -> &str {
|
||||
self.path.as_str()
|
||||
}
|
||||
pub fn is_destroyable(&self) -> bool {
|
||||
self.destroyable.load(Ordering::Relaxed)
|
||||
pub fn get_id(&self) -> u64 {
|
||||
self.id
|
||||
}
|
||||
|
||||
pub fn create(client: &Arc<Client>, parent: &str, name: &str, destroyable: bool) -> Self {
|
||||
let mut path = parent.to_string();
|
||||
path.push('/');
|
||||
path.push_str(name);
|
||||
pub fn generate(client: &Arc<Client>, destroyable: bool) -> Self {
|
||||
Self::from_id(client, client.generate_id(), destroyable)
|
||||
}
|
||||
pub fn from_id(client: &Arc<Client>, id: u64, destroyable: bool) -> Self {
|
||||
let node = Node {
|
||||
uid: nanoid!(),
|
||||
enabled: AtomicBool::new(true),
|
||||
client: Arc::downgrade(client),
|
||||
path,
|
||||
// trailing_slash_pos: parent.len(),
|
||||
message_sender_handle: client.message_sender_handle.clone(),
|
||||
id,
|
||||
local_signals: Default::default(),
|
||||
local_methods: Default::default(),
|
||||
destroyable: AtomicBool::from(destroyable),
|
||||
|
||||
alias: OnceCell::new(),
|
||||
aliases: Registry::new(),
|
||||
|
||||
spatial: OnceCell::new(),
|
||||
field: OnceCell::new(),
|
||||
pulse_sender: OnceCell::new(),
|
||||
pulse_receiver: OnceCell::new(),
|
||||
model: OnceCell::new(),
|
||||
text: OnceCell::new(),
|
||||
input_method: OnceCell::new(),
|
||||
input_handler: OnceCell::new(),
|
||||
item: OnceCell::new(),
|
||||
item_acceptor: OnceCell::new(),
|
||||
item_ui: OnceCell::new(),
|
||||
startup_settings: OnceCell::new(),
|
||||
aliases: Default::default(),
|
||||
aspects: Default::default(),
|
||||
destroyable,
|
||||
};
|
||||
node.add_local_signal("destroy", Node::destroy_flex);
|
||||
<Node as OwnedAspect>::add_node_members(&node);
|
||||
node
|
||||
}
|
||||
pub fn add_to_scenegraph(self) -> Arc<Node> {
|
||||
self.get_client().unwrap().scenegraph.add_node(self)
|
||||
pub fn add_to_scenegraph(self) -> Result<Arc<Node>> {
|
||||
Ok(self
|
||||
.get_client()
|
||||
.ok_or_else(|| eyre!("Internal: Unable to get client"))?
|
||||
.scenegraph
|
||||
.add_node(self))
|
||||
}
|
||||
pub fn add_to_scenegraph_owned(self) -> Result<OwnedNode> {
|
||||
Ok(OwnedNode(
|
||||
self.get_client()
|
||||
.ok_or_else(|| eyre!("Internal: Unable to get client"))?
|
||||
.scenegraph
|
||||
.add_node(self),
|
||||
))
|
||||
}
|
||||
pub fn enabled(&self) -> bool {
|
||||
self.enabled.load(Ordering::Relaxed)
|
||||
&& if let Ok(spatial) = self.get_aspect::<Spatial>() {
|
||||
spatial
|
||||
.global_transform()
|
||||
.to_scale_rotation_translation()
|
||||
.0
|
||||
.length_squared() > 0.0
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
pub fn set_enabled(&self, enabled: bool) {
|
||||
self.enabled.store(enabled, Ordering::Relaxed)
|
||||
}
|
||||
pub fn destroy(&self) {
|
||||
let _ = self
|
||||
.get_client()
|
||||
.map(|c| c.scenegraph.remove_node(self.get_path()));
|
||||
}
|
||||
|
||||
pub fn destroy_flex(node: &Node, _calling_client: Arc<Client>, _data: &[u8]) -> Result<()> {
|
||||
if node.is_destroyable() {
|
||||
node.destroy();
|
||||
if let Some(client) = self.get_client() {
|
||||
client.scenegraph.remove_node(self.get_id());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn add_local_signal(&self, name: &str, signal: Signal) {
|
||||
self.local_signals.insert(name.to_string(), signal);
|
||||
// very much up for debate if we should allow this, as you can match objects using this
|
||||
// pub fn get_client_pid_flex(
|
||||
// node: Arc<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 add_local_signal(&self, id: u64, signal: Signal) {
|
||||
self.local_signals.lock().insert(id, signal);
|
||||
}
|
||||
pub fn add_local_method(&self, name: &str, method: Method) {
|
||||
self.local_methods.insert(name.to_string(), method);
|
||||
pub fn add_local_method(&self, id: u64, method: Method) {
|
||||
self.local_methods.lock().insert(id, method);
|
||||
}
|
||||
|
||||
pub fn get_aspect<F, T>(
|
||||
&self,
|
||||
node_name: &'static str,
|
||||
aspect_type: &'static str,
|
||||
aspect_fn: F,
|
||||
) -> Result<Arc<T>>
|
||||
where
|
||||
F: FnOnce(&Node) -> &OnceCell<Arc<T>>,
|
||||
{
|
||||
aspect_fn(self)
|
||||
.get()
|
||||
.ok_or_else(|| anyhow!("{} is not a {} node", node_name, aspect_type))
|
||||
.cloned()
|
||||
pub fn add_aspect<A: Aspect>(&self, aspect: A) -> Arc<A> {
|
||||
self.aspects.add(aspect)
|
||||
}
|
||||
pub fn add_aspect_raw<A: Aspect>(&self, aspect: Arc<A>) {
|
||||
self.aspects.add_raw(aspect)
|
||||
}
|
||||
pub fn get_aspect<A: Aspect>(&self) -> Result<Arc<A>> {
|
||||
self.aspects.get()
|
||||
}
|
||||
|
||||
pub fn send_local_signal(
|
||||
&self,
|
||||
self: Arc<Self>,
|
||||
calling_client: Arc<Client>,
|
||||
method: &str,
|
||||
data: &[u8],
|
||||
method: u64,
|
||||
message: Message,
|
||||
) -> Result<(), ScenegraphError> {
|
||||
if let Some(alias) = self.alias.get() {
|
||||
if !alias.info.local_signals.iter().any(|e| e == &method) {
|
||||
if let Ok(alias) = self.get_aspect::<Alias>() {
|
||||
if !alias.info.server_signals.iter().any(|e| *e == method) {
|
||||
return Err(ScenegraphError::SignalNotFound);
|
||||
}
|
||||
alias
|
||||
.original
|
||||
.upgrade()
|
||||
.ok_or(ScenegraphError::BrokenAlias)?
|
||||
.send_local_signal(calling_client, method, data)
|
||||
.send_local_signal(calling_client, method, message)
|
||||
} else {
|
||||
let signal = self
|
||||
.local_signals
|
||||
.get(method)
|
||||
.lock()
|
||||
.get(&method)
|
||||
.cloned()
|
||||
.ok_or(ScenegraphError::SignalNotFound)?;
|
||||
signal(self, calling_client, data)
|
||||
.map_err(|error| ScenegraphError::SignalError { error })
|
||||
signal(self, calling_client, message).map_err(|error| ScenegraphError::SignalError {
|
||||
error: error.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
pub fn execute_local_method(
|
||||
&self,
|
||||
self: Arc<Self>,
|
||||
calling_client: Arc<Client>,
|
||||
method: &str,
|
||||
data: &[u8],
|
||||
) -> Result<Vec<u8>, ScenegraphError> {
|
||||
if let Some(alias) = self.alias.get() {
|
||||
if !alias.info.local_methods.iter().any(|e| e == &method) {
|
||||
return Err(ScenegraphError::MethodNotFound);
|
||||
method: u64,
|
||||
message: Message,
|
||||
response: MethodResponseSender,
|
||||
) {
|
||||
if let Ok(alias) = self.get_aspect::<Alias>() {
|
||||
if !alias.info.server_methods.iter().any(|e| *e == method) {
|
||||
response.send(Err(ScenegraphError::MethodNotFound));
|
||||
return;
|
||||
}
|
||||
alias
|
||||
.original
|
||||
.upgrade()
|
||||
.ok_or(ScenegraphError::BrokenAlias)?
|
||||
.execute_local_method(calling_client, method, data)
|
||||
let Some(alias) = alias.original.upgrade() else {
|
||||
response.send(Err(ScenegraphError::BrokenAlias));
|
||||
return;
|
||||
};
|
||||
alias.execute_local_method(
|
||||
calling_client,
|
||||
method,
|
||||
Message {
|
||||
data: message.data.clone(),
|
||||
fds: Vec::new(),
|
||||
},
|
||||
response,
|
||||
)
|
||||
} else {
|
||||
let method = self
|
||||
.local_methods
|
||||
.get(method)
|
||||
.ok_or(ScenegraphError::MethodNotFound)?;
|
||||
method(self, calling_client, data)
|
||||
.map_err(|error| ScenegraphError::MethodError { error })
|
||||
let Some(method) = self.local_methods.lock().get(&method).cloned() else {
|
||||
response.send(Err(ScenegraphError::MethodNotFound));
|
||||
return;
|
||||
};
|
||||
method(self, calling_client, message, response);
|
||||
}
|
||||
}
|
||||
pub fn send_remote_signal(&self, method: &str, data: &[u8]) -> Result<()> {
|
||||
pub fn send_remote_signal(&self, method: u64, message: impl Into<Message>) -> Result<()> {
|
||||
let message = message.into();
|
||||
self.aliases
|
||||
.get_valid_contents()
|
||||
.iter()
|
||||
.filter(|alias| alias.info.remote_signals.iter().any(|e| e == &method))
|
||||
.for_each(|alias| {
|
||||
let _ = alias
|
||||
.node
|
||||
.upgrade()
|
||||
.unwrap()
|
||||
.send_remote_signal(method, data);
|
||||
.filter(|alias| alias.info.client_signals.iter().any(|e| e == &method))
|
||||
.filter_map(|alias| alias.node.upgrade())
|
||||
.for_each(|node| {
|
||||
// Beware! file descriptors will not be sent to aliases!!!
|
||||
let _ = node.send_remote_signal(
|
||||
method,
|
||||
Message {
|
||||
data: message.data.clone(),
|
||||
fds: Vec::new(),
|
||||
},
|
||||
);
|
||||
});
|
||||
let path = self.path.clone();
|
||||
let method = method.to_string();
|
||||
let data = data.to_vec();
|
||||
if let Some(client) = self.get_client() {
|
||||
if let Some(messenger) = client.messenger.as_ref() {
|
||||
messenger.send_remote_signal(path.as_str(), method.as_str(), data.as_slice());
|
||||
}
|
||||
if let Some(handle) = self.message_sender_handle.as_ref() {
|
||||
handle.signal(self.id, method, &message.data, message.fds)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub async fn execute_remote_method(&self, method: &str, data: Vec<u8>) -> Result<Vec<u8>> {
|
||||
if let Some(client) = self.get_client() {
|
||||
match client.messenger.as_ref() {
|
||||
None => Err(anyhow!("Messenger does not exist for this node's client")),
|
||||
Some(messenger) => {
|
||||
messenger
|
||||
.execute_remote_method(self.path.as_str(), method, &data)
|
||||
.await
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Err(anyhow!("Client does not exist somehow?"))
|
||||
}
|
||||
pub async fn execute_remote_method_typed<S: Serialize, D: DeserializeOwned>(
|
||||
&self,
|
||||
method: u64,
|
||||
input: S,
|
||||
fds: Vec<OwnedFd>,
|
||||
) -> Result<(D, Vec<OwnedFd>)> {
|
||||
let message_sender_handle = self
|
||||
.message_sender_handle
|
||||
.as_ref()
|
||||
.ok_or(eyre!("Messenger does not exist for this node"))?;
|
||||
|
||||
let serialized = serialize(input)?;
|
||||
let result = message_sender_handle
|
||||
.method(self.id, method, &serialized, fds)?
|
||||
.await
|
||||
.map_err(|e| eyre!(e))?;
|
||||
|
||||
let (message, fds) = result.into_components();
|
||||
let deserialized: D = deserialize(&message)?;
|
||||
Ok((deserialized, fds))
|
||||
}
|
||||
}
|
||||
impl Debug for Node {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Node")
|
||||
.field("id", &self.id)
|
||||
.field("local_signals", &self.local_signals.lock().keys())
|
||||
.field("local_methods", &self.local_methods.lock().keys())
|
||||
.field("destroyable", &self.destroyable)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
impl OwnedAspect for Node {
|
||||
fn set_enabled(node: Arc<Node>, _calling_client: Arc<Client>, enabled: bool) -> Result<()> {
|
||||
node.set_enabled(enabled);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn destroy(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<()> {
|
||||
if node.destroyable {
|
||||
node.destroy();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for Node {
|
||||
fn drop(&mut self) {
|
||||
// Debug breakpoint
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Aspect: Any + Send + Sync + 'static {
|
||||
const NAME: &'static str;
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Aspects(Mutex<FxHashMap<TypeId, Arc<dyn Any + Send + Sync + 'static>>>);
|
||||
|
||||
impl Aspects {
|
||||
fn add<A: Aspect>(&self, t: A) -> Arc<A> {
|
||||
let aspect = Arc::new(t);
|
||||
self.add_raw(aspect.clone());
|
||||
aspect
|
||||
}
|
||||
fn add_raw<A: Aspect>(&self, aspect: Arc<A>) {
|
||||
self.0.lock().insert(Self::type_key::<A>(), aspect);
|
||||
}
|
||||
fn get<A: Aspect>(&self) -> Result<Arc<A>> {
|
||||
self.0
|
||||
.lock()
|
||||
.get(&Self::type_key::<A>())
|
||||
.and_then(|a| Arc::downcast(a.clone()).ok())
|
||||
.ok_or(eyre!("Couldn't get aspect {}", A::NAME.to_lowercase()))
|
||||
}
|
||||
|
||||
fn type_key<A: 'static>() -> TypeId {
|
||||
TypeId::of::<A>()
|
||||
}
|
||||
}
|
||||
impl Drop for Aspects {
|
||||
fn drop(&mut self) {
|
||||
self.0.lock().clear()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,79 +1,102 @@
|
||||
use super::spatial::Spatial;
|
||||
use super::startup::DESKTOP_STARTUP_IDS;
|
||||
use super::Node;
|
||||
use crate::core::client::Client;
|
||||
use crate::core::client_state::ClientStateParsed;
|
||||
use crate::core::registry::Registry;
|
||||
use anyhow::{anyhow, Result};
|
||||
use crate::nodes::spatial::SPATIAL_REF_ASPECT_ALIAS_INFO;
|
||||
use crate::session::connection_env;
|
||||
use color_eyre::eyre::{bail, Result};
|
||||
use glam::Mat4;
|
||||
use stardust_xr::schemas::flex::{deserialize, serialize};
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Instant;
|
||||
use tracing::info;
|
||||
|
||||
static ROOT_REGISTRY: Registry<Root> = Registry::new();
|
||||
|
||||
stardust_xr_server_codegen::codegen_root_protocol!();
|
||||
|
||||
pub struct Root {
|
||||
node: Arc<Node>,
|
||||
logic_step: AtomicBool,
|
||||
connect_instant: Instant,
|
||||
}
|
||||
impl Root {
|
||||
pub fn create(client: &Arc<Client>) -> Arc<Self> {
|
||||
let node = Node::create(client, "", "", false);
|
||||
node.add_local_signal("applyDesktopStartupID", Root::apply_desktop_startup_id);
|
||||
node.add_local_signal("subscribeLogicStep", Root::subscribe_logic_step);
|
||||
node.add_local_signal("setBasePrefixes", Root::set_base_prefixes);
|
||||
let node = node.add_to_scenegraph();
|
||||
let _ = Spatial::add_to(&node, None, Mat4::IDENTITY);
|
||||
pub fn create(client: &Arc<Client>, transform: Mat4) -> Result<Arc<Self>> {
|
||||
let node = Node::from_id(client, 0, false);
|
||||
<Self as RootAspect>::add_node_members(&node);
|
||||
let node = node.add_to_scenegraph()?;
|
||||
let _ = Spatial::add_to(&node, None, transform, false);
|
||||
|
||||
ROOT_REGISTRY.add(Root {
|
||||
Ok(ROOT_REGISTRY.add(Root {
|
||||
node,
|
||||
logic_step: AtomicBool::from(false),
|
||||
})
|
||||
connect_instant: Instant::now(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn apply_desktop_startup_id(
|
||||
node: &Node,
|
||||
_calling_client: Arc<Client>,
|
||||
data: &[u8],
|
||||
) -> 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
|
||||
.root
|
||||
.get()
|
||||
.unwrap()
|
||||
.logic_step
|
||||
.store(true, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn logic_step(delta: f64) {
|
||||
if let Ok(data) = serialize((delta, 0.0)) {
|
||||
for root in ROOT_REGISTRY.get_valid_contents() {
|
||||
if root.logic_step.load(Ordering::Relaxed) {
|
||||
let _ = root.node.send_remote_signal("logicStep", &data);
|
||||
}
|
||||
}
|
||||
pub fn send_frame_events(delta: f64) {
|
||||
for root in ROOT_REGISTRY.get_valid_contents() {
|
||||
let _ = root_client::frame(
|
||||
&root.node,
|
||||
&FrameInfo {
|
||||
delta: delta as f32,
|
||||
elapsed: root.connect_instant.elapsed().as_secs_f32(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_base_prefixes(_node: &Node, calling_client: Arc<Client>, data: &[u8]) -> Result<()> {
|
||||
*calling_client.base_resource_prefixes.lock() = deserialize(data)?;
|
||||
pub fn set_transform(&self, transform: Mat4) {
|
||||
let spatial = self.node.get_aspect::<Spatial>().unwrap();
|
||||
spatial.set_spatial_parent(None).unwrap();
|
||||
spatial.set_local_transform(transform);
|
||||
}
|
||||
pub async fn save_state(&self) -> Result<ClientState> {
|
||||
Ok(root_client::save_state(&self.node).await?.0)
|
||||
}
|
||||
}
|
||||
impl RootAspect for Root {
|
||||
async fn get_state(_node: Arc<Node>, calling_client: Arc<Client>) -> Result<ClientState> {
|
||||
let Some(state) = calling_client.state.get() else {
|
||||
bail!("Couldn't get state");
|
||||
};
|
||||
Ok(state.clone())
|
||||
}
|
||||
|
||||
#[doc = "Get a hashmap of all the environment variables to connect a given app to the stardust server"]
|
||||
async fn get_connection_environment(
|
||||
_node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
) -> Result<stardust_xr::values::Map<String, String>> {
|
||||
Ok(connection_env())
|
||||
}
|
||||
|
||||
#[doc = "Generate a client state token and return it back.\n\n When launching a new client, set the environment variable `STARDUST_STARTUP_TOKEN` to the returned string.\n Make sure the environment variable shows in `/proc/{pid}/environ` as that's the only reliable way to pass the value to the server (suggestions welcome).\n"]
|
||||
async fn generate_state_token(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
state: ClientState,
|
||||
) -> Result<String> {
|
||||
Ok(ClientStateParsed::from_deserialized(&calling_client, state).token())
|
||||
}
|
||||
|
||||
#[doc = "Set initial list of folders to look for namespaced resources in"]
|
||||
fn set_base_prefixes(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
prefixes: Vec<String>,
|
||||
) -> Result<()> {
|
||||
info!(?calling_client, ?prefixes, "Set base prefixes");
|
||||
*calling_client.base_resource_prefixes.lock() =
|
||||
prefixes.into_iter().map(PathBuf::from).collect();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[doc = "Cleanly disconnect from the server"]
|
||||
fn disconnect(_node: Arc<Node>, calling_client: Arc<Client>) -> color_eyre::eyre::Result<()> {
|
||||
calling_client.disconnect(Ok(()));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Root {
|
||||
fn drop(&mut self) {
|
||||
ROOT_REGISTRY.remove(self);
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
464
src/nodes/spatial/mod.rs
Normal file
464
src/nodes/spatial/mod.rs
Normal file
@@ -0,0 +1,464 @@
|
||||
pub mod zone;
|
||||
|
||||
use self::zone::Zone;
|
||||
use super::alias::Alias;
|
||||
use super::fields::{Field, FieldTrait};
|
||||
use super::Aspect;
|
||||
use crate::core::client::Client;
|
||||
use crate::core::registry::Registry;
|
||||
use crate::create_interface;
|
||||
use crate::nodes::{Node, OWNED_ASPECT_ALIAS_INFO};
|
||||
use color_eyre::eyre::{eyre, OptionExt, Result};
|
||||
use glam::{vec3a, Mat4, Quat, Vec3};
|
||||
use mint::Vector3;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::fmt::Debug;
|
||||
use std::ptr;
|
||||
use std::sync::{Arc, Weak};
|
||||
use stereokit_rust::maths::Bounds;
|
||||
|
||||
stardust_xr_server_codegen::codegen_spatial_protocol!();
|
||||
impl Transform {
|
||||
pub fn to_mat4(&self, position: bool, rotation: bool, scale: bool) -> Mat4 {
|
||||
let position = position
|
||||
.then_some(self.translation)
|
||||
.flatten()
|
||||
.unwrap_or_else(|| Vector3::from([0.0; 3]));
|
||||
let rotation = rotation
|
||||
.then_some(self.rotation)
|
||||
.flatten()
|
||||
.unwrap_or_else(|| Quat::IDENTITY.into());
|
||||
let scale = scale
|
||||
.then_some(self.scale)
|
||||
.flatten()
|
||||
.unwrap_or_else(|| Vector3::from([1.0; 3]));
|
||||
|
||||
Mat4::from_scale_rotation_translation(scale.into(), rotation.into(), position.into())
|
||||
}
|
||||
}
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
pub static ref EXPORTED_SPATIALS: Mutex<FxHashMap<u64, Arc<Node>>> = Mutex::new(FxHashMap::default());
|
||||
}
|
||||
|
||||
static ZONEABLE_REGISTRY: Registry<Spatial> = Registry::new();
|
||||
|
||||
pub struct Spatial {
|
||||
pub node: Weak<Node>,
|
||||
parent: Mutex<Option<Arc<Spatial>>>,
|
||||
old_parent: Mutex<Option<Arc<Spatial>>>,
|
||||
transform: Mutex<Mat4>,
|
||||
zone: Mutex<Weak<Zone>>,
|
||||
children: Registry<Spatial>,
|
||||
pub bounding_box_calc: OnceCell<fn(&Node) -> Bounds>,
|
||||
}
|
||||
|
||||
impl Spatial {
|
||||
pub fn new(node: Weak<Node>, parent: Option<Arc<Spatial>>, transform: Mat4) -> Arc<Self> {
|
||||
Arc::new(Spatial {
|
||||
node,
|
||||
parent: Mutex::new(parent),
|
||||
old_parent: Mutex::new(None),
|
||||
transform: Mutex::new(transform),
|
||||
zone: Mutex::new(Weak::new()),
|
||||
children: Registry::new(),
|
||||
bounding_box_calc: OnceCell::default(),
|
||||
})
|
||||
}
|
||||
pub fn add_to(
|
||||
node: &Arc<Node>,
|
||||
parent: Option<Arc<Spatial>>,
|
||||
transform: Mat4,
|
||||
zoneable: bool,
|
||||
) -> Arc<Spatial> {
|
||||
let spatial = Spatial::new(Arc::downgrade(node), parent.clone(), transform);
|
||||
<Spatial as SpatialAspect>::add_node_members(node);
|
||||
if zoneable {
|
||||
ZONEABLE_REGISTRY.add_raw(&spatial);
|
||||
}
|
||||
if let Some(parent) = parent {
|
||||
parent.children.add_raw(&spatial);
|
||||
}
|
||||
<Spatial as SpatialRefAspect>::add_node_members(node);
|
||||
<Spatial as SpatialAspect>::add_node_members(node);
|
||||
node.add_aspect_raw(spatial.clone());
|
||||
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.grown_box(child.get_bounding_box(), child.local_transform());
|
||||
}
|
||||
bounds
|
||||
}
|
||||
|
||||
pub fn local_transform(&self) -> Mat4 {
|
||||
*self.transform.lock()
|
||||
}
|
||||
pub fn global_transform(&self) -> Mat4 {
|
||||
let parent_transform = self
|
||||
.get_parent()
|
||||
.as_deref()
|
||||
.map(Self::global_transform)
|
||||
.unwrap_or_default();
|
||||
parent_transform * self.local_transform()
|
||||
}
|
||||
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.translation {
|
||||
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: &Arc<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.parent.lock() = new_parent.cloned();
|
||||
}
|
||||
|
||||
pub fn set_spatial_parent(self: &Arc<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: &Arc<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.map(AsRef::as_ref),
|
||||
));
|
||||
self.set_parent(parent);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(self) fn zone_distance(&self) -> f32 {
|
||||
self.zone
|
||||
.lock()
|
||||
.upgrade()
|
||||
.map(|zone| zone.field.clone())
|
||||
.map(|field| field.distance(self, vec3a(0.0, 0.0, 0.0)))
|
||||
.unwrap_or(f32::MAX)
|
||||
}
|
||||
}
|
||||
impl Aspect for Spatial {
|
||||
const NAME: &'static str = "Spatial";
|
||||
}
|
||||
impl SpatialRefAspect for Spatial {
|
||||
async fn get_local_bounding_box(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
) -> Result<BoundingBox> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
let bounds = this_spatial.get_bounding_box();
|
||||
|
||||
Ok(BoundingBox {
|
||||
center: Vec3::from(bounds.center).into(),
|
||||
size: Vec3::from(bounds.dimensions).into(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_relative_bounding_box(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
relative_to: Arc<Node>,
|
||||
) -> Result<BoundingBox> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
let relative_spatial = relative_to.get_aspect::<Spatial>()?;
|
||||
let center = Spatial::space_to_space_matrix(Some(&this_spatial), Some(&relative_spatial))
|
||||
.transform_point3([0.0; 3].into());
|
||||
let mut bounds = Bounds {
|
||||
center: center.into(),
|
||||
dimensions: [0.0; 3].into(),
|
||||
};
|
||||
bounds.grown_box(
|
||||
this_spatial.get_bounding_box(),
|
||||
Spatial::space_to_space_matrix(Some(&this_spatial), Some(&relative_spatial)),
|
||||
);
|
||||
|
||||
Ok(BoundingBox {
|
||||
center: Vec3::from(bounds.center).into(),
|
||||
size: Vec3::from(bounds.dimensions).into(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_transform(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
relative_to: Arc<Node>,
|
||||
) -> Result<Transform> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
let relative_spatial = relative_to.get_aspect::<Spatial>()?;
|
||||
|
||||
let (scale, rotation, position) = Spatial::space_to_space_matrix(
|
||||
Some(this_spatial.as_ref()),
|
||||
Some(relative_spatial.as_ref()),
|
||||
)
|
||||
.to_scale_rotation_translation();
|
||||
|
||||
Ok(Transform {
|
||||
translation: Some(position.into()),
|
||||
rotation: Some(rotation.into()),
|
||||
scale: Some(scale.into()),
|
||||
})
|
||||
}
|
||||
}
|
||||
impl SpatialAspect for Spatial {
|
||||
fn set_local_transform(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
transform: Transform,
|
||||
) -> Result<()> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
this_spatial.set_local_transform_components(None, transform);
|
||||
Ok(())
|
||||
}
|
||||
fn set_relative_transform(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
relative_to: Arc<Node>,
|
||||
transform: Transform,
|
||||
) -> Result<()> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
let relative_spatial = relative_to.get_aspect::<Spatial>()?;
|
||||
|
||||
this_spatial.set_local_transform_components(Some(&relative_spatial), transform);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_spatial_parent(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
parent: Arc<Node>,
|
||||
) -> Result<()> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
|
||||
this_spatial.set_spatial_parent(Some(&parent))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_spatial_parent_in_place(
|
||||
node: Arc<Node>,
|
||||
_calling_client: Arc<Client>,
|
||||
parent: Arc<Node>,
|
||||
) -> Result<()> {
|
||||
let this_spatial = node.get_aspect::<Spatial>()?;
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
|
||||
this_spatial.set_spatial_parent_in_place(Some(&parent))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_zoneable(node: Arc<Node>, _calling_client: Arc<Client>, zoneable: bool) -> Result<()> {
|
||||
let spatial = node.get_aspect::<Spatial>()?;
|
||||
if zoneable {
|
||||
ZONEABLE_REGISTRY.add_raw(&spatial);
|
||||
} else {
|
||||
ZONEABLE_REGISTRY.remove(&spatial);
|
||||
zone::release(&spatial);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// legit gotta find a way to remove old ones, this just keeps the node alive
|
||||
async fn export_spatial(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<u64> {
|
||||
let id = rand::random();
|
||||
EXPORTED_SPATIALS.lock().insert(id, node);
|
||||
Ok(id)
|
||||
}
|
||||
}
|
||||
impl PartialEq for Spatial {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.node.as_ptr() == other.node.as_ptr()
|
||||
}
|
||||
}
|
||||
impl Debug for Spatial {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Spatial")
|
||||
.field("parent", &self.parent)
|
||||
.field("old_parent", &self.old_parent)
|
||||
.field("transform", &self.transform)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
impl Drop for Spatial {
|
||||
fn drop(&mut self) {
|
||||
zone::release(self);
|
||||
ZONEABLE_REGISTRY.remove(self);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_transform(transform: Transform, position: bool, rotation: bool, scale: bool) -> Mat4 {
|
||||
let position = position
|
||||
.then_some(transform.translation)
|
||||
.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 struct SpatialInterface;
|
||||
impl InterfaceAspect for SpatialInterface {
|
||||
fn create_spatial(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
zoneable: bool,
|
||||
) -> Result<()> {
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = parse_transform(transform, true, true, true);
|
||||
let node = Node::from_id(&calling_client, id, true).add_to_scenegraph()?;
|
||||
Spatial::add_to(&node, Some(parent.clone()), transform, zoneable);
|
||||
Ok(())
|
||||
}
|
||||
fn create_zone(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
id: u64,
|
||||
parent: Arc<Node>,
|
||||
transform: Transform,
|
||||
field: Arc<Node>,
|
||||
) -> Result<()> {
|
||||
let parent = parent.get_aspect::<Spatial>()?;
|
||||
let transform = parse_transform(transform, true, true, false);
|
||||
let field = field.get_aspect::<Field>()?;
|
||||
|
||||
let node = Node::from_id(&calling_client, id, true).add_to_scenegraph()?;
|
||||
let space = Spatial::add_to(&node, Some(parent.clone()), transform, false);
|
||||
Zone::add_to(&node, space, field);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn import_spatial_ref(
|
||||
_node: Arc<Node>,
|
||||
calling_client: Arc<Client>,
|
||||
uid: u64,
|
||||
) -> Result<Arc<Node>> {
|
||||
EXPORTED_SPATIALS
|
||||
.lock()
|
||||
.get(&uid)
|
||||
.map(|s| {
|
||||
Alias::create(
|
||||
s,
|
||||
&calling_client,
|
||||
SPATIAL_REF_ASPECT_ALIAS_INFO.clone(),
|
||||
None,
|
||||
)
|
||||
.unwrap()
|
||||
})
|
||||
.ok_or_eyre("Couldn't find spatial with that ID")
|
||||
}
|
||||
}
|
||||
|
||||
create_interface!(SpatialInterface);
|
||||
162
src/nodes/spatial/zone.rs
Normal file
162
src/nodes/spatial/zone.rs
Normal file
@@ -0,0 +1,162 @@
|
||||
use super::{
|
||||
Spatial, ZoneAspect, SPATIAL_ASPECT_ALIAS_INFO, SPATIAL_REF_ASPECT_ALIAS_INFO,
|
||||
ZONEABLE_REGISTRY,
|
||||
};
|
||||
use crate::{
|
||||
core::{client::Client, registry::Registry},
|
||||
nodes::{
|
||||
alias::{get_original, Alias, AliasList},
|
||||
fields::{Field, FieldTrait},
|
||||
Aspect, Node,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::vec3a;
|
||||
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.distance(spatial, vec3a(0.0, 0.0, 0.0));
|
||||
if new_distance.abs() < old_distance.abs() {
|
||||
release(spatial);
|
||||
*spatial.old_parent.lock() = spatial.get_parent();
|
||||
*spatial.zone.lock() = Arc::downgrade(zone);
|
||||
let Some(zone_node) = zone.spatial.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(spatial_node) = spatial.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Ok(spatial_alias) = Alias::create(
|
||||
&spatial_node,
|
||||
&zone_node.get_client().unwrap(),
|
||||
SPATIAL_ASPECT_ALIAS_INFO.clone(),
|
||||
Some(&zone.captured),
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let _ = super::zone_client::capture(&zone_node, &spatial_alias);
|
||||
}
|
||||
}
|
||||
pub fn release(spatial: &Spatial) {
|
||||
let Some(spatial_node) = spatial.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let spatial = spatial_node.get_aspect::<Spatial>().unwrap();
|
||||
|
||||
let _ = spatial.set_spatial_parent_in_place(spatial.old_parent.lock().take().as_ref());
|
||||
let mut spatial_zone = spatial.zone.lock();
|
||||
|
||||
if let Some(spatial_zone) = spatial_zone.upgrade() {
|
||||
spatial_zone.captured.remove_aspect(spatial.as_ref());
|
||||
let Some(node) = spatial_zone.spatial.node.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let _ = super::zone_client::release(&node, spatial_node.id);
|
||||
}
|
||||
*spatial_zone = Weak::new();
|
||||
}
|
||||
|
||||
pub struct Zone {
|
||||
spatial: Arc<Spatial>,
|
||||
pub field: Arc<Field>,
|
||||
intersecting_spatials: Registry<Spatial>,
|
||||
intersecting: AliasList,
|
||||
captured: AliasList,
|
||||
}
|
||||
impl Zone {
|
||||
pub fn add_to(node: &Arc<Node>, spatial: Arc<Spatial>, field: Arc<Field>) -> Arc<Zone> {
|
||||
let zone = Arc::new(Zone {
|
||||
spatial,
|
||||
field,
|
||||
intersecting_spatials: Registry::default(),
|
||||
intersecting: AliasList::default(),
|
||||
captured: AliasList::default(),
|
||||
});
|
||||
<Zone as ZoneAspect>::add_node_members(node);
|
||||
node.add_aspect_raw(zone.clone());
|
||||
zone
|
||||
}
|
||||
pub fn update(&self) -> Result<()> {
|
||||
let node = self.spatial.node().unwrap();
|
||||
|
||||
let current_zoneables = Registry::new();
|
||||
for zoneable in ZONEABLE_REGISTRY.get_valid_contents() {
|
||||
let distance = self.field.distance(&zoneable, [0.0; 3].into());
|
||||
if distance > 0.0 {
|
||||
continue;
|
||||
}
|
||||
if let Some(zone) = zoneable.zone.lock().upgrade() {
|
||||
let zoneable_distance = zone.field.distance(&zoneable, [0.0; 3].into());
|
||||
if zoneable_distance < distance {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
current_zoneables.add_raw(&zoneable);
|
||||
}
|
||||
|
||||
let (added, removed) =
|
||||
Registry::get_changes(&self.intersecting_spatials, ¤t_zoneables);
|
||||
for added in added {
|
||||
let Some(added_node) = added.node() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(alias) = Alias::create(
|
||||
&added_node,
|
||||
&self.spatial.node().unwrap().get_client().unwrap(),
|
||||
SPATIAL_REF_ASPECT_ALIAS_INFO.clone(),
|
||||
Some(&self.intersecting),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let _ = super::zone_client::enter(&node, &alias);
|
||||
}
|
||||
for removed in removed {
|
||||
let Some(removed_node) = removed.node() else {
|
||||
continue;
|
||||
};
|
||||
release(&removed);
|
||||
let _ = super::zone_client::leave(&node, removed_node.id);
|
||||
self.intersecting.remove_aspect(removed.as_ref());
|
||||
}
|
||||
self.intersecting_spatials.set(¤t_zoneables);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Aspect for Zone {
|
||||
const NAME: &'static str = "Zone";
|
||||
}
|
||||
impl ZoneAspect for Zone {
|
||||
fn update(node: Arc<Node>, _calling_client: Arc<Client>) -> Result<()> {
|
||||
let zone = node.get_aspect::<Zone>()?;
|
||||
let _ = zone.update();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn capture(node: Arc<Node>, _calling_client: Arc<Client>, spatial: Arc<Node>) -> Result<()> {
|
||||
let zone = node.get_aspect::<Zone>()?;
|
||||
let spatial = spatial.get_aspect()?;
|
||||
capture(&spatial, &zone);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn release(_node: Arc<Node>, _calling_client: Arc<Client>, spatial: Arc<Node>) -> Result<()> {
|
||||
let spatial = spatial.get_aspect()?;
|
||||
release(&spatial);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Drop for Zone {
|
||||
fn drop(&mut self) {
|
||||
for captured in self
|
||||
.captured
|
||||
.get_aliases()
|
||||
.into_iter()
|
||||
.filter_map(|n| get_original(n, false))
|
||||
.filter_map(|n| n.get_aspect::<Spatial>().ok())
|
||||
{
|
||||
release(&captured);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
106
src/objects/input/eye_pointer.rs
Normal file
106
src/objects/input/eye_pointer.rs
Normal file
@@ -0,0 +1,106 @@
|
||||
use crate::{
|
||||
core::client::INTERNAL_CLIENT,
|
||||
nodes::{
|
||||
fields::{FieldTrait, Ray},
|
||||
input::{InputDataType, InputMethod, Pointer, INPUT_HANDLER_REGISTRY},
|
||||
spatial::Spatial,
|
||||
Node, OwnedNode,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::{vec3, Mat4};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use stardust_xr::values::Datamap;
|
||||
use std::sync::Arc;
|
||||
use stereokit_rust::system::Input;
|
||||
|
||||
#[derive(Default, Deserialize, Serialize)]
|
||||
pub struct EyeDatamap {
|
||||
eye: u32,
|
||||
}
|
||||
|
||||
#[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 {
|
||||
node: OwnedNode,
|
||||
spatial: Arc<Spatial>,
|
||||
pointer: Arc<InputMethod>,
|
||||
}
|
||||
impl EyePointer {
|
||||
pub fn new() -> Result<Self> {
|
||||
let node = Node::generate(&INTERNAL_CLIENT, false).add_to_scenegraph_owned()?;
|
||||
let spatial = Spatial::add_to(&node.0, None, Mat4::IDENTITY, false);
|
||||
let pointer = InputMethod::add_to(
|
||||
&node.0,
|
||||
InputDataType::Pointer(Pointer::default()),
|
||||
Datamap::from_typed(EyeDatamap::default())?,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
Ok(EyePointer {
|
||||
node,
|
||||
spatial,
|
||||
pointer,
|
||||
})
|
||||
}
|
||||
pub fn update(&self) {
|
||||
let ray = Input::get_eyes();
|
||||
self.spatial
|
||||
.set_local_transform(Mat4::from_rotation_translation(
|
||||
ray.orientation.into(),
|
||||
ray.position.into(),
|
||||
));
|
||||
{
|
||||
// Set pointer input datamap
|
||||
*self.pointer.datamap.lock() = Datamap::from_typed(EyeDatamap { eye: 2 }).unwrap();
|
||||
}
|
||||
|
||||
// send input to all the input handlers that are the closest to the ray as possible
|
||||
let rx = INPUT_HANDLER_REGISTRY
|
||||
.get_valid_contents()
|
||||
.into_iter()
|
||||
// filter out all the disabled handlers
|
||||
.filter(|handler| {
|
||||
let Some(node) = handler.spatial.node() else {
|
||||
return false;
|
||||
};
|
||||
node.enabled()
|
||||
})
|
||||
// ray march to all the enabled handlers' fields
|
||||
.map(|handler| {
|
||||
let result = handler.field.ray_march(Ray {
|
||||
origin: vec3(0.0, 0.0, 0.0),
|
||||
direction: vec3(0.0, 0.0, -1.0),
|
||||
space: self.spatial.clone(),
|
||||
});
|
||||
(vec![handler], result)
|
||||
})
|
||||
// make sure the field isn't at the pointer origin and that it's being hit
|
||||
.filter(|(_, result)| result.deepest_point_distance > 0.01 && result.min_distance < 0.0)
|
||||
// .inspect(|(_, result)| {
|
||||
// dbg!(result);
|
||||
// })
|
||||
// now collect all handlers that are same distance if they're the closest
|
||||
.reduce(|(mut handlers_a, result_a), (handlers_b, result_b)| {
|
||||
if (result_a.deepest_point_distance - result_b.deepest_point_distance).abs() < 0.001
|
||||
{
|
||||
// distance is basically the same
|
||||
handlers_a.extend(handlers_b);
|
||||
(handlers_a, result_a)
|
||||
} else if result_a.deepest_point_distance < result_b.deepest_point_distance {
|
||||
(handlers_a, result_a)
|
||||
} else {
|
||||
(handlers_b, result_b)
|
||||
}
|
||||
})
|
||||
.map(|(rx, _)| rx)
|
||||
.unwrap_or_default();
|
||||
self.pointer.set_handler_order(rx.iter());
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,98 @@
|
||||
pub mod eye_pointer;
|
||||
pub mod mouse_pointer;
|
||||
pub mod sk_controller;
|
||||
pub mod sk_hand;
|
||||
|
||||
use crate::nodes::{
|
||||
fields::{Field, FieldTrait, Ray},
|
||||
input::{InputDataTrait, InputDataType, InputHandler, InputMethod, INPUT_HANDLER_REGISTRY},
|
||||
spatial::Spatial,
|
||||
};
|
||||
use glam::vec3;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct CaptureManager {
|
||||
pub capture: Option<Arc<InputHandler>>,
|
||||
}
|
||||
impl CaptureManager {
|
||||
pub fn update_capture(&mut self, pointer: &InputMethod) {
|
||||
if let Some(capture) = &self.capture {
|
||||
if !pointer
|
||||
.internal_capture_requests
|
||||
.get_valid_contents()
|
||||
.contains(capture)
|
||||
{
|
||||
self.capture.take();
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn set_new_capture(
|
||||
&mut self,
|
||||
pointer: &InputMethod,
|
||||
distance_calculator: DistanceCalculator,
|
||||
) {
|
||||
if self.capture.is_none() {
|
||||
self.capture = find_closest_capture(pointer, distance_calculator);
|
||||
}
|
||||
}
|
||||
pub fn apply_capture(&self, method: &InputMethod) {
|
||||
method.captures.clear();
|
||||
if let Some(capture) = &self.capture {
|
||||
method.set_handler_order([capture].into_iter());
|
||||
method.captures.add_raw(capture);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type DistanceCalculator = fn(&Arc<Spatial>, &InputDataType, &Field) -> Option<f32>;
|
||||
|
||||
pub fn find_closest_capture(
|
||||
method: &InputMethod,
|
||||
distance_calculator: DistanceCalculator,
|
||||
) -> Option<Arc<InputHandler>> {
|
||||
method
|
||||
.internal_capture_requests
|
||||
.get_valid_contents()
|
||||
.into_iter()
|
||||
.filter_map(|h| {
|
||||
distance_calculator(&method.spatial, &method.data.lock(), &h.field)
|
||||
.map(|dist| (h.clone(), dist))
|
||||
})
|
||||
.min_by(|(_, dist_a), (_, dist_b)| dist_a.partial_cmp(dist_b).unwrap())
|
||||
.map(|(handler, _)| handler)
|
||||
}
|
||||
|
||||
pub fn get_sorted_handlers(
|
||||
method: &InputMethod,
|
||||
distance_calculator: DistanceCalculator,
|
||||
) -> Vec<Arc<InputHandler>> {
|
||||
INPUT_HANDLER_REGISTRY
|
||||
.get_valid_contents()
|
||||
.into_iter()
|
||||
.filter(|handler| handler.spatial.node().map_or(false, |node| node.enabled()))
|
||||
.filter(|handler| {
|
||||
handler
|
||||
.field
|
||||
.spatial
|
||||
.node()
|
||||
.map_or(false, |node| node.enabled())
|
||||
})
|
||||
.filter_map(|handler| {
|
||||
distance_calculator(&method.spatial, &method.data.lock(), &handler.field)
|
||||
.map(|distance| (vec![handler], distance))
|
||||
})
|
||||
.filter(|(_, distance)| *distance > 0.0)
|
||||
.reduce(|(mut handlers_a, distance_a), (handlers_b, distance_b)| {
|
||||
if (distance_a - distance_b).abs() < 0.001 {
|
||||
handlers_a.extend(handlers_b);
|
||||
(handlers_a, distance_a)
|
||||
} else if distance_a < distance_b {
|
||||
(handlers_a, distance_a)
|
||||
} else {
|
||||
(handlers_b, distance_b)
|
||||
}
|
||||
})
|
||||
.map(|(handlers, _)| handlers)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -1,59 +1,314 @@
|
||||
use crate::nodes::{
|
||||
input::{pointer::Pointer, InputMethod, InputType},
|
||||
spatial::Spatial,
|
||||
};
|
||||
use glam::{vec3, Mat4};
|
||||
use stardust_xr::{schemas::flat::Datamap, values::Transform};
|
||||
use std::sync::{Arc, Weak};
|
||||
use stereokit::{
|
||||
input::{ButtonState, Key, Ray},
|
||||
StereoKit,
|
||||
use crate::{
|
||||
core::client::INTERNAL_CLIENT,
|
||||
nodes::{
|
||||
data::{
|
||||
mask_matches, pulse_receiver_client, PulseSender, KEYMAPS, PULSE_RECEIVER_REGISTRY,
|
||||
},
|
||||
fields::{FieldTrait, Ray},
|
||||
input::{InputDataType, InputHandler, InputMethod, Pointer, INPUT_HANDLER_REGISTRY},
|
||||
spatial::Spatial,
|
||||
Node, OwnedNode,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::{vec3, Mat4, Vec3};
|
||||
use mint::Vector2;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use slotmap::{DefaultKey, Key as SlotKey};
|
||||
use stardust_xr::values::Datamap;
|
||||
use std::sync::Arc;
|
||||
use stereokit_rust::system::{Input, Key};
|
||||
use xkbcommon_rs::{xkb_keymap::CompileFlags, Context, Keymap, KeymapFormat};
|
||||
|
||||
use super::{get_sorted_handlers, CaptureManager, DistanceCalculator};
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct MouseEvent {
|
||||
select: f32,
|
||||
middle: f32,
|
||||
context: f32,
|
||||
grab: f32,
|
||||
scroll_continuous: Vector2<f32>,
|
||||
scroll_discrete: Vector2<f32>,
|
||||
raw_input_events: Vec<u32>,
|
||||
}
|
||||
impl Default for MouseEvent {
|
||||
fn default() -> Self {
|
||||
MouseEvent {
|
||||
select: 0.0,
|
||||
middle: 0.0,
|
||||
context: 0.0,
|
||||
grab: 0.0,
|
||||
scroll_continuous: [0.0; 2].into(),
|
||||
scroll_discrete: [0.0; 2].into(),
|
||||
raw_input_events: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
|
||||
pub struct KeyboardEvent {
|
||||
pub keyboard: (),
|
||||
pub xkbv1: (),
|
||||
pub keymap_id: u64,
|
||||
pub keys: Vec<i32>,
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
pub struct MousePointer {
|
||||
node: OwnedNode,
|
||||
keymap: DefaultKey,
|
||||
spatial: Arc<Spatial>,
|
||||
pointer: Arc<InputMethod>,
|
||||
capture_manager: CaptureManager,
|
||||
mouse_datamap: MouseEvent,
|
||||
keyboard_datamap: KeyboardEvent,
|
||||
keyboard_sender: Arc<PulseSender>,
|
||||
}
|
||||
impl MousePointer {
|
||||
pub fn new() -> Self {
|
||||
MousePointer {
|
||||
pointer: InputMethod::new(
|
||||
Spatial::new(Weak::new(), None, Mat4::IDENTITY),
|
||||
InputType::Pointer(Pointer::default()),
|
||||
),
|
||||
}
|
||||
pub fn new() -> Result<Self> {
|
||||
let node = Node::generate(&INTERNAL_CLIENT, false).add_to_scenegraph_owned()?;
|
||||
let spatial = Spatial::add_to(&node.0, None, Mat4::IDENTITY, false);
|
||||
let pointer = InputMethod::add_to(
|
||||
&node.0,
|
||||
InputDataType::Pointer(Pointer::default()),
|
||||
Datamap::from_typed(MouseEvent::default())?,
|
||||
)?;
|
||||
|
||||
let context = Context::new(0).unwrap();
|
||||
let keymap = KEYMAPS.lock().insert(
|
||||
Keymap::new_from_names(context, None, CompileFlags::NO_FLAGS)
|
||||
.unwrap()
|
||||
.get_as_string(KeymapFormat::TextV1)
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let keyboard_sender = PulseSender::add_to(
|
||||
&node.0,
|
||||
Datamap::from_typed(KeyboardEvent::default()).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
Ok(MousePointer {
|
||||
node,
|
||||
spatial,
|
||||
pointer,
|
||||
capture_manager: CaptureManager::default(),
|
||||
mouse_datamap: Default::default(),
|
||||
keyboard_datamap: KeyboardEvent {
|
||||
keyboard: (),
|
||||
xkbv1: (),
|
||||
keymap_id: keymap.data().as_ffi(),
|
||||
keys: vec![],
|
||||
},
|
||||
keymap,
|
||||
keyboard_sender,
|
||||
})
|
||||
}
|
||||
pub fn update(&self, sk: &StereoKit) {
|
||||
if let Some(ray) = Ray::from_mouse(sk.input_mouse()) {
|
||||
self.pointer.spatial.set_local_transform_components(
|
||||
None,
|
||||
Transform {
|
||||
position: Some(ray.pos),
|
||||
rotation: Some(
|
||||
glam::Quat::from_rotation_arc(vec3(0.0, 0.0, 1.0), ray.dir.into()).into(),
|
||||
),
|
||||
scale: None,
|
||||
},
|
||||
);
|
||||
pub fn update(&mut self) {
|
||||
let mouse = Input::get_mouse();
|
||||
|
||||
let ray = mouse.get_ray();
|
||||
self.spatial.set_local_transform(
|
||||
Mat4::look_to_rh(
|
||||
Vec3::from(ray.position),
|
||||
Vec3::from(ray.direction),
|
||||
vec3(0.0, 1.0, 0.0),
|
||||
)
|
||||
.inverse(),
|
||||
);
|
||||
{
|
||||
// Set pointer input datamap
|
||||
self.mouse_datamap = MouseEvent {
|
||||
select: Input::key(Key::MouseLeft).is_active() as u32 as f32,
|
||||
middle: Input::key(Key::MouseCenter).is_active() as u32 as f32,
|
||||
context: Input::key(Key::MouseRight).is_active() as u32 as f32,
|
||||
grab: (Input::key(Key::Backtick).is_active() && Input::key(Key::Shift).is_active()) as u32 as f32, // Was Mouse 5
|
||||
scroll_continuous: [0.0, mouse.scroll_change / 120.0].into(),
|
||||
scroll_discrete: [0.0, mouse.scroll_change / 120.0].into(),
|
||||
raw_input_events: vec![],
|
||||
};
|
||||
*self.pointer.datamap.lock() = Datamap::from_typed(&self.mouse_datamap).unwrap();
|
||||
}
|
||||
self.target_pointer_input();
|
||||
self.send_keyboard_input();
|
||||
}
|
||||
fn target_pointer_input(&mut self) {
|
||||
let distance_calculator: DistanceCalculator = |space, data, field| {
|
||||
let result = field.ray_march(Ray {
|
||||
origin: vec3(0.0, 0.0, 0.0),
|
||||
direction: vec3(0.0, 0.0, -1.0),
|
||||
space: space.clone(),
|
||||
});
|
||||
let valid =
|
||||
result.deepest_point_distance > 0.0 && result.min_distance.is_sign_negative();
|
||||
valid.then_some(result.deepest_point_distance)
|
||||
};
|
||||
|
||||
self.capture_manager.update_capture(&self.pointer);
|
||||
self.capture_manager
|
||||
.set_new_capture(&self.pointer, distance_calculator);
|
||||
self.capture_manager.apply_capture(&self.pointer);
|
||||
|
||||
if self.capture_manager.capture.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let sorted_handlers = get_sorted_handlers(&self.pointer, distance_calculator);
|
||||
self.pointer.set_handler_order(sorted_handlers.iter());
|
||||
}
|
||||
|
||||
fn send_keyboard_input(&mut self) {
|
||||
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)
|
||||
.map(|i| unsafe { std::mem::transmute(i) })
|
||||
.filter_map(|k| Some((map_key(k)?, Input::key(k))))
|
||||
.filter_map(|(i, k)| {
|
||||
if k.is_just_active() {
|
||||
Some(i as i32)
|
||||
} else if k.is_just_inactive() {
|
||||
Some(-(i as i32))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
self.keyboard_datamap.keys = keys;
|
||||
if !self.keyboard_datamap.keys.is_empty() {
|
||||
pulse_receiver_client::data(
|
||||
&rx.node.upgrade().unwrap(),
|
||||
&self.node.0,
|
||||
&Datamap::from_typed(&self.keyboard_datamap).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
let mut fbb = flexbuffers::Builder::default();
|
||||
let mut map = fbb.start_map();
|
||||
map.push(
|
||||
"select",
|
||||
if sk.input_key(Key::MouseLeft).contains(ButtonState::Active) {
|
||||
1.0f32
|
||||
} else {
|
||||
0.0f32
|
||||
},
|
||||
);
|
||||
map.push(
|
||||
"grab",
|
||||
if sk.input_key(Key::MouseRight).contains(ButtonState::Active) {
|
||||
1.0f32
|
||||
} else {
|
||||
0.0f32
|
||||
},
|
||||
);
|
||||
map.end_map();
|
||||
*self.pointer.datamap.lock() = Datamap::new(fbb.take_buffer()).ok();
|
||||
}
|
||||
}
|
||||
|
||||
fn map_key(key: Key) -> Option<u32> {
|
||||
match key {
|
||||
Key::Backspace => Some(input_event_codes::KEY_BACKSPACE!()),
|
||||
Key::Tab => Some(input_event_codes::KEY_TAB!()),
|
||||
Key::Return => Some(input_event_codes::KEY_ENTER!()),
|
||||
Key::Shift => Some(input_event_codes::KEY_LEFTSHIFT!()),
|
||||
Key::Ctrl => Some(input_event_codes::KEY_LEFTCTRL!()),
|
||||
Key::Alt => Some(input_event_codes::KEY_LEFTALT!()),
|
||||
Key::CapsLock => Some(input_event_codes::KEY_CAPSLOCK!()),
|
||||
Key::Esc => Some(input_event_codes::KEY_ESC!()),
|
||||
Key::Space => Some(input_event_codes::KEY_SPACE!()),
|
||||
Key::End => Some(input_event_codes::KEY_END!()),
|
||||
Key::Home => Some(input_event_codes::KEY_HOME!()),
|
||||
Key::Left => Some(input_event_codes::KEY_LEFT!()),
|
||||
Key::Right => Some(input_event_codes::KEY_RIGHT!()),
|
||||
Key::Up => Some(input_event_codes::KEY_UP!()),
|
||||
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 => Some(input_event_codes::KEY_GRAVE!()),
|
||||
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,128 @@
|
||||
use crate::nodes::{
|
||||
input::{tip::Tip, InputMethod, InputType},
|
||||
spatial::Spatial,
|
||||
use super::{get_sorted_handlers, CaptureManager};
|
||||
use crate::{
|
||||
core::client::INTERNAL_CLIENT,
|
||||
nodes::{
|
||||
fields::{Field, FieldTrait},
|
||||
input::{InputDataType, InputHandler, InputMethod, Tip, INPUT_HANDLER_REGISTRY},
|
||||
spatial::Spatial,
|
||||
Node, OwnedNode,
|
||||
},
|
||||
objects::{ObjectHandle, SpatialRef},
|
||||
};
|
||||
use glam::Mat4;
|
||||
use stardust_xr::{schemas::flat::Datamap, values::Transform};
|
||||
use std::sync::{Arc, Weak};
|
||||
use stereokit::{
|
||||
input::{ButtonState, Handed},
|
||||
StereoKit,
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::{Mat4, Vec2, Vec3};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use stardust_xr::values::Datamap;
|
||||
use std::sync::Arc;
|
||||
use stereokit_rust::{
|
||||
material::Material,
|
||||
model::Model,
|
||||
sk::MainThreadToken,
|
||||
system::{Handed, Input},
|
||||
util::Color128,
|
||||
};
|
||||
use zbus::Connection;
|
||||
|
||||
#[derive(Default, Debug, Deserialize, Serialize)]
|
||||
struct ControllerDatamap {
|
||||
select: f32,
|
||||
middle: f32,
|
||||
context: f32,
|
||||
grab: f32,
|
||||
scroll: Vec2,
|
||||
}
|
||||
|
||||
pub struct SkController {
|
||||
tip: Arc<InputMethod>,
|
||||
object_handle: ObjectHandle<SpatialRef>,
|
||||
input: Arc<InputMethod>,
|
||||
handed: Handed,
|
||||
model: Model,
|
||||
material: Material,
|
||||
capture_manager: CaptureManager,
|
||||
datamap: ControllerDatamap,
|
||||
}
|
||||
impl SkController {
|
||||
pub fn new(handed: Handed) -> Self {
|
||||
SkController {
|
||||
tip: InputMethod::new(
|
||||
Spatial::new(Weak::new(), None, Mat4::IDENTITY),
|
||||
InputType::Tip(Tip::default()),
|
||||
),
|
||||
pub fn new(connection: &Connection, handed: Handed) -> Result<Self> {
|
||||
let (spatial, object_handle) = SpatialRef::create(
|
||||
connection,
|
||||
&("/org/stardustxr/Controller/".to_string()
|
||||
+ match handed {
|
||||
Handed::Left => "left",
|
||||
_ => "right",
|
||||
}),
|
||||
);
|
||||
let model = Model::copy(Model::from_memory(
|
||||
"cursor.glb",
|
||||
include_bytes!("cursor.glb"),
|
||||
None,
|
||||
)?);
|
||||
let model_nodes = model.get_nodes();
|
||||
let mut model_node = model_nodes.visuals().next().unwrap();
|
||||
let material = Material::copy(&model_node.get_material().unwrap());
|
||||
model_node.material(&material);
|
||||
let tip = InputDataType::Tip(Tip::default());
|
||||
let input = InputMethod::add_to(
|
||||
&spatial.node().unwrap(),
|
||||
tip,
|
||||
Datamap::from_typed(ControllerDatamap::default())?,
|
||||
)?;
|
||||
Ok(SkController {
|
||||
object_handle,
|
||||
input,
|
||||
handed,
|
||||
}
|
||||
model,
|
||||
material,
|
||||
capture_manager: CaptureManager::default(),
|
||||
datamap: Default::default(),
|
||||
})
|
||||
}
|
||||
pub fn update(&mut self, sk: &StereoKit) {
|
||||
let controller = sk.input_controller(self.handed);
|
||||
*self.tip.enabled.lock() = controller.tracked.contains(ButtonState::Active);
|
||||
if *self.tip.enabled.lock() {
|
||||
self.tip.spatial.set_local_transform_components(
|
||||
None,
|
||||
Transform {
|
||||
position: Some(controller.pose.position),
|
||||
rotation: Some(controller.pose.orientation),
|
||||
scale: None,
|
||||
},
|
||||
pub fn update(&mut self, token: &MainThreadToken) {
|
||||
let controller = Input::controller(self.handed);
|
||||
let input_node = self.input.spatial.node().unwrap();
|
||||
input_node.set_enabled(controller.tracked.is_active());
|
||||
if input_node.enabled() {
|
||||
let world_transform = Mat4::from_rotation_translation(
|
||||
controller.aim.orientation.into(),
|
||||
controller.aim.position.into(),
|
||||
);
|
||||
self.material
|
||||
.color_tint(if self.capture_manager.capture.is_none() {
|
||||
Color128::new_rgb(1.0, 1.0, 1.0)
|
||||
} else {
|
||||
Color128::new_rgb(0.0, 1.0, 0.75)
|
||||
});
|
||||
self.model.draw(
|
||||
token,
|
||||
world_transform * Mat4::from_scale(Vec3::ONE * 0.02),
|
||||
None,
|
||||
None,
|
||||
);
|
||||
self.input.spatial.set_local_transform(world_transform);
|
||||
}
|
||||
let mut fbb = flexbuffers::Builder::default();
|
||||
let mut map = fbb.start_map();
|
||||
map.push("select", controller.trigger);
|
||||
map.push("grab", controller.grip);
|
||||
map.end_map();
|
||||
*self.tip.datamap.lock() = Datamap::new(fbb.take_buffer()).ok();
|
||||
|
||||
self.datamap = ControllerDatamap {
|
||||
select: controller.trigger,
|
||||
middle: controller.stick_click.is_active() as u32 as f32,
|
||||
context: controller.is_x2_pressed() as u32 as f32,
|
||||
grab: controller.grip,
|
||||
scroll: controller.stick.into(),
|
||||
};
|
||||
*self.input.datamap.lock() = Datamap::from_typed(&self.datamap).unwrap();
|
||||
|
||||
let distance_calculator = |space: &Arc<Spatial>, _data: &InputDataType, field: &Field| {
|
||||
Some(field.distance(space, [0.0; 3].into()).abs())
|
||||
};
|
||||
|
||||
self.capture_manager.update_capture(&self.input);
|
||||
self.capture_manager
|
||||
.set_new_capture(&self.input, distance_calculator);
|
||||
self.capture_manager.apply_capture(&self.input);
|
||||
|
||||
if self.capture_manager.capture.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let sorted_handlers = get_sorted_handlers(&self.input, distance_calculator);
|
||||
self.input.set_handler_order(sorted_handlers.iter());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,60 +1,102 @@
|
||||
use crate::core::client::INTERNAL_CLIENT;
|
||||
use crate::nodes::fields::{Field, FieldTrait};
|
||||
use crate::nodes::input::{InputDataType, InputHandler, INPUT_HANDLER_REGISTRY};
|
||||
use crate::nodes::OwnedNode;
|
||||
use crate::nodes::{
|
||||
input::{hand::Hand, InputMethod, InputType},
|
||||
input::{Hand, InputMethod, Joint},
|
||||
spatial::Spatial,
|
||||
Node,
|
||||
};
|
||||
use glam::Mat4;
|
||||
use stardust_xr::schemas::flat::{Datamap, Hand as FlatHand, Joint};
|
||||
use std::sync::{Arc, Weak};
|
||||
use stereokit::{
|
||||
input::{ButtonState, Handed, Joint as SkJoint},
|
||||
StereoKit,
|
||||
};
|
||||
use crate::objects::{ObjectHandle, SpatialRef};
|
||||
use color_eyre::eyre::Result;
|
||||
use glam::{Mat4, Quat, Vec3};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use stardust_xr::values::Datamap;
|
||||
use std::f32::INFINITY;
|
||||
use std::sync::Arc;
|
||||
use stereokit_rust::sk::{DisplayMode, MainThreadToken, Sk};
|
||||
use stereokit_rust::system::{HandJoint, HandSource, Handed, Input, LinePoint, Lines};
|
||||
use stereokit_rust::util::Color128;
|
||||
use zbus::Connection;
|
||||
|
||||
fn convert_joint(joint: SkJoint) -> Joint {
|
||||
use super::{get_sorted_handlers, CaptureManager};
|
||||
|
||||
fn convert_joint(joint: HandJoint) -> Joint {
|
||||
Joint {
|
||||
position: joint.position,
|
||||
rotation: joint.orientation,
|
||||
position: Vec3::from(joint.position).into(),
|
||||
rotation: Quat::from(joint.orientation).into(),
|
||||
radius: joint.radius,
|
||||
distance: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Deserialize, Serialize)]
|
||||
struct HandDatamap {
|
||||
pinch_strength: f32,
|
||||
grab_strength: f32,
|
||||
}
|
||||
|
||||
pub struct SkHand {
|
||||
hand: Arc<InputMethod>,
|
||||
_node: OwnedNode,
|
||||
palm_spatial: Arc<Spatial>,
|
||||
palm_object: ObjectHandle<SpatialRef>,
|
||||
handed: Handed,
|
||||
input: Arc<InputMethod>,
|
||||
capture_manager: CaptureManager,
|
||||
datamap: HandDatamap,
|
||||
}
|
||||
impl SkHand {
|
||||
pub fn new(handed: Handed) -> Self {
|
||||
SkHand {
|
||||
hand: InputMethod::new(
|
||||
Spatial::new(Weak::new(), None, Mat4::IDENTITY),
|
||||
InputType::Hand(Box::new(Hand {
|
||||
base: FlatHand {
|
||||
right: handed == Handed::Right,
|
||||
..Default::default()
|
||||
},
|
||||
})),
|
||||
),
|
||||
handed,
|
||||
}
|
||||
}
|
||||
pub fn update(&mut self, sk: &StereoKit) {
|
||||
let sk_hand = sk.input_hand(self.handed);
|
||||
if let InputType::Hand(hand) = &mut *self.hand.specialization.lock() {
|
||||
let controller = sk.input_controller(self.handed);
|
||||
*self.hand.enabled.lock() = controller.tracked.contains(ButtonState::Inactive)
|
||||
&& sk_hand.tracked_state.contains(ButtonState::Active);
|
||||
if *self.hand.enabled.lock() {
|
||||
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.proximal = convert_joint(sk_hand.fingers[0][2]);
|
||||
hand.base.thumb.metacarpal = convert_joint(sk_hand.fingers[0][1]);
|
||||
pub fn new(connection: &Connection, handed: Handed) -> Result<Self> {
|
||||
let (palm_spatial, palm_object) = SpatialRef::create(
|
||||
connection,
|
||||
&("/org/stardustxr/Hand/".to_string()
|
||||
+ match handed {
|
||||
Handed::Left => "left",
|
||||
_ => "right",
|
||||
} + "/palm"),
|
||||
);
|
||||
let _node = Node::generate(&INTERNAL_CLIENT, false).add_to_scenegraph_owned()?;
|
||||
Spatial::add_to(&_node.0, None, Mat4::IDENTITY, false);
|
||||
let hand = InputDataType::Hand(Hand {
|
||||
right: handed == Handed::Right,
|
||||
..Default::default()
|
||||
});
|
||||
let datamap = Datamap::from_typed(HandDatamap::default())?;
|
||||
let input = InputMethod::add_to(&_node.0, hand, datamap)?;
|
||||
|
||||
for (finger, sk_finger) in [
|
||||
(&mut hand.base.index, sk_hand.fingers[1]),
|
||||
(&mut hand.base.middle, sk_hand.fingers[2]),
|
||||
(&mut hand.base.ring, sk_hand.fingers[3]),
|
||||
(&mut hand.base.little, sk_hand.fingers[4]),
|
||||
Input::hand_visible(handed, false);
|
||||
Ok(SkHand {
|
||||
_node,
|
||||
palm_spatial,
|
||||
palm_object,
|
||||
handed,
|
||||
input,
|
||||
capture_manager: CaptureManager::default(),
|
||||
datamap: Default::default(),
|
||||
})
|
||||
}
|
||||
pub fn update(&mut self, sk: &Sk, token: &MainThreadToken) {
|
||||
let sk_hand = Input::hand(self.handed);
|
||||
let real_hand = Input::hand_source(self.handed) as u32 == HandSource::Articulated as u32;
|
||||
if let InputDataType::Hand(hand) = &mut *self.input.data.lock() {
|
||||
let input_node = self.input.spatial.node().unwrap();
|
||||
input_node.set_enabled(
|
||||
(real_hand || sk.get_active_display_mode() == DisplayMode::Flatscreen)
|
||||
&& sk_hand.tracked.is_active(),
|
||||
);
|
||||
if input_node.enabled() {
|
||||
hand.thumb.tip = convert_joint(sk_hand.fingers[0][4]);
|
||||
hand.thumb.distal = convert_joint(sk_hand.fingers[0][3]);
|
||||
hand.thumb.proximal = convert_joint(sk_hand.fingers[0][2]);
|
||||
hand.thumb.metacarpal = convert_joint(sk_hand.fingers[0][1]);
|
||||
|
||||
for (finger, mut sk_finger) in [
|
||||
(&mut hand.index, sk_hand.fingers[1]),
|
||||
(&mut hand.middle, sk_hand.fingers[2]),
|
||||
(&mut hand.ring, sk_hand.fingers[3]),
|
||||
(&mut hand.little, sk_hand.fingers[4]),
|
||||
] {
|
||||
sk_finger[4].radius = 0.0;
|
||||
finger.tip = convert_joint(sk_finger[4]);
|
||||
finger.distal = convert_joint(sk_finger[3]);
|
||||
finger.intermediate = convert_joint(sk_finger[2]);
|
||||
@@ -62,24 +104,134 @@ impl SkHand {
|
||||
finger.metacarpal = convert_joint(sk_finger[0]);
|
||||
}
|
||||
|
||||
hand.base.palm.position = sk_hand.palm.position;
|
||||
hand.base.palm.rotation = sk_hand.palm.orientation;
|
||||
hand.base.palm.radius =
|
||||
hand.palm.position = Vec3::from(sk_hand.palm.position).into();
|
||||
hand.palm.rotation = Quat::from(sk_hand.palm.orientation).into();
|
||||
hand.palm.radius =
|
||||
(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.rotation = sk_hand.wrist.orientation;
|
||||
hand.base.wrist.radius =
|
||||
self.palm_spatial
|
||||
.set_local_transform(Mat4::from_rotation_translation(
|
||||
hand.palm.rotation.into(),
|
||||
hand.palm.position.into(),
|
||||
));
|
||||
|
||||
hand.wrist.position = Vec3::from(sk_hand.wrist.position).into();
|
||||
hand.wrist.rotation = Quat::from(sk_hand.wrist.orientation).into();
|
||||
hand.wrist.radius =
|
||||
(sk_hand.fingers[0][0].radius + sk_hand.fingers[4][0].radius) * 0.5;
|
||||
|
||||
hand.base.elbow = None;
|
||||
hand.elbow = None;
|
||||
|
||||
self.draw(
|
||||
token,
|
||||
if self.capture_manager.capture.is_none() {
|
||||
Color128::new_rgb(1.0, 1.0, 1.0)
|
||||
} else {
|
||||
Color128::new_rgb(0.0, 1.0, 0.75)
|
||||
},
|
||||
hand,
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut fbb = flexbuffers::Builder::default();
|
||||
let mut map = fbb.start_map();
|
||||
map.push("grabStrength", sk_hand.grip_activation);
|
||||
map.push("pinchStrength", sk_hand.pinch_activation);
|
||||
map.end_map();
|
||||
*self.hand.datamap.lock() = Datamap::new(fbb.take_buffer()).ok();
|
||||
self.datamap.pinch_strength = sk_hand.pinch_activation;
|
||||
self.datamap.grab_strength = sk_hand.grip_activation;
|
||||
*self.input.datamap.lock() = Datamap::from_typed(&self.datamap).unwrap();
|
||||
|
||||
let distance_calculator = |space: &Arc<Spatial>, data: &InputDataType, field: &Field| {
|
||||
let InputDataType::Hand(hand) = data else {
|
||||
return None;
|
||||
};
|
||||
let thumb_tip_distance = field.distance(space, hand.thumb.tip.position.into());
|
||||
let index_tip_distance = field.distance(space, hand.index.tip.position.into());
|
||||
let middle_tip_distance = field.distance(space, hand.middle.tip.position.into());
|
||||
let ring_tip_distance = field.distance(space, hand.ring.tip.position.into());
|
||||
|
||||
Some(
|
||||
(thumb_tip_distance * 0.3)
|
||||
+ (index_tip_distance * 0.4)
|
||||
+ (middle_tip_distance * 0.15)
|
||||
+ (ring_tip_distance * 0.15),
|
||||
)
|
||||
};
|
||||
|
||||
self.capture_manager.update_capture(&self.input);
|
||||
self.capture_manager
|
||||
.set_new_capture(&self.input, distance_calculator);
|
||||
self.capture_manager.apply_capture(&self.input);
|
||||
|
||||
if self.capture_manager.capture.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let sorted_handlers = get_sorted_handlers(&self.input, distance_calculator);
|
||||
self.input.set_handler_order(sorted_handlers.iter());
|
||||
}
|
||||
|
||||
fn draw(&self, token: &MainThreadToken, color: Color128, hand: &Hand) {
|
||||
// thumb
|
||||
Lines::add_list(
|
||||
token,
|
||||
&[
|
||||
joint_to_line_point(&hand.thumb.tip, color),
|
||||
joint_to_line_point(&hand.thumb.distal, color),
|
||||
joint_to_line_point(&hand.thumb.proximal, color),
|
||||
joint_to_line_point(&hand.thumb.metacarpal, color),
|
||||
],
|
||||
);
|
||||
// index
|
||||
Lines::add_list(
|
||||
token,
|
||||
&[
|
||||
joint_to_line_point(&hand.index.tip, color),
|
||||
joint_to_line_point(&hand.index.distal, color),
|
||||
joint_to_line_point(&hand.index.intermediate, color),
|
||||
joint_to_line_point(&hand.index.proximal, color),
|
||||
joint_to_line_point(&hand.index.metacarpal, color),
|
||||
],
|
||||
);
|
||||
// middle
|
||||
Lines::add_list(
|
||||
token,
|
||||
&[
|
||||
joint_to_line_point(&hand.middle.tip, color),
|
||||
joint_to_line_point(&hand.middle.distal, color),
|
||||
joint_to_line_point(&hand.middle.intermediate, color),
|
||||
joint_to_line_point(&hand.middle.proximal, color),
|
||||
joint_to_line_point(&hand.middle.metacarpal, color),
|
||||
],
|
||||
);
|
||||
// ring
|
||||
Lines::add_list(
|
||||
token,
|
||||
&[
|
||||
joint_to_line_point(&hand.ring.tip, color),
|
||||
joint_to_line_point(&hand.ring.distal, color),
|
||||
joint_to_line_point(&hand.ring.intermediate, color),
|
||||
joint_to_line_point(&hand.ring.proximal, color),
|
||||
joint_to_line_point(&hand.ring.metacarpal, color),
|
||||
],
|
||||
);
|
||||
|
||||
// palm
|
||||
Lines::add_list(
|
||||
token,
|
||||
&[
|
||||
joint_to_line_point(&hand.wrist, color),
|
||||
joint_to_line_point(&hand.thumb.metacarpal, color),
|
||||
joint_to_line_point(&hand.index.metacarpal, color),
|
||||
joint_to_line_point(&hand.middle.metacarpal, color),
|
||||
joint_to_line_point(&hand.ring.metacarpal, color),
|
||||
joint_to_line_point(&hand.little.metacarpal, color),
|
||||
joint_to_line_point(&hand.wrist, color),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn joint_to_line_point(joint: &Joint, color: Color128) -> LinePoint {
|
||||
LinePoint {
|
||||
pt: Vec3::from(joint.position).into(),
|
||||
thickness: joint.radius * 2.0,
|
||||
color: color.into(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +1,274 @@
|
||||
#![allow(unused)]
|
||||
|
||||
use crate::{
|
||||
core::client::INTERNAL_CLIENT,
|
||||
nodes::{
|
||||
fields::{Field, Shape, EXPORTED_FIELDS},
|
||||
spatial::{Spatial, EXPORTED_SPATIALS},
|
||||
Node, OwnedNode,
|
||||
},
|
||||
};
|
||||
use glam::{vec3, Mat4};
|
||||
use input::{
|
||||
eye_pointer::EyePointer, mouse_pointer::MousePointer, sk_controller::SkController,
|
||||
sk_hand::SkHand,
|
||||
};
|
||||
use play_space::PlaySpaceBounds;
|
||||
use std::{marker::PhantomData, sync::Arc};
|
||||
use stereokit_rust::{
|
||||
sk::{DisplayMode, MainThreadToken, Sk},
|
||||
system::{Handed, Input, Key, World},
|
||||
util::Device,
|
||||
};
|
||||
use zbus::{interface, object_server::Interface, zvariant::OwnedObjectPath, Connection};
|
||||
|
||||
pub mod input;
|
||||
pub mod play_space;
|
||||
|
||||
enum Inputs {
|
||||
XR {
|
||||
controller_left: SkController,
|
||||
controller_right: SkController,
|
||||
hand_left: SkHand,
|
||||
hand_right: SkHand,
|
||||
eye_pointer: Option<EyePointer>,
|
||||
},
|
||||
MousePointer(MousePointer),
|
||||
// Controllers((SkController, SkController)),
|
||||
Hands {
|
||||
left: SkHand,
|
||||
right: SkHand,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct ServerObjects {
|
||||
connection: Connection,
|
||||
hmd: (Arc<Spatial>, ObjectHandle<SpatialRef>),
|
||||
play_space: Option<(Arc<Spatial>, ObjectHandle<SpatialRef>)>,
|
||||
inputs: Inputs,
|
||||
disable_controllers: bool,
|
||||
disable_hands: bool,
|
||||
}
|
||||
impl ServerObjects {
|
||||
pub fn new(
|
||||
connection: Connection,
|
||||
sk: &Sk,
|
||||
disable_controllers: bool,
|
||||
disable_hands: bool,
|
||||
) -> ServerObjects {
|
||||
let hmd = SpatialRef::create(&connection, "/org/stardustxr/HMD");
|
||||
|
||||
let play_space = (World::has_bounds()
|
||||
&& World::get_bounds_size().x != 0.0
|
||||
&& World::get_bounds_size().y != 0.0)
|
||||
.then(|| SpatialRef::create(&connection, "/org/stardustxr/PlaySpace"));
|
||||
if play_space.is_some() {
|
||||
let dbus_connection = connection.clone();
|
||||
tokio::task::spawn(async move {
|
||||
PlaySpaceBounds::create(&dbus_connection).await;
|
||||
dbus_connection
|
||||
.request_name("org.stardustxr.PlaySpace")
|
||||
.await
|
||||
.unwrap();
|
||||
});
|
||||
}
|
||||
|
||||
tokio::task::spawn({
|
||||
let connection = connection.clone();
|
||||
async move {
|
||||
connection
|
||||
.request_name("org.stardustxr.Controllers")
|
||||
.await
|
||||
.unwrap();
|
||||
connection
|
||||
.request_name("org.stardustxr.Hands")
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
|
||||
let inputs = if sk.get_active_display_mode() == DisplayMode::MixedReality {
|
||||
Inputs::XR {
|
||||
controller_left: SkController::new(&connection, Handed::Left).unwrap(),
|
||||
controller_right: SkController::new(&connection, Handed::Right).unwrap(),
|
||||
hand_left: SkHand::new(&connection, Handed::Left).unwrap(),
|
||||
hand_right: SkHand::new(&connection, Handed::Right).unwrap(),
|
||||
eye_pointer: Device::has_eye_gaze()
|
||||
.then(EyePointer::new)
|
||||
.transpose()
|
||||
.unwrap(),
|
||||
}
|
||||
} else {
|
||||
Inputs::MousePointer(MousePointer::new().unwrap())
|
||||
};
|
||||
|
||||
ServerObjects {
|
||||
connection,
|
||||
hmd,
|
||||
play_space,
|
||||
inputs,
|
||||
disable_controllers,
|
||||
disable_hands,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(&mut self, sk: &Sk, token: &MainThreadToken) {
|
||||
let hmd_pose = Input::get_head();
|
||||
self.hmd
|
||||
.0
|
||||
.set_local_transform(Mat4::from_scale_rotation_translation(
|
||||
vec3(1.0, 1.0, 1.0),
|
||||
hmd_pose.orientation.into(),
|
||||
hmd_pose.position.into(),
|
||||
));
|
||||
|
||||
if let Some(play_space) = self.play_space.as_ref() {
|
||||
let pose = World::get_bounds_pose();
|
||||
play_space
|
||||
.0
|
||||
.set_local_transform(Mat4::from_rotation_translation(
|
||||
pose.orientation.into(),
|
||||
pose.position.into(),
|
||||
));
|
||||
}
|
||||
|
||||
if sk.get_active_display_mode() != DisplayMode::MixedReality {
|
||||
if Input::key(Key::F6).is_just_inactive() {
|
||||
self.inputs = Inputs::MousePointer(MousePointer::new().unwrap());
|
||||
}
|
||||
// if Input::key(Key::F7).is_just_inactive() {
|
||||
// self.inputs = Inputs::Controllers((
|
||||
// SkController::new(Handed::Left).unwrap(),
|
||||
// SkController::new(Handed::Right).unwrap(),
|
||||
// ));
|
||||
// }
|
||||
if Input::key(Key::F8).is_just_inactive() {
|
||||
self.inputs = Inputs::Hands {
|
||||
left: SkHand::new(&self.connection, Handed::Left).unwrap(),
|
||||
right: SkHand::new(&self.connection, Handed::Right).unwrap(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
match &mut self.inputs {
|
||||
Inputs::XR {
|
||||
controller_left,
|
||||
controller_right,
|
||||
hand_left,
|
||||
hand_right,
|
||||
eye_pointer,
|
||||
} => {
|
||||
if !self.disable_controllers {
|
||||
controller_left.update(token);
|
||||
controller_right.update(token);
|
||||
}
|
||||
if !self.disable_hands {
|
||||
hand_left.update(sk, token);
|
||||
hand_right.update(sk, token);
|
||||
}
|
||||
if let Some(eye_pointer) = eye_pointer {
|
||||
eye_pointer.update();
|
||||
}
|
||||
}
|
||||
Inputs::MousePointer(mouse_pointer) => mouse_pointer.update(),
|
||||
// Inputs::Controllers((left, right)) => {
|
||||
// left.update(token);
|
||||
// right.update(token);
|
||||
// }
|
||||
Inputs::Hands { left, right } => {
|
||||
left.update(sk, token);
|
||||
right.update(sk, token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ObjectHandle<I: Interface>(Connection, OwnedObjectPath, PhantomData<I>);
|
||||
impl<I: Interface> Drop for ObjectHandle<I> {
|
||||
fn drop(&mut self) {
|
||||
let connection = self.0.clone();
|
||||
let object_path = self.1.clone();
|
||||
tokio::task::spawn(async move {
|
||||
connection.object_server().remove::<I, _>(object_path);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SpatialRef(u64, OwnedNode);
|
||||
impl SpatialRef {
|
||||
pub fn create(connection: &Connection, path: &str) -> (Arc<Spatial>, ObjectHandle<SpatialRef>) {
|
||||
let node = OwnedNode(Arc::new(Node::generate(&INTERNAL_CLIENT, false)));
|
||||
let spatial = Spatial::add_to(&node.0, None, Mat4::IDENTITY, false);
|
||||
let uid: u64 = rand::random();
|
||||
EXPORTED_SPATIALS.lock().insert(uid, node.0.clone());
|
||||
|
||||
tokio::task::spawn({
|
||||
let connection = connection.clone();
|
||||
let path = path.to_string();
|
||||
async move {
|
||||
connection
|
||||
.object_server()
|
||||
.at(path, Self(uid, node))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
(
|
||||
spatial,
|
||||
ObjectHandle(
|
||||
connection.clone(),
|
||||
OwnedObjectPath::try_from(path.to_string()).unwrap(),
|
||||
PhantomData,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
#[interface(name = "org.stardustxr.SpatialRef")]
|
||||
impl SpatialRef {
|
||||
#[zbus(property)]
|
||||
fn uid(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FieldRef(u64, OwnedNode);
|
||||
impl FieldRef {
|
||||
pub fn create(
|
||||
connection: &Connection,
|
||||
path: &str,
|
||||
shape: Shape,
|
||||
) -> (Arc<Field>, ObjectHandle<FieldRef>) {
|
||||
let node = OwnedNode(Arc::new(Node::generate(&INTERNAL_CLIENT, false)));
|
||||
Spatial::add_to(&node.0, None, Mat4::IDENTITY, false);
|
||||
let field = Field::add_to(&node.0, shape).unwrap();
|
||||
let uid: u64 = rand::random();
|
||||
EXPORTED_FIELDS.lock().insert(uid, node.0.clone());
|
||||
|
||||
tokio::task::spawn({
|
||||
let connection = connection.clone();
|
||||
let path = path.to_string();
|
||||
async move {
|
||||
connection
|
||||
.object_server()
|
||||
.at(path, Self(uid, node))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
(
|
||||
field,
|
||||
ObjectHandle(
|
||||
connection.clone(),
|
||||
OwnedObjectPath::try_from(path.to_string()).unwrap(),
|
||||
PhantomData,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
#[interface(name = "org.stardustxr.FieldRef")]
|
||||
impl FieldRef {
|
||||
#[zbus(property)]
|
||||
fn uid(&self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
26
src/objects/play_space.rs
Normal file
26
src/objects/play_space.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
use stereokit_rust::system::World;
|
||||
use zbus::{interface, Connection, ObjectServer};
|
||||
|
||||
pub struct PlaySpaceBounds;
|
||||
impl PlaySpaceBounds {
|
||||
pub async fn create(connection: &Connection) {
|
||||
connection
|
||||
.object_server()
|
||||
.at("/org/stardustxr/PlaySpace", Self)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
#[interface(name = "org.stardustxr.PlaySpace")]
|
||||
impl PlaySpaceBounds {
|
||||
#[zbus(property)]
|
||||
fn bounds(&self) -> Vec<(f64, f64)> {
|
||||
let bounds = World::get_bounds_size();
|
||||
vec![
|
||||
((bounds.x).into(), (bounds.y).into()),
|
||||
((bounds.x).into(), (-bounds.y).into()),
|
||||
((-bounds.x).into(), (-bounds.y).into()),
|
||||
((-bounds.x).into(), (bounds.y).into()),
|
||||
]
|
||||
}
|
||||
}
|
||||
114
src/session.rs
Normal file
114
src/session.rs
Normal file
@@ -0,0 +1,114 @@
|
||||
use crate::core::client::CLIENTS;
|
||||
use crate::core::client_state::ClientStateParsed;
|
||||
#[cfg(feature = "wayland")]
|
||||
use crate::wayland::WAYLAND_DISPLAY;
|
||||
use crate::{CliArgs, STARDUST_INSTANCE};
|
||||
use directories::ProjectDirs;
|
||||
use rustc_hash::FxHashMap;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::Path;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::time::Duration;
|
||||
use tokio::task::LocalSet;
|
||||
use tracing::info;
|
||||
|
||||
pub async fn save_session(project_dirs: &ProjectDirs) {
|
||||
let session_id = nanoid::nanoid!();
|
||||
let state_dir = project_dirs.state_dir().unwrap();
|
||||
let session_dir = state_dir.join(&session_id);
|
||||
std::fs::create_dir_all(&session_dir).unwrap();
|
||||
let _ = std::fs::remove_dir_all(state_dir.join("latest"));
|
||||
std::os::unix::fs::symlink(&session_dir, state_dir.join("latest")).unwrap();
|
||||
|
||||
let local_set = LocalSet::new();
|
||||
for client in CLIENTS.get_vec() {
|
||||
let session_dir = session_dir.clone();
|
||||
local_set.spawn_local(async move {
|
||||
tokio::select! {
|
||||
biased;
|
||||
s = client.save_state() => {if let Some(s) = s { s.to_file(&session_dir) }},
|
||||
_ = tokio::time::sleep(Duration::from_millis(100)) => (),
|
||||
}
|
||||
});
|
||||
}
|
||||
local_set.await;
|
||||
info!("Session ID for restore is {session_id}");
|
||||
}
|
||||
|
||||
pub fn launch_start(cli_args: &CliArgs, project_dirs: &ProjectDirs) -> Vec<Child> {
|
||||
match (&cli_args.restore, &cli_args.startup_script) {
|
||||
(Some(session_id), _) => restore_session(
|
||||
&project_dirs.state_dir().unwrap().join(session_id),
|
||||
cli_args.debug_launched_clients,
|
||||
),
|
||||
(None, Some(startup_script)) => run_script(
|
||||
&startup_script.clone().canonicalize().unwrap_or_default(),
|
||||
cli_args.debug_launched_clients,
|
||||
),
|
||||
(None, None) => run_script(
|
||||
&project_dirs.config_dir().join("startup"),
|
||||
cli_args.debug_launched_clients,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn restore_session(session_dir: &Path, debug_launched_clients: bool) -> Vec<Child> {
|
||||
let Ok(clients) = session_dir.read_dir() else {
|
||||
return Vec::new();
|
||||
};
|
||||
clients
|
||||
.filter_map(Result::ok)
|
||||
.filter_map(|c| ClientStateParsed::from_file(&c.path()))
|
||||
.filter_map(ClientStateParsed::launch_command)
|
||||
.filter_map(|c| run_client(c, debug_launched_clients))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn run_script(script_path: &Path, debug_launched_clients: bool) -> Vec<Child> {
|
||||
let _ = std::fs::set_permissions(script_path, std::fs::Permissions::from_mode(0o755));
|
||||
let startup_command = Command::new(script_path);
|
||||
run_client(startup_command, debug_launched_clients)
|
||||
.map(|c| vec![c])
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn run_client(mut command: Command, debug_launched_clients: bool) -> Option<Child> {
|
||||
command.stdin(Stdio::null());
|
||||
if !debug_launched_clients {
|
||||
command.stdout(Stdio::null());
|
||||
command.stderr(Stdio::null());
|
||||
}
|
||||
for (var, value) in connection_env() {
|
||||
command.env(var, value);
|
||||
}
|
||||
let child = command.spawn().ok()?;
|
||||
Some(child)
|
||||
}
|
||||
|
||||
pub fn connection_env() -> FxHashMap<String, String> {
|
||||
macro_rules! var_env_insert {
|
||||
($env:ident, $name:ident) => {
|
||||
$env.insert(stringify!($name).to_string(), $name.get().unwrap().clone());
|
||||
};
|
||||
}
|
||||
|
||||
let mut env: FxHashMap<String, String> = FxHashMap::default();
|
||||
var_env_insert!(env, STARDUST_INSTANCE);
|
||||
|
||||
if let Some(flat_wayland_display) = std::env::var_os("WAYLAND_DISPLAY") {
|
||||
env.insert(
|
||||
"FLAT_WAYLAND_DISPLAY".to_string(),
|
||||
flat_wayland_display.to_string_lossy().into_owned(),
|
||||
);
|
||||
}
|
||||
#[cfg(feature = "wayland")]
|
||||
{
|
||||
var_env_insert!(env, WAYLAND_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());
|
||||
}
|
||||
env
|
||||
}
|
||||
@@ -1,9 +1,25 @@
|
||||
use super::{state::WaylandState, surface::CoreSurface};
|
||||
use smithay::{
|
||||
delegate_compositor,
|
||||
reexports::wayland_server::protocol::wl_surface::WlSurface,
|
||||
wayland::compositor::{self, CompositorHandler, CompositorState},
|
||||
use super::{
|
||||
state::{ClientState, WaylandState},
|
||||
utils::{ChildInfoExt, WlSurfaceExt},
|
||||
xdg_shell::surface_panel_item,
|
||||
};
|
||||
use crate::{
|
||||
nodes::items::panel::{ChildInfo, Geometry, SurfaceId},
|
||||
wayland::surface::CoreSurface,
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
use portable_atomic::{AtomicU32, Ordering};
|
||||
use rand::Rng;
|
||||
use smithay::{
|
||||
backend::renderer::utils::{on_commit_buffer_handler, RendererSurfaceStateUserData},
|
||||
delegate_compositor,
|
||||
reexports::wayland_server::{protocol::wl_surface::WlSurface, Client},
|
||||
wayland::compositor::{
|
||||
self, add_post_commit_hook, CompositorClientState, CompositorHandler, CompositorState,
|
||||
},
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use tracing::debug;
|
||||
|
||||
impl CompositorHandler for WaylandState {
|
||||
fn compositor_state(&mut self) -> &mut CompositorState {
|
||||
@@ -11,17 +27,101 @@ impl CompositorHandler for WaylandState {
|
||||
}
|
||||
|
||||
fn commit(&mut self, surface: &WlSurface) {
|
||||
debug!(?surface, "Surface commit");
|
||||
|
||||
on_commit_buffer_handler::<WaylandState>(surface);
|
||||
let mut count = 0;
|
||||
compositor::with_states(surface, |data| {
|
||||
data.data_map.insert_if_missing_threadsafe(|| {
|
||||
CoreSurface::new(
|
||||
&self.weak_ref.upgrade().unwrap(),
|
||||
&self.display,
|
||||
self.display_handle.clone(),
|
||||
surface,
|
||||
)
|
||||
})
|
||||
let count_new = data
|
||||
.data_map
|
||||
.insert_if_missing_threadsafe(|| AtomicU32::new(0));
|
||||
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()
|
||||
});
|
||||
}
|
||||
|
||||
fn client_compositor_state<'a>(&self, client: &'a Client) -> &'a CompositorClientState {
|
||||
&client.get_data::<ClientState>().unwrap().compositor_state
|
||||
}
|
||||
|
||||
fn new_subsurface(&mut self, surface: &WlSurface, parent: &WlSurface) {
|
||||
let id = rand::thread_rng().gen_range(0..u64::MAX);
|
||||
surface.insert_data(SurfaceId::Child(id));
|
||||
CoreSurface::add_to(surface);
|
||||
let Some(parent_surface_id) = parent.get_data::<SurfaceId>() else {
|
||||
return;
|
||||
};
|
||||
surface.insert_data(Mutex::new(ChildInfo {
|
||||
id,
|
||||
parent: parent_surface_id,
|
||||
geometry: Geometry {
|
||||
origin: [0; 2].into(),
|
||||
size: [256; 2].into(),
|
||||
},
|
||||
z_order: 1,
|
||||
receives_input: false,
|
||||
}));
|
||||
|
||||
let Some(panel_item) = surface_panel_item(parent) else {
|
||||
return;
|
||||
};
|
||||
let panel_item_weak = Arc::downgrade(&panel_item);
|
||||
add_post_commit_hook(surface, move |_: &mut WaylandState, _dh, surf| {
|
||||
if surface_panel_item(surf).is_some() {
|
||||
return;
|
||||
}
|
||||
surf.insert_data(panel_item_weak.clone());
|
||||
|
||||
let Some(panel_item) = surface_panel_item(surf) else {
|
||||
return;
|
||||
};
|
||||
panel_item.backend.new_child(surf);
|
||||
});
|
||||
|
||||
add_post_commit_hook(surface, move |_: &mut WaylandState, _dh, surf| {
|
||||
let Some(view) = surf
|
||||
.get_data_raw::<RendererSurfaceStateUserData, _, _>(|s| s.lock().ok()?.view())
|
||||
.flatten()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut changed = false;
|
||||
surf.with_child_info(|info| {
|
||||
if info.geometry.origin.x != view.offset.x
|
||||
&& info.geometry.origin.y != view.offset.y
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
if info.geometry.size.x != view.dst.w as u32
|
||||
&& info.geometry.size.y != view.dst.h as u32
|
||||
{
|
||||
changed = true;
|
||||
}
|
||||
info.geometry.size = [view.dst.w as u32, view.dst.h as u32].into();
|
||||
});
|
||||
|
||||
let Some(panel_item) = surface_panel_item(surf) else {
|
||||
return;
|
||||
};
|
||||
if changed {
|
||||
panel_item.backend.reposition_child(surf);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn destroyed(&mut self, surface: &WlSurface) {
|
||||
let Some(panel_item) = surface_panel_item(surface) else {
|
||||
return;
|
||||
};
|
||||
if surface.get_child_info().is_some() {
|
||||
panel_item.backend.drop_child(surface);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
delegate_compositor!(WaylandState);
|
||||
|
||||
@@ -1,34 +1,97 @@
|
||||
use super::state::WaylandState;
|
||||
use smithay::{
|
||||
delegate_kde_decoration, delegate_xdg_decoration,
|
||||
reexports::wayland_protocols::xdg::decoration::zv1::server::zxdg_toplevel_decoration_v1::Mode,
|
||||
wayland::shell::{
|
||||
self, kde::decoration::KdeDecorationHandler, xdg::decoration::XdgDecorationHandler,
|
||||
delegate_kde_decoration,
|
||||
reexports::{
|
||||
wayland_protocols::xdg::{
|
||||
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 {
|
||||
fn new_decoration(&mut self, toplevel: smithay::wayland::shell::xdg::ToplevelSurface) {
|
||||
toplevel.with_pending_state(|state| {
|
||||
state.decoration_mode = Some(Mode::ServerSide);
|
||||
});
|
||||
toplevel.send_configure();
|
||||
}
|
||||
|
||||
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,
|
||||
impl GlobalDispatch<ZxdgDecorationManagerV1, (), WaylandState> for WaylandState {
|
||||
fn bind(
|
||||
_state: &mut WaylandState,
|
||||
_handle: &DisplayHandle,
|
||||
_client: &Client,
|
||||
resource: New<ZxdgDecorationManagerV1>,
|
||||
_global_data: &(),
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
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 {
|
||||
fn kde_decoration_state(&self) -> &shell::kde::decoration::KdeDecorationState {
|
||||
&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);
|
||||
|
||||
144
src/wayland/drm.rs
Normal file
144
src/wayland/drm.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// Re-export only the actual code, and then only use this re-export
|
||||
// The `generated` module below is just some boilerplate to properly isolate stuff
|
||||
// and avoid exposing internal details.
|
||||
//
|
||||
// You can use all the types from my_protocol as if they went from `wayland_client::protocol`.
|
||||
pub use generated::wl_drm;
|
||||
|
||||
#[allow(non_upper_case_globals, non_camel_case_types)]
|
||||
mod generated {
|
||||
use smithay::reexports::wayland_server::{self, protocol::*};
|
||||
|
||||
pub mod __interfaces {
|
||||
use smithay::reexports::wayland_server::protocol::__interfaces::*;
|
||||
wayland_scanner::generate_interfaces!("src/wayland/wayland-drm.xml");
|
||||
}
|
||||
use self::__interfaces::*;
|
||||
|
||||
wayland_scanner::generate_server_code!("src/wayland/wayland-drm.xml");
|
||||
}
|
||||
|
||||
use super::state::WaylandState;
|
||||
use smithay::{
|
||||
backend::allocator::{
|
||||
dmabuf::{Dmabuf, DmabufFlags},
|
||||
Fourcc, Modifier,
|
||||
},
|
||||
reexports::wayland_server::{
|
||||
Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource,
|
||||
},
|
||||
};
|
||||
use std::convert::TryFrom;
|
||||
|
||||
impl GlobalDispatch<wl_drm::WlDrm, (), WaylandState> for WaylandState {
|
||||
fn bind(
|
||||
state: &mut WaylandState,
|
||||
_dh: &DisplayHandle,
|
||||
_client: &Client,
|
||||
resource: New<wl_drm::WlDrm>,
|
||||
_global_data: &(),
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
let drm_instance = data_init.init(resource, ());
|
||||
|
||||
drm_instance.device("/dev/dri/renderD128".to_string());
|
||||
if drm_instance.version() >= 2 {
|
||||
drm_instance.capabilities(wl_drm::Capability::Prime as u32);
|
||||
}
|
||||
for format in state.drm_formats.iter() {
|
||||
if let Ok(converted) = wl_drm::Format::try_from(*format as u32) {
|
||||
drm_instance.format(converted as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn can_view(_client: Client, _global_dataa: &()) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<wl_drm::WlDrm, (), WaylandState> for WaylandState {
|
||||
fn request(
|
||||
state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
drm: &wl_drm::WlDrm,
|
||||
request: wl_drm::Request,
|
||||
_data: &(),
|
||||
_dh: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
match request {
|
||||
wl_drm::Request::Authenticate { .. } => drm.authenticated(),
|
||||
wl_drm::Request::CreateBuffer { .. } => drm.post_error(
|
||||
wl_drm::Error::InvalidName,
|
||||
String::from("Flink handles are unsupported, use PRIME"),
|
||||
),
|
||||
wl_drm::Request::CreatePlanarBuffer { .. } => drm.post_error(
|
||||
wl_drm::Error::InvalidName,
|
||||
String::from("Flink handles are unsupported, use PRIME"),
|
||||
),
|
||||
wl_drm::Request::CreatePrimeBuffer {
|
||||
id,
|
||||
name,
|
||||
width,
|
||||
height,
|
||||
format,
|
||||
offset0,
|
||||
stride0,
|
||||
..
|
||||
} => {
|
||||
let format = match Fourcc::try_from(format) {
|
||||
Ok(format) => {
|
||||
if !state.drm_formats.contains(&format) {
|
||||
drm.post_error(
|
||||
wl_drm::Error::InvalidFormat,
|
||||
String::from("Format not advertised by wl_drm"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
format
|
||||
}
|
||||
Err(_) => {
|
||||
drm.post_error(
|
||||
wl_drm::Error::InvalidFormat,
|
||||
String::from("Format unknown / not advertised by wl_drm"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if width < 1 || height < 1 {
|
||||
drm.post_error(
|
||||
wl_drm::Error::InvalidFormat,
|
||||
String::from("width or height not positive"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let mut dma = Dmabuf::builder(
|
||||
(width, height),
|
||||
format,
|
||||
Modifier::Invalid,
|
||||
DmabufFlags::empty(),
|
||||
);
|
||||
dma.add_plane(name, 0, offset0 as u32, stride0 as u32);
|
||||
match dma.build() {
|
||||
Some(dmabuf) => {
|
||||
state.dmabuf_tx.send((dmabuf.clone(), None)).unwrap();
|
||||
data_init.init(id, dmabuf);
|
||||
}
|
||||
None => {
|
||||
// Buffer import failed. The protocol documentation heavily implies killing the
|
||||
// client is the right thing to do here.
|
||||
drm.post_error(
|
||||
wl_drm::Error::InvalidName,
|
||||
"dmabuf global was destroyed on server",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,38 +1,45 @@
|
||||
pub mod compositor;
|
||||
mod compositor;
|
||||
mod data_device;
|
||||
pub mod decoration;
|
||||
pub mod panel_item;
|
||||
pub mod seat;
|
||||
pub mod shaders;
|
||||
pub mod state;
|
||||
pub mod surface;
|
||||
pub mod xdg_activation;
|
||||
pub mod xdg_shell;
|
||||
mod decoration;
|
||||
mod seat;
|
||||
mod state;
|
||||
mod surface;
|
||||
// mod xdg_activation;
|
||||
mod drm;
|
||||
mod utils;
|
||||
mod xdg_shell;
|
||||
|
||||
use self::{panel_item::PanelItem, state::WaylandState, surface::CORE_SURFACES};
|
||||
use crate::wayland::state::ClientState;
|
||||
use anyhow::{ensure, Result};
|
||||
use self::{state::WaylandState, surface::CORE_SURFACES};
|
||||
use crate::{core::task, wayland::state::ClientState};
|
||||
use color_eyre::eyre::{ensure, Result};
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use slog::Logger;
|
||||
use smithay::{
|
||||
backend::{egl::EGLContext, renderer::gles2::Gles2Renderer},
|
||||
reexports::wayland_server::{backend::GlobalId, Display, ListeningSocket, Resource},
|
||||
};
|
||||
use smithay::backend::allocator::dmabuf::Dmabuf;
|
||||
use smithay::backend::egl::EGLContext;
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::backend::renderer::{ImportDma, Renderer};
|
||||
use smithay::output::Output;
|
||||
use smithay::reexports::wayland_server::backend::ClientId;
|
||||
use smithay::reexports::wayland_server::DisplayHandle;
|
||||
use smithay::reexports::wayland_server::{Display, ListeningSocket};
|
||||
use smithay::wayland::dmabuf;
|
||||
use std::ffi::OsStr;
|
||||
use std::os::fd::{IntoRawFd, OwnedFd};
|
||||
use std::os::unix::prelude::AsRawFd;
|
||||
use std::{
|
||||
ffi::c_void,
|
||||
os::unix::{
|
||||
net::UnixListener,
|
||||
prelude::{FromRawFd, RawFd},
|
||||
},
|
||||
os::unix::{net::UnixListener, prelude::FromRawFd},
|
||||
sync::Arc,
|
||||
};
|
||||
use stereokit as sk;
|
||||
use stereokit::StereoKit;
|
||||
use stereokit_rust::system::{Backend, BackendGraphics};
|
||||
use tokio::io::unix::AsyncFdReadyGuard;
|
||||
use tokio::sync::mpsc::UnboundedReceiver;
|
||||
use tokio::{
|
||||
io::unix::AsyncFd, net::UnixListener as AsyncUnixListener, sync::mpsc, task::JoinHandle,
|
||||
};
|
||||
use tracing::{debug_span, info, instrument};
|
||||
|
||||
pub static WAYLAND_DISPLAY: OnceCell<String> = OnceCell::new();
|
||||
|
||||
struct EGLRawHandles {
|
||||
display: *const c_void,
|
||||
@@ -41,136 +48,167 @@ struct EGLRawHandles {
|
||||
}
|
||||
fn get_sk_egl() -> Result<EGLRawHandles> {
|
||||
ensure!(
|
||||
unsafe { sk::sys::backend_graphics_get() }
|
||||
== sk::sys::backend_graphics__backend_graphics_opengles_egl,
|
||||
Backend::graphics() == BackendGraphics::OpenGLESEGL,
|
||||
"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,
|
||||
display: stereokit_rust::system::backend_opengl_egl_get_display() as *const c_void,
|
||||
config: stereokit_rust::system::backend_opengl_egl_get_config() as *const c_void,
|
||||
context: stereokit_rust::system::backend_opengl_egl_get_context() as *const c_void,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
static GLOBAL_DESTROY_QUEUE: OnceCell<mpsc::Sender<GlobalId>> = OnceCell::new();
|
||||
pub struct DisplayWrapper(Mutex<Display<WaylandState>>, DisplayHandle);
|
||||
impl DisplayWrapper {
|
||||
pub fn handle(&self) -> DisplayHandle {
|
||||
self.1.clone()
|
||||
}
|
||||
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()
|
||||
}
|
||||
}
|
||||
|
||||
struct UnownedFd(Option<AsyncFd<OwnedFd>>);
|
||||
impl UnownedFd {
|
||||
async fn readable(&self) -> std::io::Result<AsyncFdReadyGuard<'_, OwnedFd>> {
|
||||
self.0.as_ref().unwrap().readable().await
|
||||
}
|
||||
}
|
||||
impl Drop for UnownedFd {
|
||||
fn drop(&mut self) {
|
||||
self.0.take().unwrap().into_inner().into_raw_fd();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Wayland {
|
||||
log: slog::Logger,
|
||||
|
||||
display: Arc<Mutex<Display<WaylandState>>>,
|
||||
display: Arc<DisplayWrapper>,
|
||||
pub socket_name: Option<String>,
|
||||
join_handle: JoinHandle<Result<()>>,
|
||||
renderer: Gles2Renderer,
|
||||
state: Arc<Mutex<WaylandState>>,
|
||||
renderer: GlesRenderer,
|
||||
output: Output,
|
||||
dmabuf_rx: UnboundedReceiver<(Dmabuf, Option<dmabuf::ImportNotifier>)>,
|
||||
}
|
||||
impl Wayland {
|
||||
pub fn new(log: Logger) -> Result<Self> {
|
||||
pub fn new() -> 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(),
|
||||
)?
|
||||
GlesRenderer::new(EGLContext::from_raw(
|
||||
egl_raw_handles.display,
|
||||
egl_raw_handles.config,
|
||||
egl_raw_handles.context,
|
||||
)?)?
|
||||
};
|
||||
|
||||
let display: Display<WaylandState> = Display::new()?;
|
||||
let display_handle = display.handle();
|
||||
|
||||
let display = Arc::new(Mutex::new(display));
|
||||
let state = WaylandState::new(log.clone(), display.clone(), display_handle);
|
||||
let (dmabuf_tx, dmabuf_rx) = mpsc::unbounded_channel();
|
||||
let display = Arc::new(DisplayWrapper(Mutex::new(display), display_handle.clone()));
|
||||
|
||||
let (global_destroy_queue_in, global_destroy_queue) = mpsc::channel(8);
|
||||
GLOBAL_DESTROY_QUEUE.set(global_destroy_queue_in).unwrap();
|
||||
let wayland_state = WaylandState::new(display_handle.clone(), &renderer, dmabuf_tx);
|
||||
let output = wayland_state.lock().output.clone();
|
||||
|
||||
let join_handle =
|
||||
Wayland::start_loop(display.clone(), state.clone(), global_destroy_queue)?;
|
||||
let socket = ListeningSocket::bind_auto("wayland", 0..33)?;
|
||||
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 = Wayland::start_loop(display.clone(), socket, wayland_state)?;
|
||||
|
||||
Ok(Wayland {
|
||||
log,
|
||||
display,
|
||||
socket_name,
|
||||
join_handle,
|
||||
renderer,
|
||||
state,
|
||||
output,
|
||||
dmabuf_rx,
|
||||
})
|
||||
}
|
||||
|
||||
fn start_loop(
|
||||
display: Arc<Mutex<Display<WaylandState>>>,
|
||||
display: Arc<DisplayWrapper>,
|
||||
socket: ListeningSocket,
|
||||
state: Arc<Mutex<WaylandState>>,
|
||||
mut global_destroy_queue: mpsc::Receiver<GlobalId>,
|
||||
) -> 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 =
|
||||
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_listener = AsyncFd::new(dispatch_poll_fd)?;
|
||||
let dispatch_poll_fd = display.poll_fd()?;
|
||||
let dispatch_poll_listener = UnownedFd(Some(AsyncFd::new(dispatch_poll_fd)?));
|
||||
|
||||
let dh1 = display.lock().handle();
|
||||
let dh1 = display.handle();
|
||||
let mut dh2 = dh1.clone();
|
||||
|
||||
Ok(tokio::task::spawn(async move {
|
||||
task::new(|| "wayland loop", async move {
|
||||
let _socket = socket; // Keep the socket alive
|
||||
loop {
|
||||
tokio::select! {
|
||||
e = global_destroy_queue.recv() => { // New global to destroy
|
||||
dh1.remove_global::<WaylandState>(e.unwrap());
|
||||
}
|
||||
acc = listen_async.accept() => { // New client connected
|
||||
let (stream, _) = acc?;
|
||||
let client = dh2.insert_client(stream.into_std()?, Arc::new(ClientState))?;
|
||||
|
||||
state.lock().new_client(client.id(), &dh2);
|
||||
let client_state = Arc::new(ClientState {
|
||||
pid: stream.peer_cred().ok().and_then(|c| c.pid()),
|
||||
id: OnceCell::new(),
|
||||
compositor_state: Default::default(),
|
||||
seat: state.lock().seat.clone(),
|
||||
});
|
||||
let _client = dh2.insert_client(stream.into_std()?, client_state.clone())?;
|
||||
}
|
||||
e = dispatch_poll_listener.readable() => { // Dispatch
|
||||
let mut guard = e?;
|
||||
let mut display = display.lock();
|
||||
display.dispatch_clients(&mut *state.lock())?;
|
||||
display.flush_clients()?;
|
||||
debug_span!("Dispatch wayland event").in_scope(|| -> Result<(), color_eyre::Report> {
|
||||
display.dispatch_clients(&mut state.lock())?;
|
||||
display.flush_clients(None);
|
||||
Ok(())
|
||||
})?;
|
||||
guard.clear_ready();
|
||||
}
|
||||
}
|
||||
}
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn frame(&mut self, sk: &StereoKit) {
|
||||
let time_ms = (sk.time_getf() * 1000.) as u32;
|
||||
|
||||
for core_surface in CORE_SURFACES.get_valid_contents() {
|
||||
let client_id = core_surface.wl_surface().client_id().unwrap();
|
||||
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);
|
||||
},
|
||||
);
|
||||
#[instrument(level = "debug", name = "Wayland frame", skip(self))]
|
||||
pub fn update(&mut self) {
|
||||
while let Ok((dmabuf, notifier)) = self.dmabuf_rx.try_recv() {
|
||||
if self.renderer.import_dmabuf(&dmabuf, None).is_err() {
|
||||
if let Some(notifier) = notifier {
|
||||
notifier.failed();
|
||||
}
|
||||
}
|
||||
}
|
||||
for core_surface in CORE_SURFACES.get_valid_contents() {
|
||||
core_surface.process(&mut self.renderer);
|
||||
}
|
||||
let _ = self.renderer.cleanup_texture_cache();
|
||||
|
||||
self.display.lock().flush_clients().unwrap();
|
||||
self.display.flush_clients(None);
|
||||
}
|
||||
|
||||
pub fn frame_event(&self) {
|
||||
for core_surface in CORE_SURFACES.get_valid_contents() {
|
||||
core_surface.frame(self.output.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn make_context_current(&self) {
|
||||
unsafe {
|
||||
self.renderer.egl_context().make_current().unwrap();
|
||||
let _ = self.renderer.egl_context().make_current();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,284 +1,307 @@
|
||||
use super::{state::WaylandState, surface::CoreSurface, GLOBAL_DESTROY_QUEUE};
|
||||
use crate::nodes::items::Item;
|
||||
use anyhow::Result;
|
||||
use mint::Vector2;
|
||||
use nanoid::nanoid;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use smithay::{
|
||||
input::keyboard::{KeymapFile, ModifiersState},
|
||||
reexports::wayland_server::{
|
||||
backend::{ClientId, GlobalId},
|
||||
delegate_dispatch, delegate_global_dispatch,
|
||||
protocol::{
|
||||
wl_keyboard::{self, KeyState, WlKeyboard},
|
||||
wl_pointer::{self, WlPointer},
|
||||
wl_seat::{self, Capability, WlSeat, EVT_NAME_SINCE},
|
||||
wl_touch::{self, WlTouch},
|
||||
},
|
||||
Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource,
|
||||
use super::{state::WaylandState, surface::CoreSurface, utils::WlSurfaceExt};
|
||||
use crate::{
|
||||
core::task,
|
||||
nodes::{
|
||||
data::KEYMAPS,
|
||||
items::panel::{Backend, Geometry, PanelItem},
|
||||
},
|
||||
};
|
||||
use mint::Vector2;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
use slotmap::KeyData;
|
||||
use smithay::{
|
||||
backend::input::{AxisRelativeDirection, ButtonState, KeyState},
|
||||
delegate_seat,
|
||||
input::{
|
||||
keyboard::{FilterResult, LedState},
|
||||
pointer::{AxisFrame, ButtonEvent, CursorImageStatus, MotionEvent},
|
||||
touch::{self, DownEvent, UpEvent},
|
||||
Seat, SeatHandler,
|
||||
},
|
||||
reexports::wayland_server::{protocol::wl_surface::WlSurface, Resource, Weak as WlWeak},
|
||||
utils::SERIAL_COUNTER,
|
||||
wayland::compositor,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use std::{ops::Deref, sync::Weak};
|
||||
use xkbcommon::xkb::{self, Keymap};
|
||||
use std::sync::{Arc, Weak};
|
||||
use tokio::sync::watch;
|
||||
|
||||
pub struct Cursor {
|
||||
pub core_surface: Weak<CoreSurface>,
|
||||
pub hotspot: Vector2<i32>,
|
||||
impl SeatHandler for WaylandState {
|
||||
type PointerFocus = WlSurface;
|
||||
type KeyboardFocus = WlSurface;
|
||||
type TouchFocus = WlSurface;
|
||||
|
||||
fn seat_state(&mut self) -> &mut smithay::input::SeatState<Self> {
|
||||
&mut self.seat_state
|
||||
}
|
||||
fn focus_changed(&mut self, _seat: &Seat<Self>, _focused: Option<&Self::KeyboardFocus>) {}
|
||||
fn cursor_image(&mut self, _seat: &Seat<Self>, image: CursorImageStatus) {
|
||||
self.seat.cursor_info_tx.send_modify(|c| match image {
|
||||
CursorImageStatus::Hidden => c.surface = None,
|
||||
CursorImageStatus::Surface(surface) => {
|
||||
CoreSurface::add_to(&surface);
|
||||
compositor::with_states(&surface, |data| {
|
||||
if let Some(core_surface) = data.data_map.get::<Arc<CoreSurface>>() {
|
||||
core_surface.set_material_offset(1);
|
||||
}
|
||||
});
|
||||
c.surface = Some(surface.downgrade())
|
||||
}
|
||||
_ => (),
|
||||
});
|
||||
}
|
||||
fn led_state_changed(&mut self, _seat: &Seat<Self>, _led_state: LedState) {}
|
||||
}
|
||||
delegate_seat!(WaylandState);
|
||||
|
||||
pub fn handle_cursor<B: Backend>(
|
||||
panel_item: &Arc<PanelItem<B>>,
|
||||
mut cursor: watch::Receiver<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.cursor_data());
|
||||
}
|
||||
});
|
||||
}
|
||||
pub struct CursorInfo {
|
||||
pub surface: Option<WlWeak<WlSurface>>,
|
||||
pub hotspot_x: i32,
|
||||
pub hotspot_y: i32,
|
||||
}
|
||||
impl CursorInfo {
|
||||
pub fn cursor_data(&self) -> Option<Geometry> {
|
||||
let cursor_size = self.surface.as_ref()?.upgrade().ok()?.get_size()?;
|
||||
Some(Geometry {
|
||||
origin: [self.hotspot_x, self.hotspot_y].into(),
|
||||
size: cursor_size,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct KeyboardInfo {
|
||||
pub keymap: KeymapFile,
|
||||
pub state: xkb::State,
|
||||
pub mods: ModifiersState,
|
||||
pub struct SeatWrapper {
|
||||
wayland_state: Weak<Mutex<WaylandState>>,
|
||||
cursor_info_tx: watch::Sender<CursorInfo>,
|
||||
pub cursor_info_rx: watch::Receiver<CursorInfo>,
|
||||
seat: Seat<WaylandState>,
|
||||
touches: Mutex<FxHashMap<u32, WlWeak<WlSurface>>>,
|
||||
}
|
||||
impl KeyboardInfo {
|
||||
pub fn new(keymap: &Keymap) -> Self {
|
||||
KeyboardInfo {
|
||||
state: xkb::State::new(keymap),
|
||||
keymap: KeymapFile::new(keymap, None),
|
||||
mods: ModifiersState::default(),
|
||||
impl SeatWrapper {
|
||||
pub fn new(wayland_state: Weak<Mutex<WaylandState>>, seat: Seat<WaylandState>) -> Self {
|
||||
let (cursor_info_tx, cursor_info_rx) = watch::channel(CursorInfo {
|
||||
surface: None,
|
||||
hotspot_x: 0,
|
||||
hotspot_y: 0,
|
||||
});
|
||||
SeatWrapper {
|
||||
wayland_state,
|
||||
cursor_info_tx,
|
||||
cursor_info_rx,
|
||||
seat,
|
||||
touches: Mutex::new(FxHashMap::default()),
|
||||
}
|
||||
}
|
||||
pub fn process(&mut self, key: u32, state: u32, keyboard: &WlKeyboard) -> Result<()> {
|
||||
let wl_key_state = match state {
|
||||
0 => KeyState::Released,
|
||||
1 => KeyState::Pressed,
|
||||
_ => anyhow::bail!("Invalid key state!"),
|
||||
pub fn unfocus(&self, surface: &WlSurface, state: &mut WaylandState) {
|
||||
let pointer = self.seat.get_pointer().unwrap();
|
||||
if pointer.current_focus() == Some(surface.clone()) {
|
||||
pointer.motion(
|
||||
state,
|
||||
None,
|
||||
&MotionEvent {
|
||||
location: (0.0, 0.0).into(),
|
||||
serial: SERIAL_COUNTER.next_serial(),
|
||||
time: 0,
|
||||
},
|
||||
)
|
||||
}
|
||||
let keyboard = self.seat.get_keyboard().unwrap();
|
||||
if keyboard.current_focus() == Some(surface.clone()) {
|
||||
keyboard.set_focus(state, None, SERIAL_COUNTER.next_serial());
|
||||
}
|
||||
for (id, touch_surface) in self.touches.lock().iter() {
|
||||
if touch_surface.id() == surface.id() {
|
||||
self.touch_up(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pointer_motion(&self, surface: WlSurface, position: Vector2<f32>) {
|
||||
let Some(state) = self.wayland_state.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let xkb_key_state = match state {
|
||||
0 => xkb::KeyDirection::Up,
|
||||
1 => xkb::KeyDirection::Down,
|
||||
_ => anyhow::bail!("Invalid key state!"),
|
||||
let mut state = state.lock();
|
||||
let Some(pointer) = self.seat.get_pointer() else {
|
||||
return;
|
||||
};
|
||||
let state_components = self.state.update_key(key + 8, xkb_key_state);
|
||||
if state_components != 0 {
|
||||
self.mods.update_with(&self.state);
|
||||
keyboard.modifiers(
|
||||
0,
|
||||
self.mods.serialized.depressed,
|
||||
self.mods.serialized.latched,
|
||||
self.mods.serialized.locked,
|
||||
pointer.motion(
|
||||
&mut state,
|
||||
Some((surface, (0.0, 0.0).into())),
|
||||
&MotionEvent {
|
||||
location: (position.x as f64, position.y as f64).into(),
|
||||
serial: SERIAL_COUNTER.next_serial(),
|
||||
time: 0,
|
||||
},
|
||||
);
|
||||
pointer.frame(&mut state);
|
||||
}
|
||||
pub fn pointer_button(&self, button: u32, pressed: bool) {
|
||||
let Some(state) = self.wayland_state.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let mut state = state.lock();
|
||||
let Some(pointer) = self.seat.get_pointer() else {
|
||||
return;
|
||||
};
|
||||
pointer.button(
|
||||
&mut state,
|
||||
&ButtonEvent {
|
||||
button,
|
||||
state: if pressed {
|
||||
ButtonState::Pressed
|
||||
} else {
|
||||
ButtonState::Released
|
||||
},
|
||||
serial: SERIAL_COUNTER.next_serial(),
|
||||
time: 0,
|
||||
},
|
||||
);
|
||||
pointer.frame(&mut state);
|
||||
}
|
||||
pub fn pointer_scroll(
|
||||
&self,
|
||||
scroll_distance: Option<Vector2<f32>>,
|
||||
scroll_steps: Option<Vector2<f32>>,
|
||||
) {
|
||||
let Some(state) = self.wayland_state.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let mut state = state.lock();
|
||||
let Some(pointer) = self.seat.get_pointer() else {
|
||||
return;
|
||||
};
|
||||
pointer.axis(
|
||||
&mut state,
|
||||
AxisFrame {
|
||||
source: None,
|
||||
relative_direction: (
|
||||
AxisRelativeDirection::Identical,
|
||||
AxisRelativeDirection::Identical,
|
||||
),
|
||||
time: 0,
|
||||
axis: scroll_distance
|
||||
.map(|d| (d.x as f64, d.y as f64))
|
||||
.unwrap_or((0.0, 0.0)),
|
||||
v120: scroll_steps.map(|d| ((d.x * 120.0) as i32, (d.y * 120.0) as i32)),
|
||||
stop: (false, false),
|
||||
},
|
||||
);
|
||||
pointer.frame(&mut state);
|
||||
}
|
||||
|
||||
pub fn keyboard_keys(&self, surface: WlSurface, keymap_id: u64, keys: Vec<i32>) {
|
||||
let Some(state) = self.wayland_state.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(keyboard) = self.seat.get_keyboard() else {
|
||||
return;
|
||||
};
|
||||
let keymaps = KEYMAPS.lock();
|
||||
let Some(keymap) = keymaps.get(KeyData::from_ffi(keymap_id).into()).cloned() else {
|
||||
return;
|
||||
};
|
||||
|
||||
keyboard.set_focus(
|
||||
&mut state.lock(),
|
||||
Some(surface),
|
||||
SERIAL_COUNTER.next_serial(),
|
||||
);
|
||||
if keyboard
|
||||
.set_keymap_from_string(&mut state.lock(), keymap)
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
for key in keys {
|
||||
keyboard.input(
|
||||
&mut state.lock(),
|
||||
key.unsigned_abs(),
|
||||
if key > 0 {
|
||||
KeyState::Pressed
|
||||
} else {
|
||||
KeyState::Released
|
||||
},
|
||||
SERIAL_COUNTER.next_serial(),
|
||||
0,
|
||||
|_, _, _| FilterResult::Forward::<()>,
|
||||
);
|
||||
}
|
||||
keyboard.key(0, 0, key, wl_key_state);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
unsafe impl Send for KeyboardInfo {}
|
||||
|
||||
pub struct SeatDelegate;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SeatData(Arc<SeatDataInner>);
|
||||
impl SeatData {
|
||||
pub fn new(dh: &DisplayHandle, client: ClientId) -> Self {
|
||||
let seat_data = SeatData(Arc::new(SeatDataInner {
|
||||
client,
|
||||
global_id: OnceCell::new(),
|
||||
panel_item: OnceCell::new(),
|
||||
cursor: Mutex::new(None),
|
||||
cursor_changed: Mutex::new(false),
|
||||
pointer: OnceCell::new(),
|
||||
pointer_active: Mutex::new(false),
|
||||
keyboard: OnceCell::new(),
|
||||
keyboard_info: Mutex::new(None),
|
||||
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 {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SeatDataInner {
|
||||
client: ClientId,
|
||||
pub global_id: OnceCell<GlobalId>,
|
||||
pub panel_item: OnceCell<Weak<Item>>,
|
||||
pub cursor: Mutex<Option<Arc<Mutex<Cursor>>>>,
|
||||
pub cursor_changed: Mutex<bool>,
|
||||
pointer: OnceCell<WlPointer>,
|
||||
pub pointer_active: Mutex<bool>,
|
||||
keyboard: OnceCell<WlKeyboard>,
|
||||
pub keyboard_info: Mutex<Option<KeyboardInfo>>,
|
||||
touch: OnceCell<WlTouch>,
|
||||
}
|
||||
impl SeatDataInner {
|
||||
pub fn pointer(&self) -> Option<&WlPointer> {
|
||||
self.pointer.get()
|
||||
}
|
||||
pub fn keyboard(&self) -> Option<&WlKeyboard> {
|
||||
self.keyboard.get()
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
pub fn touch(&self) -> Option<&WlTouch> {
|
||||
self.touch.get()
|
||||
}
|
||||
}
|
||||
impl Drop for SeatDataInner {
|
||||
fn drop(&mut self) {
|
||||
let id = self.global_id.take().unwrap();
|
||||
tokio::spawn(async move { GLOBAL_DESTROY_QUEUE.get().unwrap().send(id).await });
|
||||
}
|
||||
}
|
||||
|
||||
impl GlobalDispatch<WlSeat, SeatData, WaylandState> for SeatDelegate {
|
||||
fn bind(
|
||||
_state: &mut WaylandState,
|
||||
_handle: &DisplayHandle,
|
||||
_client: &Client,
|
||||
resource: New<WlSeat>,
|
||||
data: &SeatData,
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
let resource = data_init.init(resource, data.clone());
|
||||
|
||||
if resource.version() >= EVT_NAME_SINCE {
|
||||
resource.name(nanoid!());
|
||||
}
|
||||
|
||||
resource.capabilities(Capability::Pointer | Capability::Keyboard);
|
||||
}
|
||||
|
||||
fn can_view(client: Client, data: &SeatData) -> bool {
|
||||
client.id() == data.0.client
|
||||
pub fn touch_down(&self, surface: WlSurface, id: u32, position: Vector2<f32>) {
|
||||
let Some(state) = self.wayland_state.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(touch) = self.seat.get_touch() else {
|
||||
return;
|
||||
};
|
||||
touch.down(
|
||||
&mut state.lock(),
|
||||
Some((surface, (0.0, 0.0).into())),
|
||||
&DownEvent {
|
||||
slot: Some(id).into(),
|
||||
location: (position.x as f64, position.y as f64).into(),
|
||||
serial: SERIAL_COUNTER.next_serial(),
|
||||
time: 0,
|
||||
},
|
||||
);
|
||||
touch.frame(&mut state.lock());
|
||||
}
|
||||
}
|
||||
delegate_global_dispatch!(WaylandState: [WlSeat: SeatData] => SeatDelegate);
|
||||
|
||||
impl Dispatch<WlSeat, SeatData, WaylandState> for SeatDelegate {
|
||||
fn request(
|
||||
_state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
_resource: &WlSeat,
|
||||
request: <WlSeat as Resource>::Request,
|
||||
data: &SeatData,
|
||||
_dh: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
match request {
|
||||
wl_seat::Request::GetPointer { id } => {
|
||||
let _ = data.0.pointer.set(data_init.init(id, data.clone()));
|
||||
}
|
||||
wl_seat::Request::GetKeyboard { id } => {
|
||||
let keyboard = data_init.init(id, data.clone());
|
||||
keyboard.repeat_info(0, 0);
|
||||
let _ = data.0.keyboard.set(keyboard);
|
||||
}
|
||||
wl_seat::Request::GetTouch { id } => {
|
||||
let _ = data.0.touch.set(data_init.init(id, data.clone()));
|
||||
}
|
||||
wl_seat::Request::Release => (),
|
||||
_ => unreachable!(),
|
||||
pub fn touch_move(&self, id: u32, position: Vector2<f32>) {
|
||||
let Some(state) = self.wayland_state.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(surface) = self.touches.lock().get(&id).and_then(|c| c.upgrade().ok()) else {
|
||||
return;
|
||||
};
|
||||
let Some(touch) = self.seat.get_touch() else {
|
||||
return;
|
||||
};
|
||||
touch.motion(
|
||||
&mut state.lock(),
|
||||
Some((surface, (0.0, 0.0).into())),
|
||||
&touch::MotionEvent {
|
||||
slot: Some(id).into(),
|
||||
location: (position.x as f64, position.y as f64).into(),
|
||||
time: 0,
|
||||
},
|
||||
);
|
||||
touch.frame(&mut state.lock());
|
||||
}
|
||||
pub fn touch_up(&self, id: u32) {
|
||||
let Some(state) = self.wayland_state.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let Some(touch) = self.seat.get_touch() else {
|
||||
return;
|
||||
};
|
||||
touch.up(
|
||||
&mut state.lock(),
|
||||
&UpEvent {
|
||||
slot: Some(id).into(),
|
||||
serial: SERIAL_COUNTER.next_serial(),
|
||||
time: 0,
|
||||
},
|
||||
);
|
||||
touch.frame(&mut state.lock());
|
||||
}
|
||||
pub fn reset_input(&self) {
|
||||
for id in self.touches.lock().keys() {
|
||||
self.touch_up(*id)
|
||||
}
|
||||
}
|
||||
}
|
||||
delegate_dispatch!(WaylandState: [WlSeat: SeatData] => SeatDelegate);
|
||||
|
||||
impl Dispatch<WlPointer, SeatData, WaylandState> for SeatDelegate {
|
||||
fn request(
|
||||
state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
_resource: &WlPointer,
|
||||
request: <WlPointer as Resource>::Request,
|
||||
seat_data: &SeatData,
|
||||
dh: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
match request {
|
||||
wl_pointer::Request::SetCursor {
|
||||
serial: _,
|
||||
surface,
|
||||
hotspot_x,
|
||||
hotspot_y,
|
||||
} => {
|
||||
if !*seat_data.pointer_active.lock() {
|
||||
return;
|
||||
}
|
||||
*seat_data.0.cursor_changed.lock() = true;
|
||||
if let Some(surface) = surface.as_ref() {
|
||||
compositor::with_states(surface, |data| {
|
||||
data.data_map.insert_if_missing_threadsafe(|| {
|
||||
CoreSurface::new(
|
||||
&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| {
|
||||
data.data_map.get::<Arc<Mutex<Cursor>>>().cloned()
|
||||
})
|
||||
});
|
||||
}
|
||||
wl_pointer::Request::Release => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
delegate_dispatch!(WaylandState: [WlPointer: SeatData] => SeatDelegate);
|
||||
|
||||
impl Dispatch<WlKeyboard, SeatData, WaylandState> for SeatDelegate {
|
||||
fn request(
|
||||
_state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
_resource: &WlKeyboard,
|
||||
request: <WlKeyboard as Resource>::Request,
|
||||
_data: &SeatData,
|
||||
_dh: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
match request {
|
||||
wl_keyboard::Request::Release => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
delegate_dispatch!(WaylandState: [WlKeyboard: SeatData] => SeatDelegate);
|
||||
|
||||
impl Dispatch<WlTouch, SeatData, WaylandState> for SeatDelegate {
|
||||
fn request(
|
||||
_state: &mut WaylandState,
|
||||
_client: &Client,
|
||||
_resource: &WlTouch,
|
||||
request: <WlTouch as Resource>::Request,
|
||||
_data: &SeatData,
|
||||
_dh: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, WaylandState>,
|
||||
) {
|
||||
match request {
|
||||
wl_touch::Request::Release => (),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
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");
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,41 +1,64 @@
|
||||
use crate::wayland::seat::SeatData;
|
||||
use super::seat::SeatWrapper;
|
||||
use crate::wayland::drm::wl_drm::WlDrm;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use rustc_hash::FxHashMap;
|
||||
use slog::Logger;
|
||||
use smithay::{
|
||||
delegate_output, delegate_shm,
|
||||
output::{Output, Scale, Subpixel},
|
||||
backend::{
|
||||
allocator::{dmabuf::Dmabuf, Fourcc},
|
||||
egl::EGLDevice,
|
||||
renderer::gles::GlesRenderer,
|
||||
},
|
||||
delegate_dmabuf, delegate_output, delegate_shm,
|
||||
input::{keyboard::XkbConfig, SeatState},
|
||||
output::{Mode, Output, Scale, Subpixel},
|
||||
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_toplevel::WmCapabilities,
|
||||
},
|
||||
wayland_protocols_misc::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode as DecorationMode,
|
||||
wayland_server::{
|
||||
backend::{ClientData, ClientId, DisconnectReason},
|
||||
protocol::wl_data_device_manager::WlDataDeviceManager,
|
||||
Display, DisplayHandle,
|
||||
protocol::{
|
||||
wl_buffer::WlBuffer, wl_data_device_manager::WlDataDeviceManager,
|
||||
wl_output::WlOutput,
|
||||
},
|
||||
DisplayHandle,
|
||||
},
|
||||
},
|
||||
utils::Size,
|
||||
utils::{Size, Transform},
|
||||
wayland::{
|
||||
buffer::BufferHandler,
|
||||
compositor::CompositorState,
|
||||
output::OutputManagerState,
|
||||
compositor::{CompositorClientState, CompositorState},
|
||||
dmabuf::{
|
||||
self, DmabufFeedback, DmabufFeedbackBuilder, DmabufGlobal, DmabufHandler, DmabufState,
|
||||
},
|
||||
output::OutputHandler,
|
||||
shell::{
|
||||
kde::decoration::KdeDecorationState,
|
||||
xdg::{decoration::XdgDecorationState, XdgShellState},
|
||||
xdg::{WmCapabilitySet, XdgShellState},
|
||||
},
|
||||
shm::{ShmHandler, ShmState},
|
||||
xdg_activation::XdgActivationState,
|
||||
},
|
||||
};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc::UnboundedSender;
|
||||
use tracing::{info, warn};
|
||||
|
||||
pub struct ClientState;
|
||||
pub struct ClientState {
|
||||
pub pid: Option<i32>,
|
||||
pub id: OnceCell<ClientId>,
|
||||
pub compositor_state: CompositorClientState,
|
||||
pub seat: Arc<SeatWrapper>,
|
||||
}
|
||||
impl ClientData for ClientState {
|
||||
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) {
|
||||
println!(
|
||||
info!(
|
||||
"Wayland client {:?} disconnected because {:#?}",
|
||||
client_id, reason
|
||||
);
|
||||
@@ -43,35 +66,75 @@ impl ClientData for ClientState {
|
||||
}
|
||||
|
||||
pub struct WaylandState {
|
||||
pub weak_ref: Weak<Mutex<WaylandState>>,
|
||||
pub display: Arc<Mutex<Display<WaylandState>>>,
|
||||
pub display_handle: DisplayHandle,
|
||||
|
||||
pub compositor_state: CompositorState,
|
||||
pub xdg_activation_state: XdgActivationState,
|
||||
pub xdg_decoration_state: XdgDecorationState,
|
||||
// pub xdg_activation_state: XdgActivationState,
|
||||
pub kde_decoration_state: KdeDecorationState,
|
||||
pub xdg_shell_state: XdgShellState,
|
||||
pub shm_state: ShmState,
|
||||
pub output_manager_state: OutputManagerState,
|
||||
dmabuf_state: (DmabufState, DmabufGlobal, Option<DmabufFeedback>),
|
||||
pub drm_formats: Vec<Fourcc>,
|
||||
pub dmabuf_tx: UnboundedSender<(Dmabuf, Option<dmabuf::ImportNotifier>)>,
|
||||
pub seat_state: SeatState<Self>,
|
||||
pub seat: Arc<SeatWrapper>,
|
||||
pub xdg_shell: XdgShellState,
|
||||
pub output: Output,
|
||||
pub seats: FxHashMap<ClientId, SeatData>,
|
||||
}
|
||||
|
||||
impl WaylandState {
|
||||
pub fn new(
|
||||
log: Logger,
|
||||
display: Arc<Mutex<Display<WaylandState>>>,
|
||||
display_handle: DisplayHandle,
|
||||
renderer: &GlesRenderer,
|
||||
dmabuf_tx: UnboundedSender<(Dmabuf, Option<dmabuf::ImportNotifier>)>,
|
||||
) -> Arc<Mutex<Self>> {
|
||||
let compositor_state = CompositorState::new::<Self, _>(&display_handle, log.clone());
|
||||
let xdg_activation_state = XdgActivationState::new::<Self, _>(&display_handle, log.clone());
|
||||
let xdg_shell_state = XdgShellState::new::<Self, _>(&display_handle, log.clone());
|
||||
let xdg_decoration_state = XdgDecorationState::new::<Self, _>(&display_handle, log.clone());
|
||||
let compositor_state = CompositorState::new::<Self>(&display_handle);
|
||||
// let xdg_activation_state = XdgActivationState::new::<Self, _>(&display_handle);
|
||||
let kde_decoration_state =
|
||||
KdeDecorationState::new::<Self, _>(&display_handle, Mode::Server, log.clone());
|
||||
let shm_state = ShmState::new::<Self, _>(&display_handle, vec![], log.clone());
|
||||
let output_manager_state = OutputManagerState::new_with_xdg_output::<Self>(&display_handle);
|
||||
KdeDecorationState::new::<Self>(&display_handle, DecorationMode::Server);
|
||||
let shm_state = ShmState::new::<Self>(&display_handle, vec![]);
|
||||
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 drm_formats = dmabuf_formats.iter().map(|f| f.code).collect();
|
||||
|
||||
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 mut seat_state = SeatState::new();
|
||||
let mut seat = seat_state.new_wl_seat(&display_handle, "seat0");
|
||||
seat.add_pointer();
|
||||
seat.add_keyboard(XkbConfig::default(), 200, 25).unwrap();
|
||||
seat.add_touch();
|
||||
|
||||
let output = Output::new(
|
||||
"1x".to_owned(),
|
||||
smithay::output::PhysicalProperties {
|
||||
@@ -80,54 +143,80 @@ impl WaylandState {
|
||||
make: "Virtual XR Display".to_owned(),
|
||||
model: "Your Headset Name Here".to_owned(),
|
||||
},
|
||||
log.clone(),
|
||||
);
|
||||
let _global = output.create_global::<Self>(&display_handle);
|
||||
output.change_current_state(None, None, Some(Scale::Integer(2)), None);
|
||||
display_handle.create_global::<Self, WlDataDeviceManager, _>(3, ());
|
||||
let _output_global = output.create_global::<Self>(&display_handle);
|
||||
let mode = Mode {
|
||||
size: (1024, 1024).into(),
|
||||
refresh: 60000,
|
||||
};
|
||||
output.change_current_state(
|
||||
Some(mode),
|
||||
Some(Transform::Normal),
|
||||
Some(Scale::Integer(2)),
|
||||
None,
|
||||
);
|
||||
output.set_preferred(mode);
|
||||
|
||||
println!("Init Wayland compositor");
|
||||
let mut xdg_shell = XdgShellState::new::<Self>(&display_handle);
|
||||
let mut capabilities = WmCapabilitySet::default();
|
||||
capabilities.set(WmCapabilities::Maximize);
|
||||
capabilities.set(WmCapabilities::Fullscreen);
|
||||
capabilities.unset(WmCapabilities::Minimize);
|
||||
capabilities.unset(WmCapabilities::WindowMenu);
|
||||
xdg_shell.replace_capabilities(capabilities);
|
||||
display_handle.create_global::<Self, WlDataDeviceManager, _>(3, ());
|
||||
display_handle.create_global::<Self, ZxdgDecorationManagerV1, _>(1, ());
|
||||
display_handle.create_global::<Self, WlDrm, _>(2, ());
|
||||
|
||||
info!("Init Wayland compositor");
|
||||
|
||||
Arc::new_cyclic(|weak| {
|
||||
Mutex::new(WaylandState {
|
||||
weak_ref: weak.clone(),
|
||||
display,
|
||||
display_handle,
|
||||
|
||||
compositor_state,
|
||||
xdg_activation_state,
|
||||
xdg_decoration_state,
|
||||
// xdg_activation_state,
|
||||
kde_decoration_state,
|
||||
xdg_shell_state,
|
||||
shm_state,
|
||||
output_manager_state,
|
||||
drm_formats,
|
||||
dmabuf_state,
|
||||
dmabuf_tx,
|
||||
seat_state,
|
||||
seat: Arc::new(SeatWrapper::new(weak.clone(), seat)),
|
||||
xdg_shell,
|
||||
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 {
|
||||
fn drop(&mut self) {
|
||||
println!("Cleanly shut down the Wayland compositor");
|
||||
info!("Cleanly shut down the Wayland compositor");
|
||||
}
|
||||
}
|
||||
impl BufferHandler for WaylandState {
|
||||
fn buffer_destroyed(
|
||||
&mut self,
|
||||
_buffer: &smithay::reexports::wayland_server::protocol::wl_buffer::WlBuffer,
|
||||
) {
|
||||
}
|
||||
fn buffer_destroyed(&mut self, _buffer: &WlBuffer) {}
|
||||
}
|
||||
impl ShmHandler for WaylandState {
|
||||
fn shm_state(&self) -> &smithay::wayland::shm::ShmState {
|
||||
fn shm_state(&self) -> &ShmState {
|
||||
&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,
|
||||
notifier: dmabuf::ImportNotifier,
|
||||
) {
|
||||
self.dmabuf_tx.send((dmabuf, Some(notifier))).unwrap();
|
||||
}
|
||||
}
|
||||
impl OutputHandler for WaylandState {
|
||||
fn output_bound(&mut self, _output: Output, _wl_output: WlOutput) {}
|
||||
}
|
||||
delegate_dmabuf!(WaylandState);
|
||||
delegate_shm!(WaylandState);
|
||||
delegate_output!(WaylandState);
|
||||
|
||||
@@ -1,220 +1,206 @@
|
||||
use super::{shaders::PANEL_SHADER_BYTES, state::WaylandState};
|
||||
use super::utils::WlSurfaceExt;
|
||||
use crate::{
|
||||
core::{destroy_queue, registry::Registry},
|
||||
nodes::drawable::model::Model,
|
||||
core::{delta::Delta, destroy_queue, registry::Registry},
|
||||
nodes::{
|
||||
drawable::{
|
||||
model::{MaterialWrapper, ModelPart},
|
||||
shaders::PANEL_SHADER_BYTES,
|
||||
},
|
||||
items::camera::TexWrapper,
|
||||
},
|
||||
};
|
||||
use mint::Vector2;
|
||||
use once_cell::sync::OnceCell;
|
||||
use parking_lot::Mutex;
|
||||
use send_wrapper::SendWrapper;
|
||||
use slog::Logger;
|
||||
use smithay::{
|
||||
backend::renderer::{
|
||||
gles2::{Gles2Renderer, Gles2Texture},
|
||||
utils::{import_surface_tree, on_commit_buffer_handler, RendererSurfaceStateUserData},
|
||||
Texture,
|
||||
gles::{GlesRenderer, GlesTexture},
|
||||
utils::{import_surface_tree, RendererSurfaceStateUserData},
|
||||
Renderer, Texture,
|
||||
},
|
||||
desktop::utils::send_frames_surface_tree,
|
||||
reexports::wayland_server::{
|
||||
backend::ObjectId, protocol::wl_surface::WlSurface, Display, DisplayHandle, Resource,
|
||||
},
|
||||
wayland::compositor::{self, SurfaceData},
|
||||
output::Output,
|
||||
reexports::wayland_server::{self, protocol::wl_surface::WlSurface, Resource},
|
||||
};
|
||||
use std::sync::{Arc, Weak};
|
||||
use stereokit::{
|
||||
use std::{ffi::c_void, sync::Arc, time::Duration};
|
||||
use stereokit_rust::{
|
||||
material::{Material, Transparency},
|
||||
shader::Shader,
|
||||
texture::{Texture as SKTexture, TextureAddress, TextureFormat, TextureSample, TextureType},
|
||||
StereoKit,
|
||||
tex::{Tex, TexAddress, TexFormat, TexSample, TexType},
|
||||
util::Time,
|
||||
};
|
||||
|
||||
pub static CORE_SURFACES: Registry<CoreSurface> = Registry::new();
|
||||
|
||||
pub struct CoreSurfaceData {
|
||||
wl_tex: Option<SendWrapper<Gles2Texture>>,
|
||||
sk_tex: Option<SendWrapper<SKTexture>>,
|
||||
sk_mat: Option<Arc<SendWrapper<Material>>>,
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
wl_tex: Option<SendWrapper<GlesTexture>>,
|
||||
}
|
||||
impl Drop for CoreSurfaceData {
|
||||
fn drop(&mut self) {
|
||||
destroy_queue::add(self.wl_tex.take());
|
||||
destroy_queue::add(self.sk_tex.take());
|
||||
destroy_queue::add(self.sk_mat.take());
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CoreSurface {
|
||||
display: Weak<Mutex<Display<WaylandState>>>,
|
||||
pub state: Weak<Mutex<WaylandState>>,
|
||||
pub dh: DisplayHandle,
|
||||
pub surface_id: ObjectId,
|
||||
pub mapped_data: Mutex<Option<CoreSurfaceData>>,
|
||||
pub pending_material_applications: Mutex<Vec<(Arc<Model>, u32)>>,
|
||||
pub weak_surface: wayland_server::Weak<WlSurface>,
|
||||
mapped_data: Mutex<Option<CoreSurfaceData>>,
|
||||
sk_tex: OnceCell<Mutex<TexWrapper>>,
|
||||
sk_mat: OnceCell<Mutex<MaterialWrapper>>,
|
||||
material_offset: Mutex<Delta<u32>>,
|
||||
pub pending_material_applications: Registry<ModelPart>,
|
||||
}
|
||||
|
||||
impl CoreSurface {
|
||||
pub fn new(
|
||||
state: &Arc<Mutex<WaylandState>>,
|
||||
display: &Arc<Mutex<Display<WaylandState>>>,
|
||||
dh: DisplayHandle,
|
||||
surface: &WlSurface,
|
||||
) -> Arc<Self> {
|
||||
CORE_SURFACES.add(CoreSurface {
|
||||
display: Arc::downgrade(display),
|
||||
state: Arc::downgrade(state),
|
||||
dh,
|
||||
surface_id: surface.id(),
|
||||
pub fn add_to(surface: &WlSurface) {
|
||||
let core_surface = CORE_SURFACES.add(CoreSurface {
|
||||
weak_surface: surface.downgrade(),
|
||||
mapped_data: Mutex::new(None),
|
||||
pending_material_applications: Mutex::new(Vec::new()),
|
||||
})
|
||||
sk_tex: OnceCell::new(),
|
||||
sk_mat: OnceCell::new(),
|
||||
material_offset: Mutex::new(Delta::new(0)),
|
||||
pending_material_applications: Registry::new(),
|
||||
});
|
||||
surface.insert_data(core_surface);
|
||||
}
|
||||
|
||||
pub fn process<F: FnOnce(&SurfaceData), M: FnOnce(&SurfaceData)>(
|
||||
&self,
|
||||
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();
|
||||
pub fn from_wl_surface(surf: &WlSurface) -> Option<Arc<CoreSurface>> {
|
||||
surf.get_data()
|
||||
}
|
||||
|
||||
let mapped = compositor::with_states(&self.wl_surface(), |data| {
|
||||
data.data_map
|
||||
.get::<RendererSurfaceStateUserData>()
|
||||
.map(|surface_states| surface_states.borrow().wl_buffer().is_some())
|
||||
.unwrap_or(false)
|
||||
pub fn process(&self, renderer: &mut GlesRenderer) {
|
||||
let Some(wl_surface) = self.wl_surface() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let sk_tex = self.sk_tex.get_or_init(|| {
|
||||
Mutex::new(TexWrapper(Tex::new(
|
||||
TexType::ImageNomips,
|
||||
TexFormat::RGBA32Linear,
|
||||
nanoid::nanoid!(),
|
||||
)))
|
||||
});
|
||||
self.sk_mat.get_or_init(|| {
|
||||
let shader = Shader::from_memory(PANEL_SHADER_BYTES).unwrap();
|
||||
// let _ = renderer.with_context(|c| unsafe {
|
||||
// shader_inject(c, &mut shader, SIMULA_VERT_STR, SIMULA_FRAG_STR)
|
||||
// });
|
||||
|
||||
let mut mat = Material::new(shader, None);
|
||||
mat.diffuse_tex(&sk_tex.lock().0);
|
||||
mat.transparency(Transparency::Blend);
|
||||
Mutex::new(MaterialWrapper(mat))
|
||||
});
|
||||
|
||||
// Import all surface buffers into textures
|
||||
if import_surface_tree(renderer, &wl_surface).is_err() {
|
||||
return;
|
||||
}
|
||||
|
||||
self.update_textures(renderer);
|
||||
self.apply_surface_materials();
|
||||
}
|
||||
|
||||
pub fn update_textures(&self, renderer: &mut GlesRenderer) {
|
||||
let Some(wl_surface) = self.wl_surface() else {
|
||||
return;
|
||||
};
|
||||
let mapped = wl_surface
|
||||
.get_data_raw::<RendererSurfaceStateUserData, _, _>(|surface_states| {
|
||||
surface_states.lock().unwrap().buffer().is_some()
|
||||
})
|
||||
.unwrap_or(false);
|
||||
|
||||
if !mapped {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut mapped_data = self.mapped_data.lock();
|
||||
let just_mapped = mapped_data.is_none();
|
||||
if just_mapped {
|
||||
*mapped_data = Some(CoreSurfaceData::new(sk));
|
||||
|
||||
let Some(smithay_tex) = wl_surface
|
||||
.get_data_raw::<RendererSurfaceStateUserData, _, _>(|surface_states| {
|
||||
surface_states
|
||||
.lock()
|
||||
.unwrap()
|
||||
.texture::<GlesRenderer>(renderer.id())
|
||||
.cloned()
|
||||
})
|
||||
.flatten()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(sk_tex) = self.sk_tex.get() else {
|
||||
return;
|
||||
};
|
||||
let Some(sk_mat) = self.sk_mat.get() else {
|
||||
return;
|
||||
};
|
||||
sk_tex
|
||||
.lock()
|
||||
.0
|
||||
.set_native_surface(
|
||||
smithay_tex.tex_id() as usize as *mut c_void,
|
||||
TexType::ImageNomips,
|
||||
smithay::backend::renderer::gles::ffi::RGBA8.into(),
|
||||
smithay_tex.width() as i32,
|
||||
smithay_tex.height() as i32,
|
||||
1,
|
||||
false,
|
||||
)
|
||||
.sample_mode(TexSample::Point)
|
||||
.address_mode(TexAddress::Clamp);
|
||||
|
||||
if let Some(material_offset) = self.material_offset.lock().delta() {
|
||||
sk_mat.lock().0.queue_offset(*material_offset as i32);
|
||||
}
|
||||
drop(mapped_data);
|
||||
self.with_states(|data| {
|
||||
self.with_data(|mapped_data| {
|
||||
mapped_data.update_tex(
|
||||
data.data_map.get::<RendererSurfaceStateUserData>().unwrap(),
|
||||
renderer,
|
||||
);
|
||||
});
|
||||
self.apply_surface_materials();
|
||||
|
||||
if just_mapped {
|
||||
on_mapped(data);
|
||||
}
|
||||
if_mapped(data);
|
||||
});
|
||||
|
||||
send_frames_surface_tree(&self.wl_surface(), time_ms);
|
||||
let new_mapped_data = CoreSurfaceData {
|
||||
wl_tex: Some(SendWrapper::new(smithay_tex)),
|
||||
};
|
||||
*mapped_data = Some(new_mapped_data);
|
||||
}
|
||||
|
||||
pub fn apply_material(&self, model: Arc<Model>, material_idx: u32) {
|
||||
self.pending_material_applications
|
||||
.lock()
|
||||
.push((model, material_idx));
|
||||
pub fn frame(&self, output: Output) {
|
||||
let Some(wl_surface) = self.wl_surface() else {
|
||||
return;
|
||||
};
|
||||
|
||||
send_frames_surface_tree(
|
||||
&wl_surface,
|
||||
&output,
|
||||
Duration::from_secs_f64(Time::get_total_unscaled()),
|
||||
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) {
|
||||
self.with_data(|mapped_data| {
|
||||
let mut pending_material_applications = self.pending_material_applications.lock();
|
||||
for (model, material_idx) in &*pending_material_applications {
|
||||
model
|
||||
.pending_material_replacements
|
||||
.lock()
|
||||
.insert(*material_idx, mapped_data.sk_mat.clone().unwrap());
|
||||
if let Some(sk_mat) = self.sk_mat.get() {
|
||||
let sk_mat = sk_mat.lock();
|
||||
for model_node in self.pending_material_applications.get_valid_contents() {
|
||||
model_node.replace_material_now(&sk_mat.0);
|
||||
}
|
||||
pending_material_applications.clear();
|
||||
});
|
||||
self.pending_material_applications.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wayland_state(&self) -> Arc<Mutex<WaylandState>> {
|
||||
self.state.upgrade().unwrap()
|
||||
}
|
||||
|
||||
pub fn wl_surface(&self) -> WlSurface {
|
||||
WlSurface::from_id(&self.dh, self.surface_id.clone()).unwrap()
|
||||
}
|
||||
|
||||
pub fn with_states<F, T>(&self, f: F) -> T
|
||||
where
|
||||
F: FnOnce(&SurfaceData) -> T,
|
||||
{
|
||||
compositor::with_states(&self.wl_surface(), f)
|
||||
}
|
||||
|
||||
pub fn with_data<F, T>(&self, f: F) -> Option<T>
|
||||
where
|
||||
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();
|
||||
pub fn wl_surface(&self) -> Option<WlSurface> {
|
||||
self.weak_surface.upgrade().ok()
|
||||
}
|
||||
}
|
||||
impl Drop for CoreSurface {
|
||||
fn drop(&mut self) {
|
||||
CORE_SURFACES.remove(self);
|
||||
|
||||
destroy_queue::add(self.sk_tex.take());
|
||||
destroy_queue::add(self.sk_mat.take());
|
||||
}
|
||||
}
|
||||
|
||||
121
src/wayland/utils.rs
Normal file
121
src/wayland/utils.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
use mint::Vector2;
|
||||
use parking_lot::Mutex;
|
||||
use smithay::{
|
||||
backend::renderer::utils::RendererSurfaceStateUserData,
|
||||
reexports::wayland_server::protocol::wl_surface::WlSurface,
|
||||
wayland::{
|
||||
compositor,
|
||||
shell::xdg::{SurfaceCachedState, XdgToplevelSurfaceData},
|
||||
},
|
||||
};
|
||||
|
||||
use crate::nodes::items::panel::{ChildInfo, Geometry, ToplevelInfo};
|
||||
|
||||
use super::xdg_shell::surface_panel_item;
|
||||
pub trait WlSurfaceExt {
|
||||
fn insert_data<T: Send + Sync + 'static>(&self, data: T) -> bool;
|
||||
fn get_data<T: Send + Sync + Clone + 'static>(&self) -> Option<T>;
|
||||
fn get_data_raw<T: Send + Sync + 'static, O, F: FnOnce(&T) -> O>(&self, f: F) -> Option<O>;
|
||||
fn get_current_surface_state(&self) -> SurfaceCachedState;
|
||||
fn get_pending_surface_state(&self) -> SurfaceCachedState;
|
||||
fn get_size(&self) -> Option<Vector2<u32>>;
|
||||
fn get_geometry(&self) -> Option<Geometry>;
|
||||
}
|
||||
impl WlSurfaceExt for WlSurface {
|
||||
fn insert_data<T: Send + Sync + 'static>(&self, data: T) -> bool {
|
||||
compositor::with_states(self, |d| {
|
||||
d.data_map.insert_if_missing_threadsafe(move || data)
|
||||
})
|
||||
}
|
||||
fn get_data<T: Send + Sync + Clone + 'static>(&self) -> Option<T> {
|
||||
compositor::with_states(self, |d| d.data_map.get::<T>().cloned())
|
||||
}
|
||||
fn get_data_raw<T: Send + Sync + 'static, O, F: FnOnce(&T) -> O>(&self, f: F) -> Option<O> {
|
||||
compositor::with_states(self, |d| Some((f)(d.data_map.get::<T>()?)))
|
||||
}
|
||||
fn get_current_surface_state(&self) -> SurfaceCachedState {
|
||||
compositor::with_states(self, |states| {
|
||||
*states.cached_state.get::<SurfaceCachedState>().current()
|
||||
})
|
||||
}
|
||||
fn get_pending_surface_state(&self) -> SurfaceCachedState {
|
||||
compositor::with_states(self, |states| {
|
||||
*states.cached_state.get::<SurfaceCachedState>().pending()
|
||||
})
|
||||
}
|
||||
fn get_size(&self) -> Option<Vector2<u32>> {
|
||||
self.get_data_raw::<RendererSurfaceStateUserData, _, _>(|surface_states| {
|
||||
surface_states.lock().unwrap().surface_size()
|
||||
})
|
||||
.flatten()
|
||||
.map(|size| Vector2::from([size.w as u32, size.h as u32]))
|
||||
}
|
||||
fn get_geometry(&self) -> Option<Geometry> {
|
||||
self.get_current_surface_state().geometry.map(|r| r.into())
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ToplevelInfoExt {
|
||||
fn get_toplevel_info(&self) -> Option<ToplevelInfo>;
|
||||
fn with_toplevel_info<O, F: FnOnce(&mut ToplevelInfo) -> O>(&self, f: F) -> Option<O>;
|
||||
|
||||
fn get_parent(&self) -> Option<u64>;
|
||||
fn get_app_id(&self) -> Option<String>;
|
||||
fn get_title(&self) -> Option<String>;
|
||||
fn min_size(&self) -> Option<Vector2<u32>>;
|
||||
fn max_size(&self) -> Option<Vector2<u32>>;
|
||||
}
|
||||
impl ToplevelInfoExt for WlSurface {
|
||||
fn get_toplevel_info(&self) -> Option<ToplevelInfo> {
|
||||
self.get_data_raw::<Mutex<ToplevelInfo>, _, _>(|c| c.lock().clone())
|
||||
}
|
||||
fn with_toplevel_info<O, F: FnOnce(&mut ToplevelInfo) -> O>(&self, f: F) -> Option<O> {
|
||||
self.get_data_raw::<Mutex<ToplevelInfo>, _, _>(|r| (f)(&mut r.lock()))
|
||||
}
|
||||
|
||||
fn get_parent(&self) -> Option<u64> {
|
||||
self.get_data_raw::<XdgToplevelSurfaceData, _, _>(|d| d.lock().unwrap().parent.clone())
|
||||
.flatten()
|
||||
.and_then(|p| surface_panel_item(&p))
|
||||
.and_then(|p| p.node.upgrade())
|
||||
.map(|p| p.get_id())
|
||||
}
|
||||
fn get_app_id(&self) -> Option<String> {
|
||||
self.get_data_raw::<XdgToplevelSurfaceData, _, _>(|d| d.lock().ok()?.app_id.clone())
|
||||
.flatten()
|
||||
}
|
||||
fn get_title(&self) -> Option<String> {
|
||||
self.get_data_raw::<XdgToplevelSurfaceData, _, _>(|d| d.lock().ok()?.title.clone())
|
||||
.flatten()
|
||||
}
|
||||
fn min_size(&self) -> Option<Vector2<u32>> {
|
||||
let state = self.get_pending_surface_state();
|
||||
let size = state.min_size;
|
||||
if size.w == 0 && size.h == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(Vector2::from([size.w as u32, size.h as u32]))
|
||||
}
|
||||
}
|
||||
fn max_size(&self) -> Option<Vector2<u32>> {
|
||||
let state = self.get_pending_surface_state();
|
||||
let size = state.max_size;
|
||||
if size.w == 0 && size.h == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(Vector2::from([size.w as u32, size.h as u32]))
|
||||
}
|
||||
}
|
||||
}
|
||||
pub trait ChildInfoExt {
|
||||
fn get_child_info(&self) -> Option<ChildInfo>;
|
||||
fn with_child_info<O, F: FnOnce(&mut ChildInfo) -> O>(&self, f: F) -> Option<O>;
|
||||
}
|
||||
impl ChildInfoExt for WlSurface {
|
||||
fn get_child_info(&self) -> Option<ChildInfo> {
|
||||
self.get_data_raw::<Mutex<ChildInfo>, _, _>(|c| c.lock().clone())
|
||||
}
|
||||
fn with_child_info<O, F: FnOnce(&mut ChildInfo) -> O>(&self, f: F) -> Option<O> {
|
||||
self.get_data_raw::<Mutex<ChildInfo>, _, _>(|r| (f)(&mut r.lock()))
|
||||
}
|
||||
}
|
||||
189
src/wayland/wayland-drm.xml
Normal file
189
src/wayland/wayland-drm.xml
Normal file
@@ -0,0 +1,189 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<protocol name="drm">
|
||||
|
||||
<copyright>
|
||||
Copyright © 2008-2011 Kristian Høgsberg
|
||||
Copyright © 2010-2011 Intel Corporation
|
||||
|
||||
Permission to use, copy, modify, distribute, and sell this
|
||||
software and its documentation for any purpose is hereby granted
|
||||
without fee, provided that\n the above copyright notice appear in
|
||||
all copies and that both that copyright notice and this permission
|
||||
notice appear in supporting documentation, and that the name of
|
||||
the copyright holders not be used in advertising or publicity
|
||||
pertaining to distribution of the software without specific,
|
||||
written prior permission. The copyright holders make no
|
||||
representations about the suitability of this software for any
|
||||
purpose. It is provided "as is" without express or implied
|
||||
warranty.
|
||||
|
||||
THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
|
||||
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
|
||||
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
||||
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
THIS SOFTWARE.
|
||||
</copyright>
|
||||
|
||||
<!-- drm support. This object is created by the server and published
|
||||
using the display's global event. -->
|
||||
<interface name="wl_drm" version="2">
|
||||
<enum name="error">
|
||||
<entry name="authenticate_fail" value="0" />
|
||||
<entry name="invalid_format" value="1" />
|
||||
<entry name="invalid_name" value="2" />
|
||||
</enum>
|
||||
|
||||
<enum name="format">
|
||||
<!-- The drm format codes match the #defines in drm_fourcc.h.
|
||||
The formats actually supported by the compositor will be
|
||||
reported by the format event. New codes must not be added,
|
||||
unless directly taken from drm_fourcc.h. -->
|
||||
<entry name="c8" value="0x20203843" />
|
||||
<entry name="rgb332" value="0x38424752" />
|
||||
<entry name="bgr233" value="0x38524742" />
|
||||
<entry name="xrgb4444" value="0x32315258" />
|
||||
<entry name="xbgr4444" value="0x32314258" />
|
||||
<entry name="rgbx4444" value="0x32315852" />
|
||||
<entry name="bgrx4444" value="0x32315842" />
|
||||
<entry name="argb4444" value="0x32315241" />
|
||||
<entry name="abgr4444" value="0x32314241" />
|
||||
<entry name="rgba4444" value="0x32314152" />
|
||||
<entry name="bgra4444" value="0x32314142" />
|
||||
<entry name="xrgb1555" value="0x35315258" />
|
||||
<entry name="xbgr1555" value="0x35314258" />
|
||||
<entry name="rgbx5551" value="0x35315852" />
|
||||
<entry name="bgrx5551" value="0x35315842" />
|
||||
<entry name="argb1555" value="0x35315241" />
|
||||
<entry name="abgr1555" value="0x35314241" />
|
||||
<entry name="rgba5551" value="0x35314152" />
|
||||
<entry name="bgra5551" value="0x35314142" />
|
||||
<entry name="rgb565" value="0x36314752" />
|
||||
<entry name="bgr565" value="0x36314742" />
|
||||
<entry name="rgb888" value="0x34324752" />
|
||||
<entry name="bgr888" value="0x34324742" />
|
||||
<entry name="xrgb8888" value="0x34325258" />
|
||||
<entry name="xbgr8888" value="0x34324258" />
|
||||
<entry name="rgbx8888" value="0x34325852" />
|
||||
<entry name="bgrx8888" value="0x34325842" />
|
||||
<entry name="argb8888" value="0x34325241" />
|
||||
<entry name="abgr8888" value="0x34324241" />
|
||||
<entry name="rgba8888" value="0x34324152" />
|
||||
<entry name="bgra8888" value="0x34324142" />
|
||||
<entry name="xrgb2101010" value="0x30335258" />
|
||||
<entry name="xbgr2101010" value="0x30334258" />
|
||||
<entry name="rgbx1010102" value="0x30335852" />
|
||||
<entry name="bgrx1010102" value="0x30335842" />
|
||||
<entry name="argb2101010" value="0x30335241" />
|
||||
<entry name="abgr2101010" value="0x30334241" />
|
||||
<entry name="rgba1010102" value="0x30334152" />
|
||||
<entry name="bgra1010102" value="0x30334142" />
|
||||
<entry name="yuyv" value="0x56595559" />
|
||||
<entry name="yvyu" value="0x55595659" />
|
||||
<entry name="uyvy" value="0x59565955" />
|
||||
<entry name="vyuy" value="0x59555956" />
|
||||
<entry name="ayuv" value="0x56555941" />
|
||||
<entry name="xyuv8888" value="0x56555958" />
|
||||
<entry name="nv12" value="0x3231564e" />
|
||||
<entry name="nv21" value="0x3132564e" />
|
||||
<entry name="nv16" value="0x3631564e" />
|
||||
<entry name="nv61" value="0x3136564e" />
|
||||
<entry name="yuv410" value="0x39565559" />
|
||||
<entry name="yvu410" value="0x39555659" />
|
||||
<entry name="yuv411" value="0x31315559" />
|
||||
<entry name="yvu411" value="0x31315659" />
|
||||
<entry name="yuv420" value="0x32315559" />
|
||||
<entry name="yvu420" value="0x32315659" />
|
||||
<entry name="yuv422" value="0x36315559" />
|
||||
<entry name="yvu422" value="0x36315659" />
|
||||
<entry name="yuv444" value="0x34325559" />
|
||||
<entry name="yvu444" value="0x34325659" />
|
||||
<entry name="abgr16f" value="0x48344241" />
|
||||
<entry name="xbgr16f" value="0x48344258" />
|
||||
</enum>
|
||||
|
||||
<!-- Call this request with the magic received from drmGetMagic().
|
||||
It will be passed on to the drmAuthMagic() or
|
||||
DRIAuthConnection() call. This authentication must be
|
||||
completed before create_buffer could be used. -->
|
||||
<request name="authenticate">
|
||||
<arg name="id" type="uint" />
|
||||
</request>
|
||||
|
||||
<!-- Create a wayland buffer for the named DRM buffer. The DRM
|
||||
surface must have a name using the flink ioctl -->
|
||||
<request name="create_buffer">
|
||||
<arg name="id" type="new_id" interface="wl_buffer" />
|
||||
<arg name="name" type="uint" />
|
||||
<arg name="width" type="int" />
|
||||
<arg name="height" type="int" />
|
||||
<arg name="stride" type="uint" />
|
||||
<arg name="format" type="uint" />
|
||||
</request>
|
||||
|
||||
<!-- Create a wayland buffer for the named DRM buffer. The DRM
|
||||
surface must have a name using the flink ioctl -->
|
||||
<request name="create_planar_buffer">
|
||||
<arg name="id" type="new_id" interface="wl_buffer" />
|
||||
<arg name="name" type="uint" />
|
||||
<arg name="width" type="int" />
|
||||
<arg name="height" type="int" />
|
||||
<arg name="format" type="uint" />
|
||||
<arg name="offset0" type="int" />
|
||||
<arg name="stride0" type="int" />
|
||||
<arg name="offset1" type="int" />
|
||||
<arg name="stride1" type="int" />
|
||||
<arg name="offset2" type="int" />
|
||||
<arg name="stride2" type="int" />
|
||||
</request>
|
||||
|
||||
<!-- Notification of the path of the drm device which is used by
|
||||
the server. The client should use this device for creating
|
||||
local buffers. Only buffers created from this device should
|
||||
be be passed to the server using this drm object's
|
||||
create_buffer request. -->
|
||||
<event name="device">
|
||||
<arg name="name" type="string" />
|
||||
</event>
|
||||
|
||||
<event name="format">
|
||||
<arg name="format" type="uint" />
|
||||
</event>
|
||||
|
||||
<!-- Raised if the authenticate request succeeded -->
|
||||
<event name="authenticated" />
|
||||
|
||||
<enum name="capability" since="2">
|
||||
<description summary="wl_drm capability bitmask">
|
||||
Bitmask of capabilities.
|
||||
</description>
|
||||
<entry name="prime" value="1" summary="wl_drm prime available" />
|
||||
</enum>
|
||||
|
||||
<event name="capabilities">
|
||||
<arg name="value" type="uint" />
|
||||
</event>
|
||||
|
||||
<!-- Version 2 additions -->
|
||||
|
||||
<!-- Create a wayland buffer for the prime fd. Use for regular and planar
|
||||
buffers. Pass 0 for offset and stride for unused planes. -->
|
||||
<request name="create_prime_buffer" since="2">
|
||||
<arg name="id" type="new_id" interface="wl_buffer" />
|
||||
<arg name="name" type="fd" />
|
||||
<arg name="width" type="int" />
|
||||
<arg name="height" type="int" />
|
||||
<arg name="format" type="uint" />
|
||||
<arg name="offset0" type="int" />
|
||||
<arg name="stride0" type="int" />
|
||||
<arg name="offset1" type="int" />
|
||||
<arg name="stride1" type="int" />
|
||||
<arg name="offset2" type="int" />
|
||||
<arg name="stride2" type="int" />
|
||||
</request>
|
||||
|
||||
</interface>
|
||||
|
||||
</protocol>
|
||||
@@ -1,69 +1,540 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::nodes::Node;
|
||||
|
||||
use super::{panel_item::PanelItem, state::WaylandState, surface::CoreSurface};
|
||||
use super::{
|
||||
seat::{handle_cursor, SeatWrapper},
|
||||
state::{ClientState, WaylandState},
|
||||
surface::CoreSurface,
|
||||
utils::*,
|
||||
};
|
||||
use crate::nodes::{
|
||||
drawable::model::ModelPart,
|
||||
items::panel::{
|
||||
Backend, ChildInfo, Geometry, PanelItem, PanelItemInitData, SurfaceId, ToplevelInfo,
|
||||
},
|
||||
};
|
||||
use color_eyre::eyre::{eyre, Result};
|
||||
use mint::Vector2;
|
||||
use parking_lot::Mutex;
|
||||
use rand::Rng;
|
||||
use rustc_hash::FxHashMap;
|
||||
use smithay::{
|
||||
delegate_xdg_shell,
|
||||
reexports::{
|
||||
wayland_protocols::xdg::{
|
||||
decoration::zv1::server::zxdg_toplevel_decoration_v1::Mode,
|
||||
shell::server::xdg_toplevel::State,
|
||||
shell::server::xdg_toplevel::{ResizeEdge, State},
|
||||
},
|
||||
wayland_server::{
|
||||
protocol::{wl_output::WlOutput, wl_seat::WlSeat, wl_surface::WlSurface},
|
||||
Resource,
|
||||
},
|
||||
wayland_server::protocol::{wl_seat::WlSeat, wl_surface::WlSurface},
|
||||
},
|
||||
utils::Serial,
|
||||
utils::{Logical, Rectangle, Serial},
|
||||
wayland::{
|
||||
compositor,
|
||||
compositor::add_post_commit_hook,
|
||||
shell::xdg::{
|
||||
Configure, PopupSurface, PositionerState, ToplevelSurface, XdgShellHandler,
|
||||
PopupSurface, PositionerState, ShellClient, ToplevelSurface, XdgShellHandler,
|
||||
XdgShellState,
|
||||
},
|
||||
},
|
||||
};
|
||||
use std::sync::{Arc, Weak};
|
||||
use tracing::warn;
|
||||
|
||||
fn get_unconstrained_popup_geometry(positioner: &PositionerState) -> Geometry {
|
||||
positioner
|
||||
.get_unconstrained_geometry(Rectangle {
|
||||
loc: (-100000, -100000).into(),
|
||||
size: (200000, 200000).into(),
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
impl From<Rectangle<i32, Logical>> for Geometry {
|
||||
fn from(value: Rectangle<i32, Logical>) -> Self {
|
||||
Geometry {
|
||||
origin: [value.loc.x, value.loc.y].into(),
|
||||
size: [value.size.w as u32, value.size.h as u32].into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn surface_panel_item(wl_surface: &WlSurface) -> Option<Arc<PanelItem<XdgBackend>>> {
|
||||
let panel_item = wl_surface
|
||||
.get_data::<Weak<PanelItem<XdgBackend>>>()
|
||||
.as_ref()
|
||||
.and_then(Weak::upgrade);
|
||||
if panel_item.is_none() {
|
||||
warn!("Couldn't get panel item");
|
||||
}
|
||||
panel_item
|
||||
}
|
||||
|
||||
impl XdgShellHandler for WaylandState {
|
||||
fn xdg_shell_state(&mut self) -> &mut XdgShellState {
|
||||
&mut self.xdg_shell_state
|
||||
&mut self.xdg_shell
|
||||
}
|
||||
|
||||
fn new_toplevel(&mut self, surface: ToplevelSurface) {
|
||||
self.output
|
||||
.enter(&self.display_handle, surface.wl_surface());
|
||||
surface.with_pending_state(|state| {
|
||||
state.states.set(State::Maximized);
|
||||
state.states.set(State::Activated);
|
||||
state.decoration_mode = Some(Mode::ServerSide);
|
||||
fn new_client(&mut self, _client: ShellClient) {}
|
||||
fn client_destroyed(&mut self, _client: ShellClient) {}
|
||||
|
||||
fn new_toplevel(&mut self, toplevel: ToplevelSurface) {
|
||||
toplevel.wl_surface().insert_data(SurfaceId::Toplevel(()));
|
||||
toplevel.with_pending_state(|s| {
|
||||
s.decoration_mode = Some(Mode::ServerSide);
|
||||
s.states.set(State::TiledTop);
|
||||
s.states.set(State::TiledBottom);
|
||||
s.states.set(State::TiledLeft);
|
||||
s.states.set(State::TiledRight);
|
||||
s.states.set(State::Maximized);
|
||||
s.states.unset(State::Fullscreen);
|
||||
});
|
||||
surface.send_configure();
|
||||
}
|
||||
fn ack_configure(&mut self, surface: WlSurface, configure: Configure) {
|
||||
match configure {
|
||||
Configure::Toplevel(config) => {
|
||||
if let Some(size) = config.state.size {
|
||||
compositor::with_states(&surface, |data| {
|
||||
if let Some(panel_node) = data.data_map.get::<Arc<Node>>() {
|
||||
if let Some(core_surface) = data.data_map.get::<Arc<CoreSurface>>() {
|
||||
let panel_item = PanelItem::from_node(panel_node);
|
||||
let has_data = core_surface
|
||||
.with_data(|data| {
|
||||
data.size.x = size.w as u32;
|
||||
data.size.y = size.h as u32;
|
||||
})
|
||||
.is_some();
|
||||
if has_data {
|
||||
panel_item.resize();
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
toplevel.send_configure();
|
||||
|
||||
let initial_size = toplevel
|
||||
.wl_surface()
|
||||
.get_size()
|
||||
.unwrap_or(Vector2::from([0; 2]));
|
||||
|
||||
let initial_toplevel_info = ToplevelInfo {
|
||||
parent: toplevel.wl_surface().get_parent(),
|
||||
title: toplevel.wl_surface().get_title(),
|
||||
app_id: toplevel.wl_surface().get_app_id(),
|
||||
size: initial_size,
|
||||
min_size: toplevel
|
||||
.wl_surface()
|
||||
.min_size()
|
||||
.map(|s| Vector2::from([s.x as f32, s.y as f32])),
|
||||
max_size: toplevel
|
||||
.wl_surface()
|
||||
.max_size()
|
||||
.map(|s| Vector2::from([s.x as f32, s.y as f32])),
|
||||
logical_rectangle: toplevel.wl_surface().get_geometry().unwrap_or(Geometry {
|
||||
origin: [0; 2].into(),
|
||||
size: initial_size,
|
||||
}),
|
||||
};
|
||||
toplevel
|
||||
.wl_surface()
|
||||
.insert_data(Mutex::new(initial_toplevel_info));
|
||||
|
||||
CoreSurface::add_to(toplevel.wl_surface());
|
||||
|
||||
add_post_commit_hook(
|
||||
toplevel.wl_surface(),
|
||||
|_state: &mut WaylandState, _dh, surf| {
|
||||
let parent = surf.get_parent();
|
||||
let new_size = surf.get_size().unwrap_or(Vector2::from([0; 2]));
|
||||
let min_size = surf
|
||||
.min_size()
|
||||
.map(|s| Vector2::from([s.x as f32, s.y as f32]));
|
||||
let max_size = surf
|
||||
.max_size()
|
||||
.map(|s| Vector2::from([s.x as f32, s.y as f32]));
|
||||
let logical_rectangle = surf.get_geometry().unwrap_or_default();
|
||||
|
||||
let mut size_changed = false;
|
||||
surf.with_toplevel_info(|info| {
|
||||
info.parent = parent;
|
||||
if new_size != info.size {
|
||||
info.size = new_size;
|
||||
size_changed = true;
|
||||
}
|
||||
info.min_size = min_size;
|
||||
info.max_size = max_size;
|
||||
info.logical_rectangle = logical_rectangle;
|
||||
});
|
||||
|
||||
if size_changed {
|
||||
let Some(panel_item) = surface_panel_item(surf) else {
|
||||
return;
|
||||
};
|
||||
if let Some(toplevel_info) = surf.get_toplevel_info() {
|
||||
panel_item.toplevel_size_changed(toplevel_info.size);
|
||||
}
|
||||
}
|
||||
}
|
||||
Configure::Popup(_) => (),
|
||||
},
|
||||
);
|
||||
|
||||
add_post_commit_hook(
|
||||
toplevel.wl_surface(),
|
||||
|state: &mut WaylandState, _dh, surf| {
|
||||
if surface_panel_item(surf).is_some() {
|
||||
return;
|
||||
}
|
||||
let client = surf.client().unwrap();
|
||||
let client_state = client.get_data::<ClientState>().unwrap();
|
||||
let Some(toplevel) = state
|
||||
.xdg_shell
|
||||
.toplevel_surfaces()
|
||||
.iter()
|
||||
.find(|s| s.wl_surface() == surf)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let (node, panel_item) = PanelItem::create(
|
||||
Box::new(XdgBackend::create(
|
||||
toplevel.clone(),
|
||||
client_state.seat.clone(),
|
||||
)),
|
||||
client_state.pid,
|
||||
);
|
||||
handle_cursor(&panel_item, panel_item.backend.seat.cursor_info_rx.clone());
|
||||
surf.insert_data(Arc::downgrade(&panel_item));
|
||||
surf.insert_data(node);
|
||||
},
|
||||
);
|
||||
}
|
||||
fn toplevel_destroyed(&mut self, toplevel: ToplevelSurface) {
|
||||
let Some(panel_item) = surface_panel_item(toplevel.wl_surface()) else {
|
||||
return;
|
||||
};
|
||||
panel_item.backend.seat.unfocus(toplevel.wl_surface(), self);
|
||||
panel_item.backend.toplevel.lock().take();
|
||||
panel_item.backend.children.lock().clear();
|
||||
}
|
||||
fn app_id_changed(&mut self, toplevel: ToplevelSurface) {
|
||||
let wl_surface = toplevel.wl_surface();
|
||||
let Some(app_id) = wl_surface.get_app_id() else {
|
||||
return;
|
||||
};
|
||||
|
||||
wl_surface.with_toplevel_info(|info| {
|
||||
info.app_id = Some(app_id.clone());
|
||||
});
|
||||
|
||||
let Some(panel_item) = surface_panel_item(wl_surface) else {
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_app_id_changed(&app_id)
|
||||
}
|
||||
|
||||
fn title_changed(&mut self, toplevel: ToplevelSurface) {
|
||||
let wl_surface = toplevel.wl_surface();
|
||||
let Some(title) = wl_surface.get_title() else {
|
||||
return;
|
||||
};
|
||||
|
||||
wl_surface.with_toplevel_info(|info| {
|
||||
info.title = Some(title.clone());
|
||||
});
|
||||
|
||||
let Some(panel_item) = surface_panel_item(wl_surface) else {
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_title_changed(&title)
|
||||
}
|
||||
|
||||
fn new_popup(&mut self, popup: PopupSurface, positioner: PositionerState) {
|
||||
let id = rand::thread_rng().gen_range(0..u64::MAX);
|
||||
popup.wl_surface().insert_data(SurfaceId::Child(id));
|
||||
let Some(parent) = popup.get_parent_surface() else {
|
||||
return;
|
||||
};
|
||||
let _ = popup.send_configure();
|
||||
CoreSurface::add_to(popup.wl_surface());
|
||||
|
||||
popup.wl_surface().insert_data(Mutex::new(ChildInfo {
|
||||
id,
|
||||
parent: parent.get_data::<SurfaceId>().unwrap(),
|
||||
geometry: get_unconstrained_popup_geometry(&positioner),
|
||||
z_order: 1,
|
||||
receives_input: true,
|
||||
}));
|
||||
|
||||
let Some(panel_item) = surface_panel_item(&parent) else {
|
||||
return;
|
||||
};
|
||||
let panel_item_weak = Arc::downgrade(&panel_item);
|
||||
add_post_commit_hook(
|
||||
popup.wl_surface(),
|
||||
move |_: &mut WaylandState, _dh, surf| {
|
||||
if surface_panel_item(surf).is_some() {
|
||||
return;
|
||||
}
|
||||
surf.insert_data(panel_item_weak.clone());
|
||||
let Some(panel) = surface_panel_item(surf) else {
|
||||
return;
|
||||
};
|
||||
panel.backend.new_child(surf);
|
||||
},
|
||||
);
|
||||
}
|
||||
fn reposition_request(
|
||||
&mut self,
|
||||
popup: PopupSurface,
|
||||
positioner: PositionerState,
|
||||
_token: u32,
|
||||
) {
|
||||
let Some(panel_item) = surface_panel_item(popup.wl_surface()) else {
|
||||
return;
|
||||
};
|
||||
|
||||
popup.wl_surface().with_child_info(|ci| {
|
||||
ci.geometry = get_unconstrained_popup_geometry(&positioner);
|
||||
});
|
||||
|
||||
panel_item.backend.reposition_child(popup.wl_surface());
|
||||
}
|
||||
fn popup_destroyed(&mut self, popup: PopupSurface) {
|
||||
let Some(panel_item) = surface_panel_item(popup.wl_surface()) else {
|
||||
return;
|
||||
};
|
||||
panel_item.backend.seat.unfocus(popup.wl_surface(), self);
|
||||
panel_item.backend.drop_child(popup.wl_surface());
|
||||
}
|
||||
|
||||
fn grab(&mut self, _popup: PopupSurface, _seat: WlSeat, _serial: Serial) {}
|
||||
|
||||
fn move_request(&mut self, toplevel: ToplevelSurface, _seat: WlSeat, _serial: Serial) {
|
||||
let Some(panel_item) = surface_panel_item(toplevel.wl_surface()) else {
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_move_request();
|
||||
}
|
||||
fn resize_request(
|
||||
&mut self,
|
||||
toplevel: ToplevelSurface,
|
||||
_seat: WlSeat,
|
||||
_serial: Serial,
|
||||
edges: ResizeEdge,
|
||||
) {
|
||||
let Some(panel_item) = surface_panel_item(toplevel.wl_surface()) else {
|
||||
return;
|
||||
};
|
||||
let (up, down, left, right) = match edges {
|
||||
ResizeEdge::None => (false, false, false, false),
|
||||
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 maximize_request(&mut self, toplevel: ToplevelSurface) {
|
||||
toplevel.with_pending_state(|s| {
|
||||
s.states.set(State::Maximized);
|
||||
s.states.unset(State::Fullscreen);
|
||||
});
|
||||
toplevel.send_configure();
|
||||
|
||||
let Some(panel_item) = surface_panel_item(toplevel.wl_surface()) else {
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_fullscreen_active(false);
|
||||
}
|
||||
fn fullscreen_request(&mut self, toplevel: ToplevelSurface, _output: Option<WlOutput>) {
|
||||
toplevel.with_pending_state(|s| {
|
||||
s.states.set(State::Fullscreen);
|
||||
s.states.unset(State::Maximized);
|
||||
});
|
||||
toplevel.send_configure();
|
||||
|
||||
let Some(panel_item) = surface_panel_item(toplevel.wl_surface()) else {
|
||||
return;
|
||||
};
|
||||
panel_item.toplevel_fullscreen_active(true);
|
||||
}
|
||||
}
|
||||
delegate_xdg_shell!(WaylandState);
|
||||
|
||||
pub struct XdgBackend {
|
||||
toplevel: Mutex<Option<ToplevelSurface>>,
|
||||
pub children: Mutex<FxHashMap<u64, WlSurface>>,
|
||||
seat: Arc<SeatWrapper>,
|
||||
}
|
||||
impl XdgBackend {
|
||||
pub fn create(toplevel: ToplevelSurface, seat: Arc<SeatWrapper>) -> Self {
|
||||
XdgBackend {
|
||||
toplevel: Mutex::new(Some(toplevel)),
|
||||
children: Mutex::new(FxHashMap::default()),
|
||||
seat,
|
||||
}
|
||||
}
|
||||
fn wl_surface_from_id(&self, id: &SurfaceId) -> Option<WlSurface> {
|
||||
match id {
|
||||
SurfaceId::Toplevel(_) => Some(self.toplevel.lock().clone()?.wl_surface().clone()),
|
||||
SurfaceId::Child(id) => self.children.lock().get(id).cloned(),
|
||||
}
|
||||
}
|
||||
fn panel_item(&self) -> Option<Arc<PanelItem<XdgBackend>>> {
|
||||
surface_panel_item(self.toplevel.lock().clone()?.wl_surface())
|
||||
}
|
||||
|
||||
pub fn new_child(&self, surface: &WlSurface) {
|
||||
let Some(panel_item) = self.panel_item() else {
|
||||
return;
|
||||
};
|
||||
let Some(child_info) = surface.get_child_info() else {
|
||||
return;
|
||||
};
|
||||
|
||||
self.children.lock().insert(child_info.id, surface.clone());
|
||||
panel_item.create_child(child_info.id, &child_info);
|
||||
}
|
||||
pub fn reposition_child(&self, surface: &WlSurface) {
|
||||
let Some(panel_item) = self.panel_item() else {
|
||||
return;
|
||||
};
|
||||
let Some(child_info) = surface.get_child_info() else {
|
||||
return;
|
||||
};
|
||||
|
||||
panel_item.reposition_child(child_info.id, &child_info.geometry);
|
||||
}
|
||||
pub fn drop_child(&self, surface: &WlSurface) {
|
||||
let Some(panel_item) = self.panel_item() else {
|
||||
return;
|
||||
};
|
||||
let Some(child_info) = surface.get_child_info() else {
|
||||
return;
|
||||
};
|
||||
panel_item.destroy_child(child_info.id);
|
||||
self.children.lock().remove(&child_info.id);
|
||||
}
|
||||
}
|
||||
impl Backend for XdgBackend {
|
||||
fn start_data(&self) -> Result<PanelItemInitData> {
|
||||
let cursor = self
|
||||
.seat
|
||||
.cursor_info_rx
|
||||
.borrow()
|
||||
.surface
|
||||
.clone()
|
||||
.and_then(|s| s.upgrade().ok())
|
||||
.as_ref()
|
||||
.and_then(|c| c.get_size())
|
||||
.map(|size| Geometry {
|
||||
origin: [0; 2].into(),
|
||||
size,
|
||||
});
|
||||
|
||||
let toplevel_info = self
|
||||
.toplevel
|
||||
.lock()
|
||||
.as_ref()
|
||||
.and_then(|toplevel| toplevel.wl_surface().get_toplevel_info())
|
||||
.ok_or(eyre!("Internal: no toplevel or ToplevelInfo"))?;
|
||||
|
||||
let children = self
|
||||
.children
|
||||
.lock()
|
||||
.values()
|
||||
.filter_map(|v| v.get_child_info())
|
||||
.collect();
|
||||
|
||||
Ok(PanelItemInitData {
|
||||
cursor,
|
||||
toplevel: toplevel_info,
|
||||
children,
|
||||
pointer_grab: None,
|
||||
keyboard_grab: None,
|
||||
})
|
||||
}
|
||||
fn apply_cursor_material(&self, model_part: &Arc<ModelPart>) {
|
||||
let Some(surface) = self
|
||||
.seat
|
||||
.cursor_info_rx
|
||||
.borrow()
|
||||
.surface
|
||||
.clone()
|
||||
.and_then(|s| s.upgrade().ok())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(core_surface) = CoreSurface::from_wl_surface(&surface) else {
|
||||
return;
|
||||
};
|
||||
core_surface.apply_material(model_part);
|
||||
}
|
||||
fn apply_surface_material(&self, surface: SurfaceId, model_part: &Arc<ModelPart>) {
|
||||
let Some(surface) = self.wl_surface_from_id(&surface) else {
|
||||
return;
|
||||
};
|
||||
let Some(core_surface) = CoreSurface::from_wl_surface(&surface) else {
|
||||
return;
|
||||
};
|
||||
core_surface.apply_material(model_part);
|
||||
}
|
||||
|
||||
fn close_toplevel(&self) {
|
||||
if let Some(toplevel) = self.toplevel.lock().clone() {
|
||||
toplevel.send_close();
|
||||
}
|
||||
}
|
||||
|
||||
fn new_popup(&mut self, _surface: PopupSurface, _positioner: PositionerState) {}
|
||||
fn grab(&mut self, _surface: PopupSurface, _seat: WlSeat, _serial: Serial) {}
|
||||
fn auto_size_toplevel(&self) {
|
||||
let Some(toplevel) = self.toplevel.lock().clone() else {
|
||||
return;
|
||||
};
|
||||
toplevel.with_pending_state(|s| s.size = None);
|
||||
toplevel.send_configure();
|
||||
}
|
||||
fn set_toplevel_size(&self, size: Vector2<u32>) {
|
||||
let Some(toplevel) = self.toplevel.lock().clone() else {
|
||||
return;
|
||||
};
|
||||
toplevel.with_pending_state(|s| {
|
||||
s.size = Some((size.x.max(16) as i32, size.y.max(16) as i32).into())
|
||||
});
|
||||
toplevel.send_pending_configure();
|
||||
}
|
||||
fn set_toplevel_focused_visuals(&self, focused: bool) {
|
||||
let Some(toplevel) = self.toplevel.lock().clone() else {
|
||||
return;
|
||||
};
|
||||
toplevel.with_pending_state(|s| {
|
||||
if focused {
|
||||
s.states.set(State::Activated);
|
||||
} else {
|
||||
s.states.unset(State::Activated);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn pointer_motion(&self, surface: &SurfaceId, position: Vector2<f32>) {
|
||||
let Some(surface) = self.wl_surface_from_id(surface) else {
|
||||
return;
|
||||
};
|
||||
self.seat.pointer_motion(surface, position)
|
||||
}
|
||||
fn pointer_button(&self, _surface: &SurfaceId, button: u32, pressed: bool) {
|
||||
self.seat.pointer_button(button, pressed)
|
||||
}
|
||||
fn pointer_scroll(
|
||||
&self,
|
||||
_surface: &SurfaceId,
|
||||
scroll_distance: Option<Vector2<f32>>,
|
||||
scroll_steps: Option<Vector2<f32>>,
|
||||
) {
|
||||
self.seat.pointer_scroll(scroll_distance, scroll_steps)
|
||||
}
|
||||
|
||||
fn keyboard_keys(&self, surface: &SurfaceId, keymap_id: u64, keys: Vec<i32>) {
|
||||
let Some(surface) = self.wl_surface_from_id(surface) else {
|
||||
return;
|
||||
};
|
||||
self.seat.keyboard_keys(surface, keymap_id, keys)
|
||||
}
|
||||
|
||||
fn touch_down(&self, surface: &SurfaceId, id: u32, position: Vector2<f32>) {
|
||||
let Some(surface) = self.wl_surface_from_id(surface) else {
|
||||
return;
|
||||
};
|
||||
self.seat.touch_down(surface, id, position)
|
||||
}
|
||||
fn touch_move(&self, id: u32, position: Vector2<f32>) {
|
||||
self.seat.touch_move(id, position)
|
||||
}
|
||||
fn touch_up(&self, id: u32) {
|
||||
self.seat.touch_up(id)
|
||||
}
|
||||
fn reset_input(&self) {
|
||||
self.seat.reset_input()
|
||||
}
|
||||
}
|
||||
delegate_xdg_shell!(WaylandState);
|
||||
|
||||
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