Compare commits
654 Commits
bot
...
graphics-b
| Author | SHA1 | Date | |
|---|---|---|---|
|
8c66b0bd72
|
|||
|
7c16b41717
|
|||
|
69f182bca1
|
|||
|
9c30fa04a5
|
|||
|
ad4de709da
|
|||
|
288ce04060
|
|||
|
4898a5f866
|
|||
|
1d1f9cd00d
|
|||
|
310d9f837e
|
|||
|
e0c8c92eb1
|
|||
|
f40b28b776
|
|||
|
33353b36b7
|
|||
|
68f8b3bc53
|
|||
|
d7d1a6f9b6
|
|||
|
e4e8b70118
|
|||
|
76e50231c2
|
|||
|
170be30284
|
|||
|
7193b96e7c
|
|||
|
b3bccb9f50
|
|||
|
8f04516f78
|
|||
|
e1313e1e73
|
|||
| 48316a677a | |||
|
9b6be8bc68
|
|||
|
93988affd7
|
|||
|
78a80212d2
|
|||
|
125e718ec8
|
|||
|
0be912cc61
|
|||
|
cd91cca93f
|
|||
|
78d89ed3d9
|
|||
|
87853d3de8
|
|||
|
e33a419b99
|
|||
|
797b5d2100
|
|||
|
36447a76cf
|
|||
|
44f988ea4a
|
|||
|
7c14acb377
|
|||
|
98421ed24a
|
|||
|
4ebd251273
|
|||
|
05534a4863
|
|||
|
4dab573a3c
|
|||
|
841ae94255
|
|||
|
c44f4863bb
|
|||
|
298a7fcbde
|
|||
|
7a3ea40551
|
|||
|
4615ee24f3
|
|||
|
251f7cc627
|
|||
|
5519a9c4d9
|
|||
|
378619045f
|
|||
|
67d39d5e03
|
|||
|
daeabab337
|
|||
|
c3b9496e15
|
|||
|
c606adaaeb
|
|||
|
85589f0b00
|
|||
|
9d26e8cf6d
|
|||
|
80c4c1e50d
|
|||
|
0df71c6c57
|
|||
|
1a04188b8a
|
|||
|
aae7a23753
|
|||
|
96234f6bb1
|
|||
|
1cdd4676d7
|
|||
|
b7e1c8d723
|
|||
|
f781d104ab
|
|||
|
a710e33072
|
|||
|
971e95afd9
|
|||
|
e8a13d86ec
|
|||
|
2e1e8f524c
|
|||
|
7151c53553
|
|||
|
e06e51628a
|
|||
|
ea362d18a8
|
|||
|
13734bfe17
|
|||
|
74bd6d0e84
|
|||
|
ab09e384d3
|
|||
|
99d38a6eae
|
|||
|
e0d1ad48a8
|
|||
|
58ea19fbea
|
|||
|
d5791ac7a1
|
|||
| db7d7b3b36 | |||
|
06d0d70791
|
|||
|
4aab9679bf
|
|||
|
d32dcc5a58
|
|||
|
fa43f764f6
|
|||
|
4ce8516664
|
|||
|
d6441c86bc
|
|||
|
3371f3359b
|
|||
|
34d5288620
|
|||
|
82de08312d
|
|||
|
4b224b1827
|
|||
|
42862ce573
|
|||
|
3690954042
|
|||
|
bfe4b491d7
|
|||
|
36f44ffd43
|
|||
|
7f16468104
|
|||
|
a870899743
|
|||
|
b5431c0732
|
|||
|
36ccbdc6b2
|
|||
|
a68f009658
|
|||
|
118a1639a7
|
|||
|
3212fb1d41
|
|||
|
424c7ce9a6
|
|||
|
3174f9caa9
|
|||
|
b8e5343464
|
|||
|
51e7703933
|
|||
|
e46f54efe0
|
|||
|
b2993995bb
|
|||
|
7963c3632b
|
|||
|
67680312dd
|
|||
|
1a0a3403f0
|
|||
|
9e65a6eb95
|
|||
|
ebc897aad8
|
|||
|
23a6655bb0
|
|||
|
0422c223cd
|
|||
|
5db2ce076d
|
|||
|
c98364b68d
|
|||
|
b7e8fb6e18
|
|||
|
d343056664
|
|||
|
534f2a2141
|
|||
|
79ea88fc74
|
|||
|
3fd507be94
|
|||
| 0fbe37e483 | |||
|
638c2b4329
|
|||
|
317e1d57c7
|
|||
|
562e46a87e
|
|||
|
3c13d5f8ec
|
|||
|
1f0f78f9d8
|
|||
|
a90cb53a20
|
|||
|
170e2b9bce
|
|||
| 3e0fc54852 | |||
|
acea52646a
|
|||
|
7220506fd5
|
|||
|
8f94234ddc
|
|||
|
36143b8b69
|
|||
|
3893b2f44f
|
|||
|
d62ff68baa
|
|||
|
2331bef281
|
|||
| 31b52f7c34 | |||
|
b12c495a33
|
|||
|
8329eadb18
|
|||
|
4b2f93be66
|
|||
|
469ab48156
|
|||
|
c2650adf54
|
|||
| cdafbb4077 | |||
|
087e95b1f7
|
|||
|
e46a51319f
|
|||
|
a3b0306430
|
|||
|
e024f37843
|
|||
|
4059cfa527
|
|||
|
e4f3418bc6
|
|||
|
6ca6d5e484
|
|||
|
0668ac2def
|
|||
|
73e3181d0c
|
|||
|
19ba8f2445
|
|||
|
0495d07e26
|
|||
|
0ea353b27d
|
|||
|
99706079d9
|
|||
|
730c5fb7dd
|
|||
|
d1b61bb997
|
|||
|
0343ad19cf
|
|||
|
43210b1417
|
|||
|
e9d28cf15f
|
|||
|
452bac4049
|
|||
|
48aad78f59
|
|||
|
d45a42f5aa
|
|||
|
c219fec3bc
|
|||
|
2a05d50abb
|
|||
|
fbb047f8d4
|
|||
|
c4d837a552
|
|||
|
a08bd44789
|
|||
|
4ae5359046
|
|||
|
15ecaf602a
|
|||
|
1e0511a7ba
|
|||
|
a9e4705d89
|
|||
| 98069859b5 | |||
|
64d3996fa9
|
|||
|
49c0c16e35
|
|||
|
255bed4803
|
|||
|
128e137829
|
|||
|
1e19f804cc
|
|||
|
f6f35c5f54
|
|||
|
4e7d580918
|
|||
|
8d5a100a2e
|
|||
|
91208db706
|
|||
|
5a320b514e
|
|||
| 661d706a22 | |||
| 5550d5771e | |||
| c834d1d1ca | |||
| ca9d2238a7 | |||
|
f3bb8dd067
|
|||
|
e58f9b9ff2
|
|||
|
54c4ed6bad
|
|||
|
9aceafa0df
|
|||
|
d065bac130
|
|||
|
a4d0393556
|
|||
|
3692d7f79e
|
|||
|
7e49840768
|
|||
|
4ecdd547c6
|
|||
|
b0365165e8
|
|||
|
c2ff52a2ae
|
|||
|
6e778869e8
|
|||
|
6509bef070
|
|||
|
0fa097a004
|
|||
|
55d4b1d264
|
|||
|
ea28663e95
|
|||
|
bac9be9684
|
|||
|
7e76f3309b
|
|||
|
cfd9550566
|
|||
|
bd16720b5a
|
|||
|
633f767d0f
|
|||
|
602b63e953
|
|||
|
6abe622885
|
|||
|
0ab23dde2b
|
|||
|
657a2530dc
|
|||
|
c4bd034928
|
|||
|
bbcdac8879
|
|||
|
38b3f3d7a3
|
|||
|
eb80c8b9b5
|
|||
|
63714f190d
|
|||
|
f50dfb9399
|
|||
|
9db39d2a62
|
|||
|
9e2e1d9d4a
|
|||
|
6f1548403a
|
|||
|
5f3e998b3d
|
|||
|
2d8792be4f
|
|||
|
15d33eb49d
|
|||
|
156dacb838
|
|||
|
a7f0e431cb
|
|||
|
0ed3cb2adb
|
|||
|
bac43eab66
|
|||
|
2a257236fd
|
|||
|
8fe2c20635
|
|||
|
2da7ccce7c
|
|||
|
89e6d11630
|
|||
|
6abb40b6d2
|
|||
|
4dcf06c44c
|
|||
|
0171a711d9
|
|||
|
3eb702eaea
|
|||
|
92878a4ae8
|
|||
|
88dcf40d77
|
|||
|
df9fcb5b02
|
|||
|
b07064cc9d
|
|||
|
6e435e46ac
|
|||
|
ce0368590d
|
|||
|
f896e6cfff
|
|||
|
dcc91db6f7
|
|||
|
b6d6878137
|
|||
|
81c9e3470b
|
|||
|
b45e02c487
|
|||
|
8698ca4a7e
|
|||
|
8f04953326
|
|||
|
ae81d8ceaf
|
|||
|
2ecaeb1615
|
|||
|
768cd4ad1a
|
|||
|
708462441a
|
|||
|
da3ab52fe0
|
|||
|
20f3e79cde
|
|||
|
217f7fd7c3
|
|||
|
1e4d98f386
|
|||
|
71bce361e6
|
|||
|
d36c184f7e
|
|||
|
2c3f257f0e
|
|||
|
9e7e115809
|
|||
|
2ea60b07fe
|
|||
|
2fe884175e
|
|||
|
9f570d0f3e
|
|||
|
6e6bafe719
|
|||
|
5f0ddc2f28
|
|||
|
ba1c1ec8c6
|
|||
|
67cafd8cbb
|
|||
|
ca88eb1cad
|
|||
|
2bf34fd04c
|
|||
|
b5da30fd9a
|
|||
|
95fffbbf42
|
|||
|
9a636d5b50
|
|||
|
2c8954c2b4
|
|||
|
985a703811
|
|||
|
37dbe35222
|
|||
|
f0de24d161
|
|||
|
7d5ff55803
|
|||
|
7fffe05751
|
|||
|
2ac38efef6
|
|||
|
5881e593b2
|
|||
|
64a4499544
|
|||
|
fca9e1c325
|
|||
|
6a88003b09
|
|||
|
08b358c192
|
|||
|
62d9bcff81
|
|||
|
08f9163605
|
|||
|
b507624d91
|
|||
|
d8358ec25c
|
|||
|
e673a12beb
|
|||
|
18269423a5
|
|||
|
1d82799400
|
|||
|
3a9fdebb4d
|
|||
|
f8ef17e3f5
|
|||
|
8b2f37d3d5
|
|||
|
16dfe7524f
|
|||
|
3d399635d7
|
|||
|
8bfc201d1f
|
|||
|
bb8e131464
|
|||
|
05bbe05979
|
|||
|
17a2199f36
|
|||
|
84db6503f9
|
|||
|
5b5f356863
|
|||
|
d07571519e
|
|||
|
6464343428
|
|||
|
534b45d7dd
|
|||
|
3ff8ccf58d
|
|||
|
67d2a3e398
|
|||
|
c1f8a13888
|
|||
|
e11af82443
|
|||
|
5b1d5502d8
|
|||
|
f48d86fe56
|
|||
|
877964be1f
|
|||
|
62d983ef2a
|
|||
|
8b7a4ee8c1
|
|||
|
7ebcfa7bc3
|
|||
|
c98f53a151
|
|||
|
94025b52e2
|
|||
|
213d2f3f6a
|
|||
|
438a22bd86
|
|||
|
e6fb8437b3
|
|||
|
8b6166f48e
|
|||
|
3f89f2c1c5
|
|||
|
c6ebb179a1
|
|||
|
14fa450e3e
|
|||
|
448f40a5d8
|
|||
|
4ecdcec17c
|
|||
|
261b88ada6
|
|||
|
5ea0a1b07d
|
|||
|
3b8d32913e
|
|||
|
3928431ac7
|
|||
|
6ecf403a4f
|
|||
|
1f7ee20c1e
|
|||
|
19c30c8701
|
|||
|
dabb25b3d3
|
|||
|
78593200eb
|
|||
|
7649d30b55
|
|||
|
6af8dd3c1f
|
|||
|
861a8afc47
|
|||
|
f0b2470039
|
|||
|
c0ad20d54c
|
|||
|
9aea73e134
|
|||
|
b34d3f89f9
|
|||
|
5600948d8a
|
|||
|
d722bcb46f
|
|||
|
081c95190f
|
|||
|
d1f4e2132f
|
|||
|
5317d96243
|
|||
|
8bb20ffe81
|
|||
|
03b16db10a
|
|||
|
f0d4915fba
|
|||
|
6e8da50b35
|
|||
|
615372aad5
|
|||
|
08d47b0f63
|
|||
|
08b5445838
|
|||
|
fa07d16cf4
|
|||
|
327688d79e
|
|||
|
1662d814ec
|
|||
|
a3d39a81d0
|
|||
|
cb31c847d5
|
|||
|
f579370841
|
|||
|
2a542e0026
|
|||
|
ca51256a16
|
|||
| 65e17da386 | |||
| 1cf21be185 | |||
| 413e176741 | |||
| 39b2397d5e | |||
| 2ed01dffbd | |||
| d0ee597416 | |||
| be85530000 | |||
| 55ff199269 | |||
| 02615af1fd | |||
| 6594ffa87e | |||
| 6295dc68ef | |||
| 8fb0d30e1d | |||
| 0fb0230cb1 | |||
| bdb1090664 | |||
| 3ce7746489 | |||
| 7978050f8a | |||
| 77ee36fa72 | |||
| 0fc1ec3086 | |||
| f60c03ac56 | |||
| b570d8809d | |||
| 3f268ec034 | |||
| ba161ef6d1 | |||
| 0755d4413c | |||
| 459cb13957 | |||
| a5ad7d4d6e | |||
| 3d5e76f078 | |||
| 78c53ae429 | |||
| e794b2649c | |||
| 50f6fe5bd8 | |||
| fc3681f41f | |||
| a2369b4211 | |||
| bfea49ffae | |||
| 8c7063d340 | |||
| 651150760c | |||
| 3d203e2da9 | |||
| 3798f438cf | |||
| 4ace8317fe | |||
| ab4a9bb922 | |||
| a9ef07ce78 | |||
| 561e41c760 | |||
| 9896a09576 | |||
| 82840fa6cb | |||
| 2c87cb71df | |||
| 709f622547 | |||
| b20264b382 | |||
| 17cce2d702 | |||
| a2b2ddc9ce | |||
| cb57d893e0 | |||
| 9e8d66cec1 | |||
| 39fe833198 | |||
| e7688a95fd | |||
| d2cc98b04d | |||
| 9e887580af | |||
| 92feac572e | |||
| fd02a40783 | |||
| 7c787a0e0f | |||
| 6a7c076203 | |||
| af3abbcb4d | |||
| 4859c37780 | |||
| 19e65802f6 | |||
| 2cf1547423 | |||
| 63305f91c7 | |||
| e875826250 | |||
| 0a44c1630f | |||
| 5cffc03ef6 | |||
| d638e633ba | |||
| 61e44f2aba | |||
| 347b1176d2 | |||
| 7c0ad5b601 | |||
| 62851bbd60 | |||
| b3a6d08656 | |||
| 5409548348 | |||
| 57552c1a6a | |||
| aace3bb2a3 | |||
| 4899003766 | |||
| 0c991715ab | |||
| 72e0caa84a | |||
| 4805d237e2 | |||
| 8e91fbb08e | |||
| a2a69c48d6 | |||
| e74535d91f | |||
| dbca48f051 | |||
| ad6584d82a | |||
| ceb5fff333 | |||
| c6f31a3eb5 | |||
| 6c81fc43bb | |||
| 5317cd0609 | |||
| 09d151ee1c | |||
| 441b9a8559 | |||
| 707ff98d27 | |||
| 2c1910bc24 | |||
| 614535ce8c | |||
| 78c29657d6 | |||
| 9d9695f363 | |||
| ce3d8fde11 | |||
| 1ddc013fd0 | |||
| d0d2e6eca3 | |||
| 1ba7b0591b | |||
| 205db9a0db | |||
| ca50bf35c2 | |||
| 6522c255cd | |||
| 6b4122c59c | |||
| eb0365217d | |||
| c128046d88 | |||
| ff57825232 | |||
| 8e867449f0 | |||
| f028dc6c85 | |||
| 85480cb13e | |||
| a594f77453 | |||
| c356a9d654 | |||
| 23ee771c22 | |||
| a5079f21d7 | |||
| 349cd9c233 | |||
| d455cf4dc9 | |||
| 3227a6486a | |||
| 1ce51dd4da | |||
| 1ad9723905 | |||
| be9eb30a5c | |||
| 42310c5d2b | |||
| 988750a3c6 | |||
| 2f26662dda | |||
| 6f739dba8d | |||
| 2eaddd493d | |||
| d5a6f8e1bc | |||
| 95fb43b908 | |||
| 3e814cb41a | |||
| ea854a548f | |||
| 5f2cf8f32e | |||
| b6b090de78 | |||
| affbada62e | |||
| 8d2ba28700 | |||
| 3eb4e76ab2 | |||
| 5d31419370 | |||
| 44a58044c7 | |||
| 83ac776b78 | |||
| 871aadb78a | |||
| 65b49d2726 | |||
| ed70b7c484 | |||
| c7575f2e21 | |||
| c2f78eab48 | |||
| 195014400f | |||
| ee9585a4c2 | |||
| 77012d6caa | |||
| f9509353dd | |||
| 5bce4a84cf | |||
| 4bbccd68ed | |||
| 8be3be4002 | |||
| 76bafa4d0a | |||
| a612d1f864 | |||
| ad9ef141bf | |||
| 4c11980989 | |||
| 091da88b5c | |||
| 045e540020 | |||
| c14f8975fc | |||
| 8e228033e0 | |||
| eaecbc5b73 | |||
| 91a1b3d65e | |||
| e1d51ff2da | |||
| c5f2395b3a | |||
| 77aa83d6ac | |||
| 184b12a9cc | |||
| 9ba3484e25 | |||
| adcd7db4f1 | |||
| 710670d78e | |||
| 70e1514ef9 | |||
| 45e9b3d0ce | |||
| 1eac734c35 | |||
| 25e1312fe4 | |||
| cc8f6b059d | |||
| 4cd287dbb8 | |||
| 40ea0e6c7d | |||
| b45b92c627 | |||
| e90f53a111 | |||
| 6beb6c5f9a | |||
| a1507d4f26 | |||
| 77db5a7a6b | |||
| 41b28fa7d2 | |||
| a2ab23097b | |||
| 602061b44c | |||
| 1989369956 | |||
| a18aea828c | |||
| b7000ee9af | |||
| 2b77ea5712 | |||
| cf98f8e7bb | |||
|
a56c114d08
|
|||
|
b6a5324ae7
|
|||
| 6f5a3c5176 | |||
| 6bab31f3b3 | |||
| 9cdeed160f | |||
| d0c59b51a4 | |||
| 451f3ccecb | |||
| ed9701981d | |||
| 60e0197344 | |||
| 4d97a490c1 | |||
| 52ba44c6be | |||
| 95b6272b18 | |||
| 0172675b04 | |||
| 982b4aecac | |||
| c1ddcdb0c5 | |||
| c2d0a4487c | |||
| dc9fd2c442 | |||
| 4199d41d3f | |||
| 7fbcb206ff | |||
| a17901d473 | |||
| b88c6b899a | |||
| 835d4bbecd | |||
| b756dc979c | |||
| 1e888ebb01 | |||
| b9dccb1af5 | |||
| c6d293cc6b | |||
| a386f90f51 | |||
| 43115cbac6 | |||
| 35b5aff9a7 | |||
| 36419af870 | |||
| a7518bef46 | |||
| 6df1f41599 | |||
| 422d0a160d | |||
| 1727f9213c | |||
| afa9e7447d | |||
| ff85efa54f | |||
| fa69c53cfc | |||
| a57c228580 | |||
| 5dc69db885 | |||
| e54400a436 | |||
| e2a5edf8df | |||
| d6dd1b8abd | |||
| a2b793fcd3 | |||
| 9cb34f14c8 | |||
| bd2e3aa2d3 | |||
| 07f6053839 | |||
| 0d5b918ea1 | |||
| 20a568220a | |||
| d670d4129e | |||
| de7b0bd5cc | |||
| 01524146c7 | |||
| 45e8e415d0 | |||
| 4417bafc5c | |||
| 8553625738 | |||
| 3a3749eaeb | |||
| 53539f290b | |||
| 479dd37f53 | |||
| 34b6a869f0 | |||
| 19a455ee5e | |||
| 9904b7a044 | |||
| 6efa811eb6 | |||
| 81e4a201bd | |||
| 8fd5618af2 | |||
| 54c26d6e1e | |||
| 110ec94a08 | |||
| 980da5a6a7 | |||
| 1cd77984d4 | |||
| b0fe231388 | |||
| 5a4a39ab75 | |||
|
|
1b2324deeb | ||
| 4c485e76e4 | |||
| 7bbb9ca24f | |||
| eff55af1b4 | |||
| 0d05cc9996 | |||
| 2a55ef90df | |||
| 1a6202ae66 | |||
|
|
742f7b4ec0 | ||
| 2cb346f49a | |||
| e5cca9ed04 | |||
| 52d911a25a | |||
| 7ab20f36a7 | |||
| a7554da1c5 | |||
| 37f0dad7a1 | |||
| e309f15cb8 | |||
| 29374e4ff5 | |||
| b7d04d1f40 | |||
| 432ec11ea6 | |||
| 01449b1850 | |||
| 327d0a4992 | |||
| 420dbaa022 | |||
| cad29af4bb | |||
| e0e8744bfd | |||
| b434dce0f6 | |||
| 6ef8fd2f69 | |||
| 7234065bd8 | |||
| 41d8e700c5 | |||
| 4ca3d56f0f | |||
| 593b6902fd | |||
| 7523c4313a | |||
| 694440bd29 | |||
| 755e1d4d5b | |||
| 4334a6f330 | |||
| 553ad2cca5 | |||
| 3f15d2f5a8 | |||
| 206bb01c1a | |||
| df24bc9945 | |||
| 4c1632c0b6 | |||
| 9e482891ba | |||
| 38d1ff62ab |
@@ -1,6 +1,2 @@
|
||||
[registries.strafesnet]
|
||||
index = "sparse+https://git.itzana.me/api/packages/strafesnet/cargo/"
|
||||
|
||||
[target.x86_64-unknown-linux-gnu]
|
||||
linker = "clang"
|
||||
rustflags = ["-C", "link-arg=-fuse-ld=/usr/bin/mold"]
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1 +1,2 @@
|
||||
/target
|
||||
.zed
|
||||
|
||||
4101
Cargo.lock
generated
4101
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
38
Cargo.toml
38
Cargo.toml
@@ -1,5 +1,10 @@
|
||||
[workspace]
|
||||
members = [
|
||||
"engine/graphics",
|
||||
"engine/physics",
|
||||
"engine/session",
|
||||
"engine/settings",
|
||||
"integration-testing",
|
||||
"lib/bsp_loader",
|
||||
"lib/common",
|
||||
"lib/deferred_loader",
|
||||
@@ -7,8 +12,10 @@ members = [
|
||||
"lib/linear_ops",
|
||||
"lib/ratio_ops",
|
||||
"lib/rbx_loader",
|
||||
"lib/rbxassetid",
|
||||
"lib/roblox_emulator",
|
||||
"lib/snf",
|
||||
"map-tool",
|
||||
"strafe-client",
|
||||
]
|
||||
resolver = "2"
|
||||
@@ -17,3 +24,34 @@ resolver = "2"
|
||||
#lto = true
|
||||
strip = true
|
||||
codegen-units = 1
|
||||
|
||||
[workspace.lints.rust]
|
||||
# unsafe_code = "forbid"
|
||||
# missing_docs = "warn"
|
||||
# missing_debug_implementations = "warn"
|
||||
single_use_lifetimes = "warn"
|
||||
trivial_casts = "warn"
|
||||
unused_lifetimes = "warn"
|
||||
unused_qualifications = "warn"
|
||||
# variant_size_differences = "warn"
|
||||
unexpected_cfgs = "warn"
|
||||
|
||||
[workspace.dependencies]
|
||||
glam = "0.32.0"
|
||||
wgpu = "29.0.0"
|
||||
|
||||
# engine
|
||||
strafesnet_graphics = { path = "engine/graphics", registry = "strafesnet" }
|
||||
strafesnet_physics = { path = "engine/physics", registry = "strafesnet" }
|
||||
strafesnet_session = { path = "engine/session", registry = "strafesnet" }
|
||||
strafesnet_settings = { path = "engine/settings", registry = "strafesnet" }
|
||||
|
||||
# lib
|
||||
fixed_wide = { version = "0.3.0", path = "lib/fixed_wide", registry = "strafesnet" }
|
||||
linear_ops = { version = "0.2.0", path = "lib/linear_ops", registry = "strafesnet" }
|
||||
ratio_ops = { version = "0.1.0", path = "lib/ratio_ops", registry = "strafesnet" }
|
||||
strafesnet_bsp_loader = { version = "0.5.0", path = "lib/bsp_loader", registry = "strafesnet" }
|
||||
strafesnet_common = { version = "0.9.0", path = "lib/common", registry = "strafesnet" }
|
||||
strafesnet_deferred_loader = { version = "0.6.0", path = "lib/deferred_loader", registry = "strafesnet" }
|
||||
strafesnet_rbx_loader = { version = "0.10.2", path = "lib/rbx_loader", registry = "strafesnet" }
|
||||
strafesnet_snf = { version = "0.4.0", path = "lib/snf", registry = "strafesnet" }
|
||||
|
||||
@@ -3,6 +3,9 @@
|
||||
# Strafe Project
|
||||
Monorepo for working on projects related to strafe client.
|
||||
|
||||
## Try it out
|
||||
See [releases](https://git.itzana.me/StrafesNET/strafe-project/releases) for downloads.
|
||||
|
||||
## How to build and run
|
||||
1. Have rust and git installed
|
||||
2. `git clone https://git.itzana.me/StrafesNET/strafe-project`
|
||||
@@ -10,4 +13,4 @@ Monorepo for working on projects related to strafe client.
|
||||
4. `cargo run --release --bin strafe-client`
|
||||
|
||||
## Licenses
|
||||
Each project has its own license. Most crates are MIT/Apache but notably the Strafe Client has a sole proprietor license.
|
||||
Each project has its own license. Most crates are MIT/Apache but notably the Strafe Client and engine crates have a sole proprietor license.
|
||||
|
||||
15
engine/graphics/Cargo.toml
Normal file
15
engine/graphics/Cargo.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "strafesnet_graphics"
|
||||
version = "0.0.11-depth2"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
bytemuck = { version = "1.13.1", features = ["derive"] }
|
||||
ddsfile = "0.5.1"
|
||||
glam.workspace = true
|
||||
id = { version = "0.1.0", registry = "strafesnet" }
|
||||
strafesnet_common.workspace = true
|
||||
wgpu.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
8
engine/graphics/LICENSE
Normal file
8
engine/graphics/LICENSE
Normal file
@@ -0,0 +1,8 @@
|
||||
/*******************************************************
|
||||
* Copyright (C) 2023-2024 Rhys Lloyd <krakow20@gmail.com>
|
||||
*
|
||||
* This file is part of the StrafesNET bhop/surf client.
|
||||
*
|
||||
* StrafesNET can not be copied and/or distributed
|
||||
* without the express permission of Rhys Lloyd
|
||||
*******************************************************/
|
||||
@@ -44,11 +44,11 @@ struct ModelInstance{
|
||||
transform:mat4x4<f32>,
|
||||
normal_transform:mat3x3<f32>,
|
||||
color:vec4<f32>,
|
||||
texture_color:vec4<f32>,
|
||||
}
|
||||
//my fancy idea is to create a megatexture for each model that includes all the textures each intance will need
|
||||
//the texture transform then maps the texture coordinates to the location of the specific texture
|
||||
//group 1 is the model
|
||||
const MAX_MODEL_INSTANCES=512;
|
||||
@group(2)
|
||||
@binding(0)
|
||||
var<uniform> model_instances: array<ModelInstance, MAX_MODEL_INSTANCES>;
|
||||
@@ -66,6 +66,7 @@ struct EntityOutputTexture {
|
||||
@location(3) view: vec3<f32>,
|
||||
@location(4) color: vec4<f32>,
|
||||
@location(5) @interpolate(flat) model_color: vec4<f32>,
|
||||
@location(6) @interpolate(flat) texture_color: vec4<f32>,
|
||||
};
|
||||
@vertex
|
||||
fn vs_entity_texture(
|
||||
@@ -81,6 +82,7 @@ fn vs_entity_texture(
|
||||
result.texture = texture;
|
||||
result.color = color;
|
||||
result.model_color = model_instances[instance].color;
|
||||
result.texture_color = model_instances[instance].texture_color;
|
||||
result.view = position.xyz - camera.view_inv[3].xyz;//col(3)
|
||||
result.position = camera.proj * camera.view * position;
|
||||
return result;
|
||||
@@ -106,7 +108,9 @@ fn fs_entity_texture(vertex: EntityOutputTexture) -> @location(0) vec4<f32> {
|
||||
let d = dot(normal, incident);
|
||||
let reflected = incident - 2.0 * d * normal;
|
||||
|
||||
let fragment_color = textureSample(model_texture, model_sampler, vertex.texture)*vertex.color;
|
||||
let fragment_color = textureSample(model_texture, model_sampler, vertex.texture)*vertex.texture_color;
|
||||
let reflected_color = textureSample(cube_texture, cube_sampler, reflected).rgb;
|
||||
return mix(vec4<f32>(vec3<f32>(0.05) + 0.2 * reflected_color,1.0),mix(vertex.model_color,vec4<f32>(fragment_color.rgb,1.0),fragment_color.a),0.5+0.5*abs(d));
|
||||
let entity_color = mix(vertex.model_color*vertex.color,vec4<f32>(fragment_color.rgb,1.0),fragment_color.a);
|
||||
let sky_color = vec4<f32>(vec3<f32>(0.05) + 0.2 * reflected_color,1.0);
|
||||
return mix(sky_color,entity_color,0.5+0.5*abs(d));
|
||||
}
|
||||
@@ -3,7 +3,7 @@ use std::collections::{HashSet,HashMap};
|
||||
use strafesnet_common::map;
|
||||
use strafesnet_common::model::{self, ColorId, NormalId, PolygonIter, PositionId, RenderConfigId, TextureCoordinateId, VertexId};
|
||||
use wgpu::{util::DeviceExt,AstcBlock,AstcChannel};
|
||||
use crate::model_graphics::{self,IndexedGraphicsMeshOwnedRenderConfig,IndexedGraphicsMeshOwnedRenderConfigId,GraphicsMeshOwnedRenderConfig,GraphicsModelColor4,GraphicsModelOwned,GraphicsVertex};
|
||||
use crate::model::{self as model_graphics,IndexedGraphicsMeshOwnedRenderConfig,IndexedGraphicsMeshOwnedRenderConfigId,GraphicsMeshOwnedRenderConfig,GraphicsModelOwned,GraphicsVertex};
|
||||
|
||||
struct Indices{
|
||||
count:u32,
|
||||
@@ -48,6 +48,10 @@ struct GraphicsPipelines{
|
||||
model:wgpu::RenderPipeline,
|
||||
}
|
||||
|
||||
pub fn view_inv(pos:glam::Vec3,angles:glam::Vec2)->glam::Mat4{
|
||||
//f32 good enough for view matrix
|
||||
glam::Mat4::from_mat3_translation(glam::Mat3::from_euler(glam::EulerRot::YXZ,angles.x,angles.y,0f32),pos)
|
||||
}
|
||||
struct GraphicsCamera{
|
||||
screen_size:glam::UVec2,
|
||||
fov:glam::Vec2,//slope
|
||||
@@ -69,15 +73,10 @@ impl GraphicsCamera{
|
||||
pub fn proj(&self)->glam::Mat4{
|
||||
perspective_rh(self.fov.x,self.fov.y,0.4,4000.0)
|
||||
}
|
||||
pub fn world(&self,pos:glam::Vec3,angles:glam::Vec2)->glam::Mat4{
|
||||
//f32 good enough for view matrix
|
||||
glam::Mat4::from_translation(pos)*glam::Mat4::from_euler(glam::EulerRot::YXZ,angles.x,angles.y,0f32)
|
||||
}
|
||||
|
||||
pub fn to_uniform_data(&self,pos:glam::Vec3,angles:glam::Vec2)->[f32;16*4]{
|
||||
pub fn to_uniform_data(&self,view_inv:glam::Mat4)->[f32;16*4]{
|
||||
let proj=self.proj();
|
||||
let proj_inv=proj.inverse();
|
||||
let view_inv=self.world(pos,angles);
|
||||
let view=view_inv.inverse();
|
||||
|
||||
let mut raw=[0f32; 16 * 4];
|
||||
@@ -88,7 +87,7 @@ impl GraphicsCamera{
|
||||
raw
|
||||
}
|
||||
}
|
||||
impl std::default::Default for GraphicsCamera{
|
||||
impl Default for GraphicsCamera{
|
||||
fn default()->Self{
|
||||
Self{
|
||||
screen_size:glam::UVec2::ONE,
|
||||
@@ -97,6 +96,28 @@ impl std::default::Default for GraphicsCamera{
|
||||
}
|
||||
}
|
||||
|
||||
const MODEL_BUFFER_SIZE:usize=4*4 + 12 + 4 + 4;//let size=std::mem::size_of::<ModelInstance>();
|
||||
const MODEL_BUFFER_SIZE_BYTES:usize=MODEL_BUFFER_SIZE*4;
|
||||
fn get_instances_buffer_data(instances:&[GraphicsModelOwned])->Vec<f32>{
|
||||
let mut raw=Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len());
|
||||
for mi in instances{
|
||||
//model transform
|
||||
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]);
|
||||
//normal transform
|
||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.x_axis));
|
||||
raw.extend_from_slice(&[0.0]);
|
||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.y_axis));
|
||||
raw.extend_from_slice(&[0.0]);
|
||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.z_axis));
|
||||
raw.extend_from_slice(&[0.0]);
|
||||
//color
|
||||
raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color));
|
||||
//texture color
|
||||
raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.texture_color));
|
||||
}
|
||||
raw
|
||||
}
|
||||
|
||||
pub struct GraphicsState{
|
||||
pipelines:GraphicsPipelines,
|
||||
bind_groups:GraphicsBindGroups,
|
||||
@@ -106,42 +127,45 @@ pub struct GraphicsState{
|
||||
camera_buf:wgpu::Buffer,
|
||||
temp_squid_texture_view:wgpu::TextureView,
|
||||
models:Vec<GraphicsModel>,
|
||||
depth:wgpu::Texture,
|
||||
depth_view:wgpu::TextureView,
|
||||
staging_belt:wgpu::util::StagingBelt,
|
||||
model_instances_uniform_len:usize,
|
||||
}
|
||||
|
||||
impl GraphicsState{
|
||||
const DEPTH_FORMAT:wgpu::TextureFormat=wgpu::TextureFormat::Depth24Plus;
|
||||
const DEPTH_FORMAT:wgpu::TextureFormat=wgpu::TextureFormat::Depth32Float;
|
||||
fn create_depth_texture(
|
||||
config:&wgpu::SurfaceConfiguration,
|
||||
size:glam::UVec2,
|
||||
device:&wgpu::Device,
|
||||
)->wgpu::TextureView{
|
||||
let depth_texture=device.create_texture(&wgpu::TextureDescriptor{
|
||||
)->wgpu::Texture{
|
||||
device.create_texture(&wgpu::TextureDescriptor{
|
||||
size:wgpu::Extent3d{
|
||||
width:config.width,
|
||||
height:config.height,
|
||||
width:size.x,
|
||||
height:size.y,
|
||||
depth_or_array_layers:1,
|
||||
},
|
||||
mip_level_count:1,
|
||||
sample_count:1,
|
||||
dimension:wgpu::TextureDimension::D2,
|
||||
format:Self::DEPTH_FORMAT,
|
||||
usage:wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
label:None,
|
||||
usage:wgpu::TextureUsages::RENDER_ATTACHMENT|wgpu::TextureUsages::COPY_SRC,
|
||||
label:Some("Depth Texture"),
|
||||
view_formats:&[],
|
||||
});
|
||||
|
||||
depth_texture.create_view(&wgpu::TextureViewDescriptor::default())
|
||||
})
|
||||
}
|
||||
pub const fn depth_texture(&self)->&wgpu::Texture{
|
||||
&self.depth
|
||||
}
|
||||
pub const fn depth_texture_view(&self)->&wgpu::TextureView{
|
||||
&self.depth_view
|
||||
}
|
||||
pub fn clear(&mut self){
|
||||
self.models.clear();
|
||||
}
|
||||
pub fn load_user_settings(&mut self,user_settings:&crate::settings::UserSettings){
|
||||
self.camera.fov=user_settings.calculate_fov(1.0,&self.camera.screen_size).as_vec2();
|
||||
}
|
||||
pub fn generate_models(&mut self,device:&wgpu::Device,queue:&wgpu::Queue,map:&map::CompleteMap){
|
||||
//generate texture view per texture
|
||||
let texture_views:HashMap<strafesnet_common::model::TextureId,wgpu::TextureView>=map.textures.iter().enumerate().filter_map(|(texture_id,texture_data)|{
|
||||
let texture_views:HashMap<model::TextureId,wgpu::TextureView>=map.textures.iter().enumerate().filter_map(|(texture_id,texture_data)|{
|
||||
let texture_id=model::TextureId::new(texture_id as u32);
|
||||
let image=match ddsfile::Dds::read(std::io::Cursor::new(texture_data)){
|
||||
Ok(image)=>image,
|
||||
@@ -213,7 +237,8 @@ impl GraphicsState{
|
||||
let instance=GraphicsModelOwned{
|
||||
transform:model.transform.into(),
|
||||
normal_transform:glam::Mat3::from_cols_array_2d(&model.transform.matrix3.to_array().map(|row|row.map(Into::into))).inverse().transpose(),
|
||||
color:GraphicsModelColor4::new(model.color),
|
||||
color:model.color,
|
||||
texture_color:glam::Vec4::ONE,
|
||||
};
|
||||
//get or create owned mesh map
|
||||
let owned_mesh_map=owned_mesh_id_from_mesh_id_render_config_id
|
||||
@@ -243,16 +268,15 @@ impl GraphicsState{
|
||||
owned_mesh_id
|
||||
});
|
||||
let owned_mesh=unique_render_config_models.get_mut(owned_mesh_id.get() as usize).unwrap();
|
||||
match &mut owned_mesh.polys{
|
||||
model::PolygonGroup::PolygonList(polygon_list)=>polygon_list.extend(
|
||||
graphics_group.groups.iter().flat_map(|polygon_group_id|{
|
||||
mesh.polygon_groups[polygon_group_id.get() as usize].polys()
|
||||
})
|
||||
.map(|vertex_id_slice|
|
||||
vertex_id_slice.to_vec()
|
||||
)
|
||||
),
|
||||
}
|
||||
let model::PolygonGroup::PolygonList(polygon_list)=&mut owned_mesh.polys;
|
||||
polygon_list.extend(
|
||||
graphics_group.groups.iter().flat_map(|polygon_group_id|{
|
||||
mesh.polygon_groups[polygon_group_id.get() as usize].polys()
|
||||
})
|
||||
.map(|vertex_id_slice|
|
||||
vertex_id_slice.to_vec()
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
owned_mesh_map
|
||||
@@ -260,10 +284,20 @@ impl GraphicsState{
|
||||
for owned_mesh_id in owned_mesh_map.values(){
|
||||
let owned_mesh=unique_render_config_models.get_mut(owned_mesh_id.get() as usize).unwrap();
|
||||
let render_config=&map.render_configs[owned_mesh.render_config.get() as usize];
|
||||
if model.color.w==0.0&&render_config.texture.is_none(){
|
||||
continue;
|
||||
}
|
||||
owned_mesh.instances.push(instance.clone());
|
||||
let no_texture=render_config.texture.is_none();
|
||||
let instance_clone=if no_texture{
|
||||
// this model has no chance of affecting pixels on the screen
|
||||
if model.color.w==0.0{
|
||||
continue;
|
||||
}
|
||||
// hack texture_color to zero to make the texture invisible
|
||||
let mut instance=instance.clone();
|
||||
instance.texture_color=glam::Vec4::ZERO;
|
||||
instance
|
||||
}else{
|
||||
instance.clone()
|
||||
};
|
||||
owned_mesh.instances.push(instance_clone);
|
||||
}
|
||||
}
|
||||
//check every model to see if it's using the same (texture,color) but has few instances,if it is combine it into one model
|
||||
@@ -289,7 +323,7 @@ impl GraphicsState{
|
||||
//separate instances by color
|
||||
for (instance_id,instance) in model.instances.iter().enumerate(){
|
||||
let model_instance_list=unique_color
|
||||
.entry(instance.color)
|
||||
.entry(instance.hashable_color())
|
||||
.or_insert_with(||Vec::new());
|
||||
//add model instance to list
|
||||
model_instance_list.push((model_id,instance_id));
|
||||
@@ -378,6 +412,7 @@ impl GraphicsState{
|
||||
).collect()
|
||||
));
|
||||
}
|
||||
let (color,texture_color)=color.color();
|
||||
//push model into dedup
|
||||
deduplicated_models.push(IndexedGraphicsMeshOwnedRenderConfig{
|
||||
unique_pos,
|
||||
@@ -390,7 +425,8 @@ impl GraphicsState{
|
||||
instances:vec![GraphicsModelOwned{
|
||||
transform:glam::Mat4::IDENTITY,
|
||||
normal_transform:glam::Mat3::IDENTITY,
|
||||
color
|
||||
color,
|
||||
texture_color,
|
||||
}],
|
||||
});
|
||||
}
|
||||
@@ -448,16 +484,14 @@ impl GraphicsState{
|
||||
//.into_iter() the modeldata vec so entities can be /moved/ to models.entities
|
||||
let mut model_count=0;
|
||||
let mut instance_count=0;
|
||||
let uniform_buffer_binding_size=crate::setup::required_limits().max_uniform_buffer_binding_size as usize;
|
||||
let chunk_size=uniform_buffer_binding_size/MODEL_BUFFER_SIZE_BYTES;
|
||||
self.models.reserve(models.len());
|
||||
for model in models.into_iter(){
|
||||
instance_count+=model.instances.len();
|
||||
for instances_chunk in model.instances.rchunks(chunk_size){
|
||||
for instances_chunk in model.instances.rchunks(self.model_instances_uniform_len){
|
||||
model_count+=1;
|
||||
let mut model_uniforms=get_instances_buffer_data(instances_chunk);
|
||||
//TEMP: fill with zeroes to pass validation
|
||||
model_uniforms.resize(MODEL_BUFFER_SIZE*512,0.0f32);
|
||||
model_uniforms.resize(MODEL_BUFFER_SIZE*self.model_instances_uniform_len,0.0f32);
|
||||
let model_buf=device.create_buffer_init(&wgpu::util::BufferInitDescriptor{
|
||||
label:Some(format!("Model{} Buf",model_count).as_str()),
|
||||
contents:bytemuck::cast_slice(&model_uniforms),
|
||||
@@ -513,7 +547,9 @@ impl GraphicsState{
|
||||
pub fn new(
|
||||
device:&wgpu::Device,
|
||||
queue:&wgpu::Queue,
|
||||
config:&wgpu::SurfaceConfiguration,
|
||||
size:glam::UVec2,
|
||||
view_format:wgpu::TextureFormat,
|
||||
limits:wgpu::Limits,
|
||||
)->Self{
|
||||
let camera_bind_group_layout=device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor{
|
||||
label:None,
|
||||
@@ -590,7 +626,7 @@ impl GraphicsState{
|
||||
address_mode_w:wgpu::AddressMode::ClampToEdge,
|
||||
mag_filter:wgpu::FilterMode::Linear,
|
||||
min_filter:wgpu::FilterMode::Linear,
|
||||
mipmap_filter:wgpu::FilterMode::Linear,
|
||||
mipmap_filter:wgpu::MipmapFilterMode::Linear,
|
||||
..Default::default()
|
||||
});
|
||||
let repeat_sampler=device.create_sampler(&wgpu::SamplerDescriptor{
|
||||
@@ -600,15 +636,23 @@ impl GraphicsState{
|
||||
address_mode_w:wgpu::AddressMode::Repeat,
|
||||
mag_filter:wgpu::FilterMode::Linear,
|
||||
min_filter:wgpu::FilterMode::Linear,
|
||||
mipmap_filter:wgpu::FilterMode::Linear,
|
||||
mipmap_filter:wgpu::MipmapFilterMode::Linear,
|
||||
anisotropy_clamp:16,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let model_instances_uniform_len=limits.max_uniform_buffer_binding_size as usize/MODEL_BUFFER_SIZE_BYTES;
|
||||
|
||||
// write dynamic value into shader
|
||||
let shader=format!("
|
||||
// This is equal to the CHUNK_SIZE constant from graphics.rs
|
||||
const MAX_MODEL_INSTANCES={model_instances_uniform_len};
|
||||
")+include_str!("../shaders/shader.wgsl");
|
||||
|
||||
// Create the render pipeline
|
||||
let shader=device.create_shader_module(wgpu::ShaderModuleDescriptor{
|
||||
label:None,
|
||||
source:wgpu::ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
|
||||
source:wgpu::ShaderSource::Wgsl(Cow::Owned(shader)),
|
||||
});
|
||||
|
||||
//load textures
|
||||
@@ -724,19 +768,19 @@ impl GraphicsState{
|
||||
let model_pipeline_layout=device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor{
|
||||
label:None,
|
||||
bind_group_layouts:&[
|
||||
&camera_bind_group_layout,
|
||||
&skybox_texture_bind_group_layout,
|
||||
&model_bind_group_layout,
|
||||
Some(&camera_bind_group_layout),
|
||||
Some(&skybox_texture_bind_group_layout),
|
||||
Some(&model_bind_group_layout),
|
||||
],
|
||||
push_constant_ranges:&[],
|
||||
immediate_size:0,
|
||||
});
|
||||
let sky_pipeline_layout=device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor{
|
||||
label:None,
|
||||
bind_group_layouts:&[
|
||||
&camera_bind_group_layout,
|
||||
&skybox_texture_bind_group_layout,
|
||||
Some(&camera_bind_group_layout),
|
||||
Some(&skybox_texture_bind_group_layout),
|
||||
],
|
||||
push_constant_ranges:&[],
|
||||
immediate_size:0,
|
||||
});
|
||||
|
||||
// Create the render pipelines
|
||||
@@ -752,7 +796,7 @@ impl GraphicsState{
|
||||
fragment:Some(wgpu::FragmentState{
|
||||
module:&shader,
|
||||
entry_point:Some("fs_sky"),
|
||||
targets:&[Some(config.view_formats[0].into())],
|
||||
targets:&[Some(view_format.into())],
|
||||
compilation_options:wgpu::PipelineCompilationOptions::default(),
|
||||
}),
|
||||
primitive:wgpu::PrimitiveState{
|
||||
@@ -761,13 +805,13 @@ impl GraphicsState{
|
||||
},
|
||||
depth_stencil:Some(wgpu::DepthStencilState{
|
||||
format:Self::DEPTH_FORMAT,
|
||||
depth_write_enabled:false,
|
||||
depth_compare:wgpu::CompareFunction::LessEqual,
|
||||
depth_write_enabled:Some(false),
|
||||
depth_compare:Some(wgpu::CompareFunction::LessEqual),
|
||||
stencil:wgpu::StencilState::default(),
|
||||
bias:wgpu::DepthBiasState::default(),
|
||||
}),
|
||||
multisample:wgpu::MultisampleState::default(),
|
||||
multiview:None,
|
||||
multiview_mask:None,
|
||||
cache:None,
|
||||
});
|
||||
let model_pipeline=device.create_render_pipeline(&wgpu::RenderPipelineDescriptor{
|
||||
@@ -777,7 +821,7 @@ impl GraphicsState{
|
||||
module:&shader,
|
||||
entry_point:Some("vs_entity_texture"),
|
||||
buffers:&[wgpu::VertexBufferLayout{
|
||||
array_stride:std::mem::size_of::<GraphicsVertex>() as wgpu::BufferAddress,
|
||||
array_stride:size_of::<GraphicsVertex>() as wgpu::BufferAddress,
|
||||
step_mode:wgpu::VertexStepMode::Vertex,
|
||||
attributes:&wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Float32x3,3=>Float32x4],
|
||||
}],
|
||||
@@ -786,7 +830,7 @@ impl GraphicsState{
|
||||
fragment:Some(wgpu::FragmentState{
|
||||
module:&shader,
|
||||
entry_point:Some("fs_entity_texture"),
|
||||
targets:&[Some(config.view_formats[0].into())],
|
||||
targets:&[Some(view_format.into())],
|
||||
compilation_options:wgpu::PipelineCompilationOptions::default(),
|
||||
}),
|
||||
primitive:wgpu::PrimitiveState{
|
||||
@@ -796,18 +840,18 @@ impl GraphicsState{
|
||||
},
|
||||
depth_stencil:Some(wgpu::DepthStencilState{
|
||||
format:Self::DEPTH_FORMAT,
|
||||
depth_write_enabled:true,
|
||||
depth_compare:wgpu::CompareFunction::LessEqual,
|
||||
depth_write_enabled:Some(true),
|
||||
depth_compare:Some(wgpu::CompareFunction::LessEqual),
|
||||
stencil:wgpu::StencilState::default(),
|
||||
bias:wgpu::DepthBiasState::default(),
|
||||
}),
|
||||
multisample:wgpu::MultisampleState::default(),
|
||||
multiview:None,
|
||||
multiview_mask:None,
|
||||
cache:None,
|
||||
});
|
||||
|
||||
let camera=GraphicsCamera::default();
|
||||
let camera_uniforms=camera.to_uniform_data(glam::Vec3::ZERO,glam::Vec2::ZERO);
|
||||
let camera_uniforms=camera.to_uniform_data(view_inv(glam::Vec3::ZERO,glam::Vec2::ZERO));
|
||||
let camera_buf=device.create_buffer_init(&wgpu::util::BufferInitDescriptor{
|
||||
label:Some("Camera"),
|
||||
contents:bytemuck::cast_slice(&camera_uniforms),
|
||||
@@ -839,7 +883,8 @@ impl GraphicsState{
|
||||
label:Some("Sky Texture"),
|
||||
});
|
||||
|
||||
let depth_view=Self::create_depth_texture(config,device);
|
||||
let depth=Self::create_depth_texture(size,device);
|
||||
let depth_view=depth.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
Self{
|
||||
pipelines:GraphicsPipelines{
|
||||
@@ -853,46 +898,44 @@ impl GraphicsState{
|
||||
camera,
|
||||
camera_buf,
|
||||
models:Vec::new(),
|
||||
depth,
|
||||
depth_view,
|
||||
staging_belt:wgpu::util::StagingBelt::new(0x100),
|
||||
staging_belt:wgpu::util::StagingBelt::new(device.clone(),0x100),
|
||||
bind_group_layouts:GraphicsBindGroupLayouts{model:model_bind_group_layout},
|
||||
samplers:GraphicsSamplers{repeat:repeat_sampler},
|
||||
temp_squid_texture_view:squid_texture_view,
|
||||
model_instances_uniform_len,
|
||||
}
|
||||
}
|
||||
pub fn resize(
|
||||
&mut self,
|
||||
device:&wgpu::Device,
|
||||
config:&wgpu::SurfaceConfiguration,
|
||||
user_settings:&crate::settings::UserSettings,
|
||||
size:glam::UVec2,
|
||||
fov:glam::Vec2,
|
||||
){
|
||||
self.depth_view=Self::create_depth_texture(config,device);
|
||||
self.camera.screen_size=glam::uvec2(config.width,config.height);
|
||||
self.load_user_settings(user_settings);
|
||||
self.depth=Self::create_depth_texture(size,device);
|
||||
self.depth_view=self.depth.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.camera.screen_size=size;
|
||||
self.camera.fov=fov;
|
||||
}
|
||||
pub fn render(
|
||||
pub fn encode_commands(
|
||||
&mut self,
|
||||
encoder:&mut wgpu::CommandEncoder,
|
||||
view:&wgpu::TextureView,
|
||||
device:&wgpu::Device,
|
||||
queue:&wgpu::Queue,
|
||||
frame_state:crate::session::FrameState,
|
||||
camera:glam::Mat4,
|
||||
){
|
||||
//TODO:use scheduled frame times to create beautiful smoothing simulation physics extrapolation assuming no input
|
||||
|
||||
let mut encoder=device.create_command_encoder(&wgpu::CommandEncoderDescriptor{label:None});
|
||||
|
||||
// TODO: find a way to call this directly after queue.submit()
|
||||
self.staging_belt.recall();
|
||||
// update rotation
|
||||
let camera_uniforms=self.camera.to_uniform_data(
|
||||
frame_state.body.extrapolated_position(frame_state.time).map(Into::<f32>::into).to_array().into(),
|
||||
frame_state.camera.simulate_move_angles(glam::IVec2::ZERO)
|
||||
);
|
||||
let camera_uniforms=self.camera.to_uniform_data(camera);
|
||||
self.staging_belt
|
||||
.write_buffer(
|
||||
&mut encoder,
|
||||
encoder,
|
||||
&self.camera_buf,
|
||||
0,
|
||||
wgpu::BufferSize::new((camera_uniforms.len() * 4) as wgpu::BufferAddress).unwrap(),
|
||||
device,
|
||||
)
|
||||
.copy_from_slice(bytemuck::cast_slice(&camera_uniforms));
|
||||
//This code only needs to run when the uniforms change
|
||||
@@ -927,17 +970,19 @@ impl GraphicsState{
|
||||
}),
|
||||
store:wgpu::StoreOp::Store,
|
||||
},
|
||||
depth_slice:None,
|
||||
})],
|
||||
depth_stencil_attachment:Some(wgpu::RenderPassDepthStencilAttachment{
|
||||
view:&self.depth_view,
|
||||
depth_ops:Some(wgpu::Operations{
|
||||
load:wgpu::LoadOp::Clear(1.0),
|
||||
store:wgpu::StoreOp::Discard,
|
||||
store:wgpu::StoreOp::Store,
|
||||
}),
|
||||
stencil_ops:None,
|
||||
}),
|
||||
timestamp_writes:Default::default(),
|
||||
occlusion_query_set:Default::default(),
|
||||
multiview_mask:None,
|
||||
});
|
||||
|
||||
rpass.set_bind_group(0,&self.bind_groups.camera,&[]);
|
||||
@@ -955,28 +1000,5 @@ impl GraphicsState{
|
||||
rpass.set_pipeline(&self.pipelines.skybox);
|
||||
rpass.draw(0..3,0..1);
|
||||
}
|
||||
|
||||
queue.submit(std::iter::once(encoder.finish()));
|
||||
|
||||
self.staging_belt.recall();
|
||||
}
|
||||
}
|
||||
const MODEL_BUFFER_SIZE:usize=4*4 + 12 + 4;//let size=std::mem::size_of::<ModelInstance>();
|
||||
const MODEL_BUFFER_SIZE_BYTES:usize=MODEL_BUFFER_SIZE*4;
|
||||
fn get_instances_buffer_data(instances:&[GraphicsModelOwned])->Vec<f32>{
|
||||
let mut raw=Vec::with_capacity(MODEL_BUFFER_SIZE*instances.len());
|
||||
for mi in instances{
|
||||
//model transform
|
||||
raw.extend_from_slice(&AsRef::<[f32; 4*4]>::as_ref(&mi.transform)[..]);
|
||||
//normal transform
|
||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.x_axis));
|
||||
raw.extend_from_slice(&[0.0]);
|
||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.y_axis));
|
||||
raw.extend_from_slice(&[0.0]);
|
||||
raw.extend_from_slice(AsRef::<[f32; 3]>::as_ref(&mi.normal_transform.z_axis));
|
||||
raw.extend_from_slice(&[0.0]);
|
||||
//color
|
||||
raw.extend_from_slice(AsRef::<[f32; 4]>::as_ref(&mi.color.get()));
|
||||
}
|
||||
raw
|
||||
}
|
||||
4
engine/graphics/src/lib.rs
Normal file
4
engine/graphics/src/lib.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
pub mod model;
|
||||
pub mod setup;
|
||||
pub mod surface;
|
||||
pub mod graphics;
|
||||
@@ -30,19 +30,23 @@ pub struct GraphicsMeshOwnedRenderConfig{
|
||||
pub render_config:RenderConfigId,
|
||||
pub instances:Vec<GraphicsModelOwned>,
|
||||
}
|
||||
#[derive(Clone,Copy,PartialEq,id::Id)]
|
||||
pub struct GraphicsModelColor4(glam::Vec4);
|
||||
impl std::hash::Hash for GraphicsModelColor4{
|
||||
fn hash<H:std::hash::Hasher>(&self,state:&mut H) {
|
||||
for &f in self.0.as_ref(){
|
||||
bytemuck::cast::<f32,u32>(f).hash(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Eq for GraphicsModelColor4{}
|
||||
#[derive(Clone)]
|
||||
pub struct GraphicsModelOwned{
|
||||
pub transform:glam::Mat4,
|
||||
pub normal_transform:glam::Mat3,
|
||||
pub color:GraphicsModelColor4,
|
||||
pub color:glam::Vec4,
|
||||
pub texture_color:glam::Vec4,
|
||||
}
|
||||
impl GraphicsModelOwned{
|
||||
pub fn hashable_color(&self)->HashableColor{
|
||||
HashableColor([bytemuck::cast::<[f32;4],[u32;4]>(self.color.to_array()),bytemuck::cast::<[f32;4],[u32;4]>(self.texture_color.to_array())])
|
||||
}
|
||||
}
|
||||
#[derive(Clone,Copy,Eq,Hash,PartialEq)]
|
||||
pub struct HashableColor([[u32;4];2]);
|
||||
impl HashableColor{
|
||||
pub fn color(self)->(glam::Vec4,glam::Vec4){
|
||||
let [color,texture_color]=bytemuck::cast::<[[u32;4];2],[[f32;4];2]>(self.0);
|
||||
(glam::Vec4::from_array(color),glam::Vec4::from_array(texture_color))
|
||||
}
|
||||
}
|
||||
116
engine/graphics/src/setup.rs
Normal file
116
engine/graphics/src/setup.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
fn optional_features()->wgpu::Features{
|
||||
wgpu::Features::TEXTURE_COMPRESSION_ASTC
|
||||
|wgpu::Features::TEXTURE_COMPRESSION_ETC2
|
||||
}
|
||||
fn required_features()->wgpu::Features{
|
||||
wgpu::Features::TEXTURE_COMPRESSION_BC
|
||||
}
|
||||
fn required_downlevel_capabilities()->wgpu::DownlevelCapabilities{
|
||||
wgpu::DownlevelCapabilities{
|
||||
flags:wgpu::DownlevelFlags::empty(),
|
||||
shader_model:wgpu::ShaderModel::Sm5,
|
||||
..wgpu::DownlevelCapabilities::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub mod step1{
|
||||
pub fn create_instance()->wgpu::Instance{
|
||||
Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub mod step2{
|
||||
pub fn create_surface<'window>(instance:&wgpu::Instance,target:impl Into<wgpu::SurfaceTarget<'window>>)->Result<wgpu::Surface<'window>,wgpu::CreateSurfaceError>{
|
||||
instance.create_surface(target)
|
||||
}
|
||||
}
|
||||
|
||||
pub mod step3{
|
||||
pub async fn pick_adapter(instance:&wgpu::Instance,surface:&wgpu::Surface<'_>)->Option<wgpu::Adapter>{
|
||||
let backends=wgpu::Backends::from_env().unwrap_or_default();
|
||||
//TODO: prefer adapter that implements optional features
|
||||
//let optional_features=optional_features();
|
||||
let required_features=super::required_features();
|
||||
let required_downlevel_capabilities=super::required_downlevel_capabilities();
|
||||
|
||||
//no helper function smh gotta write it myself
|
||||
let adapters=instance.enumerate_adapters(backends).await;
|
||||
|
||||
let adapter=adapters.into_iter()
|
||||
// reverse because we want to select adapters that appear first in ties,
|
||||
// and max_by_key selects the last equal element in the iterator.
|
||||
.rev()
|
||||
.filter(|adapter|
|
||||
adapter.is_surface_supported(surface)
|
||||
&&adapter.features().contains(required_features)
|
||||
&&{
|
||||
let downlevel_capabilities=adapter.get_downlevel_capabilities();
|
||||
downlevel_capabilities.shader_model>=required_downlevel_capabilities.shader_model
|
||||
&&downlevel_capabilities.flags.contains(required_downlevel_capabilities.flags)
|
||||
}
|
||||
)
|
||||
.max_by_key(|adapter|match adapter.get_info().device_type{
|
||||
wgpu::DeviceType::IntegratedGpu=>3,
|
||||
wgpu::DeviceType::DiscreteGpu=>4,
|
||||
wgpu::DeviceType::VirtualGpu=>2,
|
||||
wgpu::DeviceType::Other|wgpu::DeviceType::Cpu=>1,
|
||||
})?;
|
||||
|
||||
Some(adapter)
|
||||
}
|
||||
}
|
||||
|
||||
pub mod step4{
|
||||
pub async fn request_device(adapter:&wgpu::Adapter,limits:wgpu::Limits)->Result<(wgpu::Device,wgpu::Queue),wgpu::RequestDeviceError>{
|
||||
let optional_features=super::optional_features();
|
||||
let required_features=super::required_features();
|
||||
|
||||
// Make sure we use the texture resolution limits from the adapter, so we can support images the size of the surface.
|
||||
let needed_limits=limits.using_resolution(adapter.limits());
|
||||
|
||||
let (device, queue)=adapter
|
||||
.request_device(
|
||||
&wgpu::DeviceDescriptor{
|
||||
label:None,
|
||||
required_features:(optional_features&adapter.features())|required_features,
|
||||
required_limits:needed_limits,
|
||||
memory_hints:wgpu::MemoryHints::Performance,
|
||||
trace:wgpu::Trace::Off,
|
||||
experimental_features:wgpu::ExperimentalFeatures::disabled(),
|
||||
},
|
||||
).await?;
|
||||
|
||||
Ok((
|
||||
device,
|
||||
queue,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub mod step5{
|
||||
use crate::surface::Surface;
|
||||
#[derive(Debug)]
|
||||
pub struct ErrorSurfaceNotSupported;
|
||||
impl std::fmt::Display for ErrorSurfaceNotSupported{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"Surface isn't supported by the adapter.")
|
||||
}
|
||||
}
|
||||
pub fn configure_surface<'window>(
|
||||
adapter:&wgpu::Adapter,
|
||||
device:&wgpu::Device,
|
||||
surface:wgpu::Surface<'window>,
|
||||
(width,height):(u32,u32),
|
||||
)->Result<Surface<'window>,ErrorSurfaceNotSupported>{
|
||||
let mut config=surface
|
||||
.get_default_config(adapter, width, height)
|
||||
.ok_or(ErrorSurfaceNotSupported)?;
|
||||
|
||||
let surface_view_format=config.format.add_srgb_suffix();
|
||||
config.view_formats.push(surface_view_format);
|
||||
config.present_mode=wgpu::PresentMode::AutoNoVsync;
|
||||
surface.configure(device,&config);
|
||||
|
||||
Ok(Surface::new(surface,config))
|
||||
}
|
||||
}
|
||||
75
engine/graphics/src/surface.rs
Normal file
75
engine/graphics/src/surface.rs
Normal file
@@ -0,0 +1,75 @@
|
||||
/// A texture view which can be targeted by draw calls in the command buffer, and then presented to the surface texture.
|
||||
pub struct Frame{
|
||||
surface_texture:wgpu::SurfaceTexture,
|
||||
view:wgpu::TextureView,
|
||||
}
|
||||
impl Frame{
|
||||
pub const fn view(&self)->&wgpu::TextureView{
|
||||
&self.view
|
||||
}
|
||||
pub fn present(self){
|
||||
self.surface_texture.present();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum FrameError{
|
||||
Skip,
|
||||
DeviceLost,
|
||||
}
|
||||
impl core::fmt::Display for FrameError{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"{self:?}")
|
||||
}
|
||||
}
|
||||
impl core::error::Error for FrameError{}
|
||||
|
||||
/// A render surface configuration, containing information such as resolution and pixel format
|
||||
pub struct Surface<'window>{
|
||||
surface:wgpu::Surface<'window>,
|
||||
config:wgpu::SurfaceConfiguration,
|
||||
}
|
||||
|
||||
impl<'window> Surface<'window>{
|
||||
pub(crate) fn new(
|
||||
surface:wgpu::Surface<'window>,
|
||||
config:wgpu::SurfaceConfiguration,
|
||||
)->Self{
|
||||
Self{surface,config}
|
||||
}
|
||||
#[must_use]
|
||||
pub fn new_frame(&self,device:&wgpu::Device)->Result<Frame,FrameError>{
|
||||
let frame=loop{
|
||||
match self.surface.get_current_texture(){
|
||||
wgpu::CurrentSurfaceTexture::Success(surface_texture)=>break surface_texture,
|
||||
// Suboptimal -> surface_texture must be dropped and surface reconfigured
|
||||
wgpu::CurrentSurfaceTexture::Suboptimal(_)
|
||||
|wgpu::CurrentSurfaceTexture::Outdated=>{},
|
||||
wgpu::CurrentSurfaceTexture::Timeout
|
||||
|wgpu::CurrentSurfaceTexture::Occluded=>return Err(FrameError::Skip),
|
||||
wgpu::CurrentSurfaceTexture::Lost=>return Err(FrameError::DeviceLost),
|
||||
wgpu::CurrentSurfaceTexture::Validation=>unreachable!(),
|
||||
};
|
||||
self.surface.configure(device,&self.config);
|
||||
};
|
||||
let view=frame.texture.create_view(&wgpu::TextureViewDescriptor{
|
||||
format:Some(self.config.view_formats[0]),
|
||||
..wgpu::TextureViewDescriptor::default()
|
||||
});
|
||||
Ok(Frame{
|
||||
surface_texture:frame,
|
||||
view,
|
||||
})
|
||||
}
|
||||
pub const fn size(&self)->glam::UVec2{
|
||||
glam::uvec2(self.config.width,self.config.height)
|
||||
}
|
||||
pub fn view_format(&self)->wgpu::TextureFormat{
|
||||
self.config.view_formats[0]
|
||||
}
|
||||
pub fn configure(&mut self,device:&wgpu::Device,size:glam::UVec2){
|
||||
self.config.width=size.x.max(1);
|
||||
self.config.height=size.y.max(1);
|
||||
self.surface.configure(device,&self.config);
|
||||
}
|
||||
}
|
||||
13
engine/physics/Cargo.toml
Normal file
13
engine/physics/Cargo.toml
Normal file
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "strafesnet_physics"
|
||||
version = "0.0.2"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
arrayvec = "0.7.6"
|
||||
glam.workspace = true
|
||||
id = { version = "0.1.0", registry = "strafesnet" }
|
||||
strafesnet_common.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
8
engine/physics/LICENSE
Normal file
8
engine/physics/LICENSE
Normal file
@@ -0,0 +1,8 @@
|
||||
/*******************************************************
|
||||
* Copyright (C) 2023-2024 Rhys Lloyd <krakow20@gmail.com>
|
||||
*
|
||||
* This file is part of the StrafesNET bhop/surf client.
|
||||
*
|
||||
* StrafesNET can not be copied and/or distributed
|
||||
* without the express permission of Rhys Lloyd
|
||||
*******************************************************/
|
||||
@@ -2,12 +2,18 @@ use strafesnet_common::aabb;
|
||||
use strafesnet_common::integer::{self,vec3,Time,Planar64,Planar64Vec3};
|
||||
#[derive(Clone,Copy,Debug,Hash)]
|
||||
pub struct Body<T>{
|
||||
pub position:Planar64Vec3,//I64 where 2^32 = 1 u
|
||||
pub velocity:Planar64Vec3,//I64 where 2^32 = 1 u/s
|
||||
pub acceleration:Planar64Vec3,//I64 where 2^32 = 1 u/s/s
|
||||
pub time:Time<T>,//nanoseconds x xxxxD!
|
||||
pub position:Planar64Vec3,
|
||||
pub velocity:Planar64Vec3,
|
||||
pub time:Time<T>,
|
||||
}
|
||||
impl<T> std::ops::Neg for Body<T>{
|
||||
#[derive(Clone,Copy,Debug,Hash)]
|
||||
pub struct Trajectory<T>{
|
||||
pub position:Planar64Vec3,
|
||||
pub velocity:Planar64Vec3,
|
||||
pub acceleration:Planar64Vec3,
|
||||
pub time:Time<T>,
|
||||
}
|
||||
impl<T> std::ops::Neg for Trajectory<T>{
|
||||
type Output=Self;
|
||||
fn neg(self)->Self::Output{
|
||||
Self{
|
||||
@@ -18,11 +24,48 @@ impl<T> std::ops::Neg for Body<T>{
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<T:Copy> std::ops::Neg for &Trajectory<T>{
|
||||
type Output=Trajectory<T>;
|
||||
fn neg(self)->Self::Output{
|
||||
Trajectory{
|
||||
position:self.position,
|
||||
velocity:-self.velocity,
|
||||
acceleration:self.acceleration,
|
||||
time:-self.time,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Body<T>
|
||||
where Time<T>:Copy,
|
||||
{
|
||||
pub const ZERO:Self=Self::new(vec3::ZERO,vec3::ZERO,vec3::ZERO,Time::ZERO);
|
||||
pub const ZERO:Self=Self::new(vec3::zero(),vec3::zero(),Time::ZERO);
|
||||
pub const fn new(position:Planar64Vec3,velocity:Planar64Vec3,time:Time<T>)->Self{
|
||||
Self{
|
||||
position,
|
||||
velocity,
|
||||
time,
|
||||
}
|
||||
}
|
||||
pub const fn with_acceleration(self,acceleration:Planar64Vec3)->Trajectory<T>{
|
||||
let Body{
|
||||
position,
|
||||
velocity,
|
||||
time,
|
||||
}=self;
|
||||
Trajectory{
|
||||
position,
|
||||
velocity,
|
||||
acceleration,
|
||||
time,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Trajectory<T>
|
||||
where Time<T>:Copy,
|
||||
{
|
||||
pub const ZERO:Self=Self::new(vec3::zero(),vec3::zero(),vec3::zero(),Time::ZERO);
|
||||
pub const fn new(position:Planar64Vec3,velocity:Planar64Vec3,acceleration:Planar64Vec3,time:Time<T>)->Self{
|
||||
Self{
|
||||
position,
|
||||
@@ -31,20 +74,31 @@ impl<T> Body<T>
|
||||
time,
|
||||
}
|
||||
}
|
||||
pub fn relative_to(&self,trj0:&Self,time:Time<T>)->Self{
|
||||
//(p0,v0,a0,t0)
|
||||
//(p1,v1,a1,t1)
|
||||
Trajectory::new(
|
||||
self.extrapolated_position(time)-trj0.extrapolated_position(time),
|
||||
self.extrapolated_velocity(time)-trj0.extrapolated_velocity(time),
|
||||
self.acceleration-trj0.acceleration,
|
||||
time)
|
||||
}
|
||||
pub fn extrapolated_position(&self,time:Time<T>)->Planar64Vec3{
|
||||
let dt=time-self.time;
|
||||
self.position
|
||||
+(self.velocity*dt).map(|elem|elem.divide().fix_1())
|
||||
+self.acceleration.map(|elem|(dt*dt*elem/2).divide().fix_1())
|
||||
+(self.velocity*dt).map(|elem|elem.divide().clamp_64())
|
||||
+self.acceleration.map(|elem|(dt*dt*elem/2).divide().clamp_64())
|
||||
}
|
||||
pub fn extrapolated_velocity(&self,time:Time<T>)->Planar64Vec3{
|
||||
let dt=time-self.time;
|
||||
self.velocity+(self.acceleration*dt).map(|elem|elem.divide().fix_1())
|
||||
self.velocity+(self.acceleration*dt).map(|elem|elem.divide().clamp_64())
|
||||
}
|
||||
pub fn advance_time(&mut self,time:Time<T>){
|
||||
self.position=self.extrapolated_position(time);
|
||||
self.velocity=self.extrapolated_velocity(time);
|
||||
self.time=time;
|
||||
pub fn extrapolated_body(&self,time:Time<T>)->Body<T>{
|
||||
Body::new(
|
||||
self.extrapolated_position(time),
|
||||
self.extrapolated_velocity(time),
|
||||
time,
|
||||
)
|
||||
}
|
||||
pub fn extrapolated_position_ratio_dt<Num,Den,N1,D1,N2,N3,D2,N4,T1>(&self,dt:integer::Ratio<Num,Den>)->Planar64Vec3
|
||||
where
|
||||
@@ -63,12 +117,12 @@ impl<T> Body<T>
|
||||
D2:Copy,
|
||||
Planar64:core::ops::Mul<D2,Output=N4>,
|
||||
N4:integer::Divide<D2,Output=T1>,
|
||||
T1:integer::Fix<Planar64>,
|
||||
T1:integer::Clamp<Planar64>,
|
||||
{
|
||||
// a*dt^2/2 + v*dt + p
|
||||
// (a*dt/2+v)*dt+p
|
||||
(self.acceleration.map(|elem|dt*elem/2)+self.velocity).map(|elem|dt.mul_ratio(elem))
|
||||
.map(|elem|elem.divide().fix())+self.position
|
||||
.map(|elem|elem.divide().clamp())+self.position
|
||||
}
|
||||
pub fn extrapolated_velocity_ratio_dt<Num,Den,N1,T1>(&self,dt:integer::Ratio<Num,Den>)->Planar64Vec3
|
||||
where
|
||||
@@ -77,19 +131,21 @@ impl<T> Body<T>
|
||||
Num:core::ops::Mul<Planar64,Output=N1>,
|
||||
Planar64:core::ops::Mul<Den,Output=N1>,
|
||||
N1:integer::Divide<Den,Output=T1>,
|
||||
T1:integer::Fix<Planar64>,
|
||||
T1:integer::Clamp<Planar64>,
|
||||
{
|
||||
// a*dt + v
|
||||
self.acceleration.map(|elem|(dt*elem).divide().fix())+self.velocity
|
||||
self.acceleration.map(|elem|(dt*elem).divide().clamp())+self.velocity
|
||||
}
|
||||
pub fn advance_time_ratio_dt(&mut self,dt:crate::model_physics::GigaTime){
|
||||
self.position=self.extrapolated_position_ratio_dt(dt);
|
||||
self.velocity=self.extrapolated_velocity_ratio_dt(dt);
|
||||
self.time+=dt.into();
|
||||
pub fn extrapolated_body_ratio_dt(&self,dt:crate::model::GigaTime)->Body<T>{
|
||||
Body::new(
|
||||
self.extrapolated_position_ratio_dt(dt),
|
||||
self.extrapolated_velocity_ratio_dt(dt),
|
||||
self.time+dt.into(),
|
||||
)
|
||||
}
|
||||
pub fn infinity_dir(&self)->Option<Planar64Vec3>{
|
||||
if self.velocity==vec3::ZERO{
|
||||
if self.acceleration==vec3::ZERO{
|
||||
if self.velocity==vec3::zero(){
|
||||
if self.acceleration==vec3::zero(){
|
||||
None
|
||||
}else{
|
||||
Some(self.acceleration)
|
||||
@@ -125,36 +181,12 @@ impl<T> Body<T>
|
||||
|
||||
}
|
||||
impl<T> std::fmt::Display for Body<T>{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"p({}) v({}) t({})",self.position,self.velocity,self.time)
|
||||
}
|
||||
}
|
||||
impl<T> std::fmt::Display for Trajectory<T>{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"p({}) v({}) a({}) t({})",self.position,self.velocity,self.acceleration,self.time)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct VirtualBody<'a,T>{
|
||||
body0:&'a Body<T>,
|
||||
body1:&'a Body<T>,
|
||||
}
|
||||
impl<T> VirtualBody<'_,T>
|
||||
where Time<T>:Copy,
|
||||
{
|
||||
pub const fn relative<'a>(body0:&'a Body<T>,body1:&'a Body<T>)->VirtualBody<'a,T>{
|
||||
//(p0,v0,a0,t0)
|
||||
//(p1,v1,a1,t1)
|
||||
VirtualBody{
|
||||
body0,
|
||||
body1,
|
||||
}
|
||||
}
|
||||
pub fn extrapolated_position(&self,time:Time<T>)->Planar64Vec3{
|
||||
self.body1.extrapolated_position(time)-self.body0.extrapolated_position(time)
|
||||
}
|
||||
pub fn extrapolated_velocity(&self,time:Time<T>)->Planar64Vec3{
|
||||
self.body1.extrapolated_velocity(time)-self.body0.extrapolated_velocity(time)
|
||||
}
|
||||
pub fn acceleration(&self)->Planar64Vec3{
|
||||
self.body1.acceleration-self.body0.acceleration
|
||||
}
|
||||
pub fn body(&self,time:Time<T>)->Body<T>{
|
||||
Body::new(self.extrapolated_position(time),self.extrapolated_velocity(time),self.acceleration(),time)
|
||||
}
|
||||
}
|
||||
187
engine/physics/src/face_crawler.rs
Normal file
187
engine/physics/src/face_crawler.rs
Normal file
@@ -0,0 +1,187 @@
|
||||
use crate::model::{into_giga_time,GigaTime};
|
||||
use strafesnet_common::integer::fixed_types::{F64_32,F128_64,F256_128};
|
||||
use strafesnet_common::integer::vec3::Vector3;
|
||||
use strafesnet_common::integer::{Ratio,Planar64Vec3};
|
||||
use crate::physics::{Time,Trajectory};
|
||||
use crate::mesh_query::{FEV,DirectedEdge,MeshQuery,MeshTopology};
|
||||
|
||||
use core::ops::Bound;
|
||||
|
||||
enum Transition<M:MeshTopology>{
|
||||
Miss,
|
||||
Next(FEV<M>,GigaTime),
|
||||
Hit(M::Face,GigaTime),
|
||||
}
|
||||
|
||||
pub enum CrawlResult<M:MeshTopology>{
|
||||
Miss(FEV<M>),
|
||||
Hit(M::Face,GigaTime),
|
||||
}
|
||||
impl<M:MeshTopology> CrawlResult<M>{
|
||||
pub fn hit(self)->Option<(M::Face,GigaTime)>{
|
||||
match self{
|
||||
CrawlResult::Miss(_)=>None,
|
||||
CrawlResult::Hit(face,time)=>Some((face,time)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: move predict_collision_face_out algorithm in here or something
|
||||
|
||||
/// check_lower_bound
|
||||
pub fn low<LhsNum,LhsDen,RhsNum,RhsDen,T>(lower_bound:&Bound<Ratio<LhsNum,LhsDen>>,dt:&Ratio<RhsNum,RhsDen>)->bool
|
||||
where
|
||||
RhsNum:Copy,
|
||||
RhsDen:Copy,
|
||||
LhsNum:Copy,
|
||||
LhsDen:Copy,
|
||||
LhsDen:strafesnet_common::integer::Parity,
|
||||
RhsDen:strafesnet_common::integer::Parity,
|
||||
LhsNum:core::ops::Mul<RhsDen,Output=T>,
|
||||
LhsDen:core::ops::Mul<RhsNum,Output=T>,
|
||||
T:Ord+Copy,
|
||||
{
|
||||
match lower_bound{
|
||||
Bound::Included(time)=>time.le_ratio(*dt),
|
||||
Bound::Excluded(time)=>time.lt_ratio(*dt),
|
||||
Bound::Unbounded=>true,
|
||||
}
|
||||
}
|
||||
/// check_upper_bound
|
||||
pub fn upp<LhsNum,LhsDen,RhsNum,RhsDen,T>(dt:&Ratio<LhsNum,LhsDen>,upper_bound:&Bound<Ratio<RhsNum,RhsDen>>)->bool
|
||||
where
|
||||
RhsNum:Copy,
|
||||
RhsDen:Copy,
|
||||
LhsNum:Copy,
|
||||
LhsDen:Copy,
|
||||
LhsDen:strafesnet_common::integer::Parity,
|
||||
RhsDen:strafesnet_common::integer::Parity,
|
||||
LhsNum:core::ops::Mul<RhsDen,Output=T>,
|
||||
LhsDen:core::ops::Mul<RhsNum,Output=T>,
|
||||
T:Ord+Copy,
|
||||
{
|
||||
match upper_bound{
|
||||
Bound::Included(time)=>dt.le_ratio(*time),
|
||||
Bound::Excluded(time)=>dt.lt_ratio(*time),
|
||||
Bound::Unbounded=>true,
|
||||
}
|
||||
}
|
||||
|
||||
impl<F:Copy,M:MeshQuery<Normal=Vector3<F>,Offset=F256_128,Position=Planar64Vec3,Direction=Planar64Vec3>> FEV<M>
|
||||
where
|
||||
// This is hardcoded for MinkowskiMesh lol
|
||||
M::Face:Copy,
|
||||
M::Edge:Copy,
|
||||
M::DirectedEdge:Copy,
|
||||
M::Vert:Copy,
|
||||
F:core::ops::Mul<F64_32,Output=F256_128>,
|
||||
<F as core::ops::Mul<F64_32>>::Output:core::iter::Sum,
|
||||
M::Offset:core::ops::Sub<<F as std::ops::Mul<F64_32>>::Output>,
|
||||
{
|
||||
fn next_transition(&self,mesh:&M,trajectory:&Trajectory,lower_bound:Bound<GigaTime>,mut upper_bound:Bound<GigaTime>)->Transition<M>{
|
||||
//conflicting derivative means it crosses in the wrong direction.
|
||||
//if the transition time is equal to an already tested transition, do not replace the current best.
|
||||
let mut best_transition=Transition::Miss;
|
||||
match self{
|
||||
&FEV::Face(face_id)=>{
|
||||
//test own face collision time, ignoring roots with zero or conflicting derivative
|
||||
//n=face.normal d=face.dot
|
||||
//n.a t^2+n.v t+n.p-d==0
|
||||
let (n,d)=mesh.face_nd(face_id);
|
||||
//TODO: use higher precision d value?
|
||||
//use the mesh transform translation instead of baking it into the d value.
|
||||
for dt in F256_128::zeroes2((n.dot(trajectory.position)-d)*2,n.dot(trajectory.velocity)*2,n.dot(trajectory.acceleration)){
|
||||
if low(&lower_bound,&dt)&&upp(&dt,&upper_bound)&&n.dot(trajectory.extrapolated_velocity_ratio_dt(dt)).is_negative(){
|
||||
upper_bound=Bound::Included(dt);
|
||||
best_transition=Transition::Hit(face_id,dt);
|
||||
break;
|
||||
}
|
||||
}
|
||||
//test each edge collision time, ignoring roots with zero or conflicting derivative
|
||||
mesh.for_each_face_edge(face_id,|directed_edge_id|{
|
||||
let edge_n=mesh.directed_edge_n(directed_edge_id);
|
||||
let n=n.cross(edge_n);
|
||||
let &[v0,v1]=mesh.edge_verts(directed_edge_id.as_undirected()).as_ref();
|
||||
//WARNING: d is moved out of the *2 block because of adding two vertices!
|
||||
//WARNING: precision is swept under the rug!
|
||||
//wrap for speed
|
||||
for dt in F256_128::zeroes2(n.dot(trajectory.position*2-(mesh.vert(v0)+mesh.vert(v1))).wrap_256(),n.dot(trajectory.velocity).wrap_256()*2,n.dot(trajectory.acceleration).wrap_256()){
|
||||
if low(&lower_bound,&dt)&&upp(&dt,&upper_bound)&&n.dot(trajectory.extrapolated_velocity_ratio_dt(dt)).is_negative(){
|
||||
upper_bound=Bound::Included(dt);
|
||||
best_transition=Transition::Next(FEV::Edge(directed_edge_id.as_undirected()),dt);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
//if none:
|
||||
},
|
||||
&FEV::Edge(edge_id)=>{
|
||||
//test each face collision time, ignoring roots with zero or conflicting derivative
|
||||
let edge_verts=mesh.edge_verts(edge_id);
|
||||
let &[ev0,ev1]=edge_verts.as_ref();
|
||||
let (v0,v1)=(mesh.vert(ev0),mesh.vert(ev1));
|
||||
let edge_n=v1-v0;
|
||||
let delta_pos=trajectory.position*2-(v0+v1);
|
||||
for (i,&edge_face_id) in mesh.edge_faces(edge_id).as_ref().iter().enumerate(){
|
||||
let face_n=mesh.face_nd(edge_face_id).0;
|
||||
//edge_n gets parity from the order of edge_faces
|
||||
let n=face_n.cross(edge_n)*((i as i64)*2-1);
|
||||
//WARNING yada yada d *2
|
||||
//wrap for speed
|
||||
for dt in F256_128::zeroes2(n.dot(delta_pos).wrap_256(),n.dot(trajectory.velocity).wrap_256()*2,n.dot(trajectory.acceleration).wrap_256()){
|
||||
if low(&lower_bound,&dt)&&upp(&dt,&upper_bound)&&n.dot(trajectory.extrapolated_velocity_ratio_dt(dt)).is_negative(){
|
||||
upper_bound=Bound::Included(dt);
|
||||
best_transition=Transition::Next(FEV::Face(edge_face_id),dt);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//test each vertex collision time, ignoring roots with zero or conflicting derivative
|
||||
for (i,&vert_id) in edge_verts.as_ref().iter().enumerate(){
|
||||
//vertex normal gets parity from vert index
|
||||
let n=edge_n*(1-2*(i as i64));
|
||||
for dt in F128_64::zeroes2((n.dot(trajectory.position-mesh.vert(vert_id)))*2,n.dot(trajectory.velocity)*2,n.dot(trajectory.acceleration)){
|
||||
if low(&lower_bound,&dt)&&upp(&dt,&upper_bound)&&n.dot(trajectory.extrapolated_velocity_ratio_dt(dt)).is_negative(){
|
||||
let dt=Ratio::new(dt.num.widen_256(),dt.den.widen_256());
|
||||
upper_bound=Bound::Included(dt);
|
||||
best_transition=Transition::Next(FEV::Vert(vert_id),dt);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
//if none:
|
||||
},
|
||||
&FEV::Vert(vert_id)=>{
|
||||
//test each edge collision time, ignoring roots with zero or conflicting derivative
|
||||
mesh.for_each_vert_edge(vert_id,|directed_edge_id|{
|
||||
//edge is directed away from vertex, but we want the dot product to turn out negative
|
||||
let n=-mesh.directed_edge_n(directed_edge_id);
|
||||
for dt in F128_64::zeroes2((n.dot(trajectory.position-mesh.vert(vert_id)))*2,n.dot(trajectory.velocity)*2,n.dot(trajectory.acceleration)){
|
||||
if low(&lower_bound,&dt)&&upp(&dt,&upper_bound)&&n.dot(trajectory.extrapolated_velocity_ratio_dt(dt)).is_negative(){
|
||||
let dt=Ratio::new(dt.num.widen_256(),dt.den.widen_256());
|
||||
upper_bound=Bound::Included(dt);
|
||||
best_transition=Transition::Next(FEV::Edge(directed_edge_id.as_undirected()),dt);
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
//if none:
|
||||
},
|
||||
}
|
||||
best_transition
|
||||
}
|
||||
pub fn crawl(mut self,mesh:&M,trajectory:&Trajectory,lower_bound:Bound<&Time>,upper_bound:Bound<&Time>)->CrawlResult<M>{
|
||||
let mut lower_bound=lower_bound.map(|&t|into_giga_time(t,trajectory.time));
|
||||
let upper_bound=upper_bound.map(|&t|into_giga_time(t,trajectory.time));
|
||||
for _ in 0..20{
|
||||
match self.next_transition(mesh,trajectory,lower_bound,upper_bound){
|
||||
Transition::Miss=>return CrawlResult::Miss(self),
|
||||
Transition::Next(next_fev,next_time)=>(self,lower_bound)=(next_fev,Bound::Included(next_time)),
|
||||
Transition::Hit(face,time)=>return CrawlResult::Hit(face,time),
|
||||
}
|
||||
}
|
||||
//TODO: fix all bugs
|
||||
//println!("Too many iterations! Using default behaviour instead of crashing...");
|
||||
CrawlResult::Miss(self)
|
||||
}
|
||||
}
|
||||
48
engine/physics/src/lib.rs
Normal file
48
engine/physics/src/lib.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
mod body;
|
||||
mod face_crawler;
|
||||
mod mesh_query;
|
||||
mod minkowski;
|
||||
mod model;
|
||||
mod push_solve;
|
||||
mod minimum_difference;
|
||||
|
||||
pub mod physics;
|
||||
|
||||
// Physics bug fixes can easily desync all bots.
|
||||
//
|
||||
// When replaying a bot, use the exact physics version which it was recorded with.
|
||||
//
|
||||
// When validating a new bot, ignore the version and use the latest version,
|
||||
// and overwrite the version in the file.
|
||||
//
|
||||
// Compatible physics versions should be determined
|
||||
// empirically at development time via leaderboard resimulation.
|
||||
//
|
||||
// Compatible physics versions should result in an identical leaderboard state,
|
||||
// or the only bots which fail are ones exploiting a surgically patched bug.
|
||||
#[derive(Clone,Copy,Hash,Debug,id::Id,Eq,PartialEq,Ord,PartialOrd)]
|
||||
pub struct PhysicsVersion(u32);
|
||||
pub const VERSION:PhysicsVersion=PhysicsVersion(0);
|
||||
const LATEST_COMPATIBLE_VERSION:[u32;1+VERSION.0 as usize]=const{
|
||||
let compat=[0];
|
||||
|
||||
let mut input_version=0;
|
||||
while input_version<compat.len(){
|
||||
// compatible version must be greater than or equal to the input version
|
||||
assert!(input_version as u32<=compat[input_version]);
|
||||
// compatible version must be a version that exists
|
||||
assert!(compat[input_version]<=VERSION.0);
|
||||
input_version+=1;
|
||||
}
|
||||
compat
|
||||
};
|
||||
pub enum PhysicsVersionError{
|
||||
UnknownPhysicsVersion,
|
||||
}
|
||||
pub const fn get_latest_compatible_version(PhysicsVersion(version):PhysicsVersion)->Result<PhysicsVersion,PhysicsVersionError>{
|
||||
if (version as usize)<LATEST_COMPATIBLE_VERSION.len(){
|
||||
Ok(PhysicsVersion(LATEST_COMPATIBLE_VERSION[version as usize]))
|
||||
}else{
|
||||
Err(PhysicsVersionError::UnknownPhysicsVersion)
|
||||
}
|
||||
}
|
||||
57
engine/physics/src/mesh_query.rs
Normal file
57
engine/physics/src/mesh_query.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
#[derive(Debug)]
|
||||
pub enum FEV<M:MeshTopology>{
|
||||
Vert(M::Vert),
|
||||
Edge(M::Edge),
|
||||
Face(M::Face),
|
||||
}
|
||||
|
||||
pub trait UndirectedEdge{
|
||||
type DirectedEdge:DirectedEdge<UndirectedEdge=Self>;
|
||||
fn as_directed(self,parity:bool)->Self::DirectedEdge;
|
||||
}
|
||||
pub trait DirectedEdge{
|
||||
type UndirectedEdge:UndirectedEdge<DirectedEdge=Self>;
|
||||
fn as_undirected(self)->Self::UndirectedEdge;
|
||||
fn parity(&self)->bool;
|
||||
fn reverse(self)->Self
|
||||
where
|
||||
Self:Sized
|
||||
{
|
||||
let parity=!self.parity();
|
||||
self.as_undirected().as_directed(parity)
|
||||
}
|
||||
}
|
||||
|
||||
pub trait MeshTopology{
|
||||
type Face;
|
||||
type Edge:UndirectedEdge<DirectedEdge=Self::DirectedEdge>;
|
||||
type DirectedEdge:DirectedEdge<UndirectedEdge=Self::Edge>;
|
||||
type Vert;
|
||||
fn for_each_vert_edge(&self,vert_id:Self::Vert,f:impl FnMut(Self::DirectedEdge));
|
||||
fn for_each_vert_face(&self,vert_id:Self::Vert,f:impl FnMut(Self::Face));
|
||||
fn edge_faces(&self,edge_id:Self::Edge)->impl AsRef<[Self::Face;2]>;
|
||||
fn edge_verts(&self,edge_id:Self::Edge)->impl AsRef<[Self::Vert;2]>;
|
||||
#[expect(unused)]
|
||||
fn for_each_face_vert(&self,face_id:Self::Face,f:impl FnMut(Self::Vert));
|
||||
fn for_each_face_edge(&self,face_id:Self::Face,f:impl FnMut(Self::DirectedEdge));
|
||||
}
|
||||
|
||||
// Make face_nd d value relative
|
||||
// euclidean point?
|
||||
// Simplex physics
|
||||
// Directed edge necessary?
|
||||
// recursive for_each function calls
|
||||
// define faces from vertices (Fixed<2> vs Fixed<3>)
|
||||
pub trait MeshQuery:MeshTopology{
|
||||
type Position;
|
||||
type Direction;
|
||||
type Normal;
|
||||
type Offset;
|
||||
fn vert(&self,vert_id:Self::Vert)->Self::Position;
|
||||
fn farthest_vert(&self,dir:Self::Direction)->Self::Vert;
|
||||
/// This must return a point inside the mesh.
|
||||
fn hint_point(&self)->Self::Position;
|
||||
fn face_nd(&self,face_id:Self::Face)->(Self::Normal,Self::Offset);
|
||||
fn edge_n(&self,edge_id:Self::Edge)->Self::Direction;
|
||||
fn directed_edge_n(&self,directed_edge_id:Self::DirectedEdge)->Self::Direction;
|
||||
}
|
||||
924
engine/physics/src/minimum_difference.rs
Normal file
924
engine/physics/src/minimum_difference.rs
Normal file
@@ -0,0 +1,924 @@
|
||||
use strafesnet_common::integer::fixed_types::{F128_64,F192_96,F256_128};
|
||||
use strafesnet_common::integer::vec3;
|
||||
use strafesnet_common::integer::vec3::Vector3;
|
||||
use strafesnet_common::integer::{Fixed,Planar64,Planar64Vec3};
|
||||
|
||||
use crate::mesh_query::{FEV,DirectedEdge,MeshQuery,MeshTopology};
|
||||
// TODO: remove mesh invert
|
||||
use crate::minkowski::{MinkowskiMesh,MinkowskiVert};
|
||||
|
||||
// This algorithm is based on Lua code
|
||||
// written by Trey Reynolds in 2021
|
||||
|
||||
type Simplex<const N:usize,Vert>=[Vert;N];
|
||||
#[derive(Clone,Copy)]
|
||||
enum Simplex1_3<Vert>{
|
||||
Simplex1(Simplex<1,Vert>),
|
||||
Simplex2(Simplex<2,Vert>),
|
||||
Simplex3(Simplex<3,Vert>),
|
||||
}
|
||||
impl<Vert> Simplex1_3<Vert>{
|
||||
fn push_front(self,v:Vert)->Simplex2_4<Vert>{
|
||||
match self{
|
||||
Simplex1_3::Simplex1([v0])=>Simplex2_4::Simplex2([v,v0]),
|
||||
Simplex1_3::Simplex2([v0,v1])=>Simplex2_4::Simplex3([v,v0,v1]),
|
||||
Simplex1_3::Simplex3([v0,v1,v2])=>Simplex2_4::Simplex4([v,v0,v1,v2]),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone,Copy)]
|
||||
enum Simplex2_4<Vert>{
|
||||
Simplex2(Simplex<2,Vert>),
|
||||
Simplex3(Simplex<3,Vert>),
|
||||
Simplex4(Simplex<4,Vert>),
|
||||
}
|
||||
|
||||
/*
|
||||
local function absDet(r, u, v, w)
|
||||
if w then
|
||||
return math.abs((u - r):Cross(v - r):Dot(w - r))
|
||||
elseif v then
|
||||
return (u - r):Cross(v - r).magnitude
|
||||
elseif u then
|
||||
return (u - r).magnitude
|
||||
else
|
||||
return 1
|
||||
end
|
||||
end
|
||||
*/
|
||||
impl<Vert> Simplex2_4<Vert>{
|
||||
fn det_is_zero<M:MeshQuery<Vert=Vert,Position=Planar64Vec3>>(self,mesh:&M)->bool{
|
||||
match self{
|
||||
Self::Simplex4([p0,p1,p2,p3])=>{
|
||||
let p0=mesh.vert(p0);
|
||||
let p1=mesh.vert(p1);
|
||||
let p2=mesh.vert(p2);
|
||||
let p3=mesh.vert(p3);
|
||||
(p1-p0).cross(p2-p0).dot(p3-p0)==Fixed::ZERO
|
||||
},
|
||||
Self::Simplex3([p0,p1,p2])=>{
|
||||
let p0=mesh.vert(p0);
|
||||
let p1=mesh.vert(p1);
|
||||
let p2=mesh.vert(p2);
|
||||
(p1-p0).cross(p2-p0)==vec3::zero()
|
||||
},
|
||||
Self::Simplex2([p0,p1])=>{
|
||||
let p0=mesh.vert(p0);
|
||||
let p1=mesh.vert(p1);
|
||||
p1-p0==vec3::zero()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
local function choosePerpendicularDirection(d)
|
||||
local x, y, z = d.x, d.y, d.z
|
||||
local best = math.min(x*x, y*y, z*z)
|
||||
if x*x == best then
|
||||
return Vector3.new(y*y + z*z, -x*y, -x*z)
|
||||
elseif y*y == best then
|
||||
return Vector3.new(-x*y, x*x + z*z, -y*z)
|
||||
else
|
||||
return Vector3.new(-x*z, -y*z, x*x + y*y)
|
||||
end
|
||||
end
|
||||
*/
|
||||
fn choose_perpendicular_direction(d:Planar64Vec3)->Planar64Vec3{
|
||||
let x=d.x.abs();
|
||||
let y=d.y.abs();
|
||||
let z=d.z.abs();
|
||||
if x<y&&x<z{
|
||||
Vector3::new([Fixed::ZERO,-d.z,d.y])
|
||||
}else if y<z{
|
||||
Vector3::new([d.z,Fixed::ZERO,-d.x])
|
||||
}else{
|
||||
Vector3::new([-d.y,d.x,Fixed::ZERO])
|
||||
}
|
||||
}
|
||||
|
||||
const fn choose_any_direction()->Planar64Vec3{
|
||||
vec3::X
|
||||
}
|
||||
|
||||
fn narrow_dir2(dir:Vector3<F128_64>)->Planar64Vec3{
|
||||
if dir==vec3::zero(){
|
||||
return dir.narrow_64().unwrap();
|
||||
}
|
||||
let x=dir.x.as_bits().unsigned_abs().bit_width();
|
||||
let y=dir.y.as_bits().unsigned_abs().bit_width();
|
||||
let z=dir.z.as_bits().unsigned_abs().bit_width();
|
||||
let big=x.max(y).max(z);
|
||||
const MAX_BITS:u32=64+31;
|
||||
if MAX_BITS<big{
|
||||
dir>>(big-MAX_BITS)
|
||||
}else{
|
||||
dir
|
||||
}.narrow_64().unwrap()
|
||||
}
|
||||
fn narrow_dir3(dir:Vector3<F192_96>)->Planar64Vec3{
|
||||
if dir==vec3::zero(){
|
||||
return dir.narrow_64().unwrap();
|
||||
}
|
||||
let x=dir.x.as_bits().unsigned_abs().bit_width();
|
||||
let y=dir.y.as_bits().unsigned_abs().bit_width();
|
||||
let z=dir.z.as_bits().unsigned_abs().bit_width();
|
||||
let big=x.max(y).max(z);
|
||||
const MAX_BITS:u32=96+31;
|
||||
if MAX_BITS<big{
|
||||
dir>>(big-MAX_BITS)
|
||||
}else{
|
||||
dir
|
||||
}.narrow_64().unwrap()
|
||||
}
|
||||
|
||||
fn reduce1<M:MeshQuery<Position=Planar64Vec3>>(
|
||||
[v0]:Simplex<1,M::Vert>,
|
||||
mesh:&M,
|
||||
point:Planar64Vec3,
|
||||
)->Reduced<M::Vert>
|
||||
where M::Vert:Copy,
|
||||
{
|
||||
// --debug.profilebegin("reduceSimplex0")
|
||||
// local a = a1 - a0
|
||||
let p0=mesh.vert(v0);
|
||||
|
||||
// local p = -a
|
||||
let p=-(p0+point);
|
||||
|
||||
// local direction = p
|
||||
let mut dir=p;
|
||||
|
||||
// if direction.magnitude == 0 then
|
||||
// direction = chooseAnyDirection()
|
||||
if dir==vec3::zero(){
|
||||
dir=choose_any_direction();
|
||||
}
|
||||
|
||||
// return direction, a0, a1
|
||||
Reduced{
|
||||
dir,
|
||||
simplex:Simplex1_3::Simplex1([v0]),
|
||||
}
|
||||
}
|
||||
|
||||
// local function reduceSimplex1(a0, a1, b0, b1)
|
||||
fn reduce2<M:MeshQuery<Position=Planar64Vec3>>(
|
||||
[v0,v1]:Simplex<2,M::Vert>,
|
||||
mesh:&M,
|
||||
point:Planar64Vec3,
|
||||
)->Reduced<M::Vert>
|
||||
where
|
||||
M::Vert:Copy
|
||||
{
|
||||
// --debug.profilebegin("reduceSimplex1")
|
||||
// local a = a1 - a0
|
||||
// local b = b1 - b0
|
||||
let p0=mesh.vert(v0);
|
||||
let p1=mesh.vert(v1);
|
||||
|
||||
// local p = -a
|
||||
// local u = b - a
|
||||
let p=-(p0+point);
|
||||
let u=p1-p0;
|
||||
|
||||
// -- modify to take into account the radiuses
|
||||
// local p_u = p:Dot(u)
|
||||
let p_u=p.dot(u);
|
||||
|
||||
// if p_u >= 0 then
|
||||
if !p_u.is_negative(){
|
||||
// local direction = u:Cross(p):Cross(u)
|
||||
let direction=u.cross(p).cross(u);
|
||||
|
||||
// if direction.magnitude == 0 then
|
||||
if direction==vec3::zero(){
|
||||
return Reduced{
|
||||
dir:choose_perpendicular_direction(u),
|
||||
simplex:Simplex1_3::Simplex2([v0,v1]),
|
||||
};
|
||||
}
|
||||
|
||||
// -- modify the direction to take into account a0R and b0R
|
||||
// return direction, a0, a1, b0, b1
|
||||
return Reduced{
|
||||
dir:narrow_dir3(direction),
|
||||
simplex:Simplex1_3::Simplex2([v0,v1]),
|
||||
};
|
||||
}
|
||||
|
||||
// local direction = p
|
||||
let mut dir=p;
|
||||
|
||||
// if direction.magnitude == 0 then
|
||||
if dir==vec3::zero(){
|
||||
dir=choose_perpendicular_direction(u);
|
||||
}
|
||||
|
||||
// return direction, a0, a1
|
||||
Reduced{
|
||||
dir,
|
||||
simplex:Simplex1_3::Simplex1([v0]),
|
||||
}
|
||||
}
|
||||
|
||||
// local function reduceSimplex2(a0, a1, b0, b1, c0, c1)
|
||||
fn reduce3<M:MeshQuery<Position=Planar64Vec3>>(
|
||||
[v0,mut v1,v2]:Simplex<3,M::Vert>,
|
||||
mesh:&M,
|
||||
point:Planar64Vec3,
|
||||
)->Reduced<M::Vert>
|
||||
where
|
||||
M::Vert:Copy
|
||||
{
|
||||
// --debug.profilebegin("reduceSimplex2")
|
||||
// local a = a1 - a0
|
||||
// local b = b1 - b0
|
||||
// local c = c1 - c0
|
||||
let p0=mesh.vert(v0);
|
||||
let p1=mesh.vert(v1);
|
||||
let p2=mesh.vert(v2);
|
||||
|
||||
// local p = -a
|
||||
// local u = b - a
|
||||
// local v = c - a
|
||||
let p=-(p0+point);
|
||||
let mut u=p1-p0;
|
||||
let v=p2-p0;
|
||||
|
||||
// local uv = u:Cross(v)
|
||||
// local up = u:Cross(p)
|
||||
// local pv = p:Cross(v)
|
||||
// local uv_up = uv:Dot(up)
|
||||
// local uv_pv = uv:Dot(pv)
|
||||
let mut uv=u.cross(v);
|
||||
let mut up=u.cross(p);
|
||||
let pv=p.cross(v);
|
||||
let uv_up=uv.dot(up);
|
||||
let uv_pv=uv.dot(pv);
|
||||
|
||||
// if uv_up >= 0 and uv_pv >= 0 then
|
||||
if !uv_up.is_negative()&&!uv_pv.is_negative(){
|
||||
// local uvp = uv:Dot(p)
|
||||
let uvp=uv.dot(p);
|
||||
|
||||
// local direction = uvp < 0 and -uv or uv
|
||||
let direction=if uvp.is_negative(){
|
||||
-uv
|
||||
}else{
|
||||
uv
|
||||
};
|
||||
|
||||
// return direction, a0, a1, b0, b1, c0, c1
|
||||
return Reduced{
|
||||
dir:narrow_dir2(direction),
|
||||
simplex:Simplex1_3::Simplex3([v0,v1,v2]),
|
||||
};
|
||||
}
|
||||
|
||||
// local u_u = u:Dot(u)
|
||||
// local v_v = v:Dot(v)
|
||||
// local uDist = uv_up/(u_u*v.magnitude)
|
||||
// local vDist = uv_pv/(v_v*u.magnitude)
|
||||
// local minDist2 = math.min(uDist, vDist)
|
||||
let u_dist=uv_up*v.length();
|
||||
let v_dist=uv_pv*u.length();
|
||||
|
||||
// if vDist == minDist2 then
|
||||
if v_dist<u_dist{
|
||||
u=v;
|
||||
up=-pv;
|
||||
uv=-uv;
|
||||
// b0 = c0
|
||||
// b1 = c1
|
||||
v1=v2;
|
||||
}
|
||||
|
||||
// local p_u = p:Dot(u)
|
||||
let p_u=p.dot(u);
|
||||
|
||||
// if p_u >= 0 then
|
||||
if !p_u.is_negative(){
|
||||
// local direction = up:Cross(u)
|
||||
let direction=up.cross(u);
|
||||
// if direction.magnitude == 0 then
|
||||
if direction==vec3::zero(){
|
||||
// direction = uv
|
||||
return Reduced{
|
||||
dir:narrow_dir2(uv),
|
||||
simplex:Simplex1_3::Simplex2([v0,v1]),
|
||||
};
|
||||
}
|
||||
|
||||
// return direction, a0, a1, b0, b1
|
||||
return Reduced{
|
||||
dir:narrow_dir3(direction),
|
||||
simplex:Simplex1_3::Simplex2([v0,v1]),
|
||||
};
|
||||
}
|
||||
|
||||
// local direction = p
|
||||
let dir=p;
|
||||
// if direction.magnitude == 0 then
|
||||
if dir==vec3::zero(){
|
||||
// direction = uv
|
||||
return Reduced{
|
||||
dir:narrow_dir2(uv),
|
||||
simplex:Simplex1_3::Simplex1([v0]),
|
||||
};
|
||||
}
|
||||
// return direction, a0, a0
|
||||
Reduced{
|
||||
dir,
|
||||
simplex:Simplex1_3::Simplex1([v0]),
|
||||
}
|
||||
}
|
||||
|
||||
// local function reduceSimplex3(a0, a1, b0, b1, c0, c1, d0, d1)
|
||||
fn reduce4<M:MeshQuery<Position=Planar64Vec3>>(
|
||||
[v0,mut v1,mut v2,v3]:Simplex<4,M::Vert>,
|
||||
mesh:&M,
|
||||
point:Planar64Vec3,
|
||||
)->Reduce<M::Vert>
|
||||
where
|
||||
M::Vert:Copy
|
||||
{
|
||||
// --debug.profilebegin("reduceSimplex3")
|
||||
// local a = a1 - a0
|
||||
// local b = b1 - b0
|
||||
// local c = c1 - c0
|
||||
// local d = d1 - d0
|
||||
let p0=mesh.vert(v0);
|
||||
let p1=mesh.vert(v1);
|
||||
let p2=mesh.vert(v2);
|
||||
let p3=mesh.vert(v3);
|
||||
|
||||
// local p = -a
|
||||
// local u = b - a
|
||||
// local v = c - a
|
||||
// local w = d - a
|
||||
let p=-(p0+point);
|
||||
let mut u=p1-p0;
|
||||
let mut v=p2-p0;
|
||||
let w=p3-p0;
|
||||
|
||||
// local uv = u:Cross(v)
|
||||
// local vw = v:Cross(w)
|
||||
// local wu = w:Cross(u)
|
||||
// local uvw = uv:Dot(w)
|
||||
// local pvw = vw:Dot(p)
|
||||
// local upw = wu:Dot(p)
|
||||
// local uvp = uv:Dot(p)
|
||||
let mut uv=u.cross(v);
|
||||
let vw=v.cross(w);
|
||||
let wu=w.cross(u);
|
||||
let uv_w=uv.dot(w);
|
||||
let pv_w=vw.dot(p);
|
||||
let up_w=wu.dot(p);
|
||||
let uv_p=uv.dot(p);
|
||||
|
||||
// if pvw/uvw >= 0 and upw/uvw >= 0 and uvp/uvw >= 0 then
|
||||
if !pv_w.div_sign(uv_w).is_negative()
|
||||
&&!up_w.div_sign(uv_w).is_negative()
|
||||
&&!uv_p.div_sign(uv_w).is_negative(){
|
||||
// origin is contained, this is a positive detection
|
||||
// local direction = Vector3.new(0, 0, 0)
|
||||
// return direction, a0, a1, b0, b1, c0, c1, d0, d1
|
||||
return Reduce::Escape([v0,v1,v2,v3]);
|
||||
}
|
||||
|
||||
// local uvwSign = uvw < 0 and -1 or uvw > 0 and 1 or 0
|
||||
// local uvDist = uvp*uvwSign/uv.magnitude
|
||||
// local vwDist = pvw*uvwSign/vw.magnitude
|
||||
// local wuDist = upw*uvwSign/wu.magnitude
|
||||
// local minDist3 = math.min(uvDist, vwDist, wuDist)
|
||||
let uv_dist=uv_p.mul_sign(uv_w);
|
||||
let vw_dist=pv_w.mul_sign(uv_w);
|
||||
let wu_dist=up_w.mul_sign(uv_w);
|
||||
let wu_len=wu.length();
|
||||
let uv_len=uv.length();
|
||||
let vw_len=vw.length();
|
||||
|
||||
if vw_dist*wu_len<wu_dist*vw_len{
|
||||
// if vwDist == minDist3 then
|
||||
if vw_dist*uv_len<uv_dist*vw_len{
|
||||
(u,v)=(v,w);
|
||||
uv=vw;
|
||||
// uv_p=pv_w; // unused
|
||||
// b0, c0 = c0, d0
|
||||
// b1, c1 = c1, d1
|
||||
(v1,v2)=(v2,v3);
|
||||
}
|
||||
}else{
|
||||
// elseif wuDist == minDist3 then
|
||||
if wu_dist*uv_len<uv_dist*wu_len{
|
||||
(u,v)=(w,u);
|
||||
uv=wu;
|
||||
// uv_p=up_w; // unused
|
||||
// b0, c0 = d0, b0
|
||||
// b1, c1 = d1, b1
|
||||
// before [a,b,c,d]
|
||||
(v1,v2)=(v3,v1);
|
||||
// after [a,d,b]
|
||||
}
|
||||
}
|
||||
|
||||
// local up = u:Cross(p)
|
||||
// local pv = p:Cross(v)
|
||||
// local uv_up = uv:Dot(up)
|
||||
// local uv_pv = uv:Dot(pv)
|
||||
let mut up=u.cross(p);
|
||||
let pv=p.cross(v);
|
||||
let uv_up=uv.dot(up);
|
||||
let uv_pv=uv.dot(pv);
|
||||
|
||||
// if uv_up >= 0 and uv_pv >= 0 then
|
||||
if !uv_up.is_negative()&&!uv_pv.is_negative(){
|
||||
// local direction = uvw < 0 and uv or -uv
|
||||
// return direction, a0, a1, b0, b1, c0, c1
|
||||
let dir=if uv_w.is_negative(){
|
||||
narrow_dir2(uv)
|
||||
}else{
|
||||
narrow_dir2(-uv)
|
||||
};
|
||||
return Reduce::Reduced(Reduced{
|
||||
dir,
|
||||
simplex:Simplex1_3::Simplex3([v0,v1,v2]),
|
||||
});
|
||||
}
|
||||
|
||||
// local u_u = u:Dot(u)
|
||||
// local v_v = v:Dot(v)
|
||||
// local uDist = uv_up/(u_u*v.magnitude)
|
||||
// local vDist = uv_pv/(v_v*u.magnitude)
|
||||
// local minDist2 = math.min(uDist, vDist)
|
||||
let u_dist=uv_up*v.length();
|
||||
let v_dist=uv_pv*u.length();
|
||||
|
||||
// if vDist == minDist2 then
|
||||
if v_dist<u_dist{
|
||||
u=v;
|
||||
up=-pv;
|
||||
uv=-uv;
|
||||
// b0 = c0
|
||||
// b1 = c1
|
||||
v1=v2;
|
||||
}
|
||||
|
||||
// local p_u = p:Dot(u)
|
||||
let p_u=p.dot(u);
|
||||
|
||||
// if p_u >= 0 then
|
||||
if !p_u.is_negative(){
|
||||
// local direction = up:Cross(u)
|
||||
let direction=up.cross(u);
|
||||
// if direction.magnitude == 0 then
|
||||
if direction==vec3::zero(){
|
||||
// direction = uvw < 0 and uv or -uv
|
||||
// return direction, a0, a1, b0, b1
|
||||
let dir=if uv_w.is_negative(){
|
||||
narrow_dir2(uv)
|
||||
}else{
|
||||
narrow_dir2(-uv)
|
||||
};
|
||||
return Reduce::Reduced(Reduced{
|
||||
dir,
|
||||
simplex:Simplex1_3::Simplex2([v0,v1]),
|
||||
});
|
||||
}
|
||||
|
||||
// return direction, a0, a1, b0, b1
|
||||
return Reduce::Reduced(Reduced{
|
||||
dir:narrow_dir3(direction),
|
||||
simplex:Simplex1_3::Simplex2([v0,v1]),
|
||||
});
|
||||
}
|
||||
|
||||
// local direction = p
|
||||
let dir=p;
|
||||
// if direction.magnitude == 0 then
|
||||
if dir==vec3::zero(){
|
||||
// direction = uvw < 0 and uv or -uv
|
||||
let dir=if uv_w.is_negative(){
|
||||
narrow_dir2(uv)
|
||||
}else{
|
||||
narrow_dir2(-uv)
|
||||
};
|
||||
return Reduce::Reduced(Reduced{
|
||||
dir,
|
||||
simplex:Simplex1_3::Simplex1([v0]),
|
||||
});
|
||||
}
|
||||
|
||||
// return direction, a0, a1
|
||||
Reduce::Reduced(Reduced{
|
||||
dir,
|
||||
simplex:Simplex1_3::Simplex1([v0]),
|
||||
})
|
||||
}
|
||||
|
||||
struct Reduced<Vert>{
|
||||
dir:Planar64Vec3,
|
||||
simplex:Simplex1_3<Vert>,
|
||||
}
|
||||
|
||||
enum Reduce<Vert>{
|
||||
Escape(Simplex<4,Vert>),
|
||||
Reduced(Reduced<Vert>),
|
||||
}
|
||||
|
||||
impl<Vert> Simplex2_4<Vert>{
|
||||
fn reduce<M:MeshQuery<Vert=Vert,Position=Planar64Vec3>>(self,mesh:&M,point:Planar64Vec3)->Reduce<Vert>
|
||||
where
|
||||
M::Vert:Copy
|
||||
{
|
||||
match self{
|
||||
Self::Simplex2(simplex)=>Reduce::Reduced(reduce2(simplex,mesh,point)),
|
||||
Self::Simplex3(simplex)=>Reduce::Reduced(reduce3(simplex,mesh,point)),
|
||||
Self::Simplex4(simplex)=>reduce4(simplex,mesh,point),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//infinity fev algorithm state transition
|
||||
#[derive(Debug)]
|
||||
enum Transition<Vert>{
|
||||
Done,//found closest vert, no edges are better
|
||||
Vert(Vert),//transition to vert
|
||||
}
|
||||
enum EV<M:MeshTopology>{
|
||||
Vert(M::Vert),
|
||||
Edge(M::Edge),
|
||||
}
|
||||
impl<M:MeshTopology> From<EV<M>> for FEV<M>{
|
||||
fn from(value:EV<M>)->Self{
|
||||
match value{
|
||||
EV::Vert(minkowski_vert)=>FEV::Vert(minkowski_vert),
|
||||
EV::Edge(minkowski_edge)=>FEV::Edge(minkowski_edge),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait Contains{
|
||||
fn contains(&self,point:Planar64Vec3)->bool;
|
||||
}
|
||||
|
||||
// convenience type to check if a point is within some threshold of a plane.
|
||||
struct ThickPlane{
|
||||
point:Planar64Vec3,
|
||||
normal:Vector3<F128_64>,
|
||||
epsilon:F192_96,
|
||||
}
|
||||
impl ThickPlane{
|
||||
fn new<M:MeshQuery<Position=Planar64Vec3>>(mesh:&M,[v0,v1,v2]:Simplex<3,M::Vert>)->Self{
|
||||
let p0=mesh.vert(v0);
|
||||
let p1=mesh.vert(v1);
|
||||
let p2=mesh.vert(v2);
|
||||
let point=p0;
|
||||
let normal=(p1-p0).cross(p2-p0);
|
||||
// Allow ~ 2*sqrt(3) units of thickness on the plane
|
||||
// This is to account for the variance of two voxels across the longest diagonal
|
||||
let epsilon=(normal.length()*(Planar64::EPSILON*3)).wrap_192();
|
||||
Self{point,normal,epsilon}
|
||||
}
|
||||
}
|
||||
impl Contains for ThickPlane{
|
||||
fn contains(&self,point:Planar64Vec3)->bool{
|
||||
(point-self.point).dot(self.normal).abs()<=self.epsilon
|
||||
}
|
||||
}
|
||||
|
||||
struct ThickLine{
|
||||
point:Planar64Vec3,
|
||||
dir:Planar64Vec3,
|
||||
epsilon:F256_128,
|
||||
}
|
||||
impl ThickLine{
|
||||
fn new<M:MeshQuery<Position=Planar64Vec3>>(mesh:&M,[v0,v1]:Simplex<2,M::Vert>)->Self{
|
||||
let p0=mesh.vert(v0);
|
||||
let p1=mesh.vert(v1);
|
||||
let point=p0;
|
||||
let dir=p1-p0;
|
||||
// Allow ~ 2*sqrt(3) units of thickness on the plane
|
||||
// This is to account for the variance of two voxels across the longest diagonal
|
||||
let epsilon=(dir.length_squared()*(Planar64::EPSILON*3)).widen_256();
|
||||
Self{point,dir,epsilon}
|
||||
}
|
||||
}
|
||||
impl Contains for ThickLine{
|
||||
fn contains(&self,point:Planar64Vec3)->bool{
|
||||
(point-self.point).cross(self.dir).length_squared()<=self.epsilon
|
||||
}
|
||||
}
|
||||
|
||||
struct EVFinder<'a,M,C>{
|
||||
mesh:&'a M,
|
||||
constraint:C,
|
||||
best_distance_squared:F128_64,
|
||||
}
|
||||
|
||||
impl<M:MeshQuery<Position=Planar64Vec3>,C:Contains> EVFinder<'_,M,C>
|
||||
where
|
||||
M::Vert:Copy,
|
||||
M::DirectedEdge:Copy,
|
||||
{
|
||||
fn next_transition_vert(&mut self,vert_id:M::Vert,point:Planar64Vec3)->Transition<M::Vert>{
|
||||
let mut best_transition=Transition::Done;
|
||||
self.mesh.for_each_vert_edge(vert_id,|directed_edge_id|{
|
||||
//test if this edge's opposite vertex closer
|
||||
let edge_verts=self.mesh.edge_verts(directed_edge_id.as_undirected());
|
||||
//select opposite vertex
|
||||
let test_vert_id=edge_verts.as_ref()[directed_edge_id.parity() as usize];
|
||||
let test_pos=self.mesh.vert(test_vert_id);
|
||||
let diff=point-test_pos;
|
||||
let distance_squared=diff.dot(diff);
|
||||
// ensure test_vert_id is coplanar to simplex
|
||||
if distance_squared<self.best_distance_squared&&self.constraint.contains(test_pos){
|
||||
best_transition=Transition::Vert(test_vert_id);
|
||||
self.best_distance_squared=distance_squared;
|
||||
}
|
||||
});
|
||||
best_transition
|
||||
}
|
||||
fn final_ev(&mut self,vert_id:M::Vert,point:Planar64Vec3)->EV<M>{
|
||||
let mut best_transition=EV::Vert(vert_id);
|
||||
let vert_pos=self.mesh.vert(vert_id);
|
||||
let diff=point-vert_pos;
|
||||
self.mesh.for_each_vert_edge(vert_id,|directed_edge_id|{
|
||||
//test if this edge is closer
|
||||
let edge_verts=self.mesh.edge_verts(directed_edge_id.as_undirected());
|
||||
let test_vert_id=edge_verts.as_ref()[directed_edge_id.parity() as usize];
|
||||
let test_pos=self.mesh.vert(test_vert_id);
|
||||
let edge_n=test_pos-vert_pos;
|
||||
let d=edge_n.dot(diff);
|
||||
//test the edge
|
||||
let edge_nn=edge_n.dot(edge_n);
|
||||
// ensure edge contains closest point and directed_edge_id is coplanar to simplex
|
||||
if !d.is_negative()&&d<=edge_nn&&self.constraint.contains(test_pos){
|
||||
let distance_squared={
|
||||
let c=diff.cross(edge_n);
|
||||
//wrap for speed
|
||||
(c.dot(c)/edge_nn).divide().wrap_128()
|
||||
};
|
||||
if distance_squared<=self.best_distance_squared{
|
||||
best_transition=EV::Edge(directed_edge_id.as_undirected());
|
||||
self.best_distance_squared=distance_squared;
|
||||
}
|
||||
}
|
||||
});
|
||||
best_transition
|
||||
}
|
||||
fn crawl_boundaries(&mut self,mut vert_id:M::Vert,point:Planar64Vec3)->EV<M>
|
||||
where
|
||||
M::Vert:Copy
|
||||
{
|
||||
loop{
|
||||
match self.next_transition_vert(vert_id,point){
|
||||
Transition::Done=>return self.final_ev(vert_id,point),
|
||||
Transition::Vert(new_vert_id)=>vert_id=new_vert_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// This function hops along parallel vertices until it finds the EV which contains the closest point to `point`.
|
||||
fn crawl_to_closest_ev<M:MeshQuery<Position=Planar64Vec3>>(mesh:&M,simplex:Simplex<2,M::Vert>,point:Planar64Vec3)->EV<M>
|
||||
where
|
||||
M::Vert:Copy,
|
||||
M::DirectedEdge:Copy,
|
||||
{
|
||||
// naively start at the closest vertex
|
||||
// the closest vertex is not necessarily the one with the fewest boundary hops
|
||||
// but it doesn't matter, we will get there regardless.
|
||||
let (vert_id,best_distance_squared)=simplex.into_iter().map(|vert_id|{
|
||||
let diff=point-mesh.vert(vert_id);
|
||||
(vert_id,diff.dot(diff))
|
||||
}).min_by_key(|&(_,d)|d).unwrap();
|
||||
|
||||
let constraint=ThickLine::new(mesh,simplex);
|
||||
let mut finder=EVFinder{constraint,mesh,best_distance_squared};
|
||||
//start on any vertex
|
||||
//cross uncrossable vertex-edge boundaries until you find the closest vertex or edge
|
||||
//cross edge-face boundary if it's uncrossable
|
||||
finder.crawl_boundaries(vert_id,point)
|
||||
}
|
||||
|
||||
/// This function hops along connected vertices until it finds the FEV which contains the closest point to `point`.
|
||||
fn crawl_to_closest_fev<'a>(mesh:&MinkowskiMesh<'a>,simplex:Simplex<3,MinkowskiVert>,point:Planar64Vec3)->FEV::<MinkowskiMesh<'a>>{
|
||||
// naively start at the closest vertex
|
||||
// the closest vertex is not necessarily the one with the fewest boundary hops
|
||||
// but it doesn't matter, we will get there regardless.
|
||||
let (vert_id,best_distance_squared)=simplex.into_iter().map(|vert_id|{
|
||||
let diff=point-mesh.vert(vert_id);
|
||||
(vert_id,diff.dot(diff))
|
||||
}).min_by_key(|&(_,d)|d).unwrap();
|
||||
|
||||
let constraint=ThickPlane::new(mesh,simplex);
|
||||
let mut finder=EVFinder{constraint,mesh,best_distance_squared};
|
||||
//start on any vertex
|
||||
//cross uncrossable vertex-edge boundaries until you find the closest vertex or edge
|
||||
//cross edge-face boundary if it's uncrossable
|
||||
match finder.crawl_boundaries(vert_id,point){
|
||||
//if a vert is returned, it is the closest point to the infinity point
|
||||
EV::Vert(vert_id)=>FEV::Vert(vert_id),
|
||||
EV::Edge(edge_id)=>{
|
||||
//cross to face if we are on the wrong side
|
||||
let edge_n=mesh.edge_n(edge_id);
|
||||
// point is multiplied by two because vert_sum sums two vertices.
|
||||
let delta_pos=point*2-{
|
||||
let &[v0,v1]=mesh.edge_verts(edge_id).as_ref();
|
||||
mesh.vert(v0)+mesh.vert(v1)
|
||||
};
|
||||
for (i,&face_id) in mesh.edge_faces(edge_id).as_ref().iter().enumerate(){
|
||||
//test if this face is closer
|
||||
let (face_n,d)=mesh.face_nd(face_id);
|
||||
//if test point is behind face, the face is invalid
|
||||
// TODO: find out why I thought of this backwards
|
||||
if !(face_n.dot(point)-d).is_positive(){
|
||||
continue;
|
||||
}
|
||||
//edge-face boundary nd, n facing out of the face towards the edge
|
||||
let boundary_n=face_n.cross(edge_n)*(i as i64*2-1);
|
||||
let boundary_d=boundary_n.dot(delta_pos);
|
||||
//is test point behind edge, i.e. contained in the face
|
||||
if !boundary_d.is_positive(){
|
||||
//both faces cannot pass this condition, return early if one does.
|
||||
return FEV::Face(face_id);
|
||||
}
|
||||
}
|
||||
FEV::Edge(edge_id)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn closest_fev_not_inside<'a>(mesh:&MinkowskiMesh<'a>,point:Planar64Vec3)->Option<FEV<MinkowskiMesh<'a>>>{
|
||||
const ENABLE_FAST_FAIL:bool=false;
|
||||
// TODO: remove mesh negation
|
||||
minimum_difference::<ENABLE_FAST_FAIL,_,_>(&-mesh,point,
|
||||
// on_exact
|
||||
|is_intersecting,simplex|{
|
||||
if is_intersecting{
|
||||
return None;
|
||||
}
|
||||
// Convert simplex to FEV
|
||||
// Vertices must be inverted since the mesh is inverted
|
||||
Some(match simplex{
|
||||
Simplex1_3::Simplex1([v0])=>FEV::Vert(-v0),
|
||||
Simplex1_3::Simplex2([v0,v1])=>{
|
||||
// invert
|
||||
let (v0,v1)=(-v0,-v1);
|
||||
crawl_to_closest_ev(mesh,[v0,v1],point).into()
|
||||
},
|
||||
Simplex1_3::Simplex3([v0,v1,v2])=>{
|
||||
// invert
|
||||
let (v0,v1,v2)=(-v0,-v1,-v2);
|
||||
// Shimmy to the side until you find a face that contains the closest point
|
||||
// it's ALWAYS representable as a face, but this algorithm may
|
||||
// return E or V in edge cases but I don't think that will break the face crawler
|
||||
crawl_to_closest_fev(mesh,[v0,v1,v2],point)
|
||||
},
|
||||
})
|
||||
},
|
||||
// on_escape
|
||||
|_simplex|{
|
||||
// intersection is guaranteed at this point
|
||||
// local norm, dist, u0, u1, v0, v1, w0, w1 = expand(queryP, queryQ, a0, a1, b0, b1, c0, c1, d0, d1, 1e-5)
|
||||
// let simplex=refine_to_exact(mesh,simplex);
|
||||
None
|
||||
},
|
||||
// fast_fail value is irrelevant and will never be returned!
|
||||
||unreachable!()
|
||||
)
|
||||
}
|
||||
|
||||
pub fn contains_point(mesh:&MinkowskiMesh<'_>,point:Planar64Vec3)->bool{
|
||||
const ENABLE_FAST_FAIL:bool=true;
|
||||
// TODO: remove mesh negation
|
||||
minimum_difference::<ENABLE_FAST_FAIL,_,_>(&-mesh,point,
|
||||
// on_exact
|
||||
|is_intersecting,_simplex|{
|
||||
is_intersecting
|
||||
},
|
||||
// on_escape
|
||||
|_simplex|{
|
||||
// intersection is guaranteed at this point
|
||||
true
|
||||
},
|
||||
// fast_fail value
|
||||
||false
|
||||
)
|
||||
}
|
||||
|
||||
// local function minimumDifference(
|
||||
// queryP, radiusP,
|
||||
// queryQ, radiusQ,
|
||||
// exitRadius, testIntersection
|
||||
// )
|
||||
fn minimum_difference<const ENABLE_FAST_FAIL:bool,T,M:MeshQuery<Position=Planar64Vec3,Direction=Planar64Vec3>>(
|
||||
mesh:&M,
|
||||
point:Planar64Vec3,
|
||||
on_exact:impl FnOnce(bool,Simplex1_3<M::Vert>)->T,
|
||||
on_escape:impl FnOnce(Simplex<4,M::Vert>)->T,
|
||||
on_fast_fail:impl FnOnce()->T,
|
||||
)->T
|
||||
where
|
||||
M::Vert:Copy
|
||||
{
|
||||
// local initialAxis = queryQ() - queryP()
|
||||
// local new_point_p = queryP(initialAxis)
|
||||
// local new_point_q = queryQ(-initialAxis)
|
||||
// local direction, a0, a1, b0, b1, c0, c1, d0, d1
|
||||
let mut initial_axis=mesh.hint_point()+point;
|
||||
// degenerate case
|
||||
if initial_axis==vec3::zero(){
|
||||
initial_axis=choose_any_direction();
|
||||
}
|
||||
let last_point=mesh.farthest_vert(-initial_axis);
|
||||
// this represents the 'a' value in the commented code
|
||||
let mut last_pos=mesh.vert(last_point);
|
||||
let Reduced{dir:mut direction,simplex:mut simplex_small}=reduce1([last_point],mesh,point);
|
||||
|
||||
// exitRadius = testIntersection and 0 or exitRadius or 1/0
|
||||
// for _ = 1, 100 do
|
||||
loop{
|
||||
// new_point_p = queryP(-direction)
|
||||
// new_point_q = queryQ(direction)
|
||||
// local next_point = new_point_q - new_point_p
|
||||
let next_point=mesh.farthest_vert(direction);
|
||||
let next_pos=mesh.vert(next_point);
|
||||
|
||||
// if -direction:Dot(next_point) > (exitRadius + radiusP + radiusQ)*direction.magnitude then
|
||||
if ENABLE_FAST_FAIL&&direction.dot(next_pos+point).is_negative(){
|
||||
return on_fast_fail();
|
||||
}
|
||||
|
||||
let simplex_big=simplex_small.push_front(next_point);
|
||||
|
||||
// if
|
||||
// direction:Dot(next_point - a) <= 0 or
|
||||
// absDet(next_point, a, b, c) < 1e-6
|
||||
if !direction.dot(next_pos-last_pos).is_positive()
|
||||
||simplex_big.det_is_zero(mesh){
|
||||
// Found enough information to compute the exact closest point.
|
||||
// local norm = direction.unit
|
||||
// local dist = a:Dot(norm)
|
||||
// local hits = -dist < radiusP + radiusQ
|
||||
let is_intersecting=(last_pos+point).dot(direction).is_positive();
|
||||
return on_exact(is_intersecting,simplex_small);
|
||||
}
|
||||
|
||||
// direction, a0, a1, b0, b1, c0, c1, d0, d1 = reduceSimplex(new_point_p, new_point_q, a0, a1, b0, b1, c0, c1)
|
||||
match simplex_big.reduce(mesh,point){
|
||||
// if a and b and c and d then
|
||||
Reduce::Escape(simplex)=>{
|
||||
// Enough information to conclude that the meshes are intersecting.
|
||||
// Topology information is computed if needed.
|
||||
return on_escape(simplex);
|
||||
},
|
||||
Reduce::Reduced(reduced)=>{
|
||||
direction=reduced.dir;
|
||||
simplex_small=reduced.simplex;
|
||||
},
|
||||
}
|
||||
|
||||
// next loop this will be a
|
||||
last_pos=next_pos;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test{
|
||||
use super::*;
|
||||
use crate::model::{PhysicsMesh,PhysicsMeshView};
|
||||
|
||||
fn mesh_contains_point(mesh:PhysicsMeshView<'_>,point:Planar64Vec3)->bool{
|
||||
const ENABLE_FAST_FAIL:bool=true;
|
||||
// TODO: remove mesh negation
|
||||
minimum_difference::<ENABLE_FAST_FAIL,_,_>(&mesh,point,
|
||||
// on_exact
|
||||
|is_intersecting,_simplex|{
|
||||
is_intersecting
|
||||
},
|
||||
// on_escape
|
||||
|_simplex|{
|
||||
// intersection is guaranteed at this point
|
||||
true
|
||||
},
|
||||
// fast_fail value
|
||||
||false
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cube_points(){
|
||||
let mesh=PhysicsMesh::unit_cube();
|
||||
let mesh_view=mesh.complete_mesh_view();
|
||||
for x in -2..=2{
|
||||
for y in -2..=2{
|
||||
for z in -2..=2{
|
||||
let point=vec3::int(x,y,z)>>1;
|
||||
assert!(mesh_contains_point(mesh_view,point),"Mesh did not contain point {point}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
409
engine/physics/src/minkowski.rs
Normal file
409
engine/physics/src/minkowski.rs
Normal file
@@ -0,0 +1,409 @@
|
||||
use core::ops::{Bound,RangeBounds};
|
||||
|
||||
use strafesnet_common::integer::fixed_types::{F192_96,F256_128,F512_256};
|
||||
use strafesnet_common::integer::vec3::Vector3;
|
||||
use strafesnet_common::integer::{Planar64Vec3,Ratio,Fixed};
|
||||
use crate::model::into_giga_time;
|
||||
use crate::model::{SubmeshVertId,SubmeshEdgeId,SubmeshDirectedEdgeId,SubmeshFaceId,TransformedMesh,GigaTime};
|
||||
use crate::mesh_query::{MeshQuery,MeshTopology,DirectedEdge,UndirectedEdge};
|
||||
use crate::physics::{Time,Trajectory};
|
||||
|
||||
struct AsRefHelper<T>(T);
|
||||
impl<T> AsRef<T> for AsRefHelper<T>{
|
||||
fn as_ref(&self)->&T{
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
//Note that a face on a minkowski mesh refers to a pair of fevs on the meshes it's summed from
|
||||
//(face,vertex)
|
||||
//(edge,edge)
|
||||
//(vertex,face)
|
||||
#[derive(Clone,Copy,Debug,Eq,PartialEq)]
|
||||
pub enum MinkowskiVert{
|
||||
VertVert(SubmeshVertId,SubmeshVertId),
|
||||
}
|
||||
// TODO: remove this
|
||||
impl core::ops::Neg for MinkowskiVert{
|
||||
type Output=Self;
|
||||
fn neg(self)->Self::Output{
|
||||
match self{
|
||||
MinkowskiVert::VertVert(v0,v1)=>MinkowskiVert::VertVert(v1,v0),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone,Copy,Debug)]
|
||||
pub enum MinkowskiEdge{
|
||||
VertEdge(SubmeshVertId,SubmeshEdgeId),
|
||||
EdgeVert(SubmeshEdgeId,SubmeshVertId),
|
||||
//EdgeEdge when edges are parallel
|
||||
}
|
||||
impl UndirectedEdge for MinkowskiEdge{
|
||||
type DirectedEdge=MinkowskiDirectedEdge;
|
||||
fn as_directed(self,parity:bool)->Self::DirectedEdge{
|
||||
match self{
|
||||
MinkowskiEdge::VertEdge(v0,e1)=>MinkowskiDirectedEdge::VertEdge(v0,e1.as_directed(parity)),
|
||||
MinkowskiEdge::EdgeVert(e0,v1)=>MinkowskiDirectedEdge::EdgeVert(e0.as_directed(parity),v1),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone,Copy,Debug)]
|
||||
pub enum MinkowskiDirectedEdge{
|
||||
VertEdge(SubmeshVertId,SubmeshDirectedEdgeId),
|
||||
EdgeVert(SubmeshDirectedEdgeId,SubmeshVertId),
|
||||
//EdgeEdge when edges are parallel
|
||||
}
|
||||
impl DirectedEdge for MinkowskiDirectedEdge{
|
||||
type UndirectedEdge=MinkowskiEdge;
|
||||
fn as_undirected(self)->Self::UndirectedEdge{
|
||||
match self{
|
||||
MinkowskiDirectedEdge::VertEdge(v0,e1)=>MinkowskiEdge::VertEdge(v0,e1.as_undirected()),
|
||||
MinkowskiDirectedEdge::EdgeVert(e0,v1)=>MinkowskiEdge::EdgeVert(e0.as_undirected(),v1),
|
||||
}
|
||||
}
|
||||
fn parity(&self)->bool{
|
||||
match self{
|
||||
MinkowskiDirectedEdge::VertEdge(_,e)
|
||||
|MinkowskiDirectedEdge::EdgeVert(e,_)=>e.parity(),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone,Copy,Debug,Hash)]
|
||||
pub enum MinkowskiFace{
|
||||
VertFace(SubmeshVertId,SubmeshFaceId),
|
||||
EdgeEdge(SubmeshEdgeId,SubmeshEdgeId,bool),
|
||||
FaceVert(SubmeshFaceId,SubmeshVertId),
|
||||
//EdgeFace
|
||||
//FaceEdge
|
||||
//FaceFace
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct MinkowskiMesh<'a>{
|
||||
mesh0:TransformedMesh<'a>,
|
||||
mesh1:TransformedMesh<'a>,
|
||||
}
|
||||
|
||||
// TODO: remove this
|
||||
impl<'a> core::ops::Neg for &MinkowskiMesh<'a>{
|
||||
type Output=MinkowskiMesh<'a>;
|
||||
fn neg(self)->Self::Output{
|
||||
MinkowskiMesh::minkowski_sum(self.mesh1,self.mesh0)
|
||||
}
|
||||
}
|
||||
|
||||
impl MinkowskiMesh<'_>{
|
||||
pub fn minkowski_sum<'a>(mesh0:TransformedMesh<'a>,mesh1:TransformedMesh<'a>)->MinkowskiMesh<'a>{
|
||||
MinkowskiMesh{
|
||||
mesh0,
|
||||
mesh1,
|
||||
}
|
||||
}
|
||||
pub fn predict_collision_in(&self,trajectory:&Trajectory,range:impl RangeBounds<Time>)->Option<(MinkowskiFace,GigaTime)>{
|
||||
let start_position=match range.start_bound(){
|
||||
Bound::Included(time)=>trajectory.extrapolated_position(*time),
|
||||
Bound::Excluded(time)=>trajectory.extrapolated_position(*time),
|
||||
Bound::Unbounded=>trajectory.position,
|
||||
};
|
||||
let fev=crate::minimum_difference::closest_fev_not_inside(self,start_position)?;
|
||||
//continue forwards along the body parabola
|
||||
fev.crawl(self,trajectory,range.start_bound(),range.end_bound()).hit()
|
||||
}
|
||||
pub fn predict_collision_out(&self,trajectory:&Trajectory,range:impl RangeBounds<Time>)->Option<(MinkowskiFace,GigaTime)>{
|
||||
let (lower_bound,upper_bound)=(range.start_bound(),range.end_bound());
|
||||
// TODO: handle unbounded collision using infinity fev
|
||||
let start_position=match upper_bound{
|
||||
Bound::Included(time)=>trajectory.extrapolated_position(*time),
|
||||
Bound::Excluded(time)=>trajectory.extrapolated_position(*time),
|
||||
Bound::Unbounded=>trajectory.position,
|
||||
};
|
||||
let fev=crate::minimum_difference::closest_fev_not_inside(self,start_position)?;
|
||||
// swap and negate bounds to do a time inversion
|
||||
let (lower_bound,upper_bound)=(upper_bound.map(|&t|-t),lower_bound.map(|&t|-t));
|
||||
let time_reversed_trajectory=-trajectory;
|
||||
//continue backwards along the body parabola
|
||||
fev.crawl(self,&time_reversed_trajectory,lower_bound.as_ref(),upper_bound.as_ref()).hit()
|
||||
//no need to test -time<time_limit because of the first step
|
||||
.map(|(face,time)|(face,-time))
|
||||
}
|
||||
pub fn predict_collision_face_out(&self,trajectory:&Trajectory,range:impl RangeBounds<Time>,contact_face_id:MinkowskiFace)->Option<(MinkowskiDirectedEdge,GigaTime)>{
|
||||
// TODO: make better
|
||||
use crate::face_crawler::{low,upp};
|
||||
//no algorithm needed, there is only one state and two cases (Edge,None)
|
||||
//determine when it passes an edge ("sliding off" case)
|
||||
let start_time=range.start_bound().map(|&t|(t-trajectory.time).to_ratio());
|
||||
let mut best_time=range.end_bound().map(|&t|into_giga_time(t,trajectory.time));
|
||||
let mut best_edge=None;
|
||||
let face_n=self.face_nd(contact_face_id).0;
|
||||
self.for_each_face_edge(contact_face_id,|directed_edge_id|{
|
||||
let edge_n=self.directed_edge_n(directed_edge_id);
|
||||
//f x e points in
|
||||
let n=face_n.cross(edge_n);
|
||||
let &[v0,v1]=self.edge_verts(directed_edge_id.as_undirected()).as_ref();
|
||||
let d=n.dot(self.vert(v0)+self.vert(v1));
|
||||
//WARNING! d outside of *2
|
||||
//WARNING: truncated precision
|
||||
//wrap for speed
|
||||
for dt in F256_128::zeroes2(((n.dot(trajectory.position))*2-d).wrap_256(),n.dot(trajectory.velocity).wrap_256()*2,n.dot(trajectory.acceleration).wrap_256()){
|
||||
if low(&start_time,&dt)&&upp(&dt,&best_time)&&n.dot(trajectory.extrapolated_velocity_ratio_dt(dt)).is_negative(){
|
||||
best_time=Bound::Included(dt);
|
||||
best_edge=Some((directed_edge_id,dt));
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
best_edge
|
||||
}
|
||||
pub fn contains_point(&self,point:Planar64Vec3)->bool{
|
||||
crate::minimum_difference::contains_point(self,point)
|
||||
}
|
||||
}
|
||||
impl MeshQuery for MinkowskiMesh<'_>{
|
||||
type Direction=Planar64Vec3;
|
||||
type Position=Planar64Vec3;
|
||||
type Normal=Vector3<F192_96>;
|
||||
type Offset=F256_128;
|
||||
// TODO: relative d
|
||||
fn face_nd(&self,face_id:MinkowskiFace)->(Self::Normal,Self::Offset){
|
||||
match face_id{
|
||||
MinkowskiFace::VertFace(v0,f1)=>{
|
||||
let (n,d)=self.mesh1.face_nd(f1);
|
||||
(-n,d-n.dot(self.mesh0.vert(v0)))
|
||||
},
|
||||
MinkowskiFace::EdgeEdge(e0,e1,parity)=>{
|
||||
let edge0_n=self.mesh0.edge_n(e0);
|
||||
let edge1_n=self.mesh1.edge_n(e1);
|
||||
let &[e0v0,e0v1]=self.mesh0.edge_verts(e0).as_ref();
|
||||
let &[e1v0,e1v1]=self.mesh1.edge_verts(e1).as_ref();
|
||||
let n=edge0_n.cross(edge1_n);
|
||||
let e0d=n.dot(self.mesh0.vert(e0v0)+self.mesh0.vert(e0v1));
|
||||
let e1d=n.dot(self.mesh1.vert(e1v0)+self.mesh1.vert(e1v1));
|
||||
((n*(parity as i64*4-2)).widen_192(),((e0d-e1d)*(parity as i64*2-1)).widen_256())
|
||||
},
|
||||
MinkowskiFace::FaceVert(f0,v1)=>{
|
||||
let (n,d)=self.mesh0.face_nd(f0);
|
||||
(n,d-n.dot(self.mesh1.vert(v1)))
|
||||
},
|
||||
}
|
||||
}
|
||||
fn vert(&self,vert_id:MinkowskiVert)->Planar64Vec3{
|
||||
match vert_id{
|
||||
MinkowskiVert::VertVert(v0,v1)=>{
|
||||
self.mesh0.vert(v0)-self.mesh1.vert(v1)
|
||||
},
|
||||
}
|
||||
}
|
||||
fn hint_point(&self)->Planar64Vec3{
|
||||
self.mesh0.hint_point()-self.mesh1.hint_point()
|
||||
}
|
||||
fn farthest_vert(&self,dir:Planar64Vec3)->MinkowskiVert{
|
||||
MinkowskiVert::VertVert(self.mesh0.farthest_vert(dir),self.mesh1.farthest_vert(-dir))
|
||||
}
|
||||
fn edge_n(&self,edge_id:Self::Edge)->Self::Direction{
|
||||
let &[v0,v1]=self.edge_verts(edge_id).as_ref();
|
||||
self.vert(v1)-self.vert(v0)
|
||||
}
|
||||
fn directed_edge_n(&self,directed_edge_id:Self::DirectedEdge)->Self::Direction{
|
||||
let &[v0,v1]=self.edge_verts(directed_edge_id.as_undirected()).as_ref();
|
||||
(self.vert(v1)-self.vert(v0))*((directed_edge_id.parity() as i64)*2-1)
|
||||
}
|
||||
}
|
||||
impl MeshTopology for MinkowskiMesh<'_>{
|
||||
type Face=MinkowskiFace;
|
||||
type Edge=MinkowskiEdge;
|
||||
type DirectedEdge=MinkowskiDirectedEdge;
|
||||
type Vert=MinkowskiVert;
|
||||
fn for_each_vert_edge(&self,vert_id:Self::Vert,mut f:impl FnMut(Self::DirectedEdge)){
|
||||
match vert_id{
|
||||
MinkowskiVert::VertVert(v0,v1)=>{
|
||||
//detect shared volume when the other mesh is mirrored along a test edge dir
|
||||
let v0f={
|
||||
let mut faces=Vec::new();
|
||||
self.mesh0.for_each_vert_face(v0,|face|faces.push(face));
|
||||
faces
|
||||
};
|
||||
let v1f={
|
||||
let mut faces=Vec::new();
|
||||
self.mesh1.for_each_vert_face(v1,|face|faces.push(face));
|
||||
faces
|
||||
};
|
||||
let v0f_n:Vec<_>=v0f.iter().map(|&face_id|self.mesh0.face_nd(face_id).0).collect();
|
||||
let v1f_n:Vec<_>=v1f.iter().map(|&face_id|self.mesh1.face_nd(face_id).0).collect();
|
||||
// scratch vector
|
||||
let mut face_normals=Vec::with_capacity(v0f.len()+v1f.len());
|
||||
face_normals.clone_from(&v0f_n);
|
||||
self.mesh0.for_each_vert_edge(v0,|directed_edge_id|{
|
||||
let n=self.mesh0.directed_edge_n(directed_edge_id);
|
||||
let nn=n.dot(n);
|
||||
// TODO: there's gotta be a better way to do this
|
||||
// drop faces beyond v0f_n
|
||||
face_normals.truncate(v0f.len());
|
||||
// make a set of faces from mesh0's perspective
|
||||
for face_n in &v1f_n{
|
||||
//add reflected mesh1 faces
|
||||
//wrap for speed
|
||||
face_normals.push(*face_n-(n*face_n.dot(n)*2/nn).divide().wrap_192());
|
||||
}
|
||||
if is_empty_volume(&face_normals){
|
||||
f(MinkowskiDirectedEdge::EdgeVert(directed_edge_id,v1));
|
||||
}
|
||||
});
|
||||
face_normals.clone_from(&v1f_n);
|
||||
self.mesh1.for_each_vert_edge(v1,|directed_edge_id|{
|
||||
let n=self.mesh1.directed_edge_n(directed_edge_id);
|
||||
let nn=n.dot(n);
|
||||
// drop faces beyond v1f_n
|
||||
face_normals.truncate(v1f.len());
|
||||
// make a set of faces from mesh1's perspective
|
||||
for face_n in &v0f_n{
|
||||
//wrap for speed
|
||||
face_normals.push(*face_n-(n*face_n.dot(n)*2/nn).divide().wrap_192());
|
||||
}
|
||||
if is_empty_volume(&face_normals){
|
||||
f(MinkowskiDirectedEdge::VertEdge(v0,directed_edge_id));
|
||||
}
|
||||
});
|
||||
},
|
||||
}
|
||||
}
|
||||
fn for_each_vert_face(&self,_vert_id:Self::Vert,_f:impl FnMut(Self::Face)){
|
||||
unimplemented!()
|
||||
}
|
||||
fn edge_faces(&self,edge_id:Self::Edge)->impl AsRef<[Self::Face;2]>{
|
||||
match edge_id{
|
||||
MinkowskiEdge::VertEdge(v0,e1)=>{
|
||||
//faces are listed backwards from the minkowski mesh
|
||||
let v0e={
|
||||
let mut edges=Vec::new();
|
||||
self.mesh0.for_each_vert_edge(v0,|edge|edges.push(edge));
|
||||
edges
|
||||
};
|
||||
let &[e1f0,e1f1]=self.mesh1.edge_faces(e1).as_ref();
|
||||
AsRefHelper([(e1f1,false),(e1f0,true)].map(|(edge_face_id1,face_parity)|{
|
||||
let mut best_edge=None;
|
||||
let mut best_d:Ratio<F512_256,F512_256>=Ratio::new(Fixed::ZERO,Fixed::ONE);
|
||||
let edge_face1_n=self.mesh1.face_nd(edge_face_id1).0;
|
||||
let edge_face1_nn=edge_face1_n.dot(edge_face1_n);
|
||||
for &directed_edge_id0 in &v0e{
|
||||
let edge0_n=self.mesh0.directed_edge_n(directed_edge_id0);
|
||||
//must be behind other face.
|
||||
let d=edge_face1_n.dot(edge0_n);
|
||||
if d.is_negative(){
|
||||
let edge0_nn=edge0_n.dot(edge0_n);
|
||||
// Assume not every number is huge
|
||||
// TODO: revisit this
|
||||
let dd=(d*d)/(edge_face1_nn*edge0_nn);
|
||||
if best_d<dd{
|
||||
best_d=dd;
|
||||
best_edge=Some(directed_edge_id0);
|
||||
}
|
||||
}
|
||||
}
|
||||
best_edge.map_or(
|
||||
MinkowskiFace::VertFace(v0,edge_face_id1),
|
||||
|directed_edge_id0|MinkowskiFace::EdgeEdge(directed_edge_id0.as_undirected(),e1,directed_edge_id0.parity()^face_parity)
|
||||
)
|
||||
}))
|
||||
},
|
||||
MinkowskiEdge::EdgeVert(e0,v1)=>{
|
||||
//tracking index with an external variable because .enumerate() is not available
|
||||
let v1e={
|
||||
let mut edges=Vec::new();
|
||||
self.mesh1.for_each_vert_edge(v1,|edge|edges.push(edge));
|
||||
edges
|
||||
};
|
||||
let &[e0f0,e0f1]=self.mesh0.edge_faces(e0).as_ref();
|
||||
AsRefHelper([(e0f0,true),(e0f1,false)].map(|(edge_face_id0,face_parity)|{
|
||||
let mut best_edge=None;
|
||||
let mut best_d:Ratio<F512_256,F512_256>=Ratio::new(Fixed::ZERO,Fixed::ONE);
|
||||
let edge_face0_n=self.mesh0.face_nd(edge_face_id0).0;
|
||||
let edge_face0_nn=edge_face0_n.dot(edge_face0_n);
|
||||
for &directed_edge_id1 in &v1e{
|
||||
let edge1_n=self.mesh1.directed_edge_n(directed_edge_id1);
|
||||
let d=edge_face0_n.dot(edge1_n);
|
||||
if d.is_negative(){
|
||||
let edge1_nn=edge1_n.dot(edge1_n);
|
||||
let dd=(d*d)/(edge_face0_nn*edge1_nn);
|
||||
if best_d<dd{
|
||||
best_d=dd;
|
||||
best_edge=Some(directed_edge_id1);
|
||||
}
|
||||
}
|
||||
}
|
||||
best_edge.map_or(
|
||||
MinkowskiFace::FaceVert(edge_face_id0,v1),
|
||||
|directed_edge_id1|MinkowskiFace::EdgeEdge(e0,directed_edge_id1.as_undirected(),directed_edge_id1.parity()^face_parity)
|
||||
)
|
||||
}))
|
||||
},
|
||||
}
|
||||
}
|
||||
fn edge_verts(&self,edge_id:Self::Edge)->impl AsRef<[Self::Vert;2]>{
|
||||
AsRefHelper(match edge_id{
|
||||
MinkowskiEdge::VertEdge(v0,e1)=>self.mesh1.edge_verts(e1).as_ref().map(|vert_id1|
|
||||
MinkowskiVert::VertVert(v0,vert_id1)
|
||||
),
|
||||
MinkowskiEdge::EdgeVert(e0,v1)=>self.mesh0.edge_verts(e0).as_ref().map(|vert_id0|
|
||||
MinkowskiVert::VertVert(vert_id0,v1)
|
||||
),
|
||||
})
|
||||
}
|
||||
fn for_each_face_vert(&self,_face_id:Self::Face,_f:impl FnMut(Self::Vert)){
|
||||
unimplemented!()
|
||||
}
|
||||
fn for_each_face_edge(&self,face_id:Self::Face,mut f:impl FnMut(Self::DirectedEdge)){
|
||||
match face_id{
|
||||
MinkowskiFace::VertFace(v0,f1)=>{
|
||||
self.mesh1.for_each_face_edge(f1,|edge_id1|
|
||||
f(MinkowskiDirectedEdge::VertEdge(v0,edge_id1.reverse()))
|
||||
)
|
||||
},
|
||||
MinkowskiFace::EdgeEdge(e0,e1,parity)=>{
|
||||
let &[e0v0,e0v1]=self.mesh0.edge_verts(e0).as_ref();
|
||||
let &[e1v0,e1v1]=self.mesh1.edge_verts(e1).as_ref();
|
||||
//could sort this if ordered edges are needed
|
||||
//probably just need to reverse this list according to parity
|
||||
f(MinkowskiDirectedEdge::VertEdge(e0v0,e1.as_directed(parity)));
|
||||
f(MinkowskiDirectedEdge::EdgeVert(e0.as_directed(!parity),e1v0));
|
||||
f(MinkowskiDirectedEdge::VertEdge(e0v1,e1.as_directed(!parity)));
|
||||
f(MinkowskiDirectedEdge::EdgeVert(e0.as_directed(parity),e1v1));
|
||||
},
|
||||
MinkowskiFace::FaceVert(f0,v1)=>{
|
||||
self.mesh0.for_each_face_edge(f0,|edge_id0|
|
||||
f(MinkowskiDirectedEdge::EdgeVert(edge_id0,v1))
|
||||
)
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_empty_volume(normals:&[Vector3<F192_96>])->bool{
|
||||
let len=normals.len();
|
||||
for i in 0..len-1{
|
||||
for j in i+1..len{
|
||||
let n=normals[i].cross(normals[j]);
|
||||
let mut d_comp=None;
|
||||
for k in 0..len{
|
||||
if k!=i&&k!=j{
|
||||
let d=n.dot(normals[k]).is_negative();
|
||||
if let &Some(comp)=&d_comp{
|
||||
// This is testing if d_comp*d < 0
|
||||
if comp^d{
|
||||
return true;
|
||||
}
|
||||
}else{
|
||||
d_comp=Some(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_empty_volume(){
|
||||
use strafesnet_common::integer::vec3;
|
||||
assert!(!is_empty_volume(&[vec3::X.widen_192(),vec3::Y.widen_192(),vec3::Z.widen_192()]));
|
||||
assert!(is_empty_volume(&[vec3::X.widen_192(),vec3::Y.widen_192(),vec3::Z.widen_192(),vec3::NEG_X.widen_192()]));
|
||||
}
|
||||
570
engine/physics/src/model.rs
Normal file
570
engine/physics/src/model.rs
Normal file
@@ -0,0 +1,570 @@
|
||||
use std::collections::{HashSet,HashMap};
|
||||
use strafesnet_common::integer::fixed_types::{F128_64,F192_96,F256_128};
|
||||
use strafesnet_common::integer::vec3::Vector3;
|
||||
use strafesnet_common::model::{self,MeshId,PolygonIter};
|
||||
use strafesnet_common::integer::{self,vec3,Fixed,Planar64,Planar64Vec3,Ratio};
|
||||
use strafesnet_common::physics::Time;
|
||||
use crate::mesh_query::{MeshQuery,MeshTopology,DirectedEdge,UndirectedEdge};
|
||||
|
||||
struct AsRefHelper<T>(T);
|
||||
impl<T> AsRef<T> for AsRefHelper<T>{
|
||||
fn as_ref(&self)->&T{
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
|
||||
pub struct MeshVertId(u32);
|
||||
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
|
||||
pub struct MeshFaceId(u32);
|
||||
|
||||
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
|
||||
pub struct SubmeshVertId(u32);
|
||||
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
|
||||
pub struct SubmeshEdgeId(u32);
|
||||
/// DirectedEdgeId refers to an EdgeId when undirected.
|
||||
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
|
||||
pub struct SubmeshDirectedEdgeId(u32);
|
||||
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
|
||||
pub struct SubmeshFaceId(u32);
|
||||
|
||||
impl UndirectedEdge for SubmeshEdgeId{
|
||||
type DirectedEdge=SubmeshDirectedEdgeId;
|
||||
fn as_directed(self,parity:bool)->SubmeshDirectedEdgeId{
|
||||
SubmeshDirectedEdgeId(self.0|((parity as u32)<<(u32::BITS-1)))
|
||||
}
|
||||
}
|
||||
impl DirectedEdge for SubmeshDirectedEdgeId{
|
||||
type UndirectedEdge=SubmeshEdgeId;
|
||||
fn as_undirected(self)->SubmeshEdgeId{
|
||||
SubmeshEdgeId(self.0&!(1<<(u32::BITS-1)))
|
||||
}
|
||||
fn parity(&self)->bool{
|
||||
self.0&(1<<(u32::BITS-1))!=0
|
||||
}
|
||||
}
|
||||
|
||||
//use Unit32 #[repr(C)] for map files
|
||||
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq)]
|
||||
struct Face{
|
||||
normal:Planar64Vec3,
|
||||
dot:Planar64,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct Vert(Planar64Vec3);
|
||||
#[derive(Debug)]
|
||||
struct FaceRefs{
|
||||
// I didn't write it down, but I assume the edges are directed
|
||||
// clockwise when looking towards the face normal, i.e. right hand rule.
|
||||
edges:Vec<SubmeshDirectedEdgeId>,
|
||||
//verts are redundant, use edge[i].verts[0]
|
||||
//verts:Vec<VertId>,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct EdgeRefs{
|
||||
faces:[SubmeshFaceId;2],//left, right
|
||||
verts:[SubmeshVertId;2],//start, end
|
||||
}
|
||||
#[derive(Debug)]
|
||||
struct VertRefs{
|
||||
faces:Vec<SubmeshFaceId>,
|
||||
// edges are always directed away from the vert
|
||||
edges:Vec<SubmeshDirectedEdgeId>,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct PhysicsMeshData{
|
||||
//this contains all real and virtual faces used in both the complete mesh and convex submeshes
|
||||
//faces are sorted such that all faces that belong to the complete mesh appear first, and then
|
||||
//all remaining faces are virtual to operate internal logic of the face crawler
|
||||
//and cannot be part of a physics collision
|
||||
//virtual faces are only used in convex submeshes.
|
||||
faces:Vec<Face>,//MeshFaceId indexes this list
|
||||
verts:Vec<Vert>,//MeshVertId indexes this list
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct PhysicsMeshTopology{
|
||||
//mapping of local ids to PhysicsMeshData ids
|
||||
faces:Vec<MeshFaceId>,//SubmeshFaceId indexes this list
|
||||
verts:Vec<MeshVertId>,//SubmeshVertId indexes this list
|
||||
//all ids here are local to this object
|
||||
face_topology:Vec<FaceRefs>,
|
||||
edge_topology:Vec<EdgeRefs>,
|
||||
vert_topology:Vec<VertRefs>,
|
||||
}
|
||||
#[derive(Clone,Copy,Hash,id::Id,Eq,PartialEq)]
|
||||
pub struct PhysicsMeshId(u32);
|
||||
impl Into<MeshId> for PhysicsMeshId{
|
||||
fn into(self)->MeshId{
|
||||
MeshId::new(self.0)
|
||||
}
|
||||
}
|
||||
impl From<MeshId> for PhysicsMeshId{
|
||||
fn from(value:MeshId)->Self{
|
||||
Self::new(value.get())
|
||||
}
|
||||
}
|
||||
#[derive(Debug,Default,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
|
||||
pub struct PhysicsSubmeshId(u32);
|
||||
pub struct PhysicsMesh{
|
||||
data:PhysicsMeshData,
|
||||
// The complete mesh is unused at this time.
|
||||
// complete_mesh:PhysicsMeshTopology,
|
||||
// Submeshes are guaranteed to be convex and may contain
|
||||
// "virtual" faces which are not part of the complete mesh.
|
||||
// Physics calculations should never resolve to hitting
|
||||
// a virtual face.
|
||||
submeshes:Vec<PhysicsMeshTopology>,
|
||||
}
|
||||
impl PhysicsMesh{
|
||||
pub fn unit_cube()->Self{
|
||||
//go go gadget debug print mesh
|
||||
let data=PhysicsMeshData{
|
||||
faces:vec![
|
||||
Face{normal:vec3::raw_xyz( 4294967296, 0, 0),dot:Planar64::raw(4294967296)},
|
||||
Face{normal:vec3::raw_xyz( 0, 4294967296, 0),dot:Planar64::raw(4294967296)},
|
||||
Face{normal:vec3::raw_xyz( 0, 0, 4294967296),dot:Planar64::raw(4294967296)},
|
||||
Face{normal:vec3::raw_xyz(-4294967296, 0, 0),dot:Planar64::raw(4294967296)},
|
||||
Face{normal:vec3::raw_xyz( 0,-4294967296, 0),dot:Planar64::raw(4294967296)},
|
||||
Face{normal:vec3::raw_xyz( 0, 0,-4294967296),dot:Planar64::raw(4294967296)}
|
||||
],
|
||||
verts:vec![
|
||||
Vert(vec3::raw_xyz( 4294967296,-4294967296,-4294967296)),
|
||||
Vert(vec3::raw_xyz( 4294967296, 4294967296,-4294967296)),
|
||||
Vert(vec3::raw_xyz( 4294967296, 4294967296, 4294967296)),
|
||||
Vert(vec3::raw_xyz( 4294967296,-4294967296, 4294967296)),
|
||||
Vert(vec3::raw_xyz(-4294967296, 4294967296,-4294967296)),
|
||||
Vert(vec3::raw_xyz(-4294967296, 4294967296, 4294967296)),
|
||||
Vert(vec3::raw_xyz(-4294967296,-4294967296, 4294967296)),
|
||||
Vert(vec3::raw_xyz(-4294967296,-4294967296,-4294967296))
|
||||
]
|
||||
};
|
||||
let mesh_topology=PhysicsMeshTopology{
|
||||
faces:(0..data.faces.len() as u32).map(MeshFaceId::new).collect(),
|
||||
verts:(0..data.verts.len() as u32).map(MeshVertId::new).collect(),
|
||||
face_topology:vec![
|
||||
FaceRefs{edges:vec![SubmeshDirectedEdgeId((9223372036854775808u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775809u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775810u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId(3)]},
|
||||
FaceRefs{edges:vec![SubmeshDirectedEdgeId((9223372036854775812u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775813u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId(6),SubmeshDirectedEdgeId(1)]},
|
||||
FaceRefs{edges:vec![SubmeshDirectedEdgeId(7),SubmeshDirectedEdgeId(2),SubmeshDirectedEdgeId((9223372036854775814u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775816u64-(1<<63)+(1<<31)) as u32)]},
|
||||
FaceRefs{edges:vec![SubmeshDirectedEdgeId(8),SubmeshDirectedEdgeId(5),SubmeshDirectedEdgeId((9223372036854775817u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId(10)]},
|
||||
FaceRefs{edges:vec![SubmeshDirectedEdgeId((9223372036854775815u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775818u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId(11),SubmeshDirectedEdgeId((9223372036854775811u64-(1<<63)+(1<<31)) as u32)]},
|
||||
FaceRefs{edges:vec![SubmeshDirectedEdgeId(4),SubmeshDirectedEdgeId(0),SubmeshDirectedEdgeId((9223372036854775819u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId(9)]}
|
||||
],
|
||||
edge_topology:vec![
|
||||
EdgeRefs{faces:[SubmeshFaceId(0),SubmeshFaceId(5)],verts:[SubmeshVertId(0),SubmeshVertId(1)]},
|
||||
EdgeRefs{faces:[SubmeshFaceId(0),SubmeshFaceId(1)],verts:[SubmeshVertId(1),SubmeshVertId(2)]},
|
||||
EdgeRefs{faces:[SubmeshFaceId(0),SubmeshFaceId(2)],verts:[SubmeshVertId(2),SubmeshVertId(3)]},
|
||||
EdgeRefs{faces:[SubmeshFaceId(4),SubmeshFaceId(0)],verts:[SubmeshVertId(0),SubmeshVertId(3)]},
|
||||
EdgeRefs{faces:[SubmeshFaceId(1),SubmeshFaceId(5)],verts:[SubmeshVertId(1),SubmeshVertId(4)]},
|
||||
EdgeRefs{faces:[SubmeshFaceId(1),SubmeshFaceId(3)],verts:[SubmeshVertId(4),SubmeshVertId(5)]},
|
||||
EdgeRefs{faces:[SubmeshFaceId(2),SubmeshFaceId(1)],verts:[SubmeshVertId(2),SubmeshVertId(5)]},
|
||||
EdgeRefs{faces:[SubmeshFaceId(4),SubmeshFaceId(2)],verts:[SubmeshVertId(3),SubmeshVertId(6)]},
|
||||
EdgeRefs{faces:[SubmeshFaceId(2),SubmeshFaceId(3)],verts:[SubmeshVertId(5),SubmeshVertId(6)]},
|
||||
EdgeRefs{faces:[SubmeshFaceId(3),SubmeshFaceId(5)],verts:[SubmeshVertId(4),SubmeshVertId(7)]},
|
||||
EdgeRefs{faces:[SubmeshFaceId(4),SubmeshFaceId(3)],verts:[SubmeshVertId(6),SubmeshVertId(7)]},
|
||||
EdgeRefs{faces:[SubmeshFaceId(5),SubmeshFaceId(4)],verts:[SubmeshVertId(0),SubmeshVertId(7)]}
|
||||
],
|
||||
vert_topology:vec![
|
||||
VertRefs{faces:vec![SubmeshFaceId(0),SubmeshFaceId(4),SubmeshFaceId(5)],edges:vec![SubmeshDirectedEdgeId((9223372036854775811u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775819u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775808u64-(1<<63)+(1<<31)) as u32)]},
|
||||
VertRefs{faces:vec![SubmeshFaceId(0),SubmeshFaceId(5),SubmeshFaceId(1)],edges:vec![SubmeshDirectedEdgeId((9223372036854775812u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId(0),SubmeshDirectedEdgeId((9223372036854775809u64-(1<<63)+(1<<31)) as u32)]},
|
||||
VertRefs{faces:vec![SubmeshFaceId(0),SubmeshFaceId(2),SubmeshFaceId(1)],edges:vec![SubmeshDirectedEdgeId(1),SubmeshDirectedEdgeId((9223372036854775810u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775814u64-(1<<63)+(1<<31)) as u32)]},
|
||||
VertRefs{faces:vec![SubmeshFaceId(0),SubmeshFaceId(2),SubmeshFaceId(4)],edges:vec![SubmeshDirectedEdgeId(2),SubmeshDirectedEdgeId(3),SubmeshDirectedEdgeId((9223372036854775815u64-(1<<63)+(1<<31)) as u32)]},
|
||||
VertRefs{faces:vec![SubmeshFaceId(3),SubmeshFaceId(5),SubmeshFaceId(1)],edges:vec![SubmeshDirectedEdgeId(4),SubmeshDirectedEdgeId((9223372036854775817u64-(1<<63)+(1<<31)) as u32),SubmeshDirectedEdgeId((9223372036854775813u64-(1<<63)+(1<<31)) as u32)]},
|
||||
VertRefs{faces:vec![SubmeshFaceId(2),SubmeshFaceId(3),SubmeshFaceId(1)],edges:vec![SubmeshDirectedEdgeId(5),SubmeshDirectedEdgeId(6),SubmeshDirectedEdgeId((9223372036854775816u64-(1<<63)+(1<<31)) as u32)]},
|
||||
VertRefs{faces:vec![SubmeshFaceId(2),SubmeshFaceId(3),SubmeshFaceId(4)],edges:vec![SubmeshDirectedEdgeId(7),SubmeshDirectedEdgeId(8),SubmeshDirectedEdgeId((9223372036854775818u64-(1<<63)+(1<<31)) as u32)]},
|
||||
VertRefs{faces:vec![SubmeshFaceId(4),SubmeshFaceId(3),SubmeshFaceId(5)],edges:vec![SubmeshDirectedEdgeId(10),SubmeshDirectedEdgeId(11),SubmeshDirectedEdgeId(9)]}
|
||||
]
|
||||
};
|
||||
Self{
|
||||
data,
|
||||
// complete_mesh:mesh_topology.clone(),
|
||||
submeshes:vec![mesh_topology],
|
||||
}
|
||||
}
|
||||
pub fn unit_cylinder()->Self{
|
||||
Self::unit_cube()
|
||||
}
|
||||
#[inline]
|
||||
pub fn complete_mesh(&self)->&PhysicsMeshTopology{
|
||||
// If there is exactly one submesh, then the complete mesh is identical to it.
|
||||
if self.submeshes.len()==1{
|
||||
self.submeshes.first().unwrap()
|
||||
}else{
|
||||
panic!("PhysicsMesh complete mesh is not known");
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn complete_mesh_view(&self)->PhysicsMeshView<'_>{
|
||||
PhysicsMeshView{
|
||||
data:&self.data,
|
||||
topology:self.complete_mesh(),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn submeshes(&self)->&[PhysicsMeshTopology]{
|
||||
&self.submeshes
|
||||
}
|
||||
#[inline]
|
||||
pub fn submesh_view(&self,submesh_id:PhysicsSubmeshId)->PhysicsMeshView<'_>{
|
||||
PhysicsMeshView{
|
||||
data:&self.data,
|
||||
topology:&self.submeshes()[submesh_id.get() as usize],
|
||||
}
|
||||
}
|
||||
pub fn submesh_views(&self)->impl Iterator<Item=PhysicsMeshView<'_>>{
|
||||
self.submeshes().iter().map(|topology|PhysicsMeshView{
|
||||
data:&self.data,
|
||||
topology,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
//mesh builder code
|
||||
#[derive(Default,Clone)]
|
||||
struct VertRefGuy{
|
||||
edges:HashSet<SubmeshDirectedEdgeId>,
|
||||
faces:HashSet<SubmeshFaceId>,
|
||||
}
|
||||
#[derive(Clone,Hash,Eq,PartialEq)]
|
||||
struct EdgeRefVerts([SubmeshVertId;2]);
|
||||
impl EdgeRefVerts{
|
||||
const fn new(v0:SubmeshVertId,v1:SubmeshVertId)->(Self,bool){
|
||||
(if v0.0<v1.0{
|
||||
Self([v0,v1])
|
||||
}else{
|
||||
Self([v1,v0])
|
||||
},v0.0<v1.0)
|
||||
}
|
||||
}
|
||||
struct EdgeRefFaces([SubmeshFaceId;2]);
|
||||
impl EdgeRefFaces{
|
||||
const fn new()->Self{
|
||||
Self([SubmeshFaceId(0);2])
|
||||
}
|
||||
fn push(&mut self,i:usize,face_id:SubmeshFaceId){
|
||||
self.0[i]=face_id;
|
||||
}
|
||||
}
|
||||
struct FaceRefEdges(Vec<SubmeshDirectedEdgeId>);
|
||||
#[derive(Default)]
|
||||
struct EdgePool{
|
||||
edge_guys:Vec<(EdgeRefVerts,EdgeRefFaces)>,
|
||||
edge_id_from_guy:HashMap<EdgeRefVerts,SubmeshEdgeId>,
|
||||
}
|
||||
impl EdgePool{
|
||||
fn push(&mut self,edge_ref_verts:EdgeRefVerts)->(&mut EdgeRefFaces,SubmeshEdgeId){
|
||||
let edge_id=*self.edge_id_from_guy.entry(edge_ref_verts.clone()).or_insert_with(||{
|
||||
let edge_id=SubmeshEdgeId::new(self.edge_guys.len() as u32);
|
||||
self.edge_guys.push((edge_ref_verts,EdgeRefFaces::new()));
|
||||
edge_id
|
||||
});
|
||||
(&mut self.edge_guys[edge_id.get() as usize].1,edge_id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum PhysicsMeshError{
|
||||
ZeroVertices,
|
||||
NoPhysicsGroups,
|
||||
}
|
||||
impl std::fmt::Display for PhysicsMeshError{
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f,"{self:?}")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for PhysicsMeshError{}
|
||||
|
||||
impl TryFrom<&model::Mesh> for PhysicsMesh{
|
||||
type Error=PhysicsMeshError;
|
||||
fn try_from(mesh:&model::Mesh)->Result<Self,PhysicsMeshError>{
|
||||
if mesh.unique_pos.len()==0{
|
||||
return Err(PhysicsMeshError::ZeroVertices);
|
||||
}
|
||||
// An empty physics mesh is a waste of resources
|
||||
if mesh.physics_groups.len()==0{
|
||||
return Err(PhysicsMeshError::NoPhysicsGroups);
|
||||
}
|
||||
let verts=mesh.unique_pos.iter().copied().map(Vert).collect();
|
||||
//TODO: fix submeshes
|
||||
//flat map mesh.physics_groups[$1].groups.polys()[$2] as face_id
|
||||
//lower face_id points to upper face_id
|
||||
//the same face is not allowed to be in multiple polygon groups
|
||||
// because SubmeshFaceId -> CompleteMeshFaceId -> SubmeshFaceId is ambiguous
|
||||
// when multiple SubmeshFaceId point to one MeshFaceId
|
||||
let mut faces=Vec::new();
|
||||
let mut face_id_from_face=HashMap::new();
|
||||
let mesh_topologies:Vec<PhysicsMeshTopology>=mesh.physics_groups.iter().map(|physics_group|{
|
||||
//construct submesh
|
||||
let mut submesh_faces=Vec::new();//these contain a map from submeshId->meshId
|
||||
let mut submesh_verts=Vec::new();
|
||||
let mut submesh_vert_id_from_mesh_vert_id=HashMap::<MeshVertId,SubmeshVertId>::new();
|
||||
//lazy closure
|
||||
let mut get_submesh_vert_id=|vert_id:MeshVertId|*submesh_vert_id_from_mesh_vert_id.entry(vert_id).or_insert_with(||{
|
||||
let submesh_vert_id=SubmeshVertId::new(submesh_verts.len() as u32);
|
||||
submesh_verts.push(vert_id);
|
||||
submesh_vert_id
|
||||
});
|
||||
let mut edge_pool=EdgePool::default();
|
||||
let mut vert_ref_guys=vec![VertRefGuy::default();mesh.unique_pos.len()];
|
||||
let mut face_ref_guys=Vec::new();
|
||||
for polygon_group_id in &physics_group.groups{
|
||||
let polygon_group=&mesh.polygon_groups[polygon_group_id.get() as usize];
|
||||
for poly_vertices in polygon_group.polys(){
|
||||
let submesh_face_id=SubmeshFaceId::new(submesh_faces.len() as u32);
|
||||
//one face per poly
|
||||
let mut normal=Vector3::new([Fixed::ZERO,Fixed::ZERO,Fixed::ZERO]);
|
||||
let len=poly_vertices.len();
|
||||
let face_edges=poly_vertices.into_iter().enumerate().map(|(i,vert_id)|{
|
||||
let vert0_id=MeshVertId::new(mesh.unique_vertices[vert_id.get() as usize].pos.get() as u32);
|
||||
let vert1_id=MeshVertId::new(mesh.unique_vertices[poly_vertices[(i+1)%len].get() as usize].pos.get() as u32);
|
||||
//index submesh verts
|
||||
let submesh_vert0_id=get_submesh_vert_id(vert0_id);
|
||||
let submesh_vert1_id=get_submesh_vert_id(vert1_id);
|
||||
//https://www.khronos.org/opengl/wiki/Calculating_a_Surface_Normal (Newell's Method)
|
||||
let v0=mesh.unique_pos[vert0_id.get() as usize];
|
||||
let v1=mesh.unique_pos[vert1_id.get() as usize];
|
||||
normal+=Vector3::new([
|
||||
(v0.y-v1.y)*(v0.z+v1.z),
|
||||
(v0.z-v1.z)*(v0.x+v1.x),
|
||||
(v0.x-v1.x)*(v0.y+v1.y),
|
||||
]);
|
||||
//get/create edge and push face into it
|
||||
let (edge_ref_verts,is_sorted)=EdgeRefVerts::new(submesh_vert0_id,submesh_vert1_id);
|
||||
let (edge_ref_faces,edge_id)=edge_pool.push(edge_ref_verts);
|
||||
//polygon vertices as assumed to be listed clockwise
|
||||
//populate the edge face on the left or right depending on how the edge vertices got sorted
|
||||
edge_ref_faces.push(!is_sorted as usize,submesh_face_id);
|
||||
//index edges & face into vertices
|
||||
{
|
||||
let vert_ref_guy=&mut vert_ref_guys[submesh_vert0_id.get() as usize];
|
||||
vert_ref_guy.edges.insert(edge_id.as_directed(is_sorted));
|
||||
vert_ref_guy.faces.insert(submesh_face_id);
|
||||
vert_ref_guys[submesh_vert1_id.get() as usize].edges.insert(edge_id.as_directed(!is_sorted));
|
||||
}
|
||||
//return directed_edge_id
|
||||
edge_id.as_directed(is_sorted)
|
||||
}).collect();
|
||||
let mut dot=Fixed::ZERO;
|
||||
// find the average dot
|
||||
for &v in poly_vertices{
|
||||
dot+=normal.dot(mesh.unique_pos[mesh.unique_vertices[v.get() as usize].pos.get() as usize]);
|
||||
}
|
||||
//assume face hash is stable, and there are no flush faces...
|
||||
let face=Face{
|
||||
normal:(normal/len as i64).divide().narrow_64().unwrap(),
|
||||
dot:(dot/(len*len) as i64).narrow_64().unwrap(),
|
||||
};
|
||||
let face_id=*face_id_from_face.entry(face).or_insert_with(||{
|
||||
let face_id=MeshFaceId::new(faces.len() as u32);
|
||||
faces.push(face);
|
||||
face_id
|
||||
});
|
||||
submesh_faces.push(face_id);
|
||||
face_ref_guys.push(FaceRefEdges(face_edges));
|
||||
}
|
||||
}
|
||||
PhysicsMeshTopology{
|
||||
faces:submesh_faces,
|
||||
verts:submesh_verts,
|
||||
face_topology:face_ref_guys.into_iter().map(|FaceRefEdges(edges)|{
|
||||
FaceRefs{edges}
|
||||
}).collect(),
|
||||
edge_topology:edge_pool.edge_guys.into_iter().map(|(EdgeRefVerts(verts),EdgeRefFaces(faces))|
|
||||
EdgeRefs{faces,verts}
|
||||
).collect(),
|
||||
vert_topology:vert_ref_guys.into_iter().map(|VertRefGuy{edges,faces}|
|
||||
VertRefs{
|
||||
edges:edges.into_iter().collect(),
|
||||
faces:faces.into_iter().collect(),
|
||||
}
|
||||
).collect(),
|
||||
}
|
||||
}).collect();
|
||||
Ok(Self{
|
||||
data:PhysicsMeshData{
|
||||
faces,
|
||||
verts,
|
||||
},
|
||||
// complete_mesh:None,
|
||||
submeshes:mesh_topologies,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug,Clone,Copy)]
|
||||
pub struct PhysicsMeshView<'a>{
|
||||
data:&'a PhysicsMeshData,
|
||||
topology:&'a PhysicsMeshTopology,
|
||||
}
|
||||
impl MeshQuery for PhysicsMeshView<'_>{
|
||||
type Position=Planar64Vec3;
|
||||
type Direction=Planar64Vec3;
|
||||
type Normal=Planar64Vec3;
|
||||
type Offset=Planar64;
|
||||
fn face_nd(&self,face_id:SubmeshFaceId)->(Planar64Vec3,Planar64){
|
||||
let face_idx=self.topology.faces[face_id.get() as usize].get() as usize;
|
||||
(self.data.faces[face_idx].normal,self.data.faces[face_idx].dot)
|
||||
}
|
||||
fn hint_point(&self)->Planar64Vec3{
|
||||
// invariant: meshes always encompass the origin
|
||||
vec3::zero()
|
||||
}
|
||||
fn farthest_vert(&self,dir:Planar64Vec3)->SubmeshVertId{
|
||||
//this happens to be well-defined. there are no virtual virtices
|
||||
SubmeshVertId::new(
|
||||
self.topology.verts.iter()
|
||||
.enumerate()
|
||||
.max_by_key(|&(_,&vert_id)|
|
||||
dir.dot(self.data.verts[vert_id.get() as usize].0)
|
||||
)
|
||||
//assume there is more than zero vertices.
|
||||
.unwrap().0 as u32
|
||||
)
|
||||
}
|
||||
//ideally I never calculate the vertex position, but I have to for the graphical meshes...
|
||||
fn vert(&self,vert_id:SubmeshVertId)->Planar64Vec3{
|
||||
let vert_idx=self.topology.verts[vert_id.get() as usize].get() as usize;
|
||||
self.data.verts[vert_idx].0
|
||||
}
|
||||
fn edge_n(&self,edge_id:Self::Edge)->Self::Direction{
|
||||
let &[v0,v1]=self.edge_verts(edge_id).as_ref();
|
||||
self.vert(v1)-self.vert(v0)
|
||||
}
|
||||
fn directed_edge_n(&self,directed_edge_id:Self::DirectedEdge)->Self::Direction{
|
||||
let &[v0,v1]=self.edge_verts(directed_edge_id.as_undirected()).as_ref();
|
||||
(self.vert(v1)-self.vert(v0))*((directed_edge_id.parity() as i64)*2-1)
|
||||
}
|
||||
}
|
||||
impl MeshTopology for PhysicsMeshView<'_>{
|
||||
type Face=SubmeshFaceId;
|
||||
type Edge=SubmeshEdgeId;
|
||||
type DirectedEdge=SubmeshDirectedEdgeId;
|
||||
type Vert=SubmeshVertId;
|
||||
fn for_each_vert_edge(&self,vert_id:Self::Vert,f:impl FnMut(Self::DirectedEdge)){
|
||||
self.topology.vert_topology[vert_id.get() as usize].edges.iter().copied().for_each(f);
|
||||
}
|
||||
fn for_each_vert_face(&self,vert_id:Self::Vert,f:impl FnMut(Self::Face)){
|
||||
self.topology.vert_topology[vert_id.get() as usize].faces.iter().copied().for_each(f);
|
||||
}
|
||||
fn edge_faces(&self,edge_id:Self::Edge)->impl AsRef<[Self::Face;2]>{
|
||||
AsRefHelper(self.topology.edge_topology[edge_id.get() as usize].faces)
|
||||
}
|
||||
fn edge_verts(&self,edge_id:Self::Edge)->impl AsRef<[Self::Vert;2]>{
|
||||
AsRefHelper(self.topology.edge_topology[edge_id.get() as usize].verts)
|
||||
}
|
||||
fn for_each_face_vert(&self,_face_id:Self::Face,_f:impl FnMut(Self::Vert)){
|
||||
unimplemented!()
|
||||
}
|
||||
fn for_each_face_edge(&self,face_id:Self::Face,f:impl FnMut(Self::DirectedEdge)){
|
||||
self.topology.face_topology[face_id.get() as usize].edges.iter().copied().for_each(f);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PhysicsMeshTransform{
|
||||
pub vertex:integer::Planar64Affine3,
|
||||
pub normal:integer::mat3::Matrix3<F128_64>,
|
||||
pub det:F192_96,
|
||||
}
|
||||
impl PhysicsMeshTransform{
|
||||
pub fn new(transform:integer::Planar64Affine3)->Self{
|
||||
Self{
|
||||
normal:transform.matrix3.adjugate().transpose(),
|
||||
det:transform.matrix3.det(),
|
||||
vertex:transform,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug,Clone,Copy)]
|
||||
pub struct TransformedMesh<'a>{
|
||||
view:PhysicsMeshView<'a>,
|
||||
transform:&'a PhysicsMeshTransform,
|
||||
}
|
||||
impl TransformedMesh<'_>{
|
||||
pub const fn new<'a>(
|
||||
view:PhysicsMeshView<'a>,
|
||||
transform:&'a PhysicsMeshTransform,
|
||||
)->TransformedMesh<'a>{
|
||||
TransformedMesh{
|
||||
view,
|
||||
transform,
|
||||
}
|
||||
}
|
||||
pub fn verts<'a>(&'a self)->impl Iterator<Item=Vector3<F128_64>>+'a{
|
||||
self.view.data.verts.iter().map(|&Vert(pos)|self.transform.vertex.transform_point3(pos))
|
||||
}
|
||||
}
|
||||
impl MeshQuery for TransformedMesh<'_>{
|
||||
type Direction=Planar64Vec3;
|
||||
type Position=Planar64Vec3;
|
||||
type Normal=Vector3<F192_96>;
|
||||
type Offset=F256_128;
|
||||
fn face_nd(&self,face_id:SubmeshFaceId)->(Self::Normal,Self::Offset){
|
||||
let (n,d)=self.view.face_nd(face_id);
|
||||
let transformed_n=self.transform.normal*n;
|
||||
let transformed_d=d*self.transform.det+transformed_n.dot(self.transform.vertex.translation);
|
||||
(transformed_n,transformed_d)
|
||||
}
|
||||
fn vert(&self,vert_id:SubmeshVertId)->Planar64Vec3{
|
||||
// wrap for speed
|
||||
self.transform.vertex.transform_point3(self.view.vert(vert_id)).wrap_64()
|
||||
}
|
||||
fn hint_point(&self)->Planar64Vec3{
|
||||
self.transform.vertex.translation
|
||||
}
|
||||
fn farthest_vert(&self,dir:Planar64Vec3)->SubmeshVertId{
|
||||
//this happens to be well-defined. there are no virtual virtices
|
||||
SubmeshVertId::new(
|
||||
self.view.topology.verts.iter()
|
||||
.enumerate()
|
||||
.max_by_key(|&(_,&vert_id)|
|
||||
dir.dot(self.transform.vertex.transform_point3(self.view.data.verts[vert_id.get() as usize].0))
|
||||
)
|
||||
//assume there is more than zero vertices.
|
||||
.unwrap().0 as u32
|
||||
)
|
||||
}
|
||||
fn edge_n(&self,edge_id:Self::Edge)->Self::Direction{
|
||||
let &[v0,v1]=self.edge_verts(edge_id).as_ref();
|
||||
self.vert(v1)-self.vert(v0)
|
||||
}
|
||||
fn directed_edge_n(&self,directed_edge_id:Self::DirectedEdge)->Self::Direction{
|
||||
let &[v0,v1]=self.edge_verts(directed_edge_id.as_undirected()).as_ref();
|
||||
(self.vert(v1)-self.vert(v0))*((directed_edge_id.parity() as i64)*2-1)
|
||||
}
|
||||
}
|
||||
impl MeshTopology for TransformedMesh<'_>{
|
||||
type Face=SubmeshFaceId;
|
||||
type Edge=SubmeshEdgeId;
|
||||
type DirectedEdge=SubmeshDirectedEdgeId;
|
||||
type Vert=SubmeshVertId;
|
||||
#[inline]
|
||||
fn for_each_vert_edge(&self,vert_id:Self::Vert,f:impl FnMut(Self::DirectedEdge)){
|
||||
self.view.for_each_vert_edge(vert_id,f)
|
||||
}
|
||||
#[inline]
|
||||
fn for_each_vert_face(&self,vert_id:Self::Vert,f:impl FnMut(Self::Face)){
|
||||
self.view.for_each_vert_face(vert_id,f)
|
||||
}
|
||||
#[inline]
|
||||
fn edge_faces(&self,edge_id:Self::Edge)->impl AsRef<[Self::Face;2]>{
|
||||
self.view.edge_faces(edge_id)
|
||||
}
|
||||
#[inline]
|
||||
fn edge_verts(&self,edge_id:Self::Edge)->impl AsRef<[Self::Vert;2]>{
|
||||
self.view.edge_verts(edge_id)
|
||||
}
|
||||
fn for_each_face_vert(&self,_face_id:Self::Face,_f:impl FnMut(Self::Vert)){
|
||||
unimplemented!()
|
||||
}
|
||||
#[inline]
|
||||
fn for_each_face_edge(&self,face_id:Self::Face,f:impl FnMut(Self::DirectedEdge)){
|
||||
self.view.for_each_face_edge(face_id,f)
|
||||
}
|
||||
}
|
||||
|
||||
pub type GigaTime=Ratio<F256_128,F256_128>;
|
||||
pub fn into_giga_time(time:Time,relative_to:Time)->GigaTime{
|
||||
let r=(time-relative_to).to_ratio();
|
||||
Ratio::new(r.num.widen_256(),r.den.widen_256())
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,7 @@
|
||||
use strafesnet_common::integer::{self,vec3::{self,Vector3},Fixed,Planar64,Planar64Vec3,Ratio};
|
||||
use strafesnet_common::integer::fixed_types::{F64_32,F128_64,F192_96,F256_128,F320_160};
|
||||
use strafesnet_common::integer::vec3::{self,Vector3};
|
||||
use strafesnet_common::integer::{Fixed,Planar64Vec3,Ratio};
|
||||
use strafesnet_common::ray::Ray;
|
||||
|
||||
// This algorithm is based on Lua code
|
||||
// written by Trey Reynolds in 2021
|
||||
@@ -10,27 +13,10 @@ use strafesnet_common::integer::{self,vec3::{self,Vector3},Fixed,Planar64,Planar
|
||||
type Conts<'a>=arrayvec::ArrayVec<&'a Contact,4>;
|
||||
|
||||
// hack to allow comparing ratios to zero
|
||||
const RATIO_ZERO:Ratio<Fixed<1,32>,Fixed<1,32>>=Ratio::new(Fixed::ZERO,Fixed::EPSILON);
|
||||
|
||||
struct Ray{
|
||||
origin:Planar64Vec3,
|
||||
direction:Planar64Vec3,
|
||||
}
|
||||
impl Ray{
|
||||
fn extrapolate<Num,Den,N1,T1>(&self,t:Ratio<Num,Den>)->Planar64Vec3
|
||||
where
|
||||
Num:Copy,
|
||||
Den:Copy,
|
||||
Num:core::ops::Mul<Planar64,Output=N1>,
|
||||
Planar64:core::ops::Mul<Den,Output=N1>,
|
||||
N1:integer::Divide<Den,Output=T1>,
|
||||
T1:integer::Fix<Planar64>,
|
||||
{
|
||||
self.origin+self.direction.map(|elem|(t*elem).divide().fix())
|
||||
}
|
||||
}
|
||||
const RATIO_ZERO:Ratio<F64_32,F64_32>=Ratio::new(Fixed::ZERO,Fixed::EPSILON);
|
||||
|
||||
/// Information about a contact restriction
|
||||
#[derive(Debug,PartialEq)]
|
||||
pub struct Contact{
|
||||
pub position:Planar64Vec3,
|
||||
pub velocity:Planar64Vec3,
|
||||
@@ -44,42 +30,39 @@ impl Contact{
|
||||
normal:self.normal,
|
||||
}
|
||||
}
|
||||
fn relative_dot(&self,direction:Planar64Vec3)->Fixed<2,64>{
|
||||
fn relative_dot(&self,direction:Planar64Vec3)->F128_64{
|
||||
(direction-self.velocity).dot(self.normal)
|
||||
}
|
||||
/// Calculate the time of intersection. (previously get_touch_time)
|
||||
fn solve(&self,ray:&Ray)->Ratio<Fixed<2,64>,Fixed<2,64>>{
|
||||
fn solve(&self,ray:&Ray)->Ratio<F128_64,F128_64>{
|
||||
(self.position-ray.origin).dot(self.normal)/(ray.direction-self.velocity).dot(self.normal)
|
||||
}
|
||||
}
|
||||
|
||||
//note that this is horrible with fixed point arithmetic
|
||||
fn solve1(c0:&Contact)->Option<Ratio<Vector3<Fixed<3,96>>,Fixed<2,64>>>{
|
||||
const EPSILON:Fixed<2,64>=Fixed::from_bits(Fixed::<2,64>::ONE.to_bits().shr(10));
|
||||
fn solve1(c0:&Contact)->Option<Ratio<Vector3<F192_96>,F128_64>>{
|
||||
let det=c0.normal.dot(c0.velocity);
|
||||
if det.abs()<EPSILON{
|
||||
if det.abs()==Fixed::ZERO{
|
||||
return None;
|
||||
}
|
||||
let d0=c0.normal.dot(c0.position);
|
||||
Some(c0.normal*d0/det)
|
||||
}
|
||||
fn solve2(c0:&Contact,c1:&Contact)->Option<Ratio<Vector3<Fixed<5,160>>,Fixed<4,128>>>{
|
||||
const EPSILON:Fixed<4,128>=Fixed::from_bits(Fixed::<4,128>::ONE.to_bits().shr(10));
|
||||
fn solve2(c0:&Contact,c1:&Contact)->Option<Ratio<Vector3<F320_160>,F256_128>>{
|
||||
let u0_u1=c0.velocity.cross(c1.velocity);
|
||||
let n0_n1=c0.normal.cross(c1.normal);
|
||||
let det=u0_u1.dot(n0_n1);
|
||||
if det.abs()<EPSILON{
|
||||
if det.abs()==Fixed::ZERO{
|
||||
return None;
|
||||
}
|
||||
let d0=c0.normal.dot(c0.position);
|
||||
let d1=c1.normal.dot(c1.position);
|
||||
Some((c1.normal.cross(u0_u1)*d0+u0_u1.cross(c0.normal)*d1)/det)
|
||||
}
|
||||
fn solve3(c0:&Contact,c1:&Contact,c2:&Contact)->Option<Ratio<Vector3<Fixed<4,128>>,Fixed<3,96>>>{
|
||||
const EPSILON:Fixed<3,96>=Fixed::from_bits(Fixed::<3,96>::ONE.to_bits().shr(10));
|
||||
fn solve3(c0:&Contact,c1:&Contact,c2:&Contact)->Option<Ratio<Vector3<F256_128>,F192_96>>{
|
||||
let n0_n1=c0.normal.cross(c1.normal);
|
||||
let det=c2.normal.dot(n0_n1);
|
||||
if det.abs()<EPSILON{
|
||||
if det.abs()==Fixed::ZERO{
|
||||
return None;
|
||||
}
|
||||
let d0=c0.normal.dot(c0.position);
|
||||
@@ -88,7 +71,7 @@ fn solve3(c0:&Contact,c1:&Contact,c2:&Contact)->Option<Ratio<Vector3<Fixed<4,128
|
||||
Some((c1.normal.cross(c2.normal)*d0+c2.normal.cross(c0.normal)*d1+c0.normal.cross(c1.normal)*d2)/det)
|
||||
}
|
||||
|
||||
fn decompose1(point:Planar64Vec3,u0:Planar64Vec3)->Option<[Ratio<Fixed<2,64>,Fixed<2,64>>;1]>{
|
||||
fn decompose1(point:Planar64Vec3,u0:Planar64Vec3)->Option<[Ratio<F128_64,F128_64>;1]>{
|
||||
let det=u0.dot(u0);
|
||||
if det==Fixed::ZERO{
|
||||
return None;
|
||||
@@ -96,7 +79,7 @@ fn decompose1(point:Planar64Vec3,u0:Planar64Vec3)->Option<[Ratio<Fixed<2,64>,Fix
|
||||
let s0=u0.dot(point)/det;
|
||||
Some([s0])
|
||||
}
|
||||
fn decompose2(point:Planar64Vec3,u0:Planar64Vec3,u1:Planar64Vec3)->Option<[Ratio<Fixed<4,128>,Fixed<4,128>>;2]>{
|
||||
fn decompose2(point:Planar64Vec3,u0:Planar64Vec3,u1:Planar64Vec3)->Option<[Ratio<F256_128,F256_128>;2]>{
|
||||
let u0_u1=u0.cross(u1);
|
||||
let det=u0_u1.dot(u0_u1);
|
||||
if det==Fixed::ZERO{
|
||||
@@ -106,7 +89,7 @@ fn decompose2(point:Planar64Vec3,u0:Planar64Vec3,u1:Planar64Vec3)->Option<[Ratio
|
||||
let s1=u0_u1.dot(u0.cross(point))/det;
|
||||
Some([s0,s1])
|
||||
}
|
||||
fn decompose3(point:Planar64Vec3,u0:Planar64Vec3,u1:Planar64Vec3,u2:Planar64Vec3)->Option<[Ratio<Fixed<3,96>,Fixed<3,96>>;3]>{
|
||||
fn decompose3(point:Planar64Vec3,u0:Planar64Vec3,u1:Planar64Vec3,u2:Planar64Vec3)->Option<[Ratio<F192_96,F192_96>;3]>{
|
||||
let det=u0.cross(u1).dot(u2);
|
||||
if det==Fixed::ZERO{
|
||||
return None;
|
||||
@@ -165,21 +148,22 @@ fn is_space_enclosed_4(
|
||||
}
|
||||
|
||||
const fn get_push_ray_0(point:Planar64Vec3)->Ray{
|
||||
Ray{origin:point,direction:vec3::ZERO}
|
||||
Ray{origin:point,direction:vec3::zero()}
|
||||
}
|
||||
fn get_push_ray_1(point:Planar64Vec3,c0:&Contact)->Option<Ray>{
|
||||
let direction=solve1(c0)?.divide().fix_1();
|
||||
//wrap for speed
|
||||
let direction=solve1(c0)?.divide().wrap_64();
|
||||
let [s0]=decompose1(direction,c0.velocity)?;
|
||||
if s0.lt_ratio(RATIO_ZERO){
|
||||
return None;
|
||||
}
|
||||
let origin=point+solve1(
|
||||
&c0.relative_to(point),
|
||||
)?.divide().fix_1();
|
||||
)?.divide().wrap_64();
|
||||
Some(Ray{origin,direction})
|
||||
}
|
||||
fn get_push_ray_2(point:Planar64Vec3,c0:&Contact,c1:&Contact)->Option<Ray>{
|
||||
let direction=solve2(c0,c1)?.divide().fix_1();
|
||||
let direction=solve2(c0,c1)?.divide().wrap_64();
|
||||
let [s0,s1]=decompose2(direction,c0.velocity,c1.velocity)?;
|
||||
if s0.lt_ratio(RATIO_ZERO)||s1.lt_ratio(RATIO_ZERO){
|
||||
return None;
|
||||
@@ -187,11 +171,11 @@ fn get_push_ray_2(point:Planar64Vec3,c0:&Contact,c1:&Contact)->Option<Ray>{
|
||||
let origin=point+solve2(
|
||||
&c0.relative_to(point),
|
||||
&c1.relative_to(point),
|
||||
)?.divide().fix_1();
|
||||
)?.divide().wrap_64();
|
||||
Some(Ray{origin,direction})
|
||||
}
|
||||
fn get_push_ray_3(point:Planar64Vec3,c0:&Contact,c1:&Contact,c2:&Contact)->Option<Ray>{
|
||||
let direction=solve3(c0,c1,c2)?.divide().fix_1();
|
||||
let direction=solve3(c0,c1,c2)?.divide().wrap_64();
|
||||
let [s0,s1,s2]=decompose3(direction,c0.velocity,c1.velocity,c2.velocity)?;
|
||||
if s0.lt_ratio(RATIO_ZERO)||s1.lt_ratio(RATIO_ZERO)||s2.lt_ratio(RATIO_ZERO){
|
||||
return None;
|
||||
@@ -200,14 +184,14 @@ fn get_push_ray_3(point:Planar64Vec3,c0:&Contact,c1:&Contact,c2:&Contact)->Optio
|
||||
&c0.relative_to(point),
|
||||
&c1.relative_to(point),
|
||||
&c2.relative_to(point),
|
||||
)?.divide().fix_1();
|
||||
)?.divide().wrap_64();
|
||||
Some(Ray{origin,direction})
|
||||
}
|
||||
|
||||
const fn get_best_push_ray_and_conts_0<'a>(point:Planar64Vec3)->(Ray,Conts<'a>){
|
||||
(get_push_ray_0(point),Conts::new_const())
|
||||
}
|
||||
fn get_best_push_ray_and_conts_1(point:Planar64Vec3,c0:&Contact)->Option<(Ray,Conts)>{
|
||||
fn get_best_push_ray_and_conts_1(point:Planar64Vec3,c0:&Contact)->Option<(Ray,Conts<'_>)>{
|
||||
get_push_ray_1(point,c0)
|
||||
.map(|ray|(ray,Conts::from_iter([c0])))
|
||||
}
|
||||
@@ -289,26 +273,26 @@ fn get_best_push_ray_and_conts<'a>(
|
||||
}
|
||||
}
|
||||
|
||||
fn get_first_touch<'a>(contacts:&'a Vec<Contact>,ray:&Ray,conts:&Conts)->Option<(Ratio<Fixed<2,64>,Fixed<2,64>>,&'a Contact)>{
|
||||
fn get_first_touch<'a>(contacts:&'a [Contact],ray:&Ray,conts:&Conts)->Option<(Ratio<F128_64,F128_64>,&'a Contact)>{
|
||||
contacts.iter()
|
||||
.filter(|&contact|
|
||||
!conts.iter().any(|&c|std::ptr::eq(c,contact))
|
||||
!conts.iter().any(|&c|core::ptr::eq(c,contact))
|
||||
&&contact.relative_dot(ray.direction).is_negative()
|
||||
)
|
||||
.map(|contact|(contact.solve(ray),contact))
|
||||
.min_by_key(|&(t,_)|t)
|
||||
}
|
||||
|
||||
pub fn push_solve(contacts:&Vec<Contact>,point:Planar64Vec3)->Planar64Vec3{
|
||||
pub fn push_solve(contacts:&[Contact],point:Planar64Vec3)->(Planar64Vec3,Conts<'_>){
|
||||
let (mut ray,mut conts)=get_best_push_ray_and_conts_0(point);
|
||||
loop{
|
||||
let (next_t,next_cont)=match get_first_touch(contacts,&ray,&conts){
|
||||
Some((t,cont))=>(t,cont),
|
||||
None=>return ray.origin,
|
||||
None=>return (ray.origin,conts),
|
||||
};
|
||||
|
||||
if RATIO_ZERO.le_ratio(next_t){
|
||||
return ray.origin;
|
||||
return (ray.origin,conts);
|
||||
}
|
||||
|
||||
//push_front
|
||||
@@ -324,7 +308,7 @@ pub fn push_solve(contacts:&Vec<Contact>,point:Planar64Vec3)->Planar64Vec3{
|
||||
let meet_point=ray.extrapolate(next_t);
|
||||
match get_best_push_ray_and_conts(meet_point,conts.as_slice()){
|
||||
Some((new_ray,new_conts))=>(ray,conts)=(new_ray,new_conts),
|
||||
None=>return meet_point,
|
||||
None=>return (meet_point,conts),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -336,14 +320,13 @@ mod tests{
|
||||
fn test_push_solve(){
|
||||
let contacts=vec![
|
||||
Contact{
|
||||
position:vec3::ZERO,
|
||||
position:vec3::zero(),
|
||||
velocity:vec3::Y,
|
||||
normal:vec3::Y,
|
||||
}
|
||||
];
|
||||
assert_eq!(
|
||||
vec3::ZERO,
|
||||
push_solve(&contacts,vec3::NEG_Y)
|
||||
);
|
||||
let (point,conts)=push_solve(&contacts,vec3::NEG_Y);
|
||||
assert_eq!(point,vec3::zero());
|
||||
assert_eq!(conts.as_slice(),[&contacts[0]].as_slice());
|
||||
}
|
||||
}
|
||||
15
engine/session/Cargo.toml
Normal file
15
engine/session/Cargo.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "strafesnet_session"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
glam.workspace = true
|
||||
replace_with = "0.1.7"
|
||||
strafesnet_common.workspace = true
|
||||
strafesnet_physics.workspace = true
|
||||
strafesnet_settings.workspace = true
|
||||
strafesnet_snf.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
8
engine/session/LICENSE
Normal file
8
engine/session/LICENSE
Normal file
@@ -0,0 +1,8 @@
|
||||
/*******************************************************
|
||||
* Copyright (C) 2023-2024 Rhys Lloyd <krakow20@gmail.com>
|
||||
*
|
||||
* This file is part of the StrafesNET bhop/surf client.
|
||||
*
|
||||
* StrafesNET can not be copied and/or distributed
|
||||
* without the express permission of Rhys Lloyd
|
||||
*******************************************************/
|
||||
2
engine/session/src/lib.rs
Normal file
2
engine/session/src/lib.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
mod mouse_interpolator;
|
||||
pub mod session;
|
||||
@@ -5,13 +5,13 @@ use strafesnet_common::physics::{
|
||||
TimeInner as PhysicsTimeInner,
|
||||
Time as PhysicsTime,
|
||||
};
|
||||
use strafesnet_common::session::{Time as SessionTime,TimeInner as SessionTimeInner};
|
||||
use strafesnet_common::session::Time as SessionTime;
|
||||
use strafesnet_common::instruction::{InstructionConsumer,InstructionEmitter,TimedInstruction};
|
||||
|
||||
type TimedSelfInstruction=TimedInstruction<Instruction,PhysicsTimeInner>;
|
||||
type DoubleTimedSelfInstruction=TimedInstruction<TimedSelfInstruction,SessionTimeInner>;
|
||||
type TimedSelfInstruction=TimedInstruction<Instruction,PhysicsTime>;
|
||||
type DoubleTimedSelfInstruction=TimedInstruction<TimedSelfInstruction,SessionTime>;
|
||||
|
||||
type TimedPhysicsInstruction=TimedInstruction<PhysicsInstruction,PhysicsTimeInner>;
|
||||
type TimedPhysicsInstruction=TimedInstruction<PhysicsInstruction,PhysicsTime>;
|
||||
|
||||
const MOUSE_TIMEOUT:SessionTime=SessionTime::from_millis(10);
|
||||
|
||||
@@ -89,14 +89,14 @@ pub struct MouseInterpolator{
|
||||
// Maybe MouseInterpolator manipulation is better expressed using impls
|
||||
// and called from Instruction trait impls in session
|
||||
impl InstructionConsumer<TimedSelfInstruction> for MouseInterpolator{
|
||||
type TimeInner=SessionTimeInner;
|
||||
type Time=SessionTime;
|
||||
fn process_instruction(&mut self,ins:DoubleTimedSelfInstruction){
|
||||
self.push_unbuffered_input(ins.time,ins.instruction.time,ins.instruction.instruction.into())
|
||||
}
|
||||
}
|
||||
impl InstructionEmitter<StepInstruction> for MouseInterpolator{
|
||||
type TimeInner=SessionTimeInner;
|
||||
fn next_instruction(&self,time_limit:SessionTime)->Option<TimedInstruction<StepInstruction,Self::TimeInner>>{
|
||||
type Time=SessionTime;
|
||||
fn next_instruction(&self,time_limit:SessionTime)->Option<TimedInstruction<StepInstruction,Self::Time>>{
|
||||
self.buffered_instruction_with_timeout(time_limit)
|
||||
}
|
||||
}
|
||||
@@ -108,7 +108,7 @@ impl MouseInterpolator{
|
||||
output:std::collections::VecDeque::new(),
|
||||
}
|
||||
}
|
||||
fn push_mouse_and_flush_buffer(&mut self,ins:TimedInstruction<MouseInstruction,PhysicsTimeInner>){
|
||||
fn push_mouse_and_flush_buffer(&mut self,ins:TimedInstruction<MouseInstruction,PhysicsTime>){
|
||||
self.buffer.push_front(TimedInstruction{
|
||||
time:ins.time,
|
||||
instruction:BufferedInstruction::Mouse(ins.instruction).into(),
|
||||
@@ -219,7 +219,7 @@ impl MouseInterpolator{
|
||||
}
|
||||
}
|
||||
}
|
||||
fn buffered_instruction_with_timeout(&self,time_limit:SessionTime)->Option<TimedInstruction<StepInstruction,SessionTimeInner>>{
|
||||
fn buffered_instruction_with_timeout(&self,time_limit:SessionTime)->Option<TimedInstruction<StepInstruction,SessionTime>>{
|
||||
match self.get_mouse_timedout_at(time_limit){
|
||||
Some(timeout)=>Some(TimedInstruction{
|
||||
time:timeout,
|
||||
@@ -232,7 +232,7 @@ impl MouseInterpolator{
|
||||
}),
|
||||
}
|
||||
}
|
||||
pub fn pop_buffered_instruction(&mut self,ins:TimedInstruction<StepInstruction,PhysicsTimeInner>)->Option<TimedPhysicsInstruction>{
|
||||
pub fn pop_buffered_instruction(&mut self,ins:TimedInstruction<StepInstruction,PhysicsTime>)->Option<TimedPhysicsInstruction>{
|
||||
match ins.instruction{
|
||||
StepInstruction::Pop=>(),
|
||||
StepInstruction::Timeout=>self.timeout_mouse(ins.time),
|
||||
@@ -244,6 +244,7 @@ impl MouseInterpolator{
|
||||
#[cfg(test)]
|
||||
mod test{
|
||||
use super::*;
|
||||
use strafesnet_common::session::TimeInner as SessionTimeInner;
|
||||
#[test]
|
||||
fn test(){
|
||||
let mut interpolator=MouseInterpolator::new();
|
||||
@@ -12,10 +12,11 @@ use strafesnet_common::physics::{
|
||||
};
|
||||
use strafesnet_common::timer::{Scaled,Timer};
|
||||
use strafesnet_common::session::{TimeInner as SessionTimeInner,Time as SessionTime};
|
||||
use strafesnet_settings::directories::Directories;
|
||||
|
||||
use crate::mouse_interpolator::{MouseInterpolator,StepInstruction,Instruction as MouseInterpolatorInstruction};
|
||||
use crate::physics::{PhysicsContext,PhysicsData};
|
||||
use crate::settings::UserSettings;
|
||||
use strafesnet_physics::physics::{self,PhysicsContext,PhysicsData};
|
||||
use strafesnet_settings::settings::UserSettings;
|
||||
|
||||
pub enum Instruction<'a>{
|
||||
Input(SessionInputInstruction),
|
||||
@@ -30,7 +31,7 @@ pub enum SessionInputInstruction{
|
||||
Mouse(glam::IVec2),
|
||||
SetControl(strafesnet_common::physics::SetControlInstruction),
|
||||
Mode(ImplicitModeInstruction),
|
||||
Misc(strafesnet_common::physics::MiscInstruction),
|
||||
Misc(MiscInstruction),
|
||||
}
|
||||
/// Implicit mode instruction are fed separately to session.
|
||||
/// Session generates the explicit mode instructions interlaced with a SetSensitivity instruction
|
||||
@@ -51,34 +52,41 @@ pub enum SessionControlInstruction{
|
||||
pub enum SessionPlaybackInstruction{
|
||||
SkipForward,
|
||||
SkipBack,
|
||||
TogglePaused,
|
||||
DecreaseTimescale,
|
||||
IncreaseTimescale,
|
||||
}
|
||||
|
||||
pub struct FrameState{
|
||||
pub body:crate::physics::Body,
|
||||
pub camera:crate::physics::PhysicsCamera,
|
||||
pub trajectory:physics::Trajectory,
|
||||
pub camera:physics::PhysicsCamera,
|
||||
pub time:PhysicsTime,
|
||||
}
|
||||
impl FrameState{
|
||||
pub fn pos(&self)->glam::Vec3{
|
||||
self.trajectory.extrapolated_position(self.time).map(Into::<f32>::into).to_array().into()
|
||||
}
|
||||
pub fn angles(&self)->glam::Vec2{
|
||||
self.camera.simulate_move_angles(glam::IVec2::ZERO)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Simulation{
|
||||
timer:Timer<Scaled<SessionTimeInner,PhysicsTimeInner>>,
|
||||
physics:crate::physics::PhysicsState,
|
||||
physics:physics::PhysicsState,
|
||||
}
|
||||
impl Simulation{
|
||||
pub const fn new(
|
||||
timer:Timer<Scaled<SessionTimeInner,PhysicsTimeInner>>,
|
||||
physics:crate::physics::PhysicsState,
|
||||
physics:physics::PhysicsState,
|
||||
)->Self{
|
||||
Self{
|
||||
timer,
|
||||
physics,
|
||||
}
|
||||
}
|
||||
pub fn get_frame_state(&self,time:SessionTime)->FrameState{
|
||||
pub fn get_frame_state(&self,time:SessionTime,data:&PhysicsData)->FrameState{
|
||||
FrameState{
|
||||
body:self.physics.camera_body(),
|
||||
trajectory:self.physics.camera_trajectory(data),
|
||||
camera:self.physics.camera(),
|
||||
time:self.timer.time(time),
|
||||
}
|
||||
@@ -87,11 +95,11 @@ impl Simulation{
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Recording{
|
||||
instructions:Vec<TimedInstruction<PhysicsInputInstruction,PhysicsTimeInner>>,
|
||||
instructions:Vec<TimedInstruction<PhysicsInputInstruction,PhysicsTime>>,
|
||||
}
|
||||
impl Recording{
|
||||
fn new(
|
||||
instructions:Vec<TimedInstruction<PhysicsInputInstruction,PhysicsTimeInner>>,
|
||||
pub fn new(
|
||||
instructions:Vec<TimedInstruction<PhysicsInputInstruction,PhysicsTime>>,
|
||||
)->Self{
|
||||
Self{instructions}
|
||||
}
|
||||
@@ -149,11 +157,12 @@ enum ViewState{
|
||||
}
|
||||
|
||||
pub struct Session{
|
||||
directories:Directories,
|
||||
user_settings:UserSettings,
|
||||
mouse_interpolator:crate::mouse_interpolator::MouseInterpolator,
|
||||
mouse_interpolator:MouseInterpolator,
|
||||
view_state:ViewState,
|
||||
//gui:GuiState
|
||||
geometry_shared:crate::physics::PhysicsData,
|
||||
geometry_shared:PhysicsData,
|
||||
simulation:Simulation,
|
||||
// below fields not included in lite session
|
||||
recording:Recording,
|
||||
@@ -163,12 +172,14 @@ pub struct Session{
|
||||
impl Session{
|
||||
pub fn new(
|
||||
user_settings:UserSettings,
|
||||
directories:Directories,
|
||||
simulation:Simulation,
|
||||
)->Self{
|
||||
Self{
|
||||
user_settings,
|
||||
directories,
|
||||
mouse_interpolator:MouseInterpolator::new(),
|
||||
geometry_shared:Default::default(),
|
||||
geometry_shared:PhysicsData::empty(),
|
||||
simulation,
|
||||
view_state:ViewState::Play,
|
||||
recording:Default::default(),
|
||||
@@ -180,13 +191,13 @@ impl Session{
|
||||
}
|
||||
fn change_map(&mut self,map:&strafesnet_common::map::CompleteMap){
|
||||
self.simulation.physics.clear();
|
||||
self.geometry_shared.generate_models(map);
|
||||
self.geometry_shared=PhysicsData::new(map);
|
||||
}
|
||||
pub fn get_frame_state(&self,time:SessionTime)->Option<FrameState>{
|
||||
match &self.view_state{
|
||||
ViewState::Play=>Some(self.simulation.get_frame_state(time)),
|
||||
ViewState::Play=>Some(self.simulation.get_frame_state(time,&self.geometry_shared)),
|
||||
ViewState::Replay(bot_id)=>self.replays.get(bot_id).map(|replay|
|
||||
replay.simulation.get_frame_state(time)
|
||||
replay.simulation.get_frame_state(time,&self.geometry_shared)
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -203,8 +214,8 @@ impl Session{
|
||||
// Session emits DoStep
|
||||
|
||||
impl InstructionConsumer<Instruction<'_>> for Session{
|
||||
type TimeInner=SessionTimeInner;
|
||||
fn process_instruction(&mut self,ins:TimedInstruction<Instruction,Self::TimeInner>){
|
||||
type Time=SessionTime;
|
||||
fn process_instruction(&mut self,ins:TimedInstruction<Instruction,Self::Time>){
|
||||
// repetitive procedure macro
|
||||
macro_rules! run_mouse_interpolator_instruction{
|
||||
($instruction:expr)=>{
|
||||
@@ -235,12 +246,16 @@ impl InstructionConsumer<Instruction<'_>> for Session{
|
||||
run_mouse_interpolator_instruction!(MouseInterpolatorInstruction::Mode(ModeInstruction::Reset));
|
||||
run_mouse_interpolator_instruction!(MouseInterpolatorInstruction::Misc(MiscInstruction::SetSensitivity(self.user_settings().calculate_sensitivity())));
|
||||
run_mouse_interpolator_instruction!(MouseInterpolatorInstruction::Mode(ModeInstruction::Restart(mode_id)));
|
||||
// TODO: think about this harder. This works around a bug where you fall infinitely when you reset.
|
||||
self.simulation.timer.set_time(ins.time,PhysicsTime::ZERO);
|
||||
},
|
||||
Instruction::Input(SessionInputInstruction::Mode(ImplicitModeInstruction::ResetAndSpawn(mode_id,spawn_id)))=>{
|
||||
self.clear_recording();
|
||||
run_mouse_interpolator_instruction!(MouseInterpolatorInstruction::Mode(ModeInstruction::Reset));
|
||||
run_mouse_interpolator_instruction!(MouseInterpolatorInstruction::Misc(MiscInstruction::SetSensitivity(self.user_settings().calculate_sensitivity())));
|
||||
run_mouse_interpolator_instruction!(MouseInterpolatorInstruction::Mode(ModeInstruction::Spawn(mode_id,spawn_id)));
|
||||
// TODO: think about this harder. This works around a bug where you fall infinitely when you reset.
|
||||
self.simulation.timer.set_time(ins.time,PhysicsTime::ZERO);
|
||||
},
|
||||
Instruction::Input(SessionInputInstruction::Misc(misc_instruction))=>{
|
||||
run_mouse_interpolator_instruction!(MouseInterpolatorInstruction::Misc(misc_instruction));
|
||||
@@ -249,7 +264,14 @@ impl InstructionConsumer<Instruction<'_>> for Session{
|
||||
// don't flush the buffered instructions in the mouse interpolator
|
||||
// until the mouse is confirmed to be not moving at a later time
|
||||
// what if they pause for 5ms lmao
|
||||
_=self.simulation.timer.set_paused(ins.time,paused);
|
||||
match &self.view_state{
|
||||
ViewState::Play=>{
|
||||
_=self.simulation.timer.set_paused(ins.time,paused);
|
||||
},
|
||||
ViewState::Replay(bot_id)=>if let Some(replay)=self.replays.get_mut(bot_id){
|
||||
_=replay.simulation.timer.set_paused(ins.time,paused);
|
||||
},
|
||||
}
|
||||
},
|
||||
Instruction::Control(SessionControlInstruction::CopyRecordingIntoReplayAndSpectate)=> if let ViewState::Play=self.view_state{
|
||||
// Bind: B
|
||||
@@ -292,11 +314,22 @@ impl InstructionConsumer<Instruction<'_>> for Session{
|
||||
Instruction::Control(SessionControlInstruction::SaveReplay)=>{
|
||||
// Bind: N
|
||||
let view_state=core::mem::replace(&mut self.view_state,ViewState::Play);
|
||||
let file=std::fs::File::create(format!("{}.snfb",ins.time)).unwrap();
|
||||
match view_state{
|
||||
ViewState::Play=>(),
|
||||
ViewState::Replay(bot_id)=>if let Some(replay)=self.replays.remove(&bot_id){
|
||||
strafesnet_snf::bot::write_bot(std::io::BufWriter::new(file),replay.recording.instructions).unwrap();
|
||||
let mut replays_path=self.directories.replays.clone();
|
||||
let file_name=format!("{}.snfb",ins.time);
|
||||
std::thread::spawn(move ||{
|
||||
std::fs::create_dir_all(replays_path.as_path()).unwrap();
|
||||
replays_path.push(file_name);
|
||||
let file=std::fs::File::create(replays_path).unwrap();
|
||||
strafesnet_snf::bot::write_bot(
|
||||
std::io::BufWriter::new(file),
|
||||
strafesnet_physics::VERSION.get(),
|
||||
replay.recording.instructions
|
||||
).unwrap();
|
||||
println!("Finished writing bot file!");
|
||||
});
|
||||
},
|
||||
}
|
||||
_=self.simulation.timer.set_paused(ins.time,false);
|
||||
@@ -359,14 +392,6 @@ impl InstructionConsumer<Instruction<'_>> for Session{
|
||||
},
|
||||
}
|
||||
},
|
||||
Instruction::Playback(SessionPlaybackInstruction::TogglePaused)=>{
|
||||
match &self.view_state{
|
||||
ViewState::Play=>(),
|
||||
ViewState::Replay(bot_id)=>if let Some(replay)=self.replays.get_mut(bot_id){
|
||||
_=replay.simulation.timer.set_paused(ins.time,!replay.simulation.timer.is_paused());
|
||||
},
|
||||
}
|
||||
}
|
||||
Instruction::ChangeMap(complete_map)=>{
|
||||
self.clear_recording();
|
||||
self.change_map(complete_map);
|
||||
@@ -410,8 +435,8 @@ impl InstructionConsumer<Instruction<'_>> for Session{
|
||||
}
|
||||
}
|
||||
impl InstructionConsumer<StepInstruction> for Session{
|
||||
type TimeInner=SessionTimeInner;
|
||||
fn process_instruction(&mut self,ins:TimedInstruction<StepInstruction,Self::TimeInner>){
|
||||
type Time=SessionTime;
|
||||
fn process_instruction(&mut self,ins:TimedInstruction<StepInstruction,Self::Time>){
|
||||
let time=self.simulation.timer.time(ins.time);
|
||||
if let Some(instruction)=self.mouse_interpolator.pop_buffered_instruction(ins.set_time(time)){
|
||||
//record
|
||||
@@ -421,8 +446,8 @@ impl InstructionConsumer<StepInstruction> for Session{
|
||||
}
|
||||
}
|
||||
impl InstructionEmitter<StepInstruction> for Session{
|
||||
type TimeInner=SessionTimeInner;
|
||||
fn next_instruction(&self,time_limit:SessionTime)->Option<TimedInstruction<StepInstruction,Self::TimeInner>>{
|
||||
type Time=SessionTime;
|
||||
fn next_instruction(&self,time_limit:SessionTime)->Option<TimedInstruction<StepInstruction,Self::Time>>{
|
||||
self.mouse_interpolator.next_instruction(time_limit)
|
||||
}
|
||||
}
|
||||
13
engine/settings/Cargo.toml
Normal file
13
engine/settings/Cargo.toml
Normal file
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "strafesnet_settings"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
configparser = "3.0.2"
|
||||
directories = "6.0.0"
|
||||
glam.workspace = true
|
||||
strafesnet_common.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
8
engine/settings/LICENSE
Normal file
8
engine/settings/LICENSE
Normal file
@@ -0,0 +1,8 @@
|
||||
/*******************************************************
|
||||
* Copyright (C) 2023-2024 Rhys Lloyd <krakow20@gmail.com>
|
||||
*
|
||||
* This file is part of the StrafesNET bhop/surf client.
|
||||
*
|
||||
* StrafesNET can not be copied and/or distributed
|
||||
* without the express permission of Rhys Lloyd
|
||||
*******************************************************/
|
||||
32
engine/settings/src/directories.rs
Normal file
32
engine/settings/src/directories.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::settings::{UserSettings,load_user_settings};
|
||||
|
||||
pub struct Directories{
|
||||
pub settings:PathBuf,
|
||||
pub maps:PathBuf,
|
||||
pub replays:PathBuf,
|
||||
}
|
||||
impl Directories{
|
||||
pub fn settings(&self)->UserSettings{
|
||||
load_user_settings(&self.settings)
|
||||
}
|
||||
pub fn user()->Option<Self>{
|
||||
let dirs=directories::ProjectDirs::from("net.strafes","StrafesNET","Strafe Client")?;
|
||||
Some(Self{
|
||||
settings:dirs.config_dir().join("settings.conf"),
|
||||
maps:dirs.cache_dir().join("maps"),
|
||||
// separate directory for remote downloaded replays (cache)
|
||||
// bots:dirs.cache_dir().join("bots"),
|
||||
replays:dirs.data_local_dir().join("replays"),
|
||||
})
|
||||
}
|
||||
pub fn portable()->Result<Self,std::io::Error>{
|
||||
let current_dir=std::env::current_dir()?;
|
||||
Ok(Self{
|
||||
settings:current_dir.join("settings.conf"),
|
||||
maps:current_dir.join("maps"),
|
||||
replays:current_dir.join("replays"),
|
||||
})
|
||||
}
|
||||
}
|
||||
2
engine/settings/src/lib.rs
Normal file
2
engine/settings/src/lib.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod settings;
|
||||
pub mod directories;
|
||||
@@ -74,9 +74,9 @@ sensitivity_y_from_x_ratio=1
|
||||
Sensitivity::DeriveY{x:0.0.001,y:DerivedSensitivity{ratio:1.0}}
|
||||
*/
|
||||
|
||||
pub fn read_user_settings()->UserSettings{
|
||||
pub fn load_user_settings(path:&std::path::Path)->UserSettings{
|
||||
let mut cfg=configparser::ini::Ini::new();
|
||||
if let Ok(_)=cfg.load("settings.conf"){
|
||||
if let Ok(_)=cfg.load(path){
|
||||
let (cfg_fov_x,cfg_fov_y)=(cfg.getfloat("camera","fov_x"),cfg.getfloat("camera","fov_y"));
|
||||
let fov=match(cfg_fov_x,cfg_fov_y){
|
||||
(Ok(Some(fov_x)),Ok(Some(fov_y)))=>Fov::Exactly {
|
||||
@@ -136,4 +136,4 @@ pub fn read_user_settings()->UserSettings{
|
||||
}else{
|
||||
UserSettings::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
1
integration-testing/.gitignore
vendored
Normal file
1
integration-testing/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/test_files
|
||||
15
integration-testing/Cargo.toml
Normal file
15
integration-testing/Cargo.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "integration-testing"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
glam.workspace = true
|
||||
strafesnet_common.workspace = true
|
||||
strafesnet_physics.workspace = true
|
||||
strafesnet_snf.workspace = true
|
||||
# this is just for the primitive constructor
|
||||
strafesnet_rbx_loader.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
28
integration-testing/src/error.rs
Normal file
28
integration-testing/src/error.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
#[expect(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum ReplayError{
|
||||
IO(std::io::Error),
|
||||
SNF(strafesnet_snf::Error),
|
||||
SNFM(strafesnet_snf::map::Error),
|
||||
SNFB(strafesnet_snf::bot::Error),
|
||||
}
|
||||
impl From<std::io::Error> for ReplayError{
|
||||
fn from(value:std::io::Error)->Self{
|
||||
Self::IO(value)
|
||||
}
|
||||
}
|
||||
impl From<strafesnet_snf::Error> for ReplayError{
|
||||
fn from(value:strafesnet_snf::Error)->Self{
|
||||
Self::SNF(value)
|
||||
}
|
||||
}
|
||||
impl From<strafesnet_snf::map::Error> for ReplayError{
|
||||
fn from(value:strafesnet_snf::map::Error)->Self{
|
||||
Self::SNFM(value)
|
||||
}
|
||||
}
|
||||
impl From<strafesnet_snf::bot::Error> for ReplayError{
|
||||
fn from(value:strafesnet_snf::bot::Error)->Self{
|
||||
Self::SNFB(value)
|
||||
}
|
||||
}
|
||||
225
integration-testing/src/main.rs
Normal file
225
integration-testing/src/main.rs
Normal file
@@ -0,0 +1,225 @@
|
||||
mod error;
|
||||
mod util;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod test_scenes;
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use error::ReplayError;
|
||||
use util::read_entire_file;
|
||||
use strafesnet_physics::physics::{PhysicsData,PhysicsState,PhysicsContext};
|
||||
|
||||
fn main(){
|
||||
let arg=std::env::args().skip(1).next();
|
||||
match arg.as_deref(){
|
||||
Some("determinism")|None=>test_determinism().unwrap(),
|
||||
Some("replay")=>run_replay().unwrap(),
|
||||
_=>println!("invalid argument"),
|
||||
}
|
||||
}
|
||||
|
||||
fn run_replay()->Result<(),ReplayError>{
|
||||
println!("loading map file..");
|
||||
let data=read_entire_file("../tools/bhop_maps/5692113331.snfm")?;
|
||||
let map=strafesnet_snf::read_map(data)?.into_complete_map()?;
|
||||
|
||||
println!("loading bot file..");
|
||||
let data=read_entire_file("../tools/replays/535s+159764769ns.snfb")?;
|
||||
let bot=strafesnet_snf::read_bot(data)?.read_all()?;
|
||||
|
||||
// create recording
|
||||
println!("generating models..");
|
||||
let physics_data=PhysicsData::new(&map);
|
||||
println!("simulating...");
|
||||
let mut physics=PhysicsState::default();
|
||||
for ins in bot.instructions{
|
||||
PhysicsContext::run_input_instruction(&mut physics,&physics_data,ins);
|
||||
}
|
||||
match physics.get_finish_time(){
|
||||
Some(time)=>println!("finish time:{}",time),
|
||||
None=>println!("simulation did not end in finished state"),
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
enum DeterminismResult{
|
||||
Deterministic,
|
||||
NonDeterministic,
|
||||
}
|
||||
struct SegmentResult{
|
||||
determinism:DeterminismResult,
|
||||
ticks:u64,
|
||||
nanoseconds:u64,
|
||||
}
|
||||
fn segment_determinism(bot:strafesnet_snf::bot::Segment,physics_data:&PhysicsData)->SegmentResult{
|
||||
// create default physics state
|
||||
let mut physics_deterministic=PhysicsState::default();
|
||||
// create a second physics state
|
||||
let mut physics_filtered=PhysicsState::default();
|
||||
|
||||
// invent a new bot id and insert the replay
|
||||
println!("simulating...");
|
||||
|
||||
let mut non_idle_count=0;
|
||||
let instruction_count=bot.instructions.len();
|
||||
|
||||
let start=Instant::now();
|
||||
|
||||
for (i,ins) in bot.instructions.into_iter().enumerate(){
|
||||
let state_deterministic=physics_deterministic.clone();
|
||||
let state_filtered=physics_filtered.clone();
|
||||
PhysicsContext::run_input_instruction(&mut physics_deterministic,physics_data,ins.clone());
|
||||
match ins{
|
||||
strafesnet_common::instruction::TimedInstruction{instruction:strafesnet_common::physics::Instruction::Idle,..}=>(),
|
||||
other=>{
|
||||
non_idle_count+=1;
|
||||
// run
|
||||
PhysicsContext::run_input_instruction(&mut physics_filtered,physics_data,other.clone());
|
||||
// check if position matches
|
||||
let b0=physics_deterministic.camera_trajectory(physics_data);
|
||||
let b1=physics_filtered.camera_trajectory(physics_data);
|
||||
if b0.position!=b1.position{
|
||||
let nanoseconds=start.elapsed().as_nanos() as u64;
|
||||
println!("desync at instruction #{}",i);
|
||||
println!("non idle instructions completed={non_idle_count}");
|
||||
println!("instruction #{i}={:?}",other);
|
||||
println!("deterministic state0:\n{state_deterministic:?}");
|
||||
println!("filtered state0:\n{state_filtered:?}");
|
||||
println!("deterministic state1:\n{:?}",physics_deterministic);
|
||||
println!("filtered state1:\n{:?}",physics_filtered);
|
||||
return SegmentResult{
|
||||
determinism:DeterminismResult::NonDeterministic,
|
||||
ticks:1+i as u64+non_idle_count,
|
||||
nanoseconds,
|
||||
};
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
let nanoseconds=start.elapsed().as_nanos() as u64;
|
||||
match physics_deterministic.get_finish_time(){
|
||||
Some(time)=>println!("[with idle] finish time:{}",time),
|
||||
None=>println!("[with idle] simulation did not end in finished state"),
|
||||
}
|
||||
match physics_filtered.get_finish_time(){
|
||||
Some(time)=>println!("[filtered] finish time:{}",time),
|
||||
None=>println!("[filtered] simulation did not end in finished state"),
|
||||
}
|
||||
SegmentResult{
|
||||
determinism:DeterminismResult::Deterministic,
|
||||
ticks:instruction_count as u64+non_idle_count,
|
||||
nanoseconds,
|
||||
}
|
||||
|
||||
}
|
||||
type ThreadResult=Result<Option<SegmentResult>,ReplayError>;
|
||||
fn read_and_run(file_path:std::path::PathBuf,physics_data:&PhysicsData)->ThreadResult{
|
||||
let data=read_entire_file(file_path.as_path())?;
|
||||
let bot=strafesnet_snf::read_bot(data)?.read_all()?;
|
||||
println!("Running {:?}",file_path.file_stem());
|
||||
Ok(Some(segment_determinism(bot,physics_data)))
|
||||
}
|
||||
fn do_thread<'a>(s:&'a std::thread::Scope<'a,'_>,file_path:std::path::PathBuf,send:std::sync::mpsc::Sender<ThreadResult>,physics_data:&'a PhysicsData){
|
||||
s.spawn(move ||{
|
||||
let result=read_and_run(file_path,physics_data);
|
||||
// send when thread is complete
|
||||
send.send(result).unwrap();
|
||||
});
|
||||
}
|
||||
fn get_file_path(dir_entry:std::fs::DirEntry)->Result<Option<std::path::PathBuf>,std::io::Error>{
|
||||
Ok(dir_entry.file_type()?.is_file().then_some(
|
||||
dir_entry.path()
|
||||
))
|
||||
}
|
||||
fn test_determinism()->Result<(),ReplayError>{
|
||||
let thread_limit=std::thread::available_parallelism()?.get();
|
||||
println!("loading map file..");
|
||||
let data=read_entire_file("../tools/bhop_maps/5692113331.snfm")?;
|
||||
let map=strafesnet_snf::read_map(data)?.into_complete_map()?;
|
||||
|
||||
println!("generating models..");
|
||||
let physics_data=PhysicsData::new(&map);
|
||||
|
||||
let (send,recv)=std::sync::mpsc::channel();
|
||||
|
||||
let mut read_dir=std::fs::read_dir("../tools/replays")?;
|
||||
|
||||
// promise that &physics_data will outlive the spawned threads
|
||||
let thread_results=std::thread::scope(|s|{
|
||||
let mut thread_results=Vec::new();
|
||||
|
||||
// spawn threads
|
||||
println!("spawning up to {thread_limit} threads...");
|
||||
let mut active_thread_count=0;
|
||||
while active_thread_count<thread_limit{
|
||||
if let Some(dir_entry_result)=read_dir.next(){
|
||||
if let Some(file_path)=get_file_path(dir_entry_result?)?{
|
||||
active_thread_count+=1;
|
||||
do_thread(s,file_path,send.clone(),&physics_data);
|
||||
}
|
||||
}else{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// spawn another thread every time a message is received from the channel
|
||||
println!("riding parallelism wave...");
|
||||
while let Some(dir_entry_result)=read_dir.next(){
|
||||
if let Some(file_path)=get_file_path(dir_entry_result?)?{
|
||||
// wait for a thread to complete
|
||||
thread_results.push(recv.recv().unwrap());
|
||||
do_thread(s,file_path,send.clone(),&physics_data);
|
||||
}
|
||||
}
|
||||
|
||||
// wait for remaining threads to complete
|
||||
println!("waiting for all threads to complete...");
|
||||
for _ in 0..active_thread_count{
|
||||
thread_results.push(recv.recv().unwrap());
|
||||
}
|
||||
|
||||
println!("done.");
|
||||
Ok::<_,ReplayError>(thread_results)
|
||||
})?;
|
||||
|
||||
// tally results
|
||||
#[derive(Default)]
|
||||
struct Totals{
|
||||
deterministic:u32,
|
||||
nondeterministic:u32,
|
||||
invalid:u32,
|
||||
error:u32,
|
||||
}
|
||||
let mut nanoseconds=0;
|
||||
let mut ticks=0;
|
||||
let Totals{deterministic,nondeterministic,invalid,error}=thread_results.into_iter().fold(Totals::default(),|mut totals,result|{
|
||||
match result{
|
||||
Ok(Some(segment_result))=>{
|
||||
ticks+=segment_result.ticks;
|
||||
nanoseconds+=segment_result.nanoseconds;
|
||||
match segment_result.determinism{
|
||||
DeterminismResult::Deterministic=>totals.deterministic+=1,
|
||||
DeterminismResult::NonDeterministic=>totals.nondeterministic+=1,
|
||||
}
|
||||
},
|
||||
Ok(None)=>totals.invalid+=1,
|
||||
Err(_)=>totals.error+=1,
|
||||
}
|
||||
totals
|
||||
});
|
||||
|
||||
println!("deterministic={deterministic}");
|
||||
println!("nondeterministic={nondeterministic}");
|
||||
println!("invalid={invalid}");
|
||||
println!("error={error}");
|
||||
println!("average ticks/s per core: {}",ticks*1_000_000_000/nanoseconds);
|
||||
|
||||
assert!(nondeterministic==0);
|
||||
assert!(invalid==0);
|
||||
assert!(error==0);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
113
integration-testing/src/test_scenes.rs
Normal file
113
integration-testing/src/test_scenes.rs
Normal file
@@ -0,0 +1,113 @@
|
||||
use strafesnet_physics::physics::{InternalInstruction,PhysicsData,PhysicsState,PhysicsContext};
|
||||
use strafesnet_common::gameplay_modes::NormalizedModes;
|
||||
use strafesnet_common::gameplay_attributes::{CollisionAttributes,CollisionAttributesId};
|
||||
use strafesnet_common::integer::{vec3,mat3,Planar64Affine3,Time};
|
||||
use strafesnet_common::model::{Mesh,Model,MeshId,ModelId,RenderConfigId};
|
||||
use strafesnet_common::map::CompleteMap;
|
||||
use strafesnet_rbx_loader::primitives::{unit_cube,CubeFaceDescription};
|
||||
|
||||
struct TestSceneBuilder{
|
||||
meshes:Vec<Mesh>,
|
||||
models:Vec<Model>,
|
||||
}
|
||||
impl TestSceneBuilder{
|
||||
fn new()->Self{
|
||||
Self{
|
||||
meshes:Vec::new(),
|
||||
models:Vec::new(),
|
||||
}
|
||||
}
|
||||
fn push_mesh(&mut self,mesh:Mesh)->MeshId{
|
||||
let mesh_id=self.meshes.len();
|
||||
self.meshes.push(mesh);
|
||||
MeshId::new(mesh_id as u32)
|
||||
}
|
||||
fn push_mesh_instance(&mut self,mesh:MeshId,transform:Planar64Affine3)->ModelId{
|
||||
let model=Model{
|
||||
mesh,
|
||||
attributes:CollisionAttributesId::new(0),
|
||||
color:glam::Vec4::ONE,
|
||||
transform,
|
||||
};
|
||||
let model_id=self.models.len();
|
||||
self.models.push(model);
|
||||
ModelId::new(model_id as u32)
|
||||
}
|
||||
fn build(self)->PhysicsData{
|
||||
let modes=NormalizedModes::new(Vec::new());
|
||||
let attributes=vec![CollisionAttributes::contact_default()];
|
||||
let meshes=self.meshes;
|
||||
let models=self.models;
|
||||
let textures=Vec::new();
|
||||
let render_configs=Vec::new();
|
||||
PhysicsData::new(&CompleteMap{
|
||||
modes,
|
||||
attributes,
|
||||
meshes,
|
||||
models,
|
||||
textures,
|
||||
render_configs,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn test_scene()->PhysicsData{
|
||||
let mut builder=TestSceneBuilder::new();
|
||||
let cube_face_description=CubeFaceDescription::new(Default::default(),RenderConfigId::new(0));
|
||||
let mesh=builder.push_mesh(unit_cube(cube_face_description));
|
||||
// place two 5x5x5 cubes.
|
||||
builder.push_mesh_instance(mesh,Planar64Affine3::new(
|
||||
mat3::from_diagonal(vec3::int(5,5,5)>>1),
|
||||
vec3::int(0,0,0)
|
||||
));
|
||||
builder.push_mesh_instance(mesh,Planar64Affine3::new(
|
||||
mat3::from_diagonal(vec3::int(5,5,5)>>1),
|
||||
vec3::int(5,-5,0)
|
||||
));
|
||||
builder.build()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simultaneous_collision(){
|
||||
let physics_data=test_scene();
|
||||
let body=strafesnet_physics::physics::Body::new(
|
||||
(vec3::int(5+2,0,0)>>1)+vec3::int(1,1,0),
|
||||
vec3::int(-1,-1,0),
|
||||
Time::ZERO,
|
||||
);
|
||||
let mut physics=PhysicsState::new_with_body(body);
|
||||
physics.style_mut().gravity=vec3::zero();
|
||||
let mut phys_iter=PhysicsContext::iter_internal(&mut physics,&physics_data,Time::from_secs(2))
|
||||
.filter(|ins|!matches!(ins.instruction,InternalInstruction::StrafeTick));
|
||||
// the order that they hit does matter, but we aren't currently worrying about that.
|
||||
// See multi-collision branch
|
||||
assert_eq!(phys_iter.next().unwrap().time,Time::from_secs(1));
|
||||
assert_eq!(phys_iter.next().unwrap().time,Time::from_secs(1));
|
||||
assert!(phys_iter.next().is_none());
|
||||
let body=physics.body();
|
||||
assert_eq!(body.position,vec3::int(5,0,0));
|
||||
assert_eq!(body.velocity,vec3::int(0,0,0));
|
||||
assert_eq!(body.time,Time::from_secs(1));
|
||||
}
|
||||
#[test]
|
||||
fn bug_3(){
|
||||
let physics_data=test_scene();
|
||||
let body=strafesnet_physics::physics::Body::new(
|
||||
(vec3::int(5+2,0,0)>>1)+vec3::int(1,2,0),
|
||||
vec3::int(-1,-1,0),
|
||||
Time::ZERO,
|
||||
);
|
||||
let mut physics=PhysicsState::new_with_body(body);
|
||||
physics.style_mut().gravity=vec3::zero();
|
||||
let mut phys_iter=PhysicsContext::iter_internal(&mut physics,&physics_data,Time::from_secs(3))
|
||||
.filter(|ins|!matches!(ins.instruction,InternalInstruction::StrafeTick));
|
||||
// touch side of part at 0,0,0
|
||||
assert_eq!(phys_iter.next().unwrap().time,Time::from_secs(1));
|
||||
// touch top of part at 5,-5,0
|
||||
assert_eq!(phys_iter.next().unwrap().time,Time::from_secs(2));
|
||||
assert!(phys_iter.next().is_none());
|
||||
let body=physics.body();
|
||||
assert_eq!(body.position,vec3::int(5+2,0,0)>>1);
|
||||
assert_eq!(body.velocity,vec3::int(0,0,0));
|
||||
assert_eq!(body.time,Time::from_secs(2));
|
||||
}
|
||||
78
integration-testing/src/tests.rs
Normal file
78
integration-testing/src/tests.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
use crate::error::ReplayError;
|
||||
use crate::util::read_entire_file;
|
||||
use strafesnet_physics::physics::{PhysicsData,PhysicsState,PhysicsContext};
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn physics_bug_2()->Result<(),ReplayError>{
|
||||
println!("loading map file..");
|
||||
let data=read_entire_file("test_files/bhop_monster_jam.snfm")?;
|
||||
let map=strafesnet_snf::read_map(data)?.into_complete_map()?;
|
||||
|
||||
// create recording
|
||||
println!("generating models..");
|
||||
let physics_data=PhysicsData::new(&map);
|
||||
println!("simulating...");
|
||||
|
||||
//teleport to bug
|
||||
// body pos = Vector { array: [Fixed { bits: 554895163352 }, Fixed { bits: 1485633089990 }, Fixed { bits: 1279601007173 }] }
|
||||
// after the fix it's still happening, possibly for a different reason, new position to evince:
|
||||
// body pos = Vector { array: [Fixed { bits: 555690659654 }, Fixed { bits: 1490485868773 }, Fixed { bits: 1277783839382 }] }
|
||||
use strafesnet_common::integer::{vec3,Time};
|
||||
let body=strafesnet_physics::physics::Body::new(
|
||||
vec3::raw_xyz(555690659654,1490485868773,1277783839382),
|
||||
vec3::int(0,0,0),
|
||||
Time::ZERO,
|
||||
);
|
||||
let mut physics=PhysicsState::new_with_body(body);
|
||||
// wait one second to activate the bug
|
||||
// hit=Some(ModelId(2262))
|
||||
PhysicsContext::run_input_instruction(&mut physics,&physics_data,strafesnet_common::instruction::TimedInstruction{
|
||||
time:Time::from_millis(500),
|
||||
instruction:strafesnet_common::physics::Instruction::Idle,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn physics_bug_3()->Result<(),ReplayError>{
|
||||
println!("loading map file..");
|
||||
let data=read_entire_file("../tools/bhop_maps/5692152916.snfm")?;
|
||||
let map=strafesnet_snf::read_map(data)?.into_complete_map()?;
|
||||
|
||||
// create recording
|
||||
println!("generating models..");
|
||||
let physics_data=PhysicsData::new(&map);
|
||||
println!("simulating...");
|
||||
|
||||
//teleport to bug
|
||||
use strafesnet_common::integer::{vec3,Time};
|
||||
let body=strafesnet_physics::physics::Body::new(
|
||||
// bhop_toc corner position after wall hits
|
||||
// vec3::raw_xyz(-1401734815424,3315081280280,-2466057177493),
|
||||
// vec3::raw_xyz(0,-96915585363,1265),
|
||||
// vec3::raw_xyz(0,-429496729600,0),
|
||||
// alternate room center position
|
||||
// vec3::raw_xyz(-1129043783837,3324870327882,-2014012350212),
|
||||
// vec3::raw_xyz(0,-96915585363,1265),
|
||||
// vec3::raw_xyz(0,-429496729600,0),
|
||||
// corner setup before wall hits
|
||||
// vec3::raw_xyz(-1392580080675,3325402529458,-2444727738679),
|
||||
// vec3::raw_xyz(-30259028820,-22950929553,-71141663007),
|
||||
// vec3::raw_xyz(0,-429496729600,0),
|
||||
// Actual bug 3 repro
|
||||
vec3::raw_xyz(-2505538624455,3357963283914,557275711118),
|
||||
vec3::raw_xyz(204188283920,-282280474198,166172785440),
|
||||
Time::ZERO,
|
||||
);
|
||||
let mut physics=PhysicsState::new_with_body(body);
|
||||
// wait one second to activate the bug
|
||||
PhysicsContext::run_input_instruction(&mut physics,&physics_data,strafesnet_common::instruction::TimedInstruction{
|
||||
time:Time::from_millis(500),
|
||||
instruction:strafesnet_common::physics::Instruction::Idle,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
7
integration-testing/src/util.rs
Normal file
7
integration-testing/src/util.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
use std::io::Cursor;
|
||||
use std::path::Path;
|
||||
|
||||
pub fn read_entire_file(path:impl AsRef<Path>)->Result<Cursor<Vec<u8>>,std::io::Error>{
|
||||
let data=std::fs::read(path)?;
|
||||
Ok(Cursor::new(data))
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "strafesnet_bsp_loader"
|
||||
version = "0.2.2"
|
||||
edition = "2021"
|
||||
version = "0.5.0"
|
||||
edition = "2024"
|
||||
repository = "https://git.itzana.me/StrafesNET/strafe-project"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Convert Valve BSP files to StrafesNET data structures."
|
||||
@@ -10,7 +10,13 @@ authors = ["Rhys Lloyd <krakow20@gmail.com>"]
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
glam = "0.29.0"
|
||||
strafesnet_common = { path = "../common", registry = "strafesnet" }
|
||||
vbsp = "0.6.0"
|
||||
glam.workspace = true
|
||||
strafesnet_common.workspace = true
|
||||
strafesnet_deferred_loader.workspace = true
|
||||
vbsp = "0.9.1"
|
||||
vbsp-entities-css = "0.6.0"
|
||||
vmdl = "0.2.0"
|
||||
vpk = "0.3.0"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
344
lib/bsp_loader/src/brush.rs
Normal file
344
lib/bsp_loader/src/brush.rs
Normal file
@@ -0,0 +1,344 @@
|
||||
use strafesnet_common::{model,integer};
|
||||
use strafesnet_common::integer::fixed_types::F192_96;
|
||||
use strafesnet_common::integer::vec3::Vector3;
|
||||
use strafesnet_common::integer::{Planar64,Planar64Vec3,Ratio};
|
||||
|
||||
use crate::{valve_transform_normal,valve_transform_dist};
|
||||
|
||||
#[derive(Hash,Eq,PartialEq)]
|
||||
struct Face{
|
||||
normal:Planar64Vec3,
|
||||
dot:Planar64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Faces{
|
||||
faces:Vec<Vec<Planar64Vec3>>,
|
||||
}
|
||||
|
||||
fn solve3(c0:&Face,c1:&Face,c2:&Face)->Option<Ratio<Vector3<F192_96>,F192_96>>{
|
||||
let n0_n1=c0.normal.cross(c1.normal);
|
||||
let det=c2.normal.dot(n0_n1);
|
||||
if det.abs().is_zero(){
|
||||
return None;
|
||||
}
|
||||
Some((
|
||||
c1.normal.cross(c2.normal)*c0.dot
|
||||
+c2.normal.cross(c0.normal)*c1.dot
|
||||
+c0.normal.cross(c1.normal)*c2.dot
|
||||
)/det)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum PlanesToFacesError{
|
||||
InitFace1,
|
||||
InitFace2,
|
||||
InitIntersection,
|
||||
FindNewIntersection,
|
||||
// Narrow(strafesnet_common::integer::NarrowError),
|
||||
EmptyFaces,
|
||||
InfiniteLoop1,
|
||||
InfiniteLoop2,
|
||||
}
|
||||
impl std::fmt::Display for PlanesToFacesError{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"{self:?}")
|
||||
}
|
||||
}
|
||||
impl core::error::Error for PlanesToFacesError{}
|
||||
|
||||
fn planes_to_faces(face_list:std::collections::HashSet<Face>)->Result<Faces,PlanesToFacesError>{
|
||||
let mut faces=Vec::new();
|
||||
// for each face, determine one edge at a time until you complete the face
|
||||
'face: for face0 in &face_list{
|
||||
// 1. find first edge
|
||||
// 2. follow edges around face
|
||||
|
||||
// === finding first edge ===
|
||||
// 1. pick the most perpendicular set of 3 faces
|
||||
// 2. check if any faces occlude the intersection
|
||||
// 3. use this test to replace left and right alternating until they are not occluded
|
||||
|
||||
// find the most perpendicular face to face0
|
||||
let mut face1=face_list.iter().min_by_key(|&p|{
|
||||
face0.normal.dot(p.normal).abs()
|
||||
}).ok_or(PlanesToFacesError::InitFace1)?;
|
||||
|
||||
// direction of edge formed by face0 x face1
|
||||
let edge_dir=face0.normal.cross(face1.normal);
|
||||
|
||||
// find the most perpendicular face to both face0 and face1
|
||||
let mut face2=face_list.iter().max_by_key(|&p|{
|
||||
// find the best *oriented* face (no .abs())
|
||||
edge_dir.dot(p.normal)
|
||||
}).ok_or(PlanesToFacesError::InitFace2)?;
|
||||
|
||||
let mut detect_loop=200u8;
|
||||
|
||||
let mut intersection=solve3(face0,face1,face2).ok_or(PlanesToFacesError::InitIntersection)?;
|
||||
|
||||
// repeatedly update face1, face2 until all faces form part of the convex solid
|
||||
'find: loop{
|
||||
detect_loop=detect_loop.checked_sub(1).ok_or(PlanesToFacesError::InfiniteLoop1)?;
|
||||
// test if any *other* faces occlude the intersection
|
||||
for new_face in &face_list{
|
||||
// new face occludes intersection point
|
||||
if (new_face.dot.widen_128()/Planar64::ONE).lt_ratio(new_face.normal.dot(intersection.num)/intersection.den){
|
||||
// replace one of the faces with the new face
|
||||
// dont' try to replace face0 because we are exploring that face in particular
|
||||
if let Some(new_intersection)=solve3(face0,new_face,face2){
|
||||
// face1 does not occlude (or intersect) the new intersection
|
||||
if (face1.dot.widen_128()/Planar64::ONE).gt_ratio(face1.normal.dot(new_intersection.num)/new_intersection.den){
|
||||
face1=new_face;
|
||||
intersection=new_intersection;
|
||||
continue 'find;
|
||||
}
|
||||
}
|
||||
if let Some(new_intersection)=solve3(face0,face1,new_face){
|
||||
// face2 does not occlude (or intersect) the new intersection
|
||||
if (face2.dot.widen_128()/Planar64::ONE).gt_ratio(face2.normal.dot(new_intersection.num)/new_intersection.den){
|
||||
face2=new_face;
|
||||
intersection=new_intersection;
|
||||
continue 'find;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// we have found a set of faces for which the intersection is on the convex solid
|
||||
break 'find;
|
||||
}
|
||||
|
||||
// check if face0 must go, meaning it is a degenerate face and does not contribute anything to the convex solid
|
||||
for new_face in &face_list{
|
||||
if core::ptr::eq(face0,new_face){
|
||||
continue;
|
||||
}
|
||||
if core::ptr::eq(face1,new_face){
|
||||
continue;
|
||||
}
|
||||
if core::ptr::eq(face2,new_face){
|
||||
continue;
|
||||
}
|
||||
// new_face occludes intersection meaning intersection is not on convex solid and face0 is degenrate
|
||||
if (new_face.dot.widen_128()/Planar64::ONE).lt_ratio(new_face.normal.dot(intersection.num)/intersection.den){
|
||||
// abort! reject face0 entirely
|
||||
continue 'face;
|
||||
}
|
||||
}
|
||||
|
||||
// === follow edges around face ===
|
||||
// Note that we chose face2 such that the 3 faces create a particular winding order.
|
||||
// If we choose a consistent face to follow (face1, face2) it will always wind with a consistent chirality
|
||||
|
||||
let mut detect_loop=200u8;
|
||||
|
||||
// keep looping until we meet this face again
|
||||
let face1=face1;
|
||||
let mut face=Vec::new();
|
||||
loop{
|
||||
// push point onto vertices
|
||||
// problem: this may push a vertex that does not fit in the fixed point range and is thus meaningless
|
||||
face.push(intersection.divide().narrow_64().unwrap());
|
||||
|
||||
// we looped back around to face1, we're done!
|
||||
if core::ptr::eq(face1,face2){
|
||||
break;
|
||||
}
|
||||
|
||||
// the measure
|
||||
let edge_dir=face0.normal.cross(face2.normal);
|
||||
|
||||
// the dot product to beat
|
||||
let d_intersection=edge_dir.dot(intersection.num)/intersection.den;
|
||||
|
||||
// find the next face moving clockwise around face0
|
||||
let (new_face,new_intersection,_)=face_list.iter().filter_map(|new_face|{
|
||||
// ignore faces that are part of the current edge
|
||||
if core::ptr::eq(face0,new_face)
|
||||
|core::ptr::eq(face2,new_face){
|
||||
return None;
|
||||
}
|
||||
let new_intersection=solve3(face0,face2,new_face)?;
|
||||
|
||||
// the d value must be larger
|
||||
let d_new_intersection=edge_dir.dot(new_intersection.num)/new_intersection.den;
|
||||
if d_new_intersection.le_ratio(d_intersection){
|
||||
return None;
|
||||
}
|
||||
|
||||
Some((new_face,new_intersection,d_new_intersection))
|
||||
}).min_by_key(|&(_,_,d)|d).ok_or(PlanesToFacesError::FindNewIntersection)?;
|
||||
|
||||
face2=new_face;
|
||||
intersection=new_intersection;
|
||||
|
||||
detect_loop=detect_loop.checked_sub(1).ok_or(PlanesToFacesError::InfiniteLoop2)?;
|
||||
}
|
||||
|
||||
faces.push(face);
|
||||
}
|
||||
|
||||
if faces.is_empty(){
|
||||
Err(PlanesToFacesError::EmptyFaces)
|
||||
}else{
|
||||
Ok(Faces{
|
||||
faces,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum BrushToMeshError{
|
||||
SliceBrushSides,
|
||||
MissingPlane,
|
||||
InvalidFaceCount{
|
||||
count:usize,
|
||||
},
|
||||
InvalidPlanes(PlanesToFacesError),
|
||||
}
|
||||
impl std::fmt::Display for BrushToMeshError{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"{self:?}")
|
||||
}
|
||||
}
|
||||
impl core::error::Error for BrushToMeshError{}
|
||||
|
||||
pub fn faces_to_mesh(faces:Vec<Vec<Planar64Vec3>>)->model::Mesh{
|
||||
// generate the mesh
|
||||
let mut mb=model::MeshBuilder::new();
|
||||
let color=mb.acquire_color_id(glam::Vec4::ONE);
|
||||
let tex=mb.acquire_tex_id(glam::Vec2::ZERO);
|
||||
// normals are ignored by physics
|
||||
let normal=mb.acquire_normal_id(integer::vec3::zero());
|
||||
|
||||
let polygon_list=faces.into_iter().map(|face|{
|
||||
face.into_iter().map(|pos|{
|
||||
let pos=mb.acquire_pos_id(pos);
|
||||
mb.acquire_vertex_id(model::IndexedVertex{
|
||||
pos,
|
||||
tex,
|
||||
normal,
|
||||
color,
|
||||
})
|
||||
}).collect()
|
||||
}).collect();
|
||||
|
||||
let polygon_groups=vec![model::PolygonGroup::PolygonList(model::PolygonList::new(polygon_list))];
|
||||
let physics_groups=vec![model::IndexedPhysicsGroup{
|
||||
groups:vec![model::PolygonGroupId::new(0)],
|
||||
}];
|
||||
let graphics_groups=vec![];
|
||||
|
||||
mb.build(polygon_groups,graphics_groups,physics_groups)
|
||||
}
|
||||
|
||||
pub fn brush_to_mesh(bsp:&vbsp::Bsp,brush:&vbsp::Brush)->Result<model::Mesh,BrushToMeshError>{
|
||||
let brush_start_idx=brush.brush_side as usize;
|
||||
let sides_range=brush_start_idx..brush_start_idx+brush.num_brush_sides as usize;
|
||||
let sides=bsp.brush_sides.get(sides_range).ok_or(BrushToMeshError::SliceBrushSides)?;
|
||||
let face_list=sides.iter().map(|side|{
|
||||
// The so-called tumor brushes have TRIGGER bit set
|
||||
// but also ignore visleaf hint and skip sides
|
||||
const TUMOR:vbsp::TextureFlags=vbsp::TextureFlags::HINT.union(vbsp::TextureFlags::SKIP).union(vbsp::TextureFlags::TRIGGER);
|
||||
if let Some(texture_info)=bsp.texture_info(side.texture_info as usize){
|
||||
if texture_info.flags.intersects(TUMOR){
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let plane=bsp.plane(side.plane as usize)?;
|
||||
Some(Face{
|
||||
normal:valve_transform_normal(plane.normal.into()),
|
||||
dot:valve_transform_dist(plane.dist.into()),
|
||||
})
|
||||
}).collect::<Option<std::collections::HashSet<_>>>().ok_or(BrushToMeshError::MissingPlane)?;
|
||||
|
||||
if face_list.len()<4{
|
||||
return Err(BrushToMeshError::InvalidFaceCount{count:face_list.len()});
|
||||
}
|
||||
|
||||
let faces=planes_to_faces(face_list).map_err(BrushToMeshError::InvalidPlanes)?;
|
||||
|
||||
let mesh=faces_to_mesh(faces.faces);
|
||||
|
||||
Ok(mesh)
|
||||
}
|
||||
|
||||
pub fn unit_cube()->model::Mesh{
|
||||
let face_list=[
|
||||
Face{normal:integer::vec3::X,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::Y,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::Z,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_X,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_Y,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_Z,dot:Planar64::ONE},
|
||||
].into_iter().collect();
|
||||
let faces=planes_to_faces(face_list).unwrap();
|
||||
let mesh=faces_to_mesh(faces.faces);
|
||||
mesh
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test{
|
||||
use super::*;
|
||||
#[test]
|
||||
fn test_cube(){
|
||||
let face_list=[
|
||||
Face{normal:integer::vec3::X,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::Y,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::Z,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_X,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_Y,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_Z,dot:Planar64::ONE},
|
||||
].into_iter().collect();
|
||||
let faces=planes_to_faces(face_list).unwrap();
|
||||
assert_eq!(faces.faces.len(),6);
|
||||
dbg!(faces);
|
||||
}
|
||||
#[test]
|
||||
fn test_cube_with_degernate_face(){
|
||||
let face_list=[
|
||||
Face{normal:integer::vec3::X,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::Y,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::Z,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_X,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_Y,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_Z,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_Z,dot:Planar64::EPSILON},
|
||||
].into_iter().collect();
|
||||
let faces=planes_to_faces(face_list).unwrap();
|
||||
assert_eq!(faces.faces.len(),6);
|
||||
dbg!(faces);
|
||||
}
|
||||
#[test]
|
||||
fn test_cube_with_degernate_face2(){
|
||||
let face_list=[
|
||||
Face{normal:integer::vec3::X,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::Y,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::Z,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_X,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_Y,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_Z,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_X+integer::vec3::NEG_Z,dot:-Planar64::EPSILON},
|
||||
].into_iter().collect();
|
||||
let faces=planes_to_faces(face_list).unwrap();
|
||||
assert_eq!(faces.faces.len(),5);
|
||||
dbg!(faces);
|
||||
}
|
||||
#[test]
|
||||
fn test_cube_with_degernate_face3(){
|
||||
let face_list=[
|
||||
Face{normal:integer::vec3::X,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::Y,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::Z,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_X,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_Y,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_Z,dot:Planar64::ONE},
|
||||
Face{normal:integer::vec3::NEG_X+integer::vec3::NEG_Z,dot:Planar64::EPSILON},
|
||||
].into_iter().collect();
|
||||
let faces=planes_to_faces(face_list).unwrap();
|
||||
assert_eq!(faces.faces.len(),7);
|
||||
dbg!(faces);
|
||||
}
|
||||
}
|
||||
@@ -1,43 +1,142 @@
|
||||
use strafesnet_common::{map,model,integer,gameplay_attributes};
|
||||
use std::borrow::Cow;
|
||||
|
||||
const VALVE_SCALE:f32=1.0/16.0;
|
||||
fn valve_transform([x,y,z]:[f32;3])->integer::Planar64Vec3{
|
||||
integer::vec3::try_from_f32_array([x*VALVE_SCALE,z*VALVE_SCALE,-y*VALVE_SCALE]).unwrap()
|
||||
use vbsp_entities_css::Entity;
|
||||
|
||||
use strafesnet_common::{map,model,integer,gameplay_attributes as attr};
|
||||
use strafesnet_deferred_loader::deferred_loader::{MeshDeferredLoader,RenderConfigDeferredLoader};
|
||||
use strafesnet_deferred_loader::mesh::Meshes;
|
||||
use strafesnet_deferred_loader::texture::{RenderConfigs,Texture};
|
||||
use strafesnet_common::gameplay_modes::{NormalizedMode,NormalizedModes,Mode,Stage};
|
||||
|
||||
use crate::valve_transform;
|
||||
|
||||
fn ingest_vertex(
|
||||
mb:&mut model::MeshBuilder,
|
||||
world_position:vbsp::Vector,
|
||||
texture_transform_u:glam::Vec4,
|
||||
texture_transform_v:glam::Vec4,
|
||||
normal:model::NormalId,
|
||||
color:model::ColorId,
|
||||
)->model::VertexId{
|
||||
//world_model.origin seems to always be 0,0,0
|
||||
let vertex_xyz=world_position.into();
|
||||
let pos=mb.acquire_pos_id(valve_transform(vertex_xyz));
|
||||
|
||||
//calculate texture coordinates
|
||||
let pos_4d=glam::Vec3::from_array(vertex_xyz).extend(1.0);
|
||||
let tex=glam::vec2(texture_transform_u.dot(pos_4d),texture_transform_v.dot(pos_4d));
|
||||
let tex=mb.acquire_tex_id(tex);
|
||||
|
||||
mb.acquire_vertex_id(model::IndexedVertex{
|
||||
pos,
|
||||
tex,
|
||||
normal,
|
||||
color,
|
||||
})
|
||||
}
|
||||
pub fn convert_bsp<AcquireRenderConfigId,AcquireMeshId>(
|
||||
bsp:&vbsp::Bsp,
|
||||
mut acquire_render_config_id:AcquireRenderConfigId,
|
||||
mut acquire_mesh_id:AcquireMeshId
|
||||
)->PartialMap1
|
||||
where
|
||||
AcquireRenderConfigId:FnMut(Option<&str>)->model::RenderConfigId,
|
||||
AcquireMeshId:FnMut(&str)->model::MeshId,
|
||||
{
|
||||
//figure out real attributes later
|
||||
let mut unique_attributes=Vec::new();
|
||||
unique_attributes.push(gameplay_attributes::CollisionAttributes::Decoration);
|
||||
const TEMP_TOUCH_ME_ATTRIBUTE:gameplay_attributes::CollisionAttributesId=gameplay_attributes::CollisionAttributesId::new(0);
|
||||
|
||||
let mut prop_mesh_count=0;
|
||||
fn add_brush<'a>(
|
||||
mesh_deferred_loader:&mut MeshDeferredLoader<&'a str>,
|
||||
world_models:&mut Vec<model::Model>,
|
||||
prop_models:&mut Vec<model::Model>,
|
||||
model:&'a str,
|
||||
origin:vbsp::Vector,
|
||||
rendercolor:vbsp::Color,
|
||||
attributes:attr::CollisionAttributesId,
|
||||
){
|
||||
let transform=integer::Planar64Affine3::from_translation(
|
||||
valve_transform(origin.into())
|
||||
);
|
||||
let color=(glam::Vec3::from_array([
|
||||
rendercolor.r as f32,
|
||||
rendercolor.g as f32,
|
||||
rendercolor.b as f32
|
||||
])/255.0).extend(1.0);
|
||||
|
||||
match model.chars().next(){
|
||||
// The first character of brush.model is '*'
|
||||
Some('*')=>match model[1..].parse(){
|
||||
Ok(mesh_id)=>{
|
||||
let mesh=model::MeshId::new(mesh_id);
|
||||
world_models.push(
|
||||
model::Model{mesh,attributes,transform,color}
|
||||
);
|
||||
},
|
||||
Err(e)=>{
|
||||
println!("Brush model int parse error: {e} model={model}");
|
||||
return;
|
||||
},
|
||||
},
|
||||
_=>{
|
||||
let mesh=mesh_deferred_loader.acquire_mesh_id(model);
|
||||
prop_models.push(
|
||||
model::Model{mesh,attributes,transform,color}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn convert<'a>(
|
||||
bsp:&'a crate::Bsp,
|
||||
render_config_deferred_loader:&mut RenderConfigDeferredLoader<Cow<'a,str>>,
|
||||
mesh_deferred_loader:&mut MeshDeferredLoader<&'a str>,
|
||||
)->PartialMap1{
|
||||
let bsp=bsp.as_ref();
|
||||
//figure out real attributes later
|
||||
let unique_attributes=vec![
|
||||
attr::CollisionAttributes::Decoration,
|
||||
attr::CollisionAttributes::contact_default(),
|
||||
attr::CollisionAttributes::intersect_default(),
|
||||
// ladder
|
||||
attr::CollisionAttributes::Contact(
|
||||
attr::ContactAttributes{
|
||||
contacting:attr::ContactingAttributes{
|
||||
contact_behaviour:Some(attr::ContactingBehaviour::Ladder(
|
||||
attr::ContactingLadder{sticky:true}
|
||||
))
|
||||
},
|
||||
general:attr::GeneralAttributes::default(),
|
||||
}
|
||||
),
|
||||
// water
|
||||
attr::CollisionAttributes::Intersect(
|
||||
attr::IntersectAttributes{
|
||||
intersecting:attr::IntersectingAttributes{
|
||||
water:Some(attr::IntersectingWater{
|
||||
viscosity:integer::Planar64::ONE,
|
||||
density:integer::Planar64::ONE,
|
||||
velocity:integer::vec3::zero(),
|
||||
}),
|
||||
},
|
||||
general:attr::GeneralAttributes::default(),
|
||||
}
|
||||
),
|
||||
];
|
||||
const ATTRIBUTE_DECORATION:attr::CollisionAttributesId=attr::CollisionAttributesId::new(0);
|
||||
const ATTRIBUTE_CONTACT_DEFAULT:attr::CollisionAttributesId=attr::CollisionAttributesId::new(1);
|
||||
const ATTRIBUTE_INTERSECT_DEFAULT:attr::CollisionAttributesId=attr::CollisionAttributesId::new(2);
|
||||
const ATTRIBUTE_LADDER_DEFAULT:attr::CollisionAttributesId=attr::CollisionAttributesId::new(3);
|
||||
const ATTRIBUTE_WATER_DEFAULT:attr::CollisionAttributesId=attr::CollisionAttributesId::new(4);
|
||||
|
||||
//declare all prop models to Loader
|
||||
let prop_models=bsp.static_props().map(|prop|{
|
||||
let mut prop_models=bsp.static_props().map(|prop|{
|
||||
const DEG_TO_RAD:f32=std::f32::consts::TAU/360.0;
|
||||
//get or create mesh_id
|
||||
let mesh_id=acquire_mesh_id(prop.model());
|
||||
//not the most failsafe code but this is just for the map tool lmao
|
||||
if prop_mesh_count==mesh_id.get(){
|
||||
prop_mesh_count+=1;
|
||||
};
|
||||
let placement=prop.as_prop_placement();
|
||||
let mesh_id=mesh_deferred_loader.acquire_mesh_id(prop.model());
|
||||
model::Model{
|
||||
mesh:mesh_id,
|
||||
attributes:TEMP_TOUCH_ME_ATTRIBUTE,
|
||||
attributes:ATTRIBUTE_DECORATION,
|
||||
transform:integer::Planar64Affine3::new(
|
||||
integer::mat3::try_from_f32_array_2d((
|
||||
glam::Mat3A::from_diagonal(glam::Vec3::splat(placement.scale))
|
||||
integer::mat3::try_from_f32_array_2d(
|
||||
//TODO: figure this out
|
||||
*glam::Mat3A::from_quat(glam::Quat::from_array(placement.rotation.into()))
|
||||
).to_cols_array_2d()).unwrap(),
|
||||
valve_transform(placement.origin.into()),
|
||||
glam::Mat3A::from_euler(
|
||||
glam::EulerRot::XYZ,
|
||||
prop.angles.pitch*DEG_TO_RAD,
|
||||
prop.angles.yaw*DEG_TO_RAD,
|
||||
prop.angles.roll*DEG_TO_RAD
|
||||
).to_cols_array_2d()
|
||||
).unwrap(),
|
||||
valve_transform(prop.origin.into()),
|
||||
),
|
||||
color:glam::Vec4::ONE,
|
||||
}
|
||||
@@ -47,14 +146,12 @@ where
|
||||
|
||||
//the generated MeshIds in here will collide with the Loader Mesh Ids
|
||||
//but I can't think of a good workaround other than just remapping one later.
|
||||
let world_meshes:Vec<model::Mesh>=bsp.models().map(|world_model|{
|
||||
//non-deduplicated
|
||||
let mut spam_pos=Vec::new();
|
||||
let mut spam_tex=Vec::new();
|
||||
let mut spam_normal=Vec::new();
|
||||
let mut spam_vertices=Vec::new();
|
||||
let mut world_meshes:Vec<model::Mesh>=bsp.models().map(|world_model|{
|
||||
let mut mb=model::MeshBuilder::new();
|
||||
|
||||
let color=mb.acquire_color_id(glam::Vec4::ONE);
|
||||
let mut graphics_groups=Vec::new();
|
||||
let mut physics_group=model::IndexedPhysicsGroup::default();
|
||||
let mut render_id_to_graphics_group_id=std::collections::HashMap::new();
|
||||
let polygon_groups=world_model.faces().enumerate().map(|(polygon_group_id,face)|{
|
||||
let polygon_group_id=model::PolygonGroupId::new(polygon_group_id as u32);
|
||||
let face_texture=face.texture();
|
||||
@@ -63,139 +160,200 @@ where
|
||||
let texture_transform_u=glam::Vec4::from_array(face_texture.texture_transforms_u)/(face_texture_data.width as f32);
|
||||
let texture_transform_v=glam::Vec4::from_array(face_texture.texture_transforms_v)/(face_texture_data.height as f32);
|
||||
|
||||
//this automatically figures out what the texture is trying to do and creates
|
||||
//a render config for it, and then returns the id to that render config
|
||||
let render_id=acquire_render_config_id(Some(face_texture_data.name()));
|
||||
|
||||
//normal
|
||||
let normal=face.normal();
|
||||
let normal_idx=spam_normal.len() as u32;
|
||||
spam_normal.push(valve_transform(normal.into()));
|
||||
let mut polygon_iter=face.vertex_positions().map(|vertex_position|{
|
||||
//world_model.origin seems to always be 0,0,0
|
||||
let vertex_xyz=(world_model.origin+vertex_position).into();
|
||||
let pos_idx=spam_pos.len();
|
||||
spam_pos.push(valve_transform(vertex_xyz));
|
||||
|
||||
//calculate texture coordinates
|
||||
let pos=glam::Vec3::from_array(vertex_xyz).extend(1.0);
|
||||
let tex=glam::vec2(texture_transform_u.dot(pos),texture_transform_v.dot(pos));
|
||||
let tex_idx=spam_tex.len() as u32;
|
||||
spam_tex.push(tex);
|
||||
|
||||
let vertex_id=model::VertexId::new(spam_vertices.len() as u32);
|
||||
spam_vertices.push(model::IndexedVertex{
|
||||
pos:model::PositionId::new(pos_idx as u32),
|
||||
tex:model::TextureCoordinateId::new(tex_idx as u32),
|
||||
normal:model::NormalId::new(normal_idx),
|
||||
color:model::ColorId::new(0),
|
||||
});
|
||||
vertex_id
|
||||
});
|
||||
let normal=mb.acquire_normal_id(valve_transform(face.normal().into()));
|
||||
let mut polygon_iter=face.vertex_positions().map(|vertex_position|
|
||||
world_model.origin+vertex_position
|
||||
);
|
||||
let polygon_list=std::iter::from_fn(move||{
|
||||
match (polygon_iter.next(),polygon_iter.next(),polygon_iter.next()){
|
||||
(Some(v1),Some(v2),Some(v3))=>Some(vec![v1,v2,v3]),
|
||||
(Some(v1),Some(v2),Some(v3))=>Some([v1,v2,v3]),
|
||||
//ignore extra vertices, not sure what to do in this case, failing the whole conversion could be appropriate
|
||||
_=>None,
|
||||
}
|
||||
}).map(|triplet|{
|
||||
triplet.map(|world_position|
|
||||
ingest_vertex(&mut mb,world_position,texture_transform_u,texture_transform_v,normal,color)
|
||||
).to_vec()
|
||||
}).collect();
|
||||
if face.is_visible(){
|
||||
//TODO: deduplicate graphics groups by render id
|
||||
graphics_groups.push(model::IndexedGraphicsGroup{
|
||||
render:render_id,
|
||||
groups:vec![polygon_group_id],
|
||||
})
|
||||
//this automatically figures out what the texture is trying to do and creates
|
||||
//a render config for it, and then returns the id to that render config
|
||||
let render_id=render_config_deferred_loader.acquire_render_config_id(Some(Cow::Borrowed(face_texture_data.name())));
|
||||
//deduplicate graphics groups by render id
|
||||
let graphics_group_id=*render_id_to_graphics_group_id.entry(render_id).or_insert_with(||{
|
||||
let graphics_group_id=graphics_groups.len();
|
||||
graphics_groups.push(model::IndexedGraphicsGroup{
|
||||
render:render_id,
|
||||
groups:vec![],
|
||||
});
|
||||
graphics_group_id
|
||||
});
|
||||
graphics_groups[graphics_group_id].groups.push(polygon_group_id);
|
||||
}
|
||||
physics_group.groups.push(polygon_group_id);
|
||||
model::PolygonGroup::PolygonList(model::PolygonList::new(polygon_list))
|
||||
}).collect();
|
||||
model::Mesh{
|
||||
unique_pos:spam_pos,
|
||||
unique_tex:spam_tex,
|
||||
unique_normal:spam_normal,
|
||||
unique_color:vec![glam::Vec4::ONE],
|
||||
unique_vertices:spam_vertices,
|
||||
polygon_groups,
|
||||
graphics_groups,
|
||||
physics_groups:vec![physics_group],
|
||||
}
|
||||
|
||||
mb.build(polygon_groups,graphics_groups,vec![])
|
||||
}).collect();
|
||||
|
||||
let world_models:Vec<model::Model>=
|
||||
//one instance of the main world mesh
|
||||
std::iter::once((
|
||||
//world_model
|
||||
model::MeshId::new(0),
|
||||
//model_origin
|
||||
vbsp::Vector::from([0.0,0.0,0.0]),
|
||||
//model_color
|
||||
vbsp::Color{r:255,g:255,b:255},
|
||||
)).chain(
|
||||
//entities sprinkle instances of the other meshes around
|
||||
bsp.entities.iter()
|
||||
.flat_map(|ent|ent.parse())//ignore entity parsing errors
|
||||
.filter_map(|ent|match ent{
|
||||
vbsp::Entity::Brush(brush)=>Some(brush),
|
||||
vbsp::Entity::BrushIllusionary(brush)=>Some(brush),
|
||||
vbsp::Entity::BrushWall(brush)=>Some(brush),
|
||||
vbsp::Entity::BrushWallToggle(brush)=>Some(brush),
|
||||
_=>None,
|
||||
}).flat_map(|brush|
|
||||
//The first character of brush.model is '*'
|
||||
brush.model[1..].parse().map(|mesh_id|//ignore parse int errors
|
||||
(model::MeshId::new(mesh_id),brush.origin,brush.color)
|
||||
)
|
||||
)
|
||||
).map(|(mesh_id,model_origin,vbsp::Color{r,g,b})|{
|
||||
model::Model{
|
||||
mesh:mesh_id,
|
||||
attributes:TEMP_TOUCH_ME_ATTRIBUTE,
|
||||
transform:integer::Planar64Affine3::new(
|
||||
integer::mat3::identity(),
|
||||
valve_transform(model_origin.into())
|
||||
),
|
||||
color:(glam::Vec3::from_array([r as f32,g as f32,b as f32])/255.0).extend(1.0),
|
||||
let mut found_spawn=None;
|
||||
|
||||
let mut world_models=Vec::new();
|
||||
|
||||
// the one and only world model 0
|
||||
world_models.push(model::Model{
|
||||
mesh:model::MeshId::new(0),
|
||||
attributes:ATTRIBUTE_DECORATION,
|
||||
transform:integer::Planar64Affine3::IDENTITY,
|
||||
color:glam::Vec4::W,
|
||||
});
|
||||
|
||||
const WHITE:vbsp::Color=vbsp::Color{r:255,g:255,b:255};
|
||||
for raw_ent in &bsp.entities{
|
||||
match raw_ent.parse(){
|
||||
Ok(Entity::Cycler(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::EnvSprite(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncBreakable(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncBrush(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncButton(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncDoor(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncDoorRotating(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncIllusionary(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncMonitor(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncMovelinear(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncPhysbox(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncPhysboxMultiplayer(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncRotButton(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncRotating(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncTracktrain(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncTrain(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncWall(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin.unwrap_or_default(),brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncWallToggle(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin.unwrap_or_default(),brush.rendercolor,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::FuncWaterAnalog(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,brush.rendercolor.unwrap_or(WHITE),ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::PropDoorRotating(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::PropDynamic(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::PropDynamicOverride(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::PropPhysics(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::PropPhysicsMultiplayer(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::PropPhysicsOverride(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::PropRagdoll(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::TriggerGravity(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::TriggerHurt(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::TriggerLook(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::TriggerMultiple(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model.unwrap_or_default(),brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::TriggerOnce(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::TriggerProximity(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::TriggerPush(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::TriggerSoundscape(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::TriggerTeleport(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model.unwrap_or_default(),brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::TriggerVphysicsMotion(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::TriggerWind(brush))=>add_brush(mesh_deferred_loader,&mut world_models,&mut prop_models,brush.model,brush.origin,WHITE,ATTRIBUTE_DECORATION),
|
||||
Ok(Entity::InfoPlayerCounterterrorist(spawn))=>{
|
||||
found_spawn=Some(valve_transform(spawn.origin.into()));
|
||||
},
|
||||
Ok(Entity::InfoPlayerTerrorist(spawn))=>{
|
||||
found_spawn=Some(valve_transform(spawn.origin.into()));
|
||||
},
|
||||
Err(e)=>{
|
||||
println!("Bsp Entity parse error: {e}");
|
||||
},
|
||||
_=>(),
|
||||
}
|
||||
}).collect();
|
||||
}
|
||||
|
||||
// physics models
|
||||
for brush in &bsp.brushes{
|
||||
const RELEVANT:vbsp::BrushFlags=
|
||||
vbsp::BrushFlags::SOLID
|
||||
.union(vbsp::BrushFlags::PLAYERCLIP)
|
||||
.union(vbsp::BrushFlags::WATER)
|
||||
.union(vbsp::BrushFlags::MOVEABLE)
|
||||
.union(vbsp::BrushFlags::LADDER);
|
||||
if !brush.flags.intersects(RELEVANT){
|
||||
continue;
|
||||
}
|
||||
let is_ladder=brush.flags.contains(vbsp::BrushFlags::LADDER);
|
||||
let is_water=brush.flags.contains(vbsp::BrushFlags::WATER);
|
||||
let attributes=match (is_ladder,is_water){
|
||||
(true,false)=>ATTRIBUTE_LADDER_DEFAULT,
|
||||
(false,true)=>ATTRIBUTE_WATER_DEFAULT,
|
||||
(false,false)=>ATTRIBUTE_CONTACT_DEFAULT,
|
||||
(true,true)=>{
|
||||
// water ladder? wtf
|
||||
println!("brush is a water ladder o_o defaulting to ladder");
|
||||
ATTRIBUTE_LADDER_DEFAULT
|
||||
}
|
||||
};
|
||||
let mesh_result=crate::brush::brush_to_mesh(bsp,brush);
|
||||
match mesh_result{
|
||||
Ok(mesh)=>{
|
||||
let mesh_id=model::MeshId::new(world_meshes.len() as u32);
|
||||
world_meshes.push(mesh);
|
||||
world_models.push(model::Model{
|
||||
mesh:mesh_id,
|
||||
attributes,
|
||||
transform:integer::Planar64Affine3::new(
|
||||
integer::mat3::identity(),
|
||||
integer::vec3::zero(),
|
||||
),
|
||||
color:glam::Vec4::ONE,
|
||||
});
|
||||
},
|
||||
Err(e)=>println!("Brush mesh error: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
let mut modes_list=Vec::new();
|
||||
if let Some(spawn_point)=found_spawn{
|
||||
// create a new mesh
|
||||
let mesh_id=model::MeshId::new(world_meshes.len() as u32);
|
||||
world_meshes.push(crate::brush::unit_cube());
|
||||
// create a new model
|
||||
let model_id=model::ModelId::new(world_models.len() as u32);
|
||||
world_models.push(model::Model{
|
||||
mesh:mesh_id,
|
||||
attributes:ATTRIBUTE_INTERSECT_DEFAULT,
|
||||
transform:integer::Planar64Affine3::from_translation(spawn_point),
|
||||
color:glam::Vec4::W,
|
||||
});
|
||||
|
||||
let first_stage=Stage::empty(model_id);
|
||||
let main_mode=Mode::new(
|
||||
strafesnet_common::gameplay_style::StyleModifiers::source_bhop(),
|
||||
model_id,
|
||||
std::collections::HashMap::new(),
|
||||
vec![first_stage],
|
||||
std::collections::HashMap::new(),
|
||||
);
|
||||
modes_list.push(NormalizedMode::new(main_mode));
|
||||
}
|
||||
|
||||
PartialMap1{
|
||||
attributes:unique_attributes,
|
||||
world_meshes,
|
||||
prop_models,
|
||||
world_models,
|
||||
modes:strafesnet_common::gameplay_modes::Modes::new(Vec::new()),
|
||||
modes:NormalizedModes::new(modes_list),
|
||||
}
|
||||
}
|
||||
|
||||
//partially constructed map types
|
||||
pub struct PartialMap1{
|
||||
attributes:Vec<strafesnet_common::gameplay_attributes::CollisionAttributes>,
|
||||
attributes:Vec<attr::CollisionAttributes>,
|
||||
prop_models:Vec<model::Model>,
|
||||
world_meshes:Vec<model::Mesh>,
|
||||
world_models:Vec<model::Model>,
|
||||
modes:strafesnet_common::gameplay_modes::Modes,
|
||||
modes:NormalizedModes,
|
||||
}
|
||||
impl PartialMap1{
|
||||
pub fn add_prop_meshes<AcquireRenderConfigId>(
|
||||
pub fn add_prop_meshes(
|
||||
self,
|
||||
prop_meshes:impl IntoIterator<Item=(model::MeshId,crate::data::ModelData)>,
|
||||
mut acquire_render_config_id:AcquireRenderConfigId,
|
||||
)->PartialMap2
|
||||
where
|
||||
AcquireRenderConfigId:FnMut(Option<&str>)->model::RenderConfigId,
|
||||
{
|
||||
prop_meshes:Meshes<model::Mesh>,
|
||||
)->PartialMap2{
|
||||
PartialMap2{
|
||||
attributes:self.attributes,
|
||||
prop_meshes:prop_meshes.into_iter().filter_map(|(mesh_id,model_data)|
|
||||
//this will generate new render ids and texture ids
|
||||
match convert_mesh(model_data,&mut acquire_render_config_id){
|
||||
Ok(mesh)=>Some((mesh_id,mesh)),
|
||||
Err(e)=>{
|
||||
println!("error converting mesh: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
).collect(),
|
||||
prop_meshes:prop_meshes.consume().collect(),
|
||||
prop_models:self.prop_models,
|
||||
world_meshes:self.world_meshes,
|
||||
world_models:self.world_models,
|
||||
@@ -204,18 +362,17 @@ impl PartialMap1{
|
||||
}
|
||||
}
|
||||
pub struct PartialMap2{
|
||||
attributes:Vec<strafesnet_common::gameplay_attributes::CollisionAttributes>,
|
||||
attributes:Vec<attr::CollisionAttributes>,
|
||||
prop_meshes:Vec<(model::MeshId,model::Mesh)>,
|
||||
prop_models:Vec<model::Model>,
|
||||
world_meshes:Vec<model::Mesh>,
|
||||
world_models:Vec<model::Model>,
|
||||
modes:strafesnet_common::gameplay_modes::Modes,
|
||||
modes:NormalizedModes,
|
||||
}
|
||||
impl PartialMap2{
|
||||
pub fn add_render_configs_and_textures(
|
||||
mut self,
|
||||
render_configs:impl IntoIterator<Item=(model::RenderConfigId,model::RenderConfig)>,
|
||||
textures:impl IntoIterator<Item=(model::TextureId,Vec<u8>)>,
|
||||
render_configs:RenderConfigs,
|
||||
)->map::CompleteMap{
|
||||
//merge mesh and model lists, flatten and remap all ids
|
||||
let mesh_id_offset=self.world_meshes.len();
|
||||
@@ -234,13 +391,14 @@ impl PartialMap2{
|
||||
})
|
||||
));
|
||||
//let mut models=Vec::new();
|
||||
let (textures,render_configs)=render_configs.consume();
|
||||
let (textures,texture_id_map):(Vec<Vec<u8>>,std::collections::HashMap<model::TextureId,model::TextureId>)
|
||||
=textures.into_iter()
|
||||
//.filter_map(f) cull unused textures
|
||||
.enumerate().map(|(new_texture_id,(old_texture_id,texture))|{
|
||||
.enumerate().map(|(new_texture_id,(old_texture_id,Texture::ImageDDS(texture)))|{
|
||||
(texture,(old_texture_id,model::TextureId::new(new_texture_id as u32)))
|
||||
}).unzip();
|
||||
let render_configs=render_configs.into_iter().map(|(render_config_id,mut render_config)|{
|
||||
let render_configs=render_configs.into_iter().map(|(_render_config_id,mut render_config)|{
|
||||
//this may generate duplicate no-texture render configs but idc
|
||||
render_config.texture=render_config.texture.and_then(|texture_id|
|
||||
texture_id_map.get(&texture_id).copied()
|
||||
@@ -257,77 +415,3 @@ impl PartialMap2{
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_mesh<AcquireRenderConfigId>(
|
||||
model_data:crate::data::ModelData,
|
||||
acquire_render_config_id:&mut AcquireRenderConfigId,
|
||||
)->Result<model::Mesh,vmdl::ModelError>
|
||||
where
|
||||
AcquireRenderConfigId:FnMut(Option<&str>)->model::RenderConfigId,
|
||||
{
|
||||
let model=model_data.read_model()?;
|
||||
let texture_paths=model.texture_directories();
|
||||
if texture_paths.len()!=1{
|
||||
println!("WARNING: multiple texture paths");
|
||||
}
|
||||
let skin=model.skin_tables().nth(0).unwrap();
|
||||
|
||||
let mut spam_pos=Vec::with_capacity(model.vertices().len());
|
||||
let mut spam_normal=Vec::with_capacity(model.vertices().len());
|
||||
let mut spam_tex=Vec::with_capacity(model.vertices().len());
|
||||
let mut spam_vertices=Vec::with_capacity(model.vertices().len());
|
||||
for (i,vertex) in model.vertices().iter().enumerate(){
|
||||
spam_pos.push(valve_transform(vertex.position.into()));
|
||||
spam_normal.push(valve_transform(vertex.normal.into()));
|
||||
spam_tex.push(glam::Vec2::from_array(vertex.texture_coordinates));
|
||||
spam_vertices.push(model::IndexedVertex{
|
||||
pos:model::PositionId::new(i as u32),
|
||||
tex:model::TextureCoordinateId::new(i as u32),
|
||||
normal:model::NormalId::new(i as u32),
|
||||
color:model::ColorId::new(0),
|
||||
});
|
||||
}
|
||||
let mut graphics_groups=Vec::new();
|
||||
let mut physics_groups=Vec::new();
|
||||
let polygon_groups=model.meshes().enumerate().map(|(polygon_group_id,mesh)|{
|
||||
let polygon_group_id=model::PolygonGroupId::new(polygon_group_id as u32);
|
||||
|
||||
let render_id=if let (Some(texture_path),Some(texture_name))=(texture_paths.get(0),skin.texture(mesh.material_index())){
|
||||
let mut path=std::path::PathBuf::from(texture_path.as_str());
|
||||
path.push(texture_name);
|
||||
acquire_render_config_id(path.as_os_str().to_str())
|
||||
}else{
|
||||
acquire_render_config_id(None)
|
||||
};
|
||||
|
||||
graphics_groups.push(model::IndexedGraphicsGroup{
|
||||
render:render_id,
|
||||
groups:vec![polygon_group_id],
|
||||
});
|
||||
physics_groups.push(model::IndexedPhysicsGroup{
|
||||
groups:vec![polygon_group_id],
|
||||
});
|
||||
model::PolygonGroup::PolygonList(model::PolygonList::new(
|
||||
//looking at the code, it would seem that the strips are pre-deindexed into triangle lists when calling this function
|
||||
mesh.vertex_strip_indices().flat_map(|mut strip|
|
||||
std::iter::from_fn(move||{
|
||||
match (strip.next(),strip.next(),strip.next()){
|
||||
(Some(v1),Some(v2),Some(v3))=>Some([v1,v2,v3].map(|vertex_id|model::VertexId::new(vertex_id as u32)).to_vec()),
|
||||
//ignore extra vertices, not sure what to do in this case, failing the whole conversion could be appropriate
|
||||
_=>None,
|
||||
}
|
||||
})
|
||||
).collect()
|
||||
))
|
||||
}).collect();
|
||||
Ok(model::Mesh{
|
||||
unique_pos:spam_pos,
|
||||
unique_normal:spam_normal,
|
||||
unique_tex:spam_tex,
|
||||
unique_color:vec![glam::Vec4::ONE],
|
||||
unique_vertices:spam_vertices,
|
||||
polygon_groups,
|
||||
graphics_groups,
|
||||
physics_groups,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
pub struct Bsp(vbsp::Bsp);
|
||||
impl Bsp{
|
||||
pub const fn new(value:vbsp::Bsp)->Self{
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
impl AsRef<vbsp::Bsp> for Bsp{
|
||||
fn as_ref(&self)->&vbsp::Bsp{
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MdlData(Vec<u8>);
|
||||
impl MdlData{
|
||||
pub const fn new(value:Vec<u8>)->Self{
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
impl AsRef<[u8]> for MdlData{
|
||||
fn as_ref(&self)->&[u8]{
|
||||
self.0.as_ref()
|
||||
}
|
||||
}
|
||||
pub struct VtxData(Vec<u8>);
|
||||
impl VtxData{
|
||||
pub const fn new(value:Vec<u8>)->Self{
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
impl AsRef<[u8]> for VtxData{
|
||||
fn as_ref(&self)->&[u8]{
|
||||
self.0.as_ref()
|
||||
}
|
||||
}
|
||||
pub struct VvdData(Vec<u8>);
|
||||
impl VvdData{
|
||||
pub const fn new(value:Vec<u8>)->Self{
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
impl AsRef<[u8]> for VvdData{
|
||||
fn as_ref(&self)->&[u8]{
|
||||
self.0.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ModelData{
|
||||
pub mdl:MdlData,
|
||||
pub vtx:VtxData,
|
||||
pub vvd:VvdData,
|
||||
}
|
||||
impl ModelData{
|
||||
pub fn read_model(&self)->Result<vmdl::Model,vmdl::ModelError>{
|
||||
Ok(vmdl::Model::from_parts(
|
||||
vmdl::mdl::Mdl::read(self.mdl.as_ref())?,
|
||||
vmdl::vtx::Vtx::read(self.vtx.as_ref())?,
|
||||
vmdl::vvd::Vvd::read(self.vvd.as_ref())?,
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,17 @@
|
||||
mod bsp;
|
||||
pub mod data;
|
||||
pub mod bsp;
|
||||
pub mod mesh;
|
||||
mod brush;
|
||||
|
||||
pub use data::Bsp;
|
||||
const VALVE_SCALE:f32=1.0/16.0;
|
||||
pub(crate) fn valve_transform_dist(d:f32)->strafesnet_common::integer::Planar64{
|
||||
(d*VALVE_SCALE).try_into().unwrap()
|
||||
}
|
||||
pub(crate) fn valve_transform_normal([x,y,z]:[f32;3])->strafesnet_common::integer::Planar64Vec3{
|
||||
strafesnet_common::integer::vec3::try_from_f32_array([x,z,-y]).unwrap()
|
||||
}
|
||||
pub(crate) fn valve_transform([x,y,z]:[f32;3])->strafesnet_common::integer::Planar64Vec3{
|
||||
strafesnet_common::integer::vec3::try_from_f32_array([x*VALVE_SCALE,z*VALVE_SCALE,-y*VALVE_SCALE]).unwrap()
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ReadError{
|
||||
@@ -15,6 +25,16 @@ impl std::fmt::Display for ReadError{
|
||||
}
|
||||
impl std::error::Error for ReadError{}
|
||||
|
||||
pub struct Bsp{
|
||||
bsp:vbsp::Bsp,
|
||||
case_folded_file_names:std::collections::HashMap<String,String>,
|
||||
}
|
||||
impl AsRef<vbsp::Bsp> for Bsp{
|
||||
fn as_ref(&self)->&vbsp::Bsp{
|
||||
&self.bsp
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read<R:std::io::Read>(mut input:R)->Result<Bsp,ReadError>{
|
||||
let mut s=Vec::new();
|
||||
|
||||
@@ -23,15 +43,44 @@ pub fn read<R:std::io::Read>(mut input:R)->Result<Bsp,ReadError>{
|
||||
|
||||
vbsp::Bsp::read(s.as_slice()).map(Bsp::new).map_err(ReadError::Bsp)
|
||||
}
|
||||
|
||||
pub fn convert<AcquireRenderConfigId,AcquireMeshId>(
|
||||
bsp:&Bsp,
|
||||
acquire_render_config_id:AcquireRenderConfigId,
|
||||
acquire_mesh_id:AcquireMeshId
|
||||
)->bsp::PartialMap1
|
||||
where
|
||||
AcquireRenderConfigId:FnMut(Option<&str>)->strafesnet_common::model::RenderConfigId,
|
||||
AcquireMeshId:FnMut(&str)->strafesnet_common::model::MeshId,
|
||||
{
|
||||
bsp::convert_bsp(bsp.as_ref(),acquire_render_config_id,acquire_mesh_id)
|
||||
}
|
||||
impl Bsp{
|
||||
pub fn new(bsp:vbsp::Bsp)->Self{
|
||||
let case_folded_file_names=bsp.pack.clone().into_zip().lock().unwrap().file_names().map(|s|{
|
||||
(s.to_lowercase(),s.to_owned())
|
||||
}).collect();
|
||||
Self{
|
||||
bsp,
|
||||
case_folded_file_names,
|
||||
}
|
||||
}
|
||||
pub fn pack_get(&self,name_lowercase:&str)->Result<Option<Vec<u8>>,vbsp::BspError>{
|
||||
match self.case_folded_file_names.get(name_lowercase){
|
||||
Some(name_folded)=>self.bsp.pack.get(name_folded),
|
||||
None=>Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct Vpk{
|
||||
vpk:vpk::VPK,
|
||||
case_folded_file_names:std::collections::HashMap<String,String>,
|
||||
}
|
||||
impl AsRef<vpk::VPK> for Vpk{
|
||||
fn as_ref(&self)->&vpk::VPK{
|
||||
&self.vpk
|
||||
}
|
||||
}
|
||||
impl Vpk{
|
||||
pub fn new(vpk:vpk::VPK)->Vpk{
|
||||
let case_folded_file_names=vpk.tree.keys().map(|s|{
|
||||
(s.to_lowercase(),s.to_owned())
|
||||
}).collect();
|
||||
Vpk{
|
||||
vpk,
|
||||
case_folded_file_names,
|
||||
}
|
||||
}
|
||||
pub fn tree_get(&self,name_lowercase:&str)->Option<&vpk::entry::VPKEntry>{
|
||||
let name_folded=self.case_folded_file_names.get(name_lowercase)?;
|
||||
self.vpk.tree.get(name_folded)
|
||||
}
|
||||
}
|
||||
|
||||
80
lib/bsp_loader/src/mesh.rs
Normal file
80
lib/bsp_loader/src/mesh.rs
Normal file
@@ -0,0 +1,80 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use strafesnet_common::model;
|
||||
use strafesnet_deferred_loader::deferred_loader::RenderConfigDeferredLoader;
|
||||
|
||||
use crate::valve_transform;
|
||||
|
||||
pub use model::Mesh;
|
||||
|
||||
fn ingest_vertex(mb:&mut model::MeshBuilder,vertex:&vmdl::vvd::Vertex,color:model::ColorId)->model::VertexId{
|
||||
let pos=mb.acquire_pos_id(valve_transform(vertex.position.into()));
|
||||
let normal=mb.acquire_normal_id(valve_transform(vertex.normal.into()));
|
||||
let tex=mb.acquire_tex_id(glam::Vec2::from_array(vertex.texture_coordinates));
|
||||
mb.acquire_vertex_id(model::IndexedVertex{
|
||||
pos,
|
||||
tex,
|
||||
normal,
|
||||
color,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn convert_mesh(model:vmdl::Model,deferred_loader:&mut RenderConfigDeferredLoader<Cow<str>>)->Mesh{
|
||||
let texture_paths=model.texture_directories();
|
||||
if texture_paths.len()!=1{
|
||||
println!("WARNING: multiple texture paths");
|
||||
}
|
||||
let skin=model.skin_tables().nth(0).unwrap();
|
||||
|
||||
let mut mb=model::MeshBuilder::new();
|
||||
|
||||
let color=mb.acquire_color_id(glam::Vec4::ONE);
|
||||
|
||||
let model_vertices=model.vertices();
|
||||
|
||||
let mut graphics_groups=Vec::new();
|
||||
let mut physics_groups=Vec::new();
|
||||
let polygon_groups=model.meshes().enumerate().map(|(polygon_group_id,mesh)|{
|
||||
let polygon_group_id=model::PolygonGroupId::new(polygon_group_id as u32);
|
||||
|
||||
let render_id=if let (Some(texture_path),Some(texture_name))=(texture_paths.get(0),skin.texture(mesh.material_index())){
|
||||
let mut path=std::path::PathBuf::from(texture_path.as_str());
|
||||
path.push(texture_name);
|
||||
let index=path.as_os_str().to_str().map(|s|Cow::Owned(s.to_owned()));
|
||||
deferred_loader.acquire_render_config_id(index)
|
||||
}else{
|
||||
deferred_loader.acquire_render_config_id(None)
|
||||
};
|
||||
|
||||
graphics_groups.push(model::IndexedGraphicsGroup{
|
||||
render:render_id,
|
||||
groups:vec![polygon_group_id],
|
||||
});
|
||||
physics_groups.push(model::IndexedPhysicsGroup{
|
||||
groups:vec![polygon_group_id],
|
||||
});
|
||||
model::PolygonGroup::PolygonList(model::PolygonList::new(
|
||||
//looking at the code, it would seem that the strips are pre-deindexed into triangle lists when calling this function
|
||||
mesh.vertex_strip_indices().flat_map(|mut strip|{
|
||||
std::iter::from_fn(move ||{
|
||||
match (strip.next(),strip.next(),strip.next()){
|
||||
(Some(v1),Some(v2),Some(v3))=>Some([v1,v2,v3]),
|
||||
//ignore extra vertices, not sure what to do in this case, failing the whole conversion could be appropriate
|
||||
_=>None,
|
||||
}
|
||||
})
|
||||
}).filter_map(|[v1,v2,v3]|{
|
||||
// this should probably be a fatal error :D
|
||||
let v1=model_vertices.get(v1)?;
|
||||
let v2=model_vertices.get(v2)?;
|
||||
let v3=model_vertices.get(v3)?;
|
||||
Some(vec![
|
||||
ingest_vertex(&mut mb,v1,color),
|
||||
ingest_vertex(&mut mb,v2,color),
|
||||
ingest_vertex(&mut mb,v3,color),
|
||||
])
|
||||
}).collect()
|
||||
))
|
||||
}).collect();
|
||||
mb.build(polygon_groups,graphics_groups,physics_groups)
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "strafesnet_common"
|
||||
version = "0.5.2"
|
||||
edition = "2021"
|
||||
version = "0.9.0"
|
||||
edition = "2024"
|
||||
repository = "https://git.itzana.me/StrafesNET/strafe-project"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Common types and helpers for Strafe Client associated projects."
|
||||
@@ -12,8 +12,11 @@ authors = ["Rhys Lloyd <krakow20@gmail.com>"]
|
||||
[dependencies]
|
||||
arrayvec = "0.7.4"
|
||||
bitflags = "2.6.0"
|
||||
fixed_wide = { path = "../fixed_wide", registry = "strafesnet", features = ["deferred-division","zeroes","wide-mul"] }
|
||||
linear_ops = { path = "../linear_ops", registry = "strafesnet", features = ["deferred-division","named-fields"] }
|
||||
ratio_ops = { path = "../ratio_ops", registry = "strafesnet" }
|
||||
glam = "0.29.0"
|
||||
fixed_wide = { workspace = true, features = ["deferred-division","zeroes","wide-mul"] }
|
||||
linear_ops = { workspace = true, features = ["deferred-division","named-fields"] }
|
||||
ratio_ops = { workspace = true }
|
||||
glam.workspace = true
|
||||
id = { version = "0.1.0", registry = "strafesnet" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -2,53 +2,70 @@ use crate::integer::{vec3,Planar64Vec3};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Aabb{
|
||||
// min is inclusive
|
||||
min:Planar64Vec3,
|
||||
// max is not inclusive
|
||||
max:Planar64Vec3,
|
||||
}
|
||||
|
||||
impl Default for Aabb{
|
||||
#[inline]
|
||||
fn default()->Self{
|
||||
Self{min:vec3::MAX,max:vec3::MIN}
|
||||
}
|
||||
}
|
||||
|
||||
impl Aabb{
|
||||
#[inline]
|
||||
pub const fn new(min:Planar64Vec3,max:Planar64Vec3)->Self{
|
||||
Self{min,max}
|
||||
}
|
||||
#[inline]
|
||||
pub const fn max(&self)->Planar64Vec3{
|
||||
self.max
|
||||
}
|
||||
#[inline]
|
||||
pub const fn min(&self)->Planar64Vec3{
|
||||
self.min
|
||||
}
|
||||
#[inline]
|
||||
pub fn grow(&mut self,point:Planar64Vec3){
|
||||
self.min=self.min.min(point);
|
||||
self.max=self.max.max(point);
|
||||
}
|
||||
#[inline]
|
||||
pub fn join(&mut self,aabb:&Aabb){
|
||||
self.min=self.min.min(aabb.min);
|
||||
self.max=self.max.max(aabb.max);
|
||||
}
|
||||
#[inline]
|
||||
pub fn inflate(&mut self,hs:Planar64Vec3){
|
||||
self.min-=hs;
|
||||
self.max+=hs;
|
||||
}
|
||||
#[inline]
|
||||
pub fn contains(&self,point:Planar64Vec3)->bool{
|
||||
let bvec=self.min.le(point)&point.lt(self.max);
|
||||
bvec.all()
|
||||
}
|
||||
#[inline]
|
||||
pub fn intersects(&self,aabb:&Aabb)->bool{
|
||||
let bvec=self.min.lt(aabb.max)&aabb.min.lt(self.max);
|
||||
bvec.all()
|
||||
}
|
||||
#[inline]
|
||||
pub fn size(&self)->Planar64Vec3{
|
||||
self.max-self.min
|
||||
}
|
||||
#[inline]
|
||||
pub fn center(&self)->Planar64Vec3{
|
||||
self.min+(self.max-self.min)>>1
|
||||
self.min.map_zip(self.max,|(min,max)|min.midpoint(max))
|
||||
}
|
||||
#[inline]
|
||||
pub fn area_weight(&self)->fixed_wide::types::F128_64{
|
||||
let d=self.max-self.min;
|
||||
d.x*d.y+d.y*d.z+d.z*d.x
|
||||
}
|
||||
//probably use floats for area & volume because we don't care about precision
|
||||
// pub fn area_weight(&self)->f32{
|
||||
// let d=self.max-self.min;
|
||||
// d.x*d.y+d.y*d.z+d.z*d.x
|
||||
// }
|
||||
// pub fn volume(&self)->f32{
|
||||
// let d=self.max-self.min;
|
||||
// d.x*d.y*d.z
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::aabb::Aabb;
|
||||
use crate::ray::Ray;
|
||||
use crate::integer::{Ratio,Planar64,Planar64Vec3};
|
||||
use crate::instruction::{InstructionCollector,TimedInstruction};
|
||||
|
||||
//da algaritum
|
||||
//lista boxens
|
||||
@@ -10,35 +16,117 @@ use crate::aabb::Aabb;
|
||||
//sort the centerpoints on each axis (3 lists)
|
||||
//bv is put into octant based on whether it is upper or lower in each list
|
||||
|
||||
pub enum RecursiveContent<R,T>{
|
||||
Branch(Vec<R>),
|
||||
Leaf(T),
|
||||
|
||||
pub fn intersect_aabb(ray:&Ray,aabb:&Aabb)->Option<Ratio<Planar64,Planar64>>{
|
||||
// n.(o+d*t)==n.p
|
||||
// n.o + n.d * t == n.p
|
||||
// t == (n.p - n.o)/n.d
|
||||
let mut hit=None;
|
||||
match ray.direction.x.cmp(&Planar64::ZERO){
|
||||
Ordering::Less=>{
|
||||
let rel_min=aabb.min()-ray.origin;
|
||||
let rel_max=aabb.max()-ray.origin;
|
||||
let dy=rel_max.x*ray.direction.y;
|
||||
let dz=rel_max.x*ray.direction.z;
|
||||
// x is negative, so inequalities are flipped
|
||||
if rel_min.y*ray.direction.x>dy&&dy>rel_max.y*ray.direction.x
|
||||
&&rel_min.z*ray.direction.x>dz&&dz>rel_max.z*ray.direction.x{
|
||||
let t=rel_max.x/ray.direction.x;
|
||||
hit=Some(hit.map_or(t,|best_t|t.min(best_t)));
|
||||
}
|
||||
},
|
||||
Ordering::Equal=>(),
|
||||
Ordering::Greater=>{
|
||||
let rel_min=aabb.min()-ray.origin;
|
||||
let rel_max=aabb.max()-ray.origin;
|
||||
let dy=rel_min.x*ray.direction.y;
|
||||
let dz=rel_min.x*ray.direction.z;
|
||||
// x is positive, so inequalities are normal
|
||||
if rel_min.y*ray.direction.x<dy&&dy<rel_max.y*ray.direction.x
|
||||
&&rel_min.z*ray.direction.x<dz&&dz<rel_max.z*ray.direction.x{
|
||||
let t=rel_min.x/ray.direction.x;
|
||||
hit=Some(hit.map_or(t,|best_t|t.min(best_t)));
|
||||
}
|
||||
},
|
||||
}
|
||||
match ray.direction.z.cmp(&Planar64::ZERO){
|
||||
Ordering::Less=>{
|
||||
let rel_min=aabb.min()-ray.origin;
|
||||
let rel_max=aabb.max()-ray.origin;
|
||||
let dx=rel_max.z*ray.direction.x;
|
||||
let dy=rel_max.z*ray.direction.y;
|
||||
// z is negative, so inequalities are flipped
|
||||
if rel_min.x*ray.direction.z>dx&&dx>rel_max.x*ray.direction.z
|
||||
&&rel_min.y*ray.direction.z>dy&&dy>rel_max.y*ray.direction.z{
|
||||
let t=rel_max.z/ray.direction.z;
|
||||
hit=Some(hit.map_or(t,|best_t|t.min(best_t)));
|
||||
}
|
||||
},
|
||||
Ordering::Equal=>(),
|
||||
Ordering::Greater=>{
|
||||
let rel_min=aabb.min()-ray.origin;
|
||||
let rel_max=aabb.max()-ray.origin;
|
||||
let dx=rel_min.z*ray.direction.x;
|
||||
let dy=rel_min.z*ray.direction.y;
|
||||
// z is positive, so inequalities are normal
|
||||
if rel_min.x*ray.direction.z<dx&&dx<rel_max.x*ray.direction.z
|
||||
&&rel_min.y*ray.direction.z<dy&&dy<rel_max.y*ray.direction.z{
|
||||
let t=rel_min.z/ray.direction.z;
|
||||
hit=Some(hit.map_or(t,|best_t|t.min(best_t)));
|
||||
}
|
||||
},
|
||||
}
|
||||
match ray.direction.y.cmp(&Planar64::ZERO){
|
||||
Ordering::Less=>{
|
||||
let rel_min=aabb.min()-ray.origin;
|
||||
let rel_max=aabb.max()-ray.origin;
|
||||
let dz=rel_max.y*ray.direction.z;
|
||||
let dx=rel_max.y*ray.direction.x;
|
||||
// y is negative, so inequalities are flipped
|
||||
if rel_min.z*ray.direction.y>dz&&dz>rel_max.z*ray.direction.y
|
||||
&&rel_min.x*ray.direction.y>dx&&dx>rel_max.x*ray.direction.y{
|
||||
let t=rel_max.y/ray.direction.y;
|
||||
hit=Some(hit.map_or(t,|best_t|t.min(best_t)));
|
||||
}
|
||||
},
|
||||
Ordering::Equal=>(),
|
||||
Ordering::Greater=>{
|
||||
let rel_min=aabb.min()-ray.origin;
|
||||
let rel_max=aabb.max()-ray.origin;
|
||||
let dz=rel_min.y*ray.direction.z;
|
||||
let dx=rel_min.y*ray.direction.x;
|
||||
// y is positive, so inequalities are normal
|
||||
if rel_min.z*ray.direction.y<dz&&dz<rel_max.z*ray.direction.y
|
||||
&&rel_min.x*ray.direction.y<dx&&dx<rel_max.x*ray.direction.y{
|
||||
let t=rel_min.y/ray.direction.y;
|
||||
hit=Some(hit.map_or(t,|best_t|t.min(best_t)));
|
||||
}
|
||||
},
|
||||
}
|
||||
hit
|
||||
}
|
||||
impl<R,T> Default for RecursiveContent<R,T>{
|
||||
fn default()->Self{
|
||||
|
||||
pub enum RecursiveContent<N,L>{
|
||||
Branch(Vec<N>),
|
||||
Leaf(L),
|
||||
}
|
||||
impl<N,L> RecursiveContent<N,L>{
|
||||
pub fn empty()->Self{
|
||||
Self::Branch(Vec::new())
|
||||
}
|
||||
}
|
||||
pub struct BvhNode<T>{
|
||||
content:RecursiveContent<BvhNode<T>,T>,
|
||||
pub struct BvhNode<L>{
|
||||
content:RecursiveContent<BvhNode<L>,L>,
|
||||
aabb:Aabb,
|
||||
}
|
||||
impl<T> Default for BvhNode<T>{
|
||||
fn default()->Self{
|
||||
impl<L> BvhNode<L>{
|
||||
pub fn empty()->Self{
|
||||
Self{
|
||||
content:Default::default(),
|
||||
content:RecursiveContent::empty(),
|
||||
aabb:Aabb::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
pub struct BvhWeightNode<W,T>{
|
||||
content:RecursiveContent<BvhWeightNode<W,T>,T>,
|
||||
weight:W,
|
||||
aabb:Aabb,
|
||||
}
|
||||
|
||||
impl<T> BvhNode<T>{
|
||||
pub fn the_tester<F:FnMut(&T)>(&self,aabb:&Aabb,f:&mut F){
|
||||
pub fn sample_aabb<F:FnMut(&L)>(&self,aabb:&Aabb,f:&mut F){
|
||||
match &self.content{
|
||||
RecursiveContent::Leaf(model)=>f(model),
|
||||
RecursiveContent::Branch(children)=>for child in children{
|
||||
@@ -47,51 +135,104 @@ impl<T> BvhNode<T>{
|
||||
//you're probably not going to spend a lot of time outside the map,
|
||||
//so the test is extra work for nothing
|
||||
if aabb.intersects(&child.aabb){
|
||||
child.the_tester(aabb,f);
|
||||
child.sample_aabb(aabb,f);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
pub fn into_visitor<F:FnMut(T)>(self,f:&mut F){
|
||||
match self.content{
|
||||
RecursiveContent::Leaf(model)=>f(model),
|
||||
fn populate_nodes<'a,T,IntersectLeaf,IntersectAabb>(
|
||||
&'a self,
|
||||
start_point:Planar64Vec3,
|
||||
collector:&mut InstructionCollector<&'a L,T>,
|
||||
nodes:&mut BTreeMap<T,&'a BvhNode<L>>,
|
||||
start_time:T,
|
||||
intersect_leaf:&IntersectLeaf,
|
||||
intersect_aabb:&IntersectAabb,
|
||||
)
|
||||
where
|
||||
T:Ord+Copy,
|
||||
IntersectLeaf:Fn(&L)->Option<T>,
|
||||
IntersectAabb:Fn(&Aabb)->Option<T>,
|
||||
{
|
||||
match &self.content{
|
||||
RecursiveContent::Leaf(leaf)=>if let Some(time)=intersect_leaf(leaf){
|
||||
let ins=TimedInstruction{time,instruction:leaf};
|
||||
if start_time<ins.time&&ins.time<collector.time(){
|
||||
collector.collect(Some(ins));
|
||||
}
|
||||
},
|
||||
RecursiveContent::Branch(children)=>for child in children{
|
||||
child.into_visitor(f)
|
||||
},
|
||||
}
|
||||
}
|
||||
pub fn weigh_contents<W:Copy+std::iter::Sum<W>,F:Fn(&T)->W>(self,f:&F)->BvhWeightNode<W,T>{
|
||||
match self.content{
|
||||
RecursiveContent::Leaf(model)=>BvhWeightNode{
|
||||
weight:f(&model),
|
||||
content:RecursiveContent::Leaf(model),
|
||||
aabb:self.aabb,
|
||||
},
|
||||
RecursiveContent::Branch(children)=>{
|
||||
let branch:Vec<BvhWeightNode<W,T>>=children.into_iter().map(|child|
|
||||
child.weigh_contents(f)
|
||||
).collect();
|
||||
BvhWeightNode{
|
||||
weight:branch.iter().map(|node|node.weight).sum(),
|
||||
content:RecursiveContent::Branch(branch),
|
||||
aabb:self.aabb,
|
||||
if child.aabb.contains(start_point){
|
||||
child.populate_nodes(start_point,collector,nodes,start_time,intersect_leaf,intersect_aabb);
|
||||
}else{
|
||||
// Am I an upcoming superstar?
|
||||
if let Some(t)=intersect_aabb(&child.aabb){
|
||||
if start_time<t&&t<collector.time(){
|
||||
nodes.insert(t,child);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Traverse the BVH using the given sampling functions.
|
||||
/// Nodes are tested in order of T returned by IntersectAabb.
|
||||
/// The algorithm ends when T for the next node to test is
|
||||
/// greater than the current best collected T from IntersectLeaf.
|
||||
pub fn traverse<T,IntersectLeaf,IntersectAabb>(
|
||||
&self,
|
||||
start_point:Planar64Vec3,
|
||||
start_time:T,
|
||||
time_limit:T,
|
||||
intersect_leaf:IntersectLeaf,
|
||||
intersect_aabb:IntersectAabb,
|
||||
)->Option<(T,&L)>
|
||||
where
|
||||
T:Ord+Copy,
|
||||
IntersectLeaf:Fn(&L)->Option<T>,
|
||||
IntersectAabb:Fn(&Aabb)->Option<T>,
|
||||
{
|
||||
// source of nondeterminism when Aabb boundaries are coplanar
|
||||
let mut nodes=BTreeMap::new();
|
||||
|
||||
impl <W,T> BvhWeightNode<W,T>{
|
||||
pub const fn weight(&self)->&W{
|
||||
&self.weight
|
||||
let mut collector=InstructionCollector::new(time_limit);
|
||||
// break open all nodes that contain ray.origin and populate nodes with future intersection times
|
||||
self.populate_nodes(start_point,&mut collector,&mut nodes,start_time,&intersect_leaf,&intersect_aabb);
|
||||
|
||||
// swim through nodes one at a time
|
||||
while let Some((t,node))=nodes.pop_first(){
|
||||
if collector.time()<t{
|
||||
break;
|
||||
}
|
||||
match &node.content{
|
||||
RecursiveContent::Leaf(leaf)=>if let Some(time)=intersect_leaf(leaf){
|
||||
let ins=TimedInstruction{time:time.into(),instruction:leaf};
|
||||
// this lower bound can also be omitted
|
||||
// but it causes type inference errors lol
|
||||
if start_time<ins.time&&ins.time<collector.time(){
|
||||
collector.collect(Some(ins));
|
||||
}
|
||||
},
|
||||
// break open the node and predict collisions with the child nodes
|
||||
RecursiveContent::Branch(children)=>for child in children{
|
||||
// Am I an upcoming superstar?
|
||||
if let Some(t)=intersect_aabb(&child.aabb){
|
||||
// we don't need to check the lower bound
|
||||
// because child aabbs are guaranteed to be within the parent bounds.
|
||||
if t<collector.time(){
|
||||
nodes.insert(t,child);
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
collector.take().map(|TimedInstruction{time,instruction:leaf}|(time.into(),leaf))
|
||||
}
|
||||
pub const fn aabb(&self)->&Aabb{
|
||||
&self.aabb
|
||||
pub fn into_inner(self)->(RecursiveContent<BvhNode<L>,L>,Aabb){
|
||||
(self.content,self.aabb)
|
||||
}
|
||||
pub fn into_content(self)->RecursiveContent<BvhWeightNode<W,T>,T>{
|
||||
self.content
|
||||
}
|
||||
pub fn into_visitor<F:FnMut(T)>(self,f:&mut F){
|
||||
pub fn into_visitor<F:FnMut(L)>(self,f:&mut F){
|
||||
match self.content{
|
||||
RecursiveContent::Leaf(model)=>f(model),
|
||||
RecursiveContent::Branch(children)=>for child in children{
|
||||
@@ -107,18 +248,19 @@ pub fn generate_bvh<T>(boxen:Vec<(T,Aabb)>)->BvhNode<T>{
|
||||
|
||||
fn generate_bvh_node<T>(boxen:Vec<(T,Aabb)>,force:bool)->BvhNode<T>{
|
||||
let n=boxen.len();
|
||||
if force||n<20{
|
||||
let mut aabb=Aabb::default();
|
||||
let nodes=boxen.into_iter().map(|b|{
|
||||
aabb.join(&b.1);
|
||||
const MAX_TERMINAL_BRANCH_LEAF_NODES:usize=20;
|
||||
if force||n<MAX_TERMINAL_BRANCH_LEAF_NODES{
|
||||
let mut aabb_outer=Aabb::default();
|
||||
let nodes=boxen.into_iter().map(|(data,aabb)|{
|
||||
aabb_outer.join(&aabb);
|
||||
BvhNode{
|
||||
content:RecursiveContent::Leaf(b.0),
|
||||
aabb:b.1,
|
||||
content:RecursiveContent::Leaf(data),
|
||||
aabb,
|
||||
}
|
||||
}).collect();
|
||||
BvhNode{
|
||||
content:RecursiveContent::Branch(nodes),
|
||||
aabb,
|
||||
aabb:aabb_outer,
|
||||
}
|
||||
}else{
|
||||
let mut sort_x=Vec::with_capacity(n);
|
||||
@@ -130,13 +272,13 @@ fn generate_bvh_node<T>(boxen:Vec<(T,Aabb)>,force:bool)->BvhNode<T>{
|
||||
sort_y.push((i,center.y));
|
||||
sort_z.push((i,center.z));
|
||||
}
|
||||
sort_x.sort_by(|tup0,tup1|tup0.1.cmp(&tup1.1));
|
||||
sort_y.sort_by(|tup0,tup1|tup0.1.cmp(&tup1.1));
|
||||
sort_z.sort_by(|tup0,tup1|tup0.1.cmp(&tup1.1));
|
||||
sort_x.sort_by_key(|&(_,c)|c);
|
||||
sort_y.sort_by_key(|&(_,c)|c);
|
||||
sort_z.sort_by_key(|&(_,c)|c);
|
||||
let h=n/2;
|
||||
let median_x=sort_x[h].1;
|
||||
let median_y=sort_y[h].1;
|
||||
let median_z=sort_z[h].1;
|
||||
let (_,median_x)=sort_x[h];
|
||||
let (_,median_y)=sort_y[h];
|
||||
let (_,median_z)=sort_z[h];
|
||||
//locate a run of values equal to the median
|
||||
//partition point gives the first index for which the predicate evaluates to false
|
||||
let first_index_eq_median_x=sort_x.partition_point(|&(_,x)|x<median_x);
|
||||
@@ -175,10 +317,10 @@ fn generate_bvh_node<T>(boxen:Vec<(T,Aabb)>,force:bool)->BvhNode<T>{
|
||||
};
|
||||
list_list[list_id].push((data,aabb));
|
||||
}
|
||||
let mut aabb=Aabb::default();
|
||||
if list_list.len()==1{
|
||||
generate_bvh_node(list_list.remove(0),true)
|
||||
}else{
|
||||
let mut aabb=Aabb::default();
|
||||
BvhNode{
|
||||
content:RecursiveContent::Branch(
|
||||
list_list.into_iter().map(|b|{
|
||||
|
||||
@@ -171,4 +171,7 @@ impl CollisionAttributes{
|
||||
pub fn contact_default()->Self{
|
||||
Self::Contact(ContactAttributes::default())
|
||||
}
|
||||
pub fn intersect_default()->Self{
|
||||
Self::Intersect(IntersectAttributes::default())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use std::collections::{HashSet,HashMap};
|
||||
use crate::model::ModelId;
|
||||
use crate::gameplay_style;
|
||||
use crate::updatable::Updatable;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct StageElement{
|
||||
@@ -128,18 +127,6 @@ impl Stage{
|
||||
self.unordered_checkpoints.contains(&model_id)
|
||||
}
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct StageUpdate{
|
||||
//other behaviour models of this stage can have
|
||||
ordered_checkpoints:HashMap<CheckpointId,ModelId>,
|
||||
unordered_checkpoints:HashSet<ModelId>,
|
||||
}
|
||||
impl Updatable<StageUpdate> for Stage{
|
||||
fn update(&mut self,update:StageUpdate){
|
||||
self.ordered_checkpoints.extend(update.ordered_checkpoints);
|
||||
self.unordered_checkpoints.extend(update.unordered_checkpoints);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq)]
|
||||
pub enum Zone{
|
||||
@@ -153,6 +140,15 @@ impl ModeId{
|
||||
pub const MAIN:Self=Self(0);
|
||||
pub const BONUS:Self=Self(1);
|
||||
}
|
||||
impl core::fmt::Display for ModeId{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->core::fmt::Result{
|
||||
match self{
|
||||
&Self::MAIN=>write!(f,"Main"),
|
||||
&Self::BONUS=>write!(f,"Bonus"),
|
||||
&Self(mode_id)=>write!(f,"Bonus{mode_id}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct Mode{
|
||||
style:gameplay_style::StyleModifiers,
|
||||
@@ -211,34 +207,47 @@ impl Mode{
|
||||
pub fn push_stage(&mut self,stage:Stage){
|
||||
self.stages.push(stage)
|
||||
}
|
||||
pub fn get_stage_mut(&mut self,stage:StageId)->Option<&mut Stage>{
|
||||
self.stages.get_mut(stage.0 as usize)
|
||||
pub fn get_stage_mut(&mut self,StageId(stage_id):StageId)->Option<&mut Stage>{
|
||||
self.stages.get_mut(stage_id as usize)
|
||||
}
|
||||
pub fn get_spawn_model_id(&self,stage:StageId)->Option<ModelId>{
|
||||
self.stages.get(stage.0 as usize).map(|s|s.spawn)
|
||||
pub fn get_spawn_model_id(&self,StageId(stage_id):StageId)->Option<ModelId>{
|
||||
self.stages.get(stage_id as usize).map(|s|s.spawn)
|
||||
}
|
||||
pub fn get_zone(&self,model_id:ModelId)->Option<&Zone>{
|
||||
self.zones.get(&model_id)
|
||||
}
|
||||
pub fn get_stage(&self,stage_id:StageId)->Option<&Stage>{
|
||||
self.stages.get(stage_id.0 as usize)
|
||||
pub fn get_stage(&self,StageId(stage_id):StageId)->Option<&Stage>{
|
||||
self.stages.get(stage_id as usize)
|
||||
}
|
||||
pub fn get_element(&self,model_id:ModelId)->Option<&StageElement>{
|
||||
self.elements.get(&model_id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct NormalizedMode(Mode);
|
||||
impl NormalizedMode{
|
||||
pub fn new(mode:Mode)->Self{
|
||||
Self(mode)
|
||||
}
|
||||
pub fn into_inner(self)->Mode{
|
||||
let Self(mode)=self;
|
||||
mode
|
||||
}
|
||||
//TODO: put this in the SNF
|
||||
pub fn denormalize_data(&mut self){
|
||||
pub fn denormalize(self)->Mode{
|
||||
let NormalizedMode(mut mode)=self;
|
||||
//expand and index normalized data
|
||||
self.zones.insert(self.start,Zone::Start);
|
||||
for (stage_id,stage) in self.stages.iter().enumerate(){
|
||||
self.elements.insert(stage.spawn,StageElement{
|
||||
mode.zones.insert(mode.start,Zone::Start);
|
||||
for (stage_id,stage) in mode.stages.iter().enumerate(){
|
||||
mode.elements.insert(stage.spawn,StageElement{
|
||||
stage_id:StageId(stage_id as u32),
|
||||
force:false,
|
||||
behaviour:StageElementBehaviour::SpawnAt,
|
||||
jump_limit:None,
|
||||
});
|
||||
for (_,&model) in &stage.ordered_checkpoints{
|
||||
self.elements.insert(model,StageElement{
|
||||
mode.elements.insert(model,StageElement{
|
||||
stage_id:StageId(stage_id as u32),
|
||||
force:false,
|
||||
behaviour:StageElementBehaviour::Checkpoint,
|
||||
@@ -246,7 +255,7 @@ impl Mode{
|
||||
});
|
||||
}
|
||||
for &model in &stage.unordered_checkpoints{
|
||||
self.elements.insert(model,StageElement{
|
||||
mode.elements.insert(model,StageElement{
|
||||
stage_id:StageId(stage_id as u32),
|
||||
force:false,
|
||||
behaviour:StageElementBehaviour::Checkpoint,
|
||||
@@ -254,53 +263,13 @@ impl Mode{
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//this would be nice as a macro
|
||||
#[derive(Default)]
|
||||
pub struct ModeUpdate{
|
||||
zones:HashMap<ModelId,Zone>,
|
||||
stages:HashMap<StageId,StageUpdate>,
|
||||
//mutually exlusive stage element behaviour
|
||||
elements:HashMap<ModelId,StageElement>,
|
||||
}
|
||||
impl Updatable<ModeUpdate> for Mode{
|
||||
fn update(&mut self,update:ModeUpdate){
|
||||
self.zones.extend(update.zones);
|
||||
for (stage,stage_update) in update.stages{
|
||||
if let Some(stage)=self.stages.get_mut(stage.0 as usize){
|
||||
stage.update(stage_update);
|
||||
}
|
||||
}
|
||||
self.elements.extend(update.elements);
|
||||
}
|
||||
}
|
||||
impl ModeUpdate{
|
||||
pub fn zone(model_id:ModelId,zone:Zone)->Self{
|
||||
let mut mu=Self::default();
|
||||
mu.zones.insert(model_id,zone);
|
||||
mu
|
||||
}
|
||||
pub fn stage(stage_id:StageId,stage_update:StageUpdate)->Self{
|
||||
let mut mu=Self::default();
|
||||
mu.stages.insert(stage_id,stage_update);
|
||||
mu
|
||||
}
|
||||
pub fn element(model_id:ModelId,element:StageElement)->Self{
|
||||
let mut mu=Self::default();
|
||||
mu.elements.insert(model_id,element);
|
||||
mu
|
||||
}
|
||||
pub fn map_stage_element_ids<F:Fn(StageId)->StageId>(&mut self,f:F){
|
||||
for (_,stage_element) in self.elements.iter_mut(){
|
||||
stage_element.stage_id=f(stage_element.stage_id);
|
||||
}
|
||||
mode
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default,Clone)]
|
||||
pub struct Modes{
|
||||
pub modes:Vec<Mode>,
|
||||
modes:Vec<Mode>,
|
||||
}
|
||||
impl Modes{
|
||||
pub const fn new(modes:Vec<Mode>)->Self{
|
||||
@@ -314,19 +283,191 @@ impl Modes{
|
||||
pub fn push_mode(&mut self,mode:Mode){
|
||||
self.modes.push(mode)
|
||||
}
|
||||
pub fn get_mode(&self,mode:ModeId)->Option<&Mode>{
|
||||
self.modes.get(mode.0 as usize)
|
||||
pub fn get_mode(&self,ModeId(mode_id):ModeId)->Option<&Mode>{
|
||||
self.modes.get(mode_id as usize)
|
||||
}
|
||||
}
|
||||
pub struct ModesUpdate{
|
||||
modes:HashMap<ModeId,ModeUpdate>,
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct NormalizedModes{
|
||||
modes:Vec<NormalizedMode>,
|
||||
}
|
||||
impl Updatable<ModesUpdate> for Modes{
|
||||
fn update(&mut self,update:ModesUpdate){
|
||||
for (mode,mode_update) in update.modes{
|
||||
if let Some(mode)=self.modes.get_mut(mode.0 as usize){
|
||||
mode.update(mode_update);
|
||||
}
|
||||
impl NormalizedModes{
|
||||
pub fn new(modes:Vec<NormalizedMode>)->Self{
|
||||
Self{modes}
|
||||
}
|
||||
pub fn len(&self)->usize{
|
||||
self.modes.len()
|
||||
}
|
||||
pub fn denormalize(self)->Modes{
|
||||
Modes{
|
||||
modes:self.modes.into_iter().map(NormalizedMode::denormalize).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl IntoIterator for NormalizedModes{
|
||||
type Item=<Vec<NormalizedMode> as IntoIterator>::Item;
|
||||
type IntoIter=<Vec<NormalizedMode> as IntoIterator>::IntoIter;
|
||||
fn into_iter(self)->Self::IntoIter{
|
||||
self.modes.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct StageUpdate{
|
||||
//other behaviour models of this stage can have
|
||||
ordered_checkpoints:HashMap<CheckpointId,ModelId>,
|
||||
unordered_checkpoints:HashSet<ModelId>,
|
||||
}
|
||||
impl StageUpdate{
|
||||
fn apply_to(self,stage:&mut Stage){
|
||||
stage.ordered_checkpoints.extend(self.ordered_checkpoints);
|
||||
stage.unordered_checkpoints.extend(self.unordered_checkpoints);
|
||||
}
|
||||
}
|
||||
|
||||
//this would be nice as a macro
|
||||
#[derive(Default)]
|
||||
pub struct ModeUpdate{
|
||||
zones:Option<(ModelId,Zone)>,
|
||||
stages:Option<(StageId,StageUpdate)>,
|
||||
//mutually exlusive stage element behaviour
|
||||
elements:Option<(ModelId,StageElement)>,
|
||||
}
|
||||
impl ModeUpdate{
|
||||
fn apply_to(self,mode:&mut Mode){
|
||||
mode.zones.extend(self.zones);
|
||||
if let Some((StageId(stage_id),stage_update))=self.stages{
|
||||
if let Some(stage)=mode.stages.get_mut(stage_id as usize){
|
||||
stage_update.apply_to(stage);
|
||||
}
|
||||
}
|
||||
mode.elements.extend(self.elements);
|
||||
}
|
||||
}
|
||||
impl ModeUpdate{
|
||||
pub fn zone(model_id:ModelId,zone:Zone)->Self{
|
||||
Self{
|
||||
zones:Some((model_id,zone)),
|
||||
stages:None,
|
||||
elements:None,
|
||||
}
|
||||
}
|
||||
pub fn stage(stage_id:StageId,stage_update:StageUpdate)->Self{
|
||||
Self{
|
||||
zones:None,
|
||||
stages:Some((stage_id,stage_update)),
|
||||
elements:None,
|
||||
}
|
||||
}
|
||||
pub fn element(model_id:ModelId,element:StageElement)->Self{
|
||||
Self{
|
||||
zones:None,
|
||||
stages:None,
|
||||
elements:Some((model_id,element)),
|
||||
}
|
||||
}
|
||||
pub fn map_stage_element_ids<F:Fn(StageId)->StageId>(&mut self,f:F){
|
||||
for (_,stage_element) in self.elements.iter_mut(){
|
||||
stage_element.stage_id=f(stage_element.stage_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ModeBuilder{
|
||||
mode:Mode,
|
||||
stage_id_map:HashMap<StageId,StageId>,
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct ModesBuilder{
|
||||
modes:HashMap<ModeId,Mode>,
|
||||
stages:HashMap<ModeId,HashMap<StageId,Stage>>,
|
||||
mode_updates:Vec<(ModeId,ModeUpdate)>,
|
||||
stage_updates:Vec<(ModeId,StageId,StageUpdate)>,
|
||||
}
|
||||
impl ModesBuilder{
|
||||
pub fn build_normalized(mut self)->NormalizedModes{
|
||||
//collect modes and stages into contiguous arrays
|
||||
let mut unique_modes:Vec<(ModeId,Mode)>
|
||||
=self.modes.into_iter().collect();
|
||||
unique_modes.sort_by_key(|&(mode_id,_)|mode_id);
|
||||
let (mut modes,mode_id_map):(Vec<ModeBuilder>,HashMap<ModeId,ModeId>)
|
||||
=unique_modes.into_iter().enumerate()
|
||||
.map(|(final_mode_id,(builder_mode_id,mut mode))|{
|
||||
(
|
||||
ModeBuilder{
|
||||
stage_id_map:self.stages.remove(&builder_mode_id).map_or_else(||HashMap::new(),|stages|{
|
||||
let mut unique_stages:Vec<(StageId,Stage)>
|
||||
=stages.into_iter().collect();
|
||||
unique_stages.sort_by_key(|&(StageId(stage_id),_)|stage_id);
|
||||
unique_stages.into_iter().enumerate()
|
||||
.map(|(final_stage_id,(builder_stage_id,stage))|{
|
||||
mode.push_stage(stage);
|
||||
(builder_stage_id,StageId::new(final_stage_id as u32))
|
||||
}).collect()
|
||||
}),
|
||||
mode,
|
||||
},
|
||||
(
|
||||
builder_mode_id,
|
||||
ModeId::new(final_mode_id as u32)
|
||||
)
|
||||
)
|
||||
}).unzip();
|
||||
//TODO: failure messages or errors or something
|
||||
//push stage updates
|
||||
for (builder_mode_id,builder_stage_id,stage_update) in self.stage_updates{
|
||||
if let Some(final_mode_id)=mode_id_map.get(&builder_mode_id){
|
||||
if let Some(mode)=modes.get_mut(final_mode_id.get() as usize){
|
||||
if let Some(&final_stage_id)=mode.stage_id_map.get(&builder_stage_id){
|
||||
if let Some(stage)=mode.mode.get_stage_mut(final_stage_id){
|
||||
stage_update.apply_to(stage);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
//push mode updates
|
||||
for (builder_mode_id,mut mode_update) in self.mode_updates{
|
||||
if let Some(final_mode_id)=mode_id_map.get(&builder_mode_id){
|
||||
if let Some(mode)=modes.get_mut(final_mode_id.get() as usize){
|
||||
//map stage id on stage elements
|
||||
mode_update.map_stage_element_ids(|stage_id|
|
||||
//walk down one stage id at a time until a stage is found
|
||||
//TODO use better logic like BTreeMap::upper_bound instead of walking
|
||||
// final_stage_id_from_builder_stage_id.upper_bound(Bound::Included(&stage_id))
|
||||
// .value().copied().unwrap_or(StageId::FIRST)
|
||||
(0..=stage_id.get()).rev().find_map(|builder_stage_id|
|
||||
//map the stage element to that stage
|
||||
mode.stage_id_map.get(&StageId::new(builder_stage_id)).copied()
|
||||
).unwrap_or(StageId::FIRST)
|
||||
);
|
||||
mode_update.apply_to(&mut mode.mode);
|
||||
}
|
||||
}
|
||||
}
|
||||
NormalizedModes::new(modes.into_iter().map(|mode_builder|NormalizedMode(mode_builder.mode)).collect())
|
||||
}
|
||||
pub fn insert_mode(&mut self,mode_id:ModeId,mode:Mode)->Result<(),ExistingEntryError>{
|
||||
error_if_exists(self.modes.insert(mode_id,mode))
|
||||
}
|
||||
pub fn insert_stage(&mut self,mode_id:ModeId,stage_id:StageId,stage:Stage)->Result<(),ExistingEntryError>{
|
||||
error_if_exists(self.stages.entry(mode_id).or_insert(HashMap::new()).insert(stage_id,stage))
|
||||
}
|
||||
pub fn push_mode_update(&mut self,mode_id:ModeId,mode_update:ModeUpdate){
|
||||
self.mode_updates.push((mode_id,mode_update));
|
||||
}
|
||||
// fn push_stage_update(&mut self,mode_id:ModeId,stage_id:StageId,stage_update:StageUpdate){
|
||||
// self.stage_updates.push((mode_id,stage_id,stage_update));
|
||||
// }
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ExistingEntryError;
|
||||
fn error_if_exists<T>(value:Option<T>)->Result<(),ExistingEntryError>{
|
||||
match value{
|
||||
Some(_)=>Err(ExistingEntryError),
|
||||
None=>Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ pub struct StyleModifiers{
|
||||
//unused
|
||||
pub mass:Planar64,
|
||||
}
|
||||
impl std::default::Default for StyleModifiers{
|
||||
impl Default for StyleModifiers{
|
||||
fn default()->Self{
|
||||
Self::roblox_bhop()
|
||||
}
|
||||
@@ -63,22 +63,22 @@ impl JumpImpulse{
|
||||
velocity:Planar64Vec3,
|
||||
jump_dir:Planar64Vec3,
|
||||
gravity:&Planar64Vec3,
|
||||
mass:Planar64,
|
||||
_mass:Planar64,
|
||||
)->Planar64Vec3{
|
||||
match self{
|
||||
&JumpImpulse::Time(time)=>velocity-(*gravity*time).map(|t|t.divide().fix_1()),
|
||||
&JumpImpulse::Time(time)=>velocity-(*gravity*time).map(|t|t.divide().clamp_64()),
|
||||
&JumpImpulse::Height(height)=>{
|
||||
//height==-v.y*v.y/(2*g.y);
|
||||
//use energy to determine max height
|
||||
let gg=gravity.length_squared();
|
||||
let g=gg.sqrt().fix_1();
|
||||
let g=gg.sqrt();
|
||||
let v_g=gravity.dot(velocity);
|
||||
//do it backwards
|
||||
let radicand=v_g*v_g+(g*height*2).fix_4();
|
||||
velocity-(*gravity*(radicand.sqrt().fix_2()+v_g)/gg).divide().fix_1()
|
||||
let radicand=v_g*v_g+(g*height*2).widen_256();
|
||||
velocity-(*gravity*(radicand.sqrt().wrap_128()+v_g)/gg).divide().clamp_64()
|
||||
},
|
||||
&JumpImpulse::Linear(jump_speed)=>velocity+(jump_dir*jump_speed/jump_dir.length()).divide().fix_1(),
|
||||
&JumpImpulse::Energy(energy)=>{
|
||||
&JumpImpulse::Linear(jump_speed)=>velocity+(jump_dir*jump_speed/jump_dir.length()).divide().clamp_64(),
|
||||
&JumpImpulse::Energy(_energy)=>{
|
||||
//calculate energy
|
||||
//let e=gravity.dot(velocity);
|
||||
//add
|
||||
@@ -91,10 +91,10 @@ impl JumpImpulse{
|
||||
pub fn get_jump_deltav(&self,gravity:&Planar64Vec3,mass:Planar64)->Planar64{
|
||||
//gravity.length() is actually the proper calculation because the jump is always opposite the gravity direction
|
||||
match self{
|
||||
&JumpImpulse::Time(time)=>(gravity.length().fix_1()*time/2).divide().fix_1(),
|
||||
&JumpImpulse::Height(height)=>(gravity.length()*height*2).sqrt().fix_1(),
|
||||
&JumpImpulse::Time(time)=>(gravity.length().wrap_64()*time/2).divide().clamp_64(),
|
||||
&JumpImpulse::Height(height)=>(gravity.length()*height*2).sqrt().wrap_64(),
|
||||
&JumpImpulse::Linear(deltav)=>deltav,
|
||||
&JumpImpulse::Energy(energy)=>(energy.sqrt()*2/mass.sqrt()).divide().fix_1(),
|
||||
&JumpImpulse::Energy(energy)=>(energy.sqrt()*2/mass.sqrt()).divide().clamp_64(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -126,10 +126,10 @@ impl JumpSettings{
|
||||
None=>rel_velocity,
|
||||
};
|
||||
let j=boost_vel.dot(jump_dir);
|
||||
let js=jump_speed.fix_2();
|
||||
let js=jump_speed.widen_128();
|
||||
if j<js{
|
||||
//weak booster: just do a regular jump
|
||||
boost_vel+jump_dir.with_length(js-j).divide().fix_1()
|
||||
boost_vel+jump_dir.with_length(js-j).divide().wrap_64()
|
||||
}else{
|
||||
//activate booster normally, jump does nothing
|
||||
boost_vel
|
||||
@@ -142,13 +142,13 @@ impl JumpSettings{
|
||||
None=>rel_velocity,
|
||||
};
|
||||
let j=boost_vel.dot(jump_dir);
|
||||
let js=jump_speed.fix_2();
|
||||
let js=jump_speed.widen_128();
|
||||
if j<js{
|
||||
//speed in direction of jump cannot be lower than amount
|
||||
boost_vel+jump_dir.with_length(js-j).divide().fix_1()
|
||||
boost_vel+jump_dir.with_length(js-j).divide().wrap_64()
|
||||
}else{
|
||||
//boost and jump add together
|
||||
boost_vel+jump_dir.with_length(js).divide().fix_1()
|
||||
boost_vel+jump_dir.with_length(js).divide().wrap_64()
|
||||
}
|
||||
}
|
||||
(false,JumpCalculation::Max)=>{
|
||||
@@ -159,10 +159,10 @@ impl JumpSettings{
|
||||
None=>rel_velocity,
|
||||
};
|
||||
let boost_dot=boost_vel.dot(jump_dir);
|
||||
let js=jump_speed.fix_2();
|
||||
let js=jump_speed.widen_128();
|
||||
if boost_dot<js{
|
||||
//weak boost is extended to jump speed
|
||||
boost_vel+jump_dir.with_length(js-boost_dot).divide().fix_1()
|
||||
boost_vel+jump_dir.with_length(js-boost_dot).divide().wrap_64()
|
||||
}else{
|
||||
//activate booster normally, jump does nothing
|
||||
boost_vel
|
||||
@@ -174,7 +174,7 @@ impl JumpSettings{
|
||||
Some(booster)=>booster.boost(rel_velocity),
|
||||
None=>rel_velocity,
|
||||
};
|
||||
boost_vel+jump_dir.with_length(jump_speed).divide().fix_1()
|
||||
boost_vel+jump_dir.with_length(jump_speed).divide().wrap_64()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -267,9 +267,9 @@ pub struct StrafeSettings{
|
||||
impl StrafeSettings{
|
||||
pub fn tick_velocity(&self,velocity:Planar64Vec3,control_dir:Planar64Vec3)->Option<Planar64Vec3>{
|
||||
let d=velocity.dot(control_dir);
|
||||
let mv=self.mv.fix_2();
|
||||
let mv=self.mv.widen_128();
|
||||
match d<mv{
|
||||
true=>Some(velocity+(control_dir*self.air_accel_limit.map_or(mv-d,|limit|limit.fix_2().min(mv-d))).fix_1()),
|
||||
true=>Some(velocity+(control_dir*self.air_accel_limit.map_or(mv-d,|limit|limit.widen_128().min(mv-d))).wrap_64()),
|
||||
false=>None,
|
||||
}
|
||||
}
|
||||
@@ -290,7 +290,7 @@ pub struct PropulsionSettings{
|
||||
}
|
||||
impl PropulsionSettings{
|
||||
pub fn acceleration(&self,control_dir:Planar64Vec3)->Planar64Vec3{
|
||||
(control_dir*self.magnitude).fix_1()
|
||||
(control_dir*self.magnitude).clamp_64()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,16 +310,16 @@ pub struct WalkSettings{
|
||||
impl WalkSettings{
|
||||
pub fn accel(&self,target_diff:Planar64Vec3,gravity:Planar64Vec3)->Planar64{
|
||||
//TODO: fallible walk accel
|
||||
let diff_len=target_diff.length().fix_1();
|
||||
let diff_len=target_diff.length().wrap_64();
|
||||
let friction=if diff_len<self.accelerate.topspeed{
|
||||
self.static_friction
|
||||
}else{
|
||||
self.kinetic_friction
|
||||
};
|
||||
self.accelerate.accel.min((-gravity.y*friction).fix_1())
|
||||
self.accelerate.accel.min((-gravity.y*friction).clamp_64())
|
||||
}
|
||||
pub fn get_walk_target_velocity(&self,control_dir:Planar64Vec3,normal:Planar64Vec3)->Planar64Vec3{
|
||||
if control_dir==crate::integer::vec3::ZERO{
|
||||
if control_dir==crate::integer::vec3::zero(){
|
||||
return control_dir;
|
||||
}
|
||||
let nn=normal.length_squared();
|
||||
@@ -329,19 +329,19 @@ impl WalkSettings{
|
||||
let dd=d*d;
|
||||
if dd<nnmm{
|
||||
let cr=normal.cross(control_dir);
|
||||
if cr==crate::integer::vec3::ZERO_2{
|
||||
crate::integer::vec3::ZERO
|
||||
if cr==crate::integer::vec3::zero(){
|
||||
crate::integer::vec3::zero()
|
||||
}else{
|
||||
(cr.cross(normal)*self.accelerate.topspeed/((nn*(nnmm-dd)).sqrt())).divide().fix_1()
|
||||
(cr.cross(normal)*self.accelerate.topspeed/((nn*(nnmm-dd)).sqrt())).divide().clamp_64()
|
||||
}
|
||||
}else{
|
||||
crate::integer::vec3::ZERO
|
||||
crate::integer::vec3::zero()
|
||||
}
|
||||
}
|
||||
pub fn is_slope_walkable(&self,normal:Planar64Vec3,up:Planar64Vec3)->bool{
|
||||
//normal is not guaranteed to be unit length
|
||||
let ny=normal.dot(up);
|
||||
let h=normal.length().fix_1();
|
||||
let h=normal.length().wrap_64();
|
||||
//remember this is a normal vector
|
||||
ny.is_positive()&&h*self.surf_dot<ny
|
||||
}
|
||||
@@ -355,12 +355,12 @@ pub struct LadderSettings{
|
||||
pub dot:Planar64,
|
||||
}
|
||||
impl LadderSettings{
|
||||
pub const fn accel(&self,target_diff:Planar64Vec3,gravity:Planar64Vec3)->Planar64{
|
||||
pub const fn accel(&self,_target_diff:Planar64Vec3,_gravity:Planar64Vec3)->Planar64{
|
||||
//TODO: fallible ladder accel
|
||||
self.accelerate.accel
|
||||
}
|
||||
pub fn get_ladder_target_velocity(&self,mut control_dir:Planar64Vec3,normal:Planar64Vec3)->Planar64Vec3{
|
||||
if control_dir==crate::integer::vec3::ZERO{
|
||||
if control_dir==crate::integer::vec3::zero(){
|
||||
return control_dir;
|
||||
}
|
||||
let nn=normal.length_squared();
|
||||
@@ -368,13 +368,13 @@ impl LadderSettings{
|
||||
let nnmm=nn*mm;
|
||||
let d=normal.dot(control_dir);
|
||||
let mut dd=d*d;
|
||||
if (self.dot*self.dot*nnmm).fix_4()<dd{
|
||||
if (self.dot*self.dot*nnmm).clamp_256()<dd{
|
||||
if d.is_negative(){
|
||||
control_dir=Planar64Vec3::new([Planar64::ZERO,mm.fix_1(),Planar64::ZERO]);
|
||||
control_dir=Planar64Vec3::new([Planar64::ZERO,mm.clamp_64(),Planar64::ZERO]);
|
||||
}else{
|
||||
control_dir=Planar64Vec3::new([Planar64::ZERO,-mm.fix_1(),Planar64::ZERO]);
|
||||
control_dir=Planar64Vec3::new([Planar64::ZERO,-mm.clamp_64(),Planar64::ZERO]);
|
||||
}
|
||||
dd=(normal.y*normal.y).fix_4();
|
||||
dd=(normal.y*normal.y).widen_256();
|
||||
}
|
||||
//n=d if you are standing on top of a ladder and press E.
|
||||
//two fixes:
|
||||
@@ -382,13 +382,13 @@ impl LadderSettings{
|
||||
//- fix the underlying issue
|
||||
if dd<nnmm{
|
||||
let cr=normal.cross(control_dir);
|
||||
if cr==crate::integer::vec3::ZERO_2{
|
||||
crate::integer::vec3::ZERO
|
||||
if cr==crate::integer::vec3::zero(){
|
||||
crate::integer::vec3::zero()
|
||||
}else{
|
||||
(cr.cross(normal)*self.accelerate.topspeed/((nn*(nnmm-dd)).sqrt())).divide().fix_1()
|
||||
(cr.cross(normal)*self.accelerate.topspeed/((nn*(nnmm-dd)).sqrt())).divide().clamp_64()
|
||||
}
|
||||
}else{
|
||||
crate::integer::vec3::ZERO
|
||||
crate::integer::vec3::zero()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -417,7 +417,7 @@ impl Hitbox{
|
||||
}
|
||||
pub fn source()->Self{
|
||||
Self{
|
||||
halfsize:((int3(33,73,33)>>1)*VALVE_SCALE).fix_1(),
|
||||
halfsize:((int3(33,73,33)>>1)*VALVE_SCALE).narrow_64().unwrap(),
|
||||
mesh:HitboxMesh::Box,
|
||||
}
|
||||
}
|
||||
@@ -529,20 +529,20 @@ impl StyleModifiers{
|
||||
|
||||
pub fn source_bhop()->Self{
|
||||
Self{
|
||||
controls_mask:Controls::all()-Controls::MoveUp-Controls::MoveDown,
|
||||
controls_mask:Controls::all(),
|
||||
controls_mask_state:Controls::all(),
|
||||
strafe:Some(StrafeSettings{
|
||||
enable:ControlsActivation::full_2d(),
|
||||
air_accel_limit:Some(Planar64::raw(150<<28)*100),
|
||||
mv:(Planar64::raw(30)*VALVE_SCALE).fix_1(),
|
||||
air_accel_limit:Some(Planar64::raw((150<<28)*100)),
|
||||
mv:Planar64::raw(30<<28),
|
||||
tick_rate:Ratio64::new(100,AbsoluteTime::ONE_SECOND.get() as u64).unwrap(),
|
||||
}),
|
||||
jump:Some(JumpSettings{
|
||||
impulse:JumpImpulse::Height((int(52)*VALVE_SCALE).fix_1()),
|
||||
impulse:JumpImpulse::Height((int(52)*VALVE_SCALE).narrow_64().unwrap()),
|
||||
calculation:JumpCalculation::JumpThenBoost,
|
||||
limit_minimum:true,
|
||||
}),
|
||||
gravity:(int3(0,-800,0)*VALVE_SCALE).fix_1(),
|
||||
gravity:(int3(0,-800,0)*VALVE_SCALE).narrow_64().unwrap(),
|
||||
mass:int(1),
|
||||
rocket:None,
|
||||
walk:Some(WalkSettings{
|
||||
@@ -565,25 +565,25 @@ impl StyleModifiers{
|
||||
magnitude:int(12),//?
|
||||
}),
|
||||
hitbox:Hitbox::source(),
|
||||
camera_offset:((int3(0,64,0)-(int3(0,73,0)>>1))*VALVE_SCALE).fix_1(),
|
||||
camera_offset:((int3(0,64,0)-(int3(0,73,0)>>1))*VALVE_SCALE).narrow_64().unwrap(),
|
||||
}
|
||||
}
|
||||
pub fn source_surf()->Self{
|
||||
Self{
|
||||
controls_mask:Controls::all()-Controls::MoveUp-Controls::MoveDown,
|
||||
controls_mask:Controls::all(),
|
||||
controls_mask_state:Controls::all(),
|
||||
strafe:Some(StrafeSettings{
|
||||
enable:ControlsActivation::full_2d(),
|
||||
air_accel_limit:Some((int(150)*66*VALVE_SCALE).fix_1()),
|
||||
mv:(int(30)*VALVE_SCALE).fix_1(),
|
||||
air_accel_limit:Some((int(150)*66*VALVE_SCALE).narrow_64().unwrap()),
|
||||
mv:Planar64::raw(30<<28),
|
||||
tick_rate:Ratio64::new(66,AbsoluteTime::ONE_SECOND.get() as u64).unwrap(),
|
||||
}),
|
||||
jump:Some(JumpSettings{
|
||||
impulse:JumpImpulse::Height((int(52)*VALVE_SCALE).fix_1()),
|
||||
impulse:JumpImpulse::Height((int(52)*VALVE_SCALE).narrow_64().unwrap()),
|
||||
calculation:JumpCalculation::JumpThenBoost,
|
||||
limit_minimum:true,
|
||||
}),
|
||||
gravity:(int3(0,-800,0)*VALVE_SCALE).fix_1(),
|
||||
gravity:(int3(0,-800,0)*VALVE_SCALE).narrow_64().unwrap(),
|
||||
mass:int(1),
|
||||
rocket:None,
|
||||
walk:Some(WalkSettings{
|
||||
@@ -606,7 +606,7 @@ impl StyleModifiers{
|
||||
magnitude:int(12),//?
|
||||
}),
|
||||
hitbox:Hitbox::source(),
|
||||
camera_offset:((int3(0,64,0)-(int3(0,73,0)>>1))*VALVE_SCALE).fix_1(),
|
||||
camera_offset:((int3(0,64,0)-(int3(0,73,0)>>1))*VALVE_SCALE).narrow_64().unwrap(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
use crate::integer::Time;
|
||||
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct TimedInstruction<I,T>{
|
||||
pub time:Time<T>,
|
||||
pub time:T,
|
||||
pub instruction:I,
|
||||
}
|
||||
impl<I,T> TimedInstruction<I,T>{
|
||||
#[inline]
|
||||
pub fn set_time<TimeInner>(self,new_time:Time<TimeInner>)->TimedInstruction<I,TimeInner>{
|
||||
pub fn set_time<T2>(self,new_time:T2)->TimedInstruction<I,T2>{
|
||||
TimedInstruction{
|
||||
time:new_time,
|
||||
instruction:self.instruction,
|
||||
@@ -17,51 +15,91 @@ impl<I,T> TimedInstruction<I,T>{
|
||||
|
||||
/// Ensure all emitted instructions are processed before consuming external instructions
|
||||
pub trait InstructionEmitter<I>{
|
||||
type TimeInner;
|
||||
fn next_instruction(&self,time_limit:Time<Self::TimeInner>)->Option<TimedInstruction<I,Self::TimeInner>>;
|
||||
type Time;
|
||||
fn next_instruction(&self,time_limit:Self::Time)->Option<TimedInstruction<I,Self::Time>>;
|
||||
}
|
||||
/// Apply an atomic state update
|
||||
pub trait InstructionConsumer<I>{
|
||||
type TimeInner;
|
||||
fn process_instruction(&mut self,instruction:TimedInstruction<I,Self::TimeInner>);
|
||||
type Time;
|
||||
fn process_instruction(&mut self,instruction:TimedInstruction<I,Self::Time>);
|
||||
}
|
||||
/// If the object produces its own instructions, allow exhaustively feeding them back in
|
||||
pub trait InstructionFeedback<I,T>:InstructionEmitter<I,TimeInner=T>+InstructionConsumer<I,TimeInner=T>
|
||||
pub trait InstructionFeedback<I,T>:InstructionEmitter<I,Time=T>+InstructionConsumer<I,Time=T>
|
||||
where
|
||||
Time<T>:Copy,
|
||||
T:Copy,
|
||||
{
|
||||
#[inline]
|
||||
fn process_exhaustive(&mut self,time_limit:Time<T>){
|
||||
fn process_exhaustive(&mut self,time_limit:T){
|
||||
while let Some(instruction)=self.next_instruction(time_limit){
|
||||
self.process_instruction(instruction);
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn into_iter(self,time_limit:T)->InstructionIter<I,T,Self>
|
||||
where
|
||||
Self:Sized
|
||||
{
|
||||
InstructionIter{
|
||||
time_limit,
|
||||
feedback:self,
|
||||
_phantom:core::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<I,T,X> InstructionFeedback<I,T> for X
|
||||
impl<I,T,F> InstructionFeedback<I,T> for F
|
||||
where
|
||||
Time<T>:Copy,
|
||||
X:InstructionEmitter<I,TimeInner=T>+InstructionConsumer<I,TimeInner=T>,
|
||||
T:Copy,
|
||||
F:InstructionEmitter<I,Time=T>+InstructionConsumer<I,Time=T>,
|
||||
{}
|
||||
pub struct InstructionIter<I,T:Copy,F:InstructionFeedback<I,T>>{
|
||||
time_limit:T,
|
||||
feedback:F,
|
||||
_phantom:core::marker::PhantomData<I>,
|
||||
}
|
||||
impl<I,T,F> Iterator for InstructionIter<I,T,F>
|
||||
where
|
||||
I:Clone,
|
||||
T:Clone+Copy,
|
||||
F:InstructionFeedback<I,T>,
|
||||
{
|
||||
type Item=TimedInstruction<I,T>;
|
||||
fn next(&mut self)->Option<Self::Item>{
|
||||
let instruction=self.feedback.next_instruction(self.time_limit)?;
|
||||
self.feedback.process_instruction(instruction.clone());
|
||||
Some(instruction)
|
||||
}
|
||||
}
|
||||
|
||||
//PROPER PRIVATE FIELDS!!!
|
||||
pub struct InstructionCollector<I,T>{
|
||||
time:Time<T>,
|
||||
time:T,
|
||||
instruction:Option<I>,
|
||||
}
|
||||
impl<I,T> InstructionCollector<I,T>
|
||||
where Time<T>:Copy+PartialOrd,
|
||||
{
|
||||
impl<I,T> InstructionCollector<I,T>{
|
||||
#[inline]
|
||||
pub const fn new(time:Time<T>)->Self{
|
||||
pub const fn new(time:T)->Self{
|
||||
Self{
|
||||
time,
|
||||
instruction:None
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub const fn time(&self)->Time<T>{
|
||||
pub fn take(self)->Option<TimedInstruction<I,T>>{
|
||||
//STEAL INSTRUCTION AND DESTROY INSTRUCTIONCOLLECTOR
|
||||
self.instruction.map(|instruction|TimedInstruction{
|
||||
time:self.time,
|
||||
instruction
|
||||
})
|
||||
}
|
||||
}
|
||||
impl<I,T:Copy> InstructionCollector<I,T>{
|
||||
#[inline]
|
||||
pub const fn time(&self)->T{
|
||||
self.time
|
||||
}
|
||||
}
|
||||
impl<I,T:PartialOrd> InstructionCollector<I,T>{
|
||||
#[inline]
|
||||
pub fn collect(&mut self,instruction:Option<TimedInstruction<I,T>>){
|
||||
if let Some(ins)=instruction{
|
||||
if ins.time<self.time{
|
||||
@@ -70,11 +108,4 @@ impl<I,T> InstructionCollector<I,T>
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn instruction(self)->Option<TimedInstruction<I,T>>{
|
||||
//STEAL INSTRUCTION AND DESTROY INSTRUCTIONCOLLECTOR
|
||||
self.instruction.map(|instruction|TimedInstruction{
|
||||
time:self.time,
|
||||
instruction
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,26 @@
|
||||
pub use fixed_wide::fixed::{Fixed,Fix};
|
||||
pub use ratio_ops::ratio::{Ratio,Divide};
|
||||
pub use fixed_wide::fixed::*;
|
||||
pub use ratio_ops::ratio::{Ratio,Divide,Parity};
|
||||
|
||||
pub mod fixed_types{
|
||||
pub use fixed_wide::types::*;
|
||||
}
|
||||
|
||||
use fixed_wide::types::F128_64;
|
||||
|
||||
//integer units
|
||||
|
||||
/// specific example of a "default" time type
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq,PartialOrd,Debug)]
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq,Ord,PartialOrd,Debug)]
|
||||
pub enum TimeInner{}
|
||||
pub type AbsoluteTime=Time<TimeInner>;
|
||||
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq,PartialOrd,Debug)]
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq,Ord,PartialOrd,Debug)]
|
||||
pub struct Time<T>(i64,core::marker::PhantomData<T>);
|
||||
impl<T> Time<T>{
|
||||
pub const MIN:Self=Self::raw(i64::MIN);
|
||||
pub const MAX:Self=Self::raw(i64::MAX);
|
||||
pub const ZERO:Self=Self::raw(0);
|
||||
pub const EPSILON:Self=Self::raw(1);
|
||||
pub const ONE_SECOND:Self=Self::raw(1_000_000_000);
|
||||
pub const ONE_MILLISECOND:Self=Self::raw(1_000_000);
|
||||
pub const ONE_MICROSECOND:Self=Self::raw(1_000);
|
||||
@@ -55,22 +62,36 @@ impl<T> Time<T>{
|
||||
pub const fn coerce<U>(self)->Time<U>{
|
||||
Time::raw(self.0)
|
||||
}
|
||||
#[inline]
|
||||
pub const fn div_euclid(self,other:Self)->Self{
|
||||
Time::raw(self.0.div_euclid(other.0))
|
||||
}
|
||||
#[inline]
|
||||
pub const fn rem_euclid(self,other:Self)->Self{
|
||||
Time::raw(self.0.rem_euclid(other.0))
|
||||
}
|
||||
}
|
||||
impl<T> From<Planar64> for Time<T>{
|
||||
#[inline]
|
||||
fn from(value:Planar64)->Self{
|
||||
Self::raw((value*Planar64::raw(1_000_000_000)).fix_1().to_raw())
|
||||
Self::raw((value*Planar64::raw(1_000_000_000)).clamp_64().to_raw())
|
||||
}
|
||||
}
|
||||
impl<T> From<Time<T>> for Ratio<Planar64,Planar64>{
|
||||
#[inline]
|
||||
fn from(value:Time<T>)->Self{
|
||||
value.to_ratio()
|
||||
}
|
||||
}
|
||||
impl<T,Num,Den,N1,T1> From<Ratio<Num,Den>> for Time<T>
|
||||
where
|
||||
Num:core::ops::Mul<Planar64,Output=N1>,
|
||||
N1:Divide<Den,Output=T1>,
|
||||
T1:Fix<Planar64>,
|
||||
T1:Clamp<Planar64>,
|
||||
{
|
||||
#[inline]
|
||||
fn from(value:Ratio<Num,Den>)->Self{
|
||||
Self::raw((value*Planar64::raw(1_000_000_000)).divide().fix().to_raw())
|
||||
Self::raw((value*Planar64::raw(1_000_000_000)).divide().clamp().to_raw())
|
||||
}
|
||||
}
|
||||
impl<T> std::fmt::Display for Time<T>{
|
||||
@@ -79,7 +100,7 @@ impl<T> std::fmt::Display for Time<T>{
|
||||
write!(f,"{}s+{:09}ns",self.0/Self::ONE_SECOND.0,self.0%Self::ONE_SECOND.0)
|
||||
}
|
||||
}
|
||||
impl<T> std::default::Default for Time<T>{
|
||||
impl<T> Default for Time<T>{
|
||||
fn default()->Self{
|
||||
Self::raw(0)
|
||||
}
|
||||
@@ -119,36 +140,51 @@ impl_time_additive_assign_operator!(core::ops::AddAssign,add_assign);
|
||||
impl_time_additive_assign_operator!(core::ops::SubAssign,sub_assign);
|
||||
impl_time_additive_assign_operator!(core::ops::RemAssign,rem_assign);
|
||||
impl<T> std::ops::Mul for Time<T>{
|
||||
type Output=Ratio<fixed_wide::fixed::Fixed<2,64>,fixed_wide::fixed::Fixed<2,64>>;
|
||||
type Output=Ratio<F128_64,F128_64>;
|
||||
#[inline]
|
||||
fn mul(self,rhs:Self)->Self::Output{
|
||||
Ratio::new(Fixed::raw(self.0)*Fixed::raw(rhs.0),Fixed::raw_digit(1_000_000_000i64.pow(2)))
|
||||
Ratio::new(Fixed::raw(self.0)*Fixed::raw(rhs.0),Fixed::from_u64(1_000_000_000u64.pow(2)))
|
||||
}
|
||||
}
|
||||
impl<T> std::ops::Div<i64> for Time<T>{
|
||||
type Output=Self;
|
||||
#[inline]
|
||||
fn div(self,rhs:i64)->Self::Output{
|
||||
Self::raw(self.0/rhs)
|
||||
}
|
||||
}
|
||||
impl<T> std::ops::Mul<i64> for Time<T>{
|
||||
type Output=Self;
|
||||
#[inline]
|
||||
fn mul(self,rhs:i64)->Self::Output{
|
||||
Self::raw(self.0*rhs)
|
||||
macro_rules! impl_time_i64_rhs_operator {
|
||||
($op:ident,$method:ident)=>{
|
||||
impl<T> core::ops::$op<i64> for Time<T>{
|
||||
type Output=Self;
|
||||
#[inline]
|
||||
fn $method(self,rhs:i64)->Self::Output{
|
||||
Self::raw(self.0.$method(rhs))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl_time_i64_rhs_operator!(Div,div);
|
||||
impl_time_i64_rhs_operator!(Mul,mul);
|
||||
impl_time_i64_rhs_operator!(Shr,shr);
|
||||
impl_time_i64_rhs_operator!(Shl,shl);
|
||||
impl<T> core::ops::Mul<Time<T>> for Planar64{
|
||||
type Output=Ratio<Fixed<2,64>,Planar64>;
|
||||
type Output=Ratio<F128_64,Planar64>;
|
||||
#[inline]
|
||||
fn mul(self,rhs:Time<T>)->Self::Output{
|
||||
Ratio::new(self*Fixed::raw(rhs.0),Planar64::raw(1_000_000_000))
|
||||
}
|
||||
}
|
||||
impl<T> From<Time<T>> for f32{
|
||||
#[inline]
|
||||
fn from(value:Time<T>)->Self{
|
||||
value.get() as f32/Time::<T>::ONE_SECOND.get() as f32
|
||||
}
|
||||
}
|
||||
impl<T> From<Time<T>> for f64{
|
||||
#[inline]
|
||||
fn from(value:Time<T>)->Self{
|
||||
value.get() as f64/Time::<T>::ONE_SECOND.get() as f64
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod test_time{
|
||||
use super::*;
|
||||
type Time=super::AbsoluteTime;
|
||||
use fixed_wide::types::F64_32;
|
||||
type Time=AbsoluteTime;
|
||||
#[test]
|
||||
fn time_from_planar64(){
|
||||
let a:Time=Planar64::from(1).into();
|
||||
@@ -162,13 +198,13 @@ mod test_time{
|
||||
#[test]
|
||||
fn time_squared(){
|
||||
let a=Time::from_secs(2);
|
||||
assert_eq!(a*a,Ratio::new(Fixed::<2,64>::raw_digit(1_000_000_000i64.pow(2))*4,Fixed::<2,64>::raw_digit(1_000_000_000i64.pow(2))));
|
||||
assert_eq!(a*a,Ratio::new(F128_64::from_u64(1_000_000_000u64.pow(2))*4,F128_64::from_u64(1_000_000_000u64.pow(2))));
|
||||
}
|
||||
#[test]
|
||||
fn time_times_planar64(){
|
||||
let a=Time::from_secs(2);
|
||||
let b=Planar64::from(2);
|
||||
assert_eq!(b*a,Ratio::new(Fixed::<2,64>::raw_digit(1_000_000_000*(1<<32))<<2,Fixed::<1,32>::raw_digit(1_000_000_000)));
|
||||
assert_eq!(b*a,Ratio::new(F128_64::from_u64(1_000_000_000*(1<<32))<<2,F64_32::from_u64(1_000_000_000)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,11 +242,11 @@ impl Ratio64{
|
||||
}
|
||||
#[inline]
|
||||
pub const fn mul_int(&self,rhs:i64)->i64{
|
||||
rhs*self.num/(self.den as i64)
|
||||
(rhs as i128*self.num as i128/self.den as i128) as i64
|
||||
}
|
||||
#[inline]
|
||||
pub const fn rhs_div_int(&self,rhs:i64)->i64{
|
||||
rhs*(self.den as i64)/self.num
|
||||
(rhs as i128*self.den as i128/self.num as i128) as i64
|
||||
}
|
||||
#[inline]
|
||||
pub const fn mul_ref(&self,rhs:&Ratio64)->Ratio64{
|
||||
@@ -255,7 +291,6 @@ fn integer_decode_f64(f: f64) -> (u64, i16, i8) {
|
||||
pub enum Ratio64TryFromFloatError{
|
||||
Nan,
|
||||
Infinite,
|
||||
Subnormal,
|
||||
HighlyNegativeExponent(i16),
|
||||
HighlyPositiveExponent(i16),
|
||||
}
|
||||
@@ -290,8 +325,10 @@ fn ratio64_from_mes((m,e,s):(u64,i16,i8))->Result<Ratio64,Ratio64TryFromFloatErr
|
||||
|
||||
Ok(Ratio64::new(num as i64,den as u64).unwrap())
|
||||
}else if e<0{
|
||||
// simple exact representation
|
||||
Ok(Ratio64::new((m as i64)*(s as i64),1<<-e).unwrap())
|
||||
}else if (64-m.leading_zeros() as i16)+e<64{
|
||||
// integer
|
||||
Ok(Ratio64::new((m as i64)*(s as i64)*(1<<e),1).unwrap())
|
||||
}else{
|
||||
Err(Ratio64TryFromFloatError::HighlyPositiveExponent(e))
|
||||
@@ -323,6 +360,29 @@ impl TryFrom<f64> for Ratio64{
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
fn req(r0:Ratio64,r1:Ratio64){
|
||||
println!("r0={r0:?} r1={r1:?}");
|
||||
assert_eq!(r0.num(),r1.num(),"Nums not eq");
|
||||
assert_eq!(r0.den(),r1.den(),"Dens not eq");
|
||||
}
|
||||
#[test]
|
||||
fn test_ratio64_from_float(){
|
||||
req(2.0.try_into().unwrap(),Ratio64::new(2,1).unwrap());
|
||||
req(1.0.try_into().unwrap(),Ratio64::new(1,1).unwrap());
|
||||
req(0.5.try_into().unwrap(),Ratio64::new(1,2).unwrap());
|
||||
req(1.1.try_into().unwrap(),Ratio64::new(2476979795053773,2251799813685248).unwrap());
|
||||
req(0.8.try_into().unwrap(),Ratio64::new(3602879701896397,4503599627370496).unwrap());
|
||||
req(0.61.try_into().unwrap(),Ratio64::new(5494391545392005,9007199254740992).unwrap());
|
||||
req(0.01.try_into().unwrap(),Ratio64::new(5764607523034235,576460752303423488).unwrap());
|
||||
req(0.001.try_into().unwrap(),Ratio64::new(1152921504606847,1152921504606846976).unwrap());
|
||||
req(0.00001.try_into().unwrap(),Ratio64::new(89605456633725,8960545663372499267).unwrap());
|
||||
req(0.00000000001.try_into().unwrap(),Ratio64::new(35204848,3520484800000000213).unwrap());
|
||||
req(0.000000000000000001.try_into().unwrap(),Ratio64::new(11,10999999999999999213).unwrap());
|
||||
req(2222222222222.0.try_into().unwrap(),Ratio64::new(2222222222222,1).unwrap());
|
||||
req(core::f64::consts::PI.try_into().unwrap(),Ratio64::new(884279719003555,281474976710656).unwrap());
|
||||
}
|
||||
|
||||
impl std::ops::Mul<Ratio64> for Ratio64{
|
||||
type Output=Ratio64;
|
||||
#[inline]
|
||||
@@ -394,6 +454,10 @@ impl Angle32{
|
||||
pub const NEG_FRAC_PI_2:Self=Self(-1<<30);
|
||||
pub const PI:Self=Self(-1<<31);
|
||||
#[inline]
|
||||
pub const fn raw(num:i32)->Self{
|
||||
Self(num)
|
||||
}
|
||||
#[inline]
|
||||
pub const fn wrap_from_i64(theta:i64)->Self{
|
||||
//take lower bits
|
||||
//note: this was checked on compiler explorer and compiles to 1 instruction!
|
||||
@@ -508,8 +572,8 @@ fn angle_sin_cos(){
|
||||
println!("cordic s={} c={}",(s/h).divide(),(c/h).divide());
|
||||
let (fs,fc)=f.sin_cos();
|
||||
println!("float s={} c={}",fs,fc);
|
||||
assert!(close_enough((c/h).divide().fix_1(),Planar64::raw((fc*((1u64<<32) as f64)) as i64)));
|
||||
assert!(close_enough((s/h).divide().fix_1(),Planar64::raw((fs*((1u64<<32) as f64)) as i64)));
|
||||
assert!(close_enough((c/h).divide().wrap_64(),Planar64::raw((fc*((1u64<<32) as f64)) as i64)));
|
||||
assert!(close_enough((s/h).divide().wrap_64(),Planar64::raw((fs*((1u64<<32) as f64)) as i64)));
|
||||
}
|
||||
test_angle(1.0);
|
||||
test_angle(std::f64::consts::PI/4.0);
|
||||
@@ -540,8 +604,8 @@ impl TryFrom<[f32;3]> for Unit32Vec3{
|
||||
}
|
||||
*/
|
||||
|
||||
pub type Planar64TryFromFloatError=fixed_wide::fixed::FixedFromFloatError;
|
||||
pub type Planar64=fixed_wide::types::I32F32;
|
||||
pub type Planar64TryFromFloatError=FixedFromFloatError;
|
||||
pub type Planar64=fixed_wide::types::F64_32;
|
||||
pub type Planar64Vec3=linear_ops::types::Vector3<Planar64>;
|
||||
pub type Planar64Mat3=linear_ops::types::Matrix3<Planar64>;
|
||||
pub mod vec3{
|
||||
@@ -549,8 +613,6 @@ pub mod vec3{
|
||||
pub use linear_ops::types::Vector3;
|
||||
pub const MIN:Planar64Vec3=Planar64Vec3::new([Planar64::MIN;3]);
|
||||
pub const MAX:Planar64Vec3=Planar64Vec3::new([Planar64::MAX;3]);
|
||||
pub const ZERO:Planar64Vec3=Planar64Vec3::new([Planar64::ZERO;3]);
|
||||
pub const ZERO_2:linear_ops::types::Vector3<Fixed::<2,64>>=linear_ops::types::Vector3::new([Fixed::<2,64>::ZERO;3]);
|
||||
pub const X:Planar64Vec3=Planar64Vec3::new([Planar64::ONE,Planar64::ZERO,Planar64::ZERO]);
|
||||
pub const Y:Planar64Vec3=Planar64Vec3::new([Planar64::ZERO,Planar64::ONE,Planar64::ZERO]);
|
||||
pub const Z:Planar64Vec3=Planar64Vec3::new([Planar64::ZERO,Planar64::ZERO,Planar64::ONE]);
|
||||
@@ -559,6 +621,10 @@ pub mod vec3{
|
||||
pub const NEG_Y:Planar64Vec3=Planar64Vec3::new([Planar64::ZERO,Planar64::NEG_ONE,Planar64::ZERO]);
|
||||
pub const NEG_Z:Planar64Vec3=Planar64Vec3::new([Planar64::ZERO,Planar64::ZERO,Planar64::NEG_ONE]);
|
||||
pub const NEG_ONE:Planar64Vec3=Planar64Vec3::new([Planar64::NEG_ONE,Planar64::NEG_ONE,Planar64::NEG_ONE]);
|
||||
// TODO: use #![feature(generic_const_items)] when stabilized https://github.com/rust-lang/rust/issues/113521
|
||||
pub const fn zero<const N:usize,const F:usize>()->Vector3<Fixed<N,F>>{
|
||||
Vector3::new([Fixed::ZERO;3])
|
||||
}
|
||||
#[inline]
|
||||
pub const fn int(x:i32,y:i32,z:i32)->Planar64Vec3{
|
||||
Planar64Vec3::new([Planar64::raw((x as i64)<<32),Planar64::raw((y as i64)<<32),Planar64::raw((z as i64)<<32)])
|
||||
@@ -618,8 +684,8 @@ pub mod mat3{
|
||||
let (yc,ys)=y.cos_sin();
|
||||
Planar64Mat3::from_cols([
|
||||
Planar64Vec3::new([xc,Planar64::ZERO,-xs]),
|
||||
Planar64Vec3::new([(xs*ys).fix_1(),yc,(xc*ys).fix_1()]),
|
||||
Planar64Vec3::new([(xs*yc).fix_1(),-ys,(xc*yc).fix_1()]),
|
||||
Planar64Vec3::new([(xs*ys).wrap_64(),yc,(xc*ys).wrap_64()]),
|
||||
Planar64Vec3::new([(xs*yc).wrap_64(),-ys,(xc*yc).wrap_64()]),
|
||||
])
|
||||
}
|
||||
#[inline]
|
||||
@@ -641,19 +707,27 @@ pub mod mat3{
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Default,Hash,Eq,PartialEq)]
|
||||
#[derive(Clone,Copy,Debug,Default,Hash,Eq,PartialEq)]
|
||||
pub struct Planar64Affine3{
|
||||
pub matrix3:Planar64Mat3,//includes scale above 1
|
||||
pub translation:Planar64Vec3,
|
||||
}
|
||||
impl Planar64Affine3{
|
||||
pub const IDENTITY:Self=Self::new(mat3::identity(),vec3::zero());
|
||||
#[inline]
|
||||
pub const fn new(matrix3:Planar64Mat3,translation:Planar64Vec3)->Self{
|
||||
Self{matrix3,translation}
|
||||
}
|
||||
#[inline]
|
||||
pub fn transform_point3(&self,point:Planar64Vec3)->vec3::Vector3<Fixed<2,64>>{
|
||||
self.translation.fix_2()+self.matrix3*point
|
||||
pub const fn from_translation(translation:Planar64Vec3)->Self{
|
||||
Self{
|
||||
matrix3:mat3::identity(),
|
||||
translation,
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn transform_point3(&self,point:Planar64Vec3)->vec3::Vector3<F128_64>{
|
||||
self.translation.widen_128()+self.matrix3*point
|
||||
}
|
||||
}
|
||||
impl Into<glam::Mat4> for Planar64Affine3{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod bvh;
|
||||
pub mod map;
|
||||
pub mod ray;
|
||||
pub mod run;
|
||||
pub mod aabb;
|
||||
pub mod model;
|
||||
@@ -8,7 +9,6 @@ pub mod timer;
|
||||
pub mod integer;
|
||||
pub mod physics;
|
||||
pub mod session;
|
||||
pub mod updatable;
|
||||
pub mod instruction;
|
||||
pub mod gameplay_attributes;
|
||||
pub mod gameplay_modes;
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::gameplay_attributes;
|
||||
//this is a temporary struct to try to get the code running again
|
||||
//TODO: use snf::map::Region to update the data in physics and graphics instead of this
|
||||
pub struct CompleteMap{
|
||||
pub modes:gameplay_modes::Modes,
|
||||
pub modes:gameplay_modes::NormalizedModes,
|
||||
pub attributes:Vec<gameplay_attributes::CollisionAttributes>,
|
||||
pub meshes:Vec<model::Mesh>,
|
||||
pub models:Vec<model::Model>,
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use crate::integer::{Planar64Vec3,Planar64Affine3};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::integer::{Planar64,Planar64Vec3,Planar64Affine3};
|
||||
use crate::gameplay_attributes;
|
||||
|
||||
pub type TextureCoordinate=glam::Vec2;
|
||||
@@ -123,6 +125,92 @@ pub struct Mesh{
|
||||
pub physics_groups:Vec<IndexedPhysicsGroup>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct MeshBuilder{
|
||||
unique_pos:Vec<Planar64Vec3>,//Unit32Vec3
|
||||
unique_normal:Vec<Planar64Vec3>,//Unit32Vec3
|
||||
unique_tex:Vec<TextureCoordinate>,
|
||||
unique_color:Vec<Color4>,
|
||||
unique_vertices:Vec<IndexedVertex>,
|
||||
pos_id_from:HashMap<Planar64Vec3,PositionId>,//Unit32Vec3
|
||||
normal_id_from:HashMap<Planar64Vec3,NormalId>,//Unit32Vec3
|
||||
tex_id_from:HashMap<[u32;2],TextureCoordinateId>,
|
||||
color_id_from:HashMap<[u32;4],ColorId>,
|
||||
vertex_id_from:HashMap<IndexedVertex,VertexId>,
|
||||
}
|
||||
impl MeshBuilder{
|
||||
pub fn new()->Self{
|
||||
Self::default()
|
||||
}
|
||||
pub fn build(
|
||||
self,
|
||||
polygon_groups:Vec<PolygonGroup>,
|
||||
graphics_groups:Vec<IndexedGraphicsGroup>,
|
||||
physics_groups:Vec<IndexedPhysicsGroup>,
|
||||
)->Mesh{
|
||||
let MeshBuilder{
|
||||
unique_pos,
|
||||
unique_normal,
|
||||
unique_tex,
|
||||
unique_color,
|
||||
unique_vertices,
|
||||
..
|
||||
}=self;
|
||||
Mesh{
|
||||
unique_pos,
|
||||
unique_normal,
|
||||
unique_tex,
|
||||
unique_color,
|
||||
unique_vertices,
|
||||
polygon_groups,
|
||||
graphics_groups,
|
||||
physics_groups,
|
||||
}
|
||||
}
|
||||
pub fn acquire_pos_id(&mut self,pos:Planar64Vec3)->PositionId{
|
||||
// Truncate the 16 most precise bits of the vertex positions.
|
||||
// This allows the normal vectors to exactly represent the face.
|
||||
// Remove this in Mesh V2
|
||||
const MASK:Planar64=Planar64::raw(!((1<<16)-1));
|
||||
let pos=pos.map(|c|c&MASK);
|
||||
*self.pos_id_from.entry(pos).or_insert_with(||{
|
||||
let pos_id=PositionId::new(self.unique_pos.len() as u32);
|
||||
self.unique_pos.push(pos);
|
||||
pos_id
|
||||
})
|
||||
}
|
||||
pub fn acquire_normal_id(&mut self,normal:Planar64Vec3)->NormalId{
|
||||
*self.normal_id_from.entry(normal).or_insert_with(||{
|
||||
let normal_id=NormalId::new(self.unique_normal.len() as u32);
|
||||
self.unique_normal.push(normal);
|
||||
normal_id
|
||||
})
|
||||
}
|
||||
pub fn acquire_tex_id(&mut self,tex:TextureCoordinate)->TextureCoordinateId{
|
||||
let h=tex.to_array().map(f32::to_bits);
|
||||
*self.tex_id_from.entry(h).or_insert_with(||{
|
||||
let tex_id=TextureCoordinateId::new(self.unique_tex.len() as u32);
|
||||
self.unique_tex.push(tex);
|
||||
tex_id
|
||||
})
|
||||
}
|
||||
pub fn acquire_color_id(&mut self,color:Color4)->ColorId{
|
||||
let h=color.to_array().map(f32::to_bits);
|
||||
*self.color_id_from.entry(h).or_insert_with(||{
|
||||
let color_id=ColorId::new(self.unique_color.len() as u32);
|
||||
self.unique_color.push(color);
|
||||
color_id
|
||||
})
|
||||
}
|
||||
pub fn acquire_vertex_id(&mut self,vertex:IndexedVertex)->VertexId{
|
||||
*self.vertex_id_from.entry(vertex.clone()).or_insert_with(||{
|
||||
let vertex_id=VertexId::new(self.unique_vertices.len() as u32);
|
||||
self.unique_vertices.push(vertex);
|
||||
vertex_id
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug,Clone,Copy,Hash,id::Id,Eq,PartialEq)]
|
||||
pub struct ModelId(u32);
|
||||
pub struct Model{
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::mouse::MouseState;
|
||||
use crate::gameplay_modes::{ModeId,StageId};
|
||||
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq,PartialOrd,Debug)]
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq,Ord,PartialOrd,Debug)]
|
||||
pub enum TimeInner{}
|
||||
pub type Time=crate::integer::Time<TimeInner>;
|
||||
|
||||
@@ -36,6 +36,7 @@ pub enum SetControlInstruction{
|
||||
SetMoveForward(bool),
|
||||
SetJump(bool),
|
||||
SetZoom(bool),
|
||||
SetSprint(bool),
|
||||
}
|
||||
#[derive(Clone,Debug)]
|
||||
pub enum ModeInstruction{
|
||||
|
||||
20
lib/common/src/ray.rs
Normal file
20
lib/common/src/ray.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use ratio_ops::ratio::Ratio;
|
||||
use crate::integer::{self,Planar64,Planar64Vec3};
|
||||
|
||||
pub struct Ray{
|
||||
pub origin:Planar64Vec3,
|
||||
pub direction:Planar64Vec3,
|
||||
}
|
||||
impl Ray{
|
||||
pub fn extrapolate<Num,Den,N1,T1>(&self,t:Ratio<Num,Den>)->Planar64Vec3
|
||||
where
|
||||
Num:Copy,
|
||||
Den:Copy,
|
||||
Num:core::ops::Mul<Planar64,Output=N1>,
|
||||
Planar64:core::ops::Mul<Den,Output=N1>,
|
||||
N1:integer::Divide<Den,Output=T1>,
|
||||
T1:integer::Clamp<Planar64>,
|
||||
{
|
||||
self.origin+self.direction.map(|elem|(t*elem).divide().clamp())
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use crate::timer::{TimerFixed,Realtime,Paused,Unpaused};
|
||||
|
||||
use crate::physics::{TimeInner as PhysicsTimeInner,Time as PhysicsTime};
|
||||
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq,PartialOrd,Debug)]
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq,Ord,PartialOrd,Debug)]
|
||||
pub enum TimeInner{}
|
||||
pub type Time=crate::integer::Time<TimeInner>;
|
||||
|
||||
@@ -53,36 +53,23 @@ impl std::fmt::Display for Error{
|
||||
impl std::error::Error for Error{}
|
||||
|
||||
#[derive(Clone,Copy,Debug)]
|
||||
enum RunState{
|
||||
pub enum RunState{
|
||||
Created,
|
||||
Started{timer:TimerFixed<Realtime<PhysicsTimeInner,TimeInner>,Unpaused>},
|
||||
Finished{timer:TimerFixed<Realtime<PhysicsTimeInner,TimeInner>,Paused>},
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Debug)]
|
||||
pub struct Run{
|
||||
state:RunState,
|
||||
flagged:Option<FlagReason>,
|
||||
}
|
||||
|
||||
impl Run{
|
||||
pub fn new()->Self{
|
||||
Self{
|
||||
state:RunState::Created,
|
||||
flagged:None,
|
||||
}
|
||||
}
|
||||
impl RunState{
|
||||
pub fn time(&self,time:PhysicsTime)->Time{
|
||||
match &self.state{
|
||||
match &self{
|
||||
RunState::Created=>Time::ZERO,
|
||||
RunState::Started{timer}=>timer.time(time),
|
||||
RunState::Finished{timer}=>timer.time(time),
|
||||
RunState::Finished{timer}=>timer.time(),
|
||||
}
|
||||
}
|
||||
pub fn start(&mut self,time:PhysicsTime)->Result<(),Error>{
|
||||
match &self.state{
|
||||
match &self{
|
||||
RunState::Created=>{
|
||||
self.state=RunState::Started{
|
||||
*self=RunState::Started{
|
||||
timer:TimerFixed::new(time,Time::ZERO),
|
||||
};
|
||||
Ok(())
|
||||
@@ -93,10 +80,10 @@ impl Run{
|
||||
}
|
||||
pub fn finish(&mut self,time:PhysicsTime)->Result<(),Error>{
|
||||
//this uses Copy
|
||||
match &self.state{
|
||||
match &self{
|
||||
RunState::Created=>Err(Error::NotStarted),
|
||||
RunState::Started{timer}=>{
|
||||
self.state=RunState::Finished{
|
||||
*self=RunState::Finished{
|
||||
timer:timer.into_paused(time),
|
||||
};
|
||||
Ok(())
|
||||
@@ -104,10 +91,43 @@ impl Run{
|
||||
RunState::Finished{..}=>Err(Error::AlreadyFinished),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Debug)]
|
||||
pub struct Run{
|
||||
state:RunState,
|
||||
flag_reason:Option<FlagReason>,
|
||||
}
|
||||
|
||||
impl Run{
|
||||
pub fn new()->Self{
|
||||
Self{
|
||||
state:RunState::Created,
|
||||
flag_reason:None,
|
||||
}
|
||||
}
|
||||
pub fn time(&self,time:PhysicsTime)->Time{
|
||||
self.state.time(time)
|
||||
}
|
||||
pub fn start(&mut self,time:PhysicsTime)->Result<(),Error>{
|
||||
self.state.start(time)
|
||||
}
|
||||
pub fn finish(&mut self,time:PhysicsTime)->Result<(),Error>{
|
||||
self.state.finish(time)
|
||||
}
|
||||
pub fn flag(&mut self,flag_reason:FlagReason){
|
||||
//don't replace the first reason the run was flagged
|
||||
if self.flagged.is_none(){
|
||||
self.flagged=Some(flag_reason);
|
||||
if self.flag_reason.is_none(){
|
||||
self.flag_reason=Some(flag_reason);
|
||||
}
|
||||
}
|
||||
pub fn flag_reason(&self)->Option<FlagReason>{
|
||||
self.flag_reason
|
||||
}
|
||||
pub fn get_finish_time(&self)->Option<Time>{
|
||||
match &self.state{
|
||||
RunState::Finished{timer}=>Some(timer.time()),
|
||||
_=>None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq,PartialOrd,Debug)]
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq,Ord,PartialOrd,Debug)]
|
||||
pub enum TimeInner{}
|
||||
pub type Time=crate::integer::Time<TimeInner>;
|
||||
|
||||
@@ -23,7 +23,7 @@ impl PauseState for Unpaused{
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq,PartialOrd,Debug)]
|
||||
enum Inner{}
|
||||
pub enum Inner{}
|
||||
type InnerTime=Time<Inner>;
|
||||
|
||||
#[derive(Clone,Copy,Debug)]
|
||||
@@ -69,10 +69,8 @@ impl<In,Out> Scaled<In,Out>
|
||||
const fn get_scale(&self)->Ratio64{
|
||||
self.scale
|
||||
}
|
||||
fn set_scale(&mut self,time:Time<In>,new_scale:Ratio64){
|
||||
let new_time=self.get_time(time);
|
||||
const fn set_scale(&mut self,new_scale:Ratio64){
|
||||
self.scale=new_scale;
|
||||
self.set_time(time,new_time);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,7 +130,7 @@ pub struct TimerFixed<T:TimerState,P:PauseState>{
|
||||
_paused:P,
|
||||
}
|
||||
|
||||
//scaled timer methods are generic across PauseState
|
||||
//some scaled timer methods are generic across PauseState
|
||||
impl<P:PauseState,In,Out> TimerFixed<Scaled<In,Out>,P>
|
||||
where Time<In>:Copy,
|
||||
{
|
||||
@@ -147,8 +145,22 @@ impl<P:PauseState,In,Out> TimerFixed<Scaled<In,Out>,P>
|
||||
pub const fn get_scale(&self)->Ratio64{
|
||||
self.state.get_scale()
|
||||
}
|
||||
}
|
||||
// setting the scale of an unpaused timer is different than a paused timer
|
||||
impl<In,Out> TimerFixed<Scaled<In,Out>,Unpaused>
|
||||
where Time<In>:Copy,
|
||||
{
|
||||
pub fn set_scale(&mut self,time:Time<In>,new_scale:Ratio64){
|
||||
self.state.set_scale(time,new_scale)
|
||||
let new_time=self.state.get_time(time);
|
||||
self.state.set_scale(new_scale);
|
||||
self.state.set_time(time,new_time);
|
||||
}
|
||||
}
|
||||
impl<In,Out> TimerFixed<Scaled<In,Out>,Paused>
|
||||
where Time<In>:Copy,
|
||||
{
|
||||
pub fn set_scale(&mut self,new_scale:Ratio64){
|
||||
self.state.set_scale(new_scale);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,7 +169,7 @@ impl<T:TimerState> TimerFixed<T,Paused>
|
||||
where Time<T::In>:Copy,
|
||||
{
|
||||
pub fn into_unpaused(self,time:Time<T::In>)->TimerFixed<T,Unpaused>{
|
||||
let new_time=self.time(time);
|
||||
let new_time=self.time();
|
||||
let mut timer=TimerFixed{
|
||||
state:self.state,
|
||||
_paused:Unpaused,
|
||||
@@ -165,6 +177,9 @@ impl<T:TimerState> TimerFixed<T,Paused>
|
||||
timer.set_time(time,new_time);
|
||||
timer
|
||||
}
|
||||
pub fn time(&self)->Time<T::Out>{
|
||||
self.state.get_offset().coerce()
|
||||
}
|
||||
}
|
||||
impl<T:TimerState> TimerFixed<T,Unpaused>
|
||||
where Time<T::In>:Copy,
|
||||
@@ -178,6 +193,9 @@ impl<T:TimerState> TimerFixed<T,Unpaused>
|
||||
timer.set_time(time,new_time);
|
||||
timer
|
||||
}
|
||||
pub fn time(&self,time:Time<T::In>)->Time<T::Out>{
|
||||
self.state.get_time(time)
|
||||
}
|
||||
}
|
||||
|
||||
//the new constructor and time queries are generic across both
|
||||
@@ -199,12 +217,6 @@ impl<T:TimerState,P:PauseState> TimerFixed<T,P>{
|
||||
pub fn into_state(self)->T{
|
||||
self.state
|
||||
}
|
||||
pub fn time(&self,time:Time<T::In>)->Time<T::Out>{
|
||||
match P::IS_PAUSED{
|
||||
true=>self.state.get_offset().coerce(),
|
||||
false=>self.state.get_time(time),
|
||||
}
|
||||
}
|
||||
pub fn set_time(&mut self,time:Time<T::In>,new_time:Time<T::Out>){
|
||||
match P::IS_PAUSED{
|
||||
true=>self.state.set_offset(new_time.coerce()),
|
||||
@@ -256,7 +268,7 @@ impl<T:TimerState> Timer<T>
|
||||
}
|
||||
pub fn time(&self,time:Time<T::In>)->Time<T::Out>{
|
||||
match self{
|
||||
Self::Paused(timer)=>timer.time(time),
|
||||
Self::Paused(timer)=>timer.time(),
|
||||
Self::Unpaused(timer)=>timer.time(time),
|
||||
}
|
||||
}
|
||||
@@ -305,7 +317,7 @@ impl<In,Out> Timer<Scaled<In,Out>>
|
||||
}
|
||||
pub fn set_scale(&mut self,time:Time<In>,new_scale:Ratio64){
|
||||
match self{
|
||||
Self::Paused(timer)=>timer.set_scale(time,new_scale),
|
||||
Self::Paused(timer)=>timer.set_scale(new_scale),
|
||||
Self::Unpaused(timer)=>timer.set_scale(time,new_scale),
|
||||
}
|
||||
}
|
||||
@@ -329,7 +341,7 @@ mod test{
|
||||
//create a paused timer that reads 0s
|
||||
let timer=TimerFixed::<Scaled<Parent,Calculated>,Paused>::from_state(Scaled::new(0.5f32.try_into().unwrap(),sec!(0)));
|
||||
//the paused timer at 1 second should read 0s
|
||||
assert_eq!(timer.time(sec!(1)),sec!(0));
|
||||
assert_eq!(timer.time(),sec!(0));
|
||||
|
||||
//unpause it after one second
|
||||
let timer=timer.into_unpaused(sec!(1));
|
||||
@@ -339,7 +351,7 @@ mod test{
|
||||
//pause the timer after 11 seconds
|
||||
let timer=timer.into_paused(sec!(11));
|
||||
//the paused timer at 20 seconds should read 5s
|
||||
assert_eq!(timer.time(sec!(20)),sec!(5));
|
||||
assert_eq!(timer.time(),sec!(5));
|
||||
}
|
||||
#[test]
|
||||
fn test_timer()->Result<(),Error>{
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
pub trait Updatable<Updater>{
|
||||
fn update(&mut self,update:Updater);
|
||||
}
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq)]
|
||||
struct InnerId(u32);
|
||||
#[derive(Clone)]
|
||||
struct Inner{
|
||||
id:InnerId,
|
||||
enabled:bool,
|
||||
}
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq)]
|
||||
struct OuterId(u32);
|
||||
struct Outer{
|
||||
id:OuterId,
|
||||
inners:std::collections::HashMap<InnerId,Inner>,
|
||||
}
|
||||
|
||||
enum Update<I,U>{
|
||||
Insert(I),
|
||||
Update(U),
|
||||
Remove
|
||||
}
|
||||
|
||||
struct InnerUpdate{
|
||||
//#[updatable(Update)]
|
||||
enabled:Option<bool>,
|
||||
}
|
||||
struct OuterUpdate{
|
||||
//#[updatable(Insert,Update,Remove)]
|
||||
inners:std::collections::HashMap<InnerId,Update<Inner,InnerUpdate>>,
|
||||
//#[updatable(Update)]
|
||||
//inners:std::collections::HashMap<InnerId,InnerUpdate>,
|
||||
}
|
||||
impl Updatable<InnerUpdate> for Inner{
|
||||
fn update(&mut self,update:InnerUpdate){
|
||||
if let Some(enabled)=update.enabled{
|
||||
self.enabled=enabled;
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Updatable<OuterUpdate> for Outer{
|
||||
fn update(&mut self,update:OuterUpdate){
|
||||
for (id,up) in update.inners{
|
||||
match up{
|
||||
Update::Insert(new_inner)=>self.inners.insert(id,new_inner),
|
||||
Update::Update(inner_update)=>self.inners.get_mut(&id).map(|inner|{
|
||||
let old=inner.clone();
|
||||
inner.update(inner_update);
|
||||
old
|
||||
}),
|
||||
Update::Remove=>self.inners.remove(&id),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
//*/
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "strafesnet_deferred_loader"
|
||||
version = "0.4.1"
|
||||
edition = "2021"
|
||||
version = "0.6.0"
|
||||
edition = "2024"
|
||||
repository = "https://git.itzana.me/StrafesNET/strafe-project"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Acquire IDs for objects before loading them in bulk."
|
||||
@@ -9,13 +9,8 @@ authors = ["Rhys Lloyd <krakow20@gmail.com>"]
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[features]
|
||||
default = ["legacy"]
|
||||
legacy = ["dep:url","dep:vbsp"]
|
||||
#roblox = ["dep:lazy-regex"]
|
||||
#source = ["dep:vbsp"]
|
||||
|
||||
[dependencies]
|
||||
strafesnet_common = { path = "../common", registry = "strafesnet" }
|
||||
url = { version = "2.5.2", optional = true }
|
||||
vbsp = { version = "0.6.0", optional = true }
|
||||
strafesnet_common.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
116
lib/deferred_loader/src/deferred_loader.rs
Normal file
116
lib/deferred_loader/src/deferred_loader.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
use std::collections::HashMap;
|
||||
use crate::loader::Loader;
|
||||
use crate::mesh::Meshes;
|
||||
use crate::texture::{RenderConfigs,Texture};
|
||||
use strafesnet_common::model::{MeshId,RenderConfig,RenderConfigId,TextureId};
|
||||
|
||||
#[derive(Clone,Copy,Debug)]
|
||||
pub enum LoadFailureMode{
|
||||
DefaultToNone,
|
||||
Fatal,
|
||||
}
|
||||
|
||||
pub struct RenderConfigDeferredLoader<H>{
|
||||
texture_count:u32,
|
||||
render_configs:Vec<RenderConfig>,
|
||||
render_config_id_from_asset_id:HashMap<Option<H>,RenderConfigId>,
|
||||
}
|
||||
impl<H> RenderConfigDeferredLoader<H>{
|
||||
pub fn new()->Self{
|
||||
Self{
|
||||
texture_count:0,
|
||||
render_configs:Vec::new(),
|
||||
render_config_id_from_asset_id:HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<H:core::hash::Hash+Eq> RenderConfigDeferredLoader<H>{
|
||||
pub fn acquire_render_config_id(&mut self,index:Option<H>)->RenderConfigId{
|
||||
let some_texture=index.is_some();
|
||||
*self.render_config_id_from_asset_id.entry(index).or_insert_with(||{
|
||||
//create the render config.
|
||||
let render_config=if some_texture{
|
||||
let render_config=RenderConfig::texture(TextureId::new(self.texture_count));
|
||||
self.texture_count+=1;
|
||||
render_config
|
||||
}else{
|
||||
RenderConfig::default()
|
||||
};
|
||||
let render_id=RenderConfigId::new(self.render_configs.len() as u32);
|
||||
self.render_configs.push(render_config);
|
||||
render_id
|
||||
})
|
||||
}
|
||||
pub fn into_indices(self)->impl Iterator<Item=H>{
|
||||
self.render_config_id_from_asset_id.into_keys().flatten()
|
||||
}
|
||||
pub fn into_render_configs<'a,L:Loader<Resource=Texture,Index<'a>=H>+'a>(mut self,loader:&mut L,failure_mode:LoadFailureMode)->Result<RenderConfigs,L::Error>{
|
||||
let mut sorted_textures=vec![None;self.texture_count as usize];
|
||||
for (index_option,render_config_id) in self.render_config_id_from_asset_id{
|
||||
let render_config=&mut self.render_configs[render_config_id.get() as usize];
|
||||
if let (Some(index),Some(texture_id))=(index_option,render_config.texture){
|
||||
let resource_result=loader.load(index);
|
||||
let texture=match failure_mode{
|
||||
// if texture fails to load, use no texture
|
||||
LoadFailureMode::DefaultToNone=>match resource_result{
|
||||
Ok(texture)=>Some(texture),
|
||||
Err(e)=>{
|
||||
render_config.texture=None;
|
||||
println!("Error loading texture: {e}");
|
||||
None
|
||||
},
|
||||
},
|
||||
// loading failure is fatal
|
||||
LoadFailureMode::Fatal=>Some(resource_result?)
|
||||
};
|
||||
sorted_textures[texture_id.get() as usize]=texture;
|
||||
}
|
||||
}
|
||||
Ok(RenderConfigs::new(
|
||||
sorted_textures,
|
||||
self.render_configs,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MeshDeferredLoader<H>{
|
||||
mesh_id_from_asset_id:HashMap<H,MeshId>,
|
||||
}
|
||||
impl<H> MeshDeferredLoader<H>{
|
||||
pub fn new()->Self{
|
||||
Self{
|
||||
mesh_id_from_asset_id:HashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<H:core::hash::Hash+Eq> MeshDeferredLoader<H>{
|
||||
pub fn acquire_mesh_id(&mut self,index:H)->MeshId{
|
||||
let mesh_id=MeshId::new(self.mesh_id_from_asset_id.len() as u32);
|
||||
*self.mesh_id_from_asset_id.entry(index).or_insert(mesh_id)
|
||||
}
|
||||
pub fn into_indices(self)->impl Iterator<Item=H>{
|
||||
self.mesh_id_from_asset_id.into_keys()
|
||||
}
|
||||
pub fn into_meshes<'a,M:Clone,L:Loader<Resource=M,Index<'a>=H>+'a>(self,loader:&mut L,failure_mode:LoadFailureMode)->Result<Meshes<M>,L::Error>{
|
||||
let mut mesh_list=vec![None;self.mesh_id_from_asset_id.len()];
|
||||
for (index,mesh_id) in self.mesh_id_from_asset_id{
|
||||
let resource_result=loader.load(index);
|
||||
let mesh=match failure_mode{
|
||||
// if mesh fails to load, use no mesh
|
||||
LoadFailureMode::DefaultToNone=>match resource_result{
|
||||
Ok(mesh)=>Some(mesh),
|
||||
Err(e)=>{
|
||||
println!("Error loading mesh: {e}");
|
||||
None
|
||||
},
|
||||
},
|
||||
// loading failure is fatal
|
||||
LoadFailureMode::Fatal=>Some(resource_result?)
|
||||
};
|
||||
mesh_list[mesh_id.get() as usize]=mesh;
|
||||
}
|
||||
Ok(Meshes::new(mesh_list))
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,5 @@
|
||||
#[cfg(feature="legacy")]
|
||||
mod roblox_legacy;
|
||||
#[cfg(feature="legacy")]
|
||||
mod source_legacy;
|
||||
#[cfg(feature="roblox")]
|
||||
mod roblox;
|
||||
#[cfg(feature="source")]
|
||||
mod source;
|
||||
|
||||
#[cfg(any(feature="roblox",feature="legacy"))]
|
||||
pub mod rbxassetid;
|
||||
|
||||
pub mod mesh;
|
||||
pub mod loader;
|
||||
pub mod texture;
|
||||
#[cfg(any(feature="source",feature="legacy"))]
|
||||
pub mod valve_mesh;
|
||||
#[cfg(any(feature="roblox",feature="legacy"))]
|
||||
pub mod roblox_mesh;
|
||||
|
||||
#[cfg(feature="legacy")]
|
||||
pub fn roblox_legacy()->roblox_legacy::Loader{
|
||||
roblox_legacy::Loader::new()
|
||||
}
|
||||
#[cfg(feature="legacy")]
|
||||
pub fn source_legacy()->source_legacy::Loader{
|
||||
source_legacy::Loader::new()
|
||||
}
|
||||
#[cfg(feature="roblox")]
|
||||
pub fn roblox()->roblox::Loader{
|
||||
roblox::Loader::new()
|
||||
}
|
||||
#[cfg(feature="source")]
|
||||
pub fn source()->source::Loader{
|
||||
source::Loader::new()
|
||||
}
|
||||
pub mod deferred_loader;
|
||||
|
||||
8
lib/deferred_loader/src/loader.rs
Normal file
8
lib/deferred_loader/src/loader.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
use std::error::Error;
|
||||
|
||||
pub trait Loader{
|
||||
type Error:Error;
|
||||
type Index<'a> where Self:'a;
|
||||
type Resource;
|
||||
fn load(&mut self,index:Self::Index<'_>)->Result<Self::Resource,Self::Error>;
|
||||
}
|
||||
17
lib/deferred_loader/src/mesh.rs
Normal file
17
lib/deferred_loader/src/mesh.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
use strafesnet_common::model::MeshId;
|
||||
|
||||
pub struct Meshes<M>{
|
||||
meshes:Vec<Option<M>>,
|
||||
}
|
||||
impl<M> Meshes<M>{
|
||||
pub(crate) const fn new(meshes:Vec<Option<M>>)->Self{
|
||||
Self{
|
||||
meshes,
|
||||
}
|
||||
}
|
||||
pub fn consume(self)->impl Iterator<Item=(MeshId,M)>{
|
||||
self.meshes.into_iter().enumerate().filter_map(|(mesh_id,maybe_mesh)|
|
||||
maybe_mesh.map(|mesh|(MeshId::new(mesh_id as u32),mesh))
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
#[derive(Hash,Eq,PartialEq)]
|
||||
pub struct RobloxAssetId(pub u64);
|
||||
#[derive(Debug)]
|
||||
#[allow(dead_code)]
|
||||
pub struct StringWithError{
|
||||
string:String,
|
||||
error:RobloxAssetIdParseErr,
|
||||
}
|
||||
impl std::fmt::Display for StringWithError{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"{self:?}")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for StringWithError{}
|
||||
impl StringWithError{
|
||||
const fn new(
|
||||
string:String,
|
||||
error:RobloxAssetIdParseErr,
|
||||
)->Self{
|
||||
Self{string,error}
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub enum RobloxAssetIdParseErr{
|
||||
Url(url::ParseError),
|
||||
UnknownScheme,
|
||||
ParseInt(std::num::ParseIntError),
|
||||
MissingAssetId,
|
||||
}
|
||||
impl std::str::FromStr for RobloxAssetId{
|
||||
type Err=StringWithError;
|
||||
fn from_str(s:&str)->Result<Self,Self::Err>{
|
||||
let url=url::Url::parse(s).map_err(|e|StringWithError::new(s.to_owned(),RobloxAssetIdParseErr::Url(e)))?;
|
||||
let parsed_asset_id=match url.scheme(){
|
||||
"rbxassetid"=>url.domain().ok_or_else(||StringWithError::new(s.to_owned(),RobloxAssetIdParseErr::MissingAssetId))?.parse(),
|
||||
"http"|"https"=>{
|
||||
let (_,asset_id)=url.query_pairs()
|
||||
.find(|(id,_)|match id.as_ref(){
|
||||
"ID"|"id"|"Id"|"iD"=>true,
|
||||
_=>false,
|
||||
}).ok_or_else(||StringWithError::new(s.to_owned(),RobloxAssetIdParseErr::MissingAssetId))?;
|
||||
asset_id.parse()
|
||||
},
|
||||
_=>Err(StringWithError::new(s.to_owned(),RobloxAssetIdParseErr::UnknownScheme))?,
|
||||
};
|
||||
Ok(Self(parsed_asset_id.map_err(|e|StringWithError::new(s.to_owned(),RobloxAssetIdParseErr::ParseInt(e)))?))
|
||||
}
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
use std::io::Read;
|
||||
use std::collections::HashMap;
|
||||
use crate::roblox_mesh;
|
||||
use crate::texture::{RenderConfigs,Texture};
|
||||
use strafesnet_common::model::{MeshId,RenderConfig,RenderConfigId,TextureId};
|
||||
use crate::rbxassetid::RobloxAssetId;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct RenderConfigLoader{
|
||||
texture_count:u32,
|
||||
render_configs:Vec<RenderConfig>,
|
||||
render_config_id_from_asset_id:HashMap<Option<RobloxAssetId>,RenderConfigId>,
|
||||
}
|
||||
|
||||
impl RenderConfigLoader{
|
||||
pub fn acquire_render_config_id(&mut self,name:Option<&str>)->RenderConfigId{
|
||||
let render_id=RenderConfigId::new(self.render_config_id_from_asset_id.len() as u32);
|
||||
let index=name.and_then(|name|{
|
||||
match name.parse::<RobloxAssetId>(){
|
||||
Ok(asset_id)=>Some(asset_id),
|
||||
Err(e)=>{
|
||||
println!("Failed to parse AssetId: {e}");
|
||||
None
|
||||
},
|
||||
}
|
||||
});
|
||||
*self.render_config_id_from_asset_id.entry(index).or_insert_with(||{
|
||||
//create the render config.
|
||||
let render_config=if name.is_some(){
|
||||
let render_config=RenderConfig::texture(TextureId::new(self.texture_count));
|
||||
self.texture_count+=1;
|
||||
render_config
|
||||
}else{
|
||||
RenderConfig::default()
|
||||
};
|
||||
self.render_configs.push(render_config);
|
||||
render_id
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct MeshLoader{
|
||||
mesh_id_from_asset_id:HashMap<Option<RobloxAssetId>,MeshId>,
|
||||
}
|
||||
|
||||
impl MeshLoader{
|
||||
pub fn acquire_mesh_id(&mut self,name:&str)->MeshId{
|
||||
let mesh_id=MeshId::new(self.mesh_id_from_asset_id.len() as u32);
|
||||
let index=match name.parse::<RobloxAssetId>(){
|
||||
Ok(asset_id)=>Some(asset_id),
|
||||
Err(e)=>{
|
||||
println!("Failed to parse AssetId: {e}");
|
||||
None
|
||||
},
|
||||
};
|
||||
*self.mesh_id_from_asset_id.entry(index).or_insert(mesh_id)
|
||||
}
|
||||
pub fn load_meshes(&mut self)->Result<roblox_mesh::Meshes,std::io::Error>{
|
||||
let mut mesh_data=vec![None;self.mesh_id_from_asset_id.len()];
|
||||
for (asset_id_option,mesh_id) in &self.mesh_id_from_asset_id{
|
||||
if let Some(asset_id)=asset_id_option{
|
||||
if let Ok(mut file)=std::fs::File::open(format!("meshes/{}",asset_id.0)){
|
||||
//TODO: parallel
|
||||
let mut data=Vec::<u8>::new();
|
||||
file.read_to_end(&mut data)?;
|
||||
mesh_data[mesh_id.get() as usize]=Some(roblox_mesh::RobloxMeshData::new(data));
|
||||
}else{
|
||||
println!("[roblox_legacy] no mesh name={}",asset_id.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(roblox_mesh::Meshes::new(mesh_data))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Loader{
|
||||
render_config_loader:RenderConfigLoader,
|
||||
mesh_loader:MeshLoader,
|
||||
}
|
||||
impl Loader{
|
||||
pub fn new()->Self{
|
||||
Self{
|
||||
render_config_loader:RenderConfigLoader::default(),
|
||||
mesh_loader:MeshLoader::default(),
|
||||
}
|
||||
}
|
||||
pub fn get_inner_mut(&mut self)->(&mut RenderConfigLoader,&mut MeshLoader){
|
||||
(&mut self.render_config_loader,&mut self.mesh_loader)
|
||||
}
|
||||
pub fn into_render_configs(mut self)->Result<RenderConfigs,std::io::Error>{
|
||||
let mut sorted_textures=vec![None;self.render_config_loader.texture_count as usize];
|
||||
for (asset_id_option,render_config_id) in self.render_config_loader.render_config_id_from_asset_id{
|
||||
let render_config=self.render_config_loader.render_configs.get_mut(render_config_id.get() as usize).unwrap();
|
||||
if let (Some(asset_id),Some(texture_id))=(asset_id_option,render_config.texture){
|
||||
if let Ok(mut file)=std::fs::File::open(format!("textures/{}.dds",asset_id.0)){
|
||||
//TODO: parallel
|
||||
let mut data=Vec::<u8>::new();
|
||||
file.read_to_end(&mut data)?;
|
||||
sorted_textures[texture_id.get() as usize]=Some(Texture::ImageDDS(data));
|
||||
}else{
|
||||
//texture failed to load
|
||||
render_config.texture=None;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(RenderConfigs::new(
|
||||
sorted_textures,
|
||||
self.render_config_loader.render_configs,
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
use strafesnet_common::model::MeshId;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RobloxMeshData(Vec<u8>);
|
||||
impl RobloxMeshData{
|
||||
pub(crate) fn new(data:Vec<u8>)->Self{
|
||||
Self(data)
|
||||
}
|
||||
pub fn get(self)->Vec<u8>{
|
||||
self.0
|
||||
}
|
||||
}
|
||||
pub struct Meshes{
|
||||
meshes:Vec<Option<RobloxMeshData>>,
|
||||
}
|
||||
impl Meshes{
|
||||
pub(crate) const fn new(meshes:Vec<Option<RobloxMeshData>>)->Self{
|
||||
Self{
|
||||
meshes,
|
||||
}
|
||||
}
|
||||
pub fn get_texture(&self,texture_id:MeshId)->Option<&RobloxMeshData>{
|
||||
self.meshes.get(texture_id.get() as usize)?.as_ref()
|
||||
}
|
||||
pub fn into_iter(self)->impl Iterator<Item=(MeshId,RobloxMeshData)>{
|
||||
self.meshes.into_iter().enumerate().filter_map(|(mesh_id,maybe_mesh)|
|
||||
maybe_mesh.map(|mesh|(MeshId::new(mesh_id as u32),mesh))
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
use std::io::Read;
|
||||
use std::collections::HashMap;
|
||||
use crate::valve_mesh;
|
||||
use crate::texture::{Texture,RenderConfigs};
|
||||
use strafesnet_common::model::{MeshId,TextureId,RenderConfig,RenderConfigId};
|
||||
|
||||
pub struct RenderConfigLoader{
|
||||
texture_count:u32,
|
||||
render_configs:Vec<RenderConfig>,
|
||||
texture_paths:HashMap<Option<Box<str>>,RenderConfigId>,
|
||||
}
|
||||
impl RenderConfigLoader{
|
||||
pub fn acquire_render_config_id(&mut self,name:Option<&str>)->RenderConfigId{
|
||||
let render_id=RenderConfigId::new(self.texture_paths.len() as u32);
|
||||
*self.texture_paths.entry(name.map(Into::into)).or_insert_with(||{
|
||||
//create the render config.
|
||||
let render_config=if name.is_some(){
|
||||
let render_config=RenderConfig::texture(TextureId::new(self.texture_count));
|
||||
self.texture_count+=1;
|
||||
render_config
|
||||
}else{
|
||||
RenderConfig::default()
|
||||
};
|
||||
self.render_configs.push(render_config);
|
||||
render_id
|
||||
})
|
||||
}
|
||||
}
|
||||
pub struct MeshLoader{
|
||||
mesh_paths:HashMap<Box<str>,MeshId>,
|
||||
}
|
||||
impl MeshLoader{
|
||||
pub fn acquire_mesh_id(&mut self,name:&str)->MeshId{
|
||||
let mesh_id=MeshId::new(self.mesh_paths.len() as u32);
|
||||
*self.mesh_paths.entry(name.into()).or_insert(mesh_id)
|
||||
}
|
||||
//load_meshes should look like load_textures
|
||||
pub fn load_meshes(&mut self,bsp:&vbsp::Bsp)->valve_mesh::Meshes{
|
||||
let mut mesh_data=vec![None;self.mesh_paths.len()];
|
||||
for (mesh_path,mesh_id) in &self.mesh_paths{
|
||||
let mesh_path_lower=mesh_path.to_lowercase();
|
||||
//.mdl, .vvd, .dx90.vtx
|
||||
let path=std::path::PathBuf::from(mesh_path_lower.as_str());
|
||||
let mut vvd_path=path.clone();
|
||||
let mut vtx_path=path.clone();
|
||||
vvd_path.set_extension("vvd");
|
||||
vtx_path.set_extension("dx90.vtx");
|
||||
match (bsp.pack.get(mesh_path_lower.as_str()),bsp.pack.get(vvd_path.as_os_str().to_str().unwrap()),bsp.pack.get(vtx_path.as_os_str().to_str().unwrap())){
|
||||
(Ok(Some(mdl_file)),Ok(Some(vvd_file)),Ok(Some(vtx_file)))=>{
|
||||
mesh_data[mesh_id.get() as usize]=Some(valve_mesh::ModelData{
|
||||
mdl:valve_mesh::MdlData::new(mdl_file),
|
||||
vtx:valve_mesh::VtxData::new(vtx_file),
|
||||
vvd:valve_mesh::VvdData::new(vvd_file),
|
||||
});
|
||||
},
|
||||
_=>println!("no model name={}",mesh_path),
|
||||
}
|
||||
}
|
||||
valve_mesh::Meshes::new(mesh_data)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Loader{
|
||||
render_config_loader:RenderConfigLoader,
|
||||
mesh_loader:MeshLoader,
|
||||
}
|
||||
impl Loader{
|
||||
pub fn new()->Self{
|
||||
Self{
|
||||
render_config_loader:RenderConfigLoader{
|
||||
texture_count:0,
|
||||
texture_paths:HashMap::new(),
|
||||
render_configs:Vec::new(),
|
||||
},
|
||||
mesh_loader:MeshLoader{mesh_paths:HashMap::new()},
|
||||
}
|
||||
}
|
||||
pub fn get_inner_mut(&mut self)->(&mut RenderConfigLoader,&mut MeshLoader){
|
||||
(&mut self.render_config_loader,&mut self.mesh_loader)
|
||||
}
|
||||
pub fn into_render_configs(mut self)->Result<RenderConfigs,std::io::Error>{
|
||||
let mut sorted_textures=vec![None;self.render_config_loader.texture_count as usize];
|
||||
for (texture_path,render_config_id) in self.render_config_loader.texture_paths{
|
||||
let render_config=self.render_config_loader.render_configs.get_mut(render_config_id.get() as usize).unwrap();
|
||||
if let (Some(texture_path),Some(texture_id))=(texture_path,render_config.texture){
|
||||
if let Ok(mut file)=std::fs::File::open(format!("textures/{}.dds",texture_path)){
|
||||
//TODO: parallel
|
||||
let mut data=Vec::<u8>::new();
|
||||
file.read_to_end(&mut data)?;
|
||||
sorted_textures[texture_id.get() as usize]=Some(Texture::ImageDDS(data));
|
||||
}else{
|
||||
//texture failed to load
|
||||
render_config.texture=None;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(RenderConfigs::new(
|
||||
sorted_textures,
|
||||
self.render_config_loader.render_configs,
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
use strafesnet_common::model::MeshId;
|
||||
|
||||
//duplicate this code for now
|
||||
#[derive(Clone)]
|
||||
pub struct MdlData(Vec<u8>);
|
||||
impl MdlData{
|
||||
pub const fn new(value:Vec<u8>)->Self{
|
||||
Self(value)
|
||||
}
|
||||
pub fn get(self)->Vec<u8>{
|
||||
self.0
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct VtxData(Vec<u8>);
|
||||
impl VtxData{
|
||||
pub const fn new(value:Vec<u8>)->Self{
|
||||
Self(value)
|
||||
}
|
||||
pub fn get(self)->Vec<u8>{
|
||||
self.0
|
||||
}
|
||||
}
|
||||
#[derive(Clone)]
|
||||
pub struct VvdData(Vec<u8>);
|
||||
impl VvdData{
|
||||
pub const fn new(value:Vec<u8>)->Self{
|
||||
Self(value)
|
||||
}
|
||||
pub fn get(self)->Vec<u8>{
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ModelData{
|
||||
pub mdl:MdlData,
|
||||
pub vtx:VtxData,
|
||||
pub vvd:VvdData,
|
||||
}
|
||||
|
||||
//meshes is more prone to failure
|
||||
pub struct Meshes{
|
||||
meshes:Vec<Option<ModelData>>,
|
||||
}
|
||||
impl Meshes{
|
||||
pub(crate) const fn new(meshes:Vec<Option<ModelData>>)->Self{
|
||||
Self{
|
||||
meshes,
|
||||
}
|
||||
}
|
||||
pub fn get_texture(&self,texture_id:MeshId)->Option<&ModelData>{
|
||||
self.meshes.get(texture_id.get() as usize)?.as_ref()
|
||||
}
|
||||
pub fn into_iter(self)->impl Iterator<Item=(MeshId,ModelData)>{
|
||||
self.meshes.into_iter().enumerate().filter_map(|(mesh_id,maybe_mesh)|
|
||||
maybe_mesh.map(|mesh|(MeshId::new(mesh_id as u32),mesh))
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "fixed_wide"
|
||||
version = "0.1.1"
|
||||
edition = "2021"
|
||||
version = "0.3.0"
|
||||
edition = "2024"
|
||||
repository = "https://git.itzana.me/StrafesNET/strafe-project"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Fixed point numbers with optional widening Mul operator."
|
||||
@@ -14,7 +14,10 @@ wide-mul=[]
|
||||
zeroes=["dep:arrayvec"]
|
||||
|
||||
[dependencies]
|
||||
bnum = "0.12.0"
|
||||
bnum = "0.14.3"
|
||||
arrayvec = { version = "0.7.6", optional = true }
|
||||
paste = "1.0.15"
|
||||
ratio_ops = { path = "../ratio_ops", registry = "strafesnet", optional = true }
|
||||
ratio_ops = { workspace = true, optional = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,195 +1,273 @@
|
||||
use crate::types::I32F32;
|
||||
use crate::types::I256F256;
|
||||
use crate::fixed::Fixed;
|
||||
use crate::types::{F64_32,F128_64,F192_96,F512_256};
|
||||
|
||||
#[test]
|
||||
fn you_can_add_numbers(){
|
||||
let a=I256F256::from((3i128*2).pow(4));
|
||||
assert_eq!(a+a,I256F256::from((3i128*2).pow(4)*2));
|
||||
let a=F512_256::from((3i128*2).pow(4));
|
||||
assert_eq!(a+a,F512_256::from((3i128*2).pow(4)*2));
|
||||
}
|
||||
|
||||
macro_rules! test_bit_by_bit{
|
||||
($n:expr,$float:ty,$mantissa_bits:expr)=>{{
|
||||
const MANT:u64=(1<<$mantissa_bits)-1;
|
||||
// all bits in range
|
||||
for i in 0..$n-$mantissa_bits{
|
||||
let a=Fixed::<{$n/8},{$n>>1}>::from_bits(bnum::cast::As::as_::<bnum::Int::<{$n/8}>>(MANT).shl(i));
|
||||
let b=(MANT as $float)*(2.0 as $float).powi(i as i32-{$n>>1});
|
||||
let f:$float=a.into();
|
||||
assert_eq!(f,b,"F{}_{} Into float {i}",$n,$n>>1);
|
||||
assert_eq!(a,b.try_into().unwrap(),"F{}_{} From float {i}",$n,$n>>1);
|
||||
}
|
||||
// underflow
|
||||
for i in 0u32..$mantissa_bits{
|
||||
let a=Fixed::<{$n/8},{$n>>1}>::from_bits(bnum::cast::As::as_::<bnum::Int::<{$n/8}>>(MANT>>i));
|
||||
let b=((MANT>>i) as $float)*(2.0 as $float).powi(-{$n>>1});
|
||||
let f:$float=a.into();
|
||||
assert_eq!(f,b,"Underflow F{}_{} Into float {i}",$n,$n>>1);
|
||||
assert_eq!(a,b.try_into().unwrap(),"Underflow F{}_{} From float {i}",$n,$n>>1);
|
||||
}
|
||||
}};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_many(){
|
||||
test_bit_by_bit!(64,f32,24);
|
||||
test_bit_by_bit!(128,f32,24);
|
||||
// f32 is reaching its limits here
|
||||
// test_bit_by_bit!(256,f32,24);
|
||||
// test_bit_by_bit!(512,f32,24);
|
||||
test_bit_by_bit!(64,f64,53);
|
||||
test_bit_by_bit!(128,f64,53);
|
||||
test_bit_by_bit!(256,f64,53);
|
||||
test_bit_by_bit!(512,f64,53);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_f32(){
|
||||
let a=I256F256::from(1)>>2;
|
||||
let a=F64_32::ZERO;
|
||||
let f:f32=a.into();
|
||||
assert_eq!(f,0.0f32);
|
||||
let a=F64_32::from(1)>>2;
|
||||
let f:f32=a.into();
|
||||
assert_eq!(f,0.25f32);
|
||||
let f:f32=(-a).into();
|
||||
assert_eq!(f,-0.25f32);
|
||||
let a=I256F256::from(0);
|
||||
let a=F64_32::MIN;
|
||||
let f:f32=a.into();
|
||||
assert_eq!(f,i32::MIN as f32);
|
||||
let a=F512_256::from(1)>>2;
|
||||
let f:f32=a.into();
|
||||
assert_eq!(f,0.25f32);
|
||||
let f:f32=(-a).into();
|
||||
assert_eq!(f,-0.25f32);
|
||||
let a=F512_256::from(0);
|
||||
let f:f32=(-a).into();
|
||||
assert_eq!(f,0f32);
|
||||
let a=I256F256::from(237946589723468975i64)<<16;
|
||||
let a=F512_256::from(237946589723468975i64)<<16;
|
||||
let f:f32=a.into();
|
||||
assert_eq!(f,237946589723468975f32*2.0f32.powi(16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn to_f64(){
|
||||
let a=I256F256::from(1)>>2;
|
||||
let a=F64_32::ZERO;
|
||||
let f:f64=a.into();
|
||||
assert_eq!(f,0.0f64);
|
||||
let a=F64_32::from(1)>>2;
|
||||
let f:f64=a.into();
|
||||
assert_eq!(f,0.25f64);
|
||||
let f:f64=(-a).into();
|
||||
assert_eq!(f,-0.25f64);
|
||||
let a=I256F256::from(0);
|
||||
let a=F64_32::MIN;
|
||||
let f:f64=a.into();
|
||||
assert_eq!(f,i32::MIN as f64);
|
||||
let a=F512_256::from(1)>>2;
|
||||
let f:f64=a.into();
|
||||
assert_eq!(f,0.25f64);
|
||||
let f:f64=(-a).into();
|
||||
assert_eq!(f,-0.25f64);
|
||||
let a=F512_256::from(0);
|
||||
let f:f64=(-a).into();
|
||||
assert_eq!(f,0f64);
|
||||
let a=I256F256::from(237946589723468975i64)<<16;
|
||||
let a=F512_256::from(237946589723468975i64)<<16;
|
||||
let f:f64=a.into();
|
||||
assert_eq!(f,237946589723468975f64*2.0f64.powi(16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_f32(){
|
||||
let a=I256F256::from(1)>>2;
|
||||
let b:Result<I256F256,_>=0.25f32.try_into();
|
||||
let a=F64_32::ZERO;
|
||||
let b:Result<F64_32,_>=0.0f32.try_into();
|
||||
assert_eq!(b,Ok(a));
|
||||
let a=I256F256::from(-1)>>2;
|
||||
let b:Result<I256F256,_>=(-0.25f32).try_into();
|
||||
let a=F512_256::from(1)>>2;
|
||||
let b:Result<F512_256,_>=0.25f32.try_into();
|
||||
assert_eq!(b,Ok(a));
|
||||
let a=I256F256::from(0);
|
||||
let b:Result<I256F256,_>=0.try_into();
|
||||
let a=F512_256::from(-1)>>2;
|
||||
let b:Result<F512_256,_>=(-0.25f32).try_into();
|
||||
assert_eq!(b,Ok(a));
|
||||
let a=I256F256::from(0b101011110101001010101010000000000000000000000000000i64)<<16;
|
||||
let b:Result<I256F256,_>=(0b101011110101001010101010000000000000000000000000000u64 as f32*2.0f32.powi(16)).try_into();
|
||||
let a=F512_256::from(0);
|
||||
let b:Result<F512_256,_>=0.try_into();
|
||||
assert_eq!(b,Ok(a));
|
||||
let a=F512_256::from(0b101011110101001010101010000000000000000000000000000i64)<<16;
|
||||
let b:Result<F512_256,_>=(0b101011110101001010101010000000000000000000000000000u64 as f32*2.0f32.powi(16)).try_into();
|
||||
assert_eq!(b,Ok(a));
|
||||
//I32F32::MAX into f32 is truncated into this value
|
||||
let a=I32F32::raw(0b111111111111111111111111000000000000000000000000000000000000000i64);
|
||||
let b:Result<I32F32,_>=Into::<f32>::into(I32F32::MAX).try_into();
|
||||
let a=F64_32::raw(0b111111111111111111111111000000000000000000000000000000000000000i64);
|
||||
let b:Result<F64_32,_>=Into::<f32>::into(F64_32::MAX).try_into();
|
||||
assert_eq!(b,Ok(a));
|
||||
//I32F32::MIN hits a special case since it's not representable as a positive signed integer
|
||||
//TODO: don't return an overflow because this is technically possible
|
||||
let a=I32F32::MIN;
|
||||
let b:Result<I32F32,_>=Into::<f32>::into(I32F32::MIN).try_into();
|
||||
let a=F64_32::MIN;
|
||||
let f:f32=a.into();
|
||||
let b:Result<F64_32,_>=f.try_into();
|
||||
assert_eq!(b,Err(crate::fixed::FixedFromFloatError::Overflow));
|
||||
//16 is within the 24 bits of float precision
|
||||
let b:Result<I32F32,_>=Into::<f32>::into(-I32F32::MIN.fix_2()).try_into();
|
||||
let a=-F64_32::MIN.widen_128();
|
||||
let f:f32=a.into();
|
||||
let b:Result<F64_32,_>=f.try_into();
|
||||
assert_eq!(b,Err(crate::fixed::FixedFromFloatError::Overflow));
|
||||
let b:Result<I32F32,_>=f32::MIN_POSITIVE.try_into();
|
||||
let b:Result<F64_32,_>=f32::MIN_POSITIVE.try_into();
|
||||
assert_eq!(b,Err(crate::fixed::FixedFromFloatError::Underflow));
|
||||
//test many cases
|
||||
for i in 0..64{
|
||||
let a=crate::fixed::Fixed::<2,64>::raw_digit(0b111111111111111111111111000000000000000000000000000000000000000i64)<<i;
|
||||
let a=F128_64::from_u64(0b111111111111111111111111000000000000000000000000000000000000000u64)<<i;
|
||||
let f:f32=a.into();
|
||||
let b:Result<crate::fixed::Fixed<2,64>,_>=f.try_into();
|
||||
let b:Result<F128_64,_>=f.try_into();
|
||||
assert_eq!(b,Ok(a));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_f64(){
|
||||
let a=I256F256::from(1)>>2;
|
||||
let b:Result<I256F256,_>=0.25f64.try_into();
|
||||
let a=F64_32::ZERO;
|
||||
let b:Result<F64_32,_>=0.0f64.try_into();
|
||||
assert_eq!(b,Ok(a));
|
||||
let a=I256F256::from(-1)>>2;
|
||||
let b:Result<I256F256,_>=(-0.25f64).try_into();
|
||||
let a=F512_256::from(1)>>2;
|
||||
let b:Result<F512_256,_>=0.25f64.try_into();
|
||||
assert_eq!(b,Ok(a));
|
||||
let a=I256F256::from(0);
|
||||
let b:Result<I256F256,_>=0.try_into();
|
||||
let a=F512_256::from(-1)>>2;
|
||||
let b:Result<F512_256,_>=(-0.25f64).try_into();
|
||||
assert_eq!(b,Ok(a));
|
||||
let a=I256F256::from(0b101011110101001010101010000000000000000000000000000i64)<<16;
|
||||
let b:Result<I256F256,_>=(0b101011110101001010101010000000000000000000000000000u64 as f64*2.0f64.powi(16)).try_into();
|
||||
let a=F512_256::from(0);
|
||||
let b:Result<F512_256,_>=0.try_into();
|
||||
assert_eq!(b,Ok(a));
|
||||
let a=F512_256::from(0b101011110101001010101010000000000000000000000000000i64)<<16;
|
||||
let b:Result<F512_256,_>=(0b101011110101001010101010000000000000000000000000000u64 as f64*2.0f64.powi(16)).try_into();
|
||||
assert_eq!(b,Ok(a));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn you_can_shr_numbers(){
|
||||
let a=I32F32::from(4);
|
||||
assert_eq!(a>>1,I32F32::from(2));
|
||||
let a=F64_32::from(4);
|
||||
assert_eq!(a>>1,F64_32::from(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wide_mul(){
|
||||
let a=I32F32::ONE;
|
||||
let aa=a.wide_mul_1_1(a);
|
||||
assert_eq!(aa,crate::types::I64F64::ONE);
|
||||
let a=F64_32::ONE;
|
||||
let aa=a.wide_mul_64_64(a);
|
||||
assert_eq!(aa,F128_64::ONE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wide_div(){
|
||||
let a=I32F32::ONE*4;
|
||||
let b=I32F32::ONE*2;
|
||||
let wide_a=a.wide_mul_1_1(I32F32::ONE);
|
||||
let wide_b=b.wide_mul_1_1(I32F32::ONE);
|
||||
let ab=a.wide_div_1_1(b);
|
||||
assert_eq!(ab,crate::types::I64F64::ONE*2);
|
||||
let wab=wide_a.wide_div_2_1(b);
|
||||
assert_eq!(wab,crate::fixed::Fixed::<3,96>::ONE*2);
|
||||
let awb=a.wide_div_1_2(wide_b);
|
||||
assert_eq!(awb,crate::fixed::Fixed::<3,96>::ONE*2);
|
||||
let a=F64_32::ONE*4;
|
||||
let b=F64_32::ONE*2;
|
||||
let wide_a=a.wide_mul_64_64(F64_32::ONE);
|
||||
let wide_b=b.wide_mul_64_64(F64_32::ONE);
|
||||
let ab=a.wide_div_64_64(b);
|
||||
assert_eq!(ab,F128_64::ONE*2);
|
||||
let wab=wide_a.wide_div_128_64(b);
|
||||
assert_eq!(wab,F192_96::ONE*2);
|
||||
let awb=a.wide_div_64_128(wide_b);
|
||||
assert_eq!(awb,F192_96::ONE*2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wide_mul_repeated() {
|
||||
let a=I32F32::from(2);
|
||||
let b=I32F32::from(3);
|
||||
let a=F64_32::from(2);
|
||||
let b=F64_32::from(3);
|
||||
|
||||
let w1=a.wide_mul_1_1(b);
|
||||
let w2=w1.wide_mul_2_2(w1);
|
||||
let w3=w2.wide_mul_4_4(w2);
|
||||
let w1=a.wide_mul_64_64(b);
|
||||
let w2=w1.wide_mul_128_128(w1);
|
||||
let w3=w2.wide_mul_256_256(w2);
|
||||
|
||||
assert_eq!(w3,I256F256::from((3i128*2).pow(4)));
|
||||
assert_eq!(w3,F512_256::from((3i128*2).pow(4)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bint(){
|
||||
let a=I32F32::ONE;
|
||||
assert_eq!(a*2,I32F32::from(2));
|
||||
let a=F64_32::ONE;
|
||||
assert_eq!(a*2,F64_32::from(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fix(){
|
||||
assert_eq!(I32F32::ONE.fix_8(),I256F256::ONE);
|
||||
assert_eq!(I32F32::ONE,I256F256::ONE.fix_1());
|
||||
assert_eq!(I32F32::NEG_ONE.fix_8(),I256F256::NEG_ONE);
|
||||
assert_eq!(I32F32::NEG_ONE,I256F256::NEG_ONE.fix_1());
|
||||
fn test_wrap(){
|
||||
assert_eq!(F64_32::ONE,F512_256::ONE.wrap_64());
|
||||
assert_eq!(F64_32::NEG_ONE,F512_256::NEG_ONE.wrap_64());
|
||||
}
|
||||
#[test]
|
||||
fn test_narrow(){
|
||||
assert_eq!(Ok(F64_32::ONE),F512_256::ONE.narrow_64());
|
||||
assert_eq!(Ok(F64_32::NEG_ONE),F512_256::NEG_ONE.narrow_64());
|
||||
}
|
||||
#[test]
|
||||
fn test_widen(){
|
||||
assert_eq!(F64_32::ONE.widen_512(),F512_256::ONE);
|
||||
assert_eq!(F64_32::NEG_ONE.widen_512(),F512_256::NEG_ONE);
|
||||
}
|
||||
#[test]
|
||||
fn test_clamp(){
|
||||
assert_eq!(F64_32::ONE,F512_256::ONE.clamp_64());
|
||||
assert_eq!(F64_32::NEG_ONE,F512_256::NEG_ONE.clamp_64());
|
||||
}
|
||||
#[test]
|
||||
fn test_sqrt(){
|
||||
let a=I32F32::ONE*4;
|
||||
assert_eq!(a.sqrt(),I32F32::from(2));
|
||||
let a=F64_32::ONE*4;
|
||||
assert_eq!(a.sqrt(),F64_32::from(2));
|
||||
}
|
||||
#[test]
|
||||
fn test_sqrt_zero(){
|
||||
let a=I32F32::ZERO;
|
||||
assert_eq!(a.sqrt(),I32F32::ZERO);
|
||||
let a=F64_32::ZERO;
|
||||
assert_eq!(a.sqrt(),F64_32::ZERO);
|
||||
}
|
||||
#[test]
|
||||
fn test_sqrt_low(){
|
||||
let a=I32F32::HALF;
|
||||
let a=F64_32::HALF;
|
||||
let b=a.fixed_mul(a);
|
||||
assert_eq!(b.sqrt(),a);
|
||||
}
|
||||
fn find_equiv_sqrt_via_f64(n:I32F32)->I32F32{
|
||||
fn find_equiv_sqrt_via_f64(n:F64_32)->F64_32{
|
||||
//GIMME THEM BITS BOY
|
||||
let &[bits]=n.to_bits().to_bits().digits();
|
||||
let ibits=bits as i64;
|
||||
let ibits=i64::from_le_bytes(n.to_bits().to_bytes());
|
||||
let f=(ibits as f64)/((1u64<<32) as f64);
|
||||
let f_ans=f.sqrt();
|
||||
let i=(f_ans*((1u64<<32) as f64)) as i64;
|
||||
let r=I32F32::from_bits(bnum::BInt::<1>::from(i));
|
||||
let i=(f_ans*((1u64<<32) as f64)) as u64;
|
||||
let r=F64_32::from_u64(i);
|
||||
//mimic the behaviour of the algorithm,
|
||||
//return the result if it truncates to the exact answer
|
||||
if (r+I32F32::EPSILON).wide_mul_1_1(r+I32F32::EPSILON)==n.wide_mul_1_1(I32F32::ONE){
|
||||
return r+I32F32::EPSILON;
|
||||
if (r+F64_32::EPSILON).wide_mul_64_64(r+F64_32::EPSILON)==n.wide_mul_64_64(F64_32::ONE){
|
||||
return r+F64_32::EPSILON;
|
||||
}
|
||||
if (r-I32F32::EPSILON).wide_mul_1_1(r-I32F32::EPSILON)==n.wide_mul_1_1(I32F32::ONE){
|
||||
return r-I32F32::EPSILON;
|
||||
if (r-F64_32::EPSILON).wide_mul_64_64(r-F64_32::EPSILON)==n.wide_mul_64_64(F64_32::ONE){
|
||||
return r-F64_32::EPSILON;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
fn test_exact(n:I32F32){
|
||||
fn test_exact(n:F64_32){
|
||||
assert_eq!(n.sqrt(),find_equiv_sqrt_via_f64(n));
|
||||
}
|
||||
#[test]
|
||||
fn test_sqrt_exact(){
|
||||
//43
|
||||
for i in 0..((i64::MAX as f32).ln() as u32){
|
||||
let n=I32F32::from_bits(bnum::BInt::<1>::from((i as f32).exp() as i64));
|
||||
let n=F64_32::from_u64((i as f32).exp() as u64);
|
||||
test_exact(n);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn test_sqrt_max(){
|
||||
let a=I32F32::MAX;
|
||||
let a=F64_32::MAX;
|
||||
test_exact(a);
|
||||
}
|
||||
#[test]
|
||||
@@ -197,9 +275,9 @@ fn test_sqrt_max(){
|
||||
fn test_zeroes_normal(){
|
||||
// (x-1)*(x+1)
|
||||
// x^2-1
|
||||
let zeroes=I32F32::zeroes2(I32F32::NEG_ONE,I32F32::ZERO,I32F32::ONE);
|
||||
let zeroes=F64_32::zeroes2(F64_32::NEG_ONE,F64_32::ZERO,F64_32::ONE);
|
||||
assert_eq!(zeroes,arrayvec::ArrayVec::from_iter([I32F32::NEG_ONE,I32F32::ONE]));
|
||||
let zeroes=I32F32::zeroes2(I32F32::NEG_ONE*3,I32F32::ONE*2,I32F32::ONE);
|
||||
let zeroes=F64_32::zeroes2(F64_32::NEG_ONE*3,F64_32::ONE*2,F64_32::ONE);
|
||||
assert_eq!(zeroes,arrayvec::ArrayVec::from_iter([I32F32::NEG_ONE*3,I32F32::ONE]));
|
||||
}
|
||||
#[test]
|
||||
@@ -207,12 +285,25 @@ fn test_zeroes_normal(){
|
||||
fn test_zeroes_deferred_division(){
|
||||
// (x-1)*(x+1)
|
||||
// x^2-1
|
||||
let zeroes=I32F32::zeroes2(I32F32::NEG_ONE,I32F32::ZERO,I32F32::ONE);
|
||||
let zeroes=F64_32::zeroes2(F64_32::NEG_ONE,F64_32::ZERO,F64_32::ONE);
|
||||
assert_eq!(
|
||||
zeroes,
|
||||
arrayvec::ArrayVec::from_iter([
|
||||
ratio_ops::ratio::Ratio::new(I32F32::ONE*2,I32F32::NEG_ONE*2),
|
||||
ratio_ops::ratio::Ratio::new(I32F32::ONE*2,I32F32::ONE*2),
|
||||
ratio_ops::ratio::Ratio::new(F64_32::ONE*2,F64_32::NEG_ONE*2),
|
||||
ratio_ops::ratio::Ratio::new(F64_32::ONE*2,F64_32::ONE*2),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_debug(){
|
||||
assert_eq!(format!("{:?}",F64_32::EPSILON),"0.00000001");
|
||||
assert_eq!(format!("{:?}",F64_32::ONE),"1.00000000");
|
||||
assert_eq!(format!("{:?}",F64_32::TWO),"2.00000000");
|
||||
assert_eq!(format!("{:?}",F64_32::MAX),"7fffffff.ffffffff");
|
||||
assert_eq!(format!("{:?}",F64_32::try_from(core::f64::consts::PI).unwrap()),"3.243f6a88");
|
||||
assert_eq!(format!("{:?}",F64_32::NEG_EPSILON),"-0.00000001");
|
||||
assert_eq!(format!("{:?}",F64_32::NEG_ONE),"-1.00000000");
|
||||
assert_eq!(format!("{:?}",F64_32::NEG_TWO),"-2.00000000");
|
||||
assert_eq!(format!("{:?}",F64_32::MIN),"-80000000.00000000");
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
pub type I32F32=crate::fixed::Fixed<1,32>;
|
||||
pub type I64F64=crate::fixed::Fixed<2,64>;
|
||||
pub type I128F128=crate::fixed::Fixed<4,128>;
|
||||
pub type I256F256=crate::fixed::Fixed<8,256>;
|
||||
use crate::fixed::BNUM_DIGIT_WIDTH;
|
||||
pub type F64_32=crate::fixed::Fixed<{64/BNUM_DIGIT_WIDTH},32>;
|
||||
pub type F128_64=crate::fixed::Fixed<{128/BNUM_DIGIT_WIDTH},64>;
|
||||
pub type F192_96=crate::fixed::Fixed<{192/BNUM_DIGIT_WIDTH},96>;
|
||||
pub type F256_128=crate::fixed::Fixed<{256/BNUM_DIGIT_WIDTH},128>;
|
||||
pub type F320_160=crate::fixed::Fixed<{320/BNUM_DIGIT_WIDTH},160>;
|
||||
pub type F512_256=crate::fixed::Fixed<{512/BNUM_DIGIT_WIDTH},256>;
|
||||
|
||||
@@ -1,39 +1,42 @@
|
||||
use crate::fixed::Fixed;
|
||||
use crate::fixed::BNUM_DIGIT_WIDTH;
|
||||
|
||||
use arrayvec::ArrayVec;
|
||||
use std::cmp::Ordering;
|
||||
macro_rules! impl_zeroes{
|
||||
($n:expr)=>{
|
||||
impl Fixed<$n,{$n*32}>{
|
||||
impl Fixed<{$n/BNUM_DIGIT_WIDTH},{$n>>1}>{
|
||||
#[inline]
|
||||
pub fn zeroes2(a0:Self,a1:Self,a2:Self)->ArrayVec<<Self as core::ops::Div>::Output,2>{
|
||||
let a2pos=match a2.cmp(&Self::ZERO){
|
||||
Ordering::Greater=>true,
|
||||
Ordering::Equal=>return ArrayVec::from_iter(Self::zeroes1(a0,a1).into_iter()),
|
||||
Ordering::Equal=>return ArrayVec::from_iter(Self::zeroes1(a0,a1)),
|
||||
Ordering::Less=>false,
|
||||
};
|
||||
let radicand=a1*a1-a2*a0*4;
|
||||
let radicand=a1*a1-((a2*a0)<<2);
|
||||
match radicand.cmp(&<Self as core::ops::Mul>::Output::ZERO){
|
||||
Ordering::Greater=>{
|
||||
// using wrap because sqrt always halves the number of leading digits.
|
||||
// clamp would be more defensive, but is slower.
|
||||
paste::item!{
|
||||
let planar_radicand=radicand.sqrt().[<fix_ $n>]();
|
||||
let planar_radicand=radicand.sqrt().[<wrap_ $n>]();
|
||||
}
|
||||
//sort roots ascending and avoid taking the difference of large numbers
|
||||
let zeroes=match (a2pos,Self::ZERO<a1){
|
||||
(true, true )=>[(-a1-planar_radicand)/(a2*2),(a0*2)/(-a1-planar_radicand)],
|
||||
(true, false)=>[(a0*2)/(-a1+planar_radicand),(-a1+planar_radicand)/(a2*2)],
|
||||
(false,true )=>[(a0*2)/(-a1-planar_radicand),(-a1-planar_radicand)/(a2*2)],
|
||||
(false,false)=>[(-a1+planar_radicand)/(a2*2),(a0*2)/(-a1+planar_radicand)],
|
||||
let zeroes=match (a2pos,a1.is_positive()){
|
||||
(true, true )=>[(-a1-planar_radicand)/(a2<<1),(a0<<1)/(-a1-planar_radicand)],
|
||||
(true, false)=>[(a0<<1)/(-a1+planar_radicand),(-a1+planar_radicand)/(a2<<1)],
|
||||
(false,true )=>[(a0<<1)/(-a1-planar_radicand),(-a1-planar_radicand)/(a2<<1)],
|
||||
(false,false)=>[(-a1+planar_radicand)/(a2<<1),(a0<<1)/(-a1+planar_radicand)],
|
||||
};
|
||||
ArrayVec::from_iter(zeroes)
|
||||
},
|
||||
Ordering::Equal=>ArrayVec::from_iter([(a1)/(a2*-2)]),
|
||||
Ordering::Equal=>ArrayVec::from_iter([(a1)/(-a2<<1)]),
|
||||
Ordering::Less=>ArrayVec::new_const(),
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
pub fn zeroes1(a0:Self,a1:Self)->ArrayVec<<Self as core::ops::Div>::Output,1>{
|
||||
if a1==Self::ZERO{
|
||||
if a1.is_zero(){
|
||||
ArrayVec::new_const()
|
||||
}else{
|
||||
ArrayVec::from_iter([(-a0)/(a1)])
|
||||
@@ -42,10 +45,10 @@ macro_rules! impl_zeroes{
|
||||
}
|
||||
};
|
||||
}
|
||||
impl_zeroes!(1);
|
||||
impl_zeroes!(2);
|
||||
impl_zeroes!(3);
|
||||
impl_zeroes!(4);
|
||||
impl_zeroes!(64);
|
||||
impl_zeroes!(128);
|
||||
impl_zeroes!(192);
|
||||
impl_zeroes!(256);
|
||||
//sqrt doubles twice!
|
||||
//impl_zeroes!(5);
|
||||
//impl_zeroes!(6);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "linear_ops"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
version = "0.2.0"
|
||||
edition = "2024"
|
||||
repository = "https://git.itzana.me/StrafesNET/strafe-project"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Vector/Matrix operations using trait bounds."
|
||||
@@ -14,9 +14,12 @@ fixed-wide=["dep:fixed_wide","dep:paste"]
|
||||
deferred-division=["dep:ratio_ops"]
|
||||
|
||||
[dependencies]
|
||||
ratio_ops = { path = "../ratio_ops", registry = "strafesnet", optional = true }
|
||||
fixed_wide = { path = "../fixed_wide", registry = "strafesnet", optional = true }
|
||||
ratio_ops = { workspace = true, optional = true }
|
||||
fixed_wide = { workspace = true, optional = true }
|
||||
paste = { version = "1.0.15", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
fixed_wide = { path = "../fixed_wide", registry = "strafesnet", features = ["wide-mul"] }
|
||||
fixed_wide = { workspace = true, features = ["wide-mul"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -5,17 +5,17 @@ macro_rules! impl_fixed_wide_vector_not_const_generic {
|
||||
(),
|
||||
$n:expr
|
||||
) => {
|
||||
impl<const N:usize> Vector<N,fixed_wide::fixed::Fixed<$n,{$n*32}>>{
|
||||
impl<const N:usize> Vector<N,fixed_wide::fixed::Fixed<{$n>>3},{$n>>1}>>{
|
||||
#[inline]
|
||||
pub fn length(self)-><fixed_wide::fixed::Fixed::<$n,{$n*32}> as core::ops::Mul>::Output{
|
||||
pub fn length(self)-><fixed_wide::fixed::Fixed::<{$n>>3},{$n>>1}> as core::ops::Mul>::Output{
|
||||
self.length_squared().sqrt_unchecked()
|
||||
}
|
||||
#[inline]
|
||||
pub fn with_length<U,V>(self,length:U)-><Vector<N,V> as core::ops::Div<<fixed_wide::fixed::Fixed::<$n,{$n*32}> as core::ops::Mul>::Output>>::Output
|
||||
pub fn with_length<U,V>(self,length:U)-><Vector<N,V> as core::ops::Div<<fixed_wide::fixed::Fixed::<{$n>>3},{$n>>1}> as core::ops::Mul>::Output>>::Output
|
||||
where
|
||||
fixed_wide::fixed::Fixed<$n,{$n*32}>:core::ops::Mul<U,Output=V>,
|
||||
fixed_wide::fixed::Fixed<{$n>>3},{$n>>1}>:core::ops::Mul<U,Output=V>,
|
||||
U:Copy,
|
||||
V:core::ops::Div<<fixed_wide::fixed::Fixed::<$n,{$n*32}> as core::ops::Mul>::Output>,
|
||||
V:core::ops::Div<<fixed_wide::fixed::Fixed::<{$n>>3},{$n>>1}> as core::ops::Mul>::Output>,
|
||||
{
|
||||
self*length/self.length()
|
||||
}
|
||||
@@ -27,7 +27,7 @@ macro_rules! impl_fixed_wide_vector_not_const_generic {
|
||||
#[macro_export(local_inner_macros)]
|
||||
macro_rules! macro_4 {
|
||||
( $macro: ident, $any:tt ) => {
|
||||
$crate::macro_repeated!($macro,$any,1,2,3,4);
|
||||
$crate::macro_repeated!($macro,$any,64,128,192,256);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,40 +38,95 @@ macro_rules! impl_fixed_wide_vector {
|
||||
$crate::macro_4!(impl_fixed_wide_vector_not_const_generic,());
|
||||
// I LOVE NOT BEING ABLE TO USE CONST GENERICS
|
||||
$crate::macro_repeated!(
|
||||
impl_fix_not_const_generic,(),
|
||||
(1,1),(2,1),(3,1),(4,1),(5,1),(6,1),(7,1),(8,1),(9,1),(10,1),(11,1),(12,1),(13,1),(14,1),(15,1),(16,1),
|
||||
(1,2),(2,2),(3,2),(4,2),(5,2),(6,2),(7,2),(8,2),(9,2),(10,2),(11,2),(12,2),(13,2),(14,2),(15,2),(16,2),
|
||||
(1,3),(2,3),(3,3),(4,3),(5,3),(6,3),(7,3),(8,3),(9,3),(10,3),(11,3),(12,3),(13,3),(14,3),(15,3),(16,3),
|
||||
(1,4),(2,4),(3,4),(4,4),(5,4),(6,4),(7,4),(8,4),(9,4),(10,4),(11,4),(12,4),(13,4),(14,4),(15,4),(16,4),
|
||||
(1,5),(2,5),(3,5),(4,5),(5,5),(6,5),(7,5),(8,5),(9,5),(10,5),(11,5),(12,5),(13,5),(14,5),(15,5),(16,5),
|
||||
(1,6),(2,6),(3,6),(4,6),(5,6),(6,6),(7,6),(8,6),(9,6),(10,6),(11,6),(12,6),(13,6),(14,6),(15,6),(16,6),
|
||||
(1,7),(2,7),(3,7),(4,7),(5,7),(6,7),(7,7),(8,7),(9,7),(10,7),(11,7),(12,7),(13,7),(14,7),(15,7),(16,7),
|
||||
(1,8),(2,8),(3,8),(4,8),(5,8),(6,8),(7,8),(8,8),(9,8),(10,8),(11,8),(12,8),(13,8),(14,8),(15,8),(16,8),
|
||||
(1,9),(2,9),(3,9),(4,9),(5,9),(6,9),(7,9),(8,9),(9,9),(10,9),(11,9),(12,9),(13,9),(14,9),(15,9),(16,9),
|
||||
(1,10),(2,10),(3,10),(4,10),(5,10),(6,10),(7,10),(8,10),(9,10),(10,10),(11,10),(12,10),(13,10),(14,10),(15,10),(16,10),
|
||||
(1,11),(2,11),(3,11),(4,11),(5,11),(6,11),(7,11),(8,11),(9,11),(10,11),(11,11),(12,11),(13,11),(14,11),(15,11),(16,11),
|
||||
(1,12),(2,12),(3,12),(4,12),(5,12),(6,12),(7,12),(8,12),(9,12),(10,12),(11,12),(12,12),(13,12),(14,12),(15,12),(16,12),
|
||||
(1,13),(2,13),(3,13),(4,13),(5,13),(6,13),(7,13),(8,13),(9,13),(10,13),(11,13),(12,13),(13,13),(14,13),(15,13),(16,13),
|
||||
(1,14),(2,14),(3,14),(4,14),(5,14),(6,14),(7,14),(8,14),(9,14),(10,14),(11,14),(12,14),(13,14),(14,14),(15,14),(16,14),
|
||||
(1,15),(2,15),(3,15),(4,15),(5,15),(6,15),(7,15),(8,15),(9,15),(10,15),(11,15),(12,15),(13,15),(14,15),(15,15),(16,15),
|
||||
(1,16),(2,16),(3,16),(4,16),(5,16),(6,16),(7,16),(8,16),(9,16),(10,16),(11,16),(12,16),(13,16),(14,16),(15,16),(16,16)
|
||||
impl_narrow_not_const_generic,(),
|
||||
(128,64),(192,64),(256,64),(320,64),(384,64),(448,64),(512,64),(576,64),(640,64),(704,64),(768,64),(832,64),(896,64),(960,64),(1024,64),(1088,64),
|
||||
(192,128),(256,128),(320,128),(384,128),(448,128),(512,128),(576,128),(640,128),(704,128),(768,128),(832,128),(896,128),(960,128),(1024,128),
|
||||
(256,192),(320,192),(384,192),(448,192),(512,192),(576,192),(640,192),(704,192),(768,192),(832,192),(896,192),(960,192),(1024,192),
|
||||
(320,256),(384,256),(448,256),(512,256),(576,256),(640,256),(704,256),(768,256),(832,256),(896,256),(960,256),(1024,256),
|
||||
(384,320),(448,320),(512,320),(576,320),(640,320),(704,320),(768,320),(832,320),(896,320),(960,320),(1024,320),
|
||||
(448,384),(512,384),(576,384),(640,384),(704,384),(768,384),(832,384),(896,384),(960,384),(1024,384),
|
||||
(512,448),(576,448),(640,448),(704,448),(768,448),(832,448),(896,448),(960,448),(1024,448),
|
||||
(576,512),(640,512),(704,512),(768,512),(832,512),(896,512),(960,512),(1024,512),
|
||||
(640,576),(704,576),(768,576),(832,576),(896,576),(960,576),(1024,576),
|
||||
(704,640),(768,640),(832,640),(896,640),(960,640),(1024,640),
|
||||
(768,704),(832,704),(896,704),(960,704),(1024,704),
|
||||
(832,768),(896,768),(960,768),(1024,768),
|
||||
(896,832),(960,832),(1024,832),
|
||||
(960,896),(1024,896),
|
||||
(1024,960)
|
||||
);
|
||||
$crate::macro_repeated!(
|
||||
impl_widen_not_const_generic,(),
|
||||
(64,128),
|
||||
(64,192),(128,192),
|
||||
(64,256),(128,256),(192,256),
|
||||
(64,320),(128,320),(192,320),(256,320),
|
||||
(64,384),(128,384),(192,384),(256,384),(320,384),
|
||||
(64,448),(128,448),(192,448),(256,448),(320,448),(384,448),
|
||||
(64,512),(128,512),(192,512),(256,512),(320,512),(384,512),(448,512),
|
||||
(64,576),(128,576),(192,576),(256,576),(320,576),(384,576),(448,576),(512,576),
|
||||
(64,640),(128,640),(192,640),(256,640),(320,640),(384,640),(448,640),(512,640),(576,640),
|
||||
(64,704),(128,704),(192,704),(256,704),(320,704),(384,704),(448,704),(512,704),(576,704),(640,704),
|
||||
(64,768),(128,768),(192,768),(256,768),(320,768),(384,768),(448,768),(512,768),(576,768),(640,768),(704,768),
|
||||
(64,832),(128,832),(192,832),(256,832),(320,832),(384,832),(448,832),(512,832),(576,832),(640,832),(704,832),(768,832),
|
||||
(64,896),(128,896),(192,896),(256,896),(320,896),(384,896),(448,896),(512,896),(576,896),(640,896),(704,896),(768,896),(832,896),
|
||||
(64,960),(128,960),(192,960),(256,960),(320,960),(384,960),(448,960),(512,960),(576,960),(640,960),(704,960),(768,960),(832,960),(896,960),
|
||||
(64,1024),(128,1024),(192,1024),(256,1024),(320,1024),(384,1024),(448,1024),(512,1024),(576,1024),(640,1024),(704,1024),(768,1024),(832,1024),(896,1024),(960,1024),
|
||||
(64,1088)
|
||||
);
|
||||
impl<const N:usize,T:fixed_wide::fixed::Wrap<U>,U> fixed_wide::fixed::Wrap<Vector<N,U>> for Vector<N,T>
|
||||
{
|
||||
#[inline]
|
||||
fn wrap(self)->Vector<N,U>{
|
||||
self.map(|t|t.wrap())
|
||||
}
|
||||
}
|
||||
impl<const N:usize,T:fixed_wide::fixed::Clamp<U>,U> fixed_wide::fixed::Clamp<Vector<N,U>> for Vector<N,T>
|
||||
{
|
||||
#[inline]
|
||||
fn clamp(self)->Vector<N,U>{
|
||||
self.map(|t|t.clamp())
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
#[macro_export(local_inner_macros)]
|
||||
macro_rules! impl_fix_not_const_generic{
|
||||
macro_rules! impl_narrow_not_const_generic{
|
||||
(
|
||||
(),
|
||||
($lhs:expr,$rhs:expr)
|
||||
)=>{
|
||||
impl<const N:usize> Vector<N,fixed_wide::fixed::Fixed<$lhs,{$lhs*32}>>
|
||||
{
|
||||
paste::item!{
|
||||
paste::item!{
|
||||
impl<const N:usize> Vector<N,fixed_wide::fixed::Fixed<{$lhs>>3},{$lhs>>1}>>{
|
||||
#[inline]
|
||||
pub fn [<fix_ $rhs>](self)->Vector<N,fixed_wide::fixed::Fixed<$rhs,{$rhs*32}>>{
|
||||
self.map(|t|t.[<fix_ $rhs>]())
|
||||
pub fn [<wrap_ $rhs>](self)->Vector<N,fixed_wide::fixed::Fixed<{$rhs>>3},{$rhs>>1}>>{
|
||||
self.map(|t|t.[<wrap_ $rhs>]())
|
||||
}
|
||||
#[inline]
|
||||
pub fn [<narrow_ $rhs>](self)->Vector<N,Result<fixed_wide::fixed::Fixed<{$rhs>>3},{$rhs>>1}>,fixed_wide::fixed::NarrowError>>{
|
||||
self.map(|t|t.[<narrow_ $rhs>]())
|
||||
}
|
||||
#[inline]
|
||||
pub fn [<clamp_ $rhs>](self)->Vector<N,fixed_wide::fixed::Fixed<{$rhs>>3},{$rhs>>1}>>{
|
||||
self.map(|t|t.[<clamp_ $rhs>]())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[doc(hidden)]
|
||||
#[macro_export(local_inner_macros)]
|
||||
macro_rules! impl_widen_not_const_generic{
|
||||
(
|
||||
(),
|
||||
($lhs:expr,$rhs:expr)
|
||||
)=>{
|
||||
paste::item!{
|
||||
impl<const N:usize> Vector<N,fixed_wide::fixed::Fixed<{$lhs>>3},{$lhs>>1}>>{
|
||||
#[inline]
|
||||
pub fn [<widen_ $rhs>](self)->Vector<N,fixed_wide::fixed::Fixed<{$rhs>>3},{$rhs>>1}>>{
|
||||
self.map(|t|t.[<widen_ $rhs>]())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,13 +204,21 @@ macro_rules! impl_matrix_named_fields_shape {
|
||||
type Target=$struct_outer<Vector<$size_inner,T>>;
|
||||
#[inline]
|
||||
fn deref(&self)->&Self::Target{
|
||||
unsafe{core::mem::transmute(&self.array)}
|
||||
// This cast is valid because Matrix has #[repr(transparent)]
|
||||
let ptr:*const [[T;$size_inner];$size_outer]=&self.array;
|
||||
let ptr=ptr as *const Self::Target;
|
||||
// SAFETY: this pointer is non-null because it comes from a reference
|
||||
unsafe{&*ptr}
|
||||
}
|
||||
}
|
||||
impl<T> core::ops::DerefMut for Matrix<$size_outer,$size_inner,T>{
|
||||
#[inline]
|
||||
fn deref_mut(&mut self)->&mut Self::Target{
|
||||
unsafe{core::mem::transmute(&mut self.array)}
|
||||
// This cast is valid because Matrix has #[repr(transparent)]
|
||||
let ptr:*mut [[T;$size_inner];$size_outer]=&mut self.array;
|
||||
let ptr=ptr as *mut Self::Target;
|
||||
// SAFETY: this pointer is non-null because it comes from a reference
|
||||
unsafe{&mut*ptr}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +58,15 @@ macro_rules! impl_vector {
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N:usize,T,E:std::fmt::Debug> Vector<N,Result<T,E>>{
|
||||
#[inline]
|
||||
pub fn unwrap(self)->Vector<N,T>{
|
||||
Vector{
|
||||
array:self.array.map(Result::unwrap)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N:usize,T:Ord> Vector<N,T>{
|
||||
#[inline]
|
||||
pub fn min(self,rhs:Self)->Self{
|
||||
@@ -321,13 +330,21 @@ macro_rules! impl_vector_named_fields {
|
||||
type Target=$struct<T>;
|
||||
#[inline]
|
||||
fn deref(&self)->&Self::Target{
|
||||
unsafe{core::mem::transmute(&self.array)}
|
||||
// This cast is valid because Vector has #[repr(transparent)]
|
||||
let ptr:*const [T;$size]=&self.array;
|
||||
let ptr=ptr as *const Self::Target;
|
||||
// SAFETY: this pointer is non-null because it comes from a reference
|
||||
unsafe{&*ptr}
|
||||
}
|
||||
}
|
||||
impl<T> core::ops::DerefMut for Vector<$size,T>{
|
||||
#[inline]
|
||||
fn deref_mut(&mut self)->&mut Self::Target{
|
||||
unsafe{core::mem::transmute(&mut self.array)}
|
||||
// This cast is valid because Vector has #[repr(transparent)]
|
||||
let ptr:*mut [T;$size]=&mut self.array;
|
||||
let ptr=ptr as *mut Self::Target;
|
||||
// SAFETY: this pointer is non-null because it comes from a reference
|
||||
unsafe{&mut*ptr}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::vector::Vector;
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq)]
|
||||
pub struct Matrix<const X:usize,const Y:usize,T>{
|
||||
pub(crate) array:[[T;Y];X],
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use crate::types::{Matrix3,Matrix3x2,Matrix3x4,Matrix4x2,Vector3};
|
||||
|
||||
type Planar64=fixed_wide::types::I32F32;
|
||||
type Planar64Wide1=fixed_wide::types::I64F64;
|
||||
type Planar64=fixed_wide::types::F64_32;
|
||||
type Planar64Wide1=fixed_wide::types::F128_64;
|
||||
//type Planar64Wide2=fixed_wide::types::I128F128;
|
||||
type Planar64Wide3=fixed_wide::types::I256F256;
|
||||
type Planar64Wide3=fixed_wide::types::F512_256;
|
||||
|
||||
#[test]
|
||||
fn wide_vec3(){
|
||||
@@ -72,7 +72,7 @@ fn wide_matrix_det(){
|
||||
]);
|
||||
// In[2]:= Det[{{1, 2, 3}, {4, 5, 7}, {6, 8, 9}}]
|
||||
// Out[2]= 7
|
||||
assert_eq!(m.det(),fixed_wide::fixed::Fixed::<3,96>::from(7));
|
||||
assert_eq!(m.det(),fixed_wide::types::F192_96::from(7));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
/// v.x += v.z;
|
||||
/// println!("v.x={}",v.x);
|
||||
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq)]
|
||||
pub struct Vector<const N:usize,T>{
|
||||
pub(crate) array:[T;N],
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
[package]
|
||||
name = "ratio_ops"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
version = "0.1.1"
|
||||
edition = "2024"
|
||||
repository = "https://git.itzana.me/StrafesNET/strafe-project"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Ratio operations using trait bounds for avoiding division like the plague."
|
||||
authors = ["Rhys Lloyd <krakow20@gmail.com>"]
|
||||
|
||||
[dependencies]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -268,30 +268,35 @@ impl<LhsNum,LhsDen,RhsNum,RhsDen,T,U> PartialEq<Ratio<RhsNum,RhsDen>> for Ratio<
|
||||
}
|
||||
impl<Num,Den> Eq for Ratio<Num,Den> where Self:PartialEq{}
|
||||
|
||||
// Wow! These were both completely wrong!
|
||||
// Idea: use a 'signed' trait instead of parity and float the sign to the numerator.
|
||||
impl<LhsNum,LhsDen,RhsNum,RhsDen,T,U> PartialOrd<Ratio<RhsNum,RhsDen>> for Ratio<LhsNum,LhsDen>
|
||||
where
|
||||
LhsNum:Copy,
|
||||
LhsDen:Copy,
|
||||
LhsDen:Copy+Parity,
|
||||
RhsNum:Copy,
|
||||
RhsDen:Copy,
|
||||
RhsDen:Copy+Parity,
|
||||
LhsNum:core::ops::Mul<RhsDen,Output=T>,
|
||||
LhsDen:core::ops::Mul<RhsNum,Output=T>,
|
||||
RhsNum:core::ops::Mul<LhsDen,Output=U>,
|
||||
T:PartialOrd<U>,
|
||||
RhsDen:core::ops::Mul<LhsNum,Output=U>,
|
||||
T:PartialOrd<U>+Ord,
|
||||
{
|
||||
#[inline]
|
||||
fn partial_cmp(&self,other:&Ratio<RhsNum,RhsDen>)->Option<core::cmp::Ordering>{
|
||||
(self.num*other.den).partial_cmp(&(other.num*self.den))
|
||||
fn partial_cmp(&self,&other:&Ratio<RhsNum,RhsDen>)->Option<core::cmp::Ordering>{
|
||||
self.partial_cmp_ratio(other)
|
||||
}
|
||||
}
|
||||
impl<Num,Den,T> Ord for Ratio<Num,Den>
|
||||
where
|
||||
Num:Copy,
|
||||
Den:Copy,
|
||||
Den:Copy+Parity,
|
||||
Num:core::ops::Mul<Den,Output=T>,
|
||||
Den:core::ops::Mul<Num,Output=T>,
|
||||
T:Ord,
|
||||
{
|
||||
#[inline]
|
||||
fn cmp(&self,other:&Self)->std::cmp::Ordering{
|
||||
(self.num*other.den).cmp(&(other.num*self.den))
|
||||
fn cmp(&self,&other:&Self)->std::cmp::Ordering{
|
||||
self.cmp_ratio(other)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "strafesnet_rbx_loader"
|
||||
version = "0.5.2"
|
||||
edition = "2021"
|
||||
version = "0.10.2"
|
||||
edition = "2024"
|
||||
repository = "https://git.itzana.me/StrafesNET/strafe-project"
|
||||
license = "MIT OR Apache-2.0"
|
||||
description = "Convert Roblox place and model files to StrafesNET data structures."
|
||||
@@ -11,12 +11,18 @@ authors = ["Rhys Lloyd <krakow20@gmail.com>"]
|
||||
|
||||
[dependencies]
|
||||
bytemuck = "1.14.3"
|
||||
glam = "0.29.0"
|
||||
lazy-regex = "3.1.0"
|
||||
rbx_binary = { version = "0.7.4", registry = "strafesnet" }
|
||||
rbx_dom_weak = { version = "2.7.0", registry = "strafesnet" }
|
||||
rbx_mesh = "0.1.2"
|
||||
rbx_reflection_database = { version = "0.2.10", registry = "strafesnet" }
|
||||
rbx_xml = { version = "0.13.3", registry = "strafesnet" }
|
||||
roblox_emulator = { path = "../roblox_emulator", registry = "strafesnet" }
|
||||
strafesnet_common = { path = "../common", registry = "strafesnet" }
|
||||
glam.workspace = true
|
||||
regex = { version = "1.11.3", default-features = false, features = ["unicode-perl"] }
|
||||
rbx_mesh = "0.6.0"
|
||||
rbxassetid = { version = "0.1.0", path = "../rbxassetid", registry = "strafesnet" }
|
||||
roblox_emulator = { version = "0.5.1", path = "../roblox_emulator", default-features = false, registry = "strafesnet" }
|
||||
strafesnet_common.workspace = true
|
||||
strafesnet_deferred_loader.workspace = true
|
||||
rbx_binary = "2.0.1"
|
||||
rbx_dom_weak = "4.1.0"
|
||||
rbx_reflection = "6.1.0"
|
||||
rbx_reflection_database = "2.0.2"
|
||||
rbx_xml = "2.0.1"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
249
lib/rbx_loader/src/error.rs
Normal file
249
lib/rbx_loader/src/error.rs
Normal file
@@ -0,0 +1,249 @@
|
||||
use std::collections::HashSet;
|
||||
use std::num::ParseIntError;
|
||||
|
||||
use strafesnet_common::gameplay_modes::{StageId,ModeId};
|
||||
use strafesnet_common::integer::{FixedFromFloatError,Planar64TryFromFloatError};
|
||||
|
||||
/// A collection of errors which can be ignored at your peril
|
||||
#[derive(Debug,Default)]
|
||||
pub struct RecoverableErrors{
|
||||
/// A basepart has an invalid / missing property.
|
||||
pub basepart_property:Vec<InstancePath>,
|
||||
/// A part has an unconvertable CFrame.
|
||||
pub basepart_cframe:Vec<CFrameError>,
|
||||
/// A part has an unconvertable Velocity.
|
||||
pub basepart_velocity:Vec<Planar64ConvertError>,
|
||||
/// A part has an invalid / missing property.
|
||||
pub part_property:Vec<InstancePath>,
|
||||
/// A part has an invalid shape.
|
||||
pub part_shape:Vec<ShapeError>,
|
||||
/// A meshpart has an invalid / missing property.
|
||||
pub meshpart_property:Vec<InstancePath>,
|
||||
/// A meshpart has no mesh.
|
||||
pub meshpart_content:Vec<InstancePath>,
|
||||
/// A basepart has an unsupported subclass.
|
||||
pub unsupported_class:HashSet<String>,
|
||||
/// A decal has an invalid / missing property.
|
||||
pub decal_property:Vec<InstancePath>,
|
||||
/// A SurfaceAppearance has an invalid / missing property.
|
||||
pub surface_appearance_property:Vec<InstancePath>,
|
||||
/// A decal has an invalid normal_id.
|
||||
pub normal_id:Vec<NormalIdError>,
|
||||
/// A texture has an invalid / missing property.
|
||||
pub texture_property:Vec<InstancePath>,
|
||||
/// A mode_id failed to parse.
|
||||
pub mode_id_parse_int:Vec<ParseIntContext>,
|
||||
/// There is a duplicate mode.
|
||||
pub duplicate_mode:HashSet<ModeId>,
|
||||
/// A mode_id failed to parse.
|
||||
pub stage_id_parse_int:Vec<ParseIntContext>,
|
||||
/// A Stage was duplicated leading to undefined behaviour.
|
||||
pub duplicate_stage:HashSet<DuplicateStageError>,
|
||||
/// A WormholeOut id failed to parse.
|
||||
pub wormhole_out_id_parse_int:Vec<ParseIntContext>,
|
||||
/// A WormholeOut was duplicated leading to undefined behaviour.
|
||||
pub duplicate_wormhole_out:HashSet<u32>,
|
||||
/// A WormholeIn id failed to parse.
|
||||
pub wormhole_in_id_parse_int:Vec<ParseIntContext>,
|
||||
/// A jump limit failed to parse.
|
||||
pub jump_limit_parse_int:Vec<ParseIntContext>,
|
||||
}
|
||||
|
||||
impl RecoverableErrors{
|
||||
pub fn count(&self)->usize{
|
||||
self.basepart_property.len()+
|
||||
self.basepart_cframe.len()+
|
||||
self.basepart_velocity.len()+
|
||||
self.part_property.len()+
|
||||
self.part_shape.len()+
|
||||
self.meshpart_property.len()+
|
||||
self.meshpart_content.len()+
|
||||
self.unsupported_class.len()+
|
||||
self.decal_property.len()+
|
||||
self.surface_appearance_property.len()+
|
||||
self.normal_id.len()+
|
||||
self.texture_property.len()+
|
||||
self.mode_id_parse_int.len()+
|
||||
self.duplicate_mode.len()+
|
||||
self.stage_id_parse_int.len()+
|
||||
self.duplicate_stage.len()+
|
||||
self.wormhole_out_id_parse_int.len()+
|
||||
self.duplicate_wormhole_out.len()+
|
||||
self.wormhole_in_id_parse_int.len()+
|
||||
self.jump_limit_parse_int.len()
|
||||
}
|
||||
}
|
||||
|
||||
fn write_comma_separated<T>(
|
||||
f:&mut std::fmt::Formatter<'_>,
|
||||
mut it:impl Iterator<Item=T>,
|
||||
custom_write:impl Fn(&mut std::fmt::Formatter<'_>,T)->std::fmt::Result
|
||||
)->std::fmt::Result{
|
||||
if let Some(t)=it.next(){
|
||||
custom_write(f,t)?;
|
||||
for t in it{
|
||||
write!(f,", ")?;
|
||||
custom_write(f,t)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
macro_rules! write_instance_path_error{
|
||||
($f:ident,$self:ident,$field:ident,$class:literal,$class_plural:literal,$problem:literal)=>{
|
||||
let len=$self.$field.len();
|
||||
if len!=0{
|
||||
let plural=if len==1{$class}else{$class_plural};
|
||||
write!($f,"The following {plural} {}: ",$problem)?;
|
||||
write_comma_separated($f,$self.$field.iter(),|f,InstancePath(path)|
|
||||
write!(f,"{path}")
|
||||
)?;
|
||||
writeln!($f)?;
|
||||
}
|
||||
};
|
||||
}
|
||||
macro_rules! write_duplicate_error{
|
||||
($f:ident,$self:ident,$field:ident,$class:literal,$class_plural:literal)=>{
|
||||
let len=$self.$field.len();
|
||||
if len!=0{
|
||||
let plural=if len==1{$class}else{$class_plural};
|
||||
write!($f,"The following {plural} duplicates: ")?;
|
||||
write_comma_separated($f,$self.$field.iter(),|f,id|
|
||||
write!(f,"{id}")
|
||||
)?;
|
||||
writeln!($f)?;
|
||||
}
|
||||
};
|
||||
}
|
||||
macro_rules! write_bespoke_error{
|
||||
($f:ident,$self:ident,$field:ident,$class:literal,$class_plural:literal,$problem:literal,$path_field:ident,$error_field:ident)=>{
|
||||
let len=$self.$field.len();
|
||||
if len!=0{
|
||||
let plural=if len==1{$class}else{$class_plural};
|
||||
write!($f,"The following {plural} {}: ",$problem)?;
|
||||
write_comma_separated($f,$self.$field.iter(),|f,context|
|
||||
write!(f,"{} ({})",context.$path_field,context.$error_field)
|
||||
)?;
|
||||
writeln!($f)?;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl core::fmt::Display for RecoverableErrors{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write_instance_path_error!(f,self,basepart_property,"BasePart is","BaseParts are","missing a property");
|
||||
write_bespoke_error!(f,self,basepart_cframe,"BasePart","BaseParts","CFrame float convert failed",path,error);
|
||||
write_bespoke_error!(f,self,basepart_velocity,"BasePart","BaseParts","Velocity float convert failed",path,error);
|
||||
write_instance_path_error!(f,self,part_property,"Part is","Parts are","missing a property");
|
||||
write_bespoke_error!(f,self,part_shape,"Part","Parts","Shape is invalid",path,shape);
|
||||
write_instance_path_error!(f,self,meshpart_property,"MeshPart is","MeshParts are","missing a property");
|
||||
write_instance_path_error!(f,self,meshpart_content,"MeshPart has","MeshParts have","no mesh");
|
||||
{
|
||||
let len=self.unsupported_class.len();
|
||||
if len!=0{
|
||||
let plural=if len==1{"Class is"}else{"Classes are"};
|
||||
write!(f,"The following {plural} not supported: ")?;
|
||||
write_comma_separated(f,self.unsupported_class.iter(),|f,classname|write!(f,"{classname}"))?;
|
||||
writeln!(f)?;
|
||||
}
|
||||
}
|
||||
write_instance_path_error!(f,self,decal_property,"Decal is","Decals are","missing a property");
|
||||
write_instance_path_error!(f,self,surface_appearance_property,"SurfaceAppearance is","SurfaceAppearances are","missing a property");
|
||||
write_bespoke_error!(f,self,normal_id,"Decal","Decals","NormalId is invalid",path,normal_id);
|
||||
write_instance_path_error!(f,self,texture_property,"Texture is","Textures are","missing a property");
|
||||
write_bespoke_error!(f,self,mode_id_parse_int,"ModeId","ModeIds","failed to parse",context,error);
|
||||
write_duplicate_error!(f,self,duplicate_mode,"ModeId has","ModeIds have");
|
||||
write_bespoke_error!(f,self,stage_id_parse_int,"StageId","StageIds","failed to parse",context,error);
|
||||
write_duplicate_error!(f,self,duplicate_stage,"StageId has","StageIds have");
|
||||
write_bespoke_error!(f,self,wormhole_out_id_parse_int,"WormholeOutId","WormholeOutIds","failed to parse",context,error);
|
||||
write_duplicate_error!(f,self,duplicate_wormhole_out,"WormholeOutId has","WormholeOutIds have");
|
||||
write_bespoke_error!(f,self,wormhole_in_id_parse_int,"WormholeInId","WormholeInIds","failed to parse",context,error);
|
||||
write_bespoke_error!(f,self,jump_limit_parse_int,"jump limit","jump limits","failed to parse",context,error);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A Decal was missing required properties
|
||||
#[derive(Debug)]
|
||||
pub struct InstancePath(pub String);
|
||||
|
||||
impl core::fmt::Display for InstancePath{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl InstancePath{
|
||||
pub fn new(dom:&rbx_dom_weak::WeakDom,instance:&rbx_dom_weak::Instance)->InstancePath{
|
||||
let mut names:Vec<_>=core::iter::successors(
|
||||
Some(instance),
|
||||
|i|dom.get_by_ref(i.parent())
|
||||
).map(
|
||||
|i|i.name.as_str()
|
||||
).collect();
|
||||
// discard the name of the root object
|
||||
names.pop();
|
||||
names.reverse();
|
||||
InstancePath(names.join("."))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ParseIntContext{
|
||||
pub context:String,
|
||||
pub error:ParseIntError,
|
||||
}
|
||||
impl ParseIntContext{
|
||||
pub fn parse<T:core::str::FromStr<Err=ParseIntError>>(input:&str)->Result<T,Self>{
|
||||
input.parse().map_err(|error|ParseIntContext{
|
||||
context:input.to_owned(),
|
||||
error,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NormalIdError{
|
||||
pub path:InstancePath,
|
||||
pub normal_id:u32,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ShapeError{
|
||||
pub path:InstancePath,
|
||||
pub shape:u32,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum CFrameErrorType{
|
||||
ZeroDeterminant,
|
||||
Convert(FixedFromFloatError),
|
||||
}
|
||||
impl core::fmt::Display for CFrameErrorType{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"{self:?}")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct CFrameError{
|
||||
pub path:InstancePath,
|
||||
pub error:CFrameErrorType,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Planar64ConvertError{
|
||||
pub path:InstancePath,
|
||||
pub error:Planar64TryFromFloatError,
|
||||
}
|
||||
|
||||
#[derive(Debug,Hash,Eq,PartialEq)]
|
||||
pub struct DuplicateStageError{
|
||||
pub mode_id:ModeId,
|
||||
pub stage_id:StageId,
|
||||
}
|
||||
impl core::fmt::Display for DuplicateStageError{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"{}-Spawn{}",self.mode_id,self.stage_id.get())
|
||||
}
|
||||
}
|
||||
@@ -1,35 +1,22 @@
|
||||
use std::io::Read;
|
||||
use rbx_dom_weak::WeakDom;
|
||||
use roblox_emulator::context::Context;
|
||||
|
||||
mod rbx;
|
||||
mod mesh;
|
||||
mod primitives;
|
||||
pub use error::RecoverableErrors;
|
||||
pub use roblox_emulator::runner::Error as RunnerError;
|
||||
|
||||
pub mod data{
|
||||
pub struct RobloxMeshBytes(Vec<u8>);
|
||||
impl RobloxMeshBytes{
|
||||
pub fn new(bytes:Vec<u8>)->Self{
|
||||
Self(bytes)
|
||||
}
|
||||
pub(crate) fn cursor(self)->std::io::Cursor<Vec<u8>>{
|
||||
std::io::Cursor::new(self.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
pub mod rbx;
|
||||
pub mod mesh;
|
||||
mod error;
|
||||
pub mod union;
|
||||
pub mod primitives;
|
||||
|
||||
pub struct Model{
|
||||
dom:WeakDom,
|
||||
}
|
||||
impl Model{
|
||||
fn new(dom:WeakDom)->Self{
|
||||
pub fn new(dom:WeakDom)->Self{
|
||||
Self{dom}
|
||||
}
|
||||
pub fn into_place(self)->Place{
|
||||
let Self{mut dom}=self;
|
||||
let context=roblox_emulator::context::Context::from_mut(&mut dom);
|
||||
let services=context.convert_into_place();
|
||||
Place{dom,services}
|
||||
}
|
||||
}
|
||||
impl AsRef<WeakDom> for Model{
|
||||
fn as_ref(&self)->&WeakDom{
|
||||
@@ -38,70 +25,39 @@ impl AsRef<WeakDom> for Model{
|
||||
}
|
||||
|
||||
pub struct Place{
|
||||
dom:WeakDom,
|
||||
services:roblox_emulator::context::Services,
|
||||
context:Context,
|
||||
}
|
||||
impl Place{
|
||||
fn new(dom:WeakDom)->Option<Self>{
|
||||
let context=roblox_emulator::context::Context::from_ref(&dom);
|
||||
Some(Self{
|
||||
services:context.find_services()?,
|
||||
dom,
|
||||
pub fn new(dom:WeakDom)->Result<Self,roblox_emulator::context::ServicesError>{
|
||||
let context=Context::from_place(dom)?;
|
||||
Ok(Self{
|
||||
context,
|
||||
})
|
||||
}
|
||||
pub fn run_scripts(&mut self){
|
||||
let Place{dom,services}=self;
|
||||
let runner=roblox_emulator::runner::Runner::new().unwrap();
|
||||
let context=roblox_emulator::context::Context::from_mut(dom);
|
||||
pub fn run_scripts(&mut self)->Result<Vec<RunnerError>,RunnerError>{
|
||||
let Place{context}=self;
|
||||
let runner=roblox_emulator::runner::Runner::new()?;
|
||||
let scripts=context.scripts();
|
||||
let runnable=runner.runnable_context_with_services(context,services).unwrap();
|
||||
let runnable=runner.runnable_context(context)?;
|
||||
let mut errors=Vec::new();
|
||||
for script in scripts{
|
||||
if let Err(e)=runnable.run_script(script){
|
||||
println!("runner error: {e}");
|
||||
errors.push(e);
|
||||
}
|
||||
}
|
||||
Ok(errors)
|
||||
}
|
||||
}
|
||||
impl AsRef<WeakDom> for Place{
|
||||
fn as_ref(&self)->&WeakDom{
|
||||
&self.dom
|
||||
self.context.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ReadError{
|
||||
RbxBinary(rbx_binary::DecodeError),
|
||||
RbxXml(rbx_xml::DecodeError),
|
||||
Io(std::io::Error),
|
||||
UnknownFileFormat,
|
||||
}
|
||||
impl std::fmt::Display for ReadError{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"{self:?}")
|
||||
impl From<Model> for Place{
|
||||
fn from(model:Model)->Self{
|
||||
let context=Context::from_model(model.dom);
|
||||
Self{
|
||||
context,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl std::error::Error for ReadError{}
|
||||
|
||||
pub fn read<R:Read>(input:R)->Result<Model,ReadError>{
|
||||
let mut buf=std::io::BufReader::new(input);
|
||||
let peek=std::io::BufRead::fill_buf(&mut buf).map_err(ReadError::Io)?;
|
||||
match &peek[0..8]{
|
||||
b"<roblox!"=>rbx_binary::from_reader(buf).map(Model::new).map_err(ReadError::RbxBinary),
|
||||
b"<roblox "=>rbx_xml::from_reader_default(buf).map(Model::new).map_err(ReadError::RbxXml),
|
||||
_=>Err(ReadError::UnknownFileFormat),
|
||||
}
|
||||
}
|
||||
|
||||
//ConvertError
|
||||
|
||||
pub fn convert<AcquireRenderConfigId,AcquireMeshId>(
|
||||
dom:impl AsRef<WeakDom>,
|
||||
acquire_render_config_id:AcquireRenderConfigId,
|
||||
acquire_mesh_id:AcquireMeshId
|
||||
)->rbx::PartialMap1
|
||||
where
|
||||
AcquireRenderConfigId:FnMut(Option<&str>)->strafesnet_common::model::RenderConfigId,
|
||||
AcquireMeshId:FnMut(&str)->strafesnet_common::model::MeshId,
|
||||
{
|
||||
rbx::convert(&dom.as_ref(),acquire_render_config_id,acquire_mesh_id)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,77 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use rbx_mesh::mesh::{Vertex2, Vertex2Truncated};
|
||||
use strafesnet_common::{integer::vec3,model::{self, ColorId, IndexedVertex, NormalId, PolygonGroup, PolygonList, PositionId, TextureCoordinateId, VertexId}};
|
||||
use rbx_mesh::mesh::{Vertex2,Vertex2Truncated};
|
||||
use strafesnet_common::aabb::Aabb;
|
||||
use strafesnet_common::integer::vec3;
|
||||
use strafesnet_common::model::{self,ColorId,IndexedVertex,PolygonGroup,PolygonList,RenderConfigId,VertexId};
|
||||
|
||||
use crate::rbx::RobloxPartDescription;
|
||||
|
||||
#[derive(Hash,Eq,PartialEq)]
|
||||
pub enum MeshType<'a>{
|
||||
FileMesh,
|
||||
Union{
|
||||
mesh_data:&'a [u8],
|
||||
physics_data:&'a [u8],
|
||||
size_float_bits:[u32;3],
|
||||
part_texture_description:RobloxPartDescription,
|
||||
},
|
||||
}
|
||||
#[derive(Hash,Eq,PartialEq)]
|
||||
pub struct MeshIndex<'a>{
|
||||
pub mesh_type:MeshType<'a>,
|
||||
pub content:&'a str,
|
||||
}
|
||||
impl MeshIndex<'_>{
|
||||
pub fn file_mesh(content:&str)->MeshIndex<'_>{
|
||||
MeshIndex{
|
||||
mesh_type:MeshType::FileMesh,
|
||||
content,
|
||||
}
|
||||
}
|
||||
pub fn union<'a>(
|
||||
content:&'a str,
|
||||
mesh_data:&'a [u8],
|
||||
physics_data:&'a [u8],
|
||||
size:&rbx_dom_weak::types::Vector3,
|
||||
part_texture_description:RobloxPartDescription,
|
||||
)->MeshIndex<'a>{
|
||||
MeshIndex{
|
||||
mesh_type:MeshType::Union{
|
||||
mesh_data,
|
||||
physics_data,
|
||||
size_float_bits:[size.x.to_bits(),size.y.to_bits(),size.z.to_bits()],
|
||||
part_texture_description,
|
||||
},
|
||||
content,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct MeshWithSize{
|
||||
mesh:model::Mesh,
|
||||
size:strafesnet_common::integer::Planar64Vec3,
|
||||
}
|
||||
impl MeshWithSize{
|
||||
pub(crate) const fn new(
|
||||
mesh:model::Mesh,
|
||||
size:strafesnet_common::integer::Planar64Vec3,
|
||||
)->Self{
|
||||
Self{mesh,size}
|
||||
}
|
||||
pub const fn mesh(&self)->&model::Mesh{
|
||||
&self.mesh
|
||||
}
|
||||
pub const fn size(&self)->strafesnet_common::integer::Planar64Vec3{
|
||||
self.size
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error{
|
||||
Planar64Vec3(strafesnet_common::integer::Planar64TryFromFloatError),
|
||||
RbxMesh(rbx_mesh::mesh::Error)
|
||||
NoPolygons,
|
||||
RbxMesh(rbx_mesh::mesh::Error),
|
||||
}
|
||||
impl std::fmt::Display for Error{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
@@ -15,196 +80,143 @@ impl std::fmt::Display for Error{
|
||||
}
|
||||
impl std::error::Error for Error{}
|
||||
|
||||
fn ingest_vertices2<
|
||||
AcquirePosId,
|
||||
AcquireTexId,
|
||||
AcquireNormalId,
|
||||
AcquireColorId,
|
||||
AcquireVertexId,
|
||||
>(
|
||||
fn ingest_vertices2(
|
||||
vertices:Vec<Vertex2>,
|
||||
acquire_pos_id:&mut AcquirePosId,
|
||||
acquire_tex_id:&mut AcquireTexId,
|
||||
acquire_normal_id:&mut AcquireNormalId,
|
||||
acquire_color_id:&mut AcquireColorId,
|
||||
acquire_vertex_id:&mut AcquireVertexId,
|
||||
)->Result<HashMap<rbx_mesh::mesh::VertexId2,VertexId>,Error>
|
||||
where
|
||||
AcquirePosId:FnMut([f32;3])->Result<PositionId,Error>,
|
||||
AcquireTexId:FnMut([f32;2])->TextureCoordinateId,
|
||||
AcquireNormalId:FnMut([f32;3])->Result<NormalId,Error>,
|
||||
AcquireColorId:FnMut([f32;4])->ColorId,
|
||||
AcquireVertexId:FnMut(IndexedVertex)->VertexId,
|
||||
{
|
||||
mb:&mut model::MeshBuilder,
|
||||
)->HashMap<rbx_mesh::mesh::VertexId2,VertexId>{
|
||||
//this monster is collecting a map of old_vertices_index -> unique_vertices_index
|
||||
//while also doing the inserting unique entries into lists simultaneously
|
||||
Ok(vertices.into_iter().enumerate().map(|(vertex_id,vertex)|Ok((
|
||||
// vertex positions that fail to convert are DROPPED
|
||||
vertices.into_iter().enumerate().filter_map(|(vertex_id,vertex)|Some((
|
||||
rbx_mesh::mesh::VertexId2(vertex_id as u32),
|
||||
acquire_vertex_id(IndexedVertex{
|
||||
pos:acquire_pos_id(vertex.pos)?,
|
||||
tex:acquire_tex_id(vertex.tex),
|
||||
normal:acquire_normal_id(vertex.norm)?,
|
||||
color:acquire_color_id(vertex.color.map(|f|f as f32/255.0f32))
|
||||
}),
|
||||
))).collect::<Result<_,_>>()?)
|
||||
{
|
||||
let vertex=IndexedVertex{
|
||||
pos:mb.acquire_pos_id(vec3::try_from_f32_array(vertex.pos).ok()?),
|
||||
tex:mb.acquire_tex_id(glam::Vec2::from_array(vertex.tex)),
|
||||
normal:mb.acquire_normal_id(vec3::try_from_f32_array(vertex.norm).ok()?),
|
||||
color:mb.acquire_color_id(glam::Vec4::from_array(vertex.color.map(|f|f as f32/255.0f32))),
|
||||
};
|
||||
mb.acquire_vertex_id(vertex)
|
||||
}
|
||||
))).collect()
|
||||
}
|
||||
fn ingest_vertices_truncated2<
|
||||
AcquirePosId,
|
||||
AcquireTexId,
|
||||
AcquireNormalId,
|
||||
AcquireVertexId,
|
||||
>(
|
||||
fn ingest_vertices_truncated2(
|
||||
vertices:Vec<Vertex2Truncated>,
|
||||
acquire_pos_id:&mut AcquirePosId,
|
||||
acquire_tex_id:&mut AcquireTexId,
|
||||
acquire_normal_id:&mut AcquireNormalId,
|
||||
mb:&mut model::MeshBuilder,
|
||||
static_color_id:ColorId,//pick one color and fill everything with it
|
||||
acquire_vertex_id:&mut AcquireVertexId,
|
||||
)->Result<HashMap<rbx_mesh::mesh::VertexId2,VertexId>,Error>
|
||||
where
|
||||
AcquirePosId:FnMut([f32;3])->Result<PositionId,Error>,
|
||||
AcquireTexId:FnMut([f32;2])->TextureCoordinateId,
|
||||
AcquireNormalId:FnMut([f32;3])->Result<NormalId,Error>,
|
||||
AcquireVertexId:FnMut(IndexedVertex)->VertexId,
|
||||
{
|
||||
)->HashMap<rbx_mesh::mesh::VertexId2,VertexId>{
|
||||
//this monster is collecting a map of old_vertices_index -> unique_vertices_index
|
||||
//while also doing the inserting unique entries into lists simultaneously
|
||||
Ok(vertices.into_iter().enumerate().map(|(vertex_id,vertex)|Ok((
|
||||
// vertex positions that fail to convert are DROPPED
|
||||
vertices.into_iter().enumerate().filter_map(|(vertex_id,vertex)|Some((
|
||||
rbx_mesh::mesh::VertexId2(vertex_id as u32),
|
||||
acquire_vertex_id(IndexedVertex{
|
||||
pos:acquire_pos_id(vertex.pos)?,
|
||||
tex:acquire_tex_id(vertex.tex),
|
||||
normal:acquire_normal_id(vertex.norm)?,
|
||||
color:static_color_id
|
||||
}),
|
||||
))).collect::<Result<_,_>>()?)
|
||||
{
|
||||
let vertex=IndexedVertex{
|
||||
pos:mb.acquire_pos_id(vec3::try_from_f32_array(vertex.pos).ok()?),
|
||||
tex:mb.acquire_tex_id(glam::Vec2::from_array(vertex.tex)),
|
||||
normal:mb.acquire_normal_id(vec3::try_from_f32_array(vertex.norm).ok()?),
|
||||
color:static_color_id,
|
||||
};
|
||||
mb.acquire_vertex_id(vertex)
|
||||
}
|
||||
))).collect()
|
||||
}
|
||||
|
||||
fn new_polygon_list_checked(list:Vec<model::IndexedVertexList>)->Option<PolygonList>{
|
||||
(!list.is_empty()).then_some(PolygonList::new(list))
|
||||
}
|
||||
|
||||
fn ingest_faces2_lods3(
|
||||
polygon_groups:&mut Vec<PolygonGroup>,
|
||||
vertex_id_map:&HashMap<rbx_mesh::mesh::VertexId2,VertexId>,
|
||||
faces:&Vec<rbx_mesh::mesh::Face2>,
|
||||
lods:&Vec<rbx_mesh::mesh::Lod3>
|
||||
faces:&[rbx_mesh::mesh::Face2],
|
||||
lods:&[rbx_mesh::mesh::Lod3],
|
||||
){
|
||||
//faces have to be split into polygon groups based on lod
|
||||
polygon_groups.extend(lods.windows(2).map(|lod_pair|
|
||||
PolygonGroup::PolygonList(PolygonList::new(faces[lod_pair[0].0 as usize..lod_pair[1].0 as usize].iter().map(|face|
|
||||
vec![vertex_id_map[&face.0],vertex_id_map[&face.1],vertex_id_map[&face.2]]
|
||||
).collect()))
|
||||
polygon_groups.extend(lods.windows(2).filter_map(|lod_pair|
|
||||
Some(PolygonGroup::PolygonList(new_polygon_list_checked(faces[lod_pair[0].0 as usize..lod_pair[1].0 as usize].iter().filter_map(|rbx_mesh::mesh::Face2(v0,v1,v2)|
|
||||
Some(vec![*vertex_id_map.get(&v0)?,*vertex_id_map.get(&v1)?,*vertex_id_map.get(&v2)?])
|
||||
).collect())?))
|
||||
))
|
||||
}
|
||||
|
||||
pub fn convert(roblox_mesh_bytes:crate::data::RobloxMeshBytes)->Result<model::Mesh,Error>{
|
||||
pub fn convert(roblox_mesh_bytes:&[u8])->Result<MeshWithSize,Error>{
|
||||
//generate that mesh boi
|
||||
let mut unique_pos=Vec::new();
|
||||
let mut pos_id_from=HashMap::new();
|
||||
let mut unique_tex=Vec::new();
|
||||
let mut tex_id_from=HashMap::new();
|
||||
let mut unique_normal=Vec::new();
|
||||
let mut normal_id_from=HashMap::new();
|
||||
let mut unique_color=Vec::new();
|
||||
let mut color_id_from=HashMap::new();
|
||||
let mut unique_vertices=Vec::new();
|
||||
let mut vertex_id_from=HashMap::new();
|
||||
let mut polygon_groups=Vec::new();
|
||||
let mut acquire_pos_id=|pos|{
|
||||
let p=vec3::try_from_f32_array(pos).map_err(Error::Planar64Vec3)?;
|
||||
Ok(PositionId::new(*pos_id_from.entry(p).or_insert_with(||{
|
||||
let pos_id=unique_pos.len();
|
||||
unique_pos.push(p);
|
||||
pos_id
|
||||
}) as u32))
|
||||
};
|
||||
let mut acquire_tex_id=|tex|{
|
||||
let h=bytemuck::cast::<[f32;2],[u32;2]>(tex);
|
||||
TextureCoordinateId::new(*tex_id_from.entry(h).or_insert_with(||{
|
||||
let tex_id=unique_tex.len();
|
||||
unique_tex.push(glam::Vec2::from_array(tex));
|
||||
tex_id
|
||||
}) as u32)
|
||||
};
|
||||
let mut acquire_normal_id=|normal|{
|
||||
let n=vec3::try_from_f32_array(normal).map_err(Error::Planar64Vec3)?;
|
||||
Ok(NormalId::new(*normal_id_from.entry(n).or_insert_with(||{
|
||||
let normal_id=unique_normal.len();
|
||||
unique_normal.push(n);
|
||||
normal_id
|
||||
}) as u32))
|
||||
};
|
||||
let mut acquire_color_id=|color|{
|
||||
let h=bytemuck::cast::<[f32;4],[u32;4]>(color);
|
||||
ColorId::new(*color_id_from.entry(h).or_insert_with(||{
|
||||
let color_id=unique_color.len();
|
||||
unique_color.push(glam::Vec4::from_array(color));
|
||||
color_id
|
||||
}) as u32)
|
||||
};
|
||||
let mut acquire_vertex_id=|vertex:IndexedVertex|{
|
||||
VertexId::new(*vertex_id_from.entry(vertex.clone()).or_insert_with(||{
|
||||
let vertex_id=unique_vertices.len();
|
||||
unique_vertices.push(vertex);
|
||||
vertex_id
|
||||
}) as u32)
|
||||
};
|
||||
match rbx_mesh::read_versioned(roblox_mesh_bytes.cursor()).map_err(Error::RbxMesh)?{
|
||||
rbx_mesh::mesh::VersionedMesh::Version1(mesh)=>{
|
||||
let color_id=acquire_color_id([1.0f32;4]);
|
||||
polygon_groups.push(PolygonGroup::PolygonList(PolygonList::new(mesh.vertices.chunks_exact(3).map(|trip|{
|
||||
let mut ingest_vertex1=|vertex:&rbx_mesh::mesh::Vertex1|Ok(acquire_vertex_id(IndexedVertex{
|
||||
pos:acquire_pos_id(vertex.pos)?,
|
||||
tex:acquire_tex_id([vertex.tex[0],vertex.tex[1]]),
|
||||
normal:acquire_normal_id(vertex.norm)?,
|
||||
color:color_id,
|
||||
}));
|
||||
Ok(vec![ingest_vertex1(&trip[0])?,ingest_vertex1(&trip[1])?,ingest_vertex1(&trip[2])?])
|
||||
}).collect::<Result<_,_>>()?)));
|
||||
let mut mb=model::MeshBuilder::new();
|
||||
match rbx_mesh::read_versioned(std::io::Cursor::new(roblox_mesh_bytes)).map_err(Error::RbxMesh)?{
|
||||
rbx_mesh::mesh::Mesh::V1(mesh)=>{
|
||||
let color_id=mb.acquire_color_id(glam::Vec4::ONE);
|
||||
let polygon_list=new_polygon_list_checked(mesh.vertices.chunks_exact(3).filter_map(|trip|{
|
||||
let mut ingest_vertex1=|vertex:&rbx_mesh::mesh::Vertex1|{
|
||||
let vertex=IndexedVertex{
|
||||
pos:mb.acquire_pos_id(vec3::try_from_f32_array(vertex.pos).ok()?),
|
||||
tex:mb.acquire_tex_id(glam::vec2(vertex.tex[0],vertex.tex[1])),
|
||||
normal:mb.acquire_normal_id(vec3::try_from_f32_array(vertex.norm).ok()?),
|
||||
color:color_id,
|
||||
};
|
||||
Some(mb.acquire_vertex_id(vertex))
|
||||
};
|
||||
Some(vec![ingest_vertex1(&trip[0])?,ingest_vertex1(&trip[1])?,ingest_vertex1(&trip[2])?])
|
||||
}).collect());
|
||||
if let Some(polygon_list)=polygon_list{
|
||||
polygon_groups.push(PolygonGroup::PolygonList(polygon_list));
|
||||
}
|
||||
},
|
||||
rbx_mesh::mesh::VersionedMesh::Version2(mesh)=>{
|
||||
rbx_mesh::mesh::Mesh::V2(mesh)=>{
|
||||
let vertex_id_map=match mesh.header.sizeof_vertex{
|
||||
rbx_mesh::mesh::SizeOfVertex2::Truncated=>{
|
||||
//pick white and make all the vertices white
|
||||
let color_id=acquire_color_id([1.0f32;4]);
|
||||
ingest_vertices_truncated2(mesh.vertices_truncated,&mut acquire_pos_id,&mut acquire_tex_id,&mut acquire_normal_id,color_id,&mut acquire_vertex_id)
|
||||
let color_id=mb.acquire_color_id(glam::Vec4::ONE);
|
||||
ingest_vertices_truncated2(mesh.vertices_truncated,&mut mb,color_id)
|
||||
},
|
||||
rbx_mesh::mesh::SizeOfVertex2::Full=>ingest_vertices2(mesh.vertices,&mut acquire_pos_id,&mut acquire_tex_id,&mut acquire_normal_id,&mut acquire_color_id,&mut acquire_vertex_id),
|
||||
}?;
|
||||
rbx_mesh::mesh::SizeOfVertex2::Full=>ingest_vertices2(mesh.vertices,&mut mb),
|
||||
};
|
||||
//one big happy group for all the faces
|
||||
polygon_groups.push(PolygonGroup::PolygonList(PolygonList::new(mesh.faces.into_iter().map(|face|
|
||||
vec![vertex_id_map[&face.0],vertex_id_map[&face.1],vertex_id_map[&face.2]]
|
||||
).collect())));
|
||||
let polygon_list=new_polygon_list_checked(mesh.faces.into_iter().filter_map(|face|
|
||||
Some(vec![*vertex_id_map.get(&face.0)?,*vertex_id_map.get(&face.1)?,*vertex_id_map.get(&face.2)?])
|
||||
).collect());
|
||||
if let Some(polygon_list)=polygon_list{
|
||||
polygon_groups.push(PolygonGroup::PolygonList(polygon_list));
|
||||
}
|
||||
},
|
||||
rbx_mesh::mesh::VersionedMesh::Version3(mesh)=>{
|
||||
rbx_mesh::mesh::Mesh::V3(mesh)=>{
|
||||
let vertex_id_map=match mesh.header.sizeof_vertex{
|
||||
rbx_mesh::mesh::SizeOfVertex2::Truncated=>{
|
||||
let color_id=acquire_color_id([1.0f32;4]);
|
||||
ingest_vertices_truncated2(mesh.vertices_truncated,&mut acquire_pos_id,&mut acquire_tex_id,&mut acquire_normal_id,color_id,&mut acquire_vertex_id)
|
||||
let color_id=mb.acquire_color_id(glam::Vec4::ONE);
|
||||
ingest_vertices_truncated2(mesh.vertices_truncated,&mut mb,color_id)
|
||||
},
|
||||
rbx_mesh::mesh::SizeOfVertex2::Full=>ingest_vertices2(mesh.vertices,&mut acquire_pos_id,&mut acquire_tex_id,&mut acquire_normal_id,&mut acquire_color_id,&mut acquire_vertex_id),
|
||||
}?;
|
||||
rbx_mesh::mesh::SizeOfVertex2::Full=>ingest_vertices2(mesh.vertices,&mut mb),
|
||||
};
|
||||
ingest_faces2_lods3(&mut polygon_groups,&vertex_id_map,&mesh.faces,&mesh.lods);
|
||||
},
|
||||
rbx_mesh::mesh::VersionedMesh::Version4(mesh)=>{
|
||||
let vertex_id_map=ingest_vertices2(
|
||||
mesh.vertices,&mut acquire_pos_id,&mut acquire_tex_id,&mut acquire_normal_id,&mut acquire_color_id,&mut acquire_vertex_id
|
||||
)?;
|
||||
rbx_mesh::mesh::Mesh::V4(mesh)=>{
|
||||
let vertex_id_map=ingest_vertices2(mesh.vertices,&mut mb);
|
||||
ingest_faces2_lods3(&mut polygon_groups,&vertex_id_map,&mesh.faces,&mesh.lods);
|
||||
},
|
||||
rbx_mesh::mesh::VersionedMesh::Version5(mesh)=>{
|
||||
let vertex_id_map=ingest_vertices2(
|
||||
mesh.vertices,&mut acquire_pos_id,&mut acquire_tex_id,&mut acquire_normal_id,&mut acquire_color_id,&mut acquire_vertex_id
|
||||
)?;
|
||||
rbx_mesh::mesh::Mesh::V5(mesh)=>{
|
||||
let vertex_id_map=ingest_vertices2(mesh.vertices,&mut mb);
|
||||
ingest_faces2_lods3(&mut polygon_groups,&vertex_id_map,&mesh.faces,&mesh.lods);
|
||||
},
|
||||
}
|
||||
Ok(model::Mesh{
|
||||
unique_pos,
|
||||
unique_normal,
|
||||
unique_tex,
|
||||
unique_color,
|
||||
unique_vertices,
|
||||
if polygon_groups.is_empty(){
|
||||
return Err(Error::NoPolygons);
|
||||
}
|
||||
let mesh=mb.build(
|
||||
polygon_groups,
|
||||
//these should probably be moved to the model...
|
||||
graphics_groups:Vec::new(),
|
||||
physics_groups:Vec::new(),
|
||||
})
|
||||
//but what if models want to use the same texture
|
||||
vec![model::IndexedGraphicsGroup{
|
||||
render:RenderConfigId::new(0),
|
||||
//the lowest lod is highest quality
|
||||
groups:vec![model::PolygonGroupId::new(0)]
|
||||
}],
|
||||
//disable physics
|
||||
Vec::new(),
|
||||
);
|
||||
let mut aabb=Aabb::default();
|
||||
for &point in &mesh.unique_pos{
|
||||
aabb.grow(point);
|
||||
}
|
||||
Ok(MeshWithSize{mesh,size:aabb.size()})
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use strafesnet_common::model::{Color4,TextureCoordinate,Mesh,IndexedGraphicsGroup,IndexedPhysicsGroup,IndexedVertex,PolygonGroupId,PolygonGroup,PolygonList,IndexedVertexList,PositionId,TextureCoordinateId,NormalId,ColorId,VertexId,RenderConfigId};
|
||||
use strafesnet_common::integer::{vec3,Planar64Vec3};
|
||||
use crate::rbx::{RobloxPartDescription,RobloxWedgeDescription,RobloxCornerWedgeDescription};
|
||||
use strafesnet_common::model::{Color4,TextureCoordinate,Mesh,MeshBuilder,IndexedGraphicsGroup,IndexedPhysicsGroup,IndexedVertex,PolygonGroupId,PolygonGroup,PolygonList,PositionId,TextureCoordinateId,NormalId,ColorId,VertexId,RenderConfigId};
|
||||
use strafesnet_common::integer::{vec3,Planar64,Planar64Vec3};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Primitives{
|
||||
@@ -9,7 +10,22 @@ pub enum Primitives{
|
||||
Wedge,
|
||||
CornerWedge,
|
||||
}
|
||||
#[derive(Hash,PartialEq,Eq)]
|
||||
#[derive(Debug)]
|
||||
pub struct PrimitivesError;
|
||||
impl TryFrom<u32> for Primitives{
|
||||
type Error=PrimitivesError;
|
||||
fn try_from(value:u32)->Result<Self,Self::Error>{
|
||||
match value{
|
||||
0=>Ok(Primitives::Sphere),
|
||||
1=>Ok(Primitives::Cube),
|
||||
2=>Ok(Primitives::Cylinder),
|
||||
3=>Ok(Primitives::Wedge),
|
||||
4=>Ok(Primitives::CornerWedge),
|
||||
_=>Err(PrimitivesError),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone,Copy,Hash,PartialEq,Eq)]
|
||||
pub enum CubeFace{
|
||||
Right,
|
||||
Top,
|
||||
@@ -18,13 +34,29 @@ pub enum CubeFace{
|
||||
Bottom,
|
||||
Front,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct CubeFaceError;
|
||||
impl TryFrom<u32> for CubeFace{
|
||||
type Error=CubeFaceError;
|
||||
fn try_from(value:u32)->Result<Self,Self::Error>{
|
||||
match value{
|
||||
0=>Ok(CubeFace::Right),
|
||||
1=>Ok(CubeFace::Top),
|
||||
2=>Ok(CubeFace::Back),
|
||||
3=>Ok(CubeFace::Left),
|
||||
4=>Ok(CubeFace::Bottom),
|
||||
5=>Ok(CubeFace::Front),
|
||||
_=>Err(CubeFaceError),
|
||||
}
|
||||
}
|
||||
}
|
||||
const CUBE_DEFAULT_TEXTURE_COORDS:[TextureCoordinate;4]=[
|
||||
TextureCoordinate::new(0.0,0.0),
|
||||
TextureCoordinate::new(1.0,0.0),
|
||||
TextureCoordinate::new(1.0,1.0),
|
||||
TextureCoordinate::new(0.0,1.0),
|
||||
];
|
||||
const CUBE_DEFAULT_VERTICES:[Planar64Vec3;8]=[
|
||||
pub const CUBE_DEFAULT_VERTICES:[Planar64Vec3;8]=[
|
||||
vec3::int(-1,-1, 1),//0 left bottom back
|
||||
vec3::int( 1,-1, 1),//1 right bottom back
|
||||
vec3::int( 1, 1, 1),//2 right top back
|
||||
@@ -34,7 +66,7 @@ const CUBE_DEFAULT_VERTICES:[Planar64Vec3;8]=[
|
||||
vec3::int( 1,-1,-1),//6 right bottom front
|
||||
vec3::int(-1,-1,-1),//7 left bottom front
|
||||
];
|
||||
const CUBE_DEFAULT_NORMALS:[Planar64Vec3;6]=[
|
||||
pub const CUBE_DEFAULT_NORMALS:[Planar64Vec3;6]=[
|
||||
vec3::int( 1, 0, 0),//CubeFace::Right
|
||||
vec3::int( 0, 1, 0),//CubeFace::Top
|
||||
vec3::int( 0, 0, 1),//CubeFace::Back
|
||||
@@ -42,154 +74,36 @@ const CUBE_DEFAULT_NORMALS:[Planar64Vec3;6]=[
|
||||
vec3::int( 0,-1, 0),//CubeFace::Bottom
|
||||
vec3::int( 0, 0,-1),//CubeFace::Front
|
||||
];
|
||||
const CUBE_DEFAULT_POLYS:[[[u32;3];4];6]=[
|
||||
// right (1, 0, 0)
|
||||
[
|
||||
[6,2,0],//[vertex,tex,norm]
|
||||
[5,1,0],
|
||||
[2,0,0],
|
||||
[1,3,0],
|
||||
],
|
||||
// top (0, 1, 0)
|
||||
[
|
||||
[5,3,1],
|
||||
[4,2,1],
|
||||
[3,1,1],
|
||||
[2,0,1],
|
||||
],
|
||||
// back (0, 0, 1)
|
||||
[
|
||||
[0,3,2],
|
||||
[1,2,2],
|
||||
[2,1,2],
|
||||
[3,0,2],
|
||||
],
|
||||
// left (-1, 0, 0)
|
||||
[
|
||||
[0,2,3],
|
||||
[3,1,3],
|
||||
[4,0,3],
|
||||
[7,3,3],
|
||||
],
|
||||
// bottom (0,-1, 0)
|
||||
[
|
||||
[1,1,4],
|
||||
[0,0,4],
|
||||
[7,3,4],
|
||||
[6,2,4],
|
||||
],
|
||||
// front (0, 0,-1)
|
||||
[
|
||||
[4,1,5],
|
||||
[5,0,5],
|
||||
[6,3,5],
|
||||
[7,2,5],
|
||||
],
|
||||
];
|
||||
|
||||
#[derive(Hash,PartialEq,Eq)]
|
||||
pub enum WedgeFace{
|
||||
Right,
|
||||
TopFront,
|
||||
Back,
|
||||
Left,
|
||||
Bottom,
|
||||
}
|
||||
const WEDGE_DEFAULT_NORMALS:[Planar64Vec3;5]=[
|
||||
vec3::int( 1, 0, 0),//Wedge::Right
|
||||
vec3::int( 0, 1,-1),//Wedge::TopFront
|
||||
vec3::int( 0, 0, 1),//Wedge::Back
|
||||
vec3::int(-1, 0, 0),//Wedge::Left
|
||||
vec3::int( 0,-1, 0),//Wedge::Bottom
|
||||
];
|
||||
/*
|
||||
local cornerWedgeVerticies = {
|
||||
Vector3.new(-1/2,-1/2,-1/2),7
|
||||
Vector3.new(-1/2,-1/2, 1/2),0
|
||||
Vector3.new( 1/2,-1/2,-1/2),6
|
||||
Vector3.new( 1/2,-1/2, 1/2),1
|
||||
Vector3.new( 1/2, 1/2,-1/2),5
|
||||
}
|
||||
*/
|
||||
#[derive(Hash,PartialEq,Eq)]
|
||||
pub enum CornerWedgeFace{
|
||||
Right,
|
||||
TopBack,
|
||||
TopLeft,
|
||||
Bottom,
|
||||
Front,
|
||||
}
|
||||
const CORNERWEDGE_DEFAULT_NORMALS:[Planar64Vec3;5]=[
|
||||
vec3::int( 1, 0, 0),//CornerWedge::Right
|
||||
vec3::int( 0, 1, 1),//CornerWedge::BackTop
|
||||
vec3::int(-1, 1, 0),//CornerWedge::LeftTop
|
||||
vec3::int( 0,-1, 0),//CornerWedge::Bottom
|
||||
vec3::int( 0, 0,-1),//CornerWedge::Front
|
||||
];
|
||||
pub fn unit_sphere(render:RenderConfigId)->Mesh{
|
||||
unit_cube(render)
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct CubeFaceDescription([Option<FaceDescription>;6]);
|
||||
pub struct CubeFaceDescription([FaceDescription;Self::FACES]);
|
||||
impl CubeFaceDescription{
|
||||
pub fn insert(&mut self,index:CubeFace,value:FaceDescription){
|
||||
self.0[index as usize]=Some(value);
|
||||
}
|
||||
pub fn pairs(self)->std::iter::FilterMap<std::iter::Enumerate<std::array::IntoIter<Option<FaceDescription>,6>>,impl FnMut((usize,Option<FaceDescription>))->Option<(usize,FaceDescription)>>{
|
||||
self.0.into_iter().enumerate().filter_map(|v|v.1.map(|u|(v.0,u)))
|
||||
pub const FACES:usize=6;
|
||||
pub fn new(RobloxPartDescription(part_description):RobloxPartDescription,textureless_render_id:RenderConfigId)->Self{
|
||||
Self(part_description.map(|face_description|match face_description{
|
||||
Some(roblox_texture_transform)=>roblox_texture_transform.to_face_description(),
|
||||
None=>FaceDescription::new_with_render_id(textureless_render_id),
|
||||
}))
|
||||
}
|
||||
}
|
||||
pub fn unit_cube(render:RenderConfigId)->Mesh{
|
||||
let mut t=CubeFaceDescription::default();
|
||||
t.insert(CubeFace::Right,FaceDescription::new_with_render_id(render));
|
||||
t.insert(CubeFace::Top,FaceDescription::new_with_render_id(render));
|
||||
t.insert(CubeFace::Back,FaceDescription::new_with_render_id(render));
|
||||
t.insert(CubeFace::Left,FaceDescription::new_with_render_id(render));
|
||||
t.insert(CubeFace::Bottom,FaceDescription::new_with_render_id(render));
|
||||
t.insert(CubeFace::Front,FaceDescription::new_with_render_id(render));
|
||||
generate_partial_unit_cube(t)
|
||||
}
|
||||
pub fn unit_cylinder(render:RenderConfigId)->Mesh{
|
||||
//lmao
|
||||
unit_cube(render)
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct WedgeFaceDescription([Option<FaceDescription>;5]);
|
||||
pub struct WedgeFaceDescription([FaceDescription;Self::FACES]);
|
||||
impl WedgeFaceDescription{
|
||||
pub fn insert(&mut self,index:WedgeFace,value:FaceDescription){
|
||||
self.0[index as usize]=Some(value);
|
||||
}
|
||||
pub fn pairs(self)->std::iter::FilterMap<std::iter::Enumerate<std::array::IntoIter<Option<FaceDescription>,5>>,impl FnMut((usize,Option<FaceDescription>))->Option<(usize,FaceDescription)>>{
|
||||
self.0.into_iter().enumerate().filter_map(|v|v.1.map(|u|(v.0,u)))
|
||||
pub const FACES:usize=5;
|
||||
pub fn new(RobloxWedgeDescription(part_description):RobloxWedgeDescription,textureless_render_id:RenderConfigId)->Self{
|
||||
Self(part_description.map(|face_description|match face_description{
|
||||
Some(roblox_texture_transform)=>roblox_texture_transform.to_face_description(),
|
||||
None=>FaceDescription::new_with_render_id(textureless_render_id),
|
||||
}))
|
||||
}
|
||||
}
|
||||
pub fn unit_wedge(render:RenderConfigId)->Mesh{
|
||||
let mut t=WedgeFaceDescription::default();
|
||||
t.insert(WedgeFace::Right,FaceDescription::new_with_render_id(render));
|
||||
t.insert(WedgeFace::TopFront,FaceDescription::new_with_render_id(render));
|
||||
t.insert(WedgeFace::Back,FaceDescription::new_with_render_id(render));
|
||||
t.insert(WedgeFace::Left,FaceDescription::new_with_render_id(render));
|
||||
t.insert(WedgeFace::Bottom,FaceDescription::new_with_render_id(render));
|
||||
generate_partial_unit_wedge(t)
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub struct CornerWedgeFaceDescription([Option<FaceDescription>;5]);
|
||||
pub struct CornerWedgeFaceDescription([FaceDescription;Self::FACES]);
|
||||
impl CornerWedgeFaceDescription{
|
||||
pub fn insert(&mut self,index:CornerWedgeFace,value:FaceDescription){
|
||||
self.0[index as usize]=Some(value);
|
||||
pub const FACES:usize=5;
|
||||
pub fn new(RobloxCornerWedgeDescription(part_description):RobloxCornerWedgeDescription,textureless_render_id:RenderConfigId)->Self{
|
||||
Self(part_description.map(|face_description|match face_description{
|
||||
Some(roblox_texture_transform)=>roblox_texture_transform.to_face_description(),
|
||||
None=>FaceDescription::new_with_render_id(textureless_render_id),
|
||||
}))
|
||||
}
|
||||
pub fn pairs(self)->std::iter::FilterMap<std::iter::Enumerate<std::array::IntoIter<Option<FaceDescription>,5>>,impl FnMut((usize,Option<FaceDescription>))->Option<(usize,FaceDescription)>>{
|
||||
self.0.into_iter().enumerate().filter_map(|v|v.1.map(|u|(v.0,u)))
|
||||
}
|
||||
}
|
||||
pub fn unit_cornerwedge(render:RenderConfigId)->Mesh{
|
||||
let mut t=CornerWedgeFaceDescription::default();
|
||||
t.insert(CornerWedgeFace::Right,FaceDescription::new_with_render_id(render));
|
||||
t.insert(CornerWedgeFace::TopBack,FaceDescription::new_with_render_id(render));
|
||||
t.insert(CornerWedgeFace::TopLeft,FaceDescription::new_with_render_id(render));
|
||||
t.insert(CornerWedgeFace::Bottom,FaceDescription::new_with_render_id(render));
|
||||
t.insert(CornerWedgeFace::Front,FaceDescription::new_with_render_id(render));
|
||||
generate_partial_unit_cornerwedge(t)
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -199,7 +113,7 @@ pub struct FaceDescription{
|
||||
pub color:Color4,
|
||||
}
|
||||
impl FaceDescription{
|
||||
pub fn new_with_render_id(render:RenderConfigId)->Self {
|
||||
pub fn new_with_render_id(render:RenderConfigId)->Self{
|
||||
Self{
|
||||
render,
|
||||
transform:glam::Affine2::IDENTITY,
|
||||
@@ -207,7 +121,51 @@ impl FaceDescription{
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->Mesh{
|
||||
pub const CUBE_DEFAULT_POLYS:[[[u32;2];4];6]=[
|
||||
// right (1, 0, 0)
|
||||
[
|
||||
[6,2],//[vertex,tex]
|
||||
[5,1],
|
||||
[2,0],
|
||||
[1,3],
|
||||
],
|
||||
// top (0, 1, 0)
|
||||
[
|
||||
[5,3],
|
||||
[4,2],
|
||||
[3,1],
|
||||
[2,0],
|
||||
],
|
||||
// back (0, 0, 1)
|
||||
[
|
||||
[0,3],
|
||||
[1,2],
|
||||
[2,1],
|
||||
[3,0],
|
||||
],
|
||||
// left (-1, 0, 0)
|
||||
[
|
||||
[0,2],
|
||||
[3,1],
|
||||
[4,0],
|
||||
[7,3],
|
||||
],
|
||||
// bottom (0,-1, 0)
|
||||
[
|
||||
[1,1],
|
||||
[0,0],
|
||||
[7,3],
|
||||
[6,2],
|
||||
],
|
||||
// front (0, 0,-1)
|
||||
[
|
||||
[4,1],
|
||||
[5,0],
|
||||
[6,3],
|
||||
[7,2],
|
||||
],
|
||||
];
|
||||
pub fn unit_cube(CubeFaceDescription(face_descriptions):CubeFaceDescription)->Mesh{
|
||||
let mut generated_pos=Vec::new();
|
||||
let mut generated_tex=Vec::new();
|
||||
let mut generated_normal=Vec::new();
|
||||
@@ -218,7 +176,7 @@ pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->Mesh{
|
||||
let mut physics_group=IndexedPhysicsGroup::default();
|
||||
let mut transforms=Vec::new();
|
||||
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
|
||||
for (face_id,face_description) in face_descriptions.pairs(){
|
||||
for (face_id,face_description) in face_descriptions.into_iter().enumerate(){
|
||||
//assume that scanning short lists is faster than hashing.
|
||||
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
||||
transform_index
|
||||
@@ -245,8 +203,8 @@ pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->Mesh{
|
||||
//push vertices as they are needed
|
||||
let group_id=PolygonGroupId::new(polygon_groups.len() as u32);
|
||||
polygon_groups.push(PolygonGroup::PolygonList(PolygonList::new(vec![
|
||||
CUBE_DEFAULT_POLYS[face_id].map(|tup|{
|
||||
let pos=CUBE_DEFAULT_VERTICES[tup[0] as usize];
|
||||
CUBE_DEFAULT_POLYS[face_id].map(|[pos_id,tex_id]|{
|
||||
let pos=CUBE_DEFAULT_VERTICES[pos_id as usize];
|
||||
let pos_index=if let Some(pos_index)=generated_pos.iter().position(|&p|p==pos){
|
||||
pos_index
|
||||
}else{
|
||||
@@ -258,7 +216,7 @@ pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->Mesh{
|
||||
//always push vertex
|
||||
let vertex=IndexedVertex{
|
||||
pos:PositionId::new(pos_index),
|
||||
tex:TextureCoordinateId::new(tup[1]+4*transform_index),
|
||||
tex:TextureCoordinateId::new(tex_id+4*transform_index),
|
||||
normal:NormalId::new(normal_index),
|
||||
color:ColorId::new(color_index),
|
||||
};
|
||||
@@ -285,42 +243,49 @@ pub fn generate_partial_unit_cube(face_descriptions:CubeFaceDescription)->Mesh{
|
||||
}
|
||||
}
|
||||
//don't think too hard about the copy paste because this is all going into the map tool eventually...
|
||||
pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->Mesh{
|
||||
let wedge_default_polys=[
|
||||
pub fn unit_wedge(WedgeFaceDescription(face_descriptions):WedgeFaceDescription)->Mesh{
|
||||
const WEDGE_DEFAULT_POLYS:[&[[u32;2]];5]=[
|
||||
// right (1, 0, 0)
|
||||
vec![
|
||||
[6,2,0],//[vertex,tex,norm]
|
||||
[2,0,0],
|
||||
[1,3,0],
|
||||
&[
|
||||
[6,2],//[vertex,tex]
|
||||
[2,0],
|
||||
[1,3],
|
||||
],
|
||||
// FrontTop (0, 1, -1)
|
||||
vec![
|
||||
[3,1,1],
|
||||
[2,0,1],
|
||||
[6,3,1],
|
||||
[7,2,1],
|
||||
&[
|
||||
[3,1],
|
||||
[2,0],
|
||||
[6,3],
|
||||
[7,2],
|
||||
],
|
||||
// back (0, 0, 1)
|
||||
vec![
|
||||
[0,3,2],
|
||||
[1,2,2],
|
||||
[2,1,2],
|
||||
[3,0,2],
|
||||
&[
|
||||
[0,3],
|
||||
[1,2],
|
||||
[2,1],
|
||||
[3,0],
|
||||
],
|
||||
// left (-1, 0, 0)
|
||||
vec![
|
||||
[0,2,3],
|
||||
[3,1,3],
|
||||
[7,3,3],
|
||||
&[
|
||||
[0,2],
|
||||
[3,1],
|
||||
[7,3],
|
||||
],
|
||||
// bottom (0,-1, 0)
|
||||
vec![
|
||||
[1,1,4],
|
||||
[0,0,4],
|
||||
[7,3,4],
|
||||
[6,2,4],
|
||||
&[
|
||||
[1,1],
|
||||
[0,0],
|
||||
[7,3],
|
||||
[6,2],
|
||||
],
|
||||
];
|
||||
const WEDGE_DEFAULT_NORMALS:[Planar64Vec3;5]=[
|
||||
vec3::int( 1, 0, 0),//Wedge::Right
|
||||
vec3::int( 0, 1,-1),//Wedge::TopFront
|
||||
vec3::int( 0, 0, 1),//Wedge::Back
|
||||
vec3::int(-1, 0, 0),//Wedge::Left
|
||||
vec3::int( 0,-1, 0),//Wedge::Bottom
|
||||
];
|
||||
let mut generated_pos=Vec::new();
|
||||
let mut generated_tex=Vec::new();
|
||||
let mut generated_normal=Vec::new();
|
||||
@@ -331,7 +296,7 @@ pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->Mesh
|
||||
let mut physics_group=IndexedPhysicsGroup::default();
|
||||
let mut transforms=Vec::new();
|
||||
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
|
||||
for (face_id,face_description) in face_descriptions.pairs(){
|
||||
for (face_id,face_description) in face_descriptions.into_iter().enumerate(){
|
||||
//assume that scanning short lists is faster than hashing.
|
||||
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
||||
transform_index
|
||||
@@ -358,8 +323,8 @@ pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->Mesh
|
||||
//push vertices as they are needed
|
||||
let group_id=PolygonGroupId::new(polygon_groups.len() as u32);
|
||||
polygon_groups.push(PolygonGroup::PolygonList(PolygonList::new(vec![
|
||||
wedge_default_polys[face_id].iter().map(|tup|{
|
||||
let pos=CUBE_DEFAULT_VERTICES[tup[0] as usize];
|
||||
WEDGE_DEFAULT_POLYS[face_id].iter().map(|&[pos_id,tex_id]|{
|
||||
let pos=CUBE_DEFAULT_VERTICES[pos_id as usize];
|
||||
let pos_index=if let Some(pos_index)=generated_pos.iter().position(|&p|p==pos){
|
||||
pos_index
|
||||
}else{
|
||||
@@ -371,7 +336,7 @@ pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->Mesh
|
||||
//always push vertex
|
||||
let vertex=IndexedVertex{
|
||||
pos:PositionId::new(pos_index),
|
||||
tex:TextureCoordinateId::new(tup[1]+4*transform_index),
|
||||
tex:TextureCoordinateId::new(tex_id+4*transform_index),
|
||||
normal:NormalId::new(normal_index),
|
||||
color:ColorId::new(color_index),
|
||||
};
|
||||
@@ -398,40 +363,47 @@ pub fn generate_partial_unit_wedge(face_descriptions:WedgeFaceDescription)->Mesh
|
||||
}
|
||||
}
|
||||
|
||||
pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescription)->Mesh{
|
||||
let cornerwedge_default_polys=[
|
||||
pub fn unit_cornerwedge(CornerWedgeFaceDescription(face_descriptions):CornerWedgeFaceDescription)->Mesh{
|
||||
const CORNERWEDGE_DEFAULT_POLYS:[&[[u32;2]];5]=[
|
||||
// right (1, 0, 0)
|
||||
vec![
|
||||
[6,2,0],//[vertex,tex,norm]
|
||||
[5,1,0],
|
||||
[1,3,0],
|
||||
&[
|
||||
[6,2],//[vertex,tex]
|
||||
[5,1],
|
||||
[1,3],
|
||||
],
|
||||
// BackTop (0, 1, 1)
|
||||
vec![
|
||||
[5,3,1],
|
||||
[0,1,1],
|
||||
[1,0,1],
|
||||
&[
|
||||
[5,3],
|
||||
[0,1],
|
||||
[1,0],
|
||||
],
|
||||
// LeftTop (-1, 1, 0)
|
||||
vec![
|
||||
[5,3,2],
|
||||
[7,2,2],
|
||||
[0,1,2],
|
||||
&[
|
||||
[5,3],
|
||||
[7,2],
|
||||
[0,1],
|
||||
],
|
||||
// bottom (0,-1, 0)
|
||||
vec![
|
||||
[1,1,3],
|
||||
[0,0,3],
|
||||
[7,3,3],
|
||||
[6,2,3],
|
||||
&[
|
||||
[1,1],
|
||||
[0,0],
|
||||
[7,3],
|
||||
[6,2],
|
||||
],
|
||||
// front (0, 0,-1)
|
||||
vec![
|
||||
[5,0,4],
|
||||
[6,3,4],
|
||||
[7,2,4],
|
||||
&[
|
||||
[5,0],
|
||||
[6,3],
|
||||
[7,2],
|
||||
],
|
||||
];
|
||||
const CORNERWEDGE_DEFAULT_NORMALS:[Planar64Vec3;5]=[
|
||||
vec3::int( 1, 0, 0),//CornerWedge::Right
|
||||
vec3::int( 0, 1, 1),//CornerWedge::BackTop
|
||||
vec3::int(-1, 1, 0),//CornerWedge::LeftTop
|
||||
vec3::int( 0,-1, 0),//CornerWedge::Bottom
|
||||
vec3::int( 0, 0,-1),//CornerWedge::Front
|
||||
];
|
||||
let mut generated_pos=Vec::new();
|
||||
let mut generated_tex=Vec::new();
|
||||
let mut generated_normal=Vec::new();
|
||||
@@ -442,7 +414,7 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
|
||||
let mut physics_group=IndexedPhysicsGroup::default();
|
||||
let mut transforms=Vec::new();
|
||||
//note that on a cube every vertex is guaranteed to be unique, so there's no need to hash them against existing vertices.
|
||||
for (face_id,face_description) in face_descriptions.pairs(){
|
||||
for (face_id,face_description) in face_descriptions.into_iter().enumerate(){
|
||||
//assume that scanning short lists is faster than hashing.
|
||||
let transform_index=if let Some(transform_index)=transforms.iter().position(|&transform|transform==face_description.transform){
|
||||
transform_index
|
||||
@@ -469,8 +441,8 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
|
||||
//push vertices as they are needed
|
||||
let group_id=PolygonGroupId::new(polygon_groups.len() as u32);
|
||||
polygon_groups.push(PolygonGroup::PolygonList(PolygonList::new(vec![
|
||||
cornerwedge_default_polys[face_id].iter().map(|tup|{
|
||||
let pos=CUBE_DEFAULT_VERTICES[tup[0] as usize];
|
||||
CORNERWEDGE_DEFAULT_POLYS[face_id].iter().map(|&[pos_id,tex_id]|{
|
||||
let pos=CUBE_DEFAULT_VERTICES[pos_id as usize];
|
||||
let pos_index=if let Some(pos_index)=generated_pos.iter().position(|&p|p==pos){
|
||||
pos_index
|
||||
}else{
|
||||
@@ -482,7 +454,7 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
|
||||
//always push vertex
|
||||
let vertex=IndexedVertex{
|
||||
pos:PositionId::new(pos_index),
|
||||
tex:TextureCoordinateId::new(tup[1]+4*transform_index),
|
||||
tex:TextureCoordinateId::new(tex_id+4*transform_index),
|
||||
normal:NormalId::new(normal_index),
|
||||
color:ColorId::new(color_index),
|
||||
};
|
||||
@@ -508,3 +480,133 @@ pub fn generate_partial_unit_cornerwedge(face_descriptions:CornerWedgeFaceDescri
|
||||
physics_groups:vec![physics_group],
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: fix face texture orientation
|
||||
pub fn unit_cylinder(face_descriptions:CubeFaceDescription)->Mesh{
|
||||
// cylinder is oriented about the x axis
|
||||
// roblox cylinders use projected grid coordinates
|
||||
/// how many grid coordinates to use (positive and negative)
|
||||
const GON:i32=3;
|
||||
/// grid perimeter
|
||||
const POINTS:[[i32;2];4*2*GON as usize]=const{
|
||||
let mut points=[[0;2];{4*2*GON as usize}];
|
||||
let mut i=-GON;
|
||||
while i<GON{
|
||||
points[(i+GON) as usize]=[i,GON];
|
||||
points[(i+GON+1*2*GON) as usize]=[GON,-i];
|
||||
points[(i+GON+2*2*GON) as usize]=[-i,-GON];
|
||||
points[(i+GON+3*2*GON) as usize]=[-GON,i];
|
||||
i+=1;
|
||||
}
|
||||
points
|
||||
};
|
||||
|
||||
let mut mb=MeshBuilder::new();
|
||||
let mut polygon_groups=Vec::with_capacity(CubeFaceDescription::FACES);
|
||||
let mut graphics_groups=Vec::with_capacity(CubeFaceDescription::FACES);
|
||||
let mut physics_group=IndexedPhysicsGroup{groups:Vec::with_capacity(CubeFaceDescription::FACES)};
|
||||
let CubeFaceDescription([right,top,back,left,bottom,front])=face_descriptions;
|
||||
|
||||
macro_rules! end_face{
|
||||
($face_description:expr,$end:expr,$iter:expr)=>{
|
||||
let normal=mb.acquire_normal_id($end);
|
||||
let color=mb.acquire_color_id($face_description.color);
|
||||
|
||||
// single polygon for physics
|
||||
let polygon:Vec<_>=$iter.map(|[x,y]|{
|
||||
let tex=mb.acquire_tex_id(
|
||||
$face_description.transform.transform_point2(
|
||||
(glam::vec2(-x as f32,y as f32).normalize()+1.0)/2.0
|
||||
)
|
||||
);
|
||||
let pos=mb.acquire_pos_id($end+vec3::int(0,-x,y).with_length(Planar64::ONE).divide().wrap_64());
|
||||
mb.acquire_vertex_id(IndexedVertex{pos,tex,normal,color})
|
||||
}).collect();
|
||||
|
||||
// fanned polygons for graphics
|
||||
let pos=mb.acquire_pos_id($end);
|
||||
let tex=mb.acquire_tex_id($face_description.transform.transform_point2(glam::Vec2::ONE/2.0));
|
||||
let center=mb.acquire_vertex_id(IndexedVertex{pos,tex,normal,color});
|
||||
let polygon_list=(0..POINTS.len()).map(|i|
|
||||
vec![center,polygon[i],polygon[(i+1)%POINTS.len()]]
|
||||
).collect();
|
||||
|
||||
// end face graphics
|
||||
let group_id=PolygonGroupId::new(polygon_groups.len() as u32);
|
||||
polygon_groups.push(PolygonGroup::PolygonList(PolygonList::new(polygon_list)));
|
||||
graphics_groups.push(IndexedGraphicsGroup{
|
||||
render:$face_description.render,
|
||||
groups:vec![group_id],
|
||||
});
|
||||
|
||||
// end face physics
|
||||
let polygon_list=vec![polygon];
|
||||
|
||||
let group_id=PolygonGroupId::new(polygon_groups.len() as u32);
|
||||
polygon_groups.push(PolygonGroup::PolygonList(PolygonList::new(polygon_list)));
|
||||
physics_group.groups.push(group_id);
|
||||
}
|
||||
}
|
||||
macro_rules! tex{
|
||||
($face_description:expr,$tex:expr)=>{{
|
||||
let [x,y]=$tex;
|
||||
$face_description.transform.transform_point2(
|
||||
glam::vec2((x+GON) as f32,(y+GON) as f32)/(2*GON) as f32
|
||||
)
|
||||
}};
|
||||
}
|
||||
macro_rules! barrel_face{
|
||||
($face_description:expr,$loop:ident,$lo_dir:expr,$hi_dir:expr,$tex_0:expr,$tex_1:expr,$tex_2:expr,$tex_3:expr)=>{
|
||||
let mut polygon_list=Vec::with_capacity(CubeFaceDescription::FACES);
|
||||
for $loop in -GON..GON{
|
||||
// lo Z
|
||||
let lz_dir=$lo_dir.with_length(Planar64::ONE).divide().wrap_64();
|
||||
// hi Z
|
||||
let hz_dir=$hi_dir.with_length(Planar64::ONE).divide().wrap_64();
|
||||
|
||||
// pos
|
||||
let lx_lz_pos=mb.acquire_pos_id(vec3::NEG_X+lz_dir);
|
||||
let lx_hz_pos=mb.acquire_pos_id(vec3::NEG_X+hz_dir);
|
||||
let hx_hz_pos=mb.acquire_pos_id(vec3::X+hz_dir);
|
||||
let hx_lz_pos=mb.acquire_pos_id(vec3::X+lz_dir);
|
||||
// tex
|
||||
let lx_lz_tex=mb.acquire_tex_id(tex!($face_description,$tex_0));
|
||||
let lx_hz_tex=mb.acquire_tex_id(tex!($face_description,$tex_1));
|
||||
let hx_hz_tex=mb.acquire_tex_id(tex!($face_description,$tex_2));
|
||||
let hx_lz_tex=mb.acquire_tex_id(tex!($face_description,$tex_3));
|
||||
// norm
|
||||
let lz_norm=mb.acquire_normal_id(lz_dir);
|
||||
let hz_norm=mb.acquire_normal_id(hz_dir);
|
||||
// color
|
||||
let color=mb.acquire_color_id($face_description.color);
|
||||
|
||||
polygon_list.push(vec![
|
||||
mb.acquire_vertex_id(IndexedVertex{pos:lx_lz_pos,tex:lx_lz_tex,normal:lz_norm,color}),
|
||||
mb.acquire_vertex_id(IndexedVertex{pos:lx_hz_pos,tex:lx_hz_tex,normal:hz_norm,color}),
|
||||
mb.acquire_vertex_id(IndexedVertex{pos:hx_hz_pos,tex:hx_hz_tex,normal:hz_norm,color}),
|
||||
mb.acquire_vertex_id(IndexedVertex{pos:hx_lz_pos,tex:hx_lz_tex,normal:lz_norm,color}),
|
||||
]);
|
||||
}
|
||||
|
||||
// push face
|
||||
let group_id=PolygonGroupId::new(polygon_groups.len() as u32);
|
||||
polygon_groups.push(PolygonGroup::PolygonList(PolygonList::new(polygon_list)));
|
||||
graphics_groups.push(IndexedGraphicsGroup{
|
||||
render:$face_description.render,
|
||||
groups:vec![group_id],
|
||||
});
|
||||
physics_group.groups.push(group_id);
|
||||
};
|
||||
}
|
||||
|
||||
end_face!(right, vec3::X,POINTS.into_iter());
|
||||
barrel_face!(top, z,vec3::int(0,GON,z),vec3::int(0,GON,z+1), [GON,z],[GON,z+1],[-GON,z+1],[-GON,z]);
|
||||
barrel_face!(back, y,vec3::int(0,y+1,GON),vec3::int(0,y,GON), [GON,y+1],[GON,y],[-GON,y],[-GON,y+1]);
|
||||
end_face!(left, vec3::NEG_X,POINTS.into_iter().rev());
|
||||
barrel_face!(bottom, z,vec3::int(0,-GON,z+1),vec3::int(0,-GON,z), [-GON,z+1],[-GON,z],[GON,z],[GON,z+1]);
|
||||
barrel_face!(front, y,vec3::int(0,y,-GON),vec3::int(0,y+1,-GON), [-GON,y],[-GON,y+1],[GON,y+1],[GON,y]);
|
||||
|
||||
let physics_groups=vec![physics_group];
|
||||
|
||||
mb.build(polygon_groups,graphics_groups,physics_groups)
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user