mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-12-03 19:51:49 +00:00
Compare commits
764
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e963db1a9d | ||
|
|
8e19a7ed63 | ||
|
|
5695cf053e | ||
|
|
22d69f362f | ||
|
|
263f5baa3c | ||
|
|
e862a80615 | ||
|
|
7d166df70f | ||
|
|
573e631bb8 | ||
|
|
ecc08197e8 | ||
|
|
e550c5c77b | ||
|
|
88c43590fe | ||
|
|
d4da60a253 | ||
|
|
87b088787b | ||
|
|
541419285d | ||
|
|
bdb3d16dfc | ||
|
|
ebd31db06f | ||
|
|
428f9cfb0e | ||
|
|
dccdd8c09d | ||
|
|
93d6ffe70e | ||
|
|
e759edadfe | ||
|
|
6de53ee898 | ||
|
|
4e46eb4a6a | ||
|
|
55f6a06f9f | ||
|
|
67063b02d7 | ||
|
|
6a86ad4b3f | ||
|
|
547edabfdf | ||
|
|
f4821f7b0d | ||
|
|
e9b80420de | ||
|
|
5915a968ff | ||
|
|
5e211fb1c4 | ||
|
|
1b08857bb8 | ||
|
|
e51f1b8c62 | ||
|
|
a71b27ce31 | ||
|
|
f98b6dc548 | ||
|
|
9cc45b41d0 | ||
|
|
0d18637128 | ||
|
|
6e96c6b71e | ||
|
|
e7d1ed24cb | ||
|
|
620d59ad7a | ||
|
|
24c03b66d7 | ||
|
|
91f23c52b8 | ||
|
|
0812c55425 | ||
|
|
49e8bf7885 | ||
|
|
6cf5d7131b | ||
|
|
4bdac458c0 | ||
|
|
9f3da18f2b | ||
|
|
468802ac14 | ||
|
|
3ac240f936 | ||
|
|
f9e33f560d | ||
|
|
bce3142517 | ||
|
|
eb801acd86 | ||
|
|
cd7e9e3416 | ||
|
|
65a6cebe9c | ||
|
|
bfd2a762c7 | ||
|
|
5ea1a69190 | ||
|
|
da77a04fd0 | ||
|
|
1ab8aeff9e | ||
|
|
6c4e4ef6f7 | ||
|
|
bedaac5155 | ||
|
|
22b193e70a | ||
|
|
a00e4bbdf0 | ||
|
|
3c6dc52b8e | ||
|
|
aaa5e05cf0 | ||
|
|
cb9103c4d9 | ||
|
|
2889274291 | ||
|
|
6b2b0ec7f0 | ||
|
|
1dea1b098d | ||
|
|
1e44f45a34 | ||
|
|
bcbabc8f60 | ||
|
|
3c03bba7e7 | ||
|
|
7eb45cebf6 | ||
|
|
dbfc1d0c34 | ||
|
|
e2ebc7fe8a | ||
|
|
80ecd143da | ||
|
|
2366c87659 | ||
|
|
8136fa857f | ||
|
|
a8aaa3c3cf | ||
|
|
eb2113b835 | ||
|
|
d33d29be51 | ||
|
|
4950cf1969 | ||
|
|
7042538b89 | ||
|
|
df80f2a99d | ||
|
|
69b0303148 | ||
|
|
6d4d14606c | ||
|
|
7b907cfdc9 | ||
|
|
08f4bffca9 | ||
|
|
3d55236f97 | ||
|
|
d705dee379 | ||
|
|
30c063853d | ||
|
|
6f772a2808 | ||
|
|
723764a782 | ||
|
|
d28b9d13cc | ||
|
|
76dcab175b | ||
|
|
f3bf0aea4b | ||
|
|
fc3ea69d74 | ||
|
|
ffbd0db03a | ||
|
|
3eb8566ef9 | ||
|
|
c2183bc470 | ||
|
|
843dcf702f | ||
|
|
23bed57728 | ||
|
|
0b5aa54df7 | ||
|
|
5efffcd0b2 | ||
|
|
7053224ba5 | ||
|
|
88ee0e89f7 | ||
|
|
7e4c159039 | ||
|
|
041e11f4a9 | ||
|
|
7b2a232a42 | ||
|
|
5a2c5b2592 | ||
|
|
37a294561d | ||
|
|
cf07610a0c | ||
|
|
48523f84c2 | ||
|
|
543e8c615e | ||
|
|
ba8429952a | ||
|
|
2961ed6b7d | ||
|
|
3d209b393c | ||
|
|
5ab99210b2 | ||
|
|
ff23e2fb7b | ||
|
|
2bdc3cdc93 | ||
|
|
5d7d4f9648 | ||
|
|
4b1d85177f | ||
|
|
55786d6297 | ||
|
|
c448da1155 | ||
|
|
11f45a4077 | ||
|
|
5cab50b5df | ||
|
|
f78600be70 | ||
|
|
b731ab7c02 | ||
|
|
19129c2eb8 | ||
|
|
df0186c564 | ||
|
|
ae60b14402 | ||
|
|
a02911040d | ||
|
|
b18cc310d7 | ||
|
|
742080c6f2 | ||
|
|
e87e6d9fae | ||
|
|
af72e33a1b | ||
|
|
3558a09a1f | ||
|
|
e3dd61c177 | ||
|
|
a578e90ecf | ||
|
|
de31f75797 | ||
|
|
128e90ea9b | ||
|
|
898148fade | ||
|
|
149a257a4c | ||
|
|
c77a9fb012 | ||
|
|
ccdfad8ba5 | ||
|
|
443ed9af65 | ||
|
|
8748d85e37 | ||
|
|
92ab8b6d01 | ||
|
|
0f0760e7f4 | ||
|
|
8d5b605afd | ||
|
|
0d9ea26cc9 | ||
|
|
fd936f4dd8 | ||
|
|
e004ae1775 | ||
|
|
867851366d | ||
|
|
9b86b34187 | ||
|
|
bed98c417d | ||
|
|
971cad0463 | ||
|
|
887daac844 | ||
|
|
73863e8219 | ||
|
|
de1c6e887f | ||
|
|
c3c137a33c | ||
|
|
b0f535832e | ||
|
|
36fcff7caf | ||
|
|
0f2272299e | ||
|
|
8c489e4a26 | ||
|
|
8e0e6d7d45 | ||
|
|
39e4015b44 | ||
|
|
4db1853bea | ||
|
|
fc5c6ce0ab | ||
|
|
b9d8125180 | ||
|
|
6ecfbbaa6e | ||
|
|
ae11b38093 | ||
|
|
23c93e6e74 | ||
|
|
6879af515e | ||
|
|
18c6b189d1 | ||
|
|
3691611c6c | ||
|
|
a81a3abb9f | ||
|
|
b3b0c64b55 | ||
|
|
4e226b93f4 | ||
|
|
68ae3c8d3a | ||
|
|
925c942764 | ||
|
|
cff15f93c5 | ||
|
|
7bef5dbfd4 | ||
|
|
67d5128942 | ||
|
|
27b0036450 | ||
|
|
6d18d51076 | ||
|
|
ce7f782561 | ||
|
|
28d9c34dd2 | ||
|
|
f7aaed79a6 | ||
|
|
d4704817a5 | ||
|
|
dac8baa3ab | ||
|
|
88fe8c8bcd | ||
|
|
616e50e605 | ||
|
|
0b5b0190f5 | ||
|
|
131f1575ae | ||
|
|
699ad3f6fe | ||
|
|
cd03fb0c0a | ||
|
|
0691753d21 | ||
|
|
db4972b42a | ||
|
|
769a29ce83 | ||
|
|
307b89c5fe | ||
|
|
96532f9a22 | ||
|
|
4f772e2b48 | ||
|
|
36f5b7e8b8 | ||
|
|
a3cbb0e053 | ||
|
|
62e33edfe3 | ||
|
|
6c8fa31a7b | ||
|
|
a6f1ccd1e7 | ||
|
|
97410afad9 | ||
|
|
7c90040924 | ||
|
|
fa7c3a0abf | ||
|
|
1e0a8d2bd6 | ||
|
|
cf0e49e34d | ||
|
|
a0fcb74365 | ||
|
|
7cc3302c32 | ||
|
|
c61865b9f2 | ||
|
|
a905dc24e7 | ||
|
|
2a68f41bef | ||
|
|
6a3c51e4fe | ||
|
|
a5d0229417 | ||
|
|
bcec8e474d | ||
|
|
fc81e54b0c | ||
|
|
f7d2ce86a7 | ||
|
|
5979e3d49d | ||
|
|
4e7a46fb2d | ||
|
|
ab32568550 | ||
|
|
480e5485ac | ||
|
|
e999af0082 | ||
|
|
66c4f01b21 | ||
|
|
2e4fd306e8 | ||
|
|
b943a43442 | ||
|
|
806792ebae | ||
|
|
1bcd846fb5 | ||
|
|
d1a9c2c68b | ||
|
|
949157fd26 | ||
|
|
672f781132 | ||
|
|
e8fca6d8c6 | ||
|
|
6e1a206013 | ||
|
|
6e2d94a4c8 | ||
|
|
264f754297 | ||
|
|
4acc1ee2b9 | ||
|
|
7bc9f21f50 | ||
|
|
6c4bbb1df5 | ||
|
|
c577b68c00 | ||
|
|
0c2aefef20 | ||
|
|
f466979679 | ||
|
|
32a07bd005 | ||
|
|
b961a5d3b2 | ||
|
|
956c33e8db | ||
|
|
84bd65fdc4 | ||
|
|
f98d78a87b | ||
|
|
59f24a03af | ||
|
|
cdd138d9f4 | ||
|
|
c0ac9d7f4e | ||
|
|
5d0c378f88 | ||
|
|
2b6f96e5c2 | ||
|
|
1c50eaf776 | ||
|
|
eb2ac206b1 | ||
|
|
a27c0bf860 | ||
|
|
9c39c564be | ||
|
|
922fe5e4cf | ||
|
|
db2962a25e | ||
|
|
2896aeb400 | ||
|
|
d0b57a4886 | ||
|
|
1aba430153 | ||
|
|
7eff4d0754 | ||
|
|
949d2ecac3 | ||
|
|
2befcb9487 | ||
|
|
8ace4ccc99 | ||
|
|
5dd753c589 | ||
|
|
3fde8c420f | ||
|
|
7d06fb50c3 | ||
|
|
874cb4fe16 | ||
|
|
cb3859b40f | ||
|
|
0732f5a9b8 | ||
|
|
e0812cca66 | ||
|
|
c753a1a7fe | ||
|
|
f70b8a8abc | ||
|
|
a658cd2446 | ||
|
|
674f9756e3 | ||
|
|
13c0705d44 | ||
|
|
e20bf1dd57 | ||
|
|
467d42abea | ||
|
|
4de21dace7 | ||
|
|
f1171307cd | ||
|
|
a375d3b2f0 | ||
|
|
60ba7e644c | ||
|
|
d2ce5f4a05 | ||
|
|
8be0597a36 | ||
|
|
d0ca502a56 | ||
|
|
f57c2ce92c | ||
|
|
321ab5b486 | ||
|
|
5e85e1e3b8 | ||
|
|
8ca183d0c2 | ||
|
|
d5e75114ab | ||
|
|
6429b6ea5e | ||
|
|
501862b9ea | ||
|
|
6522174c83 | ||
|
|
eb7a6e1044 | ||
|
|
a1d043b3c0 | ||
|
|
d65da98624 | ||
|
|
9852f730a7 | ||
|
|
3b9012535f | ||
|
|
2914ed168c | ||
|
|
ee5f3d90eb | ||
|
|
bcc5a1abb9 | ||
|
|
3ba62e0c47 | ||
|
|
3ac971c0d9 | ||
|
|
5e2eaba07e | ||
|
|
56bd2badab | ||
|
|
e0dda1699c | ||
|
|
b48192d355 | ||
|
|
40436352bf | ||
|
|
83bc859b31 | ||
|
|
a9e3cbaa93 | ||
|
|
3022c54a43 | ||
|
|
98c3c96881 | ||
|
|
3e8c22422f | ||
|
|
fe730fc8bd | ||
|
|
c9df155ee4 | ||
|
|
9e4ac30423 | ||
|
|
826e942123 | ||
|
|
0347e106c3 | ||
|
|
7471f9fc42 | ||
|
|
14acc4f37b | ||
|
|
95582abb6e | ||
|
|
c0ed5ed81e | ||
|
|
a13593f16e | ||
|
|
f1eb619344 | ||
|
|
e47acc847d | ||
|
|
1582a2126f | ||
|
|
398f3879ae | ||
|
|
74b129e105 | ||
|
|
217cff620c | ||
|
|
749b187dc4 | ||
|
|
c9e36761e4 | ||
|
|
bf29f4b486 | ||
|
|
d55b9ce72d | ||
|
|
2e99491429 | ||
|
|
e4cb8146a1 | ||
|
|
df10a90117 | ||
|
|
45cb5e4bcf | ||
|
|
364d735a95 | ||
|
|
711fdd078a | ||
|
|
7be7c311e3 | ||
|
|
1bc91df048 | ||
|
|
dc0d61ce63 | ||
|
|
06b3f10220 | ||
|
|
6b24e6f150 | ||
|
|
ca07b8ce0b | ||
|
|
32703269a3 | ||
|
|
05f621d82d | ||
|
|
b0a8904b31 | ||
|
|
136f57fa73 | ||
|
|
9473c827fe | ||
|
|
64658013fe | ||
|
|
9b94eecae3 | ||
|
|
b6c2992752 | ||
|
|
4bacc306e9 | ||
|
|
00e1fc1e27 | ||
|
|
3a307b5b8e | ||
|
|
7fc4445ab7 | ||
|
|
b15a41094d | ||
|
|
7143908d4b | ||
|
|
466d5149db | ||
|
|
c3d175d8de | ||
|
|
1677f4414b | ||
|
|
bc7f9127b5 | ||
|
|
06617d640b | ||
|
|
d3c0e4d6cc | ||
|
|
72c3d662c1 | ||
|
|
242ca3e323 | ||
|
|
98c090d5b2 | ||
|
|
91b251b352 | ||
|
|
8aa07403e7 | ||
|
|
c0080c4bbe | ||
|
|
46b94ad6a8 | ||
|
|
37851fee0c | ||
|
|
f06908a20f | ||
|
|
74d83b5be1 | ||
|
|
bd7c1a226a | ||
|
|
302166f115 | ||
|
|
e3e8db3329 | ||
|
|
c9058e0892 | ||
|
|
40f042dc8e | ||
|
|
2ae16b9c9e | ||
|
|
901d46a3b9 | ||
|
|
d8612fae27 | ||
|
|
ad85b7e729 | ||
|
|
14b50729e7 | ||
|
|
b630efb818 | ||
|
|
4209468b4c | ||
|
|
85dfe08290 | ||
|
|
2d6d60a0fa | ||
|
|
1f388d761e | ||
|
|
c3ed24364f | ||
|
|
f44b31edd0 | ||
|
|
9a0c4af126 | ||
|
|
0cd2a0e195 | ||
|
|
eca3908ec1 | ||
|
|
3eb987680e | ||
|
|
81e8b300ef | ||
|
|
58ed81032c | ||
|
|
4f2dd86595 | ||
|
|
27ad269e8b | ||
|
|
4928a80035 | ||
|
|
f17267ab8b | ||
|
|
26c2f128f5 | ||
|
|
182bb12cbc | ||
|
|
5d9f960a20 | ||
|
|
4644d94331 | ||
|
|
3480861f41 | ||
|
|
f7e8b74745 | ||
|
|
2fa678cce2 | ||
|
|
53b838bd3f | ||
|
|
dc28e0ecda | ||
|
|
b047a2675d | ||
|
|
3ab8b88e56 | ||
|
|
1ea5d70eaa | ||
|
|
f0fcfbe304 | ||
|
|
36d464d0a3 | ||
|
|
556ad2faf2 | ||
|
|
e8443324d4 | ||
|
|
44c5b0ed8a | ||
|
|
671bcbae8b | ||
|
|
12ec03d61c | ||
|
|
b6926d4ba4 | ||
|
|
5ddcf07fed | ||
|
|
2d63a9aaa4 | ||
|
|
57d5a65c57 | ||
|
|
965adea59e | ||
|
|
6e53d7b723 | ||
|
|
ed8c33fca7 | ||
|
|
4f69881e1f | ||
|
|
6c08f545df | ||
|
|
3ac31c573b | ||
|
|
7d6256230a | ||
|
|
9514464d9a | ||
|
|
f51ba05ec5 | ||
|
|
ef893e0ebf | ||
|
|
802c384123 | ||
|
|
412987daf9 | ||
|
|
703f206248 | ||
|
|
d15c3480ab | ||
|
|
7d9fd3faa6 | ||
|
|
75f3504ae7 | ||
|
|
a1c27c632b | ||
|
|
dfdda39667 | ||
|
|
b59538ca6f | ||
|
|
15a7250ffe | ||
|
|
1a849643bd | ||
|
|
4a0d82ea3b | ||
|
|
13b8de3458 | ||
|
|
9013c6e84b | ||
|
|
ae73115c5a | ||
|
|
2b49ffb759 | ||
|
|
540b4beaed | ||
|
|
48ff0908e2 | ||
|
|
347c69b0a2 | ||
|
|
4f852f9c47 | ||
|
|
44c98dcd8b | ||
|
|
750e0691a6 | ||
|
|
0cfcada4f2 | ||
|
|
71d0780fcb | ||
|
|
8921042fdb | ||
|
|
904a6599b3 | ||
|
|
40cb759271 | ||
|
|
dcbac2ca59 | ||
|
|
ceac26bd18 | ||
|
|
030cbbb8fc | ||
|
|
24eeeab615 | ||
|
|
d1a1512a6d | ||
|
|
6eac1a87ca | ||
|
|
f3d1ff8d13 | ||
|
|
520cae4a6b | ||
|
|
6ff5664f4e | ||
|
|
8676ebc328 | ||
|
|
cf8b2bb0f6 | ||
|
|
60d4deb0e9 | ||
|
|
7aa06e58f2 | ||
|
|
d18972048c | ||
|
|
d17a017418 | ||
|
|
48e328baef | ||
|
|
0d557da40f | ||
|
|
d2d746734f | ||
|
|
05fb6a170a | ||
|
|
0b02cb3298 | ||
|
|
9d886e3c69 | ||
|
|
80d50b5cff | ||
|
|
1a319d842b | ||
|
|
8d1a3dca18 | ||
|
|
d741bb5119 | ||
|
|
048e87c5ed | ||
|
|
973e49b354 | ||
|
|
8c253ad6dc | ||
|
|
78eee638ae | ||
|
|
0d9278c0ac | ||
|
|
339efd6174 | ||
|
|
b6a216462d | ||
|
|
949dd90f10 | ||
|
|
f99dbc6344 | ||
|
|
b39c750e26 | ||
|
|
ee2a0425e2 | ||
|
|
9147acca0c | ||
|
|
95283099fe | ||
|
|
fb92f88ab1 | ||
|
|
db0f8a9186 | ||
|
|
a707b237cf | ||
|
|
e0ffe04a0d | ||
|
|
2148eb28cd | ||
|
|
00a313bd69 | ||
|
|
8e330bca27 | ||
|
|
6ab318d445 | ||
|
|
d7de5939d7 | ||
|
|
df6081b7b7 | ||
|
|
e92de3b38a | ||
|
|
405ab0fb2d | ||
|
|
9761138fb0 | ||
|
|
c270f79827 | ||
|
|
029406b448 | ||
|
|
08a4f64d9f | ||
|
|
04ae40341f | ||
|
|
213bdf9842 | ||
|
|
bf2a0b5e59 | ||
|
|
bdf1389d77 | ||
|
|
00f220264a | ||
|
|
b60ca588fe | ||
|
|
94f7551fa0 | ||
|
|
95a086f3e0 | ||
|
|
9b5ced0cc8 | ||
|
|
bc2db7222f | ||
|
|
52f85d7ae2 | ||
|
|
0a09c007af | ||
|
|
bda84cc8c8 | ||
|
|
dce02229f1 | ||
|
|
07cb9a57eb | ||
|
|
651ff77c85 | ||
|
|
a2bee86c1f | ||
|
|
fbbc9ce4ac | ||
|
|
697d21f8a4 | ||
|
|
c9efe0d73d | ||
|
|
781ff0931d | ||
|
|
25f9ea2f37 | ||
|
|
cff492ada8 | ||
|
|
f404dec7d7 | ||
|
|
284213e9b8 | ||
|
|
df88a4a050 | ||
|
|
f26d438ff0 | ||
|
|
f7872685ce | ||
|
|
23eaa15e86 | ||
|
|
6c0c072afe | ||
|
|
f8d85dcd5e | ||
|
|
bed3f5b9cc | ||
|
|
ee2818514f | ||
|
|
fac06c3beb | ||
|
|
6617cc3957 | ||
|
|
2c7b0cd1f7 | ||
|
|
809184f787 | ||
|
|
dcf5cc045a | ||
|
|
133fb377de | ||
|
|
6757cbdd0f | ||
|
|
7a0d269780 | ||
|
|
6f52a20b25 | ||
|
|
248a087c17 | ||
|
|
95817f6d17 | ||
|
|
0b3556f09c | ||
|
|
3d7b82c2cb | ||
|
|
4755e24407 | ||
|
|
ee7bb11790 | ||
|
|
6a1d2564e2 | ||
|
|
75cd4979a7 | ||
|
|
b642b7f04e | ||
|
|
13aa3ccc68 | ||
|
|
b82c292dcb | ||
|
|
081f793696 | ||
|
|
45d967b76f | ||
|
|
4203c07c29 | ||
|
|
519129c42b | ||
|
|
8cf11774da | ||
|
|
9e69f0666d | ||
|
|
cd7584b2ab | ||
|
|
0b303eb937 | ||
|
|
83e59706be | ||
|
|
1707bb95f6 | ||
|
|
877564f545 | ||
|
|
de35bbedb6 | ||
|
|
41a2d5802e | ||
|
|
140df97040 | ||
|
|
54b22c942d | ||
|
|
5ec3fb78d3 | ||
|
|
1f3e1c9aba | ||
|
|
7ae605a4e4 | ||
|
|
4735477918 | ||
|
|
3633c105b4 | ||
|
|
e120991ad3 | ||
|
|
8428da4f50 | ||
|
|
42ba2dcfaf | ||
|
|
feaa1e88c4 | ||
|
|
93f1768174 | ||
|
|
406d3e47d3 | ||
|
|
910eab1f79 | ||
|
|
d72c96b166 | ||
|
|
f7d11e5cf0 | ||
|
|
23e07c3a5f | ||
|
|
8a6bc5bfc0 | ||
|
|
94be126d25 | ||
|
|
27ffdb08bd | ||
|
|
8bf4fb0115 | ||
|
|
e94d8e00f7 | ||
|
|
bc6d4e8857 | ||
|
|
c4c8fa69d3 | ||
|
|
ad581be494 | ||
|
|
946ad61f7f | ||
|
|
a1af4a85ff | ||
|
|
7da0ccde83 | ||
|
|
9401e8aa78 | ||
|
|
d8f92b930a | ||
|
|
587c24deb5 | ||
|
|
ba96e0cbc2 | ||
|
|
8137f6dba9 | ||
|
|
37bc1a0e70 | ||
|
|
c90ce5ce47 | ||
|
|
668d46bd91 | ||
|
|
7a3f5961cc | ||
|
|
63bd3e3de8 | ||
|
|
49b82f7c16 | ||
|
|
46676fd99b | ||
|
|
e41c9423a2 | ||
|
|
435d3798fd | ||
|
|
c1f23830a2 | ||
|
|
f3619e1c30 | ||
|
|
0f05676b7a | ||
|
|
2775a4965b | ||
|
|
3c05cfea0a | ||
|
|
04ce02c042 | ||
|
|
d6228c3074 | ||
|
|
f6c078aade | ||
|
|
2851e5d304 | ||
|
|
c895fe117f | ||
|
|
4de4b346aa | ||
|
|
99a914633d | ||
|
|
f0f3c4d1b8 | ||
|
|
25fd24b7c2 | ||
|
|
adb848bf9f | ||
|
|
94c2ef3ab0 | ||
|
|
9c69f1ea88 | ||
|
|
b808f610c6 | ||
|
|
b1414a1753 | ||
|
|
20d504bd28 | ||
|
|
5cb83a4232 | ||
|
|
182fea6002 | ||
|
|
621e0e65bc | ||
|
|
03f7d20e1a | ||
|
|
f501e3baf7 | ||
|
|
5a99c2e70c | ||
|
|
b20a3cf719 | ||
|
|
43aafc743e | ||
|
|
f69d9128d5 | ||
|
|
49d90871fa | ||
|
|
84969c74bd | ||
|
|
e670f96d26 | ||
|
|
42d31a9ce4 | ||
|
|
98562bf962 | ||
|
|
ef4b640867 | ||
|
|
2f3ba3cebe | ||
|
|
f71346d235 | ||
|
|
12c315bb52 | ||
|
|
24920c9113 | ||
|
|
d57f3cd39c | ||
|
|
7a9ea0ca5a | ||
|
|
cf53a54324 | ||
|
|
162d4d0be8 | ||
|
|
c19f955fef | ||
|
|
844e3205ac | ||
|
|
563c2cd276 | ||
|
|
818dbef261 | ||
|
|
09afee8ae3 | ||
|
|
9b20fc9c91 | ||
|
|
a07788fffe | ||
|
|
d2b4904263 | ||
|
|
c8dd584990 | ||
|
|
21efc385da | ||
|
|
6f56e42971 | ||
|
|
a319b36f2d | ||
|
|
33fc9adca9 | ||
|
|
edb47e6973 | ||
|
|
f4953497a9 | ||
|
|
3a224c6b03 | ||
|
|
d1b3299921 | ||
|
|
1802f30d8b | ||
|
|
d2094f3e6a | ||
|
|
0b9b873dfa | ||
|
|
713b6cd430 | ||
|
|
4d0ed3a635 | ||
|
|
991a2d133a | ||
|
|
22df943860 | ||
|
|
dc07dafa1e | ||
|
|
2cfb6f0d93 | ||
|
|
544a765137 | ||
|
|
81934654ed | ||
|
|
c0e8b5e7e1 | ||
|
|
847dba8212 | ||
|
|
0a06d5ff29 | ||
|
|
50f51db8b2 | ||
|
|
a77a097baf | ||
|
|
0f63a3c59a | ||
|
|
fb348d26c8 | ||
|
|
efa6cb4b4a | ||
|
|
97ac2a2982 | ||
|
|
70a69fadad | ||
|
|
5f30e27485 | ||
|
|
90f5181a88 | ||
|
|
f052960e2f | ||
|
|
2aab5ae9a3 | ||
|
|
529d70b14a | ||
|
|
522a9c85b6 | ||
|
|
da71e0e921 | ||
|
|
72cc04e20f | ||
|
|
88ddf66e6e | ||
|
|
1e6c09c66e | ||
|
|
d80dd66588 | ||
|
|
09df1af88e | ||
|
|
c5a54558fa | ||
|
|
a325640d5d | ||
|
|
05ab5ba0cf | ||
|
|
b12e7a8c49 | ||
|
|
3465f8d390 | ||
|
|
93c755ffe4 | ||
|
|
8b7accd19d | ||
|
|
525c372fc5 | ||
|
|
1ce0a19abb | ||
|
|
d5aad57ad9 | ||
|
|
77e4ab4710 | ||
|
|
1df8bb3808 | ||
|
|
333e2f6459 | ||
|
|
fe51496ab0 | ||
|
|
307e488d1a | ||
|
|
4cb718f706 | ||
|
|
6263075ecd | ||
|
|
f5cf4b3ab6 | ||
|
|
f6b08a0303 | ||
|
|
e34acf2fbb | ||
|
|
ec80683aa1 | ||
|
|
57774fade0 | ||
|
|
3873894a22 | ||
|
|
13a9300ab4 | ||
|
|
98bd9a9c12 | ||
|
|
b7b3993a8d | ||
|
|
1553959cf4 | ||
|
|
862f4d19be | ||
|
|
b137bc6d92 | ||
|
|
4fa6ddcd7a | ||
|
|
6388173f19 | ||
|
|
e918cd44a8 | ||
|
|
d78a66772a | ||
|
|
eeb5486098 | ||
|
|
9043d93fbd | ||
|
|
efc1320923 | ||
|
|
5544c96bc5 | ||
|
|
846bd3e696 | ||
|
|
190301d0f5 | ||
|
|
635cbf952e | ||
|
|
9eac507b08 | ||
|
|
715e17099d | ||
|
|
b25a479c37 | ||
|
|
a34f084615 |
No files matched your search
@@ -26,7 +26,7 @@ jobs:
|
||||
- name: Set up Gradle
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
- name: Run verification gates
|
||||
run: ./gradlew :core:check :adapters:bukkit:plugin:test :adapters:bukkit:nms:v26_2_R1:test :spi:build :probe:test :probe:run :probe:deserializationProbe -PuseLocalVolmLib=false --console=plain --stacktrace
|
||||
run: ./gradlew :core:check :adapters:bukkit:plugin:test :adapters:bukkit:nms:v26_2_R1:test :spi:build :probe:test :probe:run -PuseLocalVolmLib=false --console=plain --stacktrace
|
||||
- name: Run modded shared tests (Fabric)
|
||||
run: ./gradlew -p adapters/fabric test -PuseLocalVolmLib=false --console=plain --stacktrace
|
||||
- name: Run modded shared tests (Forge)
|
||||
|
||||
@@ -29,6 +29,10 @@ Canonical English is defined in the typed Java catalogs under `core/src/main/jav
|
||||
|
||||
Java 25 is required on every platform.
|
||||
|
||||
Built-in feature implementations and their pack settings live in the [`module`](module/README.md) folder. During the extraction stage they retain their
|
||||
engine dependencies and compile together with the host; the existing platform artifacts still
|
||||
bundle them. Core owns lifecycle, loading, scheduling, storage and platform integration.
|
||||
|
||||
The modded feature set matches the plugin wherever the operation is not Bukkit-bound: worldgen
|
||||
from Iris packs, authoring with mod blocks/items/entities (with validation suggestions), studio
|
||||
workspaces with schema autocomplete over the server's live registries, entity spawning parity
|
||||
|
||||
+10
-34
@@ -1,17 +1,16 @@
|
||||
package art.arcane.iris.core.nms.v26_2_R1;
|
||||
|
||||
import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom;
|
||||
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
|
||||
import com.mojang.datafixers.util.Pair;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.engine.data.cache.AtomicCache;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.GenerationSessionException;
|
||||
import art.arcane.iris.engine.framework.GenerationSessionLease;
|
||||
import art.arcane.iris.engine.object.IrisBiome;
|
||||
import art.arcane.iris.engine.object.IrisBiomeCustom;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisDimensionCarvingResolver;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.util.project.context.IrisContext;
|
||||
import art.arcane.volmlib.util.collection.KMap;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
@@ -49,6 +48,7 @@ import java.util.stream.Stream;
|
||||
|
||||
public class CustomBiomeSource extends BiomeSource {
|
||||
private static final int NOISE_BIOME_CACHE_MAX = 262144;
|
||||
private static final int NOISE_BIOME_CACHE_CHECK_Y_MASK = 63;
|
||||
private static final int STRONGHOLD_RING_SEARCH_Y = 0;
|
||||
private static final int STRONGHOLD_RING_SEARCH_RADIUS = 112;
|
||||
private static final int STRONGHOLD_RING_SEARCH_QUART_STEP = 4;
|
||||
@@ -440,16 +440,6 @@ public class CustomBiomeSource extends BiomeSource {
|
||||
int y,
|
||||
int z,
|
||||
Climate.Sampler sampler
|
||||
) {
|
||||
return getVisibleNoiseBiomeWithActiveGenerationLease(x, y, z, sampler, null);
|
||||
}
|
||||
|
||||
Holder<Biome> getVisibleNoiseBiomeWithActiveGenerationLease(
|
||||
int x,
|
||||
int y,
|
||||
int z,
|
||||
Climate.Sampler sampler,
|
||||
IrisDimensionCarvingResolver.State resolverState
|
||||
) {
|
||||
long cacheKey = packNoiseKey(x, y, z);
|
||||
Holder<Biome> cachedHolder = noiseBiomeCache.get(cacheKey);
|
||||
@@ -457,13 +447,13 @@ public class CustomBiomeSource extends BiomeSource {
|
||||
return cachedHolder;
|
||||
}
|
||||
|
||||
Holder<Biome> resolvedHolder = resolveVisibleBiomeHolder(x, y, z, resolverState);
|
||||
Holder<Biome> resolvedHolder = resolveVisibleBiomeHolder(x, y, z);
|
||||
Holder<Biome> existingHolder = noiseBiomeCache.putIfAbsent(cacheKey, resolvedHolder);
|
||||
if (existingHolder != null) {
|
||||
return existingHolder;
|
||||
}
|
||||
|
||||
if (noiseBiomeCache.size() > NOISE_BIOME_CACHE_MAX) {
|
||||
if ((y & NOISE_BIOME_CACHE_CHECK_Y_MASK) == 0 && noiseBiomeCache.size() > NOISE_BIOME_CACHE_MAX) {
|
||||
noiseBiomeCache.clear();
|
||||
}
|
||||
|
||||
@@ -530,13 +520,8 @@ public class CustomBiomeSource extends BiomeSource {
|
||||
return holder;
|
||||
}
|
||||
|
||||
private Holder<Biome> resolveVisibleBiomeHolder(
|
||||
int x,
|
||||
int y,
|
||||
int z,
|
||||
IrisDimensionCarvingResolver.State resolverState
|
||||
) {
|
||||
BiomeResolution resolution = resolveBiomeResolution(x, y, z, resolverState);
|
||||
private Holder<Biome> resolveVisibleBiomeHolder(int x, int y, int z) {
|
||||
BiomeResolution resolution = resolveBiomeResolution(x, y, z);
|
||||
if (resolution == null) {
|
||||
return getFallbackBiome();
|
||||
}
|
||||
@@ -569,15 +554,6 @@ public class CustomBiomeSource extends BiomeSource {
|
||||
}
|
||||
|
||||
private BiomeResolution resolveBiomeResolution(int x, int y, int z) {
|
||||
return resolveBiomeResolution(x, y, z, null);
|
||||
}
|
||||
|
||||
private BiomeResolution resolveBiomeResolution(
|
||||
int x,
|
||||
int y,
|
||||
int z,
|
||||
IrisDimensionCarvingResolver.State resolverState
|
||||
) {
|
||||
if (engine == null || engine.isClosed()) {
|
||||
return null;
|
||||
}
|
||||
@@ -599,7 +575,7 @@ public class CustomBiomeSource extends BiomeSource {
|
||||
int surfaceInternalY = engine.getComplex().getHeightStream().get(blockX, blockZ).intValue();
|
||||
underground = internalY <= surfaceInternalY - 8;
|
||||
irisBiome = underground
|
||||
? engine.getCaveBiome(blockX, internalY, blockZ, resolverState)
|
||||
? engine.getCaveBiome(blockX, internalY, blockZ)
|
||||
: engine.getComplex().getTrueBiomeStream().get(blockX, blockZ);
|
||||
} else {
|
||||
irisBiome = engine.getComplex().getTrueBiomeStream().get(blockX, blockZ);
|
||||
|
||||
+16
-16
@@ -1,8 +1,8 @@
|
||||
package art.arcane.iris.core.nms.v26_2_R1;
|
||||
|
||||
import art.arcane.iris.core.datapack.DatapackStructureScopeIndex;
|
||||
import art.arcane.iris.engine.framework.NativeStructureFrequencies;
|
||||
import art.arcane.iris.engine.framework.NativeStructureFrequencyScale;
|
||||
import art.arcane.iris.engine.object.IrisImportedStructureControl;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderOwner;
|
||||
import net.minecraft.core.Vec3i;
|
||||
@@ -32,20 +32,20 @@ final class DatapackStructureStateFilter {
|
||||
DatapackStructureScopeIndex scopeIndex,
|
||||
Set<String> declaredSources
|
||||
) {
|
||||
return filter(structureSets, scopeIndex, declaredSources, new IrisImportedStructureControl());
|
||||
return filter(structureSets, scopeIndex, declaredSources, NativeStructureFrequencies.NONE);
|
||||
}
|
||||
|
||||
static Selection filter(
|
||||
List<Holder<StructureSet>> structureSets,
|
||||
DatapackStructureScopeIndex scopeIndex,
|
||||
Set<String> declaredSources,
|
||||
IrisImportedStructureControl importedStructures
|
||||
NativeStructureFrequencies frequencies
|
||||
) {
|
||||
return filter(
|
||||
structureSets,
|
||||
scopeIndex,
|
||||
declaredSources,
|
||||
importedStructures,
|
||||
frequencies,
|
||||
keyIndex(structureSets));
|
||||
}
|
||||
|
||||
@@ -53,12 +53,12 @@ final class DatapackStructureStateFilter {
|
||||
List<Holder<StructureSet>> structureSets,
|
||||
DatapackStructureScopeIndex scopeIndex,
|
||||
Set<String> declaredSources,
|
||||
IrisImportedStructureControl importedStructures,
|
||||
NativeStructureFrequencies frequencies,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
if (scopeIndex.isEmpty()) {
|
||||
return new Selection(
|
||||
scaleFrequencyOverrides(structureSets, importedStructures, keyIndex),
|
||||
scaleFrequencyOverrides(structureSets, frequencies, keyIndex),
|
||||
0,
|
||||
0);
|
||||
}
|
||||
@@ -98,7 +98,7 @@ final class DatapackStructureStateFilter {
|
||||
}
|
||||
return new Selection(
|
||||
scaleFrequencyOverrides(
|
||||
List.copyOf(filteredSets), importedStructures, keyIndex),
|
||||
List.copyOf(filteredSets), frequencies, keyIndex),
|
||||
retainedManagedSets,
|
||||
excludedManagedSets);
|
||||
}
|
||||
@@ -244,10 +244,10 @@ final class DatapackStructureStateFilter {
|
||||
|
||||
private static List<Holder<StructureSet>> scaleFrequencyOverrides(
|
||||
List<Holder<StructureSet>> structureSets,
|
||||
IrisImportedStructureControl importedStructures,
|
||||
NativeStructureFrequencies frequencies,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
if (!importedStructures.hasFrequencyOverrides()) {
|
||||
if (!frequencies.hasOverrides()) {
|
||||
return structureSets;
|
||||
}
|
||||
Map<String, Holder<StructureSet>> holdersByKey = new HashMap<>();
|
||||
@@ -263,7 +263,7 @@ final class DatapackStructureStateFilter {
|
||||
for (Holder<StructureSet> holder : structureSets) {
|
||||
Holder<StructureSet> scaled = scaleFrequencyHolder(
|
||||
holder,
|
||||
importedStructures,
|
||||
frequencies,
|
||||
holdersByKey,
|
||||
scaledByIdentity,
|
||||
keyIndex);
|
||||
@@ -275,7 +275,7 @@ final class DatapackStructureStateFilter {
|
||||
|
||||
private static Holder<StructureSet> scaleFrequencyHolder(
|
||||
Holder<StructureSet> holder,
|
||||
IrisImportedStructureControl importedStructures,
|
||||
NativeStructureFrequencies frequencies,
|
||||
Map<String, Holder<StructureSet>> holdersByKey,
|
||||
Map<Holder<StructureSet>, Holder<StructureSet>> scaledByIdentity,
|
||||
StructureSetKeyIndex keyIndex
|
||||
@@ -284,7 +284,7 @@ final class DatapackStructureStateFilter {
|
||||
return scaledByIdentity.get(holder);
|
||||
}
|
||||
if (!dependsOnFrequencyOverride(
|
||||
holder, importedStructures, holdersByKey, keyIndex)) {
|
||||
holder, frequencies, holdersByKey, keyIndex)) {
|
||||
scaledByIdentity.put(holder, holder);
|
||||
return holder;
|
||||
}
|
||||
@@ -304,7 +304,7 @@ final class DatapackStructureStateFilter {
|
||||
originalZone.get().otherSet(), holdersByKey, keyIndex);
|
||||
Holder<StructureSet> scaledTarget = scaleFrequencyHolder(
|
||||
target,
|
||||
importedStructures,
|
||||
frequencies,
|
||||
holdersByKey,
|
||||
scaledByIdentity,
|
||||
keyIndex);
|
||||
@@ -314,7 +314,7 @@ final class DatapackStructureStateFilter {
|
||||
}
|
||||
}
|
||||
|
||||
double multiplier = importedStructures.frequencyMultiplier(
|
||||
double multiplier = frequencies.multiplier(
|
||||
structureSetKey(holder, keyIndex));
|
||||
StructurePlacement scaledPlacement = multiplier == 1D && scaledZone.equals(originalZone)
|
||||
? originalPlacement
|
||||
@@ -325,14 +325,14 @@ final class DatapackStructureStateFilter {
|
||||
|
||||
private static boolean dependsOnFrequencyOverride(
|
||||
Holder<StructureSet> holder,
|
||||
IrisImportedStructureControl importedStructures,
|
||||
NativeStructureFrequencies frequencies,
|
||||
Map<String, Holder<StructureSet>> holdersByKey,
|
||||
StructureSetKeyIndex keyIndex
|
||||
) {
|
||||
Set<Holder<StructureSet>> visited = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
Holder<StructureSet> current = holder;
|
||||
while (visited.add(current)) {
|
||||
if (importedStructures.frequencyMultiplier(
|
||||
if (frequencies.multiplier(
|
||||
structureSetKey(current, keyIndex)) != 1D) {
|
||||
return true;
|
||||
}
|
||||
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package art.arcane.iris.core.nms.v26_2_R1;
|
||||
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.world.level.LevelReader;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/** Asks the server's own rules whether a plant survives on a ground block, in a tiny level holding just the two. */
|
||||
final class GroundSurvival {
|
||||
private static final BlockPos PLANT_POS = new BlockPos(0, 64, 0);
|
||||
private static final BlockPos GROUND_POS = PLANT_POS.below();
|
||||
private static final int MIN_BUILD_Y = -64;
|
||||
private static final int BUILD_HEIGHT = 384;
|
||||
// Crops need 8 or more and mushrooms less than 13. A chunk that is still generating has no light to ask for.
|
||||
private static final int LIGHT_EVERY_PLANT_ACCEPTS = 10;
|
||||
|
||||
private final Map<BlockState, Boolean> restsOnGround = new ConcurrentHashMap<>();
|
||||
|
||||
boolean canSurviveOn(BlockState plant, BlockState ground) {
|
||||
try {
|
||||
return survives(plant, ground) || !restsOnGround(plant);
|
||||
} catch (RuntimeException e) {
|
||||
IrisLogging.reportError(e);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
void forgetRules() {
|
||||
restsOnGround.clear();
|
||||
}
|
||||
|
||||
// Wall and ceiling blocks fail on every ground, which says nothing about the ground they were decorated onto.
|
||||
private boolean restsOnGround(BlockState plant) {
|
||||
return restsOnGround.computeIfAbsent(plant, this::survivesOnSomeGround);
|
||||
}
|
||||
|
||||
private boolean survivesOnSomeGround(BlockState plant) {
|
||||
for (Block block : BuiltInRegistries.BLOCK) {
|
||||
if (survives(plant, block.defaultBlockState())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean survives(BlockState plant, BlockState ground) {
|
||||
return plant.canSurvive(levelAround(plant, ground), PLANT_POS);
|
||||
}
|
||||
|
||||
// A proxy, since LevelReader gains abstract methods with every release and Paper's chunk system adds its own.
|
||||
private LevelReader levelAround(BlockState plant, BlockState ground) {
|
||||
InvocationHandler answers = (proxy, method, args) -> answer(proxy, method, args, plant, ground);
|
||||
return (LevelReader) Proxy.newProxyInstance(LevelReader.class.getClassLoader(), new Class<?>[]{LevelReader.class}, answers);
|
||||
}
|
||||
|
||||
private Object answer(Object proxy, Method method, Object[] args, BlockState plant, BlockState ground) throws Throwable {
|
||||
switch (method.getName()) {
|
||||
case "getBlockState", "getBlockStateIfLoaded" -> {
|
||||
return stateAt((BlockPos) args[0], plant, ground);
|
||||
}
|
||||
case "getFluidState", "getFluidIfLoaded" -> {
|
||||
return stateAt((BlockPos) args[0], plant, ground).getFluidState();
|
||||
}
|
||||
case "getRawBrightness", "getMaxLocalRawBrightness", "getBrightness" -> {
|
||||
return LIGHT_EVERY_PLANT_ACCEPTS;
|
||||
}
|
||||
case "getBlockEntity" -> {
|
||||
return null;
|
||||
}
|
||||
case "getMinY" -> {
|
||||
return MIN_BUILD_Y;
|
||||
}
|
||||
case "getHeight" -> {
|
||||
if (args == null) {
|
||||
return BUILD_HEIGHT;
|
||||
}
|
||||
}
|
||||
case "isClientSide" -> {
|
||||
return false;
|
||||
}
|
||||
case "hashCode" -> {
|
||||
return System.identityHashCode(proxy);
|
||||
}
|
||||
case "equals" -> {
|
||||
return proxy == args[0];
|
||||
}
|
||||
case "toString" -> {
|
||||
return "ground survival level";
|
||||
}
|
||||
default -> {
|
||||
}
|
||||
}
|
||||
|
||||
if (method.isDefault()) {
|
||||
return InvocationHandler.invokeDefault(proxy, method, args);
|
||||
}
|
||||
throw new IllegalStateException("Ground survival level can't answer " + method.getName());
|
||||
}
|
||||
|
||||
// Water beside the ground for sugar cane and air beside the plant for cactus, so only the ground can refuse.
|
||||
private BlockState stateAt(BlockPos pos, BlockState plant, BlockState ground) {
|
||||
if (pos.equals(PLANT_POS)) {
|
||||
return plant;
|
||||
}
|
||||
if (pos.equals(GROUND_POS)) {
|
||||
return ground;
|
||||
}
|
||||
return pos.getY() == GROUND_POS.getY() ? Blocks.WATER.defaultBlockState() : Blocks.AIR.defaultBlockState();
|
||||
}
|
||||
}
|
||||
+26
-22
@@ -1,12 +1,10 @@
|
||||
package art.arcane.iris.core.nms.v26_2_R1;
|
||||
|
||||
import art.arcane.iris.engine.object.world.biome.custom.IrisBiomeCustom;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.NativeFeatureGenerationPolicy;
|
||||
import art.arcane.iris.engine.object.IrisBiome;
|
||||
import art.arcane.iris.engine.object.IrisBiomeCustom;
|
||||
import art.arcane.iris.engine.object.IrisDecorationStep;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisImportedFeatureControl;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import it.unimi.dsi.fastutil.ints.IntArraySet;
|
||||
import it.unimi.dsi.fastutil.ints.IntSet;
|
||||
@@ -32,6 +30,7 @@ import net.minecraft.world.level.levelgen.placement.PlacedFeature;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.BitSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
@@ -112,22 +111,22 @@ final class ImportedFeatureStage {
|
||||
}
|
||||
|
||||
private void build(WorldGenLevel level, IrisDimension dimension) {
|
||||
IrisImportedFeatureControl control;
|
||||
boolean enabled;
|
||||
try {
|
||||
control = NativeFeatureGenerationPolicy.control(engine);
|
||||
enabled = NativeFeatureGenerationPolicy.isEnabled(engine);
|
||||
} catch (RuntimeException error) {
|
||||
IrisLogging.error("Iris could not read importedFeatures for this dimension; features off: "
|
||||
+ error);
|
||||
markInert(dimension);
|
||||
return;
|
||||
}
|
||||
if (!control.shouldGenerateFeatures()) {
|
||||
if (!enabled) {
|
||||
markInert(dimension);
|
||||
return;
|
||||
}
|
||||
FeatureTable built;
|
||||
try {
|
||||
built = buildTable(level, control, dimension);
|
||||
built = buildTable(level, dimension);
|
||||
} catch (Throwable error) {
|
||||
IrisLogging.error("Iris importedFeatures is off for " + dimensionKey()
|
||||
+ ": feature table construction failed: " + error);
|
||||
@@ -150,8 +149,7 @@ final class ImportedFeatureStage {
|
||||
inertDimension = dimension;
|
||||
}
|
||||
|
||||
private FeatureTable buildTable(WorldGenLevel level, IrisImportedFeatureControl control,
|
||||
IrisDimension dimension) {
|
||||
private FeatureTable buildTable(WorldGenLevel level, IrisDimension dimension) {
|
||||
Registry<Biome> registry = level.registryAccess().lookupOrThrow(Registries.BIOME);
|
||||
Set<String> visibleKeys = visibleBiomeKeys();
|
||||
// Registry-ordered walk, never a hash-ordered set: FeatureSorter's cycle detection walks this list and
|
||||
@@ -185,9 +183,17 @@ final class ImportedFeatureStage {
|
||||
+ ". Remove or reorder the conflicting content, or leave importedFeatures.enabled false.");
|
||||
return null;
|
||||
}
|
||||
boolean filtered = control.getDisabled() != null && !control.getDisabled().isEmpty();
|
||||
return new FeatureTable(dimension, control, List.copyOf(biomes), Set.copyOf(biomes),
|
||||
Map.copyOf(byKey), steps, Map.copyOf(derivatives), filtered);
|
||||
return new FeatureTable(dimension, List.copyOf(biomes), Set.copyOf(biomes),
|
||||
Map.copyOf(byKey), steps, Map.copyOf(derivatives), generatedSteps(steps.size()));
|
||||
}
|
||||
|
||||
/** The decoration steps whose features generate, by the platform's step index. */
|
||||
private BitSet generatedSteps(int stepCount) {
|
||||
BitSet generated = new BitSet(stepCount);
|
||||
for (int stepIndex = 0; stepIndex < stepCount; stepIndex++) {
|
||||
generated.set(stepIndex, NativeFeatureGenerationPolicy.shouldGenerateStep(engine, stepIndex));
|
||||
}
|
||||
return generated;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -290,7 +296,7 @@ final class ImportedFeatureStage {
|
||||
|
||||
try {
|
||||
for (int stepIndex = 0; stepIndex < steps.size(); stepIndex++) {
|
||||
if (!table.control().shouldGenerateStep(IrisDecorationStep.byOrdinal(stepIndex))) {
|
||||
if (!table.generatedSteps().get(stepIndex)) {
|
||||
continue;
|
||||
}
|
||||
placeStep(level, table, steps.get(stepIndex), featureRegistry, chunkBiomes, owner,
|
||||
@@ -327,11 +333,9 @@ final class ImportedFeatureStage {
|
||||
Arrays.sort(featureIndices);
|
||||
for (int globalIndex : featureIndices) {
|
||||
PlacedFeature feature = stepData.features().get(globalIndex);
|
||||
if (table.filtered()) {
|
||||
Identifier featureId = featureRegistry.getKey(feature);
|
||||
if (featureId != null && !table.control().shouldGenerate(featureId.toString())) {
|
||||
continue;
|
||||
}
|
||||
Identifier featureId = featureRegistry.getKey(feature);
|
||||
if (featureId != null && !NativeFeatureGenerationPolicy.shouldGenerate(engine, featureId.toString())) {
|
||||
continue;
|
||||
}
|
||||
random.setFeatureSeed(decorationSeed, globalIndex, stepIndex);
|
||||
level.setCurrentlyGenerating(() -> describeFeature(featureRegistry, feature));
|
||||
@@ -390,10 +394,10 @@ final class ImportedFeatureStage {
|
||||
return identifier == null ? null : identifier.toString().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
private record FeatureTable(IrisDimension dimension, IrisImportedFeatureControl control,
|
||||
private record FeatureTable(IrisDimension dimension,
|
||||
List<Holder<Biome>> biomes, Set<Holder<Biome>> biomeSet,
|
||||
Map<String, Holder<Biome>> byKey,
|
||||
List<FeatureSorter.StepFeatureData> steps,
|
||||
Map<String, Holder<Biome>> derivatives, boolean filtered) {
|
||||
Map<String, Holder<Biome>> derivatives, BitSet generatedSteps) {
|
||||
}
|
||||
}
|
||||
+66
-98
@@ -3,38 +3,33 @@ package art.arcane.iris.core.nms.v26_2_R1;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.GenerationSessionException;
|
||||
import art.arcane.iris.engine.framework.GenerationSessionLease;
|
||||
import art.arcane.iris.engine.framework.IrisStructureLocator;
|
||||
import art.arcane.iris.core.modules.ModuleServices;
|
||||
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
|
||||
import art.arcane.iris.engine.framework.NativeStructureStartPlan;
|
||||
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
|
||||
import art.arcane.iris.engine.framework.NativeStructureLayouts;
|
||||
import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting;
|
||||
import art.arcane.iris.engine.IrisEngine;
|
||||
import art.arcane.iris.engine.mantle.DeferredPlacementRecords;
|
||||
import art.arcane.iris.engine.platform.BukkitChunkGenerator;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisDimensionCarvingResolver;
|
||||
import art.arcane.iris.engine.object.IrisMaterialPalette;
|
||||
import art.arcane.iris.engine.object.IrisNativeStructureDecision;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.nativegen.NativeStructureFitBridge;
|
||||
import art.arcane.iris.nativegen.NativeStructureGenerationException;
|
||||
import art.arcane.iris.nativegen.NativeStructureStartInjector;
|
||||
import art.arcane.iris.nativegen.NativeStructureReferenceEnvelope;
|
||||
import art.arcane.iris.nativegen.NativeStructureLocateResults;
|
||||
import art.arcane.iris.nativegen.NativeStructureLocatePersistence;
|
||||
import art.arcane.iris.nativegen.NativeStructureOwnershipRecovery;
|
||||
import art.arcane.iris.nativegen.NativeStructurePostProcessor;
|
||||
import art.arcane.iris.nativegen.NativeStructureReferenceRepair;
|
||||
import art.arcane.iris.nativegen.NativeStructureSurfaceFitter;
|
||||
import art.arcane.iris.nativegen.NativeStructureTerrainIntegrator;
|
||||
import art.arcane.iris.nativegen.NativeStructureVegetationClearer;
|
||||
import art.arcane.iris.nativegen.NativeStructureVerticalPlacer;
|
||||
import art.arcane.iris.nativegen.NativeStructureVanillaLocator;
|
||||
import art.arcane.iris.nativegen.NativeStructureVolumeIndex;
|
||||
import art.arcane.iris.nativegen.WorldgenTerrainHeightmaps;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.iris.util.common.data.IrisCustomData;
|
||||
import art.arcane.iris.util.common.reflect.WrappedField;
|
||||
import art.arcane.iris.util.common.reflect.WrappedReturningMethod;
|
||||
import art.arcane.iris.util.project.context.IrisContext;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import com.mojang.datafixers.util.Pair;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
import net.minecraft.core.BlockPos;
|
||||
@@ -87,9 +82,7 @@ import net.minecraft.world.level.levelgen.structure.StructureStart;
|
||||
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.craftbukkit.CraftWorld;
|
||||
import org.bukkit.craftbukkit.block.data.CraftBlockData;
|
||||
import org.bukkit.craftbukkit.generator.CustomChunkGenerator;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import org.spigotmc.SpigotWorldConfig;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
@@ -179,7 +172,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
if (platformGenerator != null && !platformGenerator.shouldGenerateStructures()) {
|
||||
return null;
|
||||
}
|
||||
if (level != runtimeLevel || level.getChunkSource().getGenerator() != this) {
|
||||
if (level != runtimeLevel || !isActiveGeneratorOf(level)) {
|
||||
return null;
|
||||
}
|
||||
try (GenerationSessionLease lease = requireGenerationLease("bukkit_nms_structure_locate");
|
||||
@@ -216,7 +209,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
throw new IllegalStateException("Native structure locate received an unregistered structure holder");
|
||||
}
|
||||
String structureId = id.toString();
|
||||
if (!IrisStructureLocator.hasNativePlacement(engine, structureId)) {
|
||||
if (!ModuleServices.startsStructure(engine, structureId)) {
|
||||
continue;
|
||||
}
|
||||
NativeStructureLocatePersistence.Probe probe = NativeStructureLocatePersistence.probe(
|
||||
@@ -228,19 +221,19 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
searches.sort(Comparator.comparing(IrisNativeLocateSearch::structureId));
|
||||
for (int attempt = 0; attempt < NativeStructureLocatePersistence.MAX_SELECTED_CANDIDATE_RETRIES; attempt++) {
|
||||
IrisNativeLocateSearch bestSearch = null;
|
||||
IrisStructureLocator.LocateResult bestResult = null;
|
||||
ModuleServices.StructureSearch bestResult = null;
|
||||
long bestDistance = Long.MAX_VALUE;
|
||||
for (IrisNativeLocateSearch search : searches) {
|
||||
IrisStructureLocator.LocateResult result = search.search().predict();
|
||||
if (result.status() == IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED) {
|
||||
ModuleServices.StructureSearch result = search.search().predict();
|
||||
if (result.outcome() == ModuleServices.StructureSearch.Outcome.SEARCH_LIMIT_REACHED) {
|
||||
throw new IllegalStateException("Iris structure locate reached its safety limit for "
|
||||
+ search.structureId() + " within " + radius + " placement rings");
|
||||
}
|
||||
if (!result.found()) {
|
||||
continue;
|
||||
}
|
||||
long dx = (long) result.originX() - pos.getX();
|
||||
long dz = (long) result.originZ() - pos.getZ();
|
||||
long dx = (long) result.x() - pos.getX();
|
||||
long dz = (long) result.z() - pos.getZ();
|
||||
long distance = dx * dx + dz * dz;
|
||||
if (distance < bestDistance) {
|
||||
bestDistance = distance;
|
||||
@@ -253,7 +246,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
pos, null, () -> { }, nativeLocated, nativeReference);
|
||||
}
|
||||
Pair<BlockPos, Holder<Structure>> predicted = Pair.of(
|
||||
new BlockPos(bestResult.originX(), bestResult.baseY(), bestResult.originZ()),
|
||||
new BlockPos(bestResult.x(), bestResult.y(), bestResult.z()),
|
||||
bestSearch.holder());
|
||||
if (NativeStructureLocateResults.nearest(pos, predicted, nativeLocated) != predicted) {
|
||||
return NativeStructureLocateResults.selectAndReference(
|
||||
@@ -266,8 +259,8 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
continue;
|
||||
}
|
||||
BlockPos located = new BlockPos(
|
||||
bestResult.originX(), verified.ownership().locatorY(),
|
||||
bestResult.originZ());
|
||||
bestResult.x(), verified.ownership().locatorY(),
|
||||
bestResult.z());
|
||||
Pair<BlockPos, Holder<Structure>> irisLocated = Pair.of(located, bestSearch.holder());
|
||||
IrisNativeLocateSearch selectedSearch = bestSearch;
|
||||
NativeStructureLocatePersistence.VerifiedStart selectedStart = verified;
|
||||
@@ -288,9 +281,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
throw new IllegalStateException("Native structure filtering received an unregistered structure holder");
|
||||
}
|
||||
String key = id.toString();
|
||||
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine,
|
||||
key, NativeStructureVegetationClearer.isUndergroundStep(holder.value().step()));
|
||||
if (!decision.generate()) {
|
||||
if (!NativeStructureGenerationPolicy.generates(engine, key)) {
|
||||
continue;
|
||||
}
|
||||
candidates.add(new NativeLocateCandidate(holder, key));
|
||||
@@ -357,7 +348,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
if (platformGenerator != null && !platformGenerator.shouldGenerateStructures()) {
|
||||
return;
|
||||
}
|
||||
if (runtimeLevel.getChunkSource().getGenerator() != this
|
||||
if (!isActiveGeneratorOf(runtimeLevel)
|
||||
|| runtimeLevel.getChunkSource().getGeneratorState() != structureState) {
|
||||
return;
|
||||
}
|
||||
@@ -405,33 +396,32 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
"resolution", null, chunkPos.x(), chunkPos.z());
|
||||
}
|
||||
boolean undergroundStep = NativeStructureVegetationClearer.isUndergroundStep(structure.step());
|
||||
IrisNativeStructureDecision decision;
|
||||
boolean generates;
|
||||
try {
|
||||
decision = NativeStructureGenerationPolicy.resolve(engine,
|
||||
structureId, undergroundStep);
|
||||
generates = NativeStructureGenerationPolicy.generates(engine, structureId);
|
||||
} catch (Throwable error) {
|
||||
throw NativeStructureGenerationException.failure(
|
||||
"policy resolution", structureId, chunkPos.x(), chunkPos.z(), error);
|
||||
}
|
||||
if (!decision.generate()) {
|
||||
if (!generates) {
|
||||
access.setStartForStructure(structure, StructureStart.INVALID_START);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
IntBinaryOperator surface = (x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight();
|
||||
int shift = NativeStructureLayouts.shift(engine, NativeStructureVerticalPlacer.placementOf(
|
||||
start, structureId, undergroundStep, access.getMinY(), surface));
|
||||
NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
start,
|
||||
structureId,
|
||||
decision.yShift(),
|
||||
shift,
|
||||
getSeaLevel(),
|
||||
access.getMinY(),
|
||||
access.getMinY() + access.getHeight(),
|
||||
undergroundStep,
|
||||
decision.preserveSourceY(),
|
||||
decision.yBand(),
|
||||
(x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight());
|
||||
surface);
|
||||
StructureStart wrapped = NativeStructureReferenceEnvelope.wrapForPublication(
|
||||
start, structure, start.getReferences(),
|
||||
NativeStructureTerrainIntegrator.resolveNativeTerrain(start, decision.terrain()),
|
||||
NativeStructureLayouts.reaches(engine, structureId, undergroundStep, null),
|
||||
structureId);
|
||||
access.setStartForStructure(structure, wrapped);
|
||||
} catch (Throwable error) {
|
||||
@@ -609,11 +599,15 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
private void requireCurrentStructureOwner(ServerLevel level, ChunkMap chunkMap) {
|
||||
if (runtimeLevel != level
|
||||
|| level.getChunkSource().chunkMap != chunkMap
|
||||
|| level.getChunkSource().getGenerator() != this) {
|
||||
|| !isActiveGeneratorOf(level)) {
|
||||
throw new IllegalStateException("Iris native structure state no longer belongs to the active world runtime.");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isActiveGeneratorOf(ServerLevel level) {
|
||||
return WrappedGenerators.irisGeneratorOf(level.getChunkSource().getGenerator()) == this;
|
||||
}
|
||||
|
||||
private void publishStructureState(StructureStatePublisher publisher) {
|
||||
try {
|
||||
publisher.publish();
|
||||
@@ -627,7 +621,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
if (platformGenerator != null && !platformGenerator.shouldGenerateStructures()) {
|
||||
return;
|
||||
}
|
||||
if (runtimeLevel.getChunkSource().getGenerator() != this) {
|
||||
if (!isActiveGeneratorOf(runtimeLevel)) {
|
||||
return;
|
||||
}
|
||||
try (BukkitChunkGenerator.GenerationStagePermit stage = requireGenerationStage("bukkit_nms_create_references");
|
||||
@@ -644,10 +638,9 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
GenerationSessionLease lease = requireGenerationLease("bukkit_nms_create_biomes");
|
||||
IrisContext.Scope ignored = IrisContext.open(engine, lease.sessionId(), null)) {
|
||||
customBiomeSource.prepareVisibleBiomeBatch();
|
||||
IrisDimensionCarvingResolver.State resolverState = new IrisDimensionCarvingResolver.State();
|
||||
ichunkaccess.fillBiomesFromNoise(
|
||||
(x, y, z, sampler) -> customBiomeSource.getVisibleNoiseBiomeWithActiveGenerationLease(
|
||||
x, y, z, sampler, resolverState),
|
||||
x, y, z, sampler),
|
||||
randomstate.sampler());
|
||||
return CompletableFuture.completedFuture(ichunkaccess);
|
||||
}
|
||||
@@ -808,7 +801,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
throw new IllegalStateException("Iris cannot generate native structures in chunk "
|
||||
+ disabledChunk.x() + "," + disabledChunk.z()
|
||||
+ " because structure generation is disabled outside the pack; enable native structure generation "
|
||||
+ "and deny families through importedStructures.disabled or complete keys through importedStructures.disabledExact");
|
||||
+ "and deny families through iris:structure disabled or complete keys through iris:structure disabledExact");
|
||||
}
|
||||
ChunkPos chunkPos = chunk.getPos();
|
||||
SectionPos sectionPos = SectionPos.of(chunkPos, world.getMinSectionY());
|
||||
@@ -822,7 +815,7 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
List<NativePlacementGroup> placementGroups = new ArrayList<>();
|
||||
List<StructureStart> heightmapStarts = new ArrayList<>();
|
||||
List<StructureStart> vegetationTargets = new ArrayList<>();
|
||||
List<NativeStructureTerrainIntegrator.TerrainTarget> terrainTargets = new ArrayList<>();
|
||||
List<NativeStructureFitBridge.FitTarget> fitTargets = new ArrayList<>();
|
||||
for (int step = 0; step < steps; step++) {
|
||||
int index = 0;
|
||||
for (Structure structure : byStep.get(step)) {
|
||||
@@ -833,25 +826,20 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
"resolution", null, chunkPos.x(), chunkPos.z());
|
||||
}
|
||||
try {
|
||||
IrisNativeStructureDecision sourceDecision = NativeStructureGenerationPolicy.resolve(engine,
|
||||
structureId, NativeStructureVegetationClearer.isUndergroundStep(structure.step()));
|
||||
boolean platformGenerates = NativeStructureGenerationPolicy.generates(engine, structureId);
|
||||
List<StructureStart> starts = structureManager.startsForStructure(sectionPos, structure);
|
||||
List<NativePlacement> resolvedPlacements = new ArrayList<>(starts.size());
|
||||
for (StructureStart start : starts) {
|
||||
NativeStructureOwnershipRecord ownership =
|
||||
NativeStructureOwnershipRecovery.resolve(
|
||||
engine, world.getLevel(), structureId, structure, start);
|
||||
IrisNativeStructureDecision decision =
|
||||
ownership == null ? sourceDecision : ownership.restoredDecision();
|
||||
if (!decision.generate()) {
|
||||
if (ownership == null && !platformGenerates) {
|
||||
continue;
|
||||
}
|
||||
resolvedPlacements.add(new NativePlacement(start, decision));
|
||||
resolvedPlacements.add(new NativePlacement(start, ownership != null));
|
||||
heightmapStarts.add(start);
|
||||
terrainTargets.add(new NativeStructureTerrainIntegrator.TerrainTarget(
|
||||
structureId, start,
|
||||
NativeStructureTerrainIntegrator.resolveNativeTerrain(
|
||||
start, decision.terrain())));
|
||||
fitTargets.add(new NativeStructureFitBridge.FitTarget(structureId, start,
|
||||
ownership == null ? null : ownership.restoredMemo()));
|
||||
vegetationTargets.add(start);
|
||||
}
|
||||
if (!resolvedPlacements.isEmpty()) {
|
||||
@@ -881,44 +869,29 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
"vegetation cleanup", nativeStructureBatchContext(placementGroups),
|
||||
chunkPos.x(), chunkPos.z(), error);
|
||||
}
|
||||
NativeStructureSurfaceFitter.VacuumFoundationPlan vacuumFoundationPlan;
|
||||
NativeStructureFitting.Session fit;
|
||||
try {
|
||||
vacuumFoundationPlan = NativeStructureSurfaceFitter.prepareSurfaceStructures(
|
||||
world, area, terrainTargets,
|
||||
(x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight());
|
||||
fit = NativeStructureFitting.of(engine).beforePieces(NativeStructureFitBridge.chunk(
|
||||
world, area, fitTargets, (x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight()));
|
||||
} catch (Throwable error) {
|
||||
throw NativeStructureGenerationException.failure(
|
||||
"terrain integration", nativeStructureBatchContext(placementGroups),
|
||||
chunkPos.x(), chunkPos.z(), error);
|
||||
}
|
||||
try {
|
||||
NativeStructurePostProcessor.prepareTerrain(
|
||||
world, area, terrainTargets, this::resolvePaletteBlock);
|
||||
} catch (Throwable error) {
|
||||
throw NativeStructureGenerationException.failure(
|
||||
"terrain preparation", nativeStructureBatchContext(placementGroups),
|
||||
"terrain fitting", nativeStructureBatchContext(placementGroups),
|
||||
chunkPos.x(), chunkPos.z(), error);
|
||||
}
|
||||
int placed = 0;
|
||||
for (NativePlacementGroup group : placementGroups) {
|
||||
random.setFeatureSeed(decoSeed, group.featureIndex(), group.step());
|
||||
try {
|
||||
for (NativePlacement placement : group.placements()) {
|
||||
placeVanillaStructure(world, structureManager, random, area, chunkPos,
|
||||
group.structureId(), placement.start(), placement.decision());
|
||||
group.structureId(), placement);
|
||||
fit.afterPieces(placed++);
|
||||
}
|
||||
} catch (Throwable error) {
|
||||
throw NativeStructureGenerationException.failure(
|
||||
"placement", group.structureId(), chunkPos.x(), chunkPos.z(), error);
|
||||
}
|
||||
}
|
||||
try {
|
||||
NativeStructureSurfaceFitter.repairVacuumFoundations(
|
||||
world, area, vacuumFoundationPlan);
|
||||
} catch (Throwable error) {
|
||||
throw NativeStructureGenerationException.failure(
|
||||
"foundation repair", nativeStructureBatchContext(placementGroups),
|
||||
chunkPos.x(), chunkPos.z(), error);
|
||||
}
|
||||
}
|
||||
|
||||
private static String nativeStructureBatchContext(List<NativePlacementGroup> placementGroups) {
|
||||
@@ -936,20 +909,30 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
}
|
||||
|
||||
private void placeVanillaStructure(WorldGenLevel world, StructureManager structureManager, WorldgenRandom random,
|
||||
BoundingBox area, ChunkPos chunkPos, String structureId, StructureStart start,
|
||||
IrisNativeStructureDecision decision) {
|
||||
WorldGenLevel boundedWorld = NativeStructureWorldgenAccess.create(
|
||||
BoundingBox area, ChunkPos chunkPos, String structureId,
|
||||
NativePlacement placement) {
|
||||
NativeStructureWorldgenAccess boundedWorld = NativeStructureWorldgenAccess.create(
|
||||
world, chunkPos, worldgenSurfaceHeight(), worldgenFloorHeight());
|
||||
world.setCurrentlyGenerating(() -> "Iris native structure " + structureId);
|
||||
try {
|
||||
NativeStructurePostProcessor.place(boundedWorld, structureManager, this, random, area, chunkPos,
|
||||
structureId, start, decision, this::resolvePaletteBlock,
|
||||
(x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight());
|
||||
StructureStart start = placement.start();
|
||||
NativeStructureVerticalPlacer.ensureMonumentSeaLevelAlignment(start, structureId,
|
||||
() -> placement.recorded() ? 0 : platformShift(start, structureId, world.getMinY()),
|
||||
getSeaLevel(), area.minY(), area.maxY() + 1);
|
||||
start.placeInChunk(boundedWorld, structureManager, this, random, area, chunkPos);
|
||||
} finally {
|
||||
DeferredPlacementRecords.clearWritten(engine, boundedWorld.writtenBlocks());
|
||||
world.setCurrentlyGenerating(null);
|
||||
}
|
||||
}
|
||||
|
||||
/** The shift the pack's modules give the platform's own start, as when the start was published. */
|
||||
private int platformShift(StructureStart start, String structureId, int bottomY) {
|
||||
return NativeStructureLayouts.shift(engine, NativeStructureVerticalPlacer.placementOf(start, structureId,
|
||||
NativeStructureVegetationClearer.isUndergroundStep(start.getStructure().step()), bottomY,
|
||||
(x, z) -> engine.getHeight(x, z, true) + engine.getMinHeight()));
|
||||
}
|
||||
|
||||
private List<List<Structure>> structuresByStep(Registry<Structure> registry) {
|
||||
StructureStepCache cached = structureStepCache;
|
||||
if (cached != null && cached.registry() == registry) {
|
||||
@@ -977,22 +960,6 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
}
|
||||
}
|
||||
|
||||
private BlockState resolvePaletteBlock(IrisMaterialPalette palette, RNG rng, int x, int y, int z) {
|
||||
PlatformBlockState platformState = palette.get(rng, x, y, z, engine.getData());
|
||||
if (platformState == null || !(platformState.nativeHandle() instanceof BlockData blockData)) {
|
||||
throw new IllegalStateException("Configured native structure palette did not resolve a Bukkit block at "
|
||||
+ x + "," + y + "," + z);
|
||||
}
|
||||
if (blockData instanceof IrisCustomData customData) {
|
||||
blockData = customData.getBase();
|
||||
}
|
||||
if (blockData instanceof CraftBlockData craftBlockData) {
|
||||
return craftBlockData.getState();
|
||||
}
|
||||
throw new IllegalStateException("Configured native structure palette resolved unsupported Bukkit block data "
|
||||
+ blockData.getClass().getName() + " at " + x + "," + y + "," + z);
|
||||
}
|
||||
|
||||
private BoundingBox writableArea(ChunkAccess chunk) {
|
||||
ChunkPos cp = chunk.getPos();
|
||||
int i = cp.getMinBlockX();
|
||||
@@ -1205,7 +1172,8 @@ public class IrisChunkGenerator extends CustomChunkGenerator {
|
||||
void publish() throws IllegalAccessException;
|
||||
}
|
||||
|
||||
private record NativePlacement(StructureStart start, IrisNativeStructureDecision decision) {
|
||||
/** A start placed in the chunk, and whether a module placed it (its ownership record kept its fit). */
|
||||
private record NativePlacement(StructureStart start, boolean recorded) {
|
||||
}
|
||||
|
||||
private record NativePlacementGroup(String structureId, int featureIndex, int step,
|
||||
|
||||
+42
-11
@@ -6,7 +6,7 @@ import ca.spottedleaf.moonrise.patches.chunk_system.scheduling.NewChunkHolder;
|
||||
import com.mojang.brigadier.exceptions.CommandSyntaxException;
|
||||
import art.arcane.iris.core.datapack.DatapackStructureScopeIndex;
|
||||
import art.arcane.iris.core.nms.DatapackStructureScopeResult;
|
||||
import art.arcane.iris.engine.object.IrisImportedStructureControl;
|
||||
import art.arcane.iris.engine.framework.NativeStructureFrequencies;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.core.nms.INMSBinding;
|
||||
import art.arcane.iris.core.nms.MinecraftVersion;
|
||||
@@ -15,12 +15,12 @@ import art.arcane.iris.core.nms.container.BiomeColor;
|
||||
import art.arcane.iris.core.nms.container.Pair;
|
||||
import art.arcane.iris.core.nms.container.BlockProperty;
|
||||
import art.arcane.iris.core.nms.datapack.DataVersion;
|
||||
import art.arcane.iris.engine.data.cache.AtomicCache;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.iris.engine.data.chunk.TerrainChunk;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.NativeStructureVolume;
|
||||
import art.arcane.iris.nativegen.NativeStructureVolumeIndex;
|
||||
import art.arcane.iris.engine.object.IrisDimensionRuntimeContract;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimensionRuntimeContract;
|
||||
import art.arcane.iris.engine.platform.BukkitChunkGenerator;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import art.arcane.iris.nativegen.NativeStructureFactory;
|
||||
@@ -179,6 +179,7 @@ public class NMSBinding implements INMSBinding {
|
||||
private final BlockData AIR = Material.AIR.createBlockData();
|
||||
private final AtomicCache<MCAIdMap<net.minecraft.world.level.biome.Biome>> biomeMapCache = new AtomicCache<>();
|
||||
private final AtomicBoolean injected = new AtomicBoolean();
|
||||
private final GroundSurvival groundSurvival = new GroundSurvival();
|
||||
private volatile ResettableClassFileTransformer levelStorageAccessTransformer;
|
||||
private volatile ResettableClassFileTransformer serverLevelTransformer;
|
||||
private final AtomicCache<MCAIdMapper<BlockState>> registryCache = new AtomicCache<>();
|
||||
@@ -1130,6 +1131,18 @@ public class NMSBinding implements INMSBinding {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean pollChunkTask(World world) {
|
||||
if (J.isFolia()) {
|
||||
return false;
|
||||
}
|
||||
ServerLevel level = ((CraftWorld) world).getHandle();
|
||||
if (Thread.currentThread() != level.getServer().getRunningThread()) {
|
||||
throw new IllegalStateException("Native chunk tasks can only be polled from the server thread.");
|
||||
}
|
||||
return level.getChunkSource().pollTask();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flushChunkIO(World world) {
|
||||
try {
|
||||
@@ -1140,6 +1153,11 @@ public class NMSBinding implements INMSBinding {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reconcileNativeStructurePois(Chunk chunk) {
|
||||
NativeStructurePoiUpdates.reconcile((LevelChunk) ((CraftChunk) chunk).getHandle(ChunkStatus.FULL));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean clearChunkBlocks(Chunk bukkitChunk) {
|
||||
try {
|
||||
@@ -1232,7 +1250,7 @@ public class NMSBinding implements INMSBinding {
|
||||
World world,
|
||||
DatapackStructureScopeIndex scopeIndex,
|
||||
Set<String> declaredSources,
|
||||
IrisImportedStructureControl importedStructures
|
||||
NativeStructureFrequencies frequencies
|
||||
) throws NoSuchFieldException, IllegalAccessException {
|
||||
ServerLevel level = ((CraftWorld) world).getHandle();
|
||||
ChunkMap chunkMap = level.getChunkSource().chunkMap;
|
||||
@@ -1245,7 +1263,7 @@ public class NMSBinding implements INMSBinding {
|
||||
scopedState.possibleStructureSets(),
|
||||
scopeIndex,
|
||||
declaredSources,
|
||||
importedStructures,
|
||||
frequencies,
|
||||
DatapackStructureStateFilter.keyIndex(
|
||||
structureSetRegistry.listElements().toList()));
|
||||
|
||||
@@ -1261,7 +1279,7 @@ public class NMSBinding implements INMSBinding {
|
||||
boolean studioBootstrap = platformGenerator != null
|
||||
&& platformGenerator.isStudioEntryBootstrapActive();
|
||||
boolean jigsawStudio = platformGenerator != null
|
||||
&& platformGenerator.isJigsawStudioActive();
|
||||
&& platformGenerator.isPaintedStudioActive();
|
||||
if (jigsawStudio) {
|
||||
requireIrisGenerator(generator);
|
||||
if (currentState.possibleStructureSets().isEmpty()) {
|
||||
@@ -1310,8 +1328,8 @@ public class NMSBinding implements INMSBinding {
|
||||
@Override
|
||||
public void abandonStudioStructureBootstrap(World world) {
|
||||
ServerLevel level = ((CraftWorld) world).getHandle();
|
||||
net.minecraft.world.level.chunk.ChunkGenerator generator = level.getChunkSource().getGenerator();
|
||||
if (generator instanceof IrisChunkGenerator irisGenerator) {
|
||||
IrisChunkGenerator irisGenerator = WrappedGenerators.irisGeneratorOf(level.getChunkSource().getGenerator());
|
||||
if (irisGenerator != null) {
|
||||
irisGenerator.abandonStudioStructureState();
|
||||
}
|
||||
}
|
||||
@@ -1333,7 +1351,8 @@ public class NMSBinding implements INMSBinding {
|
||||
ChunkGeneratorStructureState structureState,
|
||||
IrisChunkGenerator.StructureStatePublisher publisher
|
||||
) throws IllegalAccessException {
|
||||
if (generator instanceof IrisChunkGenerator irisGenerator) {
|
||||
IrisChunkGenerator irisGenerator = WrappedGenerators.irisGeneratorOf(generator);
|
||||
if (irisGenerator != null) {
|
||||
irisGenerator.initializeAndPublishStructureState(structureState, publisher);
|
||||
return;
|
||||
}
|
||||
@@ -1344,10 +1363,12 @@ public class NMSBinding implements INMSBinding {
|
||||
private IrisChunkGenerator requireIrisGenerator(
|
||||
net.minecraft.world.level.chunk.ChunkGenerator generator
|
||||
) {
|
||||
if (generator instanceof IrisChunkGenerator irisGenerator) {
|
||||
IrisChunkGenerator irisGenerator = WrappedGenerators.irisGeneratorOf(generator);
|
||||
if (irisGenerator != null) {
|
||||
return irisGenerator;
|
||||
}
|
||||
throw new IllegalStateException("Studio native structure state is not owned by the active Iris generator.");
|
||||
throw new IllegalStateException("Studio native structure state is not owned by the active Iris generator; active="
|
||||
+ generator.getClass().getName());
|
||||
}
|
||||
|
||||
private void validateDimensionContract(Engine engine, World world, ServerLevel level) {
|
||||
@@ -1642,6 +1663,16 @@ public class NMSBinding implements INMSBinding {
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canSurviveOn(BlockData plant, BlockData ground) {
|
||||
return groundSurvival.canSurviveOn(((CraftBlockData) plant).getState(), ((CraftBlockData) ground).getState());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forgetBlockRules() {
|
||||
groundSurvival.forgetRules();
|
||||
}
|
||||
|
||||
@Override
|
||||
public KMap<Material, List<BlockProperty>> getBlockProperties() {
|
||||
KMap<Material, List<BlockProperty>> states = new KMap<>();
|
||||
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
package art.arcane.iris.core.nms.v26_2_R1;
|
||||
|
||||
import ca.spottedleaf.moonrise.common.util.TickThread;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.SectionPos;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.ai.village.poi.PoiManager;
|
||||
import net.minecraft.world.entity.ai.village.poi.PoiRecord;
|
||||
import net.minecraft.world.entity.ai.village.poi.PoiSection;
|
||||
import net.minecraft.world.entity.ai.village.poi.PoiType;
|
||||
import net.minecraft.world.entity.ai.village.poi.PoiTypes;
|
||||
import net.minecraft.world.level.WorldGenLevel;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.chunk.ChunkAccess;
|
||||
import net.minecraft.world.level.chunk.ImposterProtoChunk;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
import net.minecraft.world.level.chunk.LevelChunkSection;
|
||||
import net.minecraft.world.level.chunk.ProtoChunk;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
|
||||
final class NativeStructurePoiUpdates {
|
||||
private static final NamespacedKey DIRTY_SECTIONS = new NamespacedKey("iris", "native_poi_sections");
|
||||
|
||||
private final int skipPoiFlag;
|
||||
|
||||
NativeStructurePoiUpdates(int skipPoiFlag) {
|
||||
this.skipPoiFlag = skipPoiFlag;
|
||||
}
|
||||
|
||||
static NativeStructurePoiUpdates create() {
|
||||
try {
|
||||
return new NativeStructurePoiUpdates(Block.class.getField("UPDATE_SKIP_POI").getInt(null));
|
||||
} catch (NoSuchFieldException e) {
|
||||
return null;
|
||||
} catch (IllegalAccessException e) {
|
||||
throw new ExceptionInInitializerError(e);
|
||||
}
|
||||
}
|
||||
|
||||
boolean setBlock(WorldGenLevel world, BlockPos position, BlockState state, int flags, int limit) {
|
||||
if ((flags & skipPoiFlag) != 0) {
|
||||
return world.setBlock(position, state, flags, limit);
|
||||
}
|
||||
ChunkAccess chunk = world.getChunk(position);
|
||||
if (!(chunk instanceof ProtoChunk)) {
|
||||
return world.setBlock(position, state, flags, limit);
|
||||
}
|
||||
if (!(chunk instanceof ImposterProtoChunk)
|
||||
&& !PoiTypes.forState(chunk.getBlockState(position)).equals(PoiTypes.forState(state))) {
|
||||
markSection(chunk, chunk.getSectionIndex(position.getY()));
|
||||
}
|
||||
return world.setBlock(position, state, flags | skipPoiFlag, limit);
|
||||
}
|
||||
|
||||
static void reconcile(LevelChunk chunk) {
|
||||
long[] sections = chunk.persistentDataContainer.get(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY);
|
||||
if (sections == null) {
|
||||
return;
|
||||
}
|
||||
validateSections(chunk, sections);
|
||||
ServerLevel world = (ServerLevel) chunk.getLevel();
|
||||
TickThread.ensureTickThread(world, chunk.getPos(), "Native structure POIs require the chunk owning thread");
|
||||
PoiManager manager = world.getPoiManager();
|
||||
for (int word = 0; word < sections.length; word++) {
|
||||
long remaining = sections[word];
|
||||
while (remaining != 0) {
|
||||
int index = (word << 6) + Long.numberOfTrailingZeros(remaining);
|
||||
reconcileSection(chunk, manager, index);
|
||||
remaining &= remaining - 1;
|
||||
}
|
||||
}
|
||||
chunk.persistentDataContainer.remove(DIRTY_SECTIONS);
|
||||
chunk.markUnsaved();
|
||||
}
|
||||
|
||||
private static void markSection(ChunkAccess chunk, int index) {
|
||||
long[] sections = chunk.persistentDataContainer.get(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY);
|
||||
int word = index >>> 6;
|
||||
long bit = 1L << (index & 63);
|
||||
if (sections == null) {
|
||||
sections = new long[word + 1];
|
||||
} else {
|
||||
validateSections(chunk, sections);
|
||||
if (word < sections.length && (sections[word] & bit) != 0) {
|
||||
return;
|
||||
}
|
||||
if (word >= sections.length) {
|
||||
sections = Arrays.copyOf(sections, word + 1);
|
||||
}
|
||||
}
|
||||
sections[word] |= bit;
|
||||
chunk.persistentDataContainer.set(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY, sections);
|
||||
}
|
||||
|
||||
private static void validateSections(ChunkAccess chunk, long[] sections) {
|
||||
int count = chunk.getSectionsCount();
|
||||
int words = (count + 63) >>> 6;
|
||||
if (sections.length > words
|
||||
|| sections.length == words && (count & 63) != 0
|
||||
&& (sections[words - 1] >>> (count & 63)) != 0) {
|
||||
throw new IllegalArgumentException("Native POI repair sections exceed chunk height at " + chunk.getPos());
|
||||
}
|
||||
}
|
||||
|
||||
private static void reconcileSection(LevelChunk chunk, PoiManager manager, int index) {
|
||||
SectionPos sectionPosition = SectionPos.of(chunk.getPos(), chunk.getSectionYFromSectionIndex(index));
|
||||
Optional<PoiSection> existing = manager.getOrLoad(sectionPosition.asLong());
|
||||
if (existing.isPresent()) {
|
||||
for (PoiRecord record : existing.get().getRecords(type -> true, PoiManager.Occupancy.ANY).toList()) {
|
||||
if (!PoiTypes.forState(chunk.getBlockState(record.getPos())).equals(Optional.of(record.getPoiType()))) {
|
||||
manager.remove(record.getPos());
|
||||
}
|
||||
}
|
||||
}
|
||||
LevelChunkSection section = chunk.getSection(index);
|
||||
if (!section.maybeHas(PoiTypes::hasPoi)) {
|
||||
return;
|
||||
}
|
||||
BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
|
||||
for (int y = 0; y < 16; y++) {
|
||||
for (int z = 0; z < 16; z++) {
|
||||
for (int x = 0; x < 16; x++) {
|
||||
Optional<Holder<PoiType>> type = PoiTypes.forState(section.getBlockState(x, y, z));
|
||||
if (type.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
position.set(sectionPosition.minBlockX() + x, sectionPosition.minBlockY() + y,
|
||||
sectionPosition.minBlockZ() + z);
|
||||
if (!manager.getType(position).equals(type)) {
|
||||
manager.add(position.immutable(), type.get());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
-3
@@ -1,5 +1,6 @@
|
||||
package art.arcane.iris.core.nms.v26_2_R1;
|
||||
|
||||
import art.arcane.iris.engine.mantle.DeferredPlacementRecords.WrittenBlocks;
|
||||
import art.arcane.iris.nativegen.WorldgenTerrainHeightmaps;
|
||||
import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap;
|
||||
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
|
||||
@@ -11,6 +12,7 @@ import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.particles.ParticleOptions;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.server.level.WorldGenRegion;
|
||||
import net.minecraft.sounds.SoundEvent;
|
||||
import net.minecraft.sounds.SoundSource;
|
||||
import net.minecraft.util.Mth;
|
||||
@@ -59,6 +61,7 @@ import java.util.function.Supplier;
|
||||
|
||||
final class NativeStructureWorldgenAccess implements WorldGenLevel {
|
||||
private static final int WRITE_RADIUS = 1;
|
||||
private static final NativeStructurePoiUpdates POI_UPDATES = NativeStructurePoiUpdates.create();
|
||||
|
||||
private final WorldGenLevel delegate;
|
||||
private final ChunkPos generationCenter;
|
||||
@@ -71,6 +74,7 @@ final class NativeStructureWorldgenAccess implements WorldGenLevel {
|
||||
private final LevelTickAccess<Fluid> fluidTicks;
|
||||
private final Long2LongOpenHashMap terrainHeights;
|
||||
private final Long2ObjectOpenHashMap<ChunkAccess> outsideChunks;
|
||||
private final WrittenBlocks writtenBlocks = new WrittenBlocks();
|
||||
|
||||
private NativeStructureWorldgenAccess(WorldGenLevel delegate, Boundary boundary) {
|
||||
this.delegate = Objects.requireNonNull(delegate, "Native structure world access requires a delegate");
|
||||
@@ -424,17 +428,50 @@ final class NativeStructureWorldgenAccess implements WorldGenLevel {
|
||||
|
||||
@Override
|
||||
public boolean setBlock(BlockPos position, BlockState state, int updateFlags, int updateLimit) {
|
||||
return isWritable(position) && delegate.setBlock(position, state, updateFlags, updateLimit);
|
||||
if (!isWritable(position)) {
|
||||
return false;
|
||||
}
|
||||
return recordWrite(position, POI_UPDATES != null
|
||||
? POI_UPDATES.setBlock(delegate, position, state, updateFlags, updateLimit)
|
||||
: delegate.setBlock(position, state, updateFlags, updateLimit));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeBlock(BlockPos position, boolean move) {
|
||||
return isWritable(position) && delegate.removeBlock(position, move);
|
||||
if (!isWritable(position)) {
|
||||
return false;
|
||||
}
|
||||
if (reconcilesPoiThroughSetBlock()) {
|
||||
return setBlock(position, Blocks.AIR.defaultBlockState(), Block.UPDATE_ALL, Block.UPDATE_LIMIT);
|
||||
}
|
||||
return recordWrite(position, delegate.removeBlock(position, move));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean destroyBlock(BlockPos position, boolean drop, Entity source, int updateLimit) {
|
||||
return isWritable(position) && delegate.destroyBlock(position, drop, source, updateLimit);
|
||||
if (!isWritable(position)) {
|
||||
return false;
|
||||
}
|
||||
if (reconcilesPoiThroughSetBlock()) {
|
||||
return !delegate.getBlockState(position).isAir()
|
||||
&& setBlock(position, Blocks.AIR.defaultBlockState(), Block.UPDATE_ALL, updateLimit);
|
||||
}
|
||||
return recordWrite(position, delegate.destroyBlock(position, drop, source, updateLimit));
|
||||
}
|
||||
|
||||
WrittenBlocks writtenBlocks() {
|
||||
return writtenBlocks;
|
||||
}
|
||||
|
||||
private boolean reconcilesPoiThroughSetBlock() {
|
||||
return POI_UPDATES != null && delegate instanceof WorldGenRegion;
|
||||
}
|
||||
|
||||
private boolean recordWrite(BlockPos position, boolean written) {
|
||||
if (written) {
|
||||
writtenBlocks.add(position.getX(), position.getY(), position.getZ());
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package art.arcane.iris.core.nms.v26_2_R1;
|
||||
|
||||
import net.minecraft.world.level.chunk.ChunkGenerator;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Finds the Iris generator behind a level's active generator. Other plugins (CraftEngine, for one)
|
||||
* wrap the active generator in a delegating generator of their own during WorldInitEvent, after
|
||||
* Iris has injected its generator, so the active generator is not always Iris itself.
|
||||
*/
|
||||
final class WrappedGenerators {
|
||||
private static final int MAX_WRAPPER_DEPTH = 4;
|
||||
private static final ClassValue<Optional<Field>> WRAPPED_GENERATOR_FIELDS = new ClassValue<>() {
|
||||
@Override
|
||||
protected Optional<Field> computeValue(Class<?> wrapperType) {
|
||||
return findWrappedGeneratorField(wrapperType);
|
||||
}
|
||||
};
|
||||
|
||||
private WrappedGenerators() {
|
||||
}
|
||||
|
||||
static IrisChunkGenerator irisGeneratorOf(ChunkGenerator activeGenerator) {
|
||||
ChunkGenerator current = activeGenerator;
|
||||
for (int depth = 0; current != null && depth <= MAX_WRAPPER_DEPTH; depth++) {
|
||||
if (current instanceof IrisChunkGenerator irisGenerator) {
|
||||
return irisGenerator;
|
||||
}
|
||||
current = wrappedBy(current);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static ChunkGenerator wrappedBy(ChunkGenerator wrapper) {
|
||||
Optional<Field> field = WRAPPED_GENERATOR_FIELDS.get(wrapper.getClass());
|
||||
if (field.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return field.get().get(wrapper) instanceof ChunkGenerator wrapped && wrapped != wrapper ? wrapped : null;
|
||||
} catch (IllegalAccessException unreadable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Optional<Field> findWrappedGeneratorField(Class<?> wrapperType) {
|
||||
for (Class<?> type = wrapperType; type != null && type != ChunkGenerator.class; type = type.getSuperclass()) {
|
||||
for (Field field : type.getDeclaredFields()) {
|
||||
if (Modifier.isStatic(field.getModifiers()) || !ChunkGenerator.class.isAssignableFrom(field.getType())) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
field.setAccessible(true);
|
||||
return Optional.of(field);
|
||||
} catch (RuntimeException inaccessible) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
+13
-16
@@ -33,7 +33,7 @@ public class IrisChunkGeneratorFailureContractTest {
|
||||
int reachabilityEnd = source.indexOf("protected MapCodec", reachabilityStart);
|
||||
String reachability = source.substring(reachabilityStart, reachabilityEnd);
|
||||
int bootstrapGate = locate.indexOf("!platformGenerator.shouldGenerateStructures()");
|
||||
int generatorIdentity = locate.indexOf("level.getChunkSource().getGenerator() != this");
|
||||
int generatorIdentity = locate.indexOf("!isActiveGeneratorOf(level)");
|
||||
int lease = locate.indexOf("requireGenerationLease(\"bukkit_nms_structure_locate\")");
|
||||
int nativePrediction = locate.indexOf("NativeStructureVanillaLocator.predict(");
|
||||
|
||||
@@ -63,20 +63,18 @@ public class IrisChunkGeneratorFailureContractTest {
|
||||
assertTrue(adjustment.contains("\"vertical adjustment\""));
|
||||
assertFalse(adjustment.contains("IrisLogging.reportError"));
|
||||
assertTrue(placement.contains("\"resolution\""));
|
||||
assertTrue(placement.contains("\"terrain integration\""));
|
||||
assertTrue(placement.contains("\"terrain preparation\""));
|
||||
assertTrue(placement.contains("\"foundation repair\""));
|
||||
assertTrue(placement.contains("\"terrain fitting\""));
|
||||
assertFalse(placement.contains("\"terrain carving\""));
|
||||
assertTrue(placement.contains("\"vegetation cleanup\""));
|
||||
assertTrue(placement.contains("\"placement\""));
|
||||
assertTrue(placement.contains("because structure generation is disabled outside the pack"));
|
||||
assertTrue(placement.contains("prepareSurfaceStructures"));
|
||||
assertTrue(placement.contains(".beforePieces("));
|
||||
assertTrue(placement.contains("clearIntersectingVegetation"));
|
||||
assertTrue(placement.indexOf("clearIntersectingVegetation")
|
||||
< placement.indexOf("prepareSurfaceStructures"));
|
||||
assertTrue(placement.indexOf("prepareSurfaceStructures")
|
||||
< placement.indexOf(".beforePieces("));
|
||||
assertTrue(placement.indexOf(".beforePieces(")
|
||||
< placement.indexOf("for (NativePlacementGroup group"));
|
||||
assertTrue(placement.indexOf("repairVacuumFoundations")
|
||||
assertTrue(placement.indexOf("fit.afterPieces(")
|
||||
> placement.indexOf("for (NativePlacementGroup group"));
|
||||
assertFalse(placement.contains("IrisLogging.reportError"));
|
||||
}
|
||||
@@ -99,7 +97,7 @@ public class IrisChunkGeneratorFailureContractTest {
|
||||
String references = source.substring(referencesStart, referencesEnd);
|
||||
|
||||
int nativeStructureGate = references.indexOf("!platformGenerator.shouldGenerateStructures()");
|
||||
int generatorIdentity = references.indexOf("runtimeLevel.getChunkSource().getGenerator() != this");
|
||||
int generatorIdentity = references.indexOf("!isActiveGeneratorOf(runtimeLevel)");
|
||||
int stage = references.indexOf("requireGenerationStage(\"bukkit_nms_create_references\")");
|
||||
int lease = references.indexOf("requireGenerationLease(\"bukkit_nms_create_references\")");
|
||||
int repair = references.indexOf("NativeStructureReferenceRepair.createReferences(");
|
||||
@@ -122,7 +120,7 @@ public class IrisChunkGeneratorFailureContractTest {
|
||||
String generation = source.substring(generationStart, generationEnd);
|
||||
int gate = generation.indexOf("!platformGenerator.shouldGenerateStructures()");
|
||||
int currentGenerator = generation.indexOf(
|
||||
"runtimeLevel.getChunkSource().getGenerator() != this");
|
||||
"!isActiveGeneratorOf(runtimeLevel)");
|
||||
int stateIdentity = generation.indexOf(
|
||||
"runtimeLevel.getChunkSource().getGeneratorState() != structureState");
|
||||
int stage = generation.indexOf(
|
||||
@@ -214,7 +212,7 @@ public class IrisChunkGeneratorFailureContractTest {
|
||||
assertEquals(1, occurrences(source, "WorldgenTerrainHeightmaps.primeTerrain("));
|
||||
assertTrue(placement.contains("WorldgenTerrainHeightmaps.primeStructurePlacement("));
|
||||
assertTrue(placement.indexOf("WorldgenTerrainHeightmaps.primeStructurePlacement(")
|
||||
< placement.indexOf("prepareSurfaceStructures"));
|
||||
< placement.indexOf(".beforePieces("));
|
||||
assertTrue(fill.contains("requireGenerationLease(\"bukkit_nms_chunk_pipeline\")"));
|
||||
assertTrue(source.contains("int minY = chunk.getMinY() + 1;"));
|
||||
}
|
||||
@@ -258,8 +256,7 @@ public class IrisChunkGeneratorFailureContractTest {
|
||||
|
||||
assertTrue(createBiomes.contains("requireGenerationStage(\"bukkit_nms_create_biomes\")"));
|
||||
assertTrue(createBiomes.contains("customBiomeSource.prepareVisibleBiomeBatch()"));
|
||||
assertTrue(createBiomes.contains("new IrisDimensionCarvingResolver.State()"));
|
||||
assertTrue(createBiomes.contains("sampler, resolverState"));
|
||||
assertTrue(createBiomes.contains("getVisibleNoiseBiomeWithActiveGenerationLease("));
|
||||
assertTrue(buildSurface.contains("delegate.buildSurface("));
|
||||
assertTrue(carvers.contains("delegate.applyCarvers("));
|
||||
assertTrue(noise.contains("requireNoiseGenerationStage("));
|
||||
@@ -442,7 +439,7 @@ public class IrisChunkGeneratorFailureContractTest {
|
||||
|
||||
@Test
|
||||
public void worldgenHeightmapPrimingLivesInTheSharedNativegenSources() throws IOException {
|
||||
Path nativegen = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")).getParent();
|
||||
Path nativegen = Path.of(System.getProperty("iris.nativeStructureFitBridgeSource")).getParent();
|
||||
Path shared = nativegen.resolve("WorldgenTerrainHeightmaps.java");
|
||||
|
||||
assertTrue("Worldgen heightmap priming must be shared with the modded loaders through "
|
||||
@@ -469,11 +466,11 @@ public class IrisChunkGeneratorFailureContractTest {
|
||||
String placement = source.substring(placementStart, placementEnd);
|
||||
int ownershipResolution = placement.indexOf(
|
||||
"NativeStructureOwnershipRecovery.resolve(");
|
||||
int persistedDecision = placement.indexOf("ownership.restoredDecision()", ownershipResolution);
|
||||
int persistedDecision = placement.indexOf("ownership.restoredMemo()", ownershipResolution);
|
||||
int adjustmentStart = source.indexOf("private void adjustGeneratedStructures");
|
||||
int adjustmentEnd = source.indexOf("public ChunkGeneratorStructureState createState", adjustmentStart);
|
||||
String adjustment = source.substring(adjustmentStart, adjustmentEnd);
|
||||
Path nativegen = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")).getParent();
|
||||
Path nativegen = Path.of(System.getProperty("iris.nativeStructureFitBridgeSource")).getParent();
|
||||
String factory = Files.readString(nativegen.resolve("NativeStructureFactory.java")).replace("\r\n", "\n");
|
||||
String injector = Files.readString(nativegen.resolve("NativeStructureStartInjector.java")).replace("\r\n", "\n");
|
||||
String recovery = Files.readString(nativegen.resolve("NativeStructureOwnershipRecovery.java")).replace("\r\n", "\n");
|
||||
|
||||
+5
-28
@@ -31,9 +31,9 @@ public class IrisChunkGeneratorMonumentLocateContractTest {
|
||||
String irisHelper = source.substring(irisHelperStart, filterStart);
|
||||
int registryLookup = irisHelper.indexOf("level.registryAccess().lookupOrThrow(Registries.STRUCTURE)");
|
||||
int placedCheck = irisHelper.indexOf(
|
||||
"if (!IrisStructureLocator.hasNativePlacement(engine, structureId))");
|
||||
"if (!ModuleServices.startsStructure(engine, structureId))");
|
||||
int irisLocate = irisHelper.indexOf("NativeStructureLocatePersistence.search(", placedCheck);
|
||||
int searchLimit = irisHelper.indexOf("LocateStatus.SEARCH_LIMIT_REACHED", irisLocate);
|
||||
int searchLimit = irisHelper.indexOf("Outcome.SEARCH_LIMIT_REACHED", irisLocate);
|
||||
int nativeFilter = outerMethod.indexOf("filterReachableStructures(level, holders)");
|
||||
int nativePrediction = outerMethod.indexOf("NativeStructureVanillaLocator.predict(", nativeFilter);
|
||||
int irisResolution = outerMethod.indexOf("return findNearestIrisStructure(", nativePrediction);
|
||||
@@ -45,7 +45,7 @@ public class IrisChunkGeneratorMonumentLocateContractTest {
|
||||
int reachabilityStart = source.indexOf("private Set<String> reachableStructureKeys", filterStart);
|
||||
assertTrue(reachabilityStart > filterStart);
|
||||
String filterMethod = source.substring(filterStart, reachabilityStart);
|
||||
int policyFilter = filterMethod.indexOf("if (!decision.generate())");
|
||||
int policyFilter = filterMethod.indexOf("if (!NativeStructureGenerationPolicy.generates(engine, key))");
|
||||
int filterContinue = filterMethod.indexOf("continue;", policyFilter);
|
||||
int emptyNativePartition = filterMethod.indexOf("if (candidates.isEmpty())", filterContinue);
|
||||
int reachabilityLookup = filterMethod.indexOf("reachableStructureKeys(level)", emptyNativePartition);
|
||||
@@ -119,7 +119,7 @@ public class IrisChunkGeneratorMonumentLocateContractTest {
|
||||
|
||||
@Test
|
||||
public void nativePredictionIsReadOnlyUntilTheWinnerIsCommitted() throws IOException {
|
||||
Path nativegen = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource")).getParent();
|
||||
Path nativegen = Path.of(System.getProperty("iris.nativeStructureFitBridgeSource")).getParent();
|
||||
String source = Files.readString(nativegen.resolve("NativeStructureVanillaLocator.java")).replace("\r\n", "\n");
|
||||
int predictionStart = source.indexOf("private static Candidate predictAt(");
|
||||
int candidateStart = source.indexOf("public static final class Candidate", predictionStart);
|
||||
@@ -131,33 +131,10 @@ public class IrisChunkGeneratorMonumentLocateContractTest {
|
||||
assertTrue(candidate.contains("committed.compareAndSet(false, true)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void stiltSupportUsesPlacedSolidOccupancyWithoutSnapshotDifferenceRequirement() throws IOException {
|
||||
Path processor = Path.of(System.getProperty("iris.nativeStructurePostProcessorSource"));
|
||||
String source = Files.readString(processor).replace("\r\n", "\n");
|
||||
String foundation = Files.readString(
|
||||
processor.resolveSibling("NativeStructureFoundationBuilder.java")).replace("\r\n", "\n");
|
||||
int placement = source.indexOf("start.placeInChunk(world, structureManager, generator");
|
||||
int stiltPlacement = source.indexOf("placeStilts(world, area, structureId, start", placement);
|
||||
int stiltDefinition = foundation.indexOf("static void placeStilts(");
|
||||
int occupancyCheck = foundation.indexOf("if (state.isSolid())", stiltDefinition);
|
||||
int terrainFloor = foundation.indexOf("Math.max(terrainY,", stiltDefinition);
|
||||
|
||||
assertTrue(placement >= 0);
|
||||
assertTrue(stiltPlacement > placement);
|
||||
assertTrue(stiltDefinition >= 0);
|
||||
assertTrue(occupancyCheck > stiltDefinition);
|
||||
assertTrue(terrainFloor > stiltDefinition);
|
||||
assertFalse(source.contains("state.equals("));
|
||||
assertFalse(foundation.contains("state.equals("));
|
||||
assertFalse(source.contains("snapshot.states"));
|
||||
assertFalse(foundation.contains("snapshot.states"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void verticalPlacementMovesPiecesMonumentChildrenJigsawJunctionsAndCachedBoundsTogether() throws IOException {
|
||||
String source = Files.readString(
|
||||
Path.of(System.getProperty("iris.nativeStructurePostProcessorSource"))
|
||||
Path.of(System.getProperty("iris.nativeStructureFitBridgeSource"))
|
||||
.resolveSibling("NativeStructureVerticalPlacer.java")).replace("\r\n", "\n");
|
||||
int placementStart = source.indexOf("public static int applyVerticalPlacement");
|
||||
int shiftStart = source.indexOf("public static int applyVerticalShift", placementStart);
|
||||
|
||||
+10
-36
@@ -2,9 +2,7 @@ package art.arcane.iris.core.nms.v26_2_R1;
|
||||
|
||||
import art.arcane.iris.core.datapack.DatapackIngestService;
|
||||
import art.arcane.iris.core.datapack.DatapackStructureScopeIndex;
|
||||
import art.arcane.iris.engine.object.IrisImportedStructureControl;
|
||||
import art.arcane.iris.engine.object.IrisStructureSetFrequencyOverride;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.iris.engine.framework.NativeStructureFrequencies;
|
||||
import com.mojang.datafixers.util.Either;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.Holder;
|
||||
@@ -32,6 +30,7 @@ import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Predicate;
|
||||
@@ -135,14 +134,14 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
List.of(spigotDirect),
|
||||
scopeIndex,
|
||||
Set.of(),
|
||||
new IrisImportedStructureControl(),
|
||||
NativeStructureFrequencies.NONE,
|
||||
keyIndex);
|
||||
DatapackStructureStateFilter.Selection retained =
|
||||
DatapackStructureStateFilter.filter(
|
||||
List.of(spigotDirect),
|
||||
scopeIndex,
|
||||
scopeIndex.declaredSources(List.of(SOURCE)),
|
||||
new IrisImportedStructureControl(),
|
||||
NativeStructureFrequencies.NONE,
|
||||
keyIndex);
|
||||
|
||||
assertEquals(0, excluded.structureSets().size());
|
||||
@@ -172,12 +171,7 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
"minecraft:nether_fossils",
|
||||
new RandomSpreadStructurePlacement(2, 1, RandomSpreadType.LINEAR, 14357921),
|
||||
structureHolder("minecraft:nether_fossil"));
|
||||
KList<IrisStructureSetFrequencyOverride> overrides = new KList<>();
|
||||
overrides.add(new IrisStructureSetFrequencyOverride()
|
||||
.setStructureSet("minecraft:nether_complexes")
|
||||
.setMultiplier(1.1D));
|
||||
IrisImportedStructureControl control = new IrisImportedStructureControl()
|
||||
.setFrequencyOverrides(overrides);
|
||||
NativeStructureFrequencies control = NativeStructureFrequencies.of(Map.of("minecraft:nether_complexes", 1.1D));
|
||||
|
||||
DatapackStructureStateFilter.Selection selection = DatapackStructureStateFilter.filter(
|
||||
List.of(complexes, fossils), index(List.of(), List.of()), Set.of(), control);
|
||||
@@ -202,12 +196,7 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
new UnsupportedPlacement(Optional.of(
|
||||
new StructurePlacement.ExclusionZone(exclusionTarget, 1))),
|
||||
structureHolder("example:custom"));
|
||||
KList<IrisStructureSetFrequencyOverride> overrides = new KList<>();
|
||||
overrides.add(new IrisStructureSetFrequencyOverride()
|
||||
.setStructureSet("minecraft:nether_complexes")
|
||||
.setMultiplier(1.1D));
|
||||
IrisImportedStructureControl control = new IrisImportedStructureControl()
|
||||
.setFrequencyOverrides(overrides);
|
||||
NativeStructureFrequencies control = NativeStructureFrequencies.of(Map.of("minecraft:nether_complexes", 1.1D));
|
||||
|
||||
DatapackStructureStateFilter.Selection selection = DatapackStructureStateFilter.filter(
|
||||
List.of(custom), index(List.of(), List.of()), Set.of(), control);
|
||||
@@ -234,12 +223,7 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
"example:dependent",
|
||||
dependentPlacement,
|
||||
structureHolder("example:dependent"));
|
||||
KList<IrisStructureSetFrequencyOverride> overrides = new KList<>();
|
||||
overrides.add(new IrisStructureSetFrequencyOverride()
|
||||
.setStructureSet("example:target")
|
||||
.setMultiplier(1.1D));
|
||||
IrisImportedStructureControl control = new IrisImportedStructureControl()
|
||||
.setFrequencyOverrides(overrides);
|
||||
NativeStructureFrequencies control = NativeStructureFrequencies.of(Map.of("example:target", 1.1D));
|
||||
|
||||
DatapackStructureStateFilter.Selection selection = DatapackStructureStateFilter.filter(
|
||||
List.of(dependent, target), index(List.of(), List.of()), Set.of(), control);
|
||||
@@ -280,12 +264,7 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
4,
|
||||
RandomSpreadType.LINEAR),
|
||||
"example:second"));
|
||||
KList<IrisStructureSetFrequencyOverride> overrides = new KList<>();
|
||||
overrides.add(new IrisStructureSetFrequencyOverride()
|
||||
.setStructureSet("example:second")
|
||||
.setMultiplier(1.1D));
|
||||
IrisImportedStructureControl control = new IrisImportedStructureControl()
|
||||
.setFrequencyOverrides(overrides);
|
||||
NativeStructureFrequencies control = NativeStructureFrequencies.of(Map.of("example:second", 1.1D));
|
||||
|
||||
DatapackStructureStateFilter.Selection selection = DatapackStructureStateFilter.filter(
|
||||
List.of(first, second), index(List.of(), List.of()), Set.of(), control);
|
||||
@@ -306,12 +285,7 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
"example:custom",
|
||||
new CustomRandomSpreadPlacement(),
|
||||
structureHolder("example:custom"));
|
||||
KList<IrisStructureSetFrequencyOverride> overrides = new KList<>();
|
||||
overrides.add(new IrisStructureSetFrequencyOverride()
|
||||
.setStructureSet("example:custom")
|
||||
.setMultiplier(1.1D));
|
||||
IrisImportedStructureControl control = new IrisImportedStructureControl()
|
||||
.setFrequencyOverrides(overrides);
|
||||
NativeStructureFrequencies control = NativeStructureFrequencies.of(Map.of("example:custom", 1.1D));
|
||||
|
||||
DatapackStructureStateFilter.Selection selection = DatapackStructureStateFilter.filter(
|
||||
List.of(custom), index(List.of(), List.of()), Set.of(), control);
|
||||
@@ -388,7 +362,7 @@ public class NMSBindingDatapackStructureScopeTest {
|
||||
assertTrue(standardPublication > retention);
|
||||
assertTrue(immediateInitialization > standardPublication);
|
||||
assertFalse(method.contains("scopedState.ensureStructuresGenerated();"));
|
||||
assertFalse(method.contains("if (studioBootstrap && platformGenerator.isJigsawStudioActive())"));
|
||||
assertFalse(method.contains("if (studioBootstrap && platformGenerator.isPaintedStudioActive())"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+11
@@ -18,6 +18,17 @@ public class NMSBindingShutdownBoundaryContractTest {
|
||||
assertTrue(boundary.contains("server.getRunningThread()"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void chunkTaskPollingIsServerThreadOnlyAndSkipsFolia() throws Exception {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.nmsBindingSource"))).replace("\r\n", "\n");
|
||||
String polling = section(source, "public boolean pollChunkTask", "public void flushChunkIO");
|
||||
|
||||
int foliaGuard = polling.indexOf("J.isFolia()");
|
||||
int ownerGuard = polling.indexOf("level.getServer().getRunningThread()");
|
||||
int poll = polling.indexOf("level.getChunkSource().pollTask()");
|
||||
assertTrue(foliaGuard >= 0 && ownerGuard > foliaGuard && poll > ownerGuard);
|
||||
}
|
||||
|
||||
private static String section(String source, String startMarker, String endMarker) {
|
||||
int start = source.indexOf(startMarker);
|
||||
int end = source.indexOf(endMarker, start);
|
||||
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
package art.arcane.iris.core.nms.v26_2_R1;
|
||||
|
||||
import ca.spottedleaf.moonrise.common.util.TickThread;
|
||||
import com.mojang.serialization.Codec;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.IdMapper;
|
||||
import net.minecraft.core.SectionPos;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.level.ServerLevel;
|
||||
import net.minecraft.world.entity.ai.village.poi.PoiManager;
|
||||
import net.minecraft.world.entity.ai.village.poi.PoiRecord;
|
||||
import net.minecraft.world.entity.ai.village.poi.PoiSection;
|
||||
import net.minecraft.world.entity.ai.village.poi.PoiType;
|
||||
import net.minecraft.world.entity.ai.village.poi.PoiTypes;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.LevelHeightAccessor;
|
||||
import net.minecraft.world.level.WorldGenLevel;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.chunk.ImposterProtoChunk;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
import net.minecraft.world.level.chunk.PalettedContainer;
|
||||
import net.minecraft.world.level.chunk.PalettedContainerFactory;
|
||||
import net.minecraft.world.level.chunk.ProtoChunk;
|
||||
import net.minecraft.world.level.chunk.Strategy;
|
||||
import net.minecraft.world.level.chunk.UpgradeData;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.craftbukkit.persistence.CraftPersistentDataTypeRegistry;
|
||||
import org.bukkit.craftbukkit.persistence.DirtyCraftPersistentDataContainer;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.FutureTask;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class NativeStructurePoiUpdatesTest {
|
||||
private static final NamespacedKey DIRTY_SECTIONS = new NamespacedKey("iris", "native_poi_sections");
|
||||
|
||||
@BeforeClass
|
||||
public static void bootstrapMinecraftRegistries() {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void generationRecordsIntentBeforeSuppressingNativePoiCallbacks() {
|
||||
Fixture fixture = new Fixture();
|
||||
BlockPos position = new BlockPos(-31, 5, 49);
|
||||
doAnswer(call -> {
|
||||
assertNotNull(fixture.proto.persistentDataContainer.get(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY));
|
||||
assertEquals(Block.UPDATE_CLIENTS | 4096, (int) call.getArgument(2));
|
||||
fixture.proto.setBlockState(position, call.getArgument(1), 0);
|
||||
return true;
|
||||
}).when(fixture.world).setBlock(any(), any(), anyInt(), anyInt());
|
||||
|
||||
assertTrue(fixture.updates.setBlock(fixture.world, position,
|
||||
Blocks.COMPOSTER.defaultBlockState(), Block.UPDATE_CLIENTS, 17));
|
||||
assertArrayEquals(new long[]{16L}, fixture.marker());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void denseWritesStoreOneSectionBitAndSurvivePersistentDataRoundTrip() throws Exception {
|
||||
Fixture fixture = new Fixture();
|
||||
for (int z = 0; z < 16; z++) {
|
||||
for (int x = 0; x < 16; x++) {
|
||||
fixture.write(new BlockPos(-32 + x, 5, 48 + z), Blocks.COMPOSTER.defaultBlockState());
|
||||
}
|
||||
}
|
||||
assertArrayEquals(new long[]{16L}, fixture.marker());
|
||||
DirtyCraftPersistentDataContainer restored = new DirtyCraftPersistentDataContainer(new CraftPersistentDataTypeRegistry());
|
||||
restored.putAll(fixture.proto.persistentDataContainer.toTagCompound());
|
||||
fixture.loaded.persistentDataContainer = restored;
|
||||
|
||||
onOwner(() -> NativeStructurePoiUpdates.reconcile(fixture.loaded));
|
||||
|
||||
assertEquals(256L, fixture.records().getRecords(type -> true, PoiManager.Occupancy.ANY).count());
|
||||
assertFalse(restored.has(DIRTY_SECTIONS));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void validSectionsReconcileFinalStatesAndKeepMatchingClaimedTickets() throws Exception {
|
||||
Fixture fixture = new Fixture();
|
||||
BlockPos retained = new BlockPos(-31, 5, 49);
|
||||
BlockPos replaced = new BlockPos(-30, 5, 49);
|
||||
BlockPos removed = new BlockPos(-29, 5, 49);
|
||||
Holder<PoiType> farmer = PoiTypes.forState(Blocks.COMPOSTER.defaultBlockState()).orElseThrow();
|
||||
PoiSection existing = new PoiSection.Packed(true, List.of(
|
||||
new PoiRecord.Packed(retained, farmer, 0),
|
||||
new PoiRecord.Packed(replaced, farmer, 1),
|
||||
new PoiRecord.Packed(removed, farmer, 1))).unpack(() -> {});
|
||||
fixture.pois.put(SectionPos.of(retained).asLong(), existing);
|
||||
PoiRecord retainedRecord = existing.getRecords(type -> true, PoiManager.Occupancy.ANY)
|
||||
.filter(record -> record.getPos().equals(retained)).findFirst().orElseThrow();
|
||||
for (BlockPos position : List.of(retained, replaced, removed)) {
|
||||
fixture.proto.setBlockState(position, Blocks.COMPOSTER.defaultBlockState(), 0);
|
||||
}
|
||||
fixture.write(replaced, Blocks.BARREL.defaultBlockState());
|
||||
fixture.write(removed, Blocks.AIR.defaultBlockState());
|
||||
|
||||
onOwner(() -> NativeStructurePoiUpdates.reconcile(fixture.loaded));
|
||||
|
||||
assertEquals(PoiTypes.forState(Blocks.BARREL.defaultBlockState()), existing.getType(replaced));
|
||||
assertTrue(existing.getType(removed).isEmpty());
|
||||
assertSame(retainedRecord, existing.getRecords(type -> true, PoiManager.Occupancy.ANY)
|
||||
.filter(record -> record.getPos().equals(retained)).findFirst().orElseThrow());
|
||||
assertEquals(0, existing.getFreeTickets(retained));
|
||||
onOwner(() -> NativeStructurePoiUpdates.reconcile(fixture.loaded));
|
||||
assertEquals(0, existing.getFreeTickets(retained));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void failedReconciliationRetainsIntentForRetry() throws Exception {
|
||||
Fixture fixture = new Fixture();
|
||||
fixture.write(new BlockPos(-31, 5, 49), Blocks.COMPOSTER.defaultBlockState());
|
||||
IllegalStateException failure = new IllegalStateException("POI storage failure");
|
||||
doThrow(failure).when(fixture.manager).add(any(), any());
|
||||
|
||||
onOwner(() -> assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> NativeStructurePoiUpdates.reconcile(fixture.loaded))));
|
||||
|
||||
assertArrayEquals(new long[]{16L}, fixture.marker());
|
||||
fixture.allowPoiAdds();
|
||||
onOwner(() -> NativeStructurePoiUpdates.reconcile(fixture.loaded));
|
||||
assertFalse(fixture.proto.persistentDataContainer.has(DIRTY_SECTIONS));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void explicitPoiSuppressionAndReadOnlyFullChunksDoNotCreateIntent() {
|
||||
Fixture fixture = new Fixture();
|
||||
BlockPos position = new BlockPos(-31, 5, 49);
|
||||
fixture.updates.setBlock(fixture.world, position, Blocks.COMPOSTER.defaultBlockState(),
|
||||
4096, 17);
|
||||
assertFalse(fixture.proto.persistentDataContainer.has(DIRTY_SECTIONS));
|
||||
ImposterProtoChunk full = mock(ImposterProtoChunk.class);
|
||||
when(fixture.world.getChunk(any(BlockPos.class))).thenReturn(full);
|
||||
fixture.updates.setBlock(fixture.world, position, Blocks.BARREL.defaultBlockState(), 2, 17);
|
||||
assertFalse(fixture.proto.persistentDataContainer.has(DIRTY_SECTIONS));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void invalidSectionBitsRetainTheStoredRecord() throws Exception {
|
||||
Fixture fixture = new Fixture();
|
||||
fixture.proto.persistentDataContainer.set(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY, new long[]{1L << 24});
|
||||
onOwner(() -> assertThrows(IllegalArgumentException.class,
|
||||
() -> NativeStructurePoiUpdates.reconcile(fixture.loaded)));
|
||||
assertArrayEquals(new long[]{1L << 24}, fixture.marker());
|
||||
}
|
||||
|
||||
private static void onOwner(Runnable action) throws Exception {
|
||||
FutureTask<Void> task = new FutureTask<>(action, null);
|
||||
new TickThread(task, "Native POI test").start();
|
||||
task.get(5L, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
private static PalettedContainerFactory containerFactory() {
|
||||
Strategy<BlockState> blocks = Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY);
|
||||
BlockState air = Blocks.AIR.defaultBlockState();
|
||||
IdMapper<Holder<Biome>> biomeIds = new IdMapper<>();
|
||||
Holder<Biome> biome = Holder.direct((Biome) null);
|
||||
biomeIds.add(biome);
|
||||
Strategy<Holder<Biome>> biomes = Strategy.createForBiomes(biomeIds);
|
||||
Codec<Holder<Biome>> biomeCodec = Codec.STRING.xmap(name -> biome, holder -> "iris-test-biome");
|
||||
return new PalettedContainerFactory(blocks, air, PalettedContainer.codecRW(BlockState.CODEC, blocks, air),
|
||||
biomes, biome, PalettedContainer.codecRO(biomeCodec, biomes, biome),
|
||||
PalettedContainer.codecRW(biomeCodec, biomes, biome));
|
||||
}
|
||||
|
||||
private static final class Fixture {
|
||||
private final NativeStructurePoiUpdates updates = new NativeStructurePoiUpdates(4096);
|
||||
private final ProtoChunk proto = new ProtoChunk(new ChunkPos(-2, 3), UpgradeData.EMPTY,
|
||||
LevelHeightAccessor.create(-64, 384), containerFactory(), null);
|
||||
private final LevelChunk loaded = mock(LevelChunk.class);
|
||||
private final WorldGenLevel world = mock(WorldGenLevel.class);
|
||||
private final PoiManager manager = mock(PoiManager.class);
|
||||
private final Map<Long, PoiSection> pois = new HashMap<>();
|
||||
|
||||
private Fixture() {
|
||||
ServerLevel level = mock(ServerLevel.class);
|
||||
when(level.getPoiManager()).thenReturn(manager);
|
||||
loaded.persistentDataContainer = proto.persistentDataContainer;
|
||||
when(loaded.getLevel()).thenReturn(level);
|
||||
when(loaded.getPos()).thenReturn(proto.getPos());
|
||||
when(loaded.getSectionsCount()).thenReturn(proto.getSectionsCount());
|
||||
when(loaded.getSectionYFromSectionIndex(anyInt())).thenAnswer(call -> proto.getSectionYFromSectionIndex(call.getArgument(0)));
|
||||
when(loaded.getSection(anyInt())).thenAnswer(call -> proto.getSection(call.getArgument(0)));
|
||||
when(loaded.getBlockState(any())).thenAnswer(call -> proto.getBlockState(call.getArgument(0)));
|
||||
when(world.getChunk(any(BlockPos.class))).thenReturn(proto);
|
||||
when(world.setBlock(any(), any(), anyInt(), anyInt())).thenAnswer(call -> {
|
||||
proto.setBlockState(call.getArgument(0), call.getArgument(1), call.getArgument(2));
|
||||
return true;
|
||||
});
|
||||
when(manager.getOrLoad(anyLong())).thenAnswer(call -> Optional.ofNullable(pois.get((long) call.getArgument(0))));
|
||||
when(manager.getType(any())).thenAnswer(call -> {
|
||||
BlockPos position = call.getArgument(0);
|
||||
PoiSection section = pois.get(SectionPos.of(position).asLong());
|
||||
return section == null ? Optional.empty() : section.getType(position);
|
||||
});
|
||||
doAnswer(call -> {
|
||||
BlockPos position = call.getArgument(0);
|
||||
pois.get(SectionPos.of(position).asLong()).remove(position);
|
||||
return null;
|
||||
}).when(manager).remove(any());
|
||||
allowPoiAdds();
|
||||
}
|
||||
|
||||
private void allowPoiAdds() {
|
||||
doAnswer(call -> {
|
||||
BlockPos position = call.getArgument(0);
|
||||
return pois.computeIfAbsent(SectionPos.of(position).asLong(), ignored -> new PoiSection(() -> {}))
|
||||
.add(position, call.getArgument(1));
|
||||
}).when(manager).add(any(), any());
|
||||
}
|
||||
|
||||
private void write(BlockPos position, BlockState state) {
|
||||
updates.setBlock(world, position, state, Block.UPDATE_CLIENTS, Block.UPDATE_LIMIT);
|
||||
}
|
||||
|
||||
private long[] marker() {
|
||||
return proto.persistentDataContainer.get(DIRTY_SECTIONS, PersistentDataType.LONG_ARRAY);
|
||||
}
|
||||
|
||||
private PoiSection records() {
|
||||
return pois.get(SectionPos.of(new BlockPos(-31, 5, 49)).asLong());
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-10
@@ -54,13 +54,14 @@ public class VillageImporterListPoolElementRuntimeContractTest {
|
||||
StructureTemplatePool.Projection.RIGID
|
||||
);
|
||||
|
||||
VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(towers);
|
||||
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(towers);
|
||||
Map<String, Object> entry = VillageImporter.piecePoolEntry(
|
||||
"qa/pillager_outpost/piece/minecraft/pillager_outpost/watchtower",
|
||||
1
|
||||
);
|
||||
StructureLoss loss = VillageImporter.listElementFallbackLoss(
|
||||
resolution,
|
||||
resolution.listLevels(),
|
||||
resolution.omittedElements(),
|
||||
"minecraft:pillager_outpost/towers"
|
||||
);
|
||||
Map<String, Object> basePlatePiece = VillageImporter.pieceJson(
|
||||
@@ -103,7 +104,7 @@ public class VillageImporterListPoolElementRuntimeContractTest {
|
||||
StructurePoolElement waystone = StructurePoolElement
|
||||
.legacy("dungeons_and_taverns:waystones/waystone_scaffold")
|
||||
.apply(StructureTemplatePool.Projection.RIGID);
|
||||
VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(waystone);
|
||||
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(waystone);
|
||||
VillageImporter.PoolMemberNormalization normalization = VillageImporter.normalizePoolMember(
|
||||
"dungeons_and_taverns:waystones",
|
||||
"qa/pool/dungeons_and_taverns/waystones",
|
||||
@@ -130,7 +131,7 @@ public class VillageImporterListPoolElementRuntimeContractTest {
|
||||
StructurePoolElement orphan = StructurePoolElement
|
||||
.legacy("test:orphan_house")
|
||||
.apply(StructureTemplatePool.Projection.RIGID);
|
||||
VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(orphan);
|
||||
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(orphan);
|
||||
VillageImporter.PoolMemberNormalization normalization = VillageImporter.normalizePoolMember(
|
||||
"test:orphan_pool",
|
||||
"qa/pool/test/orphan_pool",
|
||||
@@ -160,7 +161,7 @@ public class VillageImporterListPoolElementRuntimeContractTest {
|
||||
StructurePoolElement start = StructurePoolElement
|
||||
.legacy("test:air_start")
|
||||
.apply(StructureTemplatePool.Projection.RIGID);
|
||||
VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(start);
|
||||
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(start);
|
||||
VillageImporter.PoolMemberNormalization normalization = VillageImporter.normalizePoolMember(
|
||||
"test:start",
|
||||
"qa/pool/test/start",
|
||||
@@ -184,7 +185,7 @@ public class VillageImporterListPoolElementRuntimeContractTest {
|
||||
StructurePoolElement inert = StructurePoolElement
|
||||
.legacy("test:mixed_air_inert")
|
||||
.apply(StructureTemplatePool.Projection.RIGID);
|
||||
VillageImporter.PoolElementResolution resolution = VillageImporter.resolvePoolElement(inert);
|
||||
PoolElementReader.PoolElementResolution resolution = PoolElementReader.resolvePoolElement(inert);
|
||||
VillageImporter.PoolMemberNormalization normalization = VillageImporter.normalizePoolMember(
|
||||
"test:mixed",
|
||||
"qa/pool/test/mixed",
|
||||
@@ -214,8 +215,8 @@ public class VillageImporterListPoolElementRuntimeContractTest {
|
||||
StructurePoolElement nonAirElement = StructurePoolElement
|
||||
.legacy("test:mixed_non_air_primary")
|
||||
.apply(StructureTemplatePool.Projection.RIGID);
|
||||
VillageImporter.PoolElementResolution allAirResolution = VillageImporter.resolvePoolElement(allAirElement);
|
||||
VillageImporter.PoolElementResolution nonAirResolution = VillageImporter.resolvePoolElement(nonAirElement);
|
||||
PoolElementReader.PoolElementResolution allAirResolution = PoolElementReader.resolvePoolElement(allAirElement);
|
||||
PoolElementReader.PoolElementResolution nonAirResolution = PoolElementReader.resolvePoolElement(nonAirElement);
|
||||
VillageImporter.PoolMemberNormalization allAir = VillageImporter.normalizePoolMember(
|
||||
"test:mixed",
|
||||
"qa/pool/test/mixed",
|
||||
@@ -257,8 +258,8 @@ public class VillageImporterListPoolElementRuntimeContractTest {
|
||||
StructurePoolElement nonAirElement = StructurePoolElement
|
||||
.legacy("test:non_air_primary")
|
||||
.apply(StructureTemplatePool.Projection.RIGID);
|
||||
VillageImporter.PoolElementResolution allAirResolution = VillageImporter.resolvePoolElement(allAirElement);
|
||||
VillageImporter.PoolElementResolution nonAirResolution = VillageImporter.resolvePoolElement(nonAirElement);
|
||||
PoolElementReader.PoolElementResolution allAirResolution = PoolElementReader.resolvePoolElement(allAirElement);
|
||||
PoolElementReader.PoolElementResolution nonAirResolution = PoolElementReader.resolvePoolElement(nonAirElement);
|
||||
VillageImporter.PoolMemberNormalization allAir = VillageImporter.normalizePoolMember(
|
||||
"test:primary",
|
||||
"qa/pool/test/primary",
|
||||
|
||||
+6
-5
@@ -1,7 +1,7 @@
|
||||
package art.arcane.iris.nativegen;
|
||||
|
||||
import art.arcane.iris.engine.object.IrisJigsawConfiguration;
|
||||
import art.arcane.iris.engine.object.IrisStructureTerrain;
|
||||
import art.arcane.iris.engine.framework.NativeJigsawOverrides;
|
||||
import art.arcane.iris.engine.framework.NativeStructureReach;
|
||||
import com.mojang.datafixers.util.Either;
|
||||
import com.mojang.datafixers.util.Pair;
|
||||
import com.mojang.serialization.MapCodec;
|
||||
@@ -98,7 +98,8 @@ public class NativeStructureFactoryTest {
|
||||
new Structure.StructureSettings(HolderSet.empty()));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> NativeStructureFactory.configure(
|
||||
null, source, new IrisJigsawConfiguration(), false, 80));
|
||||
null, source, new NativeJigsawOverrides("", "", null, null, null, null,
|
||||
NativeJigsawOverrides.SOURCE, null, null, NativeJigsawOverrides.SOURCE), false, 80));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -303,11 +304,11 @@ public class NativeStructureFactoryTest {
|
||||
);
|
||||
|
||||
StructureStart boundaryResult = NativeStructureReferenceEnvelope.wrapForPublication(
|
||||
boundary, source, 0, new IrisStructureTerrain(), "test:boundary_content");
|
||||
boundary, source, 0, List.of(NativeStructureReach.PLATFORM), "test:boundary_content");
|
||||
|
||||
StructureStart result = NativeStructureReferenceEnvelope.wrapForPublication(
|
||||
oversized, source, 0,
|
||||
new IrisStructureTerrain(),
|
||||
List.of(NativeStructureReach.PLATFORM),
|
||||
"test:oversized_content");
|
||||
|
||||
assertTrue(boundaryResult.isValid());
|
||||
|
||||
+1219
File diff suppressed because it is too large.
Load diff
+571
@@ -0,0 +1,571 @@
|
||||
package art.arcane.iris.nativegen;
|
||||
|
||||
import art.arcane.iris.engine.framework.NativeStartMemo;
|
||||
import art.arcane.iris.engine.mantle.components.StructureModule;
|
||||
import art.arcane.iris.engine.framework.nativefit.NativeStructureFitting;
|
||||
import com.mojang.datafixers.util.Either;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.WorldGenLevel;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.Rotation;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.levelgen.GenerationStep;
|
||||
import net.minecraft.world.level.levelgen.structure.BoundingBox;
|
||||
import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraft.world.level.levelgen.structure.StructurePiece;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureStart;
|
||||
import net.minecraft.world.level.levelgen.structure.TerrainAdjustment;
|
||||
import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer;
|
||||
import net.minecraft.world.level.levelgen.structure.pools.JigsawJunction;
|
||||
import net.minecraft.world.level.levelgen.structure.pools.LegacySinglePoolElement;
|
||||
import net.minecraft.world.level.levelgen.structure.pools.SinglePoolElement;
|
||||
import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElement;
|
||||
import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool;
|
||||
import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidPiece;
|
||||
import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidStructure;
|
||||
import net.minecraft.world.level.levelgen.structure.templatesystem.LiquidSettings;
|
||||
import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings;
|
||||
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorList;
|
||||
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.IntBinaryOperator;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* Pins the blocks the native structure fit leaves in one decorated chunk for each terrain mode, so the fit can move
|
||||
* without changing what a world generates. Every scenario builds an uneven terrain with water, caves, ores and trees,
|
||||
* starts with real pieces and inline templates, and fit records written the way ownership records persist them. It
|
||||
* then runs the chunk's fit in the generator's order (terrain fitting for every start, then each start's pieces and
|
||||
* stilts, then the foundation repair) with a fixed stand-in for the platform's piece placement, and hashes every block
|
||||
* that differs from the untouched terrain. The hashes were taken from the platform-side fit before it moved into the
|
||||
* structure module; they now run through the platform bridge and the built-in modules.
|
||||
*/
|
||||
public class NativeStructureFitPinTest {
|
||||
private static final long WORLD_SEED = 8675309L;
|
||||
private static final int SEA_LEVEL = 61;
|
||||
private static final int WORLD_MIN_Y = -64;
|
||||
private static final int WORLD_HEIGHT = 384;
|
||||
private static final BoundingBox CHUNK_AREA = new BoundingBox(0, WORLD_MIN_Y + 1, 0, 15, WORLD_MIN_Y + WORLD_HEIGHT - 2, 15);
|
||||
private static final String NO_STILTS = "null";
|
||||
private static final String SOURCE_TERRAIN = "{}";
|
||||
|
||||
private static final Map<String, String> PINNED = Map.ofEntries(
|
||||
Map.entry("encase", "1371:5448f4c7083265eaa032022d"),
|
||||
Map.entry("source-bury", "1662:a826097850d8e5e4ebe324d7"),
|
||||
Map.entry("source-encapsulate", "4907:206093fc3b11fe5e4678a04d"),
|
||||
Map.entry("source-beard", "721:bc95c2ac5138738846f342fd"),
|
||||
Map.entry("vacuum", "667:302305ab38330cc32cd42123"),
|
||||
Map.entry("carve", "11573:7c238685fe13c6a7c115863c"),
|
||||
Map.entry("stilts", "903:9c949d85eb9882f87f478478")
|
||||
);
|
||||
|
||||
@BeforeClass
|
||||
public static void bootstrapMinecraft() {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void everyScenarioLeavesThePinnedBlocks() throws Exception {
|
||||
Map<String, String> actual = new LinkedHashMap<>();
|
||||
actual.put("encase", fit(encase()));
|
||||
actual.put("source-bury", fit(sourceBury()));
|
||||
actual.put("source-encapsulate", fit(sourceEncapsulate()));
|
||||
actual.put("source-beard", fit(sourceBeard()));
|
||||
actual.put("vacuum", fit(vacuum()));
|
||||
actual.put("carve", fit(carve()));
|
||||
actual.put("stilts", fit(stilts()));
|
||||
StringBuilder report = new StringBuilder();
|
||||
actual.forEach((name, hash) -> report.append(" Map.entry(\"").append(name)
|
||||
.append("\", \"").append(hash).append("\"),\n"));
|
||||
assertEquals("Pinned fit hashes changed:\n" + report, PINNED, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void everyScenarioChangesTheTerrain() throws Exception {
|
||||
for (Scenario scenario : List.of(encase(), sourceBury(), sourceEncapsulate(), sourceBeard(), vacuum(), carve(), stilts())) {
|
||||
String hash = fit(scenario);
|
||||
assertTrue(scenario.name() + " left the terrain untouched", !hash.startsWith("0:"));
|
||||
}
|
||||
}
|
||||
|
||||
private static String fit(Scenario scenario) throws Exception {
|
||||
TerrainWorld terrain = new TerrainWorld();
|
||||
WorldGenLevel world = terrain.level();
|
||||
fitChunk(world, scenario);
|
||||
return terrain.changedBlocksHash(CHUNK_AREA);
|
||||
}
|
||||
|
||||
/**
|
||||
* The chunk's fit in the order the generators run it, through the platform bridge and the built-in modules: the
|
||||
* fit before any piece, then each start's pieces ({@link #placePieces}) and its fit after them.
|
||||
*/
|
||||
private static void fitChunk(WorldGenLevel world, Scenario scenario) {
|
||||
List<NativeStructureFitBridge.FitTarget> targets = new ArrayList<>();
|
||||
for (FitTarget target : scenario.targets()) {
|
||||
targets.add(new NativeStructureFitBridge.FitTarget(target.structureId(), target.start(),
|
||||
new NativeStartMemo("{\"terrain\":" + target.terrainJson() + ",\"stilts\":" + target.stiltJson() + "}")));
|
||||
}
|
||||
NativeStructureFitting.Session fit = BuiltInFitting.FITTING.beforePieces(
|
||||
NativeStructureFitBridge.chunk(world, CHUNK_AREA, targets, TerrainWorld::surfaceY));
|
||||
for (int index = 0; index < targets.size(); index++) {
|
||||
placePieces(world, scenario.targets().get(index));
|
||||
fit.afterPieces(index);
|
||||
}
|
||||
}
|
||||
|
||||
/** The built-in modules load once for every scenario. */
|
||||
private static final class BuiltInFitting {
|
||||
private static final NativeStructureFitting FITTING = NativeStructureFitting.ofModules(new StructureModule());
|
||||
}
|
||||
|
||||
/**
|
||||
* A fixed stand-in for the platform placing a start's pieces in the chunk: template pieces write their template
|
||||
* blocks turned with the piece (jigsaws as air, structure voids not at all), other pieces a sandstone floor and
|
||||
* walls. Only blocks inside the chunk are written, as the platform clips them.
|
||||
*/
|
||||
private static void placePieces(WorldGenLevel world, FitTarget target) {
|
||||
BlockPos.MutableBlockPos position = new BlockPos.MutableBlockPos();
|
||||
for (StructurePiece piece : target.start().getPieces()) {
|
||||
List<StructureTemplate.StructureBlockInfo> blocks = target.templates().get(piece);
|
||||
if (blocks == null) {
|
||||
placeShell(world, piece.getBoundingBox(), position);
|
||||
continue;
|
||||
}
|
||||
PoolElementStructurePiece poolPiece = (PoolElementStructurePiece) piece;
|
||||
StructurePlaceSettings settings = new StructurePlaceSettings().setRotation(poolPiece.getRotation());
|
||||
for (StructureTemplate.StructureBlockInfo block : blocks) {
|
||||
if (block.state().is(Blocks.STRUCTURE_VOID)) {
|
||||
continue;
|
||||
}
|
||||
BlockPos at = poolPiece.getPosition().offset(StructureTemplate.calculateRelativePosition(settings, block.pos()));
|
||||
if (!CHUNK_AREA.isInside(at)) {
|
||||
continue;
|
||||
}
|
||||
BlockState state = block.state().is(Blocks.JIGSAW)
|
||||
? Blocks.AIR.defaultBlockState() : block.state().rotate(poolPiece.getRotation());
|
||||
world.setBlock(position.set(at), state, 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void placeShell(WorldGenLevel world, BoundingBox box, BlockPos.MutableBlockPos position) {
|
||||
for (int x = box.minX(); x <= box.maxX(); x++) {
|
||||
for (int z = box.minZ(); z <= box.maxZ(); z++) {
|
||||
for (int y = box.minY(); y <= Math.min(box.maxY(), box.minY() + 3); y++) {
|
||||
boolean wall = x == box.minX() || x == box.maxX() || z == box.minZ() || z == box.maxZ();
|
||||
if ((y == box.minY() || wall) && CHUNK_AREA.isInside(position.set(x, y, z))) {
|
||||
world.setBlock(position, Blocks.SANDSTONE.defaultBlockState(), 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Scenario encase() {
|
||||
return new Scenario("encase", List.of(
|
||||
pyramid("minecraft:stronghold", GenerationStep.Decoration.STRONGHOLDS, TerrainAdjustment.BURY, 2, 2, 14,
|
||||
NO_STILTS, "{\"mode\":\"ENCASE\",\"horizontalPadding\":2,\"ceilingPadding\":2,\"floorPadding\":1}"),
|
||||
pyramid("minecraft:trial_chambers", GenerationStep.Decoration.UNDERGROUND_STRUCTURES, TerrainAdjustment.ENCAPSULATE,
|
||||
4, -12, -8, NO_STILTS, "{\"mode\":\"ENCASE\"}")));
|
||||
}
|
||||
|
||||
private static Scenario sourceBury() {
|
||||
TemplateStart start = new TemplateStart("minecraft:ancient_city", GenerationStep.Decoration.UNDERGROUND_STRUCTURES,
|
||||
TerrainAdjustment.BURY);
|
||||
PoolElementStructurePiece room = start.single(room(7, 5, 7), new BoundingBox(2, 30, 2, 8, 34, 8), 1, Rotation.NONE);
|
||||
room.addJunction(new JigsawJunction(5, 31, 9, 0, StructureTemplatePool.Projection.RIGID));
|
||||
start.single(path(3, 5), new BoundingBox(6, 31, 9, 8, 31, 13), 0, Rotation.NONE,
|
||||
StructureTemplatePool.Projection.TERRAIN_MATCHING);
|
||||
start.legacy(airPocket(4, 4, 4), new BoundingBox(10, 28, 10, 13, 31, 13), 1, Rotation.NONE);
|
||||
start.single(room(5, 6, 4), new BoundingBox(1, 58, 11, 5, 63, 14), 1, Rotation.NONE);
|
||||
return new Scenario("source-bury", List.of(start.target(NO_STILTS, SOURCE_TERRAIN)));
|
||||
}
|
||||
|
||||
private static Scenario sourceEncapsulate() {
|
||||
return new Scenario("source-encapsulate", List.of(
|
||||
pyramid("minecraft:ocean_ruin_cold", GenerationStep.Decoration.SURFACE_STRUCTURES, TerrainAdjustment.ENCAPSULATE,
|
||||
-3, 1, 55, NO_STILTS, SOURCE_TERRAIN)));
|
||||
}
|
||||
|
||||
private static Scenario sourceBeard() {
|
||||
TemplateStart village = new TemplateStart("minecraft:village_plains", GenerationStep.Decoration.SURFACE_STRUCTURES,
|
||||
TerrainAdjustment.BEARD_THIN);
|
||||
PoolElementStructurePiece house = village.single(room(6, 6, 6), new BoundingBox(1, 64, 1, 6, 69, 6), 1, Rotation.NONE);
|
||||
house.addJunction(new JigsawJunction(7, 63, 3, 0, StructureTemplatePool.Projection.TERRAIN_MATCHING));
|
||||
PoolElementStructurePiece road = village.single(path(3, 8), new BoundingBox(7, 63, 2, 9, 63, 9), 0, Rotation.NONE,
|
||||
StructureTemplatePool.Projection.TERRAIN_MATCHING);
|
||||
road.addJunction(new JigsawJunction(8, 63, 10, 0, StructureTemplatePool.Projection.RIGID));
|
||||
village.single(room(5, 5, 5), new BoundingBox(9, 60, 9, 13, 64, 13), 1, Rotation.NONE);
|
||||
village.single(floor(3, 3), new BoundingBox(10, 62, 10, 12, 66, 12), 1, Rotation.NONE);
|
||||
village.legacy(airPocket(3, 3, 3), new BoundingBox(2, 65, 11, 4, 67, 13), 1, Rotation.NONE);
|
||||
return new Scenario("source-beard", List.of(
|
||||
village.target(NO_STILTS, SOURCE_TERRAIN),
|
||||
pyramid("minecraft:desert_pyramid", GenerationStep.Decoration.SURFACE_STRUCTURES, TerrainAdjustment.BEARD_BOX,
|
||||
-14, 9, 61, NO_STILTS, SOURCE_TERRAIN)));
|
||||
}
|
||||
|
||||
private static Scenario vacuum() {
|
||||
TemplateStart village = new TemplateStart("minecraft:village_taiga", GenerationStep.Decoration.SURFACE_STRUCTURES,
|
||||
TerrainAdjustment.NONE);
|
||||
PoolElementStructurePiece houseA = village.single(room(5, 5, 5), new BoundingBox(2, 68, 2, 6, 72, 6), 1, Rotation.NONE);
|
||||
houseA.addJunction(new JigsawJunction(7, 66, 6, 0, StructureTemplatePool.Projection.RIGID));
|
||||
village.single(voidedRoom(4, 4, 4), new BoundingBox(9, 65, 8, 12, 68, 11), 1, Rotation.CLOCKWISE_90);
|
||||
village.single(path(2, 6), new BoundingBox(7, 64, 1, 8, 64, 6), 0, Rotation.NONE,
|
||||
StructureTemplatePool.Projection.TERRAIN_MATCHING);
|
||||
village.single(room(4, 3, 4), new BoundingBox(13, 70, 12, 16, 72, 15), 1, Rotation.NONE);
|
||||
return new Scenario("vacuum", List.of(
|
||||
village.target(NO_STILTS, "{\"mode\":\"VACUUM\"}"),
|
||||
pyramid("minecraft:igloo", GenerationStep.Decoration.SURFACE_STRUCTURES, TerrainAdjustment.BEARD_THIN,
|
||||
8, -10, 64, NO_STILTS, "{\"mode\":\"PRESERVE\"}")));
|
||||
}
|
||||
|
||||
private static Scenario carve() {
|
||||
TemplateStart eroded = new TemplateStart("minecraft:mineshaft", GenerationStep.Decoration.UNDERGROUND_STRUCTURES,
|
||||
TerrainAdjustment.NONE);
|
||||
eroded.single(room(6, 5, 6), new BoundingBox(3, 2, 3, 8, 6, 8), 1, Rotation.NONE);
|
||||
eroded.single(voidedRoom(4, 4, 4), new BoundingBox(9, 4, 2, 12, 7, 5), 1, Rotation.NONE);
|
||||
return new Scenario("carve", List.of(
|
||||
eroded.target(NO_STILTS, "{\"mode\":\"FORCE_CARVE\",\"shape\":\"ERODED\",\"horizontalPadding\":6,"
|
||||
+ "\"ceilingPadding\":4,\"floorPadding\":1,\"erosionStrength\":0.9,\"erosionFrequency\":0.08,\"lobeStrength\":0.7}"),
|
||||
pyramid("minecraft:buried_treasure", GenerationStep.Decoration.UNDERGROUND_STRUCTURES, TerrainAdjustment.NONE,
|
||||
-6, 4, 30, NO_STILTS, "{\"mode\":\"BORE\",\"horizontalPadding\":2,\"ceilingPadding\":3}"),
|
||||
pyramid("minecraft:trail_ruins", GenerationStep.Decoration.UNDERGROUND_STRUCTURES, TerrainAdjustment.NONE,
|
||||
2, -9, -40, NO_STILTS, "{\"mode\":\"FORCE_CARVE\",\"shape\":\"ROUNDED\",\"horizontalPadding\":3,"
|
||||
+ "\"ceilingPadding\":2,\"floorPadding\":2}"),
|
||||
pyramid("minecraft:swamp_hut", GenerationStep.Decoration.UNDERGROUND_STRUCTURES, TerrainAdjustment.NONE,
|
||||
-10, -2, 44, NO_STILTS, "{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":1,\"floorPadding\":1}")));
|
||||
}
|
||||
|
||||
private static Scenario stilts() {
|
||||
TemplateStart hut = new TemplateStart("minecraft:pillager_outpost", GenerationStep.Decoration.SURFACE_STRUCTURES,
|
||||
TerrainAdjustment.NONE);
|
||||
hut.single(room(5, 4, 5), new BoundingBox(9, 71, 1, 13, 74, 5), 1, Rotation.NONE);
|
||||
hut.single(floor(4, 4), new BoundingBox(1, 69, 10, 4, 72, 13), 1, Rotation.COUNTERCLOCKWISE_90);
|
||||
return new Scenario("stilts", List.of(
|
||||
pyramid("minecraft:jungle_pyramid", GenerationStep.Decoration.SURFACE_STRUCTURES, TerrainAdjustment.NONE,
|
||||
-12, -14, 70, "{\"maxDepth\":16,\"spacing\":2,\"palette\":null}", "{\"mode\":\"PRESERVE\"}"),
|
||||
pyramid("minecraft:stronghold", GenerationStep.Decoration.STRONGHOLDS, TerrainAdjustment.NONE,
|
||||
-2, -3, 24, "{\"maxDepth\":6,\"spacing\":1,\"palette\":null}", "{\"mode\":\"PRESERVE\"}"),
|
||||
hut.target("{\"maxDepth\":64,\"spacing\":1,\"palette\":null}", "{\"mode\":\"VACUUM\"}")));
|
||||
}
|
||||
|
||||
private static FitTarget pyramid(String structureId, GenerationStep.Decoration step, TerrainAdjustment adjustment,
|
||||
int x, int z, int minY, String stiltJson, String terrainJson) {
|
||||
StructurePiece piece = new DesertPyramidPiece(RandomSource.create(7L), x, z);
|
||||
piece.move(0, minY - piece.getBoundingBox().minY(), 0);
|
||||
StructureStart start = new StructureStart(structure(step, adjustment), new ChunkPos(0, 0), 0,
|
||||
new PiecesContainer(List.of(piece)));
|
||||
return new FitTarget(structureId, start, Map.of(), stiltJson, terrainJson);
|
||||
}
|
||||
|
||||
private static Structure structure(GenerationStep.Decoration step, TerrainAdjustment adjustment) {
|
||||
return new DesertPyramidStructure(new Structure.StructureSettings(HolderSet.empty(), Map.of(), step, adjustment));
|
||||
}
|
||||
|
||||
/** A room: a stone floor, plank walls with a doorway and a glass window, air inside, a slab roof. */
|
||||
private static List<StructureTemplate.StructureBlockInfo> room(int width, int height, int depth) {
|
||||
List<StructureTemplate.StructureBlockInfo> blocks = new ArrayList<>();
|
||||
for (int x = 0; x < width; x++) {
|
||||
for (int z = 0; z < depth; z++) {
|
||||
for (int y = 0; y < height; y++) {
|
||||
boolean wall = x == 0 || z == 0 || x == width - 1 || z == depth - 1;
|
||||
BlockState state;
|
||||
if (y == 0) {
|
||||
state = Blocks.COBBLESTONE.defaultBlockState();
|
||||
} else if (y == height - 1) {
|
||||
state = Blocks.OAK_SLAB.defaultBlockState();
|
||||
} else if (wall && x == width / 2 && z == 0 && y < 3) {
|
||||
state = Blocks.AIR.defaultBlockState();
|
||||
} else if (wall) {
|
||||
state = y == 2 && z == depth / 2 ? Blocks.GLASS.defaultBlockState() : Blocks.OAK_PLANKS.defaultBlockState();
|
||||
} else {
|
||||
state = Blocks.AIR.defaultBlockState();
|
||||
}
|
||||
blocks.add(block(x, y, z, state));
|
||||
}
|
||||
}
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
/** A room whose middle columns are structure void and whose corner holds a jigsaw. */
|
||||
private static List<StructureTemplate.StructureBlockInfo> voidedRoom(int width, int height, int depth) {
|
||||
List<StructureTemplate.StructureBlockInfo> blocks = new ArrayList<>();
|
||||
for (StructureTemplate.StructureBlockInfo block : room(width, height, depth)) {
|
||||
BlockPos pos = block.pos();
|
||||
boolean middle = pos.getX() > 0 && pos.getX() < width - 1 && pos.getZ() > 0 && pos.getZ() < depth - 1;
|
||||
if (middle && pos.getY() > 0) {
|
||||
blocks.add(block(pos.getX(), pos.getY(), pos.getZ(), Blocks.STRUCTURE_VOID.defaultBlockState()));
|
||||
} else if (pos.getX() == 0 && pos.getZ() == 0 && pos.getY() == 0) {
|
||||
blocks.add(block(0, 0, 0, Blocks.JIGSAW.defaultBlockState()));
|
||||
} else {
|
||||
blocks.add(block);
|
||||
}
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
private static List<StructureTemplate.StructureBlockInfo> path(int width, int depth) {
|
||||
List<StructureTemplate.StructureBlockInfo> blocks = new ArrayList<>();
|
||||
for (int x = 0; x < width; x++) {
|
||||
for (int z = 0; z < depth; z++) {
|
||||
blocks.add(block(x, 0, z, Blocks.DIRT_PATH.defaultBlockState()));
|
||||
}
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
private static List<StructureTemplate.StructureBlockInfo> floor(int width, int depth) {
|
||||
List<StructureTemplate.StructureBlockInfo> blocks = new ArrayList<>();
|
||||
for (int x = 0; x < width; x++) {
|
||||
for (int z = 0; z < depth; z++) {
|
||||
blocks.add(block(x, 0, z, (x + z) % 2 == 0 ? Blocks.STONE_BRICKS.defaultBlockState() : Blocks.MOSSY_COBBLESTONE.defaultBlockState()));
|
||||
}
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
private static List<StructureTemplate.StructureBlockInfo> airPocket(int width, int height, int depth) {
|
||||
List<StructureTemplate.StructureBlockInfo> blocks = new ArrayList<>();
|
||||
for (int x = 0; x < width; x++) {
|
||||
for (int z = 0; z < depth; z++) {
|
||||
for (int y = 0; y < height; y++) {
|
||||
blocks.add(block(x, y, z, y == 0 && x == 0 ? Blocks.BRICKS.defaultBlockState() : Blocks.AIR.defaultBlockState()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
private static StructureTemplate.StructureBlockInfo block(int x, int y, int z, BlockState state) {
|
||||
return new StructureTemplate.StructureBlockInfo(new BlockPos(x, y, z), state, null);
|
||||
}
|
||||
|
||||
private static StructureTemplate template(List<StructureTemplate.StructureBlockInfo> blocks) {
|
||||
try {
|
||||
Constructor<StructureTemplate.Palette> constructor =
|
||||
StructureTemplate.Palette.class.getDeclaredConstructor(List.class);
|
||||
if (!constructor.trySetAccessible()) {
|
||||
throw new IllegalStateException("StructureTemplate.Palette is not accessible");
|
||||
}
|
||||
StructureTemplate template = new StructureTemplate();
|
||||
template.palettes.add(constructor.newInstance(blocks));
|
||||
return template;
|
||||
} catch (ReflectiveOperationException error) {
|
||||
throw new IllegalStateException(error);
|
||||
}
|
||||
}
|
||||
|
||||
private record Scenario(String name, List<FitTarget> targets) {
|
||||
}
|
||||
|
||||
/** A start in the chunk with its fit as an ownership record persists it, and the template blocks of its pieces. */
|
||||
private record FitTarget(String structureId, StructureStart start,
|
||||
Map<StructurePiece, List<StructureTemplate.StructureBlockInfo>> templates,
|
||||
String stiltJson, String terrainJson) {
|
||||
}
|
||||
|
||||
/** Builds a jigsaw start from template pieces, remembering each piece's template blocks for the placement stand-in. */
|
||||
private static final class TemplateStart {
|
||||
private final String structureId;
|
||||
private final Structure structure;
|
||||
private final List<StructurePiece> pieces = new ArrayList<>();
|
||||
private final Map<StructurePiece, List<StructureTemplate.StructureBlockInfo>> templates = new IdentityHashMap<>();
|
||||
|
||||
private TemplateStart(String structureId, GenerationStep.Decoration step, TerrainAdjustment adjustment) {
|
||||
this.structureId = structureId;
|
||||
this.structure = structure(step, adjustment);
|
||||
}
|
||||
|
||||
PoolElementStructurePiece single(List<StructureTemplate.StructureBlockInfo> blocks, BoundingBox bounds,
|
||||
int groundLevelDelta, Rotation rotation) {
|
||||
return single(blocks, bounds, groundLevelDelta, rotation, StructureTemplatePool.Projection.RIGID);
|
||||
}
|
||||
|
||||
PoolElementStructurePiece single(List<StructureTemplate.StructureBlockInfo> blocks, BoundingBox bounds,
|
||||
int groundLevelDelta, Rotation rotation,
|
||||
StructureTemplatePool.Projection projection) {
|
||||
return add(new InlineSinglePoolElement(template(blocks), projection), blocks, bounds, groundLevelDelta, rotation);
|
||||
}
|
||||
|
||||
PoolElementStructurePiece legacy(List<StructureTemplate.StructureBlockInfo> blocks, BoundingBox bounds,
|
||||
int groundLevelDelta, Rotation rotation) {
|
||||
return add(new InlineLegacyPoolElement(template(blocks)), blocks, bounds, groundLevelDelta, rotation);
|
||||
}
|
||||
|
||||
private PoolElementStructurePiece add(StructurePoolElement element, List<StructureTemplate.StructureBlockInfo> blocks,
|
||||
BoundingBox bounds, int groundLevelDelta, Rotation rotation) {
|
||||
PoolElementStructurePiece piece = new PoolElementStructurePiece(null, element,
|
||||
new BlockPos(bounds.minX(), bounds.minY(), bounds.minZ()), groundLevelDelta, rotation, bounds,
|
||||
LiquidSettings.APPLY_WATERLOGGING);
|
||||
pieces.add(piece);
|
||||
templates.put(piece, blocks);
|
||||
return piece;
|
||||
}
|
||||
|
||||
FitTarget target(String stiltJson, String terrainJson) {
|
||||
StructureStart start = new StructureStart(structure, new ChunkPos(0, 0), 0, new PiecesContainer(List.copyOf(pieces)));
|
||||
return new FitTarget(structureId, start, templates, stiltJson, terrainJson);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class InlineSinglePoolElement extends SinglePoolElement {
|
||||
private InlineSinglePoolElement(StructureTemplate template, StructureTemplatePool.Projection projection) {
|
||||
super(Either.right(template), Holder.direct(new StructureProcessorList(List.of())), projection,
|
||||
Optional.<LiquidSettings>empty());
|
||||
}
|
||||
}
|
||||
|
||||
private static final class InlineLegacyPoolElement extends LegacySinglePoolElement {
|
||||
private InlineLegacyPoolElement(StructureTemplate template) {
|
||||
super(Either.right(template), Holder.direct(new StructureProcessorList(List.of())),
|
||||
StructureTemplatePool.Projection.RIGID, Optional.<LiquidSettings>empty());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An uneven terrain computed per block, with the fit's writes kept on top: grass over dirt over stone (deepslate
|
||||
* below 0), a sea at {@link #SEA_LEVEL}, a flooded cave and a dry cave, scattered iron ore and two trees.
|
||||
*/
|
||||
private static final class TerrainWorld {
|
||||
private final Map<BlockPos, BlockState> written = new HashMap<>();
|
||||
|
||||
static int surfaceY(int x, int z) {
|
||||
return 62 + (int) Math.round(3D * Math.sin(x * 0.35D) + 2D * Math.cos(z * 0.27D));
|
||||
}
|
||||
|
||||
static BlockState natural(int x, int y, int z) {
|
||||
int surface = surfaceY(x, z);
|
||||
if (insideSphere(x, y, z, 8, 20, 8, 6)) {
|
||||
return y <= 17 ? Blocks.WATER.defaultBlockState() : Blocks.AIR.defaultBlockState();
|
||||
}
|
||||
if (insideSphere(x, y, z, 4, -6, 11, 4)) {
|
||||
return Blocks.AIR.defaultBlockState();
|
||||
}
|
||||
BlockState tree = tree(x, y, z);
|
||||
if (tree != null) {
|
||||
return tree;
|
||||
}
|
||||
if (y > surface) {
|
||||
return y <= SEA_LEVEL ? Blocks.WATER.defaultBlockState() : Blocks.AIR.defaultBlockState();
|
||||
}
|
||||
if (y == surface) {
|
||||
return surface < SEA_LEVEL ? Blocks.SAND.defaultBlockState() : Blocks.GRASS_BLOCK.defaultBlockState();
|
||||
}
|
||||
if (y >= surface - 3) {
|
||||
return Blocks.DIRT.defaultBlockState();
|
||||
}
|
||||
if (Math.floorMod(x + z, 11) == 0 && Math.floorMod(y, 7) == 0) {
|
||||
return Blocks.IRON_ORE.defaultBlockState();
|
||||
}
|
||||
return y < 0 ? Blocks.DEEPSLATE.defaultBlockState() : Blocks.STONE.defaultBlockState();
|
||||
}
|
||||
|
||||
private static BlockState tree(int x, int y, int z) {
|
||||
for (int[] trunk : new int[][]{{12, 3}, {5, 13}}) {
|
||||
int base = surfaceY(trunk[0], trunk[1]);
|
||||
if (base < SEA_LEVEL) {
|
||||
continue;
|
||||
}
|
||||
if (x == trunk[0] && z == trunk[1] && y > base && y <= base + 4) {
|
||||
return Blocks.OAK_LOG.defaultBlockState();
|
||||
}
|
||||
if (Math.abs(x - trunk[0]) <= 1 && Math.abs(z - trunk[1]) <= 1 && y >= base + 4 && y <= base + 5
|
||||
&& !(x == trunk[0] && z == trunk[1] && y == base + 4)) {
|
||||
return Blocks.OAK_LEAVES.defaultBlockState();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean insideSphere(int x, int y, int z, int cx, int cy, int cz, int radius) {
|
||||
int dx = x - cx;
|
||||
int dy = y - cy;
|
||||
int dz = z - cz;
|
||||
return dx * dx + dy * dy + dz * dz <= radius * radius;
|
||||
}
|
||||
|
||||
BlockState get(int x, int y, int z) {
|
||||
BlockState state = written.get(new BlockPos(x, y, z));
|
||||
return state == null ? natural(x, y, z) : state;
|
||||
}
|
||||
|
||||
/** The heightmap the platform's processors read: one above the highest block that is not air. */
|
||||
int heightmapY(int x, int z) {
|
||||
for (int y = CHUNK_AREA.maxY(); y >= CHUNK_AREA.minY() - 1; y--) {
|
||||
if (!get(x, y, z).isAir()) {
|
||||
return y + 1;
|
||||
}
|
||||
}
|
||||
return CHUNK_AREA.minY() - 1;
|
||||
}
|
||||
|
||||
WorldGenLevel level() {
|
||||
InvocationHandler handler = (proxy, method, arguments) -> switch (method.getName()) {
|
||||
case "getBlockState" -> {
|
||||
BlockPos position = (BlockPos) arguments[0];
|
||||
yield get(position.getX(), position.getY(), position.getZ());
|
||||
}
|
||||
case "setBlock" -> {
|
||||
written.put(((BlockPos) arguments[0]).immutable(), (BlockState) arguments[1]);
|
||||
yield true;
|
||||
}
|
||||
case "getSeed" -> WORLD_SEED;
|
||||
case "getMinY" -> WORLD_MIN_Y;
|
||||
case "getHeight" -> arguments == null ? WORLD_HEIGHT : heightmapY((int) arguments[1], (int) arguments[2]);
|
||||
case "getLevel" -> null;
|
||||
case "holderLookup" -> BuiltInRegistries.BLOCK;
|
||||
case "hashCode" -> System.identityHashCode(proxy);
|
||||
case "equals" -> proxy == arguments[0];
|
||||
case "toString" -> "fit-pin-world";
|
||||
default -> throw new UnsupportedOperationException(method.toString());
|
||||
};
|
||||
return (WorldGenLevel) Proxy.newProxyInstance(
|
||||
WorldGenLevel.class.getClassLoader(), new Class<?>[]{WorldGenLevel.class}, handler);
|
||||
}
|
||||
|
||||
String changedBlocksHash(BoundingBox area) throws Exception {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
int changed = 0;
|
||||
for (int x = area.minX(); x <= area.maxX(); x++) {
|
||||
for (int z = area.minZ(); z <= area.maxZ(); z++) {
|
||||
for (int y = area.minY(); y <= area.maxY(); y++) {
|
||||
BlockState state = get(x, y, z);
|
||||
if (state == natural(x, y, z)) {
|
||||
continue;
|
||||
}
|
||||
changed++;
|
||||
digest.update((x + "," + y + "," + z + "=" + state + "\n").getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
return changed + ":" + HexFormat.of().formatHex(digest.digest()).substring(0, 24);
|
||||
}
|
||||
}
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
package art.arcane.iris.nativegen;
|
||||
|
||||
import art.arcane.iris.engine.framework.NativeStructureReach;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.levelgen.GenerationStep;
|
||||
import net.minecraft.world.level.levelgen.structure.BoundingBox;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraft.world.level.levelgen.structure.StructurePiece;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureStart;
|
||||
import net.minecraft.world.level.levelgen.structure.TerrainAdjustment;
|
||||
import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer;
|
||||
import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidPiece;
|
||||
import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidStructure;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.IntBinaryOperator;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
/**
|
||||
* Pins where the platform's own starts end up vertically for each adjustment the dimension can give them (shift,
|
||||
* band, keeping the platform's height, burial under the terrain), and which chunks a start reaches for each terrain
|
||||
* fit. The values were taken before the fit moved into the structure module; since then the module answers the shift
|
||||
* and the reach ({@code StartLayoutsPinTest} in core pins those answers for the same starts) and the platform side,
|
||||
* pinned here, aligns, moves and references the starts with them.
|
||||
*/
|
||||
public class NativeStructureLayoutPinTest {
|
||||
private static final int SEA_LEVEL = 61;
|
||||
private static final int WORLD_MIN_Y = -64;
|
||||
private static final int WORLD_MAX_Y_EXCLUSIVE = 320;
|
||||
private static final IntBinaryOperator SURFACE = (x, z) -> 62 + Math.floorMod(x * 7 + z * 3, 11) - 5;
|
||||
private static final int[][] CHUNKS = {{0, 0}, {3, -5}, {-11, 7}};
|
||||
private static final Map<String, Integer> ADJUSTMENT_SHIFTS = adjustmentShifts();
|
||||
private static final Map<String, NativeStructureReach> TERRAIN_REACHES = terrainReaches();
|
||||
|
||||
private static final List<String> PINNED_SHIFTS = List.of(
|
||||
"none minecraft:stronghold 0,0 offset 0 minY 50",
|
||||
"none minecraft:desert_pyramid 0,0 offset -6 minY 58",
|
||||
"none minecraft:stronghold 3,-5 offset 0 minY 50",
|
||||
"none minecraft:desert_pyramid 3,-5 offset -6 minY 58",
|
||||
"none minecraft:stronghold -11,7 offset 0 minY 50",
|
||||
"none minecraft:desert_pyramid -11,7 offset -6 minY 58",
|
||||
"shift minecraft:stronghold 0,0 offset 5 minY 55",
|
||||
"shift minecraft:desert_pyramid 0,0 offset -1 minY 63",
|
||||
"shift minecraft:stronghold 3,-5 offset 5 minY 55",
|
||||
"shift minecraft:desert_pyramid 3,-5 offset -1 minY 63",
|
||||
"shift minecraft:stronghold -11,7 offset 5 minY 55",
|
||||
"shift minecraft:desert_pyramid -11,7 offset -1 minY 63",
|
||||
"burial minecraft:stronghold 0,0 offset -8 minY 42",
|
||||
"burial minecraft:desert_pyramid 0,0 offset -13 minY 51",
|
||||
"burial minecraft:stronghold 3,-5 offset -8 minY 42",
|
||||
"burial minecraft:desert_pyramid 3,-5 offset -13 minY 51",
|
||||
"burial minecraft:stronghold -11,7 offset -8 minY 42",
|
||||
"burial minecraft:desert_pyramid -11,7 offset -13 minY 51",
|
||||
"burial-unshifted minecraft:stronghold 0,0 offset -8 minY 42",
|
||||
"burial-unshifted minecraft:desert_pyramid 0,0 offset -6 minY 58",
|
||||
"burial-unshifted minecraft:stronghold 3,-5 offset -8 minY 42",
|
||||
"burial-unshifted minecraft:desert_pyramid 3,-5 offset -6 minY 58",
|
||||
"burial-unshifted minecraft:stronghold -11,7 offset -8 minY 42",
|
||||
"burial-unshifted minecraft:desert_pyramid -11,7 offset -6 minY 58",
|
||||
"kept minecraft:stronghold 0,0 offset 3 minY 53",
|
||||
"kept minecraft:desert_pyramid 0,0 offset -3 minY 61",
|
||||
"kept minecraft:stronghold 3,-5 offset 3 minY 53",
|
||||
"kept minecraft:desert_pyramid 3,-5 offset -3 minY 61",
|
||||
"kept minecraft:stronghold -11,7 offset 3 minY 53",
|
||||
"kept minecraft:desert_pyramid -11,7 offset -3 minY 61",
|
||||
"band minecraft:stronghold 0,0 offset -94 minY -44",
|
||||
"band minecraft:desert_pyramid 0,0 offset -6 minY 58",
|
||||
"band minecraft:stronghold 3,-5 offset -58 minY -8",
|
||||
"band minecraft:desert_pyramid 3,-5 offset -6 minY 58",
|
||||
"band minecraft:stronghold -11,7 offset -96 minY -46",
|
||||
"band minecraft:desert_pyramid -11,7 offset -6 minY 58",
|
||||
"narrow-band minecraft:stronghold 0,0 offset -46 minY 4",
|
||||
"narrow-band minecraft:desert_pyramid 0,0 offset -2 minY 62",
|
||||
"narrow-band minecraft:stronghold 3,-5 offset -46 minY 4",
|
||||
"narrow-band minecraft:desert_pyramid 3,-5 offset -2 minY 62",
|
||||
"narrow-band minecraft:stronghold -11,7 offset -46 minY 4",
|
||||
"narrow-band minecraft:desert_pyramid -11,7 offset -2 minY 62",
|
||||
"kept-over-band minecraft:stronghold 0,0 offset 2 minY 52",
|
||||
"kept-over-band minecraft:desert_pyramid 0,0 offset -4 minY 60",
|
||||
"kept-over-band minecraft:stronghold 3,-5 offset 2 minY 52",
|
||||
"kept-over-band minecraft:desert_pyramid 3,-5 offset -4 minY 60",
|
||||
"kept-over-band minecraft:stronghold -11,7 offset 2 minY 52",
|
||||
"kept-over-band minecraft:desert_pyramid -11,7 offset -4 minY 60");
|
||||
private static final List<String> PINNED_REACHES = List.of(
|
||||
"{} NONE 32,40,-48 52,54,-28",
|
||||
"{} BEARD_THIN 20,28,-60 64,66,-16",
|
||||
"{} BURY 20,28,-60 64,66,-16",
|
||||
"{\"mode\":\"PRESERVE\"} NONE 32,40,-48 52,54,-28",
|
||||
"{\"mode\":\"PRESERVE\"} BEARD_THIN 32,40,-48 52,54,-28",
|
||||
"{\"mode\":\"PRESERVE\"} BURY 32,40,-48 52,54,-28",
|
||||
"{\"mode\":\"VACUUM\"} NONE 20,40,-60 64,54,-16",
|
||||
"{\"mode\":\"VACUUM\"} BEARD_THIN 20,40,-60 64,54,-16",
|
||||
"{\"mode\":\"VACUUM\"} BURY 20,40,-60 64,54,-16",
|
||||
"{\"mode\":\"ENCASE\",\"horizontalPadding\":4} NONE 28,40,-52 56,54,-24",
|
||||
"{\"mode\":\"ENCASE\",\"horizontalPadding\":4} BEARD_THIN 28,40,-52 56,54,-24",
|
||||
"{\"mode\":\"ENCASE\",\"horizontalPadding\":4} BURY 28,40,-52 56,54,-24",
|
||||
"{\"mode\":\"BORE\",\"horizontalPadding\":20} NONE 12,40,-68 72,54,-8",
|
||||
"{\"mode\":\"BORE\",\"horizontalPadding\":20} BEARD_THIN 12,40,-68 72,54,-8",
|
||||
"{\"mode\":\"BORE\",\"horizontalPadding\":20} BURY 12,40,-68 72,54,-8",
|
||||
"{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":112} NONE -80,40,-160 164,54,84",
|
||||
"{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":112} BEARD_THIN -80,40,-160 164,54,84",
|
||||
"{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":112} BURY -80,40,-160 164,54,84",
|
||||
"{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":0} NONE 32,40,-48 52,54,-28",
|
||||
"{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":0} BEARD_THIN 32,40,-48 52,54,-28",
|
||||
"{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":0} BURY 32,40,-48 52,54,-28");
|
||||
|
||||
@BeforeClass
|
||||
public static void bootstrapMinecraft() {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
}
|
||||
|
||||
/**
|
||||
* The module's shift for a stronghold is the move it makes; for a desert temple, which the platform aligns to the
|
||||
* terrain itself, it is the adjustment's own shift on top of that alignment.
|
||||
*/
|
||||
@Test
|
||||
public void platformStartsMoveWhereTheirAdjustmentSays() {
|
||||
List<String> actual = new ArrayList<>();
|
||||
for (String pinned : PINNED_SHIFTS) {
|
||||
String[] parts = pinned.split(" ");
|
||||
String structureId = parts[1];
|
||||
String[] chunkXZ = parts[2].split(",");
|
||||
ChunkPos chunk = new ChunkPos(Integer.parseInt(chunkXZ[0]), Integer.parseInt(chunkXZ[1]));
|
||||
boolean stronghold = structureId.equals("minecraft:stronghold");
|
||||
int moduleShift = stronghold ? Integer.parseInt(parts[4]) : ADJUSTMENT_SHIFTS.get(parts[0]);
|
||||
StructureStart start = start(chunk, stronghold ? 50 : 64, TerrainAdjustment.NONE);
|
||||
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(start, structureId, moduleShift,
|
||||
SEA_LEVEL, WORLD_MIN_Y, WORLD_MAX_Y_EXCLUSIVE, SURFACE);
|
||||
actual.add(parts[0] + " " + structureId + " " + parts[2] + " offset " + offset
|
||||
+ " minY " + start.getBoundingBox().minY());
|
||||
}
|
||||
assertEquals(PINNED_SHIFTS, actual);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void startsReachTheChunksTheirTerrainFitSays() {
|
||||
List<String> actual = new ArrayList<>();
|
||||
for (Map.Entry<String, NativeStructureReach> fit : TERRAIN_REACHES.entrySet()) {
|
||||
for (TerrainAdjustment adjustment : List.of(TerrainAdjustment.NONE, TerrainAdjustment.BEARD_THIN, TerrainAdjustment.BURY)) {
|
||||
StructureStart start = start(new ChunkPos(2, -3), 40, adjustment);
|
||||
BoundingBox bounds = NativeStructureReferenceEnvelope.referenceBounds(start, start.getStructure(),
|
||||
List.of(fit.getValue()), "minecraft:village_plains");
|
||||
actual.add(fit.getKey() + " " + adjustment + " " + bounds.minX() + "," + bounds.minY() + "," + bounds.minZ()
|
||||
+ " " + bounds.maxX() + "," + bounds.maxY() + "," + bounds.maxZ());
|
||||
}
|
||||
}
|
||||
assertEquals(PINNED_REACHES, actual);
|
||||
}
|
||||
|
||||
private static Map<String, Integer> adjustmentShifts() {
|
||||
Map<String, Integer> shifts = new LinkedHashMap<>();
|
||||
shifts.put("none", 0);
|
||||
shifts.put("shift", 5);
|
||||
shifts.put("burial", -7);
|
||||
shifts.put("burial-unshifted", 0);
|
||||
shifts.put("kept", 3);
|
||||
shifts.put("band", 0);
|
||||
shifts.put("narrow-band", 4);
|
||||
shifts.put("kept-over-band", 2);
|
||||
return shifts;
|
||||
}
|
||||
|
||||
/** What the structure module answers for each terrain fit (pinned in core by {@code StartLayoutsPinTest}). */
|
||||
private static Map<String, NativeStructureReach> terrainReaches() {
|
||||
Map<String, NativeStructureReach> reaches = new LinkedHashMap<>();
|
||||
reaches.put("{}", NativeStructureReach.PLATFORM);
|
||||
reaches.put("{\"mode\":\"PRESERVE\"}", new NativeStructureReach(false, 0));
|
||||
reaches.put("{\"mode\":\"VACUUM\"}", new NativeStructureReach(false, 12));
|
||||
reaches.put("{\"mode\":\"ENCASE\",\"horizontalPadding\":4}", new NativeStructureReach(false, 4));
|
||||
reaches.put("{\"mode\":\"BORE\",\"horizontalPadding\":20}", new NativeStructureReach(false, 20));
|
||||
reaches.put("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":112}", new NativeStructureReach(false, 112));
|
||||
reaches.put("{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":0}", new NativeStructureReach(false, 0));
|
||||
return reaches;
|
||||
}
|
||||
|
||||
private static StructureStart start(ChunkPos chunk, int minY, TerrainAdjustment adjustment) {
|
||||
Structure structure = new DesertPyramidStructure(new Structure.StructureSettings(
|
||||
HolderSet.empty(), Map.of(), GenerationStep.Decoration.SURFACE_STRUCTURES, adjustment));
|
||||
StructurePiece piece = new DesertPyramidPiece(RandomSource.create(7L), chunk.getMinBlockX(), chunk.getMinBlockZ());
|
||||
piece.move(0, minY - piece.getBoundingBox().minY(), 0);
|
||||
return new StructureStart(structure, chunk, 0, new PiecesContainer(List.of(piece)));
|
||||
}
|
||||
}
|
||||
+7
-25
@@ -2,11 +2,8 @@ package art.arcane.iris.nativegen;
|
||||
|
||||
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
|
||||
import art.arcane.iris.engine.framework.NativeStructureStartPlan;
|
||||
import art.arcane.iris.engine.object.IrisNativeStructure;
|
||||
import art.arcane.iris.engine.object.IrisStructurePlacement;
|
||||
import art.arcane.iris.engine.object.IrisStructureTerrain;
|
||||
import art.arcane.iris.engine.object.IrisStructureTerrainMode;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.iris.engine.framework.NativeStartMemo;
|
||||
import art.arcane.iris.engine.framework.NativeStructureReach;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Direction;
|
||||
@@ -64,9 +61,7 @@ public class NativeStructureOwnershipFingerprintTest {
|
||||
NativeStructureVerticalPlacer.alignOceanMonumentToSeaLevel(
|
||||
generated, 0, 80, -64, 320);
|
||||
int alignedLocatorY = NativeStructureOwnershipFingerprint.locatorY(generated);
|
||||
IrisStructureTerrain terrain = new IrisStructureTerrain()
|
||||
.setMode(IrisStructureTerrainMode.FORCE_CARVE)
|
||||
.setHorizontalPadding(24);
|
||||
List<NativeStructureReach> terrain = List.of(new NativeStructureReach(false, 24));
|
||||
StructureStart wrapped = NativeStructureReferenceEnvelope.wrap(
|
||||
generated,
|
||||
structure,
|
||||
@@ -128,9 +123,7 @@ public class NativeStructureOwnershipFingerprintTest {
|
||||
StructureStart generated = monumentStart(structure, origin, seed);
|
||||
NativeStructureVerticalPlacer.alignOceanMonumentToSeaLevel(
|
||||
generated, 0, 80, -64, 320);
|
||||
IrisStructureTerrain terrain = new IrisStructureTerrain()
|
||||
.setMode(IrisStructureTerrainMode.FORCE_CARVE)
|
||||
.setHorizontalPadding(24);
|
||||
List<NativeStructureReach> terrain = List.of(new NativeStructureReach(false, 24));
|
||||
StructureStart wrapped = NativeStructureReferenceEnvelope.wrap(
|
||||
generated,
|
||||
structure,
|
||||
@@ -246,19 +239,8 @@ public class NativeStructureOwnershipFingerprintTest {
|
||||
}
|
||||
|
||||
private static NativeStructureStartPlan plan(ChunkPos origin, int baseY) {
|
||||
IrisNativeStructure source = new IrisNativeStructure()
|
||||
.setStructure("minecraft:monument")
|
||||
.setWeight(1);
|
||||
IrisStructurePlacement placement = new IrisStructurePlacement()
|
||||
.setPlacementId("monument-test")
|
||||
.setNativeStructures(new KList<IrisNativeStructure>().qadd(source));
|
||||
return new NativeStructureStartPlan(
|
||||
placement,
|
||||
source,
|
||||
origin.x(),
|
||||
origin.z(),
|
||||
baseY
|
||||
);
|
||||
return new NativeStructureStartPlan("minecraft:monument", origin.x(), origin.z(), baseY, false, false,
|
||||
null, new NativeStartMemo("{\"terrain\":{\"mode\":\"SOURCE\"}}"));
|
||||
}
|
||||
|
||||
private static NativeStructureOwnershipRecord ownership(
|
||||
@@ -268,7 +250,7 @@ public class NativeStructureOwnershipFingerprintTest {
|
||||
start,
|
||||
plan(origin, NativeStructureReferenceEnvelope.contentBounds(start).minY()),
|
||||
NativeStructureReferenceEnvelope.referenceBounds(
|
||||
start, structure, new IrisStructureTerrain())
|
||||
start, structure, List.of(NativeStructureReach.PLATFORM))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+58
-64
@@ -2,12 +2,8 @@ package art.arcane.iris.nativegen;
|
||||
|
||||
import art.arcane.iris.engine.framework.NativeStructureOwnershipRecord;
|
||||
import art.arcane.iris.engine.framework.NativeStructureStartPlan;
|
||||
import art.arcane.iris.engine.framework.StructurePlacementGrid;
|
||||
import art.arcane.iris.engine.object.IrisNativeStructure;
|
||||
import art.arcane.iris.engine.object.IrisStructurePlacement;
|
||||
import art.arcane.iris.engine.object.IrisStructureTerrain;
|
||||
import art.arcane.iris.engine.object.IrisStructureTerrainMode;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.iris.engine.framework.NativeStartMemo;
|
||||
import art.arcane.iris.engine.framework.NativeStructureReach;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.HolderSet;
|
||||
@@ -51,7 +47,7 @@ public class NativeStructureOwnershipRecoveryTest {
|
||||
NativeStructureVerticalPlacer.alignOceanMonumentToSeaLevel(
|
||||
expected, 0, 80, -64, 320);
|
||||
int expectedLocatorY = NativeStructureOwnershipFingerprint.locatorY(expected);
|
||||
NativeStructureStartPlan plan = plan(origin, "recovery-exact", 24);
|
||||
NativeStructureStartPlan plan = plan(origin, 24);
|
||||
StructureStart reloaded = new StructureStart(
|
||||
structure,
|
||||
origin,
|
||||
@@ -63,17 +59,13 @@ public class NativeStructureOwnershipRecoveryTest {
|
||||
NativeStructureOwnershipRecord recovered =
|
||||
NativeStructureOwnershipRecovery.proveCandidate(
|
||||
"minecraft:monument", structure, reloaded,
|
||||
plan, expected, false);
|
||||
plan, expected, false, reaches(plan));
|
||||
|
||||
assertNotNull(recovered);
|
||||
assertEquals(StructurePlacementGrid.placementIdentity(plan.placement()),
|
||||
recovered.placementIdentity());
|
||||
assertEquals(expectedLocatorY, recovered.locatorY());
|
||||
assertNotEquals(NativeStructureOwnershipFingerprint.locatorY(reloaded),
|
||||
recovered.locatorY());
|
||||
assertEquals(IrisStructureTerrainMode.FORCE_CARVE,
|
||||
recovered.restoredDecision().terrain().resolvedMode());
|
||||
assertEquals(24, recovered.restoredDecision().terrain().getHorizontalPadding());
|
||||
assertEquals(plan.memo(), recovered.restoredMemo());
|
||||
assertTrue(recovered.referenceMinChunkX()
|
||||
< NativeStructureReferenceEnvelope.contentBounds(reloaded).minX() >> 4);
|
||||
}
|
||||
@@ -84,18 +76,18 @@ public class NativeStructureOwnershipRecoveryTest {
|
||||
ChunkPos origin = new ChunkPos(-3, 6);
|
||||
OceanMonumentStructure structure = structure();
|
||||
StructureStart natural = monumentStart(structure, origin, seed);
|
||||
NativeStructureStartPlan plan = plan(origin, "natural-ambiguous", 0);
|
||||
NativeStructureStartPlan plan = plan(origin, 0);
|
||||
|
||||
NativeStructureOwnershipRecord recovered =
|
||||
NativeStructureOwnershipRecovery.proveCandidate(
|
||||
"minecraft:monument", structure, natural,
|
||||
plan, natural, true);
|
||||
plan, natural, true, reaches(plan));
|
||||
|
||||
assertNull(recovered);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void changedPlacementIdentityOrGeometryCannotRecoverOwnership() {
|
||||
public void changedOriginOrGeometryCannotRecoverOwnership() {
|
||||
long seed = 991723L;
|
||||
ChunkPos origin = new ChunkPos(2, 4);
|
||||
OceanMonumentStructure structure = structure();
|
||||
@@ -104,20 +96,14 @@ public class NativeStructureOwnershipRecoveryTest {
|
||||
for (StructurePiece piece : changedGeometry.getPieces()) {
|
||||
piece.move(1, 0, 0);
|
||||
}
|
||||
NativeStructureStartPlan originalIdentity = plan(
|
||||
origin, "original-identity", 0);
|
||||
NativeStructureStartPlan changedIdentity = plan(
|
||||
new ChunkPos(origin.x() + 1, origin.z()), "changed-identity", 0);
|
||||
NativeStructureStartPlan changedOrigin = plan(new ChunkPos(origin.x() + 1, origin.z()), 0);
|
||||
|
||||
assertNotEquals(
|
||||
StructurePlacementGrid.placementIdentity(originalIdentity.placement()),
|
||||
StructurePlacementGrid.placementIdentity(changedIdentity.placement()));
|
||||
assertNull(NativeStructureOwnershipRecovery.proveCandidate(
|
||||
"minecraft:monument", structure, expected,
|
||||
changedIdentity, expected, false));
|
||||
changedOrigin, expected, false, reaches(changedOrigin)));
|
||||
assertNull(NativeStructureOwnershipRecovery.proveCandidate(
|
||||
"minecraft:monument", structure, changedGeometry,
|
||||
plan(origin, "geometry-check", 0), expected, false));
|
||||
plan(origin, 0), expected, false, reaches(plan(origin, 0))));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -129,7 +115,7 @@ public class NativeStructureOwnershipRecoveryTest {
|
||||
NativeStructureOwnershipRecord recovered =
|
||||
NativeStructureOwnershipRecovery.proveCandidate(
|
||||
"minecraft:monument", structure, expected,
|
||||
plan(origin, "fingerprint-check", 16), expected, false);
|
||||
plan(origin, 16), expected, false, reaches(plan(origin, 16)));
|
||||
assertNotNull(recovered);
|
||||
|
||||
StructureStart moved = monumentStart(structure, origin, seed);
|
||||
@@ -148,35 +134,32 @@ public class NativeStructureOwnershipRecoveryTest {
|
||||
OceanMonumentStructure structure = structure();
|
||||
StructureStart start = monumentStart(structure, origin, seed);
|
||||
NativeStructureStartPlan plan = plan(
|
||||
origin, "vacuum-envelope-refresh", IrisStructureTerrainMode.VACUUM, 0);
|
||||
origin, "VACUUM", 0);
|
||||
BoundingBox content = NativeStructureReferenceEnvelope.contentBounds(start);
|
||||
NativeStructureOwnershipRecord stale = NativeStructureOwnershipFingerprint.capture(
|
||||
structureKey, start, plan, content);
|
||||
|
||||
NativeStructureOwnershipRecord refreshed =
|
||||
NativeStructureOwnershipRecovery.refreshReferenceEnvelope(
|
||||
structureKey, structure, start, stale);
|
||||
structureKey, structure, start, stale, reaches(plan));
|
||||
|
||||
assertNotNull(refreshed);
|
||||
assertNotEquals(stale, refreshed);
|
||||
assertEquals(stale.schema(), refreshed.schema());
|
||||
assertEquals(stale.ownershipKey(), refreshed.ownershipKey());
|
||||
assertEquals(stale.placementIdentity(), refreshed.placementIdentity());
|
||||
assertEquals(stale.baseY(), refreshed.baseY());
|
||||
assertEquals(stale.locatorY(), refreshed.locatorY());
|
||||
assertEquals(stale.contentFingerprint(), refreshed.contentFingerprint());
|
||||
assertEquals(stale.decision(), refreshed.decision());
|
||||
assertEquals(IrisStructureTerrainMode.VACUUM,
|
||||
refreshed.restoredDecision().terrain().resolvedMode());
|
||||
assertEquals(stale.memo(), refreshed.memo());
|
||||
BoundingBox expected = NativeStructureReferenceEnvelope.referenceBounds(
|
||||
start, structure, plan.placement().resolvedTerrain(), structureKey);
|
||||
start, structure, reaches(plan), structureKey);
|
||||
assertEquals(expected.minX() >> 4, refreshed.referenceMinChunkX());
|
||||
assertEquals(expected.maxX() >> 4, refreshed.referenceMaxChunkX());
|
||||
assertEquals(expected.minZ() >> 4, refreshed.referenceMinChunkZ());
|
||||
assertEquals(expected.maxZ() >> 4, refreshed.referenceMaxChunkZ());
|
||||
assertTrue(hasExpandedCoverage(stale, refreshed));
|
||||
assertSame(refreshed, NativeStructureOwnershipRecovery.refreshReferenceEnvelope(
|
||||
structureKey, structure, start, refreshed));
|
||||
structureKey, structure, start, refreshed, reaches(plan)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -187,7 +170,7 @@ public class NativeStructureOwnershipRecoveryTest {
|
||||
OceanMonumentStructure structure = structure();
|
||||
StructureStart expected = monumentStart(structure, origin, seed);
|
||||
NativeStructureStartPlan plan = plan(
|
||||
origin, "vacuum-content-check", IrisStructureTerrainMode.VACUUM, 0);
|
||||
origin, "VACUUM", 0);
|
||||
NativeStructureOwnershipRecord stale = NativeStructureOwnershipFingerprint.capture(
|
||||
structureKey, expected, plan,
|
||||
NativeStructureReferenceEnvelope.contentBounds(expected));
|
||||
@@ -197,7 +180,7 @@ public class NativeStructureOwnershipRecoveryTest {
|
||||
}
|
||||
|
||||
assertNull(NativeStructureOwnershipRecovery.refreshReferenceEnvelope(
|
||||
structureKey, structure, moved, stale));
|
||||
structureKey, structure, moved, stale, reaches(plan)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -207,14 +190,29 @@ public class NativeStructureOwnershipRecoveryTest {
|
||||
ChunkPos origin = new ChunkPos(3, 8);
|
||||
OceanMonumentStructure structure = structure();
|
||||
StructureStart start = monumentStart(structure, origin, seed);
|
||||
NativeStructureStartPlan plan = plan(origin, "current-force-carve", 24);
|
||||
NativeStructureStartPlan plan = plan(origin, 24);
|
||||
BoundingBox envelope = NativeStructureReferenceEnvelope.referenceBounds(
|
||||
start, structure, plan.placement().resolvedTerrain(), structureKey);
|
||||
start, structure, reaches(plan), structureKey);
|
||||
NativeStructureOwnershipRecord ownership = NativeStructureOwnershipFingerprint.capture(
|
||||
structureKey, start, plan, envelope);
|
||||
|
||||
assertSame(ownership, NativeStructureOwnershipRecovery.refreshReferenceEnvelope(
|
||||
structureKey, structure, start, ownership));
|
||||
structureKey, structure, start, ownership, reaches(plan)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aRecordedEnvelopeWiderThanTodaysReachNeverShrinks() {
|
||||
String structureKey = "minecraft:monument";
|
||||
long seed = 927451L;
|
||||
ChunkPos origin = new ChunkPos(3, 8);
|
||||
OceanMonumentStructure structure = structure();
|
||||
StructureStart start = monumentStart(structure, origin, seed);
|
||||
NativeStructureStartPlan plan = plan(origin, 24);
|
||||
NativeStructureOwnershipRecord ownership = NativeStructureOwnershipFingerprint.capture(structureKey, start, plan,
|
||||
NativeStructureReferenceEnvelope.referenceBounds(start, structure, reaches(plan), structureKey));
|
||||
|
||||
assertSame(ownership, NativeStructureOwnershipRecovery.refreshReferenceEnvelope(
|
||||
structureKey, structure, start, ownership, List.of(NativeStructureReach.PLATFORM)));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -232,16 +230,16 @@ public class NativeStructureOwnershipRecoveryTest {
|
||||
piece.move(shiftX, 0, 0);
|
||||
}
|
||||
NativeStructureStartPlan plan = plan(
|
||||
origin, "clipped-vacuum", IrisStructureTerrainMode.VACUUM, 0);
|
||||
origin, "VACUUM", 0);
|
||||
BoundingBox envelope = NativeStructureReferenceEnvelope.referenceBounds(
|
||||
start, structure, plan.placement().resolvedTerrain(), structureKey);
|
||||
start, structure, reaches(plan), structureKey);
|
||||
NativeStructureOwnershipRecord ownership = NativeStructureOwnershipFingerprint.capture(
|
||||
structureKey, start, plan, envelope);
|
||||
|
||||
assertEquals(origin.x() + NativeStructureOwnershipRecord.MAX_REFERENCE_DISTANCE_CHUNKS,
|
||||
ownership.referenceMaxChunkX());
|
||||
assertSame(ownership, NativeStructureOwnershipRecovery.refreshReferenceEnvelope(
|
||||
structureKey, structure, start, ownership));
|
||||
structureKey, structure, start, ownership, reaches(plan)));
|
||||
}
|
||||
|
||||
private static OceanMonumentStructure structure() {
|
||||
@@ -266,37 +264,33 @@ public class NativeStructureOwnershipRecoveryTest {
|
||||
structure, origin, 0, new PiecesContainer(List.of(building)));
|
||||
}
|
||||
|
||||
private static NativeStructureStartPlan plan(ChunkPos origin,
|
||||
String placementId,
|
||||
int horizontalPadding) {
|
||||
return plan(origin, placementId,
|
||||
IrisStructureTerrainMode.FORCE_CARVE, horizontalPadding);
|
||||
private static NativeStructureStartPlan plan(ChunkPos origin, int horizontalPadding) {
|
||||
return plan(origin, "FORCE_CARVE", horizontalPadding);
|
||||
}
|
||||
|
||||
private static NativeStructureStartPlan plan(ChunkPos origin,
|
||||
String placementId,
|
||||
IrisStructureTerrainMode terrainMode,
|
||||
int horizontalPadding) {
|
||||
IrisNativeStructure source = new IrisNativeStructure()
|
||||
.setStructure("minecraft:monument")
|
||||
.setWeight(1);
|
||||
IrisStructureTerrain terrain = new IrisStructureTerrain()
|
||||
.setMode(terrainMode)
|
||||
.setHorizontalPadding(horizontalPadding);
|
||||
IrisStructurePlacement placement = new IrisStructurePlacement()
|
||||
.setPlacementId(placementId)
|
||||
.setTerrain(terrain)
|
||||
.setNativeStructures(new KList<IrisNativeStructure>().qadd(source));
|
||||
/** A start the structure module placed with a terrain fit of {@code terrainMode}, as its memo records it. */
|
||||
private static NativeStructureStartPlan plan(ChunkPos origin, String terrainMode, int horizontalPadding) {
|
||||
String terrain = "{\"mode\":\"" + terrainMode + "\",\"horizontalPadding\":" + horizontalPadding + "}";
|
||||
return new NativeStructureStartPlan(
|
||||
placement,
|
||||
source,
|
||||
"minecraft:monument",
|
||||
origin.x(),
|
||||
origin.z(),
|
||||
NativeStructureReferenceEnvelope.contentBounds(
|
||||
monumentStart(structure(), origin, 1L)).minY()
|
||||
monumentStart(structure(), origin, 1L)).minY(),
|
||||
false,
|
||||
false,
|
||||
null,
|
||||
new NativeStartMemo("{\"terrain\":" + terrain + "}")
|
||||
);
|
||||
}
|
||||
|
||||
/** The reach the structure module gives the plan's terrain fit: VACUUM its 12-block falloff, else the padding. */
|
||||
private static List<NativeStructureReach> reaches(NativeStructureStartPlan plan) {
|
||||
String terrain = plan.memo().text();
|
||||
int padding = Integer.parseInt(terrain.replaceAll(".*\"horizontalPadding\":(\\d+).*", "$1"));
|
||||
return List.of(new NativeStructureReach(false, terrain.contains("VACUUM") ? 12 : padding));
|
||||
}
|
||||
|
||||
private static boolean hasExpandedCoverage(
|
||||
NativeStructureOwnershipRecord stale,
|
||||
NativeStructureOwnershipRecord refreshed) {
|
||||
|
||||
-547
@@ -1,547 +0,0 @@
|
||||
package art.arcane.iris.nativegen;
|
||||
|
||||
import art.arcane.iris.engine.object.IrisMaterialPalette;
|
||||
import art.arcane.iris.engine.object.IrisStructureTerrain;
|
||||
import art.arcane.iris.engine.object.IrisStructureTerrainMode;
|
||||
import art.arcane.iris.engine.object.IrisStructureYBand;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.WorldGenLevel;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.Rotation;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
|
||||
import net.minecraft.world.level.levelgen.GenerationStep;
|
||||
import net.minecraft.world.level.levelgen.structure.BoundingBox;
|
||||
import net.minecraft.world.level.levelgen.structure.PoolElementStructurePiece;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraft.world.level.levelgen.structure.StructurePiece;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureStart;
|
||||
import net.minecraft.world.level.levelgen.structure.TerrainAdjustment;
|
||||
import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer;
|
||||
import net.minecraft.world.level.levelgen.structure.pools.StructurePoolElement;
|
||||
import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool;
|
||||
import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidPiece;
|
||||
import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidStructure;
|
||||
import net.minecraft.world.level.levelgen.structure.templatesystem.BlockIgnoreProcessor;
|
||||
import net.minecraft.world.level.levelgen.structure.templatesystem.LiquidSettings;
|
||||
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorList;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.InvocationHandler;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.BitSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertSame;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class NativeStructurePostProcessorEncaseTest {
|
||||
private static final long TEST_SEED = 1234L;
|
||||
|
||||
@BeforeClass
|
||||
public static void bootstrapMinecraft() {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encaseFillsAirAndLiquidWithoutOverwritingExistingTerrain() {
|
||||
StructureStart start = start(TerrainAdjustment.BURY, 64);
|
||||
BoundingBox bounds = start.getPieces().getFirst().getBoundingBox();
|
||||
BoundingBox area = new BoundingBox(
|
||||
bounds.minX() - 1, bounds.minY() - 1, bounds.minZ() - 1,
|
||||
bounds.maxX() + 1, bounds.maxY() + 1, bounds.maxZ() + 1);
|
||||
Map<BlockPos, BlockState> blocks = new HashMap<>();
|
||||
put(blocks, bounds.minX(), bounds.minY(), bounds.minZ(), Blocks.DIRT.defaultBlockState());
|
||||
put(blocks, bounds.maxX(), bounds.minY(), bounds.maxZ(), Blocks.WATER.defaultBlockState());
|
||||
|
||||
NativeStructureTerrainIntegrator.integrateTerrain(
|
||||
world(blocks), area, "minecraft:stronghold", start,
|
||||
new IrisStructureTerrain()
|
||||
.setMode(IrisStructureTerrainMode.ENCASE)
|
||||
.setHorizontalPadding(1)
|
||||
.setCeilingPadding(1)
|
||||
.setFloorPadding(1),
|
||||
null);
|
||||
|
||||
assertEquals(Blocks.DIRT.defaultBlockState(),
|
||||
state(blocks, bounds.minX(), bounds.minY(), bounds.minZ()));
|
||||
assertEquals(Blocks.STONE.defaultBlockState(),
|
||||
state(blocks, bounds.maxX(), bounds.minY(), bounds.maxZ()));
|
||||
assertEquals(Blocks.STONE.defaultBlockState(),
|
||||
state(blocks, bounds.minX() - 1, bounds.minY() - 1, bounds.minZ() - 1));
|
||||
assertEquals(Blocks.STONE.defaultBlockState(),
|
||||
state(blocks, bounds.maxX() + 1, bounds.maxY() + 1, bounds.maxZ() + 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultEncasePaletteSplitsStoneAboveZeroAndDeepslateBelow() {
|
||||
StructureStart start = start(TerrainAdjustment.BURY, -1);
|
||||
BoundingBox bounds = start.getPieces().getFirst().getBoundingBox();
|
||||
Map<BlockPos, BlockState> blocks = new HashMap<>();
|
||||
|
||||
NativeStructureTerrainIntegrator.integrateTerrain(
|
||||
world(blocks), bounds, "minecraft:stronghold", start,
|
||||
new IrisStructureTerrain().setMode(IrisStructureTerrainMode.ENCASE),
|
||||
null);
|
||||
|
||||
assertEquals(-1, bounds.minY());
|
||||
assertEquals(Blocks.DEEPSLATE.defaultBlockState(),
|
||||
state(blocks, bounds.minX(), -1, bounds.minZ()));
|
||||
assertEquals(Blocks.STONE.defaultBlockState(),
|
||||
state(blocks, bounds.minX(), 0, bounds.minZ()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void defaultEncaseMaterialFollowsVanillaDimensionTerrain() {
|
||||
assertEquals(Blocks.NETHERRACK.defaultBlockState(),
|
||||
NativeStructureTerrainIntegrator.defaultEncaseBlock(Level.NETHER, 64));
|
||||
assertEquals(Blocks.END_STONE.defaultBlockState(),
|
||||
NativeStructureTerrainIntegrator.defaultEncaseBlock(Level.END, 64));
|
||||
assertEquals(Blocks.STONE.defaultBlockState(),
|
||||
NativeStructureTerrainIntegrator.defaultEncaseBlock(Level.OVERWORLD, 64));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sourceEncaseMaterialFollowsNearbyIrisTerrain() {
|
||||
Map<BlockPos, BlockState> blocks = new HashMap<>();
|
||||
BlockPos fill = new BlockPos(4, 64, 8);
|
||||
put(blocks, fill.getX() + 3, fill.getY(), fill.getZ(), Blocks.TUFF.defaultBlockState());
|
||||
|
||||
assertEquals(Blocks.TUFF.defaultBlockState(),
|
||||
NativeStructureTerrainIntegrator.sourceEncaseBlock(world(blocks), fill));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sourceMaterialSnapshotIgnoresPreviouslyDecoratedAdjacentChunks() {
|
||||
Map<BlockPos, BlockState> blocks = new HashMap<>();
|
||||
BlockPos fill = new BlockPos(0, 64, 8);
|
||||
put(blocks, -1, 64, 8, Blocks.OAK_PLANKS.defaultBlockState());
|
||||
put(blocks, 3, 64, 8, Blocks.TUFF.defaultBlockState());
|
||||
WorldGenLevel world = world(blocks);
|
||||
NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceTerrain =
|
||||
sourceSnapshot(world, new BoundingBox(0, 64, 0, 15, 64, 15));
|
||||
|
||||
assertEquals(Blocks.TUFF.defaultBlockState(),
|
||||
NativeStructureTerrainIntegrator.sourceEncaseBlock(
|
||||
world, fill, sourceTerrain));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sourceMaterialSnapshotIsStableAcrossEarlierFillsInTheSameChunk() {
|
||||
Map<BlockPos, BlockState> blocks = new HashMap<>();
|
||||
BlockPos fill = new BlockPos(0, 64, 8);
|
||||
put(blocks, 3, 64, 8, Blocks.TUFF.defaultBlockState());
|
||||
WorldGenLevel world = world(blocks);
|
||||
NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceTerrain =
|
||||
sourceSnapshot(world, new BoundingBox(0, 64, 0, 15, 64, 15));
|
||||
put(blocks, 1, 64, 8, Blocks.OAK_PLANKS.defaultBlockState());
|
||||
|
||||
assertEquals(Blocks.TUFF.defaultBlockState(),
|
||||
NativeStructureTerrainIntegrator.sourceEncaseBlock(
|
||||
world, fill, sourceTerrain));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sourceMaterialRejectsStructureBlocksAndOresBeforeDimensionFallback() {
|
||||
Map<BlockPos, BlockState> blocks = new HashMap<>();
|
||||
BlockPos fill = new BlockPos(4, -20, 8);
|
||||
put(blocks, 3, -20, 8, Blocks.OAK_PLANKS.defaultBlockState());
|
||||
put(blocks, 5, -20, 8, Blocks.STONE_BRICKS.defaultBlockState());
|
||||
put(blocks, 4, -20, 7, Blocks.IRON_ORE.defaultBlockState());
|
||||
|
||||
assertEquals(Blocks.DEEPSLATE.defaultBlockState(),
|
||||
NativeStructureTerrainIntegrator.sourceEncaseBlock(world(blocks), fill));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sourceMaterialSnapshotOnlyAllocatesActualFillLayers() {
|
||||
StructureStart start = start(TerrainAdjustment.BURY, 64);
|
||||
BoundingBox area = new BoundingBox(0, -2032, 0, 15, 2030, 15);
|
||||
NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceTerrain =
|
||||
NativeStructureTerrainIntegrator.captureSourceTerrain(
|
||||
world(new HashMap<>()), area,
|
||||
List.of(new NativeStructureTerrainIntegrator.TerrainTarget(
|
||||
"test:bounded-snapshot", start,
|
||||
new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE))));
|
||||
|
||||
assertNotNull(sourceTerrain);
|
||||
assertEquals(23 * 16 * 16, sourceTerrain.sampledCells());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void customDimensionKeyUsesRegisteredVanillaDimensionType() {
|
||||
ResourceKey<Level> customDimension = ResourceKey.create(
|
||||
Registries.DIMENSION, Identifier.parse("iris:custom_nether"));
|
||||
|
||||
assertEquals(Blocks.NETHERRACK.defaultBlockState(),
|
||||
NativeStructureTerrainIntegrator.defaultEncaseBlock(
|
||||
customDimension, BuiltinDimensionTypes.NETHER, null, 64));
|
||||
assertEquals(Blocks.END_STONE.defaultBlockState(),
|
||||
NativeStructureTerrainIntegrator.defaultEncaseBlock(
|
||||
customDimension, BuiltinDimensionTypes.END, null, 64));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void configuredEncasePaletteReplacesTheDefaultMaterial() {
|
||||
StructureStart start = start(TerrainAdjustment.BURY, 64);
|
||||
BoundingBox bounds = start.getPieces().getFirst().getBoundingBox();
|
||||
Map<BlockPos, BlockState> blocks = new HashMap<>();
|
||||
IrisMaterialPalette palette = new IrisMaterialPalette().qclear().qadd("minecraft:tuff");
|
||||
|
||||
NativeStructureTerrainIntegrator.integrateTerrain(
|
||||
world(blocks), bounds, "minecraft:stronghold", start,
|
||||
new IrisStructureTerrain()
|
||||
.setMode(IrisStructureTerrainMode.ENCASE)
|
||||
.setEncasePalette(palette),
|
||||
NativeStructurePostProcessorEncaseTest::tuffBlock);
|
||||
|
||||
assertEquals(Blocks.TUFF.defaultBlockState(),
|
||||
state(blocks, bounds.minX(), bounds.minY(), bounds.minZ()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encaseFillRunsBeforeNativePlacement() throws IOException {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.nmsChunkGeneratorSource"))).replace("\r\n", "\n");
|
||||
int prepareTerrain = source.indexOf("NativeStructurePostProcessor.prepareTerrain(");
|
||||
int placementLoop = source.indexOf("for (NativePlacementGroup group : placementGroups)", prepareTerrain);
|
||||
int placement = source.indexOf("placeVanillaStructure(world, structureManager, random", placementLoop);
|
||||
|
||||
assertTrue(prepareTerrain >= 0);
|
||||
assertTrue(placementLoop > prepareTerrain);
|
||||
assertTrue(placement > placementLoop);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void omittedTerrainConfigurationRetainsSourceSemantics() {
|
||||
for (TerrainAdjustment adjustment : TerrainAdjustment.values()) {
|
||||
IrisStructureTerrain resolved = NativeStructureTerrainIntegrator.resolveNativeTerrain(
|
||||
start(adjustment, 64), null);
|
||||
|
||||
assertEquals(IrisStructureTerrainMode.SOURCE, resolved.resolvedMode());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sourceBuryUsesTheVanillaSixByTwelveInfluenceEnvelope() {
|
||||
StructureStart start = start(TerrainAdjustment.BURY, 64);
|
||||
BoundingBox bounds = start.getPieces().getFirst().getBoundingBox();
|
||||
int groundY = bounds.minY();
|
||||
BoundingBox area = new BoundingBox(
|
||||
bounds.minX() - 7, groundY - 13, bounds.minZ(),
|
||||
bounds.maxX(), groundY + 13, bounds.maxZ());
|
||||
Map<BlockPos, BlockState> blocks = new HashMap<>();
|
||||
|
||||
NativeStructureTerrainIntegrator.integrateTerrain(
|
||||
world(blocks), area, "test:bury", start,
|
||||
new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE), null);
|
||||
|
||||
assertEquals(Blocks.STONE.defaultBlockState(),
|
||||
state(blocks, bounds.minX() - 5, groundY, bounds.minZ()));
|
||||
assertEquals(Blocks.STONE.defaultBlockState(),
|
||||
state(blocks, bounds.minX(), groundY + 11, bounds.minZ()));
|
||||
assertEquals(Blocks.AIR.defaultBlockState(),
|
||||
state(blocks, bounds.minX() - 6, groundY, bounds.minZ()));
|
||||
assertEquals(Blocks.AIR.defaultBlockState(),
|
||||
state(blocks, bounds.minX(), groundY + 12, bounds.minZ()));
|
||||
assertEquals(Blocks.AIR.defaultBlockState(),
|
||||
state(blocks, bounds.minX() - 7, groundY, bounds.minZ()));
|
||||
assertEquals(Blocks.AIR.defaultBlockState(),
|
||||
state(blocks, bounds.minX(), groundY + 13, bounds.minZ()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sourceEncapsulateWrapsTheFullPieceBounds() {
|
||||
StructureStart start = start(TerrainAdjustment.ENCAPSULATE, 64);
|
||||
BoundingBox bounds = start.getPieces().getFirst().getBoundingBox();
|
||||
BoundingBox area = new BoundingBox(
|
||||
bounds.minX() - 13, bounds.minY(), bounds.minZ(),
|
||||
bounds.maxX(), bounds.maxY() + 13, bounds.maxZ());
|
||||
Map<BlockPos, BlockState> blocks = new HashMap<>();
|
||||
|
||||
NativeStructureTerrainIntegrator.integrateTerrain(
|
||||
world(blocks), area, "test:encapsulate", start,
|
||||
new IrisStructureTerrain().setMode(IrisStructureTerrainMode.SOURCE), null);
|
||||
|
||||
assertEquals(Blocks.STONE.defaultBlockState(),
|
||||
state(blocks, bounds.minX() - 11, bounds.minY(), bounds.minZ()));
|
||||
assertEquals(Blocks.STONE.defaultBlockState(),
|
||||
state(blocks, bounds.minX(), bounds.maxY() + 11, bounds.minZ()));
|
||||
assertEquals(Blocks.AIR.defaultBlockState(),
|
||||
state(blocks, bounds.minX() - 12, bounds.minY(), bounds.minZ()));
|
||||
assertEquals(Blocks.AIR.defaultBlockState(),
|
||||
state(blocks, bounds.minX(), bounds.maxY() + 12, bounds.minZ()));
|
||||
assertEquals(Blocks.AIR.defaultBlockState(),
|
||||
state(blocks, bounds.minX() - 13, bounds.minY(), bounds.minZ()));
|
||||
assertEquals(Blocks.AIR.defaultBlockState(),
|
||||
state(blocks, bounds.minX(), bounds.maxY() + 13, bounds.minZ()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sourceTerrainDensityOnlyUsesRigidPoolPieces() {
|
||||
PoolElementStructurePiece terrainMatching = poolPiece(StructureTemplatePool.Projection.TERRAIN_MATCHING);
|
||||
PoolElementStructurePiece rigid = poolPiece(StructureTemplatePool.Projection.RIGID);
|
||||
|
||||
assertFalse(NativeStructureTerrainIntegrator.isSourceRigidPiece(terrainMatching));
|
||||
assertTrue(NativeStructureTerrainIntegrator.isSourceRigidPiece(rigid));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sourceJunctionTerrainUsesTheStrictLowerTwelveBlockEnvelope() {
|
||||
assertTrue(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(0, -1, 0));
|
||||
assertTrue(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(0, -11, 0));
|
||||
assertFalse(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(0, 0, 0));
|
||||
assertFalse(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(0, -12, 0));
|
||||
assertFalse(NativeStructureTerrainIntegrator.insideSourceJunctionEnvelope(12, -1, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void explicitTerrainConfigurationWinsOverAutoEncase() {
|
||||
IrisStructureTerrain configured = new IrisStructureTerrain()
|
||||
.setMode(IrisStructureTerrainMode.PRESERVE);
|
||||
|
||||
assertSame(configured, NativeStructureTerrainIntegrator.resolveNativeTerrain(
|
||||
start(TerrainAdjustment.BURY, 64), configured));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void legacyTemplateAirIsClearedAfterEveryTerrainFillPath() {
|
||||
IrisStructureTerrain source = new IrisStructureTerrain()
|
||||
.setMode(IrisStructureTerrainMode.SOURCE);
|
||||
IrisStructureTerrain preserve = new IrisStructureTerrain()
|
||||
.setMode(IrisStructureTerrainMode.PRESERVE);
|
||||
IrisStructureTerrain encase = new IrisStructureTerrain()
|
||||
.setMode(IrisStructureTerrainMode.ENCASE);
|
||||
|
||||
assertTrue(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir(
|
||||
start(TerrainAdjustment.BURY, 64), source));
|
||||
assertTrue(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir(
|
||||
start(TerrainAdjustment.BEARD_BOX, 64), source));
|
||||
assertTrue(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir(
|
||||
start(TerrainAdjustment.NONE, 64), encase));
|
||||
assertFalse(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir(
|
||||
start(TerrainAdjustment.NONE, 64), source));
|
||||
assertFalse(NativeStructureTerrainIntegrator.clearsLegacyTemplateAir(
|
||||
start(TerrainAdjustment.BURY, 64), preserve));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void encaseReservesTheNeighborChunkEnvelope() {
|
||||
StructureStart generated = start(TerrainAdjustment.BURY, 64);
|
||||
BoundingBox sourceBounds = generated.getBoundingBox();
|
||||
BoundingBox content = NativeStructureReferenceEnvelope.contentBounds(generated);
|
||||
IrisStructureTerrain terrain = new IrisStructureTerrain()
|
||||
.setMode(IrisStructureTerrainMode.ENCASE)
|
||||
.setHorizontalPadding(4);
|
||||
|
||||
StructureStart wrapped = NativeStructureReferenceEnvelope.wrap(
|
||||
generated,
|
||||
generated.getStructure(),
|
||||
0,
|
||||
terrain);
|
||||
BoundingBox referenceBounds = NativeStructureReferenceEnvelope.referenceBounds(
|
||||
wrapped, wrapped.getStructure(), terrain);
|
||||
|
||||
assertEquals(sourceBounds, wrapped.getBoundingBox());
|
||||
assertEquals(content.minX() - 4, referenceBounds.minX());
|
||||
assertEquals(content.maxX() + 4, referenceBounds.maxX());
|
||||
assertEquals(content.minZ() - 4, referenceBounds.minZ());
|
||||
assertEquals(content.maxZ() + 4, referenceBounds.maxZ());
|
||||
assertEquals(generated.getPieces().size(), wrapped.getPieces().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void referenceEnvelopeRejectsChunkCoordinateOverflow() {
|
||||
StructureStart generated = start(TerrainAdjustment.NONE, 64);
|
||||
StructureStart extreme = new StructureStart(
|
||||
generated.getStructure(), new ChunkPos(Integer.MAX_VALUE, 0), 0,
|
||||
new PiecesContainer(generated.getPieces()));
|
||||
|
||||
assertThrows(IllegalStateException.class, () ->
|
||||
NativeStructureReferenceEnvelope.referenceBounds(
|
||||
extreme, extreme.getStructure(), new IrisStructureTerrain()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void explicitTerrainEnvelopeDoesNotInheritSourceAdjustment() {
|
||||
StructureStart generated = start(TerrainAdjustment.BURY, 64);
|
||||
BoundingBox content = NativeStructureReferenceEnvelope.contentBounds(generated);
|
||||
IrisStructureTerrain terrain = new IrisStructureTerrain()
|
||||
.setMode(IrisStructureTerrainMode.ENCASE)
|
||||
.setHorizontalPadding(112);
|
||||
|
||||
StructureStart wrapped = NativeStructureReferenceEnvelope.wrap(
|
||||
generated, generated.getStructure(), 0, terrain);
|
||||
BoundingBox referenceBounds = NativeStructureReferenceEnvelope.referenceBounds(
|
||||
wrapped, wrapped.getStructure(), terrain);
|
||||
|
||||
assertEquals(content.minX() - 112, referenceBounds.minX());
|
||||
assertEquals(content.maxX() + 112, referenceBounds.maxX());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void yBandRelocatesTheStartMidpointDeterministically() {
|
||||
IrisStructureYBand band = new IrisStructureYBand().setMin(-120).setMax(-20);
|
||||
StructureStart first = start(TerrainAdjustment.BURY, 64);
|
||||
StructureStart second = start(TerrainAdjustment.BURY, 64);
|
||||
|
||||
NativeStructureVerticalPlacer.applyVerticalShift(
|
||||
first, -64, -256, 320, true, false, band, (x, z) -> 40);
|
||||
NativeStructureVerticalPlacer.applyVerticalShift(
|
||||
second, -64, -256, 320, true, false, band, (x, z) -> 40);
|
||||
|
||||
BoundingBox bounds = first.getBoundingBox();
|
||||
assertEquals(bounds.minY(), second.getBoundingBox().minY());
|
||||
assertTrue(bounds.minY() >= -120);
|
||||
assertTrue(bounds.maxY() <= -20);
|
||||
|
||||
int repeated = NativeStructureVerticalPlacer.applyVerticalShift(
|
||||
first, -64, -256, 320, true, false, band, (x, z) -> 40);
|
||||
assertEquals(0, repeated);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void yBandClampsWhenTheBandCannotContainTheStructure() {
|
||||
IrisStructureYBand band = new IrisStructureYBand().setMin(-50).setMax(-45);
|
||||
StructureStart start = start(TerrainAdjustment.BURY, 64);
|
||||
|
||||
NativeStructureVerticalPlacer.applyVerticalShift(
|
||||
start, 0, -256, 320, true, false, band, (x, z) -> 40);
|
||||
|
||||
BoundingBox bounds = start.getBoundingBox();
|
||||
int midpoint = bounds.minY() + (bounds.maxY() - bounds.minY()) / 2;
|
||||
assertTrue(midpoint >= -50);
|
||||
assertTrue(midpoint <= -45);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void yBandReplacesBothTheBlindShiftAndBurial() {
|
||||
IrisStructureYBand band = new IrisStructureYBand().setMin(-64).setMax(-64);
|
||||
StructureStart start = start(TerrainAdjustment.BURY, 64);
|
||||
BoundingBox bounds = start.getBoundingBox();
|
||||
int height = bounds.maxY() - bounds.minY();
|
||||
|
||||
NativeStructureVerticalPlacer.applyVerticalShift(
|
||||
start, -200, -256, 320, true, false, band, (x, z) -> 40);
|
||||
|
||||
assertEquals(-64 - height / 2, start.getBoundingBox().minY());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void preserveSourceYWinsOverTheConfiguredBand() {
|
||||
IrisStructureYBand band = new IrisStructureYBand().setMin(-120).setMax(-20);
|
||||
StructureStart start = start(TerrainAdjustment.BURY, 64);
|
||||
int minY = start.getBoundingBox().minY();
|
||||
|
||||
int offset = NativeStructureVerticalPlacer.applyVerticalShift(
|
||||
start, 0, -256, 320, true, true, band, (x, z) -> 40);
|
||||
|
||||
assertEquals(0, offset);
|
||||
assertEquals(minY, start.getBoundingBox().minY());
|
||||
}
|
||||
|
||||
private static BlockState tuffBlock(IrisMaterialPalette palette, RNG rng, int x, int y, int z) {
|
||||
assertNotNull(palette);
|
||||
assertNotNull(rng);
|
||||
return Blocks.TUFF.defaultBlockState();
|
||||
}
|
||||
|
||||
private static StructureStart start(TerrainAdjustment adjustment, int minY) {
|
||||
Structure structure = new DesertPyramidStructure(new Structure.StructureSettings(
|
||||
HolderSet.empty(), Map.of(), GenerationStep.Decoration.STRONGHOLDS, adjustment));
|
||||
StructurePiece piece = new DesertPyramidPiece(RandomSource.create(7L), 0, 0);
|
||||
piece.move(0, minY - piece.getBoundingBox().minY(), 0);
|
||||
return new StructureStart(
|
||||
structure, new ChunkPos(0, 0), 0, new PiecesContainer(List.of(piece)));
|
||||
}
|
||||
|
||||
private static PoolElementStructurePiece poolPiece(StructureTemplatePool.Projection projection) {
|
||||
BlockPos position = new BlockPos(0, 64, 0);
|
||||
StructurePoolElement element = StructurePoolElement.single(
|
||||
"minecraft:empty",
|
||||
Holder.direct(new StructureProcessorList(List.of(
|
||||
BlockIgnoreProcessor.STRUCTURE_AND_AIR))),
|
||||
LiquidSettings.APPLY_WATERLOGGING
|
||||
).apply(projection);
|
||||
return new PoolElementStructurePiece(
|
||||
null,
|
||||
element,
|
||||
position,
|
||||
0,
|
||||
Rotation.NONE,
|
||||
new BoundingBox(position),
|
||||
LiquidSettings.APPLY_WATERLOGGING);
|
||||
}
|
||||
|
||||
private static WorldGenLevel world(Map<BlockPos, BlockState> blocks) {
|
||||
InvocationHandler handler = (proxy, method, arguments) -> {
|
||||
String methodName = method.getName();
|
||||
if (methodName.equals("getBlockState")) {
|
||||
BlockPos position = (BlockPos) arguments[0];
|
||||
return state(blocks, position.getX(), position.getY(), position.getZ());
|
||||
}
|
||||
if (methodName.equals("setBlock")) {
|
||||
BlockPos position = (BlockPos) arguments[0];
|
||||
BlockState blockState = (BlockState) arguments[1];
|
||||
put(blocks, position.getX(), position.getY(), position.getZ(), blockState);
|
||||
return true;
|
||||
}
|
||||
if (methodName.equals("getSeed")) {
|
||||
return TEST_SEED;
|
||||
}
|
||||
if (methodName.equals("getLevel")) {
|
||||
return null;
|
||||
}
|
||||
if (methodName.equals("hashCode")) {
|
||||
return System.identityHashCode(proxy);
|
||||
}
|
||||
if (methodName.equals("equals")) {
|
||||
return proxy == arguments[0];
|
||||
}
|
||||
if (methodName.equals("toString")) {
|
||||
return "encase-test-world";
|
||||
}
|
||||
throw new UnsupportedOperationException(method.toString());
|
||||
};
|
||||
return (WorldGenLevel) Proxy.newProxyInstance(
|
||||
WorldGenLevel.class.getClassLoader(), new Class<?>[]{WorldGenLevel.class}, handler);
|
||||
}
|
||||
|
||||
private static NativeStructureTerrainIntegrator.SourceTerrainSnapshot sourceSnapshot(
|
||||
WorldGenLevel world, BoundingBox area) {
|
||||
BitSet requiredLayers = new BitSet(area.getYSpan());
|
||||
requiredLayers.set(0, area.getYSpan());
|
||||
return NativeStructureTerrainIntegrator.SourceTerrainSnapshot.capture(
|
||||
world, area, requiredLayers);
|
||||
}
|
||||
|
||||
private static void put(Map<BlockPos, BlockState> blocks,
|
||||
int x, int y, int z, BlockState state) {
|
||||
blocks.put(new BlockPos(x, y, z), state);
|
||||
}
|
||||
|
||||
private static BlockState state(Map<BlockPos, BlockState> blocks, int x, int y, int z) {
|
||||
return blocks.getOrDefault(new BlockPos(x, y, z), Blocks.AIR.defaultBlockState());
|
||||
}
|
||||
}
|
||||
+12
-17
@@ -1,7 +1,6 @@
|
||||
package art.arcane.iris.nativegen;
|
||||
|
||||
import art.arcane.iris.engine.object.IrisStructureTerrain;
|
||||
import art.arcane.iris.engine.object.IrisStructureTerrainMode;
|
||||
import art.arcane.iris.engine.framework.NativeStructureReach;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.Direction;
|
||||
import net.minecraft.core.HolderSet;
|
||||
@@ -41,7 +40,7 @@ public class NativeStructurePostProcessorMonumentTest {
|
||||
StructureStart start = monumentStart(1337L);
|
||||
|
||||
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
start, "minecraft:monument", 0, 63, -64, 320, false, false, null, (x, z) -> 0);
|
||||
start, "minecraft:monument", 0, 63, -64, 320, (x, z) -> 0);
|
||||
|
||||
assertEquals(0, offset);
|
||||
assertEquals(39, start.getBoundingBox().minY());
|
||||
@@ -57,7 +56,7 @@ public class NativeStructurePostProcessorMonumentTest {
|
||||
BoundingBox cachedBounds = start.getBoundingBox();
|
||||
|
||||
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
start, "minecraft:monument", 0, 50, -256, 512, false, false, null, (x, z) -> 0);
|
||||
start, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0);
|
||||
|
||||
assertEquals(-13, offset);
|
||||
assertSame(cachedBounds, start.getBoundingBox());
|
||||
@@ -71,7 +70,7 @@ public class NativeStructurePostProcessorMonumentTest {
|
||||
}
|
||||
|
||||
int repeatedOffset = NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
start, "minecraft:monument", 0, 50, -256, 512, false, false, null, (x, z) -> 0);
|
||||
start, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0);
|
||||
assertEquals(0, repeatedOffset);
|
||||
}
|
||||
|
||||
@@ -80,7 +79,7 @@ public class NativeStructurePostProcessorMonumentTest {
|
||||
StructureStart start = monumentStart(1337L);
|
||||
|
||||
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
start, "minecraft:monument", 3, 50, -256, 512, false, false, null, (x, z) -> 0);
|
||||
start, "minecraft:monument", 3, 50, -256, 512, (x, z) -> 0);
|
||||
|
||||
assertEquals(-10, offset);
|
||||
assertEquals(29, start.getBoundingBox().minY());
|
||||
@@ -94,13 +93,10 @@ public class NativeStructurePostProcessorMonumentTest {
|
||||
start,
|
||||
start.getStructure(),
|
||||
0,
|
||||
new IrisStructureTerrain()
|
||||
.setMode(IrisStructureTerrainMode.FORCE_CARVE)
|
||||
.setHorizontalPadding(4));
|
||||
List.of(new NativeStructureReach(false, 4)));
|
||||
|
||||
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
wrapped, "minecraft:monument", 0, 63, -64, 320,
|
||||
false, false, null, (x, z) -> 0);
|
||||
wrapped, "minecraft:monument", 0, 63, -64, 320, (x, z) -> 0);
|
||||
|
||||
assertEquals(0, offset);
|
||||
assertEquals(1, wrapped.getPieces().size());
|
||||
@@ -112,7 +108,7 @@ public class NativeStructurePostProcessorMonumentTest {
|
||||
ChunkPos chunkPos = new ChunkPos(0, 0);
|
||||
StructureStart initial = monumentStart(seed);
|
||||
NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
initial, "minecraft:monument", 0, 50, -256, 512, false, false, null, (x, z) -> 0);
|
||||
initial, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0);
|
||||
|
||||
PiecesContainer regenerated = OceanMonumentStructure.regeneratePiecesAfterLoad(
|
||||
chunkPos, seed, new PiecesContainer(initial.getPieces()));
|
||||
@@ -121,7 +117,7 @@ public class NativeStructurePostProcessorMonumentTest {
|
||||
|
||||
assertEquals(39, reloaded.getBoundingBox().minY());
|
||||
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
reloaded, "minecraft:monument", 0, 50, -256, 512, false, false, null, (x, z) -> 0);
|
||||
reloaded, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0);
|
||||
assertEquals(-13, offset);
|
||||
assertEquals(26, reloaded.getBoundingBox().minY());
|
||||
assertEquals(48, reloaded.getBoundingBox().maxY());
|
||||
@@ -133,8 +129,7 @@ public class NativeStructurePostProcessorMonumentTest {
|
||||
ChunkPos chunkPos = new ChunkPos(0, 0);
|
||||
StructureStart initial = monumentStart(seed);
|
||||
NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
initial, "minecraft:monument", 0, 50, -256, 512,
|
||||
false, false, null, (x, z) -> 0);
|
||||
initial, "minecraft:monument", 0, 50, -256, 512, (x, z) -> 0);
|
||||
PiecesContainer regenerated = OceanMonumentStructure.regeneratePiecesAfterLoad(
|
||||
chunkPos, seed, new PiecesContainer(initial.getPieces()));
|
||||
StructureStart reloaded = new StructureStart(
|
||||
@@ -147,7 +142,7 @@ public class NativeStructurePostProcessorMonumentTest {
|
||||
futures.add(executor.submit(() -> {
|
||||
release.await();
|
||||
NativeStructureVerticalPlacer.ensureMonumentSeaLevelAlignment(
|
||||
reloaded, "minecraft:monument", 0, 50, -256, 512);
|
||||
reloaded, "minecraft:monument", () -> 0, 50, -256, 512);
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
@@ -168,7 +163,7 @@ public class NativeStructurePostProcessorMonumentTest {
|
||||
StructureStart start = monumentStart(1337L);
|
||||
try {
|
||||
NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
start, "minecraft:monument", 0, -50, -64, 320, false, false, null, (x, z) -> 0);
|
||||
start, "minecraft:monument", 0, -50, -64, 320, (x, z) -> 0);
|
||||
} catch (IllegalStateException error) {
|
||||
assertTrue(error.getMessage().contains("cannot align"));
|
||||
return;
|
||||
|
||||
+12
-14
@@ -11,6 +11,7 @@ import net.minecraft.world.level.levelgen.structure.ScatteredFeaturePiece;
|
||||
import net.minecraft.world.level.levelgen.structure.Structure;
|
||||
import net.minecraft.world.level.levelgen.structure.StructurePiece;
|
||||
import net.minecraft.world.level.levelgen.structure.StructureStart;
|
||||
import net.minecraft.world.level.levelgen.structure.TerrainAdjustment;
|
||||
import net.minecraft.world.level.levelgen.structure.pieces.PiecesContainer;
|
||||
import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidPiece;
|
||||
import net.minecraft.world.level.levelgen.structure.structures.DesertPyramidStructure;
|
||||
@@ -46,8 +47,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
|
||||
BoundingBox footprint = piece.getBoundingBox();
|
||||
|
||||
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
start, "minecraft:desert_pyramid", 0, 63, -64, 320, false, false, null,
|
||||
(x, z) -> x == footprint.maxX() && z == footprint.maxZ() ? 64 : 92);
|
||||
start, "minecraft:desert_pyramid", 0, 63, -64, 320, (x, z) -> x == footprint.maxX() && z == footprint.maxZ() ? 64 : 92);
|
||||
|
||||
assertEquals(1, offset);
|
||||
assertSame(cachedBounds, start.getBoundingBox());
|
||||
@@ -64,8 +64,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
|
||||
BoundingBox footprint = piece.getBoundingBox();
|
||||
|
||||
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
start, "minecraft:jungle_pyramid", 4, 63, -64, 320, false, false, null,
|
||||
(x, z) -> x == footprint.minX() && z == footprint.minZ() ? 88 : 70);
|
||||
start, "minecraft:jungle_pyramid", 4, 63, -64, 320, (x, z) -> x == footprint.minX() && z == footprint.minZ() ? 88 : 70);
|
||||
|
||||
assertEquals(11, offset);
|
||||
assertEquals(75, piece.getBoundingBox().minY());
|
||||
@@ -79,9 +78,9 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
|
||||
StructureStart start = desertStart(piece);
|
||||
|
||||
int initialOffset = NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
start, "minecraft:desert_pyramid", 0, 63, -64, 320, false, false, null, (x, z) -> 80);
|
||||
start, "minecraft:desert_pyramid", 0, 63, -64, 320, (x, z) -> 80);
|
||||
int repeatedOffset = NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
start, "minecraft:desert_pyramid", 0, 63, -64, 320, false, false, null, (x, z) -> 80);
|
||||
start, "minecraft:desert_pyramid", 0, 63, -64, 320, (x, z) -> 80);
|
||||
|
||||
assertEquals(17, initialOffset);
|
||||
assertEquals(0, repeatedOffset);
|
||||
@@ -94,7 +93,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
|
||||
StructureStart start = desertStart(piece);
|
||||
|
||||
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
start, "minecraft:desert_pyramid", 0, 63, -64, 320, false, false, null, (x, z) -> 318);
|
||||
start, "minecraft:desert_pyramid", 0, 63, -64, 320, (x, z) -> 318);
|
||||
|
||||
assertEquals(241, offset);
|
||||
assertEquals(305, piece.getBoundingBox().minY());
|
||||
@@ -110,14 +109,13 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
|
||||
StructureStart jungleStart = jungleStart(jungle);
|
||||
StructureStart swampStart = swampStart(swamp);
|
||||
|
||||
assertFalse(NativeStructureSurfaceFitter.requiresSurfaceTerrain(desertStart));
|
||||
assertFalse(NativeStructureSurfaceFitter.requiresSurfaceTerrain(jungleStart));
|
||||
assertFalse(NativeStructureSurfaceFitter.requiresSurfaceTerrain(swampStart));
|
||||
assertEquals(TerrainAdjustment.NONE, desertStart.getStructure().terrainAdaptation());
|
||||
assertEquals(TerrainAdjustment.NONE, jungleStart.getStructure().terrainAdaptation());
|
||||
assertEquals(TerrainAdjustment.NONE, swampStart.getStructure().terrainAdaptation());
|
||||
|
||||
AtomicInteger terrainQueries = new AtomicInteger();
|
||||
int offset = NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
swampStart, "minecraft:swamp_hut", 0, 63, -64, 320, false, false, null,
|
||||
(x, z) -> terrainQueries.incrementAndGet());
|
||||
swampStart, "minecraft:swamp_hut", 0, 63, -64, 320, (x, z) -> terrainQueries.incrementAndGet());
|
||||
assertEquals(0, offset);
|
||||
assertEquals(0, terrainQueries.get());
|
||||
assertEquals(64, swamp.getBoundingBox().minY());
|
||||
@@ -142,7 +140,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
|
||||
int pyramidMinY = pyramidOverride.getBoundingBox().minY();
|
||||
int pyramidOffset = NativeStructureVerticalPlacer.applyVerticalPlacement(
|
||||
pyramidOverride, "minecraft:desert_pyramid", 5,
|
||||
63, -64, 320, false, false, null, (x, z) -> 200);
|
||||
63, -64, 320, (x, z) -> 200);
|
||||
|
||||
assertEquals(5, pyramidOffset);
|
||||
assertEquals(pyramidMinY + 5, pyramidOverride.getBoundingBox().minY());
|
||||
@@ -151,7 +149,7 @@ public class NativeStructurePostProcessorScatteredFeatureTest {
|
||||
new SwampHutPiece(RandomSource.create(47L), 0, 0));
|
||||
int monumentMinY = monumentOverride.getBoundingBox().minY();
|
||||
NativeStructureVerticalPlacer.ensureMonumentSeaLevelAlignment(
|
||||
monumentOverride, "minecraft:monument", 0, 40, -64, 320);
|
||||
monumentOverride, "minecraft:monument", () -> 0, 40, -64, 320);
|
||||
|
||||
assertEquals(monumentMinY, monumentOverride.getBoundingBox().minY());
|
||||
}
|
||||
|
||||
-2375
File diff suppressed because it is too large.
Load diff
-15
@@ -173,21 +173,6 @@ public class NativeStructurePostProcessorVegetationTest {
|
||||
GenerationStep.Decoration.SURFACE_STRUCTURES));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void undergroundStructuresUseTheLowestTerrainColumn() {
|
||||
BoundingBox bounds = new BoundingBox(0, 60, 0, 1, 80, 0);
|
||||
int offset = NativeStructureVerticalPlacer.resolveBuriedOffset(
|
||||
bounds, 0, -64, 320, (x, z) -> x == 1 ? 76 : 100);
|
||||
assertEquals(-5, offset);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void undergroundBurialClampsToTheWorldFloorInsteadOfFailing() {
|
||||
BoundingBox bounds = new BoundingBox(0, 60, 0, 1, 80, 0);
|
||||
assertEquals(-2, NativeStructureVerticalPlacer.resolveBuriedOffset(
|
||||
bounds, 0, 58, 320, (x, z) -> x == 1 ? 76 : 100));
|
||||
}
|
||||
|
||||
private static void clearVegetation(ProtoChunk chunk, StructureStart start) {
|
||||
NativeStructureVegetationClearer.clearIntersectingVegetation(
|
||||
world(chunk), chunk, AREA, List.of(start));
|
||||
|
||||
+2
-2
@@ -123,8 +123,8 @@ public class NativeStructureVolumeIndexTest {
|
||||
public void vanillaVolumesAreGatedOnPackPolicy() throws Exception {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.nativeStructureVolumeIndexSource")));
|
||||
|
||||
assertTrue(source.contains("NativeStructureGenerationPolicy.resolve("));
|
||||
assertTrue(source.contains("if (!decision.generate())"));
|
||||
assertTrue(source.contains("if (!NativeStructureGenerationPolicy.generates(engine, structureId))"));
|
||||
assertTrue(source.contains("NativeStructureLayouts.shift(engine"));
|
||||
assertTrue(source.contains("isStructureChunk("));
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ String volmLibCoordinate = providers.gradleProperty('volmLibCoordinate')
|
||||
|
||||
dependencies {
|
||||
compileOnly(project(':core'))
|
||||
// The structure commands look up structures through the module's PackResources lookups; core shades the API.
|
||||
compileOnly('com.volmit:iris-api')
|
||||
compileOnly(libs.lombok)
|
||||
annotationProcessor(libs.lombok)
|
||||
compileOnly(volmLibCoordinate) {
|
||||
@@ -21,7 +23,11 @@ dependencies {
|
||||
testImplementation('org.mockito:mockito-core:5.23.0')
|
||||
testImplementation(libs.paper.api)
|
||||
testImplementation(libs.bstats)
|
||||
testImplementation(libs.caffeine)
|
||||
testImplementation(libs.paralithic)
|
||||
testImplementation(project(':core'))
|
||||
// Iris's objects are API placeable objects, so tests that read them compile against the API too.
|
||||
testImplementation('com.volmit:iris-api')
|
||||
testImplementation(volmLibCoordinate) {
|
||||
transitive = false
|
||||
}
|
||||
@@ -60,13 +66,15 @@ tasks.named('jar', Jar).configure {
|
||||
|
||||
tasks.named('test').configure {
|
||||
systemProperty('iris.commandFindSource', file('src/main/java/art/arcane/iris/core/commands/CommandFind.java').absolutePath)
|
||||
systemProperty('iris.commandStructureSource', file('src/main/java/art/arcane/iris/core/commands/CommandStructure.java').absolutePath)
|
||||
systemProperty('iris.importCommandsSource', rootProject.file('module/src/main/java/art/arcane/iris/core/structure/tooling/ImportCommands.java').absolutePath)
|
||||
systemProperty('iris.studioLifecycleCommandsSource', rootProject.file('module/src/main/java/art/arcane/iris/core/structure/tooling/StudioLifecycleCommands.java').absolutePath)
|
||||
systemProperty('iris.commandIrisSource', file('src/main/java/art/arcane/iris/core/commands/CommandIris.java').absolutePath)
|
||||
systemProperty('iris.bukkitChunkGeneratorSource', rootProject.file('core/src/main/java/art/arcane/iris/engine/platform/BukkitChunkGenerator.java').absolutePath)
|
||||
systemProperty('iris.pregeneratorJobSource', rootProject.file('core/src/main/java/art/arcane/iris/core/gui/PregeneratorJob.java').absolutePath)
|
||||
systemProperty('iris.bukkitEnginePlatformHooksSource', file('src/main/java/art/arcane/iris/core/runtime/BukkitEnginePlatformHooks.java').absolutePath)
|
||||
systemProperty('iris.engineSvcSource', file('src/main/java/art/arcane/iris/core/service/IrisEngineSVC.java').absolutePath)
|
||||
systemProperty('iris.jigsawStudioSvcSource', rootProject.file('core/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java').absolutePath)
|
||||
systemProperty('iris.jigsawStudioSvcSource', rootProject.file('module/src/main/java/art/arcane/iris/core/service/JigsawStudioService.java').absolutePath)
|
||||
systemProperty('iris.toolWorldServiceSource', file('src/main/java/art/arcane/iris/core/toolworld/BukkitToolWorldService.java').absolutePath)
|
||||
systemProperty('iris.studioSvcSource', rootProject.file('core/src/main/java/art/arcane/iris/core/service/StudioSVC.java').absolutePath)
|
||||
systemProperty('iris.terrainSvcSource', file('src/main/java/art/arcane/iris/core/service/IrisTerrainSVC.java').absolutePath)
|
||||
systemProperty('iris.apiEventSvcSource', file('src/main/java/art/arcane/iris/core/service/IrisApiEventSVC.java').absolutePath)
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
package art.arcane.iris;
|
||||
|
||||
import art.arcane.iris.engine.IrisEngineEffects;
|
||||
import art.arcane.iris.engine.data.cache.AtomicCacheFailureReporting;
|
||||
import art.arcane.iris.engine.IrisWorldManager;
|
||||
|
||||
import art.arcane.iris.engine.framework.EngineComponentCleanup;
|
||||
@@ -38,6 +39,7 @@ import art.arcane.iris.core.SettingsHotloadWatch;
|
||||
import art.arcane.iris.core.ServerConfigurator;
|
||||
import art.arcane.iris.core.datapack.DatapackIngestService;
|
||||
import art.arcane.iris.core.datapack.DatapackIngestService.StartupValidationOutcome;
|
||||
import art.arcane.iris.core.lifecycle.IrisRuntimeStatics;
|
||||
import art.arcane.iris.core.lifecycle.ManagedWorldLoader;
|
||||
import art.arcane.iris.core.lifecycle.MissingWorldStorageLog;
|
||||
import art.arcane.iris.core.lifecycle.PaperLibBootstrap;
|
||||
@@ -45,15 +47,23 @@ import art.arcane.iris.core.lifecycle.WorldLifecycleService;
|
||||
import art.arcane.iris.core.runtime.BukkitEnginePlatformHooks;
|
||||
import art.arcane.iris.core.runtime.WorldDeletionQueue;
|
||||
import art.arcane.iris.core.runtime.WorldRuntimeControlService;
|
||||
import art.arcane.iris.core.toolworld.BukkitToolWorldService;
|
||||
import art.arcane.iris.core.structure.BukkitPlatformStructures;
|
||||
import art.arcane.iris.core.tooling.ToolWorldsHost;
|
||||
import com.volmit.tooling.PlatformStructures;
|
||||
import art.arcane.iris.api.terrain.IrisTerrainService;
|
||||
import art.arcane.iris.core.link.CustomBlockSource;
|
||||
import art.arcane.iris.core.link.IrisPapiInstaller;
|
||||
import art.arcane.iris.core.link.IrisPapiListener;
|
||||
import art.arcane.iris.core.link.IrisPapiState;
|
||||
import art.arcane.iris.core.localization.IrisLanguage;
|
||||
import art.arcane.iris.core.link.MultiverseCoreLink;
|
||||
import art.arcane.iris.core.agent.AttachSignal;
|
||||
import art.arcane.iris.core.nms.INMS;
|
||||
import art.arcane.iris.core.gui.BukkitGuiHost;
|
||||
import art.arcane.iris.core.gui.GuiHost;
|
||||
import art.arcane.iris.core.gui.PregeneratorJob;
|
||||
import art.arcane.iris.core.service.BlockRulesSVC;
|
||||
import art.arcane.iris.core.service.BoardSVC;
|
||||
import art.arcane.iris.core.service.CommandSVC;
|
||||
import art.arcane.iris.core.service.DatapackStructureScopeSVC;
|
||||
@@ -66,13 +76,13 @@ import art.arcane.iris.core.service.IrisEngineSVC;
|
||||
import art.arcane.iris.core.service.IrisIntegrationService;
|
||||
import art.arcane.iris.core.service.IrisProtocolService;
|
||||
import art.arcane.iris.core.service.IrisTerrainSVC;
|
||||
import art.arcane.iris.core.service.JigsawStudioService;
|
||||
import art.arcane.iris.core.service.LogFilterSVC;
|
||||
import art.arcane.iris.core.service.MultiverseSVC;
|
||||
import art.arcane.iris.core.service.ObjectSVC;
|
||||
import art.arcane.iris.core.service.ObjectStudioSaveService;
|
||||
import art.arcane.iris.core.service.PreservationSVC;
|
||||
import art.arcane.iris.core.service.StudioSVC;
|
||||
import art.arcane.iris.core.studio.bridge.StudioBridges;
|
||||
import art.arcane.iris.core.service.TreeFellerSVC;
|
||||
import art.arcane.iris.core.service.TreeSVC;
|
||||
import art.arcane.iris.core.service.WandSVC;
|
||||
@@ -81,7 +91,7 @@ import art.arcane.iris.engine.EnginePanic;
|
||||
import art.arcane.iris.engine.framework.BlockEditAccess;
|
||||
import art.arcane.iris.engine.framework.PreservationRegistry;
|
||||
import art.arcane.iris.engine.framework.TreeBlockMaterial;
|
||||
import art.arcane.iris.engine.object.IrisCompat;
|
||||
import art.arcane.iris.engine.object.compatibility.IrisCompat;
|
||||
import art.arcane.iris.core.safeguard.IrisSafeguard;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
@@ -200,19 +210,25 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
private final PendingWorldDeleteQueue pendingWorldDeletes = new PendingWorldDeleteQueue(this);
|
||||
private final PendingWorldReplacementManager pendingWorldReplacements = new PendingWorldReplacementManager(this);
|
||||
private volatile SettingsHotloadWatch settingsHotloadWatch;
|
||||
private volatile Thread serverLifecycleThread;
|
||||
|
||||
public static VolmitSender getSender() {
|
||||
if (sender == null) {
|
||||
sender = new VolmitSender(Bukkit.getConsoleSender());
|
||||
sender.setTag(instance.getTag());
|
||||
VolmitSender current = sender;
|
||||
if (current == null) {
|
||||
Iris plugin = instance;
|
||||
current = new VolmitSender(Bukkit.getConsoleSender());
|
||||
current.setTag(plugin == null ? IrisSafeguard.mode().tag("") : plugin.getTag());
|
||||
sender = current;
|
||||
}
|
||||
return sender;
|
||||
return current;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T service(Class<T> c) {
|
||||
return (T) instance.services.get(c);
|
||||
Iris plugin = instance;
|
||||
if (plugin == null || plugin.services == null) {
|
||||
throw new IllegalStateException("Iris is disabled; " + c.getSimpleName() + " is unavailable");
|
||||
}
|
||||
return (T) plugin.services.get(c);
|
||||
}
|
||||
|
||||
public static void callEvent(Event e) {
|
||||
@@ -251,7 +267,11 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
}
|
||||
|
||||
public static File getTemp() {
|
||||
return instance.getDataFolder("cache", "temp");
|
||||
Iris plugin = instance;
|
||||
if (plugin == null) {
|
||||
throw new IllegalStateException("Iris is disabled; the temp folder is unavailable");
|
||||
}
|
||||
return plugin.getDataFolder("cache", "temp");
|
||||
}
|
||||
|
||||
public static void msg(String string) {
|
||||
@@ -520,12 +540,23 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
Iris::msg,
|
||||
Iris::reportError,
|
||||
(event) -> Iris.callEvent((org.bukkit.event.Event) event),
|
||||
() -> Iris.instance.getDataFolder(),
|
||||
(path) -> Iris.instance.getDataFile(path),
|
||||
() -> Iris.instance.getJarFile(),
|
||||
() -> Iris.instance.getIrisVersion(),
|
||||
() -> Iris.instance.getMCVersion()));
|
||||
this::getDataFolder,
|
||||
this::getDataFile,
|
||||
this::getJarFile,
|
||||
this::getIrisVersion,
|
||||
this::getMCVersion));
|
||||
SlimJar.load();
|
||||
restoreAttachSignal();
|
||||
}
|
||||
|
||||
private static void restoreAttachSignal() {
|
||||
try {
|
||||
if (AttachSignal.restoreJvmHandler()) {
|
||||
info("Restored the JVM SIGQUIT handler that the server console replaced");
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
reportError("Could not restore the JVM SIGQUIT handler; the Iris agent may fail to attach.", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static void bridgeLog(LogLevel level, String message) {
|
||||
@@ -560,15 +591,18 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the section-sign colours core writes but reads nothing else as markup: a diagnostic quotes pack files,
|
||||
* whose text may hold tag-like or ampersand sequences that have to show as written.
|
||||
*/
|
||||
private static void diagnostic(Level level, String message) {
|
||||
String line = IrisLogging.clean(message);
|
||||
Iris plugin = instance;
|
||||
ComponentLog.log(
|
||||
plugin,
|
||||
Logger.getLogger("Iris"),
|
||||
logPrefix(plugin),
|
||||
level,
|
||||
ComponentText.literal(line),
|
||||
ComponentText.section(message),
|
||||
null);
|
||||
}
|
||||
|
||||
@@ -609,7 +643,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
// Explicit, ordered service list: the previous reflective jar scan gave hash-ordered
|
||||
// enable/disable and paid a full-jar class sweep at boot. Infrastructure first,
|
||||
// engine/world services next, commands last.
|
||||
List<IrisService> orderedServices = List.of(
|
||||
List<IrisService> orderedServices = new ArrayList<>(List.of(
|
||||
new PreservationSVC(),
|
||||
new GlobalCacheSVC(),
|
||||
new LogFilterSVC(),
|
||||
@@ -617,7 +651,6 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
new EditSVC(),
|
||||
new ObjectSVC(),
|
||||
new ObjectStudioSaveService(),
|
||||
new JigsawStudioService(),
|
||||
new StudioSVC(),
|
||||
new DatapackStructureScopeSVC(),
|
||||
new IrisEngineSVC(),
|
||||
@@ -627,18 +660,26 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
new EntityRiseSVC(),
|
||||
new WandSVC(),
|
||||
new BoardSVC(),
|
||||
new BukkitToolWorldService(),
|
||||
new IrisIntegrationService(),
|
||||
new MultiverseSVC(),
|
||||
new IrisProtocolService(),
|
||||
new IrisApiEventSVC(),
|
||||
new CommandSVC()
|
||||
);
|
||||
));
|
||||
if (BlockRulesSVC.isSupported()) {
|
||||
int commandServiceIndex = orderedServices.size() - 1;
|
||||
orderedServices.add(commandServiceIndex, new BlockRulesSVC());
|
||||
}
|
||||
for (IrisService i : orderedServices) {
|
||||
Class<? extends IrisService> serviceType = i.getClass().asSubclass(IrisService.class);
|
||||
services.put(serviceType, i);
|
||||
IrisServices.register(serviceType, i);
|
||||
}
|
||||
IrisServices.register(ToolWorldsHost.class, services.get(BukkitToolWorldService.class));
|
||||
IrisServices.register(PlatformStructures.class, new BukkitPlatformStructures());
|
||||
IrisServices.register(BlockEditAccess.class, services.get(EditSVC.class));
|
||||
IrisServices.register(CustomBlockSource.class, services.get(ExternalDataSVC.class));
|
||||
IrisServices.register(PreservationRegistry.class, services.get(PreservationSVC.class));
|
||||
compat = IrisCompat.configured(getDataFile("compat.json"));
|
||||
IrisServices.register(IrisCompat.class, compat);
|
||||
@@ -732,7 +773,6 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
|
||||
public void addShutdownHook() {
|
||||
removeShutdownHook();
|
||||
serverLifecycleThread = Thread.currentThread();
|
||||
shutdownHook = new Thread(this::runShutdownHook, "Iris-ShutdownHook");
|
||||
try {
|
||||
Runtime.getRuntime().addShutdownHook(shutdownHook);
|
||||
@@ -804,6 +844,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
|
||||
public void onEnable() {
|
||||
IrisPlatforms.bind(new BukkitPlatform());
|
||||
AtomicCacheFailureReporting.bind();
|
||||
IrisStartupValidation.begin();
|
||||
Bukkit.getPluginManager().registerEvents(new IrisStartupAdmissionListener(), this);
|
||||
Bukkit.getPluginManager().registerEvents(pendingWorldReplacements, this);
|
||||
@@ -820,6 +861,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
return;
|
||||
}
|
||||
BukkitGuiHost.install();
|
||||
postShutdown(GuiHost::closeWindows);
|
||||
// super.onEnable() already registers this instance as a listener.
|
||||
super.onEnable();
|
||||
if (IrisStartupValidation.isRestartRequired()) {
|
||||
@@ -862,6 +904,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
pendingWorldReplacements.awaitStagingForShutdown();
|
||||
teardownPapi();
|
||||
boolean serverStopping = IrisToolbelt.isServerStopping();
|
||||
boolean restartingAtStartupBoundary = startupBoundaryRestart.get();
|
||||
@@ -948,27 +991,38 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
J.attempt(MultiBurst.burst::close);
|
||||
J.attempt(MultiBurst.ioBurst::close);
|
||||
clearQueues();
|
||||
IrisServices.clear();
|
||||
IrisRuntimeStatics.reset();
|
||||
releaseStatics();
|
||||
}
|
||||
}
|
||||
|
||||
private static void releaseStatics() {
|
||||
linkMultiverseCore = null;
|
||||
compat = null;
|
||||
tickets = null;
|
||||
sender = null;
|
||||
instance = null;
|
||||
}
|
||||
|
||||
private void quiesceRuntimeForServerShutdown(String reason) {
|
||||
serverStopTeardownDeferred.set(true);
|
||||
JigsawStudioService jigsawStudioService = IrisServices.getOrNull(JigsawStudioService.class);
|
||||
if (jigsawStudioService != null) {
|
||||
try {
|
||||
jigsawStudioService.quiesceForServerShutdown();
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError("Failed to quiesce Jigsaw Studio before server shutdown.", e);
|
||||
}
|
||||
}
|
||||
StudioSVC studioService = IrisServices.getOrNull(StudioSVC.class);
|
||||
if (studioService != null) {
|
||||
studioService.quiesceDownloadsForShutdown();
|
||||
}
|
||||
StudioBridges.closeAll();
|
||||
|
||||
try {
|
||||
PregeneratorJob.shutdownAndWait(SERVER_STOP_PREGEN_TIMEOUT_MILLIS);
|
||||
if (J.isFolia()) {
|
||||
PregeneratorJob.shutdownAndWait(SERVER_STOP_PREGEN_TIMEOUT_MILLIS);
|
||||
} else {
|
||||
List<World> worlds = Bukkit.getWorlds();
|
||||
PregeneratorJob.shutdownAndWait(SERVER_STOP_PREGEN_TIMEOUT_MILLIS, () -> {
|
||||
for (World world : worlds) {
|
||||
INMS.get().pollChunkTask(world);
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError("Failed to quiesce the Iris pregenerator before server shutdown.", e);
|
||||
}
|
||||
@@ -978,7 +1032,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
if (generator == null) {
|
||||
continue;
|
||||
}
|
||||
IrisToolbelt.beginWorldMaintenance(world, reason, true);
|
||||
IrisToolbelt.beginWorldMaintenance(world, reason);
|
||||
if (!deferredShutdownGenerators.contains(generator)) {
|
||||
deferredShutdownGenerators.add(generator);
|
||||
}
|
||||
@@ -990,51 +1044,31 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
if (!postStopFinisherStarted.compareAndSet(false, true)) {
|
||||
return;
|
||||
}
|
||||
Thread activeServerThread = serverLifecycleThread;
|
||||
if (activeServerThread == null) {
|
||||
Iris.warn("Iris could not start its post-stop runtime finisher because the server lifecycle thread is unavailable.");
|
||||
return;
|
||||
}
|
||||
|
||||
Thread finisher = new Thread(() -> {
|
||||
if (!awaitServerThreadTermination(activeServerThread)) {
|
||||
return;
|
||||
}
|
||||
finishDeferredRuntimeTeardown("post-server-stop", 30L);
|
||||
}, "Iris-PostStop-Finisher");
|
||||
Thread finisher = new Thread(() -> finishRuntimeAfterServerShutdown("post-server-stop"),
|
||||
"Iris-PostStop-Finisher");
|
||||
finisher.setDaemon(false);
|
||||
finisher.start();
|
||||
}
|
||||
|
||||
static boolean awaitServerThreadTermination(Thread serverThread) {
|
||||
if (serverThread == null || serverThread == Thread.currentThread()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
serverThread.join();
|
||||
return true;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
Iris.reportError("Iris post-stop runtime finisher was interrupted.", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void runShutdownHook() {
|
||||
if (startupBoundaryRestart.get()) {
|
||||
finishDeferredRuntimeTeardown("startup-boundary-restart-hook", 30L);
|
||||
return;
|
||||
}
|
||||
finishRuntimeAfterServerShutdown("shutdown-hook");
|
||||
}
|
||||
|
||||
private void finishRuntimeAfterServerShutdown(String reason) {
|
||||
if (!awaitServerShutdownBoundary()) {
|
||||
Iris.warn("Iris skipped JVM-hook runtime teardown because Paper did not reach its post-world-close boundary.");
|
||||
Iris.warn("Iris retained its runtime and plugin class loader because the server did not reach its post-world-close boundary.");
|
||||
return;
|
||||
}
|
||||
finishDeferredRuntimeTeardown("shutdown-hook", 30L);
|
||||
finishDeferredRuntimeTeardown(reason, 30L);
|
||||
}
|
||||
|
||||
private boolean awaitServerShutdownBoundary() {
|
||||
if (!INMS.isBound()) {
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return INMS.get().awaitServerShutdownBoundary(
|
||||
@@ -1063,6 +1097,7 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
Iris.reportError("Failed to run Iris post-shutdown cleanup.", e);
|
||||
} finally {
|
||||
IrisPlatforms.unbind();
|
||||
BukkitPlatform.releaseHost();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1244,14 +1279,17 @@ public class Iris extends VolmitPlugin implements Listener, ReloadAware {
|
||||
}
|
||||
|
||||
public int getIrisVersion() {
|
||||
String input = Iris.instance.getDescription().getVersion();
|
||||
String input = getDescription().getVersion();
|
||||
int hyphenIndex = input.indexOf('-');
|
||||
if (hyphenIndex != -1) {
|
||||
String result = input.substring(0, hyphenIndex);
|
||||
result = result.replaceAll("\\.", "");
|
||||
return Integer.parseInt(result);
|
||||
String release = hyphenIndex < 0 ? input : input.substring(0, hyphenIndex);
|
||||
if (!release.matches("[0-9]+(?:\\.[0-9]+)*")) {
|
||||
return -1;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(release.replace(".", ""));
|
||||
} catch (NumberFormatException invalid) {
|
||||
return -1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int getMCVersion() {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package art.arcane.iris.api.tree;
|
||||
|
||||
public interface TreeFellerRunHooks {
|
||||
default boolean requiresSneaking() {
|
||||
return true;
|
||||
}
|
||||
|
||||
TreeFellerRunHooks NONE = new TreeFellerRunHooks() {
|
||||
@Override
|
||||
public void onActivationAccepted() {
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ import art.arcane.iris.core.lifecycle.BukkitWorldConfiguration;
|
||||
import art.arcane.iris.core.lifecycle.LifecycleOperationCoordinator;
|
||||
import art.arcane.iris.core.nms.INMS;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.platform.bukkit.BukkitEnvironment;
|
||||
import art.arcane.iris.util.common.format.C;
|
||||
import art.arcane.iris.util.common.misc.ServerProperties;
|
||||
|
||||
+70
-19
@@ -28,10 +28,12 @@ import art.arcane.iris.core.pack.PackValidationCache;
|
||||
import art.arcane.iris.core.pack.PackValidationRegistry;
|
||||
import art.arcane.iris.core.pack.PackValidationResult;
|
||||
import art.arcane.iris.core.pack.PackValidator;
|
||||
import art.arcane.iris.core.service.ExternalDataSVC;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisWorld;
|
||||
import art.arcane.iris.spi.IrisServices;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.object.world.IrisWorld;
|
||||
import art.arcane.iris.engine.platform.BukkitChunkGenerator;
|
||||
import art.arcane.iris.util.common.plugin.VolmitPlugin;
|
||||
import art.arcane.volmlib.util.bukkit.WorldIdentity;
|
||||
@@ -60,6 +62,8 @@ import java.util.function.Supplier;
|
||||
*/
|
||||
public final class IrisWorldGeneratorResolver {
|
||||
private static final int VALIDATION_STABILITY_ATTEMPTS = 2;
|
||||
private static final String STARTUP_CACHE_FILE = "pack-validation.json";
|
||||
private static final String PLUGIN_CONTENT_CACHE_FILE = "pack-validation-with-plugin-content.json";
|
||||
private static final Object SNAPSHOT_VALIDATION_LOCK = new Object();
|
||||
private static final String IRIS_DIMENSION_NAMESPACE = "iris";
|
||||
private static final String PLOT_SQUARED_DISCOVERY_WORLD = "CheckingPlotSquaredGenerator";
|
||||
@@ -70,12 +74,71 @@ public final class IrisWorldGeneratorResolver {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates every pack before worlds load, so a broken pack refuses its worlds. Block plugins like CraftEngine
|
||||
* register their blocks only after that, so the warnings wait for them: once they have loaded, a pack is validated
|
||||
* again when the registry changed, and only then does it report the keys that are still unknown.
|
||||
*/
|
||||
public void validateAllPacks() {
|
||||
PackValidationRun startupRun = validateAndPublish(STARTUP_CACHE_FILE);
|
||||
reportBlockingErrors(startupRun.results());
|
||||
IrisStartupValidation.markPacksReady();
|
||||
IrisServices.get(ExternalDataSVC.class).afterProviderContentLoads(() -> reportWarningsWithPluginContent(startupRun));
|
||||
}
|
||||
|
||||
private void reportWarningsWithPluginContent(PackValidationRun startupRun) {
|
||||
if (safeContextFingerprint().equals(startupRun.contextFingerprint())) {
|
||||
reportWarnings(startupRun);
|
||||
return;
|
||||
}
|
||||
reportWarnings(validateAndPublish(PLUGIN_CONTENT_CACHE_FILE));
|
||||
}
|
||||
|
||||
private static String safeContextFingerprint() {
|
||||
try {
|
||||
return PackValidationCache.contextFingerprint();
|
||||
} catch (RuntimeException exception) {
|
||||
Iris.reportError("Could not fingerprint the pack-validation context", exception);
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
private static void reportBlockingErrors(List<PackValidationResult> results) {
|
||||
for (PackValidationResult result : results) {
|
||||
if (result.isLoadable()) {
|
||||
continue;
|
||||
}
|
||||
Iris.error("Pack '" + result.getPackName()
|
||||
+ "' FAILED validation - world and Studio creation with this pack will be refused. Reasons:");
|
||||
for (String reason : result.getBlockingErrors()) {
|
||||
Iris.error(" - " + reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void reportWarnings(PackValidationRun run) {
|
||||
for (PackValidationResult result : run.results()) {
|
||||
if (!result.isLoadable()) {
|
||||
continue;
|
||||
}
|
||||
if (!result.getWarnings().isEmpty()) {
|
||||
Iris.info("Pack '" + result.getPackName() + "' validated ("
|
||||
+ result.getWarnings().size() + " warning(s)).");
|
||||
for (String warning : result.getWarnings()) {
|
||||
Iris.warn(" [" + result.getPackName() + "] " + warning);
|
||||
}
|
||||
} else if (!run.fromCache()) {
|
||||
Iris.success("Pack '" + result.getPackName() + "' validated.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PackValidationRun validateAndPublish(String cacheFileName) {
|
||||
File packsRoot = plugin.getDataFolder("packs");
|
||||
List<File> packDirs = PackDirectoryResolver.listVisiblePackDirectories(packsRoot);
|
||||
PackValidationRegistry.clear();
|
||||
List<String> packNames = packDirs.stream().map(File::getName).sorted().toList();
|
||||
Path cacheFile = IrisPlatforms.get().dataFile("cache", "pack-validation.json").toPath();
|
||||
Path cacheFile = IrisPlatforms.get().dataFile("cache", cacheFileName).toPath();
|
||||
ServerConfigurator.PackContentSnapshot contentSnapshot =
|
||||
new ServerConfigurator.PackContentSnapshot("", Map.of());
|
||||
String contextFingerprint = "";
|
||||
@@ -123,23 +186,8 @@ public final class IrisWorldGeneratorResolver {
|
||||
if (packDirectory != null && packFingerprint != null && !packFingerprint.isBlank()) {
|
||||
PackValidationRegistry.publish(packDirectory.toPath(), result, packFingerprint);
|
||||
}
|
||||
if (!result.isLoadable()) {
|
||||
Iris.error("Pack '" + result.getPackName()
|
||||
+ "' FAILED validation - world and Studio creation with this pack will be refused. Reasons:");
|
||||
for (String reason : result.getBlockingErrors()) {
|
||||
Iris.error(" - " + reason);
|
||||
}
|
||||
} else if (!result.getWarnings().isEmpty()) {
|
||||
Iris.info("Pack '" + result.getPackName() + "' validated ("
|
||||
+ result.getWarnings().size() + " warning(s)).");
|
||||
for (String warning : result.getWarnings()) {
|
||||
Iris.warn(" [" + result.getPackName() + "] " + warning);
|
||||
}
|
||||
} else if (cached.isEmpty()) {
|
||||
Iris.success("Pack '" + result.getPackName() + "' validated.");
|
||||
}
|
||||
}
|
||||
IrisStartupValidation.markPacksReady();
|
||||
return new PackValidationRun(results, contextFingerprint, cached.isPresent());
|
||||
}
|
||||
|
||||
private static FreshValidation validateStablePacks(
|
||||
@@ -495,6 +543,9 @@ public final class IrisWorldGeneratorResolver {
|
||||
return new BukkitChunkGenerator(world, false, snapshotRoot, dimension.getLoadKey());
|
||||
}
|
||||
|
||||
private record PackValidationRun(List<PackValidationResult> results, String contextFingerprint, boolean fromCache) {
|
||||
}
|
||||
|
||||
private record FreshValidation(
|
||||
List<File> packDirs,
|
||||
ServerConfigurator.PackContentSnapshot contentSnapshot,
|
||||
|
||||
+60
-3
@@ -19,8 +19,8 @@ import art.arcane.iris.core.pack.PackValidationRegistry;
|
||||
import art.arcane.iris.core.runtime.WorldRuntimeControlService;
|
||||
import art.arcane.iris.core.service.StudioSVC;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisEnvironment;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.object.world.IrisEnvironment;
|
||||
import art.arcane.iris.engine.platform.BukkitChunkGenerator;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import art.arcane.iris.util.common.misc.ServerProperties;
|
||||
@@ -55,6 +55,7 @@ import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
@@ -73,6 +74,9 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
private volatile UUID overworldEntryAwaitingVerification;
|
||||
private volatile World overworldEntryWorld;
|
||||
private volatile boolean paperEntryListenerRegistered;
|
||||
private final Object stagingMonitor = new Object();
|
||||
private boolean stagingAdmissionOpen = true;
|
||||
private StagingAdmission activeStaging;
|
||||
|
||||
public PendingWorldReplacementManager(Iris plugin) {
|
||||
this.plugin = Objects.requireNonNull(plugin, "plugin");
|
||||
@@ -135,7 +139,7 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
LifecycleOperationCoordinator.Domain.WORLD_MUTATION,
|
||||
LifecycleOperationCoordinator.OperationKind.WORLD_REPLACE,
|
||||
requiredWorldKey.toString()
|
||||
)) {
|
||||
); StagingAdmission stagingAdmission = admitStaging(requiredWorldKey)) {
|
||||
if (findTransaction(requiredWorldSlotKey) != null) {
|
||||
throw new IOException("A replacement is already pending for " + requiredWorldKey + ".");
|
||||
}
|
||||
@@ -251,6 +255,29 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
}
|
||||
}
|
||||
|
||||
public void awaitStagingForShutdown() {
|
||||
StagingAdmission staging;
|
||||
synchronized (stagingMonitor) {
|
||||
stagingAdmissionOpen = false;
|
||||
staging = activeStaging;
|
||||
}
|
||||
if (staging == null) {
|
||||
return;
|
||||
}
|
||||
Iris.warn("Waiting for the replacement of " + staging.worldKey + " to finish staging before Iris shuts down.");
|
||||
boolean interrupted = false;
|
||||
while (staging.finished.getCount() > 0L) {
|
||||
try {
|
||||
staging.finished.await();
|
||||
} catch (InterruptedException e) {
|
||||
interrupted = true;
|
||||
}
|
||||
}
|
||||
if (interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void processPendingStartupReplacements() {
|
||||
ArrayList<String> failures = new ArrayList<>();
|
||||
ArrayList<String> restartBoundaries = new ArrayList<>();
|
||||
@@ -993,6 +1020,17 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
return plugin.getDataFolder().toPath().toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
StagingAdmission admitStaging(NamespacedKey worldKey) throws IOException {
|
||||
synchronized (stagingMonitor) {
|
||||
if (!stagingAdmissionOpen) {
|
||||
throw new IOException("Iris is shutting down. Run the replacement again after the server starts.");
|
||||
}
|
||||
StagingAdmission staging = new StagingAdmission(worldKey);
|
||||
activeStaging = staging;
|
||||
return staging;
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void loadOverworldEntryGuard() throws IOException {
|
||||
ExactWorldSlotPathPolicy.Target target = resolveTarget(OVERWORLD_KEY);
|
||||
Optional<WorldReplacementEntryGuard.Entry> loaded = WorldReplacementEntryGuard.load(target.worldDirectory());
|
||||
@@ -1157,6 +1195,25 @@ public final class PendingWorldReplacementManager implements Listener {
|
||||
}
|
||||
}
|
||||
|
||||
final class StagingAdmission implements AutoCloseable {
|
||||
private final NamespacedKey worldKey;
|
||||
private final CountDownLatch finished = new CountDownLatch(1);
|
||||
|
||||
private StagingAdmission(NamespacedKey worldKey) {
|
||||
this.worldKey = worldKey;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
synchronized (stagingMonitor) {
|
||||
if (activeStaging == this) {
|
||||
activeStaging = null;
|
||||
}
|
||||
}
|
||||
finished.countDown();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class RestartBoundaryRequired extends IOException {
|
||||
private RestartBoundaryRequired(String message) {
|
||||
super(message);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package art.arcane.iris.core.agent;
|
||||
|
||||
import java.lang.foreign.Arena;
|
||||
import java.lang.foreign.FunctionDescriptor;
|
||||
import java.lang.foreign.Linker;
|
||||
import java.lang.foreign.MemorySegment;
|
||||
import java.lang.foreign.ValueLayout;
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.util.Locale;
|
||||
|
||||
public final class AttachSignal {
|
||||
private static final int SIGQUIT = 3;
|
||||
private static final int SIGTERM = 15;
|
||||
private static final long ACTION_BYTES = 256;
|
||||
private static final long SIG_IGN = 1L;
|
||||
|
||||
private AttachSignal() {
|
||||
}
|
||||
|
||||
public static boolean restoreJvmHandler() {
|
||||
if (System.getProperty("os.name", "").toLowerCase(Locale.ROOT).contains("win")) {
|
||||
return false;
|
||||
}
|
||||
Linker linker = Linker.nativeLinker();
|
||||
MethodHandle sigaction = linker.downcallHandle(
|
||||
linker.defaultLookup().find("sigaction")
|
||||
.orElseThrow(() -> new IllegalStateException("sigaction is unavailable")),
|
||||
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
|
||||
try (Arena arena = Arena.ofConfined()) {
|
||||
MemorySegment jvm = arena.allocate(ACTION_BYTES);
|
||||
MemorySegment quit = arena.allocate(ACTION_BYTES);
|
||||
if ((int) sigaction.invokeExact(SIGTERM, MemorySegment.NULL, jvm) != 0
|
||||
|| (int) sigaction.invokeExact(SIGQUIT, MemorySegment.NULL, quit) != 0) {
|
||||
throw new IllegalStateException("sigaction could not read the SIGTERM and SIGQUIT handlers");
|
||||
}
|
||||
long handler = jvm.get(ValueLayout.JAVA_LONG, 0);
|
||||
if (handler == 0L || handler == SIG_IGN || quit.get(ValueLayout.JAVA_LONG, 0) == handler) {
|
||||
return false;
|
||||
}
|
||||
if ((int) sigaction.invokeExact(SIGQUIT, jvm, MemorySegment.NULL) != 0) {
|
||||
throw new IllegalStateException("sigaction could not restore the JVM SIGQUIT handler");
|
||||
}
|
||||
return true;
|
||||
} catch (RuntimeException | Error failure) {
|
||||
throw failure;
|
||||
} catch (Throwable failure) {
|
||||
throw new IllegalStateException("Unable to restore the JVM SIGQUIT handler", failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -32,7 +32,7 @@ import art.arcane.iris.core.tools.IrisPackBenchmarking;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.engine.IrisEngineMantle;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import art.arcane.iris.util.project.matter.IrisMatterContext;
|
||||
import art.arcane.iris.util.common.director.DirectorExecutor;
|
||||
|
||||
+44
-50
@@ -19,23 +19,22 @@
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.core.loader.IrisRegistrant;
|
||||
import art.arcane.iris.core.localization.BukkitCommandMessagesExtended;
|
||||
import art.arcane.iris.core.localization.IrisLanguage;
|
||||
import art.arcane.iris.core.project.StudioEditor;
|
||||
import art.arcane.iris.core.project.StudioEditorLauncher;
|
||||
import art.arcane.iris.core.service.StudioSVC;
|
||||
import art.arcane.iris.engine.object.IrisBiome;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisRegion;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.util.common.director.DirectorExecutor;
|
||||
import art.arcane.volmlib.util.director.DirectorOrigin;
|
||||
import art.arcane.volmlib.util.director.annotations.Director;
|
||||
import art.arcane.volmlib.util.director.annotations.Param;
|
||||
import art.arcane.iris.util.common.format.C;
|
||||
|
||||
import java.awt.Desktop;
|
||||
import java.awt.GraphicsEnvironment;
|
||||
|
||||
|
||||
import art.arcane.iris.core.localization.IrisLanguage;
|
||||
import art.arcane.iris.core.localization.BukkitCommandMessagesExtended;
|
||||
import art.arcane.volmlib.util.localization.MessageArgument;
|
||||
import art.arcane.volmlib.util.localization.TextKey;
|
||||
|
||||
@Director(name = "edit", origin = DirectorOrigin.PLAYER, description = "Edit something", descriptionKey = "iris.director.commandedit.director.edit_something")
|
||||
public class CommandEdit implements DirectorExecutor {
|
||||
private boolean noStudio() {
|
||||
@@ -51,72 +50,67 @@ public class CommandEdit implements DirectorExecutor {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_YOU_MUST_BE_STUDIO_WORLD));
|
||||
return true;
|
||||
}
|
||||
return editorUnavailable();
|
||||
}
|
||||
|
||||
if (GraphicsEnvironment.isHeadless()) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_OPEN_FILES_HEADLESS_ENVIRONMENTS));
|
||||
private boolean editorUnavailable() {
|
||||
StudioEditor editor = StudioEditorLauncher.configuredEditor();
|
||||
if (editor == StudioEditor.NONE) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_NO_EDITOR_SET));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!Desktop.isDesktopSupported()) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_DESKTOP_IS_NOT_SUPPORTED_BY_THIS_ENVIRONMENT));
|
||||
if (!StudioEditorLauncher.canLaunch(editor)) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_OPEN_FILES_HEADLESS_ENVIRONMENTS));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@Director(description = "Edit the biome you specified", descriptionKey = "iris.director.commandedit.director.edit_biome_you_specified", aliases = {"b"}, origin = DirectorOrigin.PLAYER)
|
||||
public void biome(@Param(contextual = false, description = "The biome to edit", descriptionKey = "iris.director.commandedit.param.biome_edit") IrisBiome biome) {
|
||||
if (noStudio()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (biome == null || biome.getLoadFile() == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM));
|
||||
return;
|
||||
}
|
||||
Desktop.getDesktop().open(biome.getLoadFile());
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_VSCODE, MessageArgument.untrusted("value", biome.getTypeName()), MessageArgument.untrusted("value2", biome.getLoadFile().getName().split("\\Q.\\E")[0])));
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError(e);
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST));
|
||||
}
|
||||
edit(biome,
|
||||
BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM,
|
||||
BukkitCommandMessagesExtended.COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST);
|
||||
}
|
||||
|
||||
@Director(description = "Edit the region you specified", descriptionKey = "iris.director.commandedit.director.edit_region_you_specified", aliases = {"r"}, origin = DirectorOrigin.PLAYER)
|
||||
public void region(@Param(contextual = false, description = "The region to edit", descriptionKey = "iris.director.commandedit.param.region_edit") IrisRegion region) {
|
||||
if (noStudio()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (region == null || region.getLoadFile() == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM_2));
|
||||
return;
|
||||
}
|
||||
Desktop.getDesktop().open(region.getLoadFile());
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_VSCODE_2, MessageArgument.untrusted("value", region.getTypeName()), MessageArgument.untrusted("value2", region.getLoadFile().getName().split("\\Q.\\E")[0])));
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError(e);
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST_2));
|
||||
}
|
||||
edit(region,
|
||||
BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM_2,
|
||||
BukkitCommandMessagesExtended.COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST_2);
|
||||
}
|
||||
|
||||
@Director(description = "Edit the dimension you specified", descriptionKey = "iris.director.commandedit.director.edit_dimension_you_specified", aliases = {"d"}, origin = DirectorOrigin.PLAYER)
|
||||
public void dimension(@Param(contextual = false, description = "The dimension to edit", descriptionKey = "iris.director.commandedit.param.dimension_edit") IrisDimension dimension) {
|
||||
edit(dimension,
|
||||
BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM_3,
|
||||
BukkitCommandMessagesExtended.COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST_3);
|
||||
}
|
||||
|
||||
private void edit(IrisRegistrant registrant, TextKey fileMissing, TextKey openFailed) {
|
||||
if (noStudio()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
if (dimension == null || dimension.getLoadFile() == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM_3));
|
||||
if (registrant == null || registrant.getLoadFile() == null) {
|
||||
sender().sendMessage(IrisLanguage.text(fileMissing));
|
||||
return;
|
||||
}
|
||||
Desktop.getDesktop().open(dimension.getLoadFile());
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_VSCODE_3, MessageArgument.untrusted("value", dimension.getTypeName()), MessageArgument.untrusted("value2", dimension.getLoadFile().getName().split("\\Q.\\E")[0])));
|
||||
openInEditor(registrant);
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError(e);
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANT_FIND_FILE_REGISTRANT_DOES_NOT_EXIST_3));
|
||||
sender().sendMessage(IrisLanguage.text(openFailed));
|
||||
}
|
||||
}
|
||||
|
||||
private void openInEditor(IrisRegistrant registrant) {
|
||||
MessageArgument editor = MessageArgument.untrusted("editor", StudioEditorLauncher.configuredEditor().displayName());
|
||||
if (registrant.openInEditor() == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_COULD_NOT_OPEN_EDITOR, editor));
|
||||
return;
|
||||
}
|
||||
String fileName = registrant.getLoadFile().getName().split("\\Q.\\E")[0];
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_IN_EDITOR,
|
||||
MessageArgument.untrusted("value", registrant.getTypeName()), MessageArgument.untrusted("value2", fileName), editor));
|
||||
}
|
||||
}
|
||||
+40
-43
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.core.modules.ModuleServices;
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.core.localization.BukkitCommandMessages;
|
||||
import art.arcane.iris.core.localization.BukkitCommandMessagesExtended;
|
||||
@@ -25,13 +26,11 @@ import art.arcane.iris.core.localization.IrisLanguage;
|
||||
import art.arcane.iris.core.datapack.DatapackIngestService;
|
||||
import art.arcane.iris.core.service.ObjectStudioSaveService;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.IrisStructureLocator;
|
||||
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
|
||||
import art.arcane.iris.engine.framework.StructureReachability;
|
||||
import art.arcane.iris.engine.object.IrisBiome;
|
||||
import art.arcane.iris.engine.object.IrisNativeStructureDecision;
|
||||
import art.arcane.iris.engine.object.IrisRegion;
|
||||
import art.arcane.iris.engine.object.NativeStructureGenerationStatus;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
|
||||
import art.arcane.iris.engine.platform.EngineBukkitOps;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
@@ -143,20 +142,20 @@ public class CommandFind implements DirectorExecutor {
|
||||
String structureKey = structure == null ? "" : structure.trim();
|
||||
Structure nativeStructure = resolveNativeStructure(structureKey);
|
||||
boolean registered = nativeStructure != null;
|
||||
IrisNativeStructureDecision decision = registered
|
||||
? NativeStructureGenerationPolicy.resolve(e, structureKey, false)
|
||||
NativeStructureGenerationStatus status = registered
|
||||
? NativeStructureGenerationPolicy.resolve(e, structureKey)
|
||||
: null;
|
||||
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(e, structureKey);
|
||||
boolean locatableNativePlacement = IrisStructureLocator.hasLocatableNativePlacement(e, structureKey);
|
||||
boolean locatableEditablePlacement = IrisStructureLocator.hasLocatableEditablePlacement(e, structureKey);
|
||||
boolean nativePlacement = ModuleServices.startsStructure(e, structureKey);
|
||||
boolean locatableNativePlacement = ModuleServices.canLocateStart(e, structureKey);
|
||||
boolean locatableEditablePlacement = ModuleServices.canLocateStructure(e, structureKey);
|
||||
World targetWorld = target.getWorld();
|
||||
boolean nativeGenerationEnabled = targetWorld.canGenerateStructures();
|
||||
boolean requiresReachability = registered && decision.generate()
|
||||
&& decision.status() != NativeStructureGenerationStatus.REPLACED_BY_IRIS
|
||||
boolean requiresReachability = registered && status == NativeStructureGenerationStatus.GENERATE_NATIVE
|
||||
&& status != NativeStructureGenerationStatus.REPLACED_BY_IRIS
|
||||
&& nativeGenerationEnabled;
|
||||
boolean reachable = !requiresReachability || StructureReachability.isReachable(e, structureKey);
|
||||
StructureLookupRoute route = selectStructureLookupRoute(
|
||||
registered, decision, nativePlacement, locatableNativePlacement,
|
||||
registered, status, nativePlacement, locatableNativePlacement,
|
||||
locatableEditablePlacement, nativeGenerationEnabled, reachable);
|
||||
|
||||
if (route == StructureLookupRoute.UNKNOWN) {
|
||||
@@ -165,7 +164,7 @@ public class CommandFind implements DirectorExecutor {
|
||||
}
|
||||
if (route == StructureLookupRoute.POLICY_DISABLED) {
|
||||
commandSender.sendMessage(C.RED + NativeStructureGenerationPolicy.generationStatusMessage(
|
||||
structureKey, decision.status()));
|
||||
structureKey, status));
|
||||
return;
|
||||
}
|
||||
if (route == StructureLookupRoute.NO_ACTIVE_PLACEMENT) {
|
||||
@@ -272,58 +271,58 @@ public class CommandFind implements DirectorExecutor {
|
||||
for (Map.Entry<String, String> entry : registeredKeys.entrySet()) {
|
||||
String normalizedKey = entry.getKey();
|
||||
String key = entry.getValue();
|
||||
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, key, false);
|
||||
boolean nativePlacement = IrisStructureLocator.hasNativePlacement(engine, key);
|
||||
boolean locatableNativePlacement = IrisStructureLocator.hasLocatableNativePlacement(engine, key);
|
||||
boolean locatableEditablePlacement = IrisStructureLocator.hasLocatableEditablePlacement(engine, key);
|
||||
NativeStructureGenerationStatus status = NativeStructureGenerationPolicy.resolve(engine, key);
|
||||
boolean nativePlacement = ModuleServices.startsStructure(engine, key);
|
||||
boolean locatableNativePlacement = ModuleServices.canLocateStart(engine, key);
|
||||
boolean locatableEditablePlacement = ModuleServices.canLocateStructure(engine, key);
|
||||
StructureLookupRoute route = selectStructureLookupRoute(
|
||||
true, decision, nativePlacement, locatableNativePlacement,
|
||||
true, status, nativePlacement, locatableNativePlacement,
|
||||
locatableEditablePlacement, nativeGenerationEnabled,
|
||||
reachableKeys.contains(normalizedKey));
|
||||
if (route == StructureLookupRoute.IRIS || route == StructureLookupRoute.NATIVE) {
|
||||
continue;
|
||||
}
|
||||
List<String> requiredBiomes = needsNativeReachabilityReason(route, decision)
|
||||
List<String> requiredBiomes = needsNativeReachabilityReason(route, status)
|
||||
? structureHooks.structureBiomeKeys(key)
|
||||
: List.of();
|
||||
exclusions.add(new StructureExclusion(
|
||||
StructureExclusionKind.EXCLUDED, key, null,
|
||||
describeStructureExclusion(
|
||||
route, key, decision.status(), nativePlacement,
|
||||
route, key, status, nativePlacement,
|
||||
requiredBiomes, possibleBiomeKeys)));
|
||||
registeredExcluded++;
|
||||
}
|
||||
|
||||
int configuredUnregistered = 0;
|
||||
Set<String> configuredUnregisteredKeys = new LinkedHashSet<>();
|
||||
for (String configuredKey : IrisStructureLocator.placedKeys(engine)) {
|
||||
for (String configuredKey : ModuleServices.placedStructures(engine)) {
|
||||
String normalizedKey = normalizeStructureKey(configuredKey);
|
||||
if (normalizedKey.isEmpty()
|
||||
|| registeredKeys.containsKey(normalizedKey)
|
||||
|| !IrisStructureLocator.hasNativePlacement(engine, configuredKey)
|
||||
|| !ModuleServices.startsStructure(engine, configuredKey)
|
||||
|| !configuredUnregisteredKeys.add(normalizedKey)) {
|
||||
continue;
|
||||
}
|
||||
exclusions.add(new StructureExclusion(
|
||||
StructureExclusionKind.UNREGISTERED, configuredKey, null,
|
||||
describeConfiguredUnregisteredNative(
|
||||
IrisStructureLocator.hasLocatableNativePlacement(engine, configuredKey))));
|
||||
ModuleServices.canLocateStart(engine, configuredKey))));
|
||||
configuredUnregistered++;
|
||||
}
|
||||
|
||||
int editableUnplaced = 0;
|
||||
Set<String> unplacedEditableKeys = new LinkedHashSet<>();
|
||||
Set<String> locatableEditableKeys = normalizedStructureKeys(
|
||||
IrisStructureLocator.locatableEditableKeys(engine));
|
||||
for (String editableKey : engine.getData().getStructureLoader().getPossibleKeys()) {
|
||||
ModuleServices.locatableStructures(engine));
|
||||
for (String editableKey : ModuleServices.structureKeys(engine.getData())) {
|
||||
String normalizedKey = normalizeStructureKey(editableKey);
|
||||
if (!isUnplacedEditableCandidate(
|
||||
normalizedKey, registeredKeys.keySet(), locatableEditableKeys,
|
||||
IrisStructureLocator.hasNativePlacement(engine, editableKey))
|
||||
ModuleServices.startsStructure(engine, editableKey))
|
||||
|| !unplacedEditableKeys.add(normalizedKey)) {
|
||||
continue;
|
||||
}
|
||||
boolean configuredPlacement = IrisStructureLocator.hasEditablePlacement(engine, editableKey);
|
||||
boolean configuredPlacement = ModuleServices.placesStructure(engine, editableKey);
|
||||
String reason = configuredPlacement
|
||||
? "editable Iris structure has a configured placement, but no matching placement is active "
|
||||
+ "because its density is not positive or its Y band does not intersect this world"
|
||||
@@ -334,7 +333,7 @@ public class CommandFind implements DirectorExecutor {
|
||||
}
|
||||
|
||||
Set<String> configuredImportUrls = normalizedImportUrls(
|
||||
engine.getDimension().getDatapackImports());
|
||||
DatapackIngestService.configuredImports(engine.getDimension()));
|
||||
return new StructureExclusionReport(
|
||||
List.copyOf(exclusions), Set.copyOf(registeredKeys.keySet()),
|
||||
configuredImportUrls, registeredExcluded, configuredUnregistered,
|
||||
@@ -417,9 +416,9 @@ public class CommandFind implements DirectorExecutor {
|
||||
}
|
||||
|
||||
private static boolean needsNativeReachabilityReason(
|
||||
StructureLookupRoute route, IrisNativeStructureDecision decision) {
|
||||
StructureLookupRoute route, NativeStructureGenerationStatus status) {
|
||||
return route == StructureLookupRoute.UNREACHABLE
|
||||
|| route == StructureLookupRoute.NO_ACTIVE_PLACEMENT && decision.generate();
|
||||
|| route == StructureLookupRoute.NO_ACTIVE_PLACEMENT && status == NativeStructureGenerationStatus.GENERATE_NATIVE;
|
||||
}
|
||||
|
||||
static String describeStructureExclusion(
|
||||
@@ -528,7 +527,7 @@ public class CommandFind implements DirectorExecutor {
|
||||
}
|
||||
|
||||
static StructureLookupRoute selectStructureLookupRoute(
|
||||
boolean registered, IrisNativeStructureDecision decision, boolean nativePlacement,
|
||||
boolean registered, NativeStructureGenerationStatus status, boolean nativePlacement,
|
||||
boolean locatableNativePlacement, boolean locatableEditablePlacement,
|
||||
boolean nativeGenerationEnabled, boolean reachable) {
|
||||
if (!registered) {
|
||||
@@ -536,14 +535,14 @@ public class CommandFind implements DirectorExecutor {
|
||||
? StructureLookupRoute.IRIS
|
||||
: StructureLookupRoute.UNKNOWN;
|
||||
}
|
||||
if (decision == null) {
|
||||
throw new IllegalArgumentException("Registered structure lookup requires a generation decision");
|
||||
if (status == null) {
|
||||
throw new IllegalArgumentException("Registered structure lookup requires a generation status");
|
||||
}
|
||||
if (!decision.generate()
|
||||
&& decision.status() != NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
|
||||
if (status != NativeStructureGenerationStatus.GENERATE_NATIVE
|
||||
&& status != NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
|
||||
return StructureLookupRoute.POLICY_DISABLED;
|
||||
}
|
||||
if (decision.status() == NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
|
||||
if (status == NativeStructureGenerationStatus.REPLACED_BY_IRIS) {
|
||||
if (!nativePlacement) {
|
||||
return locatableEditablePlacement
|
||||
? StructureLookupRoute.IRIS
|
||||
@@ -597,9 +596,8 @@ public class CommandFind implements DirectorExecutor {
|
||||
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_FIND_LOCATING_2, MessageArgument.untrusted("structure", structure)));
|
||||
J.a(() -> {
|
||||
try {
|
||||
IrisStructureLocator.LocateResult result =
|
||||
IrisStructureLocator.locate(engine, structure, blockX, blockZ, 1024);
|
||||
if (result.status() == IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED) {
|
||||
ModuleServices.StructureSearch result = ModuleServices.locateStructure(engine, structure, blockX, blockZ, 1024);
|
||||
if (result.outcome() == ModuleServices.StructureSearch.Outcome.SEARCH_LIMIT_REACHED) {
|
||||
sendStructureMessage(target, commandSender,
|
||||
C.YELLOW + "Unable to locate " + structure
|
||||
+ ": the density search safety limit was reached before the full 1024-chunk radius was searched.");
|
||||
@@ -610,8 +608,7 @@ public class CommandFind implements DirectorExecutor {
|
||||
C.YELLOW + "No " + structure + " found within 1024 chunks of you.");
|
||||
return;
|
||||
}
|
||||
Location destination = new Location(
|
||||
targetWorld, result.originX(), result.baseY(), result.originZ());
|
||||
Location destination = new Location(targetWorld, result.x(), result.y(), result.z());
|
||||
prepareStructureTeleport(target, targetWorld, commandSender, structure, destination, true);
|
||||
} catch (Throwable t) {
|
||||
sendStructureMessage(target, commandSender,
|
||||
@@ -647,7 +644,7 @@ public class CommandFind implements DirectorExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
if (e.hasObjectPlacement(object)) {
|
||||
if (!ModuleServices.objectPlacers(e, object).isEmpty()) {
|
||||
EngineBukkitOps.gotoObject(e, object, player(), teleport);
|
||||
return;
|
||||
}
|
||||
|
||||
+11
-6
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.engine.object.world.IrisWorld;
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.core.BukkitWorldReconciler;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
@@ -36,7 +37,7 @@ import art.arcane.iris.core.service.StudioSVC;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.bukkit.WorldIdentity;
|
||||
import art.arcane.volmlib.util.director.DirectorParameterHandler;
|
||||
@@ -85,8 +86,6 @@ public class CommandIris implements DirectorExecutor {
|
||||
private CommandStudio studio;
|
||||
private CommandPregen pregen;
|
||||
private CommandObject object;
|
||||
private CommandStructure structure;
|
||||
private CommandJigsaw jigsaw;
|
||||
private CommandWhat what;
|
||||
private CommandEdit edit;
|
||||
private CommandDeveloper developer;
|
||||
@@ -509,7 +508,7 @@ public class CommandIris implements DirectorExecutor {
|
||||
return;
|
||||
}
|
||||
PlatformChunkGenerator generator = IrisToolbelt.access(world);
|
||||
IrisToolbelt.beginWorldMaintenance(world, "world-unload", true);
|
||||
AtomicBoolean maintenanceEntered = new AtomicBoolean(false);
|
||||
try {
|
||||
AtomicBoolean terminalTimeout = new AtomicBoolean(false);
|
||||
CompletableFuture<Boolean> sequence = IrisToolbelt.evacuateAsync(world)
|
||||
@@ -521,6 +520,8 @@ public class CommandIris implements DirectorExecutor {
|
||||
if (!Boolean.TRUE.equals(evacuated)) {
|
||||
return CompletableFuture.completedFuture(false);
|
||||
}
|
||||
IrisToolbelt.beginWorldMaintenance(world, "world-unload", true);
|
||||
maintenanceEntered.set(true);
|
||||
return WorldLifecycleService.get().unloadAsync(world, true);
|
||||
})
|
||||
.thenCompose(unloaded -> {
|
||||
@@ -535,7 +536,9 @@ public class CommandIris implements DirectorExecutor {
|
||||
});
|
||||
guardUnloadCompletion(sequence, terminalTimeout, world.getName())
|
||||
.whenComplete((unloaded, throwable) -> {
|
||||
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
|
||||
if (maintenanceEntered.get()) {
|
||||
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
|
||||
}
|
||||
lease.close();
|
||||
Runnable response = () -> reportUnloadResult(responseSender, world, unloaded, throwable);
|
||||
if (responseSender.isPlayer() && J.runEntity(responseSender.player(), response)) {
|
||||
@@ -544,7 +547,9 @@ public class CommandIris implements DirectorExecutor {
|
||||
J.s(response);
|
||||
});
|
||||
} catch (Exception e) {
|
||||
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
|
||||
if (maintenanceEntered.get()) {
|
||||
IrisToolbelt.endWorldMaintenance(world, "world-unload", true);
|
||||
}
|
||||
lease.close();
|
||||
responseSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_IRIS_FAILED_UNLOAD_WORLD_3, MessageArgument.untrusted("value", String.valueOf(e.getMessage()))));
|
||||
Iris.reportError("Failed to unload world \"" + world.getName() + "\".", e);
|
||||
|
||||
-2209
File diff suppressed because it is too large.
Load diff
+22
-32
@@ -32,13 +32,12 @@ import art.arcane.iris.core.service.WandSVC;
|
||||
import art.arcane.iris.core.tools.IrisConverter;
|
||||
import art.arcane.iris.core.tools.TreePlausibilizeBatch;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.IObjectPlacer;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisObject;
|
||||
import art.arcane.iris.engine.object.IrisObjectPlacement;
|
||||
import art.arcane.iris.engine.object.IrisObjectPlacementScaleInterpolator;
|
||||
import art.arcane.iris.engine.object.IrisObjectRotation;
|
||||
import art.arcane.iris.engine.object.TileData;
|
||||
import art.arcane.iris.engine.object.placement.IObjectPlacer;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.object.prefab.ObjectTurn;
|
||||
import com.volmit.object.ScaleMethod;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import art.arcane.iris.platform.bukkit.BukkitBlockState;
|
||||
import art.arcane.iris.spi.PlatformBlockState;
|
||||
import art.arcane.volmlib.util.data.Cuboid;
|
||||
@@ -54,7 +53,6 @@ import art.arcane.iris.util.common.director.specialhandlers.ObjectHandler;
|
||||
import art.arcane.iris.util.common.director.specialhandlers.ObjectTargetHandler;
|
||||
import art.arcane.iris.util.common.format.C;
|
||||
import art.arcane.iris.util.common.math.Direction;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.GameMode;
|
||||
@@ -261,11 +259,6 @@ public class CommandObject implements DirectorExecutor {
|
||||
: targetEngine.getMinHeight() + targetEngine.getDimension().getFluidHeight();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDebugSmartBore() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTile(int xx, int yy, int zz, TileData tile) {
|
||||
tile.toBukkitTry(world.getBlockAt(xx, yy, zz));
|
||||
@@ -527,21 +520,19 @@ public class CommandObject implements DirectorExecutor {
|
||||
return;
|
||||
}
|
||||
|
||||
if (WandSVC.isHoldingIrisWand(player)) {
|
||||
Location[] g = WandSVC.getCuboid(player);
|
||||
Location[] g = WandSVC.getCuboid(player);
|
||||
|
||||
if (g == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!here) {
|
||||
// TODO: WARNING HEIGHT
|
||||
g[0] = player.getTargetBlock(null, 256).getLocation().clone();
|
||||
} else {
|
||||
g[0] = player.getLocation().getBlock().getLocation().clone().add(0, -1, 0);
|
||||
}
|
||||
player.getInventory().setItemInMainHand(WandSVC.createWand(g[0], g[1]));
|
||||
if (g == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!here) {
|
||||
// TODO: WARNING HEIGHT
|
||||
g[0] = player.getTargetBlock(null, 256).getLocation().clone();
|
||||
} else {
|
||||
g[0] = player.getLocation().getBlock().getLocation().clone().add(0, -1, 0);
|
||||
}
|
||||
player.getInventory().setItemInMainHand(WandSVC.createWand(g[0], g[1]));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -557,7 +548,7 @@ public class CommandObject implements DirectorExecutor {
|
||||
double scale
|
||||
// ,
|
||||
// @Param(description = "The scale interpolator to use", descriptionKey = "iris.director.commandobject.param.scale_interpolator_use", defaultValue = "none")
|
||||
// IrisObjectPlacementScaleInterpolator interpolator
|
||||
// ScaleInterpolation interpolator
|
||||
) {
|
||||
IrisObject o = IrisData.loadAnyObject(object, data());
|
||||
double maxScale = Double.max(10 - o.getBlocks().size() / 10000d, 1);
|
||||
@@ -566,8 +557,7 @@ public class CommandObject implements DirectorExecutor {
|
||||
scale = maxScale;
|
||||
}
|
||||
|
||||
IrisObjectPlacement placement = new IrisObjectPlacement();
|
||||
placement.setRotation(IrisObjectRotation.of(0, rotate, 0));
|
||||
ObjectTurn turn = ObjectTurn.of(0, rotate, 0);
|
||||
|
||||
VolmitSender commandSender = sender();
|
||||
Player player = player();
|
||||
@@ -584,13 +574,13 @@ public class CommandObject implements DirectorExecutor {
|
||||
Map<Block, BlockData> futureChanges = new HashMap<>();
|
||||
|
||||
if (scale != 1) {
|
||||
o = o.scaled(scale, IrisObjectPlacementScaleInterpolator.TRICUBIC);
|
||||
o = o.scaled(scale, ScaleMethod.TRICUBIC);
|
||||
}
|
||||
|
||||
// Block writes must run on the thread owning the target chunk; the undo log stays global.
|
||||
final IrisObject placed = o;
|
||||
if (!J.runAt(block, () -> {
|
||||
placed.place(block.getBlockX(), block.getBlockY() + (int) placed.getCenter().getY(), block.getBlockZ(), createPlacer(block.getWorld(), futureChanges, null), placement, new RNG(), null);
|
||||
placed.paste(block.getBlockX(), block.getBlockY() + (int) placed.getCenter().getY(), block.getBlockZ(), createPlacer(block.getWorld(), futureChanges, null), turn);
|
||||
J.runGlobal(() -> Iris.service(ObjectSVC.class).addChanges(futureChanges));
|
||||
|
||||
if (!edit) {
|
||||
@@ -599,7 +589,7 @@ public class CommandObject implements DirectorExecutor {
|
||||
}
|
||||
|
||||
onPlayerThread(player, () -> {
|
||||
ObjectPasteBounds bounds = ObjectPasteBounds.resolve(placed, placement.getRotation(), block.getBlockX(),
|
||||
ObjectPasteBounds bounds = ObjectPasteBounds.resolve(placed, turn, block.getBlockX(),
|
||||
block.getBlockY() + placed.getCenter().getBlockY(), block.getBlockZ());
|
||||
Location minimum = new Location(block.getWorld(), bounds.minX(), bounds.minY(), bounds.minZ());
|
||||
Location maximum = new Location(block.getWorld(), bounds.maxX(), bounds.maxY(), bounds.maxZ());
|
||||
|
||||
@@ -19,6 +19,9 @@
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.core.localization.BukkitCommandMessagesExtended;
|
||||
import art.arcane.iris.core.modules.KeptModuleUpdates;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.core.pack.PackDirectoryResolver;
|
||||
import art.arcane.iris.core.pack.PackResourceCleanup;
|
||||
import art.arcane.iris.core.pack.PackValidationCache;
|
||||
@@ -31,6 +34,8 @@ import art.arcane.volmlib.util.director.annotations.Director;
|
||||
import art.arcane.volmlib.util.director.annotations.Param;
|
||||
import art.arcane.volmlib.util.localization.TextKey;
|
||||
|
||||
import org.bukkit.World;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
@@ -90,6 +95,18 @@ public class CommandPack implements DirectorExecutor {
|
||||
persistValidationCache(packsRoot);
|
||||
}
|
||||
|
||||
@Director(description = "Update the modules a world kept back", descriptionKey = "iris.director.commandpack.director.take_kept_module_updates")
|
||||
public void update(
|
||||
@Param(name = "world", description = "The Iris world whose modules to update", descriptionKey = "iris.director.commandpack.param.world_take_module_updates", contextual = true, contextualOverride = true)
|
||||
World world
|
||||
) {
|
||||
if (!IrisToolbelt.isIrisWorld(world)) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
|
||||
return;
|
||||
}
|
||||
KeptModuleUpdates.takeForWorld(IrisToolbelt.access(world).getEngine().getData()).forEach(sender()::sendMessage);
|
||||
}
|
||||
|
||||
@Director(description = "Preview or apply unused-resource cleanup", descriptionKey = "iris.director.commandpack.director.preview_apply_unused_resource_cleanup", aliases = {"c"})
|
||||
public void cleanup(
|
||||
@Param(description = "The pack folder name to clean", descriptionKey = "iris.director.commandpack.param.pack_folder_name_clean")
|
||||
|
||||
-392
@@ -1,392 +0,0 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.structure.BulkStructureImporter;
|
||||
import art.arcane.iris.core.structure.StructureCaptureImporter;
|
||||
import art.arcane.iris.core.structure.StructureImporter;
|
||||
import art.arcane.iris.core.structure.StructureIndexService;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.IrisStructureLocator;
|
||||
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
|
||||
import art.arcane.iris.engine.framework.PlacedStructurePiece;
|
||||
import art.arcane.iris.engine.framework.StructureAssembler;
|
||||
import art.arcane.iris.engine.framework.StructureReachability;
|
||||
import art.arcane.iris.engine.framework.structure.StructureAssemblyResult;
|
||||
import art.arcane.iris.engine.object.IObjectPlacer;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisNativeStructureDecision;
|
||||
import art.arcane.iris.engine.object.IrisObjectPlacement;
|
||||
import art.arcane.iris.engine.object.IrisPosition;
|
||||
import art.arcane.iris.engine.object.IrisStructure;
|
||||
import art.arcane.iris.engine.object.NativeStructureGenerationStatus;
|
||||
import art.arcane.iris.engine.object.ObjectPlaceMode;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.iris.util.common.director.DirectorExecutor;
|
||||
import art.arcane.iris.util.common.format.C;
|
||||
import art.arcane.volmlib.util.director.DirectorOrigin;
|
||||
import art.arcane.volmlib.util.director.annotations.Director;
|
||||
import art.arcane.volmlib.util.director.annotations.Param;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import art.arcane.iris.util.common.plugin.VolmitSender;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.Registry;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.generator.structure.Structure;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import art.arcane.iris.core.localization.IrisLanguage;
|
||||
import art.arcane.iris.core.localization.BukkitCommandMessages;
|
||||
import art.arcane.volmlib.util.localization.MessageArgument;
|
||||
import art.arcane.iris.core.localization.BukkitCommandMessagesExtended;
|
||||
@Director(name = "structure", aliases = {"struct", "str"}, description = "Iris structure tools (index, import, info)", descriptionKey = "iris.director.commandstructure.director.iris_structure_tools_index_import_info")
|
||||
public class CommandStructure implements DirectorExecutor {
|
||||
@Director(description = "Regenerate structure-index.json listing all vanilla, datapack & iris structures", descriptionKey = "iris.director.commandstructure.director.regenerate_structure_index_json_listing_all_vanilla_datapack_iris_structures", aliases = {"ls"}, origin = DirectorOrigin.BOTH)
|
||||
public void list(
|
||||
@Param(description = "The dimension whose pack to index", descriptionKey = "iris.director.commandstructure.param.dimension_whose_pack_index", aliases = "dim")
|
||||
IrisDimension dimension
|
||||
) {
|
||||
IrisData data = dimension.getLoader();
|
||||
if (data == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_COULD_NOT_RESOLVE_PACK_DIMENSION, MessageArgument.untrusted("value", dimension.getLoadKey())));
|
||||
return;
|
||||
}
|
||||
File file = StructureIndexService.write(data);
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_WROTE_STRUCTURE_INDEX, MessageArgument.untrusted("value", file.getPath())));
|
||||
}
|
||||
|
||||
@Director(name = "import", description = "Import EVERY structure - vanilla AND ingested datapacks - into this pack as editable Iris resources, always overwriting. Rebuilds jigsaw structures (villages, outposts, datapack jigsaws) as editable pool/piece graphs, imports every structure template NBT as an object, and assembles the multi-template structures (shipwrecks, ruined portals, ocean ruins, nether fossils). Run after ingesting a datapack and restarting. Regenerate chunks or use a fresh world for the imported copies to place.", descriptionKey = "iris.director.commandstructure.director.import_every_structure_vanilla_ingested_datapacks_into_this_pack_as_editable_iris", aliases = {"import-all", "reimport", "imp", "all"}, origin = DirectorOrigin.BOTH)
|
||||
public void importAll(
|
||||
@Param(description = "The dimension whose pack to import into", descriptionKey = "iris.director.commandstructure.param.dimension_whose_pack_import_into", aliases = "dim")
|
||||
IrisDimension dimension
|
||||
) {
|
||||
IrisData data = dimension.getLoader();
|
||||
if (data == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_COULD_NOT_RESOLVE_PACK_DIMENSION_2, MessageArgument.untrusted("value", dimension.getLoadKey())));
|
||||
return;
|
||||
}
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_IMPORTING_ALL_VANILLA_DATAPACK_STRUCTURES_INTO_OVERWRITE, MessageArgument.untrusted("value", dimension.getLoadKey())));
|
||||
BulkStructureImporter.Report jigsaws = BulkStructureImporter.importAllVanilla(data, StructureImporter.Mode.OVERWRITE, true, sender());
|
||||
BulkStructureImporter.Report templates = BulkStructureImporter.importAllTemplates(data, StructureImporter.Mode.OVERWRITE, sender());
|
||||
BulkStructureImporter.Report groups = BulkStructureImporter.importTemplateGroups(data, StructureImporter.Mode.OVERWRITE, sender());
|
||||
StructureCaptureImporter.Report captured = StructureCaptureImporter.importStructures(
|
||||
data, StructureImporter.Mode.OVERWRITE, sender(), jigsaws.captureCandidates());
|
||||
int imported = jigsaws.imported() + templates.imported() + groups.imported() + captured.imported();
|
||||
int failed = jigsaws.failed() + templates.failed() + groups.failed() + captured.failed();
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_IMPORT_COMPLETE_STRUCTURES_OBJECTS_WRITTEN_FAILED, MessageArgument.untrusted("imported", imported), MessageArgument.untrusted("failed", failed)));
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_REFERENCE_THEM_FROM_BIOME_REGION_DIMENSION_STRUCTURES_LIST_RUN_IRIS, MessageArgument.untrusted("value", dimension.getLoadKey())));
|
||||
}
|
||||
|
||||
@Director(name = "capture", description = "Capture live registered structures into editable Iris objects by generating each one in a throwaway scratch world and reading back its blocks. This standalone command overwrites its owned outputs; structures wider/taller than the capture cap and anything that will not generate in a flat overworld are skipped. Each captured structure becomes a single-piece Iris structure you can place from a biome/region/dimension 'structures' list. /iris structure import runs a restricted final capture pass only for non-jigsaw structures that have no loadable NBT template.", descriptionKey = "iris.director.commandstructure.director.capture_code_generated_structures_that_have_no_nbt_template_swamp_huts_igloos", aliases = {"cap"}, origin = DirectorOrigin.BOTH)
|
||||
public void capture(
|
||||
@Param(description = "The dimension whose pack to capture into", descriptionKey = "iris.director.commandstructure.param.dimension_whose_pack_capture_into", aliases = "dim")
|
||||
IrisDimension dimension
|
||||
) {
|
||||
IrisData data = dimension.getLoader();
|
||||
if (data == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_COULD_NOT_RESOLVE_PACK_DIMENSION_3, MessageArgument.untrusted("value", dimension.getLoadKey())));
|
||||
return;
|
||||
}
|
||||
StructureCaptureImporter.Report report = StructureCaptureImporter.importAllStructures(data, StructureImporter.Mode.OVERWRITE, sender());
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_CAPTURED_STRUCTURES_PLACE_THEM_FROM_STRUCTURES_LIST_REGENERATE_CHUNKS_DELETE, MessageArgument.untrusted("value", report.imported())));
|
||||
}
|
||||
|
||||
@Director(description = "Verify native structure eligibility and locate Iris-placed structures without running blocking native searches.", descriptionKey = "iris.director.commandstructure.director.verify_native_structure_eligibility_locate_iris_placed_structures_without_running_blocking_native", aliases = {"locateall"}, origin = DirectorOrigin.BOTH, sync = true)
|
||||
public void verify(
|
||||
@Param(description = "The dimension to verify", descriptionKey = "iris.director.commandstructure.param.dimension_verify", aliases = "dim")
|
||||
IrisDimension dimension,
|
||||
@Param(description = "Search radius in chunks around the origin (larger is much slower)", descriptionKey = "iris.director.commandstructure.param.search_radius_chunks_around_origin_larger_is_much_slower", defaultValue = "48")
|
||||
int radius
|
||||
) {
|
||||
World world = resolveIrisWorld(dimension);
|
||||
if (world == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_NO_LOADED_IRIS_WORLD_FOUND_JOIN_CREATE_ONE_FIRST_SEARCH, MessageArgument.untrusted("value", dimension.getLoadKey())));
|
||||
return;
|
||||
}
|
||||
boolean senderIsPlayer = sender() != null && sender().isPlayer();
|
||||
Location center = senderIsPlayer && player().getWorld() == world
|
||||
? player().getLocation()
|
||||
: world.getSpawnLocation();
|
||||
int searchRadius = Math.max(1, Math.min(radius, 1000));
|
||||
PlatformChunkGenerator access = IrisToolbelt.access(world);
|
||||
Engine engine = access == null ? null : access.getEngine();
|
||||
if (engine == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_SELECTED_IRIS_WORLD_HAS_NO_ACTIVE_GENERATOR_ENGINE));
|
||||
return;
|
||||
}
|
||||
KList<String> structureKeys = new KList<>();
|
||||
Registry<Structure> structureRegistry = Bukkit.getRegistry(Structure.class);
|
||||
if (structureRegistry != null) {
|
||||
for (Structure structure : structureRegistry) {
|
||||
NamespacedKey key = structureRegistry.getKey(structure);
|
||||
if (key != null) {
|
||||
structureKeys.add(key.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
for (String placedKey : IrisStructureLocator.placedKeys(engine)) {
|
||||
if (!structureKeys.contains(placedKey)) {
|
||||
structureKeys.add(placedKey);
|
||||
}
|
||||
}
|
||||
VolmitSender commandSender = sender();
|
||||
Player target = senderIsPlayer ? player() : null;
|
||||
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STRUCTURE_VERIFYING_STRUCTURES_FROM_WITHIN_CHUNKS, MessageArgument.untrusted("value", world.getName()), MessageArgument.untrusted("value2", center.getBlockX()), MessageArgument.untrusted("value3", center.getBlockZ()), MessageArgument.untrusted("searchRadius", searchRadius)));
|
||||
int centerX = center.getBlockX();
|
||||
int centerZ = center.getBlockZ();
|
||||
J.a(() -> runVerification(engine, structureKeys, centerX, centerZ, searchRadius, commandSender, target));
|
||||
}
|
||||
|
||||
private void runVerification(Engine engine, KList<String> structureKeys, int centerX, int centerZ,
|
||||
int searchRadius, VolmitSender commandSender, Player target) {
|
||||
KList<String> messages = new KList<>();
|
||||
Map<String, IrisNativeStructureDecision> decisions = new HashMap<>(structureKeys.size());
|
||||
boolean requiresNativeReachability = false;
|
||||
for (String keyName : structureKeys) {
|
||||
IrisNativeStructureDecision decision = NativeStructureGenerationPolicy.resolve(engine, keyName, false);
|
||||
decisions.put(keyName, decision);
|
||||
requiresNativeReachability |= !IrisStructureLocator.isPlaced(engine, keyName)
|
||||
&& decision.generate();
|
||||
}
|
||||
Set<String> reachable = Set.of();
|
||||
if (requiresNativeReachability) {
|
||||
try {
|
||||
reachable = StructureReachability.reachableKeys(engine);
|
||||
} catch (Throwable error) {
|
||||
messages.add(C.RED + "Structure verification could not resolve native biome reachability.");
|
||||
sendVerificationMessages(commandSender, target, messages);
|
||||
Iris.reportError("Could not resolve native structure biome reachability for verification.", error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
int located = 0;
|
||||
int nativeEligible = 0;
|
||||
int disabled = 0;
|
||||
int unreachable = 0;
|
||||
int searchLimited = 0;
|
||||
int errors = 0;
|
||||
for (String keyName : structureKeys) {
|
||||
IrisNativeStructureDecision decision = decisions.get(keyName);
|
||||
if (IrisStructureLocator.isPlaced(engine, keyName)) {
|
||||
try {
|
||||
IrisStructureLocator.LocateResult result =
|
||||
IrisStructureLocator.locate(engine, keyName, centerX, centerZ, searchRadius);
|
||||
if (result.status() == IrisStructureLocator.LocateStatus.SEARCH_LIMIT_REACHED) {
|
||||
searchLimited++;
|
||||
messages.add(C.YELLOW + "[iris-search-limit] " + C.WHITE + keyName + C.YELLOW
|
||||
+ ": unable to complete the density search before its safety limit was reached");
|
||||
continue;
|
||||
}
|
||||
if (!result.found()) {
|
||||
messages.add(C.YELLOW + "[iris-not-found] " + C.WHITE + keyName);
|
||||
continue;
|
||||
}
|
||||
located++;
|
||||
messages.add(C.AQUA + "[iris-planned] " + C.WHITE + keyName + C.GREEN + " @ "
|
||||
+ result.originX() + "," + result.baseY() + "," + result.originZ());
|
||||
} catch (Throwable error) {
|
||||
errors++;
|
||||
messages.add(C.RED + "[error] " + C.WHITE + keyName + C.RED + ": "
|
||||
+ error.getClass().getSimpleName());
|
||||
Iris.reportError("Could not verify Iris-placed structure '" + keyName + "'.", error);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!decision.generate()) {
|
||||
disabled++;
|
||||
messages.add(C.GRAY + "[disabled] " + C.WHITE + keyName);
|
||||
continue;
|
||||
}
|
||||
if (!reachable.contains(keyName.toLowerCase(Locale.ROOT))) {
|
||||
unreachable++;
|
||||
KList<String> missing = StructureReachability.missingBiomeKeys(engine, keyName);
|
||||
messages.add(C.YELLOW + "[unreachable] " + C.WHITE + keyName
|
||||
+ (missing.isEmpty() ? "" : C.YELLOW + " needs " + String.join("/", missing)));
|
||||
continue;
|
||||
}
|
||||
nativeEligible++;
|
||||
messages.add(C.GREEN + "[native-eligible] " + C.WHITE + keyName);
|
||||
}
|
||||
messages.add(C.GREEN + "Structure verify: " + C.WHITE + located + C.GREEN + " Iris placement plans found, "
|
||||
+ C.WHITE + nativeEligible + C.GREEN + " native structures eligible, "
|
||||
+ C.WHITE + disabled + C.GREEN + " disabled by policy, "
|
||||
+ C.WHITE + unreachable + C.GREEN + " biome-unreachable, "
|
||||
+ C.WHITE + searchLimited + C.GREEN + " density searches safety-limited, "
|
||||
+ C.WHITE + errors + C.GREEN + " errors. Native eligibility is checked without running blocking live locates.");
|
||||
sendVerificationMessages(commandSender, target, messages);
|
||||
}
|
||||
|
||||
private void sendVerificationMessages(VolmitSender commandSender, Player target,
|
||||
KList<String> messages) {
|
||||
Runnable send = () -> {
|
||||
for (String message : messages) {
|
||||
commandSender.sendMessage(message);
|
||||
}
|
||||
};
|
||||
if (target != null) {
|
||||
J.runEntity(target, send);
|
||||
} else {
|
||||
J.s(send);
|
||||
}
|
||||
}
|
||||
|
||||
private World resolveIrisWorld(IrisDimension dimension) {
|
||||
if (sender() != null && sender().isPlayer() && IrisToolbelt.isIrisWorld(player().getWorld())) {
|
||||
PlatformChunkGenerator playerGenerator = IrisToolbelt.access(player().getWorld());
|
||||
if (matchesDimension(playerGenerator, dimension.getLoadKey())) {
|
||||
return player().getWorld();
|
||||
}
|
||||
}
|
||||
for (World w : Bukkit.getWorlds()) {
|
||||
if (!IrisToolbelt.isIrisWorld(w)) {
|
||||
continue;
|
||||
}
|
||||
PlatformChunkGenerator gen = IrisToolbelt.access(w);
|
||||
if (matchesDimension(gen, dimension.getLoadKey())) {
|
||||
return w;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static boolean matchesDimension(PlatformChunkGenerator generator, String dimensionKey) {
|
||||
return dimensionKey != null
|
||||
&& generator != null
|
||||
&& generator.getEngine() != null
|
||||
&& generator.getEngine().getDimension() != null
|
||||
&& dimensionKey.equals(generator.getEngine().getDimension().getLoadKey());
|
||||
}
|
||||
|
||||
@Director(description = "Resolve an iris structure's jigsaw graph and report piece count & bounds", descriptionKey = "iris.director.commandstructure.director.resolve_iris_structure_s_jigsaw_graph_report_piece_count_bounds", origin = DirectorOrigin.BOTH)
|
||||
public void info(
|
||||
@Param(description = "The dimension whose pack holds the structure", descriptionKey = "iris.director.commandstructure.param.dimension_whose_pack_holds_structure", aliases = "dim")
|
||||
IrisDimension dimension,
|
||||
@Param(description = "The iris structure key to inspect", descriptionKey = "iris.director.commandstructure.param.iris_structure_key_inspect")
|
||||
String structure
|
||||
) {
|
||||
IrisData data = dimension.getLoader();
|
||||
if (data == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_COULD_NOT_RESOLVE_PACK_DIMENSION_4, MessageArgument.untrusted("value", dimension.getLoadKey())));
|
||||
return;
|
||||
}
|
||||
IrisStructure s = data.load(IrisStructure.class, structure, false);
|
||||
if (s == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_NO_IRIS_STRUCTURE_THIS_PACK, MessageArgument.untrusted("structure", structure)));
|
||||
return;
|
||||
}
|
||||
StructureAssembler assembler = StructureAssembler.forData(
|
||||
data, s, new IrisPosition(0, 64, 0));
|
||||
StructureAssemblyResult assembly = assembler.assemble(new RNG(1234));
|
||||
List<PlacedStructurePiece> pieces = assembly.pieces();
|
||||
if (!assembly.hasOutput()) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_STRUCTURE_ASSEMBLED_0_PIECES_CHECK_STARTPOOL, MessageArgument.untrusted("structure", structure), MessageArgument.untrusted("value", s.getStartPool())));
|
||||
return;
|
||||
}
|
||||
int minX = Integer.MAX_VALUE;
|
||||
int minZ = Integer.MAX_VALUE;
|
||||
int maxX = Integer.MIN_VALUE;
|
||||
int maxZ = Integer.MIN_VALUE;
|
||||
for (PlacedStructurePiece p : pieces) {
|
||||
minX = Math.min(minX, p.getMinX());
|
||||
minZ = Math.min(minZ, p.getMinZ());
|
||||
maxX = Math.max(maxX, p.getMaxX());
|
||||
maxZ = Math.max(maxZ, p.getMaxZ());
|
||||
}
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_STRUCTURE_PIECES_FOOTPRINT_X_BLOCKS_SAMPLE_SEED_1234, MessageArgument.untrusted("structure", structure), MessageArgument.untrusted("value", pieces.size()), MessageArgument.untrusted("value2", (maxX - minX + 1)), MessageArgument.untrusted("value3", (maxZ - minZ + 1))));
|
||||
}
|
||||
|
||||
@Director(description = "Assemble and place an iris structure at your location (studio testing)", descriptionKey = "iris.director.commandstructure.director.assemble_place_iris_structure_at_your_location_studio_testing", aliases = {"p"}, origin = DirectorOrigin.PLAYER, sync = true)
|
||||
public void place(
|
||||
@Param(description = "The dimension whose pack holds the structure", descriptionKey = "iris.director.commandstructure.param.dimension_whose_pack_holds_structure_2", aliases = "dim")
|
||||
IrisDimension dimension,
|
||||
@Param(description = "The iris structure key to place", descriptionKey = "iris.director.commandstructure.param.iris_structure_key_place")
|
||||
String structure
|
||||
) {
|
||||
IrisData data = dimension.getLoader();
|
||||
if (data == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_COULD_NOT_RESOLVE_PACK_DIMENSION_5, MessageArgument.untrusted("value", dimension.getLoadKey())));
|
||||
return;
|
||||
}
|
||||
IrisStructure s = data.load(IrisStructure.class, structure, false);
|
||||
if (s == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_NO_IRIS_STRUCTURE_THIS_PACK_2, MessageArgument.untrusted("structure", structure)));
|
||||
return;
|
||||
}
|
||||
Location loc = player().getLocation();
|
||||
StructureAssembler assembler = StructureAssembler.forData(
|
||||
data, s, new IrisPosition(loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
|
||||
RNG rng = new RNG((long) loc.getBlockX() * 341873128712L + loc.getBlockZ());
|
||||
StructureAssemblyResult assembly = assembler.assemble(rng);
|
||||
List<PlacedStructurePiece> pieces = assembly.pieces();
|
||||
if (!assembly.hasOutput()) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STRUCTURE_STRUCTURE_ASSEMBLED_0_PIECES, MessageArgument.untrusted("structure", structure)));
|
||||
return;
|
||||
}
|
||||
Map<Block, BlockData> future = new HashMap<>();
|
||||
World targetWorld = player().getWorld();
|
||||
PlatformChunkGenerator targetGenerator = IrisToolbelt.access(targetWorld);
|
||||
Engine targetEngine = targetGenerator == null ? null : targetGenerator.getEngine();
|
||||
IObjectPlacer placer = CommandObject.createPlacer(targetWorld, future, targetEngine);
|
||||
for (PlacedStructurePiece p : pieces) {
|
||||
IrisObjectPlacement config = new IrisObjectPlacement();
|
||||
config.setMode(ObjectPlaceMode.STRUCTURE_PIECE);
|
||||
config.setRotation(p.getRotation());
|
||||
config.getPlace().add(p.getObject().getLoadKey());
|
||||
if (!s.getEdit().isEmpty()) {
|
||||
config.setEdit(s.getEdit());
|
||||
}
|
||||
p.getObject().place(p.getX(), p.getY(), p.getZ(), placer, config, rng, null, null, data);
|
||||
}
|
||||
int blockChanges = 0;
|
||||
for (Map.Entry<Block, BlockData> entry : future.entrySet()) {
|
||||
if (!entry.getKey().getBlockData().equals(entry.getValue())) {
|
||||
blockChanges++;
|
||||
}
|
||||
}
|
||||
if (blockChanges == 0) {
|
||||
sender().sendMessage(IrisLanguage.text(
|
||||
BukkitCommandMessagesExtended.COMMAND_STRUCTURE_PLACEMENT_CHANGED_NO_BLOCKS,
|
||||
MessageArgument.untrusted("structure", structure),
|
||||
MessageArgument.untrusted("value", pieces.size())));
|
||||
return;
|
||||
}
|
||||
sender().sendMessage(IrisLanguage.text(
|
||||
BukkitCommandMessagesExtended.COMMAND_STRUCTURE_PLACED_PIECES_AT_YOUR_LOCATION,
|
||||
MessageArgument.untrusted("structure", structure),
|
||||
MessageArgument.untrusted("value", pieces.size()),
|
||||
MessageArgument.untrusted("value2", blockChanges)));
|
||||
}
|
||||
|
||||
}
|
||||
+178
-150
@@ -20,42 +20,42 @@ package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
|
||||
import art.arcane.iris.core.IrisSettings;
|
||||
import art.arcane.iris.core.gui.ImageMapStudioGUI;
|
||||
import art.arcane.iris.core.gui.NoiseExplorerGUI;
|
||||
import art.arcane.iris.core.gui.VisionGUI;
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
import art.arcane.iris.core.modules.KeptModuleUpdates;
|
||||
import art.arcane.iris.core.modules.PackModulesListing;
|
||||
import art.arcane.iris.core.localization.IrisMessages;
|
||||
import art.arcane.iris.core.studio.bridge.StudioBridge;
|
||||
import art.arcane.iris.core.studio.bridge.StudioBridges;
|
||||
import art.arcane.iris.core.studio.bridge.StudioWindow;
|
||||
import art.arcane.iris.core.pack.PackDownloader;
|
||||
import art.arcane.iris.core.project.IrisProject;
|
||||
import art.arcane.iris.core.project.IrisCodeWorkspace;
|
||||
import art.arcane.iris.core.project.StudioEditor;
|
||||
import art.arcane.iris.core.project.StudioEditorLauncher;
|
||||
import art.arcane.iris.core.localization.RuntimeUiMessages;
|
||||
import art.arcane.iris.core.service.BoardSVC;
|
||||
import art.arcane.iris.core.service.StudioSVC;
|
||||
import art.arcane.iris.core.structure.BulkStructureImporter;
|
||||
import art.arcane.iris.core.structure.FeatureImporter;
|
||||
import art.arcane.iris.core.structure.StructureImporter;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.InventorySlotType;
|
||||
import art.arcane.iris.engine.object.IrisBiome;
|
||||
import art.arcane.iris.engine.object.IrisBiomePaletteLayer;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisEntity;
|
||||
import art.arcane.iris.engine.object.IrisGenerator;
|
||||
import art.arcane.iris.engine.object.IrisInterpolator;
|
||||
import art.arcane.iris.engine.object.IrisLootTable;
|
||||
import art.arcane.iris.engine.object.IrisNoiseGenerator;
|
||||
import art.arcane.iris.engine.object.IrisObject;
|
||||
import art.arcane.iris.engine.object.IrisObjectPlacement;
|
||||
import art.arcane.iris.engine.object.IrisRegion;
|
||||
import art.arcane.iris.engine.object.NoiseStyle;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.platform.BukkitEntitySpawner;
|
||||
import art.arcane.iris.engine.object.terrain.IrisGenerator;
|
||||
import art.arcane.iris.engine.object.noise.IrisInterpolator;
|
||||
import art.arcane.iris.engine.object.noise.IrisNoiseGenerator;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.engine.object.noise.NoiseStyle;
|
||||
import art.arcane.iris.engine.platform.EngineBukkitOps;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.collection.KMap;
|
||||
import art.arcane.volmlib.util.collection.KSet;
|
||||
import art.arcane.iris.util.common.director.DirectorExecutor;
|
||||
import art.arcane.iris.util.common.director.handlers.DimensionHandler;
|
||||
import art.arcane.iris.util.common.director.specialhandlers.NullableDimensionHandler;
|
||||
import art.arcane.iris.util.common.director.specialhandlers.EntityKeyHandler;
|
||||
import art.arcane.volmlib.util.director.DirectorOrigin;
|
||||
import art.arcane.volmlib.util.director.annotations.Director;
|
||||
import art.arcane.volmlib.util.director.annotations.Param;
|
||||
@@ -124,54 +124,66 @@ public class CommandStudio implements DirectorExecutor {
|
||||
@Param(defaultValue = "false", description = "Attempt to open Studio before a required registry restart", aliases = "f")
|
||||
boolean force) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_STUDIO_PACK_SEED, MessageArgument.untrusted("value", dimension.getName()), MessageArgument.untrusted("seed", seed)));
|
||||
KeptModuleUpdates.keptAtLoad(dimension.getLoader()).forEach(sender()::sendMessage);
|
||||
Iris.service(StudioSVC.class).open(sender(), seed, dimension.getLoadKey(), force);
|
||||
}
|
||||
|
||||
@Director(description = "Import vanilla trees, mushrooms & objects (and structures/jigsaw) from the server into a pack's objects/vanilla folder", descriptionKey = "iris.director.commandstudio.director.import_vanilla_trees_mushrooms_objects_structures_jigsaw_from_server_into_pack_s", aliases = {"importv", "iv"}, origin = DirectorOrigin.BOTH)
|
||||
@Director(description = "Import vanilla trees, mushrooms & objects from the server into a pack's objects/vanilla folder", descriptionKey = "iris.director.commandstudio.director.import_vanilla_trees_mushrooms_objects_structures_jigsaw_from_server_into_pack_s", aliases = {"importv", "iv"}, origin = DirectorOrigin.BOTH)
|
||||
public void importvanilla(
|
||||
@Param(description = "The dimension pack to import vanilla content into", descriptionKey = "iris.director.commandstudio.param.dimension_pack_import_vanilla_content_into", aliases = {"pack", "dim"}, customHandler = DimensionHandler.class)
|
||||
@Param(defaultValue = "null", description = "The dimension pack to import vanilla content into", descriptionKey = "iris.director.commandstudio.param.dimension_pack_import_vanilla_content_into", aliases = {"pack", "dim"}, customHandler = NullableDimensionHandler.class)
|
||||
IrisDimension dimension,
|
||||
@Param(description = "How many variants to capture per tree/object feature", descriptionKey = "iris.director.commandstudio.param.how_many_variants_capture_per_tree_object_feature", defaultValue = "3")
|
||||
int variants,
|
||||
@Param(description = "Also import vanilla & datapack structures/jigsaw into the pack", descriptionKey = "iris.director.commandstudio.param.also_import_vanilla_datapack_structures_jigsaw_into_pack", defaultValue = "true")
|
||||
boolean structures
|
||||
int variants
|
||||
) {
|
||||
if (dimension == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_PROVIDE_DIMENSION_PACK_IRIS_STD_IMPORTVANILLA_PACK_DIMENSION));
|
||||
IrisDimension pack = namedOrCurrentPack(dimension);
|
||||
if (pack == null) {
|
||||
return;
|
||||
}
|
||||
IrisData data = dimension.getLoader();
|
||||
IrisData data = pack.getLoader();
|
||||
if (data == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_COULD_NOT_RESOLVE_PACK_DIMENSION, MessageArgument.untrusted("value", dimension.getLoadKey())));
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_COULD_NOT_RESOLVE_PACK_DIMENSION, MessageArgument.untrusted("value", pack.getLoadKey())));
|
||||
return;
|
||||
}
|
||||
|
||||
VolmitSender sender = sender();
|
||||
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_IMPORTING_VANILLA_CONTENT_INTO, MessageArgument.untrusted("value", dimension.getLoadKey())));
|
||||
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_IMPORTING_VANILLA_CONTENT_INTO, MessageArgument.untrusted("value", pack.getLoadKey())));
|
||||
|
||||
FeatureImporter.Report features = FeatureImporter.importAllObjectFeatures(data, variants, sender);
|
||||
int imported = features.imported();
|
||||
int failed = features.failed();
|
||||
|
||||
if (structures) {
|
||||
BulkStructureImporter.Report jigsaws = BulkStructureImporter.importAllVanilla(data, StructureImporter.Mode.OVERWRITE, true, sender);
|
||||
BulkStructureImporter.Report templates = BulkStructureImporter.importAllTemplates(data, StructureImporter.Mode.OVERWRITE, sender);
|
||||
BulkStructureImporter.Report groups = BulkStructureImporter.importTemplateGroups(data, StructureImporter.Mode.OVERWRITE, sender);
|
||||
imported += jigsaws.imported() + templates.imported() + groups.imported();
|
||||
failed += jigsaws.failed() + templates.failed() + groups.failed();
|
||||
}
|
||||
|
||||
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_IMPORTVANILLA_COMPLETE_OBJECTS_STRUCTURES_WRITTEN_FAILED, MessageArgument.untrusted("imported", imported), MessageArgument.untrusted("failed", failed)));
|
||||
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_IMPORTVANILLA_COMPLETE_OBJECTS_STRUCTURES_WRITTEN_FAILED, MessageArgument.untrusted("imported", features.imported()), MessageArgument.untrusted("failed", features.failed())));
|
||||
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_TREES_OBJECTS_ARE_UNDER_OBJECTS_VANILLA_REFERENCE_THEM_FROM_BIOME));
|
||||
}
|
||||
|
||||
@Director(description = "Open VSCode for a dimension", descriptionKey = "iris.director.commandstudio.director.open_vscode_dimension", aliases = {"vsc"})
|
||||
public void vscode(
|
||||
@Param(defaultValue = "default", description = "The dimension to open VSCode for", descriptionKey = "iris.director.commandstudio.param.dimension_open_vscode", aliases = "dim", customHandler = DimensionHandler.class)
|
||||
@Director(description = "Open VSCode/Zed for a dimension", descriptionKey = "iris.director.commandstudio.director.open_editor_dimension", aliases = {"vscode", "vsc"})
|
||||
public void editor(
|
||||
@Param(defaultValue = "null", description = "The dimension to open VSCode/Zed for (defaults to the open studio, else the default world type)", descriptionKey = "iris.director.commandstudio.param.dimension_open_editor", aliases = "dim", customHandler = NullableDimensionHandler.class)
|
||||
IrisDimension dimension
|
||||
) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_VSCODE_PACK, MessageArgument.untrusted("value", dimension.getName())));
|
||||
Iris.service(StudioSVC.class).openVSCode(sender(), dimension.getLoadKey());
|
||||
StudioSVC studio = Iris.service(StudioSVC.class);
|
||||
String pack = dimension != null ? dimension.getLoadKey() : packForEditor(studio);
|
||||
if (!PackDownloader.isPackPresent(studio.getWorkspaceFolder(), pack)) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_COULD_NOT_RESOLVE_PACK_DIMENSION, MessageArgument.untrusted("value", pack)));
|
||||
return;
|
||||
}
|
||||
StudioEditor editor = StudioEditorLauncher.configuredEditor();
|
||||
if (editor == StudioEditor.NONE) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_NO_EDITOR_SET));
|
||||
return;
|
||||
}
|
||||
if (!StudioEditorLauncher.canLaunch(editor)) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_OPEN_FILES_HEADLESS_ENVIRONMENTS));
|
||||
return;
|
||||
}
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_EDITOR_PACK,
|
||||
MessageArgument.untrusted("editor", editor.displayName()), MessageArgument.untrusted("value", pack)));
|
||||
studio.openEditor(sender(), pack);
|
||||
}
|
||||
|
||||
private static String packForEditor(StudioSVC studio) {
|
||||
if (studio.isProjectOpen()) {
|
||||
return studio.getActiveProject().getName();
|
||||
}
|
||||
return IrisSettings.get().getGenerator().getDefaultWorldType();
|
||||
}
|
||||
|
||||
@Director(description = "Close an open studio project", descriptionKey = "iris.director.commandstudio.director.close_open_studio_project", aliases = {"x"}, sync = true)
|
||||
@@ -203,6 +215,28 @@ public class CommandStudio implements DirectorExecutor {
|
||||
}));
|
||||
}
|
||||
|
||||
@Director(description = "Hotload the studio you are in", descriptionKey = "iris.director.commandstudio.director.hotload_studio", aliases = {"reload", "h"})
|
||||
public void hotload() {
|
||||
VolmitSender commandSender = sender();
|
||||
PlatformChunkGenerator studio = currentStudio();
|
||||
if (studio == null || studio.getEngine() == null) {
|
||||
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_NO_OPEN_STUDIO_PROJECTS));
|
||||
return;
|
||||
}
|
||||
|
||||
String pack = studio.getEngine().getDimension().getLoadKey();
|
||||
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_HOTLOADING, MessageArgument.untrusted("value", pack)));
|
||||
studio.hotloadOnRequest().whenComplete((ignored, failure) -> J.s(() -> reportHotload(commandSender, pack, failure)));
|
||||
}
|
||||
|
||||
private static void reportHotload(VolmitSender commandSender, String pack, Throwable failure) {
|
||||
if (failure != null) {
|
||||
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_HOTLOAD_FAILED, MessageArgument.untrusted("value", String.valueOf(failure.getMessage()))));
|
||||
return;
|
||||
}
|
||||
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_HOTLOADED, MessageArgument.untrusted("value", pack)));
|
||||
}
|
||||
|
||||
@Director(description = "Toggle your Studio debug scoreboard", descriptionKey = "iris.director.commandstudio.director.toggle_your_studio_debug_scoreboard", aliases = {"board", "sidebar", "sb"}, origin = DirectorOrigin.PLAYER)
|
||||
public void scoreboard() {
|
||||
Player target = player();
|
||||
@@ -242,29 +276,26 @@ public class CommandStudio implements DirectorExecutor {
|
||||
|
||||
@Director(description = "Get the version of a pack", descriptionKey = "iris.director.commandstudio.director.get_version_pack")
|
||||
public void version(
|
||||
@Param(defaultValue = "default", description = "The dimension get the version of", descriptionKey = "iris.director.commandstudio.param.dimension_get_version", aliases = "dim", contextual = true, contextualOverride = true, customHandler = DimensionHandler.class)
|
||||
@Param(defaultValue = "null", description = "The dimension get the version of", descriptionKey = "iris.director.commandstudio.param.dimension_get_version", aliases = "dim", customHandler = NullableDimensionHandler.class)
|
||||
IrisDimension dimension
|
||||
) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_PACK_HAS_VERSION, MessageArgument.untrusted("value", dimension.getName()), MessageArgument.untrusted("value2", dimension.getVersion())));
|
||||
}
|
||||
|
||||
@Director(description = "Open the noise explorer (External GUI)", descriptionKey = "iris.director.commandstudio.director.open_noise_explorer_external_gui", aliases = {"nmap"})
|
||||
public void noise(
|
||||
@Param(description = "Optional pack generator to preview", descriptionKey = "iris.director.commandstudio.param.optional_pack_generator_preview", defaultValue = "null", contextual = true, contextualOverride = true)
|
||||
IrisGenerator generator,
|
||||
@Param(description = "The seed to preview the generator with", descriptionKey = "iris.director.commandstudio.param.seed_preview_generator_with", defaultValue = "12345")
|
||||
long seed
|
||||
) {
|
||||
if (noGUI()) return;
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER));
|
||||
|
||||
if (generator == null) {
|
||||
NoiseExplorerGUI.launch();
|
||||
IrisDimension pack = namedOrCurrentPack(dimension);
|
||||
if (pack == null) {
|
||||
return;
|
||||
}
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_PACK_HAS_VERSION, MessageArgument.untrusted("value", pack.getName()), MessageArgument.untrusted("value2", pack.getVersion())));
|
||||
}
|
||||
|
||||
String generatorKey = generator.getLoadKey();
|
||||
NoiseExplorerGUI.launchGeneratorKey(generatorKey, generator, seed);
|
||||
@Director(description = "List the modules a pack loads", descriptionKey = "iris.director.commandstudio.director.list_pack_modules")
|
||||
public void modules(
|
||||
@Param(defaultValue = "null", description = "The pack to list the modules of", descriptionKey = "iris.director.commandstudio.param.dimension_list_modules", aliases = "dim", customHandler = NullableDimensionHandler.class)
|
||||
IrisDimension dimension
|
||||
) {
|
||||
IrisDimension pack = namedOrCurrentPack(dimension);
|
||||
if (pack == null) {
|
||||
return;
|
||||
}
|
||||
PackModulesListing.describe(pack.getLoader()).lines().forEach(sender()::sendMessage);
|
||||
}
|
||||
|
||||
@Director(description = "Open the image-map studio (External GUI)", descriptionKey = "iris.director.commandstudio.director.open_image_map_studio_external_gui", aliases = {"imap"})
|
||||
@@ -279,12 +310,13 @@ public class CommandStudio implements DirectorExecutor {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_MUST_HAVE_SERVER_LAUNCHED_GUIS_ENABLED_SETTINGS));
|
||||
return;
|
||||
}
|
||||
if (!IrisToolbelt.isIrisWorld(world)) {
|
||||
World target = irisWorldOrCurrent(world);
|
||||
if (target == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
|
||||
return;
|
||||
}
|
||||
|
||||
Engine activeEngine = IrisToolbelt.access(world).getEngine();
|
||||
Engine activeEngine = IrisToolbelt.access(target).getEngine();
|
||||
ImageMapStudioGUI.launch(activeEngine);
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO));
|
||||
}
|
||||
@@ -298,11 +330,10 @@ public class CommandStudio implements DirectorExecutor {
|
||||
) {
|
||||
if (noStudio()) return;
|
||||
|
||||
KList<IrisLootTable> tables = EngineBukkitOps.getLootTables(engine(), RNG.r, player().getLocation().getBlock());
|
||||
Inventory inv = Bukkit.createInventory(null, 27 * 2);
|
||||
|
||||
try {
|
||||
EngineBukkitOps.addItems(engine(), true, inv, tables, InventorySlotType.STORAGE, player().getWorld(), player().getLocation().getBlockX(), player().getLocation().getBlockY(), player().getLocation().getBlockZ());
|
||||
EngineBukkitOps.addLootOf(engine(), true, inv, player().getLocation());
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError(e);
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_CANNOT_ADD_ITEMS_VIRTUAL_INVENTORY_BECAUSE, MessageArgument.untrusted("value", String.valueOf(e.getMessage()))));
|
||||
@@ -329,7 +360,7 @@ public class CommandStudio implements DirectorExecutor {
|
||||
inv.clear();
|
||||
}
|
||||
|
||||
EngineBukkitOps.addItems(engine, true, inv, tables, InventorySlotType.STORAGE, player.getWorld(), player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ());
|
||||
EngineBukkitOps.addLootOf(engine, true, inv, player.getLocation());
|
||||
}, fast ? 5 : 35));
|
||||
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_INVENTORY_NOW));
|
||||
@@ -360,7 +391,7 @@ public class CommandStudio implements DirectorExecutor {
|
||||
boolean progressShown = false;
|
||||
int c = -1;
|
||||
try {
|
||||
engine.getDimension().getRegions().forEach(key -> data.put(key, new AtomicInteger(0)));
|
||||
engine.getDimension().getRegionKeys().forEach(key -> data.put(key, new AtomicInteger(0)));
|
||||
multiBurst = new MultiBurst("Region Sampler");
|
||||
var executor = multiBurst.burst(Math.min(radius * radius, 1 << 20));
|
||||
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_GENERATING_DATA));
|
||||
@@ -382,8 +413,7 @@ public class CommandStudio implements DirectorExecutor {
|
||||
executor.complete();
|
||||
|
||||
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_DONE));
|
||||
var loader = engine.getData().getRegionLoader();
|
||||
data.forEach((k, v) -> sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_MESSAGE, MessageArgument.untrusted("k", k), MessageArgument.untrusted("value", loader.load(k).getRarity()), MessageArgument.untrusted("value2", Form.f((double) v.get() / totalTasks * 100, 2)))));
|
||||
data.forEach((k, v) -> sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_MESSAGE, MessageArgument.untrusted("k", k), MessageArgument.untrusted("value", engine.getDimension().getRegionWeight(k)),MessageArgument.untrusted("value2", Form.f((double) v.get() / totalTasks * 100, 2)))));
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError(e);
|
||||
sender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_REGIONS_SCAN_FAILED,
|
||||
@@ -408,35 +438,48 @@ public class CommandStudio implements DirectorExecutor {
|
||||
@Param(name = "world", description = "The world to open the generator for", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true)
|
||||
World world
|
||||
) {
|
||||
if (noGUI()) return;
|
||||
|
||||
if (!IrisToolbelt.isIrisWorld(world)) {
|
||||
World target = irisWorldOrCurrent(world);
|
||||
if (target == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
|
||||
return;
|
||||
}
|
||||
|
||||
UUID openerId = sender().isPlayer() ? player().getUniqueId() : null;
|
||||
VisionGUI.launch(IrisToolbelt.access(world).getEngine(), openerId);
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP));
|
||||
PlatformChunkGenerator generator = IrisToolbelt.access(target);
|
||||
try {
|
||||
StudioBridge bridge = StudioBridges.open(target.getName(), generator::getEngine, openerId);
|
||||
if (!StudioWindow.show(bridge)) {
|
||||
sender().sendMessage(IrisLanguage.text(IrisMessages.STUDIO_MAP_READY,
|
||||
MessageArgument.untrusted("world", target.getName()), MessageArgument.untrusted("link", bridge.link())));
|
||||
}
|
||||
} catch (IOException error) {
|
||||
sender().sendMessage(IrisLanguage.text(IrisMessages.STUDIO_MAP_FAILED, MessageArgument.untrusted("value", String.valueOf(error.getMessage()))));
|
||||
}
|
||||
}
|
||||
|
||||
@Director(description = "Package a dimension into a compressed format", descriptionKey = "iris.director.commandstudio.director.package_dimension_into_compressed_format", aliases = "package")
|
||||
public void pkg(
|
||||
@Param(name = "dimension", description = "The dimension pack to compress", descriptionKey = "iris.director.commandstudio.param.dimension_pack_compress", contextual = true, contextualOverride = true, defaultValue = "default", customHandler = DimensionHandler.class)
|
||||
@Param(name = "dimension", description = "The dimension pack to compress", descriptionKey = "iris.director.commandstudio.param.dimension_pack_compress", aliases = "dim", defaultValue = "null", customHandler = NullableDimensionHandler.class)
|
||||
IrisDimension dimension,
|
||||
@Param(name = "obfuscate", description = "Whether or not to obfuscate the pack", descriptionKey = "iris.director.commandstudio.param.whether_not_obfuscate_pack", defaultValue = "false")
|
||||
boolean obfuscate,
|
||||
@Param(name = "minify", description = "Whether or not to minify the pack", descriptionKey = "iris.director.commandstudio.param.whether_not_minify_pack", defaultValue = "true")
|
||||
boolean minify
|
||||
) {
|
||||
Iris.service(StudioSVC.class).compilePackage(sender(), dimension.getLoadKey(), obfuscate, minify);
|
||||
IrisDimension pack = namedOrCurrentPack(dimension);
|
||||
if (pack == null) {
|
||||
return;
|
||||
}
|
||||
Iris.service(StudioSVC.class).compilePackage(sender(), pack.getLoadKey(), minify);
|
||||
}
|
||||
|
||||
@Director(description = "Profiles the performance of a dimension", descriptionKey = "iris.director.commandstudio.director.profiles_performance_dimension", origin = DirectorOrigin.PLAYER)
|
||||
public void profile(
|
||||
@Param(description = "The dimension to profile", descriptionKey = "iris.director.commandstudio.param.dimension_profile", contextual = true, contextualOverride = true, defaultValue = "default", customHandler = DimensionHandler.class)
|
||||
IrisDimension dimension
|
||||
@Param(name = "dimension", description = "The dimension to profile", descriptionKey = "iris.director.commandstudio.param.dimension_profile", aliases = "dim", defaultValue = "null", customHandler = NullableDimensionHandler.class)
|
||||
IrisDimension named
|
||||
) {
|
||||
IrisDimension dimension = namedOrCurrentPack(named);
|
||||
if (dimension == null) {
|
||||
return;
|
||||
}
|
||||
// Todo: Make this more accurate
|
||||
File pack = dimension.getLoadFile().getParentFile().getParentFile();
|
||||
File report = Iris.instance.getDataFile("profile.txt");
|
||||
@@ -555,13 +598,6 @@ public class CommandStudio implements DirectorExecutor {
|
||||
IrisBiome b = data.getBiomeLoader().load(i);
|
||||
double score = 0;
|
||||
|
||||
int m = 0;
|
||||
for (IrisBiomePaletteLayer j : b.getLayers()) {
|
||||
m++;
|
||||
score += styleTimings.get(j.getStyle().getStyle());
|
||||
vv.add("Palette Layer " + m + ": " + styleTimings.get(j.getStyle().getStyle()));
|
||||
}
|
||||
|
||||
score += styleTimings.get(b.getBiomeStyle().getStyle());
|
||||
vv.add("Biome Style: " + styleTimings.get(b.getBiomeStyle().getStyle()));
|
||||
score += styleTimings.get(b.getChildStyle().getStyle());
|
||||
@@ -648,8 +684,8 @@ public class CommandStudio implements DirectorExecutor {
|
||||
|
||||
@Director(description = "Spawn an Iris entity", descriptionKey = "iris.director.commandstudio.director.spawn_iris_entity", aliases = "summon", origin = DirectorOrigin.PLAYER)
|
||||
public void spawn(
|
||||
@Param(description = "The entity to spawn", descriptionKey = "iris.director.commandstudio.param.entity_spawn")
|
||||
IrisEntity entity,
|
||||
@Param(description = "The entity to spawn", descriptionKey = "iris.director.commandstudio.param.entity_spawn", customHandler = EntityKeyHandler.class)
|
||||
String entity,
|
||||
@Param(description = "The location to spawn the entity at", descriptionKey = "iris.director.commandstudio.param.location_spawn_entity_at", contextual = true, contextualOverride = true)
|
||||
Vector location
|
||||
) {
|
||||
@@ -662,7 +698,7 @@ public class CommandStudio implements DirectorExecutor {
|
||||
|
||||
// Entity creation must run on the thread owning the destination chunk.
|
||||
Location at = new Location(world(), location.getX(), location.getY(), location.getZ());
|
||||
if (!J.runAt(at, () -> entity.spawn(spawnEngine, at))) {
|
||||
if (!J.runAt(at, () -> BukkitEntitySpawner.spawnByKey(spawnEngine, entity, at))) {
|
||||
Iris.warn("Could not schedule the entity spawn at " + at.getBlockX() + ", " + at.getBlockY() + ", " + at.getBlockZ() + ".");
|
||||
}
|
||||
}
|
||||
@@ -691,17 +727,20 @@ public class CommandStudio implements DirectorExecutor {
|
||||
});
|
||||
}
|
||||
|
||||
@Director(description = "Update your dimension projects VSCode workspace", descriptionKey = "iris.director.commandstudio.director.update_your_dimension_projects_vscode_workspace")
|
||||
@Director(description = "Update a pack's modules to the versions this Iris ships", descriptionKey = "iris.director.commandstudio.director.update_pack_modules")
|
||||
public void update(
|
||||
@Param(description = "The dimension to update the workspace of", descriptionKey = "iris.director.commandstudio.param.dimension_update_workspace", contextual = true, contextualOverride = true, defaultValue = "default", customHandler = DimensionHandler.class)
|
||||
IrisDimension dimension
|
||||
@Param(description = "The pack to update", descriptionKey = "iris.director.commandstudio.param.dimension_update_modules", aliases = "dim", defaultValue = "null", customHandler = NullableDimensionHandler.class)
|
||||
IrisDimension dimension,
|
||||
@Param(defaultValue = "false", description = "Also add every module Iris ships that the pack does not list", descriptionKey = "iris.director.commandstudio.param.force_restore_shipped_modules", aliases = "f")
|
||||
boolean force
|
||||
) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_UPDATING_CODE_WORKSPACE, MessageArgument.untrusted("value", dimension.getName())));
|
||||
if (new IrisCodeWorkspace(new IrisProject(dimension.getLoader().getDataFolder())).updateWorkspace()) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_UPDATED_CODE_WORKSPACE, MessageArgument.untrusted("value", dimension.getName())));
|
||||
} else {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_INVALID_PROJECT_TRY_DELETING_CODE_WORKSPACE_FILE_TRY_AGAIN, MessageArgument.untrusted("value", dimension.getName())));
|
||||
IrisDimension pack = namedOrCurrentPack(dimension);
|
||||
if (pack == null) {
|
||||
return;
|
||||
}
|
||||
IrisData data = pack.getLoader();
|
||||
List<String> lines = force ? KeptModuleUpdates.restoreForPack(data) : KeptModuleUpdates.takeForPack(data);
|
||||
lines.forEach(sender()::sendMessage);
|
||||
}
|
||||
|
||||
@Director(aliases = "find-objects", description = "Capture an IGenData chunk report for nearby chunks", descriptionKey = "iris.director.commandstudio.director.capture_igendata_chunk_report_nearby_chunks", origin = DirectorOrigin.PLAYER)
|
||||
@@ -797,7 +836,6 @@ public class CommandStudio implements DirectorExecutor {
|
||||
|
||||
KList<String> biomes = new KList<>();
|
||||
KList<String> caveBiomes = new KList<>();
|
||||
KMap<String, KMap<String, KList<String>>> objects = new KMap<>();
|
||||
|
||||
for (Chunk i : chunks) {
|
||||
for (int j = 0; j < 16; j += 3) {
|
||||
@@ -809,8 +847,6 @@ public class CommandStudio implements DirectorExecutor {
|
||||
IrisBiome bxf = engine().getCaveBiome((i.getX() * 16) + j, (i.getZ() * 16) + k);
|
||||
biomes.addIfMissing(bb.getName() + " [" + Form.capitalize(bb.getInferredType().name().toLowerCase()) + "] " + " (" + bb.getLoadFile().getName() + ")");
|
||||
caveBiomes.addIfMissing(bxf.getName() + " (" + bxf.getLoadFile().getName() + ")");
|
||||
exportObjects(bb, pw, engine(), objects);
|
||||
exportObjects(bxf, pw, engine(), objects);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -835,59 +871,12 @@ public class CommandStudio implements DirectorExecutor {
|
||||
}
|
||||
pw.println();
|
||||
|
||||
pw.println("== Object Info ==");
|
||||
|
||||
for (String i : objects.k()) {
|
||||
pw.println("- " + i);
|
||||
|
||||
for (String j : objects.get(i).k()) {
|
||||
pw.println(" @ " + j);
|
||||
|
||||
for (String k : objects.get(i).get(j)) {
|
||||
pw.println(" * " + k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pw.println();
|
||||
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_REPORTED, MessageArgument.untrusted("value", ff.getPath())));
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void exportObjects(IrisBiome bb, PrintWriter pw, Engine g, KMap<String, KMap<String, KList<String>>> objects) {
|
||||
String n1 = bb.getName() + " [" + Form.capitalize(bb.getInferredType().name().toLowerCase()) + "] " + " (" + bb.getLoadFile().getName() + ")";
|
||||
int m = 0;
|
||||
KSet<String> stop = new KSet<>();
|
||||
for (IrisObjectPlacement f : bb.getObjects()) {
|
||||
m++;
|
||||
String n2 = "Placement #" + m + " (" + f.getPlace().size() + " possible objects)";
|
||||
|
||||
for (String i : f.getPlace()) {
|
||||
String nn3 = i + ": [ERROR] Failed to find object!";
|
||||
|
||||
try {
|
||||
if (stop.contains(i)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
File ff = g.getData().getObjectLoader().findFile(i);
|
||||
art.arcane.iris.util.common.math.IrisBlockVector sz = IrisObject.sampleSize(ff);
|
||||
nn3 = i + ": size=[" + sz.getBlockX() + "," + sz.getBlockY() + "," + sz.getBlockZ() + "] location=[" + ff.getPath() + "]";
|
||||
stop.add(i);
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError(e);
|
||||
}
|
||||
|
||||
String n3 = nn3;
|
||||
objects.computeIfAbsent(n1, (k1) -> new KMap<>())
|
||||
.computeIfAbsent(n2, (k) -> new KList<>()).addIfMissing(n3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if server GUIs are not enabled
|
||||
*/
|
||||
@@ -899,6 +888,45 @@ public class CommandStudio implements DirectorExecutor {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The studio the sender stands in, else the open studio; null when no studio is open. */
|
||||
private PlatformChunkGenerator currentStudio() {
|
||||
if (sender().isPlayer() && IrisToolbelt.isStudio(world())) {
|
||||
return IrisToolbelt.access(world());
|
||||
}
|
||||
IrisProject project = Iris.service(StudioSVC.class).getActiveProject();
|
||||
return project == null ? null : project.getActiveProvider();
|
||||
}
|
||||
|
||||
/** The Iris world the sender stands in, else the open studio; null when there is neither. */
|
||||
private Engine currentIrisEngine() {
|
||||
PlatformChunkGenerator generator = sender().isPlayer() && IrisToolbelt.isIrisWorld(world())
|
||||
? IrisToolbelt.access(world())
|
||||
: currentStudio();
|
||||
return generator == null ? null : generator.getEngine();
|
||||
}
|
||||
|
||||
/** The pack named, else the current Iris world's; null after asking the sender to name one. */
|
||||
private IrisDimension namedOrCurrentPack(IrisDimension named) {
|
||||
if (named != null) {
|
||||
return named;
|
||||
}
|
||||
Engine current = currentIrisEngine();
|
||||
if (current == null) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_NAME_PACK_OUTSIDE_STUDIO));
|
||||
return null;
|
||||
}
|
||||
return current.getDimension();
|
||||
}
|
||||
|
||||
/** The world given when it is an Iris world, else the current Iris world; null when there is neither. */
|
||||
private World irisWorldOrCurrent(World given) {
|
||||
if (given != null && IrisToolbelt.isIrisWorld(given)) {
|
||||
return given;
|
||||
}
|
||||
Engine current = currentIrisEngine();
|
||||
return current == null ? null : BukkitWorldBinding.world(current.getWorld());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if no studio is open or the player is not in one
|
||||
*/
|
||||
|
||||
@@ -30,8 +30,8 @@ import art.arcane.iris.engine.framework.GenerationSessionException;
|
||||
import art.arcane.iris.engine.framework.GenerationSessionLease;
|
||||
import art.arcane.iris.engine.platform.EngineBukkitOps;
|
||||
import art.arcane.iris.util.project.context.IrisContext;
|
||||
import art.arcane.iris.engine.object.IrisBiome;
|
||||
import art.arcane.iris.engine.object.IrisRegion;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.util.common.director.DirectorExecutor;
|
||||
import art.arcane.iris.util.common.plugin.VolmitSender;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
@@ -181,7 +181,7 @@ public class CommandWhat implements DirectorExecutor {
|
||||
private static final int MARKER_SIGNAL_BATCH = 128;
|
||||
|
||||
@Director(description = "Show markers in chunk", descriptionKey = "iris.director.commandwhat.director.show_markers_chunk", origin = DirectorOrigin.PLAYER)
|
||||
public void markers(@Param(description = "Marker name such as cave_floor or cave_ceiling", descriptionKey = "iris.director.commandwhat.param.marker_name_such_as_cave_floor_cave_ceiling") String marker) {
|
||||
public void markers(@Param(description = "Marker name such as cave_floor", descriptionKey = "iris.director.commandwhat.param.marker_name_such_as_cave_floor") String marker) {
|
||||
VolmitSender commandSender = sender();
|
||||
Player player = player();
|
||||
if (player == null) {
|
||||
|
||||
+6
-6
@@ -1,21 +1,21 @@
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.engine.object.IrisObject;
|
||||
import art.arcane.iris.engine.object.IrisObjectRotation;
|
||||
import art.arcane.iris.util.common.math.IrisBlockVector;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.engine.object.prefab.ObjectTurn;
|
||||
import art.arcane.volmlib.util.math.IrisBlockVector;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
record ObjectPasteBounds(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) {
|
||||
static ObjectPasteBounds resolve(
|
||||
IrisObject object,
|
||||
IrisObjectRotation rotation,
|
||||
ObjectTurn turn,
|
||||
int anchorX,
|
||||
int anchorY,
|
||||
int anchorZ
|
||||
) {
|
||||
IrisObject placedObject = Objects.requireNonNull(object, "object");
|
||||
IrisObjectRotation placementRotation = Objects.requireNonNull(rotation, "rotation");
|
||||
ObjectTurn pastedTurn = Objects.requireNonNull(turn, "turn");
|
||||
int[] xOffsets = {
|
||||
-placedObject.getCenter().getBlockX(),
|
||||
placedObject.getW() - 1 - placedObject.getCenter().getBlockX()
|
||||
@@ -38,7 +38,7 @@ record ObjectPasteBounds(int minX, int minY, int minZ, int maxX, int maxY, int m
|
||||
for (int xOffset : xOffsets) {
|
||||
for (int yOffset : yOffsets) {
|
||||
for (int zOffset : zOffsets) {
|
||||
IrisBlockVector transformed = placementRotation.rotate(new IrisBlockVector(xOffset, yOffset, zOffset));
|
||||
IrisBlockVector transformed = pastedTurn.rotate(new IrisBlockVector(xOffset, yOffset, zOffset));
|
||||
int worldX = anchorX + (int) Math.round(transformed.getX());
|
||||
int worldY = anchorY + (int) Math.round(transformed.getY());
|
||||
int worldZ = anchorZ + (int) Math.round(transformed.getZ());
|
||||
|
||||
+10
-10
@@ -21,7 +21,7 @@ package art.arcane.iris.core.gui;
|
||||
import art.arcane.iris.engine.IrisComplex;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.render.RenderType;
|
||||
import art.arcane.iris.engine.object.IrisWorld;
|
||||
import art.arcane.iris.engine.object.world.IrisWorld;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
@@ -81,7 +81,7 @@ public final class BukkitVisionOverlay implements GuiOverlay {
|
||||
List<GuiMarker> markers = new ArrayList<>();
|
||||
for (Player player : BukkitWorldBinding.players(engine.getWorld())) {
|
||||
Location at = player.getLocation();
|
||||
markers.add(GuiMarker.player(player.getName(), at.getX(), at.getZ()));
|
||||
markers.add(GuiMarker.player(player.getName(), at.getX(), at.getZ(), at.getYaw()));
|
||||
}
|
||||
playerMarkers = List.copyOf(markers);
|
||||
} finally {
|
||||
@@ -156,8 +156,8 @@ public final class BukkitVisionOverlay implements GuiOverlay {
|
||||
public void teleport(double worldX, double worldZ) {
|
||||
VisionTeleportRequest request = new VisionTeleportRequest(
|
||||
teleportSequence.incrementAndGet(),
|
||||
VisionGUI.floorWorldCoordinate(worldX),
|
||||
VisionGUI.floorWorldCoordinate(worldZ));
|
||||
(int) StrictMath.floor(worldX),
|
||||
(int) StrictMath.floor(worldZ));
|
||||
latestTeleport.set(request);
|
||||
startTeleport(request);
|
||||
}
|
||||
@@ -318,12 +318,12 @@ public final class BukkitVisionOverlay implements GuiOverlay {
|
||||
public String openInEditor(double worldX, double worldZ, RenderType type) {
|
||||
IrisComplex complex = engine.getComplex();
|
||||
File file = switch (type) {
|
||||
case BIOME, LAYER_LOAD, DECORATOR_LOAD, OBJECT_LOAD, HEIGHT ->
|
||||
complex.getTrueBiomeStream().get(worldX, worldZ).openInVSCode();
|
||||
case BIOME_LAND -> complex.getLandBiomeStream().get(worldX, worldZ).openInVSCode();
|
||||
case BIOME_SEA -> complex.getSeaBiomeStream().get(worldX, worldZ).openInVSCode();
|
||||
case REGION -> complex.getRegionStream().get(worldX, worldZ).openInVSCode();
|
||||
case CAVE_LAND -> complex.getCaveBiomeStream().get(worldX, worldZ).openInVSCode();
|
||||
case BIOME, HEIGHT ->
|
||||
complex.getTrueBiomeStream().get(worldX, worldZ).openInEditor();
|
||||
case BIOME_LAND -> complex.getLandBiomeStream().get(worldX, worldZ).openInEditor();
|
||||
case BIOME_SEA -> complex.getSeaBiomeStream().get(worldX, worldZ).openInEditor();
|
||||
case REGION -> complex.getRegionStream().get(worldX, worldZ).openInEditor();
|
||||
case CAVE_LAND -> complex.getCaveBiomeStream().get(worldX, worldZ).openInEditor();
|
||||
default -> null;
|
||||
};
|
||||
return file == null ? null : file.getName();
|
||||
|
||||
+7
-7
@@ -30,13 +30,13 @@ import art.arcane.iris.core.service.IrisApiEventSVC;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.core.tools.WorldMaintenance;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.EngineMode;
|
||||
import art.arcane.iris.engine.framework.EngineGeneration;
|
||||
import art.arcane.iris.engine.framework.EnginePlatformHooks;
|
||||
import art.arcane.iris.engine.framework.NativeStructureVolume;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisDimensionRuntimeContract;
|
||||
import art.arcane.iris.engine.object.IrisWorld;
|
||||
import art.arcane.iris.engine.object.IrisWorldBoundary;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimensionRuntimeContract;
|
||||
import art.arcane.iris.engine.object.world.IrisWorld;
|
||||
import art.arcane.iris.engine.object.world.IrisWorldBoundary;
|
||||
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
@@ -137,7 +137,7 @@ public final class BukkitEnginePlatformHooks implements EnginePlatformHooks {
|
||||
return false;
|
||||
}
|
||||
boolean maintenanceActive = WorldMaintenance.isWorldMaintenanceActive(world.identity());
|
||||
return EngineMode.shouldDisableContextCacheForMaintenance(maintenanceActive, isPregeneratorActive(engine));
|
||||
return EngineGeneration.shouldDisableContextCacheForMaintenance(maintenanceActive, isPregeneratorActive(engine));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -159,7 +159,7 @@ public final class BukkitEnginePlatformHooks implements EnginePlatformHooks {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean shouldBypassMantleStages(Engine engine) {
|
||||
public boolean shouldRefuseGeneration(Engine engine) {
|
||||
if (!J.isFolia() || !engine.getWorld().hasPlatformWorld()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.core.nms.INMS;
|
||||
import art.arcane.iris.util.common.plugin.IrisService;
|
||||
import io.papermc.paper.event.server.ServerResourcesReloadedEvent;
|
||||
import org.bukkit.event.EventHandler;
|
||||
|
||||
public class BlockRulesSVC implements IrisService {
|
||||
private static final String RELOAD_EVENT_CLASS = "io.papermc.paper.event.server.ServerResourcesReloadedEvent";
|
||||
|
||||
public static boolean isSupported() {
|
||||
try {
|
||||
Class.forName(RELOAD_EVENT_CLASS, false, BlockRulesSVC.class.getClassLoader());
|
||||
return true;
|
||||
} catch (ClassNotFoundException | LinkageError unavailable) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onResourcesReloaded(ServerResourcesReloadedEvent event) {
|
||||
INMS.get().forgetBlockRules();
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.core.project.IrisProject;
|
||||
import art.arcane.iris.core.toolworld.BukkitToolWorldService;
|
||||
import art.arcane.iris.core.tooling.IrisServedPack;
|
||||
import art.arcane.iris.core.tooling.SenderWorld;
|
||||
import art.arcane.iris.core.tooling.ServedPack;
|
||||
import art.arcane.iris.core.tooling.ToolingSender;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import art.arcane.iris.spi.IrisServices;
|
||||
import art.arcane.iris.util.common.format.C;
|
||||
import art.arcane.iris.util.common.plugin.VolmitSender;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import com.volmit.tooling.world.ToolPlayer;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A Bukkit sender of a tooling command. It reads the world the sender stands in and the open studio when it is built, which
|
||||
* the adapter does on the thread that received the command, and delivers messages on the sender's own thread.
|
||||
*/
|
||||
public final class BukkitToolingSender implements ToolingSender {
|
||||
private final CommandSender sender;
|
||||
private final VolmitSender messages;
|
||||
private final Optional<SenderWorld> world;
|
||||
private final Optional<ServedPack> openStudioPack;
|
||||
|
||||
public BukkitToolingSender(CommandSender sender) {
|
||||
this.sender = sender;
|
||||
this.messages = new VolmitSender(sender);
|
||||
this.world = standingWorld(sender);
|
||||
this.openStudioPack = openStudio();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return sender.getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String message) {
|
||||
deliver(C.WHITE + message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void success(String message) {
|
||||
deliver(C.GREEN + message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String message) {
|
||||
deliver(C.RED + message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> Optional<T> extension(Class<T> type) {
|
||||
return type.isInstance(sender) ? Optional.of(type.cast(sender)) : Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ToolPlayer> player() {
|
||||
BukkitToolWorldService toolWorlds = IrisServices.getOrNull(BukkitToolWorldService.class);
|
||||
if (!(sender instanceof Player player) || toolWorlds == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(toolWorlds.playerOf(player));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOperator() {
|
||||
return sender.hasPermission(CommandSVC.ROOT_PERMISSION);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<SenderWorld> world() {
|
||||
return world;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ServedPack> openStudioPack() {
|
||||
return openStudioPack;
|
||||
}
|
||||
|
||||
private void deliver(String message) {
|
||||
if (sender instanceof Player player) {
|
||||
J.runEntity(player, () -> messages.sendMessage(message));
|
||||
return;
|
||||
}
|
||||
messages.sendMessage(message);
|
||||
}
|
||||
|
||||
private static Optional<SenderWorld> standingWorld(CommandSender sender) {
|
||||
if (!(sender instanceof Player player)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.ofNullable(IrisToolbelt.access(player.getWorld()))
|
||||
.map(PlatformChunkGenerator::getEngine)
|
||||
.filter(engine -> !engine.isClosed())
|
||||
.map(SenderWorld::of);
|
||||
}
|
||||
|
||||
private static Optional<ServedPack> openStudio() {
|
||||
StudioSVC studio = IrisServices.getOrNull(StudioSVC.class);
|
||||
if (studio == null || !studio.isProjectOpen()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.ofNullable(studio.getActiveProject())
|
||||
.map(IrisProject::getActiveProvider)
|
||||
.map(PlatformChunkGenerator::getEngine)
|
||||
.filter(engine -> !engine.isClosed())
|
||||
.map(Engine::getData)
|
||||
.map(IrisServedPack::new);
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,9 @@ package art.arcane.iris.core.service;
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.core.IrisSettings;
|
||||
import art.arcane.iris.core.commands.CommandIris;
|
||||
import art.arcane.iris.engine.data.cache.AtomicCache;
|
||||
import art.arcane.iris.core.tooling.ToolingCommands;
|
||||
import art.arcane.iris.core.tooling.ToolingSender;
|
||||
import art.arcane.volmlib.util.cache.AtomicCache;
|
||||
import art.arcane.iris.util.common.director.DirectorContext;
|
||||
import art.arcane.iris.util.common.director.DirectorContextHandler;
|
||||
import art.arcane.iris.util.common.director.DirectorSystem;
|
||||
@@ -54,8 +56,10 @@ import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -65,8 +69,9 @@ import art.arcane.volmlib.util.localization.MessageArgument;
|
||||
import art.arcane.volmlib.util.plugin.ComponentMessenger;
|
||||
public class CommandSVC implements IrisService, CommandExecutor, TabCompleter, DirectorInvocationHook {
|
||||
private static final String ROOT_COMMAND = "iris";
|
||||
private static final String ROOT_PERMISSION = "iris.all";
|
||||
static final String ROOT_PERMISSION = "iris.all";
|
||||
|
||||
private final transient ToolingCommands tooling = ToolingCommands.forBoundPlatform();
|
||||
private final transient AtomicCache<DirectorRuntimeEngine> directorCache = new AtomicCache<>();
|
||||
private final transient ThreadLocal<CommandSender> dispatchSenders = new ThreadLocal<>();
|
||||
|
||||
@@ -169,25 +174,52 @@ public class CommandSVC implements IrisService, CommandExecutor, TabCompleter, D
|
||||
}
|
||||
|
||||
public void executeRoot(CommandSender sender, String label, String[] args) {
|
||||
ToolingSender toolingSender = new BukkitToolingSender(sender);
|
||||
if (!sender.hasPermission(ROOT_PERMISSION)) {
|
||||
ComponentMessenger.sendSection(sender, IrisLanguage.text(
|
||||
IrisMessages.COMMAND_PERMISSION_DENIED,
|
||||
MessageArgument.trusted("permission", ROOT_PERMISSION)
|
||||
));
|
||||
J.aBukkit(() -> denyUnlessOpenToEveryone(sender, toolingSender, args));
|
||||
return;
|
||||
}
|
||||
|
||||
J.aBukkit(() -> executeCommand(sender, label, args));
|
||||
J.aBukkit(() -> executeCommand(sender, toolingSender, label, args));
|
||||
}
|
||||
|
||||
private void denyUnlessOpenToEveryone(CommandSender sender, ToolingSender toolingSender, String[] args) {
|
||||
if (isModuleBranch(args) && tooling.executeIfOpenToEveryone(toolingSender, wordsAfterBranch(args))) {
|
||||
return;
|
||||
}
|
||||
ComponentMessenger.sendSection(sender, IrisLanguage.text(
|
||||
IrisMessages.COMMAND_PERMISSION_DENIED,
|
||||
MessageArgument.trusted("permission", ROOT_PERMISSION)
|
||||
));
|
||||
}
|
||||
|
||||
private static boolean isModuleBranch(String[] args) {
|
||||
return args.length > 0 && ToolingCommands.isBranchWord(args[0]);
|
||||
}
|
||||
|
||||
private static List<String> wordsAfterBranch(String[] args) {
|
||||
return Arrays.asList(args).subList(1, args.length);
|
||||
}
|
||||
|
||||
public List<String> tabCompleteRoot(CommandSender sender, String alias, String[] args) {
|
||||
List<String> suggestions = runDirectorTab(sender, alias, args);
|
||||
List<String> suggestions = isModuleBranch(args) && args.length > 1
|
||||
? tooling.complete(new BukkitToolingSender(sender), wordsAfterBranch(args))
|
||||
: directorSuggestionsWithModuleBranch(sender, alias, args);
|
||||
if (sender instanceof Player player && IrisSettings.get().getGeneral().isCommandSounds()) {
|
||||
player.playSound(player.getLocation(), Sound.BLOCK_AMETHYST_BLOCK_CHIME, 0.25f, RNG.r.f(0.125f, 1.95f));
|
||||
}
|
||||
return suggestions;
|
||||
}
|
||||
|
||||
private List<String> directorSuggestionsWithModuleBranch(CommandSender sender, String alias, String[] args) {
|
||||
List<String> suggestions = new ArrayList<>(runDirectorTab(sender, alias, args));
|
||||
boolean typingFirstWord = args.length == 1;
|
||||
if (typingFirstWord && ToolingCommands.BRANCH.startsWith(args[0].toLowerCase(Locale.ROOT))) {
|
||||
suggestions.add(ToolingCommands.BRANCH);
|
||||
}
|
||||
return suggestions;
|
||||
}
|
||||
|
||||
private PluginCommand findBukkitCommand() {
|
||||
try {
|
||||
return Iris.instance.getCommand(ROOT_COMMAND);
|
||||
@@ -215,7 +247,13 @@ public class CommandSVC implements IrisService, CommandExecutor, TabCompleter, D
|
||||
}
|
||||
}
|
||||
|
||||
private void executeCommand(CommandSender sender, String label, String[] args) {
|
||||
private void executeCommand(CommandSender sender, ToolingSender toolingSender, String label, String[] args) {
|
||||
if (isModuleBranch(args)) {
|
||||
tooling.execute(toolingSender, wordsAfterBranch(args));
|
||||
playSuccessSound(sender);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sendHelpIfRequested(sender, args)) {
|
||||
playSuccessSound(sender);
|
||||
return;
|
||||
|
||||
+13
-17
@@ -8,7 +8,7 @@ import art.arcane.iris.core.nms.INMS;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.engine.platform.BukkitChunkGenerator;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import art.arcane.iris.engine.object.IrisImportedStructureControl;
|
||||
import art.arcane.iris.engine.framework.NativeStructureFrequencies;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.util.common.plugin.IrisService;
|
||||
import org.bukkit.Bukkit;
|
||||
@@ -41,9 +41,9 @@ public final class DatapackStructureScopeSVC implements IrisService {
|
||||
}
|
||||
for (World world : Bukkit.getWorlds()) {
|
||||
try {
|
||||
IrisImportedStructureControl importedStructures = importedStructures(world);
|
||||
if (!scopeIndex.isEmpty() || importedStructures != null && importedStructures.hasFrequencyOverrides()) {
|
||||
applyScope(world, importedStructures);
|
||||
NativeStructureFrequencies frequencies = frequencies(world);
|
||||
if (!scopeIndex.isEmpty() || frequencies.hasOverrides()) {
|
||||
applyScope(world, frequencies);
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
// Per-world containment: one world's scoping failure must not abort the
|
||||
@@ -67,10 +67,9 @@ public final class DatapackStructureScopeSVC implements IrisService {
|
||||
boolean studioEntryBootstrap = event.getWorld().getGenerator()
|
||||
instanceof BukkitChunkGenerator generator
|
||||
&& generator.isStudioEntryBootstrapActive();
|
||||
IrisImportedStructureControl importedStructures = importedStructures(event.getWorld());
|
||||
if (shouldApplyScope(scopeIndex.isEmpty(), studioEntryBootstrap,
|
||||
importedStructures != null && importedStructures.hasFrequencyOverrides())) {
|
||||
applyScope(event.getWorld(), importedStructures);
|
||||
NativeStructureFrequencies frequencies = frequencies(event.getWorld());
|
||||
if (shouldApplyScope(scopeIndex.isEmpty(), studioEntryBootstrap, frequencies.hasOverrides())) {
|
||||
applyScope(event.getWorld(), frequencies);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,14 +83,11 @@ public final class DatapackStructureScopeSVC implements IrisService {
|
||||
return !scopeIndexEmpty || studioEntryBootstrap || hasFrequencyOverrides;
|
||||
}
|
||||
|
||||
private void applyScope(World world, IrisImportedStructureControl importedStructures) {
|
||||
private void applyScope(World world, NativeStructureFrequencies frequencies) {
|
||||
Set<String> declaredSources = declaredSources(world);
|
||||
IrisImportedStructureControl activeControl = importedStructures == null
|
||||
? new IrisImportedStructureControl()
|
||||
: importedStructures;
|
||||
try {
|
||||
DatapackStructureScopeResult result = INMS.get().scopeDatapackStructures(
|
||||
world, scopeIndex, declaredSources, activeControl);
|
||||
world, scopeIndex, declaredSources, frequencies);
|
||||
IrisLogging.info("Scoped Iris-managed datapack structure sets for world '"
|
||||
+ world.getName() + "': " + result.retainedManagedSets() + " retained, "
|
||||
+ result.excludedManagedSets() + " excluded.");
|
||||
@@ -101,13 +97,13 @@ public final class DatapackStructureScopeSVC implements IrisService {
|
||||
}
|
||||
}
|
||||
|
||||
private IrisImportedStructureControl importedStructures(World world) {
|
||||
private NativeStructureFrequencies frequencies(World world) {
|
||||
PlatformChunkGenerator generator = IrisToolbelt.access(world);
|
||||
if (generator == null || generator.getTarget() == null
|
||||
|| generator.getTarget().getDimension() == null) {
|
||||
return null;
|
||||
return NativeStructureFrequencies.NONE;
|
||||
}
|
||||
return generator.getTarget().getDimension().getImportedStructures();
|
||||
return NativeStructureFrequencies.of(generator.getTarget().getData(), generator.getTarget().getDimension());
|
||||
}
|
||||
|
||||
private Set<String> declaredSources(World world) {
|
||||
@@ -116,6 +112,6 @@ public final class DatapackStructureScopeSVC implements IrisService {
|
||||
return Set.of();
|
||||
}
|
||||
return scopeIndex.declaredSources(
|
||||
generator.getTarget().getDimension().getDatapackImports());
|
||||
DatapackIngestService.configuredImports(generator.getTarget().getDimension()));
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -13,9 +13,9 @@ import art.arcane.iris.core.service.terrain.IrisSampleLimits;
|
||||
import art.arcane.iris.core.service.terrain.IrisSurfaceClassifier;
|
||||
import art.arcane.iris.core.service.terrain.IrisWorldInfoFactory;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.InferredType;
|
||||
import art.arcane.iris.engine.object.IrisBiome;
|
||||
import art.arcane.iris.engine.object.IrisRegion;
|
||||
import art.arcane.iris.engine.object.world.biome.InferredType;
|
||||
import art.arcane.iris.engine.object.world.biome.IrisBiome;
|
||||
import art.arcane.iris.engine.object.world.region.IrisRegion;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
|
||||
+1
-1
@@ -220,7 +220,7 @@ public class TreeFellerSVC implements IrisService, IrisTreeFellerService {
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void haltWhenSneakingStops(PlayerToggleSneakEvent event) {
|
||||
if (!event.isSneaking()) {
|
||||
runner.finishRuns(event.getPlayer().getUniqueId());
|
||||
runner.finishSneakRuns(event.getPlayer().getUniqueId());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+21
-1
@@ -526,10 +526,19 @@ final class TreeFellingRunner {
|
||||
private boolean isRunControlActive(FellingRun run, Player player) {
|
||||
return player.isOnline()
|
||||
&& player.getGameMode() == GameMode.SURVIVAL
|
||||
&& player.isSneaking()
|
||||
&& (!requiresSneaking(run) || player.isSneaking())
|
||||
&& player.getWorld().equals(run.candidate.world());
|
||||
}
|
||||
|
||||
private boolean requiresSneaking(FellingRun run) {
|
||||
try {
|
||||
return run.runHooks.requiresSneaking();
|
||||
} catch (RuntimeException error) {
|
||||
IrisLogging.reportError("An Iris tree-feller integration sneak requirement check failed.", error);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean reserveLogCost(FellingRun run) {
|
||||
try {
|
||||
return run.runHooks.reserveLogCost();
|
||||
@@ -611,11 +620,22 @@ final class TreeFellingRunner {
|
||||
}
|
||||
|
||||
void finishRuns(UUID playerId) {
|
||||
finishRuns(playerId, false);
|
||||
}
|
||||
|
||||
void finishSneakRuns(UUID playerId) {
|
||||
finishRuns(playerId, true);
|
||||
}
|
||||
|
||||
private void finishRuns(UUID playerId, boolean onlySneakRuns) {
|
||||
Set<FellingRun> runs = service.activeRuns.get(playerId);
|
||||
if (runs == null) {
|
||||
return;
|
||||
}
|
||||
for (FellingRun run : List.copyOf(runs)) {
|
||||
if (onlySneakRuns && !requiresSneaking(run)) {
|
||||
continue;
|
||||
}
|
||||
if (run.abortReason == null) {
|
||||
run.abortReason = "halted";
|
||||
}
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ import art.arcane.iris.core.service.tree.TreeDefinitionIndex;
|
||||
import art.arcane.iris.core.service.tree.TreeMarkerTraversal;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.framework.StructurePlacementMarker;
|
||||
import art.arcane.iris.core.modules.PlacementMarkers;
|
||||
import art.arcane.iris.engine.framework.TreeBlockMaterial;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import org.bukkit.GameMode;
|
||||
@@ -67,7 +67,7 @@ final class TreeProvenance {
|
||||
int maximumY = world.getMaxHeight();
|
||||
int relativeY = block.getY() - minimumY;
|
||||
String marker = markerAt(engine, minimumY, block.getX(), block.getY(), block.getZ());
|
||||
StructurePlacementMarker.Decoded decoded = StructurePlacementMarker.decode(marker);
|
||||
PlacementMarkers.Decoded decoded = PlacementMarkers.decode(marker);
|
||||
if (decoded == null || decoded.structureAware()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -27,13 +27,11 @@ import org.bukkit.Particle;
|
||||
import org.bukkit.Sound;
|
||||
import org.bukkit.World;
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.core.IrisSettings;
|
||||
import art.arcane.iris.core.localization.IrisLanguage;
|
||||
import art.arcane.iris.core.localization.RuntimeUiMessages;
|
||||
import art.arcane.iris.core.edit.DustRevealer;
|
||||
import art.arcane.iris.core.link.WorldEditLink;
|
||||
import art.arcane.iris.core.wand.WandSelection;
|
||||
import art.arcane.iris.engine.object.IrisObject;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import art.arcane.iris.util.project.matter.WorldMatter;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.bukkit.WorldIdentity;
|
||||
@@ -333,26 +331,14 @@ public class WandSVC implements IrisService {
|
||||
}
|
||||
|
||||
public static Location[] getCuboid(Player p) {
|
||||
if (isHoldingIrisWand(p)) {
|
||||
if (isHoldingWand(p)) {
|
||||
return getCuboidFromItem(p.getInventory().getItemInMainHand());
|
||||
}
|
||||
|
||||
if (IrisSettings.get().getWorld().worldEditWandCUI) {
|
||||
Cuboid c = WorldEditLink.getSelection(p);
|
||||
|
||||
if (c != null) {
|
||||
return new Location[]{c.getLowerNE(), c.getUpperSW()};
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static boolean isHoldingWand(Player p) {
|
||||
return isHoldingIrisWand(p) || (IrisSettings.get().getWorld().worldEditWandCUI && WorldEditLink.getSelection(p) != null);
|
||||
}
|
||||
|
||||
public static boolean isHoldingIrisWand(Player p) {
|
||||
ItemStack is = p.getInventory().getItemInMainHand();
|
||||
return is != null && isWand(is);
|
||||
}
|
||||
@@ -567,7 +553,7 @@ public class WandSVC implements IrisService {
|
||||
if (e.getHand() != EquipmentSlot.HAND)
|
||||
return;
|
||||
try {
|
||||
if (isHoldingIrisWand(e.getPlayer())) {
|
||||
if (isHoldingWand(e.getPlayer())) {
|
||||
activePlayers.put(e.getPlayer().getUniqueId(), e.getPlayer());
|
||||
if (e.getAction().equals(Action.LEFT_CLICK_BLOCK)) {
|
||||
e.setCancelled(true);
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package art.arcane.iris.core.service.terrain;
|
||||
|
||||
import art.arcane.iris.api.terrain.IrisSurfaceKind;
|
||||
import art.arcane.iris.engine.object.InferredType;
|
||||
import art.arcane.iris.engine.object.world.biome.InferredType;
|
||||
|
||||
public final class IrisSurfaceClassifier {
|
||||
private IrisSurfaceClassifier() {
|
||||
|
||||
+2
-2
@@ -2,8 +2,8 @@ package art.arcane.iris.core.service.terrain;
|
||||
|
||||
import art.arcane.iris.api.terrain.IrisWorldInfo;
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisWorld;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.object.world.IrisWorld;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.generator.ChunkGenerator;
|
||||
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure;
|
||||
|
||||
import art.arcane.iris.core.modules.BlockEntities;
|
||||
import art.arcane.iris.core.modules.PlatformBlockStates;
|
||||
import art.arcane.iris.core.nms.INMS;
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import art.arcane.iris.platform.bukkit.BukkitBlockState;
|
||||
import art.arcane.iris.util.common.plugin.VolmitSender;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.object.BlockEntityData;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.tooling.CapturedStructure;
|
||||
import com.volmit.tooling.PlatformStructures;
|
||||
import com.volmit.tooling.TemplateBlock;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
/** A throwaway Bukkit world structures are generated in one after another, one cell of a grid each, and removed on close. */
|
||||
final class BukkitCaptureArea implements PlatformStructures.CaptureArea {
|
||||
private static final int CELL_STRIDE = 128;
|
||||
private static final int CELL_COLUMNS = 8;
|
||||
private static final long REGION_TIMEOUT_SECONDS = 30L;
|
||||
|
||||
private final World world;
|
||||
private final VolmitSender sender;
|
||||
private int nextCell;
|
||||
|
||||
BukkitCaptureArea(World world, VolmitSender sender) {
|
||||
this.world = world;
|
||||
this.sender = sender;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<CapturedStructure> capture(ResourceId structure, long seed, int maxSpan) {
|
||||
int cellIndex = nextCell++;
|
||||
int originX = (cellIndex % CELL_COLUMNS) * CELL_STRIDE;
|
||||
int originZ = (cellIndex / CELL_COLUMNS) * CELL_STRIDE;
|
||||
int anchorChunkX = (originX + CELL_STRIDE / 2) >> 4;
|
||||
int anchorChunkZ = (originZ + CELL_STRIDE / 2) >> 4;
|
||||
String key = structure.toString();
|
||||
|
||||
AtomicReference<CapturedStructure> capturedRef = new AtomicReference<>();
|
||||
AtomicReference<Throwable> errorRef = new AtomicReference<>();
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
|
||||
boolean scheduled = J.runRegion(world, anchorChunkX, anchorChunkZ, () -> {
|
||||
try {
|
||||
capturedRef.set(placeAndRead(key, anchorChunkX, anchorChunkZ, seed, maxSpan));
|
||||
} catch (Throwable e) {
|
||||
errorRef.set(e);
|
||||
} finally {
|
||||
latch.countDown();
|
||||
}
|
||||
});
|
||||
|
||||
if (!scheduled) {
|
||||
throw captureFailure(key, anchorChunkX, anchorChunkZ, "region task was not accepted", null);
|
||||
}
|
||||
|
||||
try {
|
||||
if (!latch.await(REGION_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
|
||||
throw captureFailure(key, anchorChunkX, anchorChunkZ,
|
||||
"region task did not complete within " + REGION_TIMEOUT_SECONDS + " seconds", null);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw captureFailure(key, anchorChunkX, anchorChunkZ, "interrupted while waiting for the region task", e);
|
||||
}
|
||||
|
||||
Throwable error = errorRef.get();
|
||||
if (error != null) {
|
||||
throw captureFailure(key, anchorChunkX, anchorChunkZ, "platform placement failed", error);
|
||||
}
|
||||
return Optional.ofNullable(capturedRef.get());
|
||||
}
|
||||
|
||||
private CapturedStructure placeAndRead(String key, int anchorChunkX, int anchorChunkZ, long seed, int maxSpan) {
|
||||
int[] box = INMS.get().placeStructure(world, anchorChunkX, anchorChunkZ, key, seed, maxSpan);
|
||||
if (box == null) {
|
||||
return null;
|
||||
}
|
||||
int width = box[3] - box[0] + 1;
|
||||
int height = box[4] - box[1] + 1;
|
||||
int depth = box[5] - box[2] + 1;
|
||||
if (width <= 0 || height <= 0 || depth <= 0) {
|
||||
return null;
|
||||
}
|
||||
List<TemplateBlock> blocks = new ArrayList<>();
|
||||
for (int dx = 0; dx < width; dx++) {
|
||||
for (int dy = 0; dy < height; dy++) {
|
||||
for (int dz = 0; dz < depth; dz++) {
|
||||
Block block = world.getBlockAt(box[0] + dx, box[1] + dy, box[2] + dz);
|
||||
if (block.getType() == Material.AIR) {
|
||||
continue;
|
||||
}
|
||||
blocks.add(blockOf(block, dx, dy, dz));
|
||||
}
|
||||
}
|
||||
}
|
||||
unloadChunksOf(box);
|
||||
return blocks.isEmpty() ? null : new CapturedStructure(new BlockPosition(width, height, depth), blocks);
|
||||
}
|
||||
|
||||
private static TemplateBlock blockOf(Block block, int x, int y, int z) {
|
||||
BlockState state = BlockState.parse(
|
||||
PlatformBlockStates.namespaced(BukkitBlockState.of(block.getBlockData()).key()));
|
||||
TileData tile = TileData.getTileState(block, false);
|
||||
Optional<BlockEntityData> blockEntity = tile == null ? Optional.empty() : Optional.of(BlockEntities.of(tile));
|
||||
return TemplateBlock.of(new BlockPosition(x, y, z), state, blockEntity);
|
||||
}
|
||||
|
||||
private void unloadChunksOf(int[] box) {
|
||||
int minCX = box[0] >> 4;
|
||||
int maxCX = box[3] >> 4;
|
||||
int minCZ = box[2] >> 4;
|
||||
int maxCZ = box[5] >> 4;
|
||||
for (int cx = minCX; cx <= maxCX; cx++) {
|
||||
for (int cz = minCZ; cz <= maxCZ; cz++) {
|
||||
try {
|
||||
world.unloadChunk(cx, cz, false);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
FeatureImporter.destroyScratchWorld(world, sender);
|
||||
}
|
||||
|
||||
static IllegalStateException captureFailure(String key, int chunkX, int chunkZ, String detail, Throwable cause) {
|
||||
String message = "Structure capture failed for '" + key + "' at chunk "
|
||||
+ chunkX + "," + chunkZ + ": " + detail;
|
||||
return cause == null ? new IllegalStateException(message) : new IllegalStateException(message, cause);
|
||||
}
|
||||
}
|
||||
+319
@@ -0,0 +1,319 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure;
|
||||
|
||||
import art.arcane.iris.core.nms.INMS;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.util.common.plugin.VolmitSender;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.tooling.JigsawStructureInfo;
|
||||
import com.volmit.tooling.PlatformStructures;
|
||||
import com.volmit.tooling.Sender;
|
||||
import com.volmit.tooling.StructureAccessException;
|
||||
import com.volmit.tooling.StructureTemplate;
|
||||
import com.volmit.tooling.TemplatePool;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.TreeSet;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* The structures of a Bukkit server: its registered structures and structure sets through the NMS binding, the
|
||||
* jigsaw structures and template pools through the server's registries, the templates through Bukkit's structure
|
||||
* manager and the server's resource manager, and structure capture through the NMS binding in a scratch world.
|
||||
*/
|
||||
public final class BukkitPlatformStructures implements PlatformStructures {
|
||||
private static final String STRUCTURE_TEMPLATE_FOLDER = "structure";
|
||||
private static final String TEMPLATE_FILE_SUFFIX = ".nbt";
|
||||
private static final String JIGSAW_STRUCTURE_CLASS_SUFFIX = "JigsawStructure";
|
||||
|
||||
@Override
|
||||
public List<ResourceId> templates() {
|
||||
try {
|
||||
return enumerateTemplateKeys();
|
||||
} catch (Exception e) {
|
||||
throw new StructureAccessException(ServerReflection.failureDetail(e), true, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<StructureTemplate> template(ResourceId id) {
|
||||
return BukkitTemplateReader.read(Bukkit.getStructureManager().loadStructure(new NamespacedKey(id.namespace(), id.path())));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ResourceId> structures() {
|
||||
return idsOf(INMS.get().getStructureKeys());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ResourceId> structureSets() {
|
||||
return idsOf(INMS.get().getStructureSetKeys());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<JigsawStructureInfo> jigsaw(ResourceId structureKey) {
|
||||
Object registryAccess = registryAccess();
|
||||
Object structureRegistry;
|
||||
Object structure;
|
||||
try {
|
||||
structureRegistry = ServerReflection.lookupRegistry(registryAccess, "STRUCTURE");
|
||||
structure = ServerReflection.registryGet(structureRegistry, structureKey);
|
||||
} catch (Throwable e) {
|
||||
throw new StructureAccessException("Failed to read jigsaw structure graph: " + e, true, e);
|
||||
}
|
||||
if (structure == null || !structure.getClass().getName().endsWith(JIGSAW_STRUCTURE_CLASS_SUFFIX)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Object startPool;
|
||||
int maxDepth;
|
||||
int maxDistanceFromCenter;
|
||||
try {
|
||||
startPool = ServerReflection.unwrapHolder(ServerReflection.invoke(structure, "getStartPool"));
|
||||
maxDepth = ServerReflection.readIntMember(structure, "maxDepth");
|
||||
maxDistanceFromCenter = ServerReflection.readIntMember(structure, "maxDistanceFromCenter");
|
||||
} catch (Throwable e) {
|
||||
throw new StructureAccessException("Failed to read jigsaw structure graph: " + e, true, e);
|
||||
}
|
||||
Object templatePoolRegistry = templatePoolRegistry(registryAccess);
|
||||
String startPoolKey;
|
||||
try {
|
||||
startPoolKey = ServerReflection.registryKeyOf(templatePoolRegistry, startPool);
|
||||
} catch (Throwable e) {
|
||||
throw new StructureAccessException("Could not resolve the start pool key for " + structureKey + ": " + e, true, e);
|
||||
}
|
||||
if (startPoolKey == null) {
|
||||
throw new StructureAccessException("Could not resolve the start pool key for " + structureKey, false);
|
||||
}
|
||||
return Optional.of(new JigsawStructureInfo(
|
||||
ResourceId.parse(startPoolKey),
|
||||
maxDepth,
|
||||
maxDistanceFromCenter,
|
||||
Bukkit.getBukkitVersion(),
|
||||
new NamespacedKey(structureKey.namespace(), structureKey.path()).hashCode()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<TemplatePool> pool(ResourceId poolKey) {
|
||||
Object server;
|
||||
Object structureManager;
|
||||
Object registry;
|
||||
Object pool;
|
||||
try {
|
||||
server = ServerReflection.minecraftServer();
|
||||
structureManager = ServerReflection.invoke(server, "getStructureManager");
|
||||
registry = templatePoolRegistry(registryAccess());
|
||||
pool = ServerReflection.registryGet(registry, poolKey);
|
||||
} catch (StructureAccessException e) {
|
||||
throw e;
|
||||
} catch (Throwable e) {
|
||||
throw new StructureAccessException("pool " + poolKey + ": " + e.getMessage(), true, e);
|
||||
}
|
||||
if (pool == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
Optional<ResourceId> fallback = Optional.empty();
|
||||
Optional<String> fallbackFailure = Optional.empty();
|
||||
try {
|
||||
Object fallbackPool = ServerReflection.unwrapHolder(ServerReflection.invoke(pool, "getFallback"));
|
||||
String fallbackKey = ServerReflection.registryKeyOf(registry, fallbackPool);
|
||||
fallback = Optional.ofNullable(fallbackKey).map(ResourceId::parse);
|
||||
} catch (Throwable e) {
|
||||
fallbackFailure = Optional.of(ServerReflection.failureDetail(e));
|
||||
}
|
||||
|
||||
List<?> templates;
|
||||
try {
|
||||
templates = (List<?>) ServerReflection.invoke(pool, "getTemplates");
|
||||
} catch (Throwable e) {
|
||||
throw new StructureAccessException("templates " + poolKey + ": " + e.getMessage(), true, e);
|
||||
}
|
||||
List<TemplatePool.Member> members = new ArrayList<>();
|
||||
for (Object pair : templates) {
|
||||
members.add(PoolElementReader.memberOf(pair, structureManager));
|
||||
}
|
||||
return Optional.of(new TemplatePool(members, fallback, fallbackFailure));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supportsCapture() {
|
||||
return INMS.get().supportsStructureCapture();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<CaptureArea> openCaptureArea(Sender sender) {
|
||||
VolmitSender messages = messagesOf(sender);
|
||||
World scratch = FeatureImporter.createScratchWorld(messages);
|
||||
return scratch == null ? Optional.empty() : Optional.of(new BukkitCaptureArea(scratch, messages));
|
||||
}
|
||||
|
||||
private static VolmitSender messagesOf(Sender sender) {
|
||||
return sender.extension(CommandSender.class).map(VolmitSender::new).orElseGet(BukkitPlatform::console);
|
||||
}
|
||||
|
||||
private static Object registryAccess() {
|
||||
Object server;
|
||||
try {
|
||||
server = ServerReflection.minecraftServer();
|
||||
} catch (Throwable e) {
|
||||
throw new StructureAccessException("Failed to access server registries via reflection: " + e, true, e);
|
||||
}
|
||||
Object registryAccess = ServerReflection.resolveRegistryAccess(server);
|
||||
if (registryAccess == null) {
|
||||
throw new StructureAccessException("Could not resolve RegistryAccess from the server", true);
|
||||
}
|
||||
return registryAccess;
|
||||
}
|
||||
|
||||
private static Object templatePoolRegistry(Object registryAccess) {
|
||||
try {
|
||||
return ServerReflection.lookupRegistry(registryAccess, "TEMPLATE_POOL");
|
||||
} catch (Throwable e) {
|
||||
throw new StructureAccessException("Failed to access TEMPLATE_POOL registry: " + e, true, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<ResourceId> idsOf(Iterable<String> keys) {
|
||||
TreeSet<ResourceId> ids = new TreeSet<>();
|
||||
for (String key : keys) {
|
||||
if (key == null || key.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
ids.add(ResourceId.parse(key.toLowerCase(Locale.ROOT)));
|
||||
} catch (IllegalArgumentException invalidKey) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(ids);
|
||||
}
|
||||
|
||||
private static List<ResourceId> enumerateTemplateKeys() throws Exception {
|
||||
Object server = ServerReflection.minecraftServer();
|
||||
Object resourceManager = resolveResourceManager(server);
|
||||
if (resourceManager == null) {
|
||||
throw new IllegalStateException("Could not resolve the server ResourceManager via reflection");
|
||||
}
|
||||
|
||||
Method listResources = null;
|
||||
for (Method m : resourceManager.getClass().getMethods()) {
|
||||
if (m.getName().equals("listResources") && m.getParameterCount() == 2
|
||||
&& m.getParameterTypes()[0] == String.class
|
||||
&& m.getParameterTypes()[1] == Predicate.class
|
||||
&& Map.class.isAssignableFrom(m.getReturnType())) {
|
||||
listResources = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (listResources == null) {
|
||||
throw new NoSuchMethodException("listResources(String, Predicate) on " + resourceManager.getClass().getName());
|
||||
}
|
||||
listResources.setAccessible(true);
|
||||
|
||||
Predicate<Object> endsWithNbt = location -> {
|
||||
String path = identifierPath(location);
|
||||
return path != null && path.endsWith(TEMPLATE_FILE_SUFFIX);
|
||||
};
|
||||
|
||||
Object resultMap = listResources.invoke(resourceManager, STRUCTURE_TEMPLATE_FOLDER, endsWithNbt);
|
||||
TreeSet<String> keys = new TreeSet<>();
|
||||
if (resultMap instanceof Map<?, ?> map) {
|
||||
for (Object location : map.keySet()) {
|
||||
String namespace = identifierNamespace(location);
|
||||
String path = identifierPath(location);
|
||||
if (namespace == null || path == null) {
|
||||
continue;
|
||||
}
|
||||
String stripped = path;
|
||||
if (stripped.startsWith(STRUCTURE_TEMPLATE_FOLDER + "/")) {
|
||||
stripped = stripped.substring((STRUCTURE_TEMPLATE_FOLDER + "/").length());
|
||||
}
|
||||
if (stripped.endsWith(TEMPLATE_FILE_SUFFIX)) {
|
||||
stripped = stripped.substring(0, stripped.length() - TEMPLATE_FILE_SUFFIX.length());
|
||||
}
|
||||
if (stripped.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
keys.add(namespace + ":" + stripped);
|
||||
}
|
||||
}
|
||||
return idsOf(keys);
|
||||
}
|
||||
|
||||
private static Object resolveResourceManager(Object server) {
|
||||
try {
|
||||
Class<?> resourceManagerClass = Class.forName("net.minecraft.server.packs.resources.ResourceManager");
|
||||
Method getter = null;
|
||||
for (Method m : server.getClass().getMethods()) {
|
||||
if (m.getName().equals("getResourceManager") && m.getParameterCount() == 0
|
||||
&& resourceManagerClass.isAssignableFrom(m.getReturnType())) {
|
||||
getter = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (getter == null) {
|
||||
for (Method m : server.getClass().getMethods()) {
|
||||
if (m.getParameterCount() == 0 && resourceManagerClass.isAssignableFrom(m.getReturnType())) {
|
||||
getter = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (getter == null) {
|
||||
return null;
|
||||
}
|
||||
getter.setAccessible(true);
|
||||
return getter.invoke(server);
|
||||
} catch (Throwable e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String identifierNamespace(Object location) {
|
||||
try {
|
||||
Method m = location.getClass().getMethod("getNamespace");
|
||||
m.setAccessible(true);
|
||||
Object value = m.invoke(location);
|
||||
return value == null ? null : value.toString();
|
||||
} catch (Throwable e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String identifierPath(Object location) {
|
||||
try {
|
||||
Method m = location.getClass().getMethod("getPath");
|
||||
m.setAccessible(true);
|
||||
Object value = m.invoke(location);
|
||||
return value == null ? null : value.toString();
|
||||
} catch (Throwable e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure;
|
||||
|
||||
import art.arcane.iris.core.modules.BlockEntities;
|
||||
import art.arcane.iris.core.modules.PlatformBlockStates;
|
||||
import art.arcane.iris.engine.object.prefab.LegacyTileData;
|
||||
import art.arcane.iris.platform.bukkit.BukkitBlockState;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.object.BlockEntityData;
|
||||
import com.volmit.tooling.StructureTemplate;
|
||||
import com.volmit.tooling.TemplateBlock;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
import org.bukkit.structure.Palette;
|
||||
import org.bukkit.structure.Structure;
|
||||
import org.bukkit.util.BlockVector;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Reads a Bukkit {@link Structure} as a {@link StructureTemplate}: its size, and the blocks of its first palette. */
|
||||
final class BukkitTemplateReader {
|
||||
private static final String FINAL_STATE_NBT_KEY = "final_state";
|
||||
|
||||
private BukkitTemplateReader() {
|
||||
}
|
||||
|
||||
/** The template; empty when the structure holds no palette. */
|
||||
static Optional<StructureTemplate> read(Structure structure) {
|
||||
if (structure == null || structure.getPalettes().isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
BlockVector size = structure.getSize();
|
||||
Palette palette = structure.getPalettes().get(0);
|
||||
List<TemplateBlock> blocks = new ArrayList<>();
|
||||
for (org.bukkit.block.BlockState block : palette.getBlocks()) {
|
||||
blocks.add(blockOf(block));
|
||||
}
|
||||
return Optional.of(new StructureTemplate(
|
||||
new BlockPosition(size.getBlockX(), size.getBlockY(), size.getBlockZ()),
|
||||
structure.getPaletteCount(),
|
||||
structure.getEntityCount(),
|
||||
blocks));
|
||||
}
|
||||
|
||||
private static TemplateBlock blockOf(org.bukkit.block.BlockState block) {
|
||||
Location location = block.getLocation();
|
||||
BlockPosition position = new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ());
|
||||
BlockData data = block.getBlockData();
|
||||
Material material = data.getMaterial();
|
||||
BlockState state = BlockState.parse(PlatformBlockStates.namespaced(BukkitBlockState.of(data).key()));
|
||||
if (material == Material.JIGSAW) {
|
||||
return new TemplateBlock(position, state, Optional.empty(), readJigsawFinalState(block));
|
||||
}
|
||||
if (material == Material.STRUCTURE_BLOCK || material == Material.STRUCTURE_VOID) {
|
||||
return TemplateBlock.of(position, state, Optional.empty());
|
||||
}
|
||||
return TemplateBlock.of(position, state, blockEntityOf(block));
|
||||
}
|
||||
|
||||
private static Optional<BlockEntityData> blockEntityOf(org.bukkit.block.BlockState block) {
|
||||
try {
|
||||
LegacyTileData tile = LegacyTileData.fromBukkit(block);
|
||||
return tile == null ? Optional.empty() : Optional.of(BlockEntities.of(tile));
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private static Optional<String> readJigsawFinalState(org.bukkit.block.BlockState block) {
|
||||
try {
|
||||
Object nbt = block.getClass().getMethod("getSnapshotNBT").invoke(block);
|
||||
if (nbt == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Object res = nbt.getClass().getMethod("getString", String.class).invoke(nbt, FINAL_STATE_NBT_KEY);
|
||||
String finalState = null;
|
||||
if (res instanceof String s) {
|
||||
finalState = s;
|
||||
} else if (res instanceof Optional<?> o && o.isPresent()) {
|
||||
finalState = String.valueOf(o.get());
|
||||
}
|
||||
return finalState == null || finalState.isBlank() ? Optional.empty() : Optional.of(finalState);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure;
|
||||
|
||||
import com.volmit.geometry.BlockFace;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.tooling.StructureAccessException;
|
||||
import com.volmit.tooling.TemplatePool;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import java.util.function.LongSupplier;
|
||||
|
||||
/** Reads the members of a registered template pool by reflection: their weights, templates and jigsaw connectors. */
|
||||
final class PoolElementReader {
|
||||
private static final String LIST_POOL_ELEMENT_SUFFIX = "ListPoolElement";
|
||||
private static final String DEFAULT_FRONT = "north";
|
||||
private static final String DEFAULT_TOP = "up";
|
||||
private static final String FINAL_STATE_NBT_KEY = "final_state";
|
||||
|
||||
private PoolElementReader() {
|
||||
}
|
||||
|
||||
/** The member of a pool for the pair the pool lists it as: its element and weight. */
|
||||
static TemplatePool.Member memberOf(Object pair, Object structureManager) {
|
||||
Object element;
|
||||
int weight;
|
||||
try {
|
||||
element = ServerReflection.invoke(pair, "getFirst");
|
||||
Object second = ServerReflection.invoke(pair, "getSecond");
|
||||
weight = second instanceof Number ? Math.max(1, ((Number) second).intValue()) : 1;
|
||||
} catch (Throwable e) {
|
||||
return new TemplatePool.Unreadable(TemplatePool.Part.ENTRY, ServerReflection.failureDetail(e));
|
||||
}
|
||||
if (element == null) {
|
||||
return new TemplatePool.Absent();
|
||||
}
|
||||
PoolElementResolution resolution;
|
||||
try {
|
||||
resolution = resolvePoolElement(element);
|
||||
} catch (Throwable e) {
|
||||
return new TemplatePool.Unreadable(TemplatePool.Part.TEMPLATE_LOCATION, ServerReflection.failureDetail(e));
|
||||
}
|
||||
String type = resolution.physicalElement() == null
|
||||
? element.getClass().getSimpleName()
|
||||
: resolution.physicalElement().getClass().getSimpleName();
|
||||
Optional<ResourceId> template;
|
||||
try {
|
||||
template = Optional.ofNullable(resolution.templateLocation()).map(PoolElementReader::templateId);
|
||||
} catch (IllegalArgumentException invalidLocation) {
|
||||
return new TemplatePool.Unreadable(TemplatePool.Part.TEMPLATE_LOCATION,
|
||||
"invalid piece key " + resolution.templateLocation());
|
||||
}
|
||||
return new TemplatePool.Element(weight, type, template, resolution.listLevels(), resolution.omittedElements(),
|
||||
shuffleSeeds -> readConnectors(element, structureManager, shuffleSeeds));
|
||||
}
|
||||
|
||||
private static ResourceId templateId(String location) {
|
||||
return ResourceId.parse(location.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
private static TemplatePool.Connectors readConnectors(Object element, Object structureManager, LongSupplier shuffleSeeds) {
|
||||
try {
|
||||
Object zero = ServerReflection.staticField("net.minecraft.core.BlockPos", "ZERO");
|
||||
Object rotationNone = ServerReflection.staticField("net.minecraft.world.level.block.Rotation", "NONE");
|
||||
Method m = ServerReflection.findMethod(element.getClass(), "getShuffledJigsawBlocks", 4);
|
||||
if (m == null) {
|
||||
return new TemplatePool.Connectors(TemplatePool.Availability.UNAVAILABLE, List.of());
|
||||
}
|
||||
m.setAccessible(true);
|
||||
Object random = ServerReflection.freshRandomSource(shuffleSeeds.getAsLong());
|
||||
List<?> blocks = (List<?>) m.invoke(element, structureManager, zero, rotationNone, random);
|
||||
if (blocks == null) {
|
||||
return new TemplatePool.Connectors(TemplatePool.Availability.NO_COLLECTION, List.of());
|
||||
}
|
||||
List<TemplatePool.Connector> connectors = new ArrayList<>();
|
||||
for (Object jigsaw : blocks) {
|
||||
connectors.add(connectorOf(jigsaw));
|
||||
}
|
||||
return new TemplatePool.Connectors(TemplatePool.Availability.READ, connectors);
|
||||
} catch (Throwable e) {
|
||||
throw new StructureAccessException(ServerReflection.failureDetail(e), true, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static TemplatePool.Connector connectorOf(Object jigsaw) {
|
||||
try {
|
||||
return connectorFrom(jigsaw);
|
||||
} catch (Throwable e) {
|
||||
return new TemplatePool.UnreadableConnector(ServerReflection.failureDetail(e));
|
||||
}
|
||||
}
|
||||
|
||||
static TemplatePool.JigsawConnector connectorFrom(Object jigsaw) throws Exception {
|
||||
Object info = ServerReflection.invoke(jigsaw, "info");
|
||||
Object pos = ServerReflection.invoke(info, "pos");
|
||||
Object blockState = ServerReflection.invoke(info, "state");
|
||||
BlockPosition position = new BlockPosition(
|
||||
ServerReflection.readInt(pos, "getX"),
|
||||
ServerReflection.readInt(pos, "getY"),
|
||||
ServerReflection.readInt(pos, "getZ"));
|
||||
|
||||
Object poolKey = ServerReflection.invoke(jigsaw, "pool");
|
||||
String poolId = ServerReflection.identifierString(ServerReflection.invoke(poolKey, "identifier"));
|
||||
String name = ServerReflection.identifierString(ServerReflection.invoke(jigsaw, "name"));
|
||||
String target = ServerReflection.identifierString(ServerReflection.invoke(jigsaw, "target"));
|
||||
Object jointType = ServerReflection.invoke(jigsaw, "jointType");
|
||||
|
||||
BlockFace front = faceOf(frontFacing(blockState));
|
||||
BlockFace top = faceOf(topFacing(blockState));
|
||||
Optional<ResourceId> pool = poolId == null || poolId.isEmpty() ? Optional.empty() : Optional.of(ResourceId.parse(poolId));
|
||||
ConnectorMetadata metadata = readConnectorMetadata(jigsaw, info);
|
||||
boolean aligned = jointType != null && jointType.toString().toUpperCase(Locale.ROOT).contains("ALIGN");
|
||||
return new TemplatePool.JigsawConnector(
|
||||
position,
|
||||
front,
|
||||
top,
|
||||
pool,
|
||||
name,
|
||||
target,
|
||||
aligned,
|
||||
metadata.finalState(),
|
||||
metadata.selectionPriority(),
|
||||
metadata.placementPriority());
|
||||
}
|
||||
|
||||
static ConnectorMetadata readConnectorMetadata(Object jigsaw, Object info) throws Exception {
|
||||
String finalState = readNbtString(ServerReflection.invoke(info, "nbt"), FINAL_STATE_NBT_KEY);
|
||||
return new ConnectorMetadata(
|
||||
finalState == null || finalState.isBlank() ? Optional.empty() : Optional.of(finalState),
|
||||
readIntAccessor(jigsaw, "selectionPriority"),
|
||||
readIntAccessor(jigsaw, "placementPriority"));
|
||||
}
|
||||
|
||||
record ConnectorMetadata(Optional<String> finalState, int selectionPriority, int placementPriority) {
|
||||
}
|
||||
|
||||
static BlockFace faceOf(String facing) {
|
||||
return switch (facing) {
|
||||
case "up" -> BlockFace.UP;
|
||||
case "down" -> BlockFace.DOWN;
|
||||
case "south" -> BlockFace.SOUTH;
|
||||
case "east" -> BlockFace.EAST;
|
||||
case "west" -> BlockFace.WEST;
|
||||
default -> BlockFace.NORTH;
|
||||
};
|
||||
}
|
||||
|
||||
private static String readNbtString(Object nbt, String key) throws Exception {
|
||||
if (nbt == null) {
|
||||
return null;
|
||||
}
|
||||
Method method = ServerReflection.findMethod(nbt.getClass(), "getString", 1);
|
||||
if (method == null) {
|
||||
throw new NoSuchMethodException("getString(String) on " + nbt.getClass().getName());
|
||||
}
|
||||
method.setAccessible(true);
|
||||
Object value = method.invoke(nbt, key);
|
||||
if (value instanceof String string) {
|
||||
return string;
|
||||
}
|
||||
if (value instanceof Optional<?> optional) {
|
||||
return optional.isPresent() ? String.valueOf(optional.get()) : null;
|
||||
}
|
||||
return value == null ? null : String.valueOf(value);
|
||||
}
|
||||
|
||||
private static int readIntAccessor(Object value, String accessor) throws Exception {
|
||||
Method method = ServerReflection.findMethod(value.getClass(), accessor);
|
||||
if (method == null) {
|
||||
throw new NoSuchMethodException(accessor + "() on " + value.getClass().getName());
|
||||
}
|
||||
method.setAccessible(true);
|
||||
Object result = method.invoke(value);
|
||||
if (result instanceof Number number) {
|
||||
return number.intValue();
|
||||
}
|
||||
throw new IllegalStateException(accessor + " on " + value.getClass().getName() + " is not numeric");
|
||||
}
|
||||
|
||||
private static String frontFacing(Object blockState) throws Exception {
|
||||
return facing(blockState, "getFrontFacing", DEFAULT_FRONT);
|
||||
}
|
||||
|
||||
private static String topFacing(Object blockState) throws Exception {
|
||||
return facing(blockState, "getTopFacing", DEFAULT_TOP);
|
||||
}
|
||||
|
||||
private static String facing(Object blockState, String jigsawBlockMethod, String fallback) throws Exception {
|
||||
Class<?> jigsawBlock = Class.forName("net.minecraft.world.level.block.JigsawBlock");
|
||||
Method read = jigsawBlock.getMethod(jigsawBlockMethod, Class.forName("net.minecraft.world.level.block.state.BlockState"));
|
||||
Object direction = read.invoke(null, blockState);
|
||||
if (direction == null) {
|
||||
return fallback;
|
||||
}
|
||||
Method getName = direction.getClass().getMethod("getName");
|
||||
getName.setAccessible(true);
|
||||
return String.valueOf(getName.invoke(direction)).toLowerCase();
|
||||
}
|
||||
|
||||
private static String templateLocationOf(Object element) throws Exception {
|
||||
Method m = ServerReflection.findMethod(element.getClass(), "getTemplateLocation");
|
||||
if (m == null) {
|
||||
return null;
|
||||
}
|
||||
m.setAccessible(true);
|
||||
Object id = m.invoke(element);
|
||||
return ServerReflection.identifierString(id);
|
||||
}
|
||||
|
||||
static PoolElementResolution resolvePoolElement(Object element) throws Exception {
|
||||
if (element == null) {
|
||||
return new PoolElementResolution(null, null, 0, 0);
|
||||
}
|
||||
if (!element.getClass().getSimpleName().endsWith(LIST_POOL_ELEMENT_SUFFIX)) {
|
||||
return new PoolElementResolution(element, templateLocationOf(element), 0, 0);
|
||||
}
|
||||
Object rawElements = ServerReflection.invoke(element, "getElements");
|
||||
if (!(rawElements instanceof List<?> elements)) {
|
||||
throw new IllegalStateException("getElements on " + element.getClass().getName() + " is not a list");
|
||||
}
|
||||
if (elements.isEmpty()) {
|
||||
return new PoolElementResolution(null, null, 1, 0);
|
||||
}
|
||||
PoolElementResolution primary = resolvePoolElement(elements.getFirst());
|
||||
return new PoolElementResolution(
|
||||
primary.physicalElement(),
|
||||
primary.templateLocation(),
|
||||
primary.listLevels() + 1,
|
||||
primary.omittedElements() + elements.size() - 1
|
||||
);
|
||||
}
|
||||
|
||||
record PoolElementResolution(
|
||||
Object physicalElement,
|
||||
String templateLocation,
|
||||
int listLevels,
|
||||
int omittedElements
|
||||
) {
|
||||
}
|
||||
}
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.structure;
|
||||
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Reads the server's registries and resource manager by reflection, because they are version-bound server internals
|
||||
* that Paper's api does not reach. Every lookup finds its members by name, so a server version that renamed one fails the
|
||||
* read with the member's name instead of failing to link.
|
||||
*/
|
||||
final class ServerReflection {
|
||||
private ServerReflection() {
|
||||
}
|
||||
|
||||
/** The server's {@code MinecraftServer}. */
|
||||
static Object minecraftServer() throws Exception {
|
||||
Object craftServer = Bukkit.getServer();
|
||||
Object dedicated = invoke(craftServer, "getHandle");
|
||||
return invoke(dedicated, "getServer");
|
||||
}
|
||||
|
||||
static Object resolveRegistryAccess(Object server) {
|
||||
try {
|
||||
Class<?> frozen = Class.forName("net.minecraft.core.RegistryAccess$Frozen");
|
||||
for (Method m : server.getClass().getMethods()) {
|
||||
if (m.getParameterCount() == 0 && frozen.isAssignableFrom(m.getReturnType())) {
|
||||
m.setAccessible(true);
|
||||
Object o = m.invoke(server);
|
||||
if (o != null) {
|
||||
return o;
|
||||
}
|
||||
}
|
||||
}
|
||||
Class<?> ra = Class.forName("net.minecraft.core.RegistryAccess");
|
||||
for (Method m : server.getClass().getMethods()) {
|
||||
if (m.getParameterCount() == 0 && ra.isAssignableFrom(m.getReturnType())) {
|
||||
m.setAccessible(true);
|
||||
Object o = m.invoke(server);
|
||||
if (o != null) {
|
||||
return o;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static Object lookupRegistry(Object registryAccess, String registryName) throws Exception {
|
||||
Class<?> registries = Class.forName("net.minecraft.core.registries.Registries");
|
||||
Object resourceKey = registries.getField(registryName).get(null);
|
||||
Class<?> registryClass = Class.forName("net.minecraft.core.Registry");
|
||||
Method registryOverload = null;
|
||||
for (Method m : registryAccess.getClass().getMethods()) {
|
||||
if (m.getName().equals("lookupOrThrow") && m.getParameterCount() == 1
|
||||
&& m.getParameterTypes()[0].getName().endsWith("ResourceKey")
|
||||
&& registryClass.isAssignableFrom(m.getReturnType())) {
|
||||
registryOverload = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (registryOverload == null) {
|
||||
for (Method m : registryAccess.getClass().getMethods()) {
|
||||
if (m.getName().equals("lookupOrThrow") && m.getParameterCount() == 1
|
||||
&& m.getParameterTypes()[0].getName().endsWith("ResourceKey")) {
|
||||
registryOverload = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (registryOverload == null) {
|
||||
throw new NoSuchMethodException("lookupOrThrow(ResourceKey) on " + registryAccess.getClass().getName());
|
||||
}
|
||||
registryOverload.setAccessible(true);
|
||||
return registryOverload.invoke(registryAccess, resourceKey);
|
||||
}
|
||||
|
||||
static Object registryGet(Object registry, ResourceId key) throws Exception {
|
||||
Object id = identifierOf(key);
|
||||
for (Method m : registry.getClass().getMethods()) {
|
||||
if (m.getName().equals("getValue") && m.getParameterCount() == 1 && m.getParameterTypes()[0].getName().endsWith("Identifier")) {
|
||||
m.setAccessible(true);
|
||||
return m.invoke(registry, id);
|
||||
}
|
||||
}
|
||||
for (Method m : registry.getClass().getMethods()) {
|
||||
if (m.getName().equals("getOptional") && m.getParameterCount() == 1 && m.getParameterTypes()[0].getName().endsWith("Identifier")) {
|
||||
m.setAccessible(true);
|
||||
return unwrapOptional(m.invoke(registry, id));
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static String registryKeyOf(Object registry, Object value) throws Exception {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
for (Method m : registry.getClass().getMethods()) {
|
||||
if (m.getName().equals("getKey") && m.getParameterCount() == 1) {
|
||||
m.setAccessible(true);
|
||||
Object id = m.invoke(registry, value);
|
||||
String s = identifierString(id);
|
||||
if (s != null) {
|
||||
return s;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static Object identifierOf(ResourceId key) throws Exception {
|
||||
Class<?> identifier = Class.forName("net.minecraft.resources.Identifier");
|
||||
try {
|
||||
Method fromNamespaceAndPath = identifier.getMethod("fromNamespaceAndPath", String.class, String.class);
|
||||
return fromNamespaceAndPath.invoke(null, key.namespace(), key.path());
|
||||
} catch (NoSuchMethodException e) {
|
||||
Method withDefaultNamespace = identifier.getMethod("parse", String.class);
|
||||
return withDefaultNamespace.invoke(null, key.toString());
|
||||
}
|
||||
}
|
||||
|
||||
static String identifierString(Object id) {
|
||||
if (id == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Method getNamespace = id.getClass().getMethod("getNamespace");
|
||||
Method getPath = id.getClass().getMethod("getPath");
|
||||
getNamespace.setAccessible(true);
|
||||
getPath.setAccessible(true);
|
||||
return getNamespace.invoke(id) + ":" + getPath.invoke(id);
|
||||
} catch (Throwable e) {
|
||||
return id.toString();
|
||||
}
|
||||
}
|
||||
|
||||
static Object unwrapHolder(Object holder) {
|
||||
if (holder == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Method value = findMethod(holder.getClass(), "value");
|
||||
if (value != null) {
|
||||
value.setAccessible(true);
|
||||
return value.invoke(holder);
|
||||
}
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
return holder;
|
||||
}
|
||||
|
||||
static Object unwrapOptional(Object opt) {
|
||||
if (opt == null) {
|
||||
return null;
|
||||
}
|
||||
if (opt instanceof Optional<?> o) {
|
||||
return o.orElse(null);
|
||||
}
|
||||
return opt;
|
||||
}
|
||||
|
||||
static int readIntMember(Object value, String memberName) throws Exception {
|
||||
Class<?> type = value.getClass();
|
||||
while (type != null) {
|
||||
try {
|
||||
Field field = type.getDeclaredField(memberName);
|
||||
field.setAccessible(true);
|
||||
return coerceInt(field.get(value), memberName, value);
|
||||
} catch (NoSuchFieldException ignored) {
|
||||
type = type.getSuperclass();
|
||||
}
|
||||
}
|
||||
Method method = findMethod(value.getClass(), memberName);
|
||||
if (method != null) {
|
||||
method.setAccessible(true);
|
||||
return coerceInt(method.invoke(value), memberName, value);
|
||||
}
|
||||
throw new NoSuchFieldException(memberName + " on " + value.getClass().getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Members that are plain numbers on one server build are wrapper objects on another
|
||||
* (JigsawStructure.maxDistanceFromCenter became a MaxDistance{horizontal, vertical} record).
|
||||
* Numbers pass through; a wrapper contributes its horizontal component, else its largest
|
||||
* integral component, so a distance bound is never under-read.
|
||||
*/
|
||||
private static int coerceInt(Object member, String memberName, Object owner) throws Exception {
|
||||
if (member instanceof Number n) {
|
||||
return n.intValue();
|
||||
}
|
||||
if (member == null) {
|
||||
throw new NoSuchFieldException(memberName + " on " + owner.getClass().getName() + " is null");
|
||||
}
|
||||
Method horizontal = findMethod(member.getClass(), "horizontal");
|
||||
if (horizontal != null && Number.class.isAssignableFrom(boxedType(horizontal.getReturnType()))) {
|
||||
horizontal.setAccessible(true);
|
||||
return ((Number) horizontal.invoke(member)).intValue();
|
||||
}
|
||||
Integer widest = null;
|
||||
for (Field component : member.getClass().getDeclaredFields()) {
|
||||
if (Modifier.isStatic(component.getModifiers())
|
||||
|| !Number.class.isAssignableFrom(boxedType(component.getType()))) {
|
||||
continue;
|
||||
}
|
||||
component.setAccessible(true);
|
||||
Object componentValue = component.get(member);
|
||||
if (componentValue instanceof Number n && (widest == null || n.intValue() > widest)) {
|
||||
widest = n.intValue();
|
||||
}
|
||||
}
|
||||
if (widest != null) {
|
||||
return widest;
|
||||
}
|
||||
throw new NoSuchFieldException(memberName + " on " + owner.getClass().getName()
|
||||
+ " is a " + member.getClass().getName() + " with no integral component");
|
||||
}
|
||||
|
||||
private static Class<?> boxedType(Class<?> type) {
|
||||
return type == int.class ? Integer.class : type;
|
||||
}
|
||||
|
||||
static int readInt(Object o, String method) throws Exception {
|
||||
Method m = o.getClass().getMethod(method);
|
||||
m.setAccessible(true);
|
||||
return ((Number) m.invoke(o)).intValue();
|
||||
}
|
||||
|
||||
static Object staticField(String className, String fieldName) throws Exception {
|
||||
Class<?> c = Class.forName(className);
|
||||
Field f = c.getField(fieldName);
|
||||
return f.get(null);
|
||||
}
|
||||
|
||||
static Object invoke(Object target, String method) throws Exception {
|
||||
Method m = findMethod(target.getClass(), method);
|
||||
if (m == null) {
|
||||
throw new NoSuchMethodException(method + " on " + target.getClass().getName());
|
||||
}
|
||||
m.setAccessible(true);
|
||||
return m.invoke(target);
|
||||
}
|
||||
|
||||
static Method findMethod(Class<?> type, String name) {
|
||||
return findMethod(type, name, 0);
|
||||
}
|
||||
|
||||
static Method findMethod(Class<?> type, String name, int parameterCount) {
|
||||
Class<?> c = type;
|
||||
while (c != null) {
|
||||
for (Method m : c.getDeclaredMethods()) {
|
||||
if (m.getName().equals(name) && m.getParameterCount() == parameterCount) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
c = c.getSuperclass();
|
||||
}
|
||||
for (Method m : type.getMethods()) {
|
||||
if (m.getName().equals(name) && m.getParameterCount() == parameterCount) {
|
||||
return m;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static Object freshRandomSource(long seed) throws Exception {
|
||||
Class<?> randomSource = Class.forName("net.minecraft.util.RandomSource");
|
||||
Method create = randomSource.getMethod("create", long.class);
|
||||
return create.invoke(null, seed);
|
||||
}
|
||||
|
||||
/** The message a failed read shows: the failure's message, else its class name. */
|
||||
static String failureDetail(Throwable failure) {
|
||||
String message = failure.getMessage();
|
||||
return message == null || message.isBlank() ? failure.getClass().getSimpleName() : message;
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.modules.BlockEntities;
|
||||
import art.arcane.iris.engine.object.prefab.TileData;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.geometry.BlockFace;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.object.BlockEntityData;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/** Blocks, positions and block entities between the tool world api and Bukkit. */
|
||||
final class BukkitToolBlocks {
|
||||
private BukkitToolBlocks() {
|
||||
}
|
||||
|
||||
static BlockPosition positionOf(Block block) {
|
||||
return new BlockPosition(block.getX(), block.getY(), block.getZ());
|
||||
}
|
||||
|
||||
static BlockPosition positionOf(Location location) {
|
||||
return new BlockPosition(location.getBlockX(), location.getBlockY(), location.getBlockZ());
|
||||
}
|
||||
|
||||
static Block blockAt(World world, BlockPosition at) {
|
||||
return world.getBlockAt(at.x(), at.y(), at.z());
|
||||
}
|
||||
|
||||
/** The complete state of {@code data}, with every property. */
|
||||
static BlockState stateOf(BlockData data) {
|
||||
return BlockState.parse(data.getAsString());
|
||||
}
|
||||
|
||||
/**
|
||||
* The platform's data for {@code state}.
|
||||
*
|
||||
* @throws IllegalArgumentException when the platform has no such block or property
|
||||
*/
|
||||
static BlockData dataOf(BlockState state) {
|
||||
return Bukkit.createBlockData(state.key());
|
||||
}
|
||||
|
||||
/** The block entity of {@code block}; empty for a block without one. */
|
||||
static Optional<BlockEntityData> blockEntityOf(Block block) {
|
||||
return Optional.ofNullable(TileData.getTileState(block, false)).map(BlockEntities::of);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes {@code data} into the block entity of {@code block}, which must already be the block it was made for.
|
||||
*
|
||||
* @throws IllegalArgumentException when the block cannot take it, or the data is not in the format Iris stores
|
||||
*/
|
||||
static void applyBlockEntity(Block block, BlockEntityData data) {
|
||||
TileData tile = BlockEntities.tileOf(data);
|
||||
if (!TileData.setTileState(block, tile)) {
|
||||
throw new IllegalArgumentException("The block " + block.getType() + " at " + block.getX() + ", " + block.getY()
|
||||
+ ", " + block.getZ() + " cannot take block entity data of " + tile.getMaterialKey());
|
||||
}
|
||||
}
|
||||
|
||||
/** The api face for a Bukkit face; empty for the diagonals and for {@code SELF}. */
|
||||
static Optional<BlockFace> faceOf(org.bukkit.block.BlockFace face) {
|
||||
if (face == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return switch (face) {
|
||||
case UP -> Optional.of(BlockFace.UP);
|
||||
case DOWN -> Optional.of(BlockFace.DOWN);
|
||||
case NORTH -> Optional.of(BlockFace.NORTH);
|
||||
case SOUTH -> Optional.of(BlockFace.SOUTH);
|
||||
case EAST -> Optional.of(BlockFace.EAST);
|
||||
case WEST -> Optional.of(BlockFace.WEST);
|
||||
default -> Optional.empty();
|
||||
};
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.tooling.world.ToolItem;
|
||||
import com.volmit.tooling.world.ToolText;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataContainer;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* {@link ToolItem}s as Bukkit item stacks. The payload is a string in the item's persistent data; its presence is what
|
||||
* makes a stack a tool item, so an empty payload is stored as an empty string.
|
||||
*/
|
||||
final class BukkitToolItems {
|
||||
static final NamespacedKey PAYLOAD_KEY = new NamespacedKey("iris", "tool_payload");
|
||||
|
||||
private BukkitToolItems() {
|
||||
}
|
||||
|
||||
/**
|
||||
* A new stack of {@code item}. The name and lore are set as legacy strings, the way a plugin sets text on an item
|
||||
* with the platform's own calls, so the stack shows what such a stack always showed.
|
||||
*/
|
||||
@SuppressWarnings("deprecation")
|
||||
static ItemStack create(ToolItem item) {
|
||||
Material material = Material.matchMaterial(item.item().toString());
|
||||
if (material == null || !material.isItem()) {
|
||||
throw new IllegalArgumentException("The platform has no item " + item.item());
|
||||
}
|
||||
ItemStack stack = new ItemStack(material);
|
||||
ItemMeta meta = stack.getItemMeta();
|
||||
if (meta == null) {
|
||||
throw new IllegalStateException("The item " + item.item() + " cannot carry a name or a payload");
|
||||
}
|
||||
if (!item.name().isEmpty()) {
|
||||
meta.setDisplayName(BukkitToolText.legacy(item.name()));
|
||||
}
|
||||
if (!item.lore().isEmpty()) {
|
||||
meta.setLore(item.lore().stream().map(BukkitToolText::legacy).toList());
|
||||
}
|
||||
if (item.glowing()) {
|
||||
meta.setEnchantmentGlintOverride(true);
|
||||
}
|
||||
meta.getPersistentDataContainer().set(PAYLOAD_KEY, PersistentDataType.STRING, item.payload());
|
||||
if (!stack.setItemMeta(meta)) {
|
||||
throw new IllegalStateException("The metadata of tool item " + item.item() + " was rejected");
|
||||
}
|
||||
return stack;
|
||||
}
|
||||
|
||||
/** The tool item {@code stack} is; empty for nothing, air or a stack without the tool payload. */
|
||||
static Optional<ToolItem> read(ItemStack stack) {
|
||||
if (stack == null || stack.getType() == Material.AIR || !stack.hasItemMeta()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
ItemMeta meta = stack.getItemMeta();
|
||||
if (meta == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
PersistentDataContainer data = meta.getPersistentDataContainer();
|
||||
String payload = data.get(PAYLOAD_KEY, PersistentDataType.STRING);
|
||||
if (payload == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new ToolItem(
|
||||
ResourceId.parse(stack.getType().getKey().toString()),
|
||||
meta.hasDisplayName() ? plainText(meta.displayName()) : ToolText.EMPTY,
|
||||
meta.hasLore() ? lore(meta) : List.of(),
|
||||
Boolean.TRUE.equals(meta.getEnchantmentGlintOverride()),
|
||||
payload));
|
||||
}
|
||||
|
||||
private static List<ToolText> lore(ItemMeta meta) {
|
||||
List<Component> lines = meta.lore();
|
||||
return lines == null ? List.of() : lines.stream().map(BukkitToolItems::plainText).toList();
|
||||
}
|
||||
|
||||
private static ToolText plainText(Component component) {
|
||||
return component == null ? ToolText.EMPTY : ToolText.plain(PlainTextComponentSerializer.plainText().serialize(component));
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import art.arcane.volmlib.util.data.MaterialBlock;
|
||||
import art.arcane.volmlib.util.inventorygui.UIElement;
|
||||
import art.arcane.volmlib.util.inventorygui.UIPaneDecorator;
|
||||
import art.arcane.volmlib.util.inventorygui.UIWindow;
|
||||
import art.arcane.volmlib.util.inventorygui.WindowResolution;
|
||||
import com.volmit.tooling.world.MenuButton;
|
||||
import com.volmit.tooling.world.MenuClick;
|
||||
import com.volmit.tooling.world.ToolItem;
|
||||
import com.volmit.tooling.world.ToolMenu;
|
||||
import com.volmit.tooling.world.ToolText;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/** The chest menus tools open for players, as VolmLib inventory windows. */
|
||||
final class BukkitToolMenus {
|
||||
private static final int MAX_TITLE_LENGTH = 32;
|
||||
private static final int SLOTS_PER_ROW = ToolMenu.SLOTS_PER_ROW;
|
||||
private static final int CENTER_SLOT_OFFSET = SLOTS_PER_ROW / 2;
|
||||
|
||||
private final Map<UUID, OpenMenu> windows = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* The window a player has open and what it was opened with. A menu with the rows and title of the open one fills the
|
||||
* same window, as a page of buttons changing under the player's cursor; the close handler is the latest menu's.
|
||||
*/
|
||||
private static final class OpenMenu {
|
||||
private final UIWindow window;
|
||||
private final int rows;
|
||||
private final String title;
|
||||
private volatile Runnable onClose;
|
||||
|
||||
private OpenMenu(UIWindow window, int rows, String title, Runnable onClose) {
|
||||
this.window = window;
|
||||
this.rows = rows;
|
||||
this.title = title;
|
||||
this.onClose = onClose;
|
||||
}
|
||||
|
||||
private boolean showsSameFrame(ToolMenu menu) {
|
||||
return rows == menu.rows() && title.equals(shortened(menu.title()));
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens {@code menu} for {@code viewer}, replacing the one they had. Runs on the viewer's thread. */
|
||||
void open(BukkitToolPlayer viewer, ToolMenu menu) {
|
||||
Player player = viewer.bukkit();
|
||||
OpenMenu open = windows.get(player.getUniqueId());
|
||||
if (open != null && open.showsSameFrame(menu)) {
|
||||
fill(open, viewer, menu);
|
||||
return;
|
||||
}
|
||||
close(player);
|
||||
UUID playerId = player.getUniqueId();
|
||||
UIWindow window = new UIWindow(BukkitPlatform.volmitPlugin(), player);
|
||||
OpenMenu created = new OpenMenu(window, menu.rows(), shortened(menu.title()), menu.onClose());
|
||||
window.setResolution(WindowResolution.W9_H6);
|
||||
window.setViewportHeight(menu.rows());
|
||||
window.setDecorator(new UIPaneDecorator(Material.BLACK_STAINED_GLASS_PANE));
|
||||
window.setTitle(created.title);
|
||||
window.onClosed(closed -> {
|
||||
windows.remove(playerId, created);
|
||||
runGuarded(created.onClose, "menu close handler of " + player.getName());
|
||||
});
|
||||
window.batch(() -> addButtons(window, viewer, menu));
|
||||
windows.put(playerId, created);
|
||||
window.open();
|
||||
}
|
||||
|
||||
/** Puts the buttons of {@code menu} in the window {@code open} holds, telling the menu it replaces that it closed. */
|
||||
private void fill(OpenMenu open, BukkitToolPlayer viewer, ToolMenu menu) {
|
||||
Runnable replaced = open.onClose;
|
||||
open.onClose = menu.onClose();
|
||||
open.window.batch(() -> {
|
||||
open.window.clearElements();
|
||||
addButtons(open.window, viewer, menu);
|
||||
});
|
||||
runGuarded(replaced, "menu close handler of " + viewer.name());
|
||||
}
|
||||
|
||||
private static void addButtons(UIWindow window, BukkitToolPlayer viewer, ToolMenu menu) {
|
||||
for (MenuButton button : menu.buttons()) {
|
||||
window.setElement(positionOf(button.slot()), button.slot() / SLOTS_PER_ROW, element(viewer, button));
|
||||
}
|
||||
}
|
||||
|
||||
/** Closes the player's menu; does nothing when none is open. Runs on the player's thread. */
|
||||
void close(Player player) {
|
||||
OpenMenu open = windows.remove(player.getUniqueId());
|
||||
if (open != null) {
|
||||
open.window.close();
|
||||
}
|
||||
}
|
||||
|
||||
void forget(UUID playerId) {
|
||||
windows.remove(playerId);
|
||||
}
|
||||
|
||||
private static UIElement element(BukkitToolPlayer viewer, MenuButton button) {
|
||||
ToolItem icon = button.icon();
|
||||
Material material = Material.matchMaterial(icon.item().toString());
|
||||
if (material == null || !material.isItem()) {
|
||||
throw new IllegalArgumentException("The platform has no item " + icon.item());
|
||||
}
|
||||
UIElement element = new UIElement("slot-" + button.slot())
|
||||
.setMaterial(new MaterialBlock(material))
|
||||
.setName(BukkitToolText.legacy(icon.name()))
|
||||
.setEnchanted(icon.glowing());
|
||||
icon.lore().forEach(line -> element.addLore(BukkitToolText.legacy(line)));
|
||||
element.onLeftClick(clicked -> click(viewer, button, false, false));
|
||||
element.onRightClick(clicked -> click(viewer, button, true, false));
|
||||
element.onShiftLeftClick(clicked -> click(viewer, button, false, true));
|
||||
element.onShiftRightClick(clicked -> click(viewer, button, true, true));
|
||||
element.onMiddleClick(clicked -> runGuarded(
|
||||
() -> button.action().accept(new MenuClick(viewer, false, false, true)),
|
||||
"menu button of " + viewer.name()));
|
||||
return element;
|
||||
}
|
||||
|
||||
private static void click(BukkitToolPlayer viewer, MenuButton button, boolean right, boolean shift) {
|
||||
runGuarded(() -> button.action().accept(new MenuClick(viewer, right, shift)), "menu button of " + viewer.name());
|
||||
}
|
||||
|
||||
/** The window counts positions from its middle column, left of it negative; a slot counts from the left. */
|
||||
static int positionOf(int slot) {
|
||||
return slot % SLOTS_PER_ROW - CENTER_SLOT_OFFSET;
|
||||
}
|
||||
|
||||
/** The title in the legacy codes the window takes, cut to what it can show without leaving half a code. */
|
||||
static String shortened(ToolText title) {
|
||||
String legacy = BukkitToolText.legacy(title);
|
||||
if (legacy.length() <= MAX_TITLE_LENGTH) {
|
||||
return legacy;
|
||||
}
|
||||
String cut = legacy.substring(0, MAX_TITLE_LENGTH);
|
||||
return cut.endsWith("§") ? cut.substring(0, MAX_TITLE_LENGTH - 1) : cut;
|
||||
}
|
||||
|
||||
private static void runGuarded(Runnable task, String what) {
|
||||
try {
|
||||
task.run();
|
||||
} catch (RuntimeException failure) {
|
||||
IrisLogging.reportError("A tool failed in the " + what + ".", failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
+253
@@ -0,0 +1,253 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.service.BoardSVC;
|
||||
import art.arcane.iris.core.service.BukkitToolingSender;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.spi.IrisServices;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import art.arcane.volmlib.util.plugin.ComponentMessenger;
|
||||
import art.arcane.volmlib.util.plugin.ComponentText;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.resource.ResourceId;
|
||||
import com.volmit.tooling.Sender;
|
||||
import com.volmit.tooling.world.Particle;
|
||||
import com.volmit.tooling.world.ToolItem;
|
||||
import com.volmit.tooling.world.ToolMenu;
|
||||
import com.volmit.tooling.world.ToolPlayer;
|
||||
import com.volmit.tooling.world.ToolText;
|
||||
import com.volmit.tooling.world.ToolWorld;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Color;
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/** A Bukkit player as a tool sees them. Readers must run on the player's thread; changes hop there by themselves. */
|
||||
final class BukkitToolPlayer implements ToolPlayer {
|
||||
private final Player player;
|
||||
private final OpenToolWorlds worlds;
|
||||
private final ToolPlayers players;
|
||||
private final BukkitToolMenus menus;
|
||||
|
||||
BukkitToolPlayer(Player player, OpenToolWorlds worlds, ToolPlayers players, BukkitToolMenus menus) {
|
||||
this.player = player;
|
||||
this.worlds = worlds;
|
||||
this.players = players;
|
||||
this.menus = menus;
|
||||
}
|
||||
|
||||
Player bukkit() {
|
||||
return player;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UUID id() {
|
||||
return player.getUniqueId();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return player.getName();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Sender sender() {
|
||||
return new BukkitToolingSender(player);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ToolWorld> world() {
|
||||
return worlds.forWorld(player.getWorld()).map(world -> world);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockPosition position() {
|
||||
return BukkitToolBlocks.positionOf(player.getLocation());
|
||||
}
|
||||
|
||||
@Override
|
||||
public float yaw() {
|
||||
return player.getLocation().getYaw();
|
||||
}
|
||||
|
||||
@Override
|
||||
public float pitch() {
|
||||
return player.getLocation().getPitch();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<BlockPosition> targetBlock(int maxDistance) {
|
||||
return Optional.ofNullable(player.getTargetBlockExact(maxDistance)).map(BukkitToolBlocks::positionOf);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean sneaking() {
|
||||
return player.isSneaking();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(Runnable task) {
|
||||
J.runEntity(player, task);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Boolean> teleport(ToolWorld world, double x, double y, double z, float yaw, float pitch) {
|
||||
if (!(world instanceof BukkitToolWorld target)) {
|
||||
return CompletableFuture.failedFuture(new IllegalArgumentException("Not a tool world of this platform: " + world));
|
||||
}
|
||||
CompletableFuture<Boolean> arrived = new CompletableFuture<>();
|
||||
boolean scheduled = J.runEntity(player, () -> BukkitPlatform
|
||||
.teleportAsync(player, new Location(target.bukkit(), x, y, z, yaw, pitch))
|
||||
.whenComplete((success, failure) -> {
|
||||
if (failure != null) {
|
||||
arrived.completeExceptionally(failure);
|
||||
} else {
|
||||
arrived.complete(Boolean.TRUE.equals(success));
|
||||
}
|
||||
}));
|
||||
if (!scheduled) {
|
||||
arrived.complete(false);
|
||||
}
|
||||
return arrived;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void creative(boolean on) {
|
||||
J.runEntity(player, () -> {
|
||||
if (on) {
|
||||
players.rememberModeBeforeCreative(player);
|
||||
player.setGameMode(GameMode.CREATIVE);
|
||||
return;
|
||||
}
|
||||
players.restoreGameMode(player);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void message(ToolText text) {
|
||||
J.runEntity(player, () -> ComponentMessenger.send(player, ComponentText.component(BukkitToolText.component(text))));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void actionBar(ToolText text) {
|
||||
J.runEntity(player, () -> player.sendActionBar(BukkitToolText.component(text)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sound(ResourceId sound, float volume, float pitch) {
|
||||
J.runEntity(player, () -> player.playSound(player.getLocation(), sound.toString(), volume, pitch));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sidebar(ToolText title, List<ToolText> lines) {
|
||||
BoardSVC board = IrisServices.getOrNull(BoardSVC.class);
|
||||
if (board == null) {
|
||||
return;
|
||||
}
|
||||
J.runEntity(player, () -> board.applyToolSidebar(player,
|
||||
new BoardSVC.ToolSidebar(player.getWorld().getUID(), title, lines)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void hideSidebar() {
|
||||
BoardSVC board = IrisServices.getOrNull(BoardSVC.class);
|
||||
if (board != null) {
|
||||
board.clearToolSidebar(player);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void particles(List<Particle> dust) {
|
||||
List<Particle> specks = List.copyOf(dust);
|
||||
J.runEntity(player, () -> specks.forEach(this::showDust));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean give(ToolItem item) {
|
||||
ItemStack stack = BukkitToolItems.create(item);
|
||||
if (J.isOwnedByCurrentRegion(player)) {
|
||||
return player.getInventory().addItem(stack).isEmpty();
|
||||
}
|
||||
J.runEntity(player, () -> player.getInventory().addItem(stack));
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ToolItem> held() {
|
||||
return BukkitToolItems.read(player.getInventory().getItemInMainHand());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void openMenu(ToolMenu menu) {
|
||||
J.runEntity(player, () -> menus.open(this, menu));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void closeMenu() {
|
||||
J.runEntity(player, () -> menus.close(player));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the player to where they were before they entered a tool world, or to the spawn of the main world when that
|
||||
* is not known any more, and gives back the game mode they had. Completes with whether they arrived.
|
||||
*/
|
||||
CompletableFuture<Boolean> returnToOrigin() {
|
||||
CompletableFuture<Boolean> returned = new CompletableFuture<>();
|
||||
boolean scheduled = J.runEntity(player, () -> {
|
||||
menus.close(player);
|
||||
players.restoreGameMode(player);
|
||||
Location destination = players.takeOrigin(player)
|
||||
.filter(this::isOutsideToolWorlds)
|
||||
.orElseGet(() -> Bukkit.getWorlds().getFirst().getSpawnLocation());
|
||||
BukkitPlatform.teleportAsync(player, destination).whenComplete((success, failure) -> {
|
||||
if (failure != null) {
|
||||
returned.completeExceptionally(failure);
|
||||
} else {
|
||||
returned.complete(Boolean.TRUE.equals(success));
|
||||
}
|
||||
});
|
||||
});
|
||||
if (!scheduled) {
|
||||
returned.complete(false);
|
||||
}
|
||||
return returned;
|
||||
}
|
||||
|
||||
private boolean isOutsideToolWorlds(Location location) {
|
||||
return location.getWorld() != null && worlds.forWorld(location.getWorld()).isEmpty();
|
||||
}
|
||||
|
||||
private void showDust(Particle speck) {
|
||||
org.bukkit.Particle.DustOptions options = new org.bukkit.Particle.DustOptions(Color.fromRGB(speck.rgb()), speck.size());
|
||||
player.spawnParticle(org.bukkit.Particle.DUST, speck.x(), speck.y(), speck.z(), 1, 0.0D, 0.0D, 0.0D, 0.0D, options);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "tool player " + player.getName();
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import com.volmit.tooling.world.TextColor;
|
||||
import com.volmit.tooling.world.ToolText;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import net.kyori.adventure.text.format.TextDecoration;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** {@link ToolText} as the text Bukkit shows: an Adventure component, or the legacy string the platform's older calls take. */
|
||||
final class BukkitToolText {
|
||||
private static final char SECTION = '§';
|
||||
private static final Map<TextColor, NamedTextColor> COLORS = new EnumMap<>(Map.ofEntries(
|
||||
Map.entry(TextColor.BLACK, NamedTextColor.BLACK),
|
||||
Map.entry(TextColor.DARK_BLUE, NamedTextColor.DARK_BLUE),
|
||||
Map.entry(TextColor.DARK_GREEN, NamedTextColor.DARK_GREEN),
|
||||
Map.entry(TextColor.DARK_AQUA, NamedTextColor.DARK_AQUA),
|
||||
Map.entry(TextColor.DARK_RED, NamedTextColor.DARK_RED),
|
||||
Map.entry(TextColor.DARK_PURPLE, NamedTextColor.DARK_PURPLE),
|
||||
Map.entry(TextColor.GOLD, NamedTextColor.GOLD),
|
||||
Map.entry(TextColor.GRAY, NamedTextColor.GRAY),
|
||||
Map.entry(TextColor.DARK_GRAY, NamedTextColor.DARK_GRAY),
|
||||
Map.entry(TextColor.BLUE, NamedTextColor.BLUE),
|
||||
Map.entry(TextColor.GREEN, NamedTextColor.GREEN),
|
||||
Map.entry(TextColor.AQUA, NamedTextColor.AQUA),
|
||||
Map.entry(TextColor.RED, NamedTextColor.RED),
|
||||
Map.entry(TextColor.LIGHT_PURPLE, NamedTextColor.LIGHT_PURPLE),
|
||||
Map.entry(TextColor.YELLOW, NamedTextColor.YELLOW),
|
||||
Map.entry(TextColor.WHITE, NamedTextColor.WHITE)));
|
||||
|
||||
private BukkitToolText() {
|
||||
}
|
||||
|
||||
static Component component(ToolText text) {
|
||||
TextComponent.Builder whole = Component.text();
|
||||
for (ToolText.Span span : text.spans()) {
|
||||
Component piece = Component.text(span.text());
|
||||
if (span.color() != null) {
|
||||
piece = piece.color(COLORS.get(span.color()));
|
||||
}
|
||||
piece = piece
|
||||
.decoration(TextDecoration.BOLD, span.bold() ? TextDecoration.State.TRUE : TextDecoration.State.NOT_SET)
|
||||
.decoration(TextDecoration.ITALIC, span.italic() ? TextDecoration.State.TRUE : TextDecoration.State.NOT_SET)
|
||||
.decoration(TextDecoration.STRIKETHROUGH,
|
||||
span.strikethrough() ? TextDecoration.State.TRUE : TextDecoration.State.NOT_SET);
|
||||
whole.append(piece);
|
||||
}
|
||||
return whole.build();
|
||||
}
|
||||
|
||||
/** The legacy string of {@code text}: formatting signs for the colour and style of each span, a reset between uncoloured ones. */
|
||||
static String legacy(ToolText text) {
|
||||
StringBuilder legacy = new StringBuilder();
|
||||
for (ToolText.Span span : text.spans()) {
|
||||
if (span.color() != null) {
|
||||
legacy.append(SECTION).append(span.color().code());
|
||||
} else if (!legacy.isEmpty()) {
|
||||
legacy.append(SECTION).append('r');
|
||||
}
|
||||
if (span.bold()) {
|
||||
legacy.append(SECTION).append('l');
|
||||
}
|
||||
if (span.italic()) {
|
||||
legacy.append(SECTION).append('o');
|
||||
}
|
||||
if (span.strikethrough()) {
|
||||
legacy.append(SECTION).append('m');
|
||||
}
|
||||
legacy.append(span.text());
|
||||
}
|
||||
return legacy.toString();
|
||||
}
|
||||
}
|
||||
+408
@@ -0,0 +1,408 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.nms.INMS;
|
||||
import art.arcane.iris.core.project.IrisProject;
|
||||
import art.arcane.iris.core.runtime.InPlaceChunkRegenerator;
|
||||
import art.arcane.iris.core.runtime.StudioOpenCoordinator;
|
||||
import art.arcane.iris.core.runtime.StudioPainterSlots;
|
||||
import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity;
|
||||
import art.arcane.iris.core.runtime.StudioSlotOccupant;
|
||||
import art.arcane.iris.core.service.StudioSVC;
|
||||
import art.arcane.iris.engine.data.chunk.TerrainChunk;
|
||||
import art.arcane.iris.engine.platform.studio.TerrainChunkCanvas;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.IrisServices;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.geometry.ChunkPos;
|
||||
import com.volmit.object.BlockEntityData;
|
||||
import com.volmit.tooling.world.ToolPlayer;
|
||||
import com.volmit.tooling.world.ToolWorld;
|
||||
import com.volmit.tooling.world.ToolWorldListener;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Chunk;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* One tool world on Bukkit: a studio world whose chunks come from the tool's painter. It exists, registered, from before
|
||||
* Bukkit creates the world until the world is unloaded; {@link #bind} gives it the Bukkit world once that exists.
|
||||
*/
|
||||
final class BukkitToolWorld implements ToolWorld, StudioSlotOccupant {
|
||||
private static final int CHUNK_SHIFT = 4;
|
||||
|
||||
private final String packName;
|
||||
private final String name;
|
||||
private final String storageName;
|
||||
private final ToolWorldListener listener;
|
||||
private final StudioPainterSlots.Slot slot;
|
||||
private final PendingBlockEntities pending;
|
||||
private final ToolWorldPresence presence = new ToolWorldPresence();
|
||||
private final OpenToolWorlds registry;
|
||||
private final ToolPlayers players;
|
||||
private final AtomicBoolean closing = new AtomicBoolean();
|
||||
private final AtomicBoolean gone = new AtomicBoolean();
|
||||
private final CompletableFuture<Void> closed = new CompletableFuture<>();
|
||||
private final IrisProject project;
|
||||
private volatile World world;
|
||||
|
||||
BukkitToolWorld(
|
||||
String packName,
|
||||
String name,
|
||||
String storageName,
|
||||
ToolWorldListener listener,
|
||||
StudioPainterSlots.Slot slot,
|
||||
PendingBlockEntities pending,
|
||||
OpenToolWorlds registry,
|
||||
ToolPlayers players
|
||||
) {
|
||||
this.packName = packName;
|
||||
this.name = name;
|
||||
this.storageName = storageName;
|
||||
this.listener = listener;
|
||||
this.slot = slot;
|
||||
this.pending = pending;
|
||||
this.registry = registry;
|
||||
this.players = players;
|
||||
this.project = new IrisProject(new File(workspaceFolder(), packName));
|
||||
}
|
||||
|
||||
/** The studio project this world is, as the studio service shows the open studio to its commands. */
|
||||
@Override
|
||||
public IrisProject project() {
|
||||
return project;
|
||||
}
|
||||
|
||||
private static File workspaceFolder() {
|
||||
StudioSVC studios = IrisServices.getOrNull(StudioSVC.class);
|
||||
return studios == null ? new File(".") : studios.getWorkspaceFolder();
|
||||
}
|
||||
|
||||
String packName() {
|
||||
return packName;
|
||||
}
|
||||
|
||||
/** The logical name of the world's storage, which the generator finds its painter by. */
|
||||
String storageName() {
|
||||
return storageName;
|
||||
}
|
||||
|
||||
/** Gives the world its Bukkit world, once Bukkit has created it. */
|
||||
void bind(World created) {
|
||||
world = Objects.requireNonNull(created, "created");
|
||||
registry.bound(this);
|
||||
}
|
||||
|
||||
boolean isBound() {
|
||||
return world != null;
|
||||
}
|
||||
|
||||
UUID worldId() {
|
||||
return bukkit().getUID();
|
||||
}
|
||||
|
||||
World bukkit() {
|
||||
World bound = world;
|
||||
if (bound == null) {
|
||||
throw new IllegalStateException("The tool world " + name + " is not created yet");
|
||||
}
|
||||
return bound;
|
||||
}
|
||||
|
||||
ToolWorldPresence presence() {
|
||||
return presence;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int minY() {
|
||||
return bukkit().getMinHeight();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int maxY() {
|
||||
return bukkit().getMaxHeight();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ToolPlayer> players() {
|
||||
return bukkit().getPlayers().stream().<ToolPlayer>map(players::of).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean owns(BlockPosition at) {
|
||||
return J.isOwnedByCurrentRegion(bukkit(), at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(BlockPosition at, Runnable task) {
|
||||
World target = bukkit();
|
||||
Runnable guarded = () -> runGuarded(task, "task at " + at);
|
||||
if (!J.runRegion(target, at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT, guarded)) {
|
||||
IrisLogging.warn("Tool world %s could not schedule a task at %s.", name, at);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> CompletableFuture<T> call(BlockPosition at, Supplier<T> task) {
|
||||
CompletableFuture<T> result = new CompletableFuture<>();
|
||||
boolean scheduled = J.runRegion(bukkit(), at.x() >> CHUNK_SHIFT, at.z() >> CHUNK_SHIFT, () -> {
|
||||
try {
|
||||
result.complete(task.get());
|
||||
} catch (Throwable failure) {
|
||||
result.completeExceptionally(failure);
|
||||
}
|
||||
});
|
||||
if (!scheduled) {
|
||||
result.completeExceptionally(new IllegalStateException("Tool world " + name + " could not schedule a task at " + at));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BlockState block(BlockPosition at) {
|
||||
return BukkitToolBlocks.stateOf(ownedBlock(at).getBlockData());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<BlockEntityData> blockEntity(BlockPosition at) {
|
||||
return BukkitToolBlocks.blockEntityOf(ownedBlock(at));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBlock(BlockPosition at, BlockState state, Optional<BlockEntityData> data) {
|
||||
Block block = ownedBlock(at);
|
||||
block.setBlockData(BukkitToolBlocks.dataOf(state), false);
|
||||
data.ifPresent(entity -> BukkitToolBlocks.applyBlockEntity(block, entity));
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean loaded(ChunkPos chunk) {
|
||||
return bukkit().isChunkLoaded(chunk.x(), chunk.z());
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> repaint(Collection<ChunkPos> chunks) {
|
||||
if (isClosed()) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException("Tool world " + name + " is closed"));
|
||||
}
|
||||
List<CompletableFuture<Void>> repaints = chunks.stream().distinct().map(this::repaintChunk).toList();
|
||||
return CompletableFuture.allOf(repaints.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> close() {
|
||||
if (!closing.compareAndSet(false, true)) {
|
||||
return closed;
|
||||
}
|
||||
sendPlayersBack()
|
||||
.thenCompose(ignored -> StudioOpenCoordinator.get().closeToolWorld(bukkit(), project))
|
||||
.whenComplete((result, failure) -> finishClose(result, failure));
|
||||
return closed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> closeRefusal() {
|
||||
try {
|
||||
return listener.closeRefusal();
|
||||
} catch (Throwable failure) {
|
||||
IrisLogging.reportError("The listener of tool world " + name + " failed.", failure);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> prepareReplacement(Optional<UUID> requestedBy) {
|
||||
Optional<ToolPlayer> by = requestedBy.map(Bukkit::getPlayer).map(players::of);
|
||||
try {
|
||||
return listener.closing(by);
|
||||
} catch (Throwable failure) {
|
||||
IrisLogging.reportError("The listener of tool world " + name + " failed.", failure);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
}
|
||||
|
||||
/** The tool's listener asked, with {@code fallback} as the answer when it throws. Runs on the caller's thread. */
|
||||
boolean ask(Function<ToolWorldListener, Boolean> question, boolean fallback) {
|
||||
try {
|
||||
return question.apply(listener);
|
||||
} catch (Throwable failure) {
|
||||
IrisLogging.reportError("The listener of tool world " + name + " failed.", failure);
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/** Tells the listener something. Runs on the caller's thread. */
|
||||
void tell(Consumer<ToolWorldListener> news) {
|
||||
ask(listener -> {
|
||||
news.accept(listener);
|
||||
return true;
|
||||
}, true);
|
||||
}
|
||||
|
||||
/** A chunk of the world loaded: writes the block entities its paint asked for, then tells the tool. */
|
||||
void chunkLoaded(Chunk chunk) {
|
||||
for (PaintedBlockEntity entity : pending.take(chunk.getX(), chunk.getZ())) {
|
||||
applyPainted(chunk, entity);
|
||||
}
|
||||
tell(toolListener -> toolListener.chunkLoaded(chunk.getX(), chunk.getZ()));
|
||||
}
|
||||
|
||||
/** Bukkit unloaded the world, whoever asked: it is gone for the tool and for the host. */
|
||||
void unloaded() {
|
||||
if (!gone.compareAndSet(false, true)) {
|
||||
return;
|
||||
}
|
||||
StudioPainterSlots.remove(storageName);
|
||||
registry.unregister(this);
|
||||
releaseStudioSlot();
|
||||
tell(ToolWorldListener::closed);
|
||||
}
|
||||
|
||||
private void releaseStudioSlot() {
|
||||
StudioSVC studios = IrisServices.getOrNull(StudioSVC.class);
|
||||
if (studios != null) {
|
||||
studios.releaseStudioSlot(this);
|
||||
}
|
||||
}
|
||||
|
||||
/** Called by the opener when creating the world failed: nothing of it is left to unload. */
|
||||
void abandon() {
|
||||
StudioPainterSlots.remove(storageName);
|
||||
registry.unregister(this);
|
||||
}
|
||||
|
||||
private void finishClose(StudioOpenCoordinator.StudioCloseResult result, Throwable failure) {
|
||||
unloaded();
|
||||
Throwable cause = failure != null ? unwrap(failure) : result == null ? null : result.failureCause();
|
||||
if (cause == null) {
|
||||
closed.complete(null);
|
||||
return;
|
||||
}
|
||||
closed.completeExceptionally(cause);
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> sendPlayersBack() {
|
||||
List<CompletableFuture<Boolean>> departures = bukkit().getPlayers().stream()
|
||||
.map(player -> players.of(player).returnToOrigin())
|
||||
.toList();
|
||||
return CompletableFuture.allOf(departures.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
private record Repainted(TerrainChunk terrain, TerrainChunkCanvas canvas) {
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> repaintChunk(ChunkPos position) {
|
||||
World target = bukkit();
|
||||
AtomicReference<Repainted> repainted = new AtomicReference<>();
|
||||
CompletableFuture<Void> painting = J.afut(() -> repainted.set(paintAgain(target, position)));
|
||||
CompletableFuture<Chunk> loading = target.getChunkAtAsync(position.x(), position.z());
|
||||
return painting.thenCombine(loading, (ignored, chunk) -> chunk)
|
||||
.thenCompose(chunk -> J.runRegionFuture(target, position.x(), position.z(),
|
||||
() -> writeRepainted(target, chunk, repainted.get())));
|
||||
}
|
||||
|
||||
private Repainted paintAgain(World target, ChunkPos position) {
|
||||
TerrainChunk terrain = TerrainChunk.create(target);
|
||||
TerrainChunkCanvas canvas = TerrainChunkCanvas.onPlatform(terrain);
|
||||
slot.painter().paint(position.x(), position.z(), canvas);
|
||||
return new Repainted(terrain, canvas);
|
||||
}
|
||||
|
||||
private void writeRepainted(World target, Chunk chunk, Repainted repainted) {
|
||||
if (!INMS.get().applyChunkBlocks(chunk, repainted.terrain())) {
|
||||
InPlaceChunkRegenerator.applyBlockDiffs(chunk, repainted.terrain().getChunkData(),
|
||||
target.getMinHeight(), target.getMaxHeight());
|
||||
}
|
||||
repainted.canvas().blockEntities().forEach(entity -> applyPainted(chunk, entity));
|
||||
target.refreshChunk(chunk.getX(), chunk.getZ());
|
||||
}
|
||||
|
||||
private void applyPainted(Chunk chunk, PaintedBlockEntity entity) {
|
||||
Block block = chunk.getBlock(entity.x(), entity.y(), entity.z());
|
||||
try {
|
||||
BukkitToolBlocks.applyBlockEntity(block, entity.data());
|
||||
} catch (RuntimeException failure) {
|
||||
IrisLogging.reportError("Tool world " + name + " could not write a block entity at "
|
||||
+ block.getX() + ", " + block.getY() + ", " + block.getZ() + ".", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private Block ownedBlock(BlockPosition at) {
|
||||
requireOpen();
|
||||
if (!owns(at)) {
|
||||
throw new IllegalStateException("The calling thread does not own " + at + " in tool world " + name);
|
||||
}
|
||||
return BukkitToolBlocks.blockAt(bukkit(), at);
|
||||
}
|
||||
|
||||
private void requireOpen() {
|
||||
if (isClosed()) {
|
||||
throw new IllegalStateException("Tool world " + name + " is closed");
|
||||
}
|
||||
bukkit();
|
||||
}
|
||||
|
||||
private boolean isClosed() {
|
||||
return closing.get() || gone.get();
|
||||
}
|
||||
|
||||
private void runGuarded(Runnable task, String what) {
|
||||
try {
|
||||
task.run();
|
||||
} catch (Throwable failure) {
|
||||
IrisLogging.reportError("A task of tool world " + name + " failed: " + what + ".", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static Throwable unwrap(Throwable failure) {
|
||||
Throwable cursor = failure;
|
||||
while (cursor instanceof CompletionException && cursor.getCause() != null) {
|
||||
cursor = cursor.getCause();
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "tool world " + name;
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.tooling.ToolWorldsHost;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.util.common.plugin.IrisService;
|
||||
import com.volmit.tooling.world.ToolPlayer;
|
||||
import com.volmit.tooling.world.ToolWorlds;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
/**
|
||||
* Tool worlds on Bukkit: the platform side of {@code com.volmit.tooling.world}. It keeps the open tool worlds and the
|
||||
* tool players, listens for the events that concern them ({@link ToolWorldEvents}), and hands each pack its
|
||||
* {@link ToolWorlds} through {@link ToolWorldsHost}, which core reaches it by.
|
||||
*/
|
||||
public final class BukkitToolWorldService implements IrisService, ToolWorldsHost {
|
||||
private static final long CLOSING_WAIT_SECONDS = 30L;
|
||||
|
||||
private final OpenToolWorlds worlds = new OpenToolWorlds();
|
||||
private final ToolPlayers players = new ToolPlayers(worlds);
|
||||
private final ToolWorldEvents events = new ToolWorldEvents(worlds, players);
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
Bukkit.getPluginManager().registerEvents(events, BukkitPlatform.plugin());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
HandlerList.unregisterAll(events);
|
||||
List<BukkitToolWorld> open = worlds.all();
|
||||
awaitClosing(open);
|
||||
open.forEach(BukkitToolWorld::unloaded);
|
||||
}
|
||||
|
||||
/** Lets every tool hear that its world is closing, as a replacement does, so it can save what it holds before the world is gone. */
|
||||
private static void awaitClosing(List<BukkitToolWorld> open) {
|
||||
CompletableFuture<?>[] closing = open.stream()
|
||||
.map(world -> world.prepareReplacement(Optional.empty()))
|
||||
.toArray(CompletableFuture[]::new);
|
||||
try {
|
||||
CompletableFuture.allOf(closing).get(CLOSING_WAIT_SECONDS, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
} catch (ExecutionException | TimeoutException notReady) {
|
||||
IrisLogging.reportError("A tool world was not ready to close when Iris stopped.", notReady);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public ToolWorlds worldsOf(String packName) {
|
||||
return new BukkitToolWorlds(packName, worlds, players);
|
||||
}
|
||||
|
||||
/** The tool player for {@code player}, the same object for as long as the player is online. */
|
||||
public ToolPlayer playerOf(Player player) {
|
||||
return players.of(player);
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.runtime.StudioOpenCoordinator;
|
||||
import art.arcane.iris.core.runtime.StudioPainterSlots;
|
||||
import art.arcane.iris.core.service.StudioSVC;
|
||||
import art.arcane.iris.spi.IrisServices;
|
||||
import com.volmit.tooling.world.ToolWorld;
|
||||
import com.volmit.tooling.world.ToolWorldDenied;
|
||||
import com.volmit.tooling.world.ToolWorldSpec;
|
||||
import com.volmit.tooling.world.ToolWorlds;
|
||||
import org.bukkit.World;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionException;
|
||||
|
||||
/**
|
||||
* The tool worlds of one pack on Bukkit. A tool world is created through the studio's own world creation, with the
|
||||
* tool's painter installed first so that even the first chunk is the tool's.
|
||||
*/
|
||||
final class BukkitToolWorlds implements ToolWorlds {
|
||||
private static final String STORAGE_NAME_PREFIX = "iris-";
|
||||
private static final long TOOL_WORLD_SEED = 1337L;
|
||||
|
||||
private final String packName;
|
||||
private final OpenToolWorlds registry;
|
||||
private final ToolPlayers players;
|
||||
|
||||
BukkitToolWorlds(String packName, OpenToolWorlds registry, ToolPlayers players) {
|
||||
this.packName = packName;
|
||||
this.registry = registry;
|
||||
this.players = players;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<ToolWorld> open(ToolWorldSpec spec) {
|
||||
Optional<String> denial = StudioSVC.packAdmissionDenial(packName, StudioOpenCoordinator.StudioOpenKind.TOOL);
|
||||
if (denial.isPresent()) {
|
||||
return CompletableFuture.failedFuture(new ToolWorldDenied(denial.get()));
|
||||
}
|
||||
PendingBlockEntities pending = new PendingBlockEntities();
|
||||
StudioPainterSlots.Slot slot = new StudioPainterSlots.Slot(spec.painter(), pending::add);
|
||||
String storageName = STORAGE_NAME_PREFIX + UUID.randomUUID();
|
||||
BukkitToolWorld toolWorld = new BukkitToolWorld(packName, spec.name(), storageName, spec.listener(), slot, pending,
|
||||
registry, players);
|
||||
if (!registry.register(toolWorld)) {
|
||||
return CompletableFuture.failedFuture(new IllegalStateException(
|
||||
"A tool world called " + spec.name() + " is open already in pack " + packName));
|
||||
}
|
||||
StudioPainterSlots.install(storageName, slot);
|
||||
CompletableFuture<ToolWorld> opened = new CompletableFuture<>();
|
||||
IrisServices.get(StudioSVC.class).occupyStudioSlot(
|
||||
toolWorld,
|
||||
() -> StudioOpenCoordinator.get().open(openRequest(storageName, toolWorld))
|
||||
).whenComplete((result, failure) -> {
|
||||
if (failure != null) {
|
||||
toolWorld.abandon();
|
||||
opened.completeExceptionally(unwrap(failure));
|
||||
return;
|
||||
}
|
||||
opened.complete(toolWorld);
|
||||
});
|
||||
return opened;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<ToolWorld> find(String name) {
|
||||
return registry.forName(packName, name).filter(BukkitToolWorld::isBound).map(world -> world);
|
||||
}
|
||||
|
||||
private StudioOpenCoordinator.StudioOpenRequest openRequest(String storageName, BukkitToolWorld toolWorld) {
|
||||
return new StudioOpenCoordinator.StudioOpenRequest(
|
||||
packName,
|
||||
toolWorld.project(),
|
||||
null,
|
||||
TOOL_WORLD_SEED,
|
||||
storageName,
|
||||
null,
|
||||
StudioOpenCoordinator.StudioOpenKind.TOOL,
|
||||
false,
|
||||
null,
|
||||
world -> prepare(toolWorld, world),
|
||||
System.nanoTime());
|
||||
}
|
||||
|
||||
private static void prepare(BukkitToolWorld toolWorld, World created) {
|
||||
toolWorld.bind(created);
|
||||
ToolWorldRules.apply(created);
|
||||
}
|
||||
|
||||
private static Throwable unwrap(Throwable failure) {
|
||||
Throwable cursor = failure;
|
||||
while (cursor instanceof CompletionException && cursor.getCause() != null) {
|
||||
cursor = cursor.getCause();
|
||||
}
|
||||
return cursor;
|
||||
}
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.IrisWorldStorage;
|
||||
import org.bukkit.World;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* The tool worlds that are open or opening: found by the Bukkit world they live in, and by the tool's name for them
|
||||
* within a pack. A world is registered before Bukkit has created it, since chunks load while it is created; until it
|
||||
* is bound to its Bukkit world it is found by the logical name of its storage, which the creator fixes beforehand.
|
||||
*/
|
||||
final class OpenToolWorlds {
|
||||
private final Map<String, BukkitToolWorld> byStorageName = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, BukkitToolWorld> byWorldId = new ConcurrentHashMap<>();
|
||||
private final Map<String, BukkitToolWorld> byPackAndName = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Registers {@code world} under its storage name and the name its tool gave it.
|
||||
*
|
||||
* @return whether the tool's name was free; when it is not, nothing is registered
|
||||
*/
|
||||
boolean register(BukkitToolWorld world) {
|
||||
if (byPackAndName.putIfAbsent(packAndName(world.packName(), world.name()), world) != null) {
|
||||
return false;
|
||||
}
|
||||
byStorageName.put(world.storageName(), world);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Records the Bukkit world of {@code world}, which is bound already. */
|
||||
void bound(BukkitToolWorld world) {
|
||||
byWorldId.put(world.worldId(), world);
|
||||
}
|
||||
|
||||
void unregister(BukkitToolWorld world) {
|
||||
byStorageName.remove(world.storageName(), world);
|
||||
byPackAndName.remove(packAndName(world.packName(), world.name()), world);
|
||||
if (world.isBound()) {
|
||||
byWorldId.remove(world.worldId(), world);
|
||||
}
|
||||
}
|
||||
|
||||
/** The tool world that {@code world} is; empty for every other world. */
|
||||
Optional<BukkitToolWorld> forWorld(World world) {
|
||||
if (world == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
BukkitToolWorld bound = byWorldId.get(world.getUID());
|
||||
return bound != null ? Optional.of(bound) : forOpeningWorld(world);
|
||||
}
|
||||
|
||||
Optional<BukkitToolWorld> forName(String packName, String name) {
|
||||
return Optional.ofNullable(byPackAndName.get(packAndName(packName, name)));
|
||||
}
|
||||
|
||||
List<BukkitToolWorld> all() {
|
||||
return new ArrayList<>(byStorageName.values());
|
||||
}
|
||||
|
||||
private Optional<BukkitToolWorld> forOpeningWorld(World world) {
|
||||
boolean anyOpening = byStorageName.values().stream().anyMatch(candidate -> !candidate.isBound());
|
||||
if (!anyOpening) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.ofNullable(byStorageName.get(IrisWorldStorage.logicalName(world)));
|
||||
}
|
||||
|
||||
private static String packAndName(String packName, String name) {
|
||||
return packName + "/" + name;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedBlockEntity;
|
||||
import art.arcane.iris.core.runtime.StudioPainterSlots.PaintedChunk;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* The block entities a painter asked for in chunks that are generated but not loaded yet. A chunk is painted on a
|
||||
* generation thread and its block entities can only be written once it is live, so they wait here for its load.
|
||||
*/
|
||||
final class PendingBlockEntities {
|
||||
private static final int INT_BITS = 32;
|
||||
|
||||
private final Map<Long, List<PaintedBlockEntity>> byChunk = new ConcurrentHashMap<>();
|
||||
|
||||
/** Keeps what a paint of a chunk asked for; a later paint of the same chunk replaces it. */
|
||||
void add(PaintedChunk painted) {
|
||||
byChunk.put(chunkKey(painted.chunkX(), painted.chunkZ()), painted.blockEntities());
|
||||
}
|
||||
|
||||
/** Hands over what waits for the chunk, once; empty when nothing does. */
|
||||
List<PaintedBlockEntity> take(int chunkX, int chunkZ) {
|
||||
List<PaintedBlockEntity> waiting = byChunk.remove(chunkKey(chunkX, chunkZ));
|
||||
return waiting == null ? List.of() : waiting;
|
||||
}
|
||||
|
||||
private static long chunkKey(int chunkX, int chunkZ) {
|
||||
return ((long) chunkX << INT_BITS) | (chunkZ & 0xFFFFFFFFL);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import org.bukkit.GameMode;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* The tool players: one {@link BukkitToolPlayer} for each online player, and what the host remembers about them while
|
||||
* they are in tool worlds, which is where they came from and the game mode they had before a tool made them creative.
|
||||
*/
|
||||
final class ToolPlayers {
|
||||
private final OpenToolWorlds worlds;
|
||||
private final BukkitToolMenus menus = new BukkitToolMenus();
|
||||
private final Map<UUID, BukkitToolPlayer> players = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Location> origins = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, GameMode> modesBeforeCreative = new ConcurrentHashMap<>();
|
||||
|
||||
ToolPlayers(OpenToolWorlds worlds) {
|
||||
this.worlds = worlds;
|
||||
}
|
||||
|
||||
BukkitToolPlayer of(Player player) {
|
||||
return players.computeIfAbsent(player.getUniqueId(), id -> new BukkitToolPlayer(player, worlds, this, menus));
|
||||
}
|
||||
|
||||
/** Forgets everything about a player who left the server. */
|
||||
void forget(Player player) {
|
||||
UUID id = player.getUniqueId();
|
||||
players.remove(id);
|
||||
origins.remove(id);
|
||||
modesBeforeCreative.remove(id);
|
||||
menus.forget(id);
|
||||
}
|
||||
|
||||
/** Remembers where a player was before their first step into a tool world; later steps keep the first. */
|
||||
void rememberOrigin(Player player, Location origin) {
|
||||
origins.putIfAbsent(player.getUniqueId(), origin.clone());
|
||||
}
|
||||
|
||||
/** Hands over where the player came from, once. */
|
||||
Optional<Location> takeOrigin(Player player) {
|
||||
return Optional.ofNullable(origins.remove(player.getUniqueId()));
|
||||
}
|
||||
|
||||
/** Remembers the game mode of a player a tool makes creative; the first mode is kept while they stay creative. */
|
||||
void rememberModeBeforeCreative(Player player) {
|
||||
modesBeforeCreative.putIfAbsent(player.getUniqueId(), player.getGameMode());
|
||||
}
|
||||
|
||||
/** Gives a player the game mode they had before a tool made them creative; does nothing when none did. */
|
||||
void restoreGameMode(Player player) {
|
||||
GameMode previous = modesBeforeCreative.remove(player.getUniqueId());
|
||||
if (previous != null) {
|
||||
player.setGameMode(previous);
|
||||
}
|
||||
}
|
||||
|
||||
BukkitToolMenus menus() {
|
||||
return menus;
|
||||
}
|
||||
}
|
||||
+593
@@ -0,0 +1,593 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import com.volmit.block.BlockState;
|
||||
import com.volmit.geometry.BlockPosition;
|
||||
import com.volmit.tooling.world.BlockChange;
|
||||
import com.volmit.tooling.world.BlockChange.Cause;
|
||||
import com.volmit.tooling.world.ToolPlayer;
|
||||
import com.volmit.tooling.world.ToolUse;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.BlockFace;
|
||||
import org.bukkit.block.DoubleChest;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.block.BlockBreakEvent;
|
||||
import org.bukkit.event.block.BlockBurnEvent;
|
||||
import org.bukkit.event.block.BlockCookEvent;
|
||||
import org.bukkit.event.block.BlockDispenseEvent;
|
||||
import org.bukkit.event.block.BlockExplodeEvent;
|
||||
import org.bukkit.event.block.BlockFadeEvent;
|
||||
import org.bukkit.event.block.BlockFormEvent;
|
||||
import org.bukkit.event.block.BlockFromToEvent;
|
||||
import org.bukkit.event.block.BlockGrowEvent;
|
||||
import org.bukkit.event.block.BlockMultiPlaceEvent;
|
||||
import org.bukkit.event.block.BlockPistonExtendEvent;
|
||||
import org.bukkit.event.block.BlockPistonRetractEvent;
|
||||
import org.bukkit.event.block.BlockPlaceEvent;
|
||||
import org.bukkit.event.block.BlockRedstoneEvent;
|
||||
import org.bukkit.event.block.BlockSpreadEvent;
|
||||
import org.bukkit.event.block.BrewingStartEvent;
|
||||
import org.bukkit.event.block.CrafterCraftEvent;
|
||||
import org.bukkit.event.entity.CreatureSpawnEvent;
|
||||
import org.bukkit.event.entity.EntityChangeBlockEvent;
|
||||
import org.bukkit.event.entity.EntityExplodeEvent;
|
||||
import org.bukkit.event.inventory.BrewEvent;
|
||||
import org.bukkit.event.inventory.BrewingStandFuelEvent;
|
||||
import org.bukkit.event.inventory.FurnaceBurnEvent;
|
||||
import org.bukkit.event.inventory.FurnaceStartSmeltEvent;
|
||||
import org.bukkit.event.inventory.InventoryCloseEvent;
|
||||
import org.bukkit.event.inventory.FurnaceSmeltEvent;
|
||||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.inventory.InventoryDragEvent;
|
||||
import org.bukkit.event.inventory.InventoryMoveItemEvent;
|
||||
import org.bukkit.event.inventory.InventoryPickupItemEvent;
|
||||
import org.bukkit.event.player.PlayerBucketEmptyEvent;
|
||||
import org.bukkit.event.player.PlayerBucketFillEvent;
|
||||
import org.bukkit.event.player.PlayerChangedWorldEvent;
|
||||
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerMoveEvent;
|
||||
import org.bukkit.event.player.PlayerPortalEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
import org.bukkit.event.player.PlayerRespawnEvent;
|
||||
import org.bukkit.event.player.PlayerTeleportEvent;
|
||||
import org.bukkit.event.player.PlayerToggleSneakEvent;
|
||||
import org.bukkit.event.server.ServerCommandEvent;
|
||||
import org.bukkit.event.world.ChunkLoadEvent;
|
||||
import org.bukkit.event.world.StructureGrowEvent;
|
||||
import org.bukkit.event.world.WorldUnloadEvent;
|
||||
import org.bukkit.inventory.BlockInventoryHolder;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The one listener that maps Bukkit's events onto {@link com.volmit.tooling.world.ToolWorldListener}, for tool worlds
|
||||
* only. Every handler first asks whether the event happens in a tool world and does nothing when it does not. The
|
||||
* priorities and {@code ignoreCancelled} flags are those of the jigsaw studio's own handlers: decisions at HIGHEST so
|
||||
* that other plugins have had their say, observations at MONITOR.
|
||||
*/
|
||||
public final class ToolWorldEvents implements Listener {
|
||||
private static final String COMMAND_PREFIX = "/";
|
||||
|
||||
private final OpenToolWorlds worlds;
|
||||
private final ToolPlayers players;
|
||||
|
||||
ToolWorldEvents(OpenToolWorlds worlds, ToolPlayers players) {
|
||||
this.worlds = worlds;
|
||||
this.players = players;
|
||||
}
|
||||
|
||||
// Block changes: the tool decides, `false` cancels.
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockPlace(BlockPlaceEvent event) {
|
||||
Block placed = event.getBlockPlaced();
|
||||
allowOrCancel(event, Cause.PLACE, placed.getWorld(), List.of(positionOf(placed)), Optional.of(event.getPlayer()),
|
||||
Optional.of(BukkitToolBlocks.stateOf(placed.getBlockData())));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockMultiPlace(BlockMultiPlaceEvent event) {
|
||||
List<BlockPosition> replaced = event.getReplacedBlockStates().stream()
|
||||
.map(state -> positionOf(state.getBlock())).toList();
|
||||
allowOrCancel(event, Cause.PLACE, event.getBlock().getWorld(), replaced, Optional.of(event.getPlayer()), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockBreak(BlockBreakEvent event) {
|
||||
allowOrCancel(event, Cause.BREAK, event.getBlock(), Optional.of(event.getPlayer()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBucketEmpty(PlayerBucketEmptyEvent event) {
|
||||
allowOrCancel(event, Cause.BUCKET, event.getBlockClicked().getRelative(event.getBlockFace()), Optional.of(event.getPlayer()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBucketFill(PlayerBucketFillEvent event) {
|
||||
allowOrCancel(event, Cause.BUCKET, event.getBlockClicked(), Optional.of(event.getPlayer()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockForm(BlockFormEvent event) {
|
||||
allowOrCancel(event, Cause.PHYSICS, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockFade(BlockFadeEvent event) {
|
||||
allowOrCancel(event, Cause.PHYSICS, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockSpread(BlockSpreadEvent event) {
|
||||
allowOrCancel(event, Cause.PHYSICS, event.getBlock().getWorld(),
|
||||
List.of(positionOf(event.getBlock()), positionOf(event.getSource())), Optional.empty(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockFromTo(BlockFromToEvent event) {
|
||||
allowOrCancel(event, Cause.FLUID, event.getBlock().getWorld(),
|
||||
List.of(positionOf(event.getBlock()), positionOf(event.getToBlock())), Optional.empty(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockGrow(BlockGrowEvent event) {
|
||||
allowOrCancel(event, Cause.GROWTH, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onStructureGrow(StructureGrowEvent event) {
|
||||
World world = event.getLocation().getWorld();
|
||||
List<BlockPosition> grown = event.getBlocks().stream().map(state -> positionOf(state.getBlock())).toList();
|
||||
if (!grown.isEmpty()) {
|
||||
allowOrCancel(event, Cause.GROWTH, world, grown, Optional.ofNullable(event.getPlayer()), Optional.empty());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockBurn(BlockBurnEvent event) {
|
||||
allowOrCancel(event, Cause.FIRE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onBlockRedstone(BlockRedstoneEvent event) {
|
||||
Block block = event.getBlock();
|
||||
if (!isAllowed(Cause.REDSTONE, block.getWorld(), List.of(positionOf(block)), Optional.empty(), Optional.empty())) {
|
||||
event.setNewCurrent(event.getOldCurrent());
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPistonExtend(BlockPistonExtendEvent event) {
|
||||
allowPistonOrCancel(event, event.getBlock(), event.getBlocks(), event.getDirection());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPistonRetract(BlockPistonRetractEvent event) {
|
||||
allowPistonOrCancel(event, event.getBlock(), event.getBlocks(), event.getDirection());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockExplode(BlockExplodeEvent event) {
|
||||
keepAllowedBlocks(event.getBlock().getWorld(), event.blockList());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onEntityExplode(EntityExplodeEvent event) {
|
||||
keepAllowedBlocks(event.getEntity().getWorld(), event.blockList());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
|
||||
Optional<Player> actor = event.getEntity() instanceof Player player ? Optional.of(player) : Optional.empty();
|
||||
allowOrCancel(event, Cause.ENTITY, event.getBlock(), actor);
|
||||
}
|
||||
|
||||
// Containers and machines.
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onInventoryClick(InventoryClickEvent event) {
|
||||
allowContainerOrCancel(event, event.getView().getTopInventory(), event.getWhoClicked() instanceof Player player ? player : null);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onInventoryDrag(InventoryDragEvent event) {
|
||||
allowContainerOrCancel(event, event.getView().getTopInventory(), event.getWhoClicked() instanceof Player player ? player : null);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onInventoryMove(InventoryMoveItemEvent event) {
|
||||
allowContainerOrCancel(event, event.getSource(), null);
|
||||
if (!event.isCancelled()) {
|
||||
allowContainerOrCancel(event, event.getDestination(), null);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onInventoryPickup(InventoryPickupItemEvent event) {
|
||||
allowContainerOrCancel(event, event.getInventory(), null);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockCook(BlockCookEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onFurnaceBurn(FurnaceBurnEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onFurnaceSmelt(FurnaceSmeltEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBrew(BrewEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBrewingStandFuel(BrewingStandFuelEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onBlockDispense(BlockDispenseEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onCrafterCraft(CrafterCraftEvent event) {
|
||||
allowOrCancel(event, Cause.MACHINE, event.getBlock(), Optional.empty());
|
||||
}
|
||||
|
||||
// What changed inside containers and machines, told after the fact.
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onInventoryClose(InventoryCloseEvent event) {
|
||||
Player player = event.getPlayer() instanceof Player closer ? closer : null;
|
||||
tellContainerChanged(containerBlocks(event.getView().getTopInventory()), Optional.ofNullable(player));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onFurnaceStartSmelt(FurnaceStartSmeltEvent event) {
|
||||
tellContainerChanged(List.of(event.getBlock()), Optional.empty());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onBrewingStart(BrewingStartEvent event) {
|
||||
tellContainerChanged(List.of(event.getBlock()), Optional.empty());
|
||||
}
|
||||
|
||||
private void tellContainerChanged(List<Block> blocks, Optional<Player> player) {
|
||||
for (Block block : blocks) {
|
||||
Optional<ToolPlayer> toolPlayer = player.map(players::of).map(ToolPlayer.class::cast);
|
||||
BlockPosition at = positionOf(block);
|
||||
worlds.forWorld(block.getWorld()).ifPresent(world ->
|
||||
world.tell(listener -> listener.containerChanged(toolPlayer, at)));
|
||||
}
|
||||
}
|
||||
|
||||
// What players do.
|
||||
|
||||
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
|
||||
public void onInteract(PlayerInteractEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
Optional<BukkitToolWorld> toolWorld = worlds.forWorld(player.getWorld());
|
||||
if (toolWorld.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
ToolUse use = new ToolUse(
|
||||
event.getHand() == org.bukkit.inventory.EquipmentSlot.OFF_HAND ? ToolUse.Hand.OFF : ToolUse.Hand.MAIN,
|
||||
ToolUse.Action.valueOf(event.getAction().name()),
|
||||
BukkitToolItems.read(event.getItem()),
|
||||
Optional.ofNullable(event.getClickedBlock()).map(ToolWorldEvents::positionOf),
|
||||
BukkitToolBlocks.faceOf(event.getBlockFace()));
|
||||
ToolPlayer toolPlayer = players.of(player);
|
||||
if (!toolWorld.get().ask(listener -> listener.used(toolPlayer, use), false)) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onToggleSneak(PlayerToggleSneakEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
worlds.forWorld(player.getWorld()).ifPresent(world ->
|
||||
world.tell(listener -> listener.sneakToggled(players.of(player), event.isSneaking())));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
Optional<BukkitToolWorld> toolWorld = worlds.forWorld(player.getWorld());
|
||||
if (toolWorld.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
String line = lineOf(event.getMessage());
|
||||
ToolPlayer toolPlayer = players.of(player);
|
||||
if (!toolWorld.get().ask(listener -> listener.command(Optional.of(toolPlayer), line), true)) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onServerCommand(ServerCommandEvent event) {
|
||||
String line = lineOf(event.getCommand());
|
||||
for (BukkitToolWorld toolWorld : worlds.all()) {
|
||||
if (!toolWorld.ask(listener -> listener.command(Optional.empty(), line), true)) {
|
||||
event.setCancelled(true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Arriving, leaving and moving.
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onJoin(PlayerJoinEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
worlds.forWorld(player.getWorld()).ifPresent(world -> enter(world, player, player.getLocation()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onQuit(PlayerQuitEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
worlds.forWorld(player.getWorld()).ifPresent(world -> leave(world, player));
|
||||
players.forget(player);
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onChangedWorld(PlayerChangedWorldEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
worlds.forWorld(event.getFrom()).ifPresent(world -> leave(world, player));
|
||||
worlds.forWorld(player.getWorld()).ifPresent(world -> enter(world, player, player.getLocation()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Every teleport of any player by anyone, portals included, is told to the tool worlds it touches at the time it
|
||||
* happens, with the position it goes to: the world it leaves hears {@code left}, the one it enters {@code entered},
|
||||
* and the one it arrives in {@code teleported}.
|
||||
*/
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onTeleport(PlayerTeleportEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
Location destination = event.getTo();
|
||||
Optional<BukkitToolWorld> from = worlds.forWorld(event.getFrom().getWorld());
|
||||
Optional<BukkitToolWorld> to = destination == null ? Optional.empty() : worlds.forWorld(destination.getWorld());
|
||||
if (from.isEmpty() && to.isPresent()) {
|
||||
players.rememberOrigin(player, event.getFrom());
|
||||
}
|
||||
if (from.isPresent() && to.isEmpty()) {
|
||||
players.restoreGameMode(player);
|
||||
players.takeOrigin(player);
|
||||
}
|
||||
if (!from.equals(to)) {
|
||||
from.ifPresent(world -> leave(world, player));
|
||||
}
|
||||
to.ifPresent(world -> enter(world, player, destination));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void onRespawn(PlayerRespawnEvent event) {
|
||||
Location respawn = event.getRespawnLocation();
|
||||
worlds.forWorld(respawn.getWorld()).ifPresent(world -> enter(world, event.getPlayer(), respawn));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onMove(PlayerMoveEvent event) {
|
||||
Location to = event.getTo();
|
||||
if (to == null || sameBlock(event.getFrom(), to)) {
|
||||
return;
|
||||
}
|
||||
worlds.forWorld(to.getWorld()).ifPresent(world ->
|
||||
world.tell(listener -> listener.moved(players.of(event.getPlayer()), BukkitToolBlocks.positionOf(to))));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void onChunkLoad(ChunkLoadEvent event) {
|
||||
worlds.forWorld(event.getWorld()).ifPresent(world -> world.chunkLoaded(event.getChunk()));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void onWorldUnload(WorldUnloadEvent event) {
|
||||
worlds.forWorld(event.getWorld()).ifPresent(BukkitToolWorld::unloaded);
|
||||
}
|
||||
|
||||
// The host's own rules.
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onNaturalSpawn(CreatureSpawnEvent event) {
|
||||
if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.NATURAL
|
||||
&& worlds.forWorld(event.getLocation().getWorld()).isPresent()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void onPortal(PlayerPortalEvent event) {
|
||||
if (worlds.forWorld(event.getFrom().getWorld()).isPresent()) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
/** The player is in the world at {@code at}: told as having entered on the first of their arrivals, and as having arrived on each. */
|
||||
private void enter(BukkitToolWorld world, Player player, Location at) {
|
||||
if (world.presence().enter(player.getUniqueId())) {
|
||||
world.tell(listener -> listener.entered(players.of(player)));
|
||||
}
|
||||
BlockPosition arrival = BukkitToolBlocks.positionOf(at);
|
||||
world.tell(listener -> listener.teleported(players.of(player), arrival));
|
||||
}
|
||||
|
||||
private void leave(BukkitToolWorld world, Player player) {
|
||||
if (world.presence().leave(player.getUniqueId())) {
|
||||
world.tell(listener -> listener.left(players.of(player)));
|
||||
}
|
||||
}
|
||||
|
||||
private void allowOrCancel(Cancellable event, Cause cause, Block block, Optional<Player> player) {
|
||||
allowOrCancel(event, cause, block.getWorld(), List.of(positionOf(block)), player, Optional.empty());
|
||||
}
|
||||
|
||||
private void allowOrCancel(
|
||||
Cancellable event,
|
||||
Cause cause,
|
||||
World world,
|
||||
List<BlockPosition> positions,
|
||||
Optional<Player> player,
|
||||
Optional<BlockState> placed
|
||||
) {
|
||||
if (!isAllowed(cause, world, positions, player, placed)) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void allowPistonOrCancel(Cancellable event, Block piston, List<Block> moved, BlockFace direction) {
|
||||
boolean allowed = isAllowed(
|
||||
Cause.PISTON,
|
||||
piston.getWorld(),
|
||||
pistonChecked(moved, direction),
|
||||
pistonChanged(piston, moved, direction),
|
||||
Optional.empty(),
|
||||
Optional.empty());
|
||||
if (!allowed) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
||||
private void allowContainerOrCancel(Cancellable event, Inventory inventory, Player player) {
|
||||
List<Block> blocks = containerBlocks(inventory);
|
||||
if (blocks.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<BlockPosition> positions = blocks.stream().map(ToolWorldEvents::positionOf).toList();
|
||||
allowOrCancel(event, Cause.CONTAINER, blocks.getFirst().getWorld(), positions, Optional.ofNullable(player), Optional.empty());
|
||||
}
|
||||
|
||||
/** Whether the tool lets the change happen; changes outside tool worlds are none of the host's business. */
|
||||
private boolean isAllowed(
|
||||
Cause cause,
|
||||
World world,
|
||||
List<BlockPosition> positions,
|
||||
Optional<Player> player,
|
||||
Optional<BlockState> placed
|
||||
) {
|
||||
return isAllowed(cause, world, positions, positions, player, placed);
|
||||
}
|
||||
|
||||
private boolean isAllowed(
|
||||
Cause cause,
|
||||
World world,
|
||||
List<BlockPosition> positions,
|
||||
List<BlockPosition> changed,
|
||||
Optional<Player> player,
|
||||
Optional<BlockState> placed
|
||||
) {
|
||||
Optional<BukkitToolWorld> toolWorld = worlds.forWorld(world);
|
||||
if (toolWorld.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
BlockChange change = new BlockChange(
|
||||
cause, positions, changed, player.map(players::of).map(ToolPlayer.class::cast), placed);
|
||||
return toolWorld.get().ask(listener -> listener.blockChanging(change), false);
|
||||
}
|
||||
|
||||
private void keepAllowedBlocks(World world, List<Block> exploded) {
|
||||
if (worlds.forWorld(world).isEmpty()) {
|
||||
return;
|
||||
}
|
||||
exploded.removeIf(block -> !isAllowed(Cause.EXPLOSION, world, List.of(positionOf(block)), Optional.empty(), Optional.empty()));
|
||||
}
|
||||
|
||||
/** Each block a piston moves and the block each of them enters and leaves, which a protected area is checked against; not the piston. */
|
||||
static List<BlockPosition> pistonChecked(List<Block> moved, BlockFace direction) {
|
||||
List<BlockPosition> positions = new ArrayList<>();
|
||||
for (Block block : moved) {
|
||||
positions.add(positionOf(block));
|
||||
positions.add(positionOf(block.getRelative(direction)));
|
||||
positions.add(positionOf(block.getRelative(direction.getOppositeFace())));
|
||||
}
|
||||
return positions.stream().distinct().toList();
|
||||
}
|
||||
|
||||
/** The piston and the block ahead of it, then each block it moves and the block each enters: what a piston changes. */
|
||||
static List<BlockPosition> pistonChanged(Block piston, List<Block> moved, BlockFace direction) {
|
||||
List<BlockPosition> positions = new ArrayList<>();
|
||||
positions.add(positionOf(piston));
|
||||
positions.add(positionOf(piston.getRelative(direction)));
|
||||
for (Block block : moved) {
|
||||
positions.add(positionOf(block));
|
||||
positions.add(positionOf(block.getRelative(direction)));
|
||||
}
|
||||
return positions.stream().distinct().toList();
|
||||
}
|
||||
|
||||
/** The blocks a container inventory is made of: none for a player's or a menu, two for a double chest. */
|
||||
static List<Block> containerBlocks(Inventory inventory) {
|
||||
if (inventory == null) {
|
||||
return List.of();
|
||||
}
|
||||
List<Block> blocks = new ArrayList<>(2);
|
||||
InventoryHolder holder = inventory.getHolder();
|
||||
if (holder instanceof BlockInventoryHolder blockHolder) {
|
||||
blocks.add(blockHolder.getBlock());
|
||||
} else if (holder instanceof DoubleChest doubleChest) {
|
||||
addBlockOf(blocks, doubleChest.getLeftSide());
|
||||
addBlockOf(blocks, doubleChest.getRightSide());
|
||||
}
|
||||
return blocks;
|
||||
}
|
||||
|
||||
private static void addBlockOf(List<Block> blocks, InventoryHolder holder) {
|
||||
if (holder instanceof BlockInventoryHolder blockHolder && !blocks.contains(blockHolder.getBlock())) {
|
||||
blocks.add(blockHolder.getBlock());
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether two locations are in one block of one world. */
|
||||
static boolean sameBlock(Location from, Location to) {
|
||||
return from.getWorld() == to.getWorld()
|
||||
&& from.getBlockX() == to.getBlockX()
|
||||
&& from.getBlockY() == to.getBlockY()
|
||||
&& from.getBlockZ() == to.getBlockZ();
|
||||
}
|
||||
|
||||
/** What a command line is for the tool: without the slash a player types before it. */
|
||||
static String lineOf(String typed) {
|
||||
return typed.startsWith(COMMAND_PREFIX) ? typed.substring(COMMAND_PREFIX.length()) : typed;
|
||||
}
|
||||
|
||||
private static BlockPosition positionOf(Block block) {
|
||||
return BukkitToolBlocks.positionOf(block);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Who stands in one tool world, so that the platform's several ways of arriving and leaving (join, teleport, world
|
||||
* change, respawn, quit) tell the tool once for each stay: {@code entered} on the first of them, {@code left} on the
|
||||
* first of them after.
|
||||
*/
|
||||
final class ToolWorldPresence {
|
||||
private final Set<UUID> present = ConcurrentHashMap.newKeySet();
|
||||
|
||||
/** Whether the player was not here before, which is when the tool hears {@code entered}. */
|
||||
boolean enter(UUID player) {
|
||||
return present.add(player);
|
||||
}
|
||||
|
||||
/** Whether the player was here, which is when the tool hears {@code left}. */
|
||||
boolean leave(UUID player) {
|
||||
return present.remove(player);
|
||||
}
|
||||
|
||||
boolean isPresent(UUID player) {
|
||||
return present.contains(player);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.core.toolworld;
|
||||
|
||||
import art.arcane.iris.core.runtime.WorldRuntimeControlService;
|
||||
import org.bukkit.GameRules;
|
||||
import org.bukkit.World;
|
||||
|
||||
/**
|
||||
* What every tool world is made to be, whatever the server's studio settings say: no natural mobs, no weather, no
|
||||
* daylight cycle, no portals, on top of the rules the object and jigsaw studios already use.
|
||||
*/
|
||||
final class ToolWorldRules {
|
||||
private ToolWorldRules() {
|
||||
}
|
||||
|
||||
/** Applies the rules; runs on the thread that may change the world's rules (the main or global thread). */
|
||||
static void apply(World world) {
|
||||
WorldRuntimeControlService.get().applyObjectStudioWorldRules(world);
|
||||
world.setGameRule(GameRules.SPAWN_MOBS, false);
|
||||
world.setGameRule(GameRules.ADVANCE_WEATHER, false);
|
||||
world.setGameRule(GameRules.ADVANCE_TIME, false);
|
||||
world.setGameRule(GameRules.ALLOW_ENTERING_NETHER_USING_PORTALS, false);
|
||||
world.setStorm(false);
|
||||
world.setThundering(false);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -56,7 +56,7 @@ public class IrisDiagnosticLogLevelTest {
|
||||
assertTrue(bridge, bridge.contains("diagnostic(diagnostic, message)"));
|
||||
String diagnostic = method(source, "private static void diagnostic(Level level, String message)");
|
||||
assertTrue(diagnostic, diagnostic.contains("ComponentLog.log("));
|
||||
assertTrue(diagnostic, diagnostic.contains("ComponentText.literal(line)"));
|
||||
assertTrue(diagnostic, diagnostic.contains("ComponentText.section(message)"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package art.arcane.iris;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
|
||||
public class IrisDisabledStaticsTest {
|
||||
@Test
|
||||
public void serviceLookupAfterDisableStatesThatIrisIsDisabled() {
|
||||
assertNull(Iris.instance);
|
||||
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class, () -> Iris.service(Runnable.class));
|
||||
|
||||
assertEquals("Iris is disabled; Runnable is unavailable", failure.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void tempFolderAfterDisableStatesThatIrisIsDisabled() {
|
||||
assertNull(Iris.instance);
|
||||
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class, Iris::getTemp);
|
||||
|
||||
assertEquals("Iris is disabled; the temp folder is unavailable", failure.getMessage());
|
||||
}
|
||||
}
|
||||
+35
-37
@@ -1,5 +1,6 @@
|
||||
package art.arcane.iris;
|
||||
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.nio.file.Files;
|
||||
@@ -23,9 +24,10 @@ public class IrisShutdownOrderingTest {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.startupSource")));
|
||||
String onDisable = section(source, "public void onDisable()", "public void onPreUnload");
|
||||
String quiesce = section(source, "private void quiesceRuntimeForServerShutdown", "private void startPostStopFinisher");
|
||||
String shutdownHook = section(source, "private void runShutdownHook()", "private boolean awaitServerShutdownBoundary");
|
||||
String finisher = section(source, "private void startPostStopFinisher()", "static boolean awaitServerThreadTermination");
|
||||
String serverJoin = section(source, "static boolean awaitServerThreadTermination", "private void runShutdownHook");
|
||||
String shutdownHook = section(source, "private void runShutdownHook()", "private void finishRuntimeAfterServerShutdown");
|
||||
String boundaryFinish = section(source, "private void finishRuntimeAfterServerShutdown", "private boolean awaitServerShutdownBoundary");
|
||||
String boundaryAwait = section(source, "private boolean awaitServerShutdownBoundary", "private void finishDeferredRuntimeTeardown");
|
||||
String finisher = section(source, "private void startPostStopFinisher()", "private void runShutdownHook");
|
||||
String generatorSource = Files.readString(Path.of(System.getProperty("iris.bukkitChunkGeneratorSource")));
|
||||
String generatorQuiesce = section(generatorSource,
|
||||
"public void quiesceForServerShutdown()", "public boolean isStudio()");
|
||||
@@ -42,26 +44,33 @@ public class IrisShutdownOrderingTest {
|
||||
"startupBoundaryRestart.get()",
|
||||
"finishDeferredRuntimeTeardown(\"startup-boundary-restart-hook\", 30L)",
|
||||
"return;",
|
||||
"awaitServerShutdownBoundary()",
|
||||
"finishDeferredRuntimeTeardown(\"shutdown-hook\", 30L)");
|
||||
"finishRuntimeAfterServerShutdown(\"shutdown-hook\")");
|
||||
assertOrdered(finisher,
|
||||
"finishRuntimeAfterServerShutdown(\"post-server-stop\")",
|
||||
"finisher.setDaemon(false)",
|
||||
"finisher.start()");
|
||||
assertOrdered(finisher,
|
||||
"awaitServerThreadTermination(activeServerThread)",
|
||||
"finishDeferredRuntimeTeardown(\"post-server-stop\", 30L)");
|
||||
assertOrdered(serverJoin,
|
||||
"serverThread == Thread.currentThread()",
|
||||
"serverThread.join()");
|
||||
assertOrdered(boundaryFinish,
|
||||
"awaitServerShutdownBoundary()",
|
||||
"return;",
|
||||
"finishDeferredRuntimeTeardown(reason, 30L)");
|
||||
assertTrue("A missing shutdown boundary must retain the runtime",
|
||||
boundaryAwait.contains("if (!INMS.isBound()) {\n return false;"));
|
||||
assertFalse("Runtime cleanup must wait for the shutdown boundary, not the server thread",
|
||||
source.contains("serverThread.join()") || source.contains("serverLifecycleThread"));
|
||||
assertTrue("Server-stop quiescence must leave queued Paper generation admitted",
|
||||
quiesce.contains("generator.quiesceForServerShutdown()"));
|
||||
assertOrdered(quiesce,
|
||||
"jigsawStudioService.quiesceForServerShutdown()",
|
||||
"PregeneratorJob.shutdownAndWait",
|
||||
"generator.quiesceForServerShutdown()");
|
||||
assertOrdered(onDisable,
|
||||
"quiesceRuntimeForServerShutdown(\"onDisable\")",
|
||||
"super.onDisable()");
|
||||
assertTrue("Server-stop quiescence must keep queued generation running its mantle stages",
|
||||
quiesce.contains("IrisToolbelt.beginWorldMaintenance(world, reason);"));
|
||||
assertTrue("Disable must wait for a replacement that is staging before it tears anything down",
|
||||
onDisable.indexOf("pendingWorldReplacements.awaitStagingForShutdown()") >= 0
|
||||
&& onDisable.indexOf("pendingWorldReplacements.awaitStagingForShutdown()")
|
||||
< onDisable.indexOf("teardownPapi()"));
|
||||
assertFalse("Server-stop quiescence must not begin generator close before Paper's boundary",
|
||||
generatorQuiesce.contains("closing = true"));
|
||||
assertFalse("Server-stop quiescence must not dispatch generator close before Paper's boundary",
|
||||
@@ -113,32 +122,21 @@ public class IrisShutdownOrderingTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jigsawStudio_quiescesOnceBeforeDeferredServiceTeardown() throws Exception {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.jigsawStudioSvcSource")));
|
||||
String enable = section(source, "public void onEnable()", "public void onDisable()");
|
||||
String disable = section(source, "public void onDisable()", "public void quiesceForServerShutdown()");
|
||||
String quiesce = section(source, "public void quiesceForServerShutdown()", "public void register(");
|
||||
String register = section(source, "public void register(", "public void activationCommitted(");
|
||||
String activation = section(source, "public void activationCommitted(", "public void markChunkGenerated(");
|
||||
String chunkGenerated = section(source, "public void markChunkGenerated(", "private void markChunkAvailable(");
|
||||
public void jigsawStudio_quiescesThroughItsToolWorldBeforeTheWorldIsUnloaded() throws Exception {
|
||||
String startup = Files.readString(Path.of(System.getProperty("iris.startupSource")));
|
||||
String toolWorlds = Files.readString(Path.of(System.getProperty("iris.toolWorldServiceSource")));
|
||||
String studio = Files.readString(Path.of(System.getProperty("iris.jigsawStudioSvcSource")));
|
||||
String disable = section(toolWorlds, "public void onDisable()", "public ToolWorlds worldsOf");
|
||||
String closing = section(studio, "CompletableFuture<Void> closing(", "private boolean markDirty(");
|
||||
|
||||
assertOrdered(enable, "disableStarted.set(false)", "enabled = true");
|
||||
assertTrue("Deferred service teardown must reuse the idempotent early disable",
|
||||
disable.contains("quiesceForServerShutdown();"));
|
||||
assertOrdered(quiesce,
|
||||
"disableStarted.compareAndSet(false, true)",
|
||||
"finalizeAllJigsawTileWatches()",
|
||||
"drainAutosavesBeforeDisable()",
|
||||
"enabled = false",
|
||||
"activeMenuController.closeAll()",
|
||||
"previewRenderer.removeAll()",
|
||||
"studios.clear()");
|
||||
assertTrue("Registration must reject work after shutdown begins",
|
||||
occurrences(register, "!enabled || disableStarted.get()") >= 2);
|
||||
assertTrue("Activation must reject work after shutdown begins",
|
||||
activation.contains("!enabled || disableStarted.get()"));
|
||||
assertTrue("Chunk-generation callbacks must reject work after shutdown begins",
|
||||
occurrences(chunkGenerated, "!enabled || disableStarted.get()") >= 2);
|
||||
assertFalse("Iris no longer holds or quiesces a studio itself", startup.contains("JigsawStudio"));
|
||||
assertOrdered(disable,
|
||||
"awaitClosing(open)",
|
||||
"open.forEach(BukkitToolWorld::unloaded)");
|
||||
assertTrue("The host asks every tool world to get ready to close", toolWorlds.contains("world.prepareReplacement(Optional.empty())"));
|
||||
assertOrdered(closing,
|
||||
"drainAutosavesBeforeRemoval(studios.get(worldId))",
|
||||
"awaitCloseForReplacement(");
|
||||
}
|
||||
|
||||
private static String section(String source, String startMarker, String endMarker) {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package art.arcane.iris;
|
||||
|
||||
import org.bukkit.plugin.PluginDescriptionFile;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.mockito.Answers.CALLS_REAL_METHODS;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
public class IrisVersionNumberTest {
|
||||
@Test
|
||||
public void releaseAndQualifiedBuildsUseTheSameVersionNumber() {
|
||||
for (String version : List.of("4.3.3", "4.3.3-SNAPSHOT", "4.3.3-test")) {
|
||||
assertEquals(version, 433, plugin(version).getIrisVersion());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void processedPluginMetadataProvidesAValidEngineVersion() throws Exception {
|
||||
try (InputStream stream = getClass().getResourceAsStream("/plugin.yml")) {
|
||||
assertNotNull(stream);
|
||||
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
|
||||
doReturn(new PluginDescriptionFile(stream)).when(plugin).getDescription();
|
||||
|
||||
assertNotEquals(-1, plugin.getIrisVersion());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void malformedAndOverflowingReleaseNumbersStayInvalid() {
|
||||
for (String version : List.of("development", "4..3", ".4.3.3", "4.3.3.", "4.3a.3-test",
|
||||
"2147483648", "999999999999999999999-SNAPSHOT", "-SNAPSHOT")) {
|
||||
assertEquals(version, -1, plugin(version).getIrisVersion());
|
||||
}
|
||||
}
|
||||
|
||||
private static Iris plugin(String version) {
|
||||
Iris plugin = mock(Iris.class, CALLS_REAL_METHODS);
|
||||
doReturn(new PluginDescriptionFile("Iris", version, Iris.class.getName())).when(plugin).getDescription();
|
||||
return plugin;
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -526,11 +526,11 @@ public class IrisWorldGeneratorResolverTest {
|
||||
Files.createDirectories(packRoot.resolve("biomes"));
|
||||
Files.writeString(
|
||||
packRoot.resolve("dimensions/main.json"),
|
||||
"{\"regions\":[\"region\"]}",
|
||||
"{\"regions\":[{\"region\":\"region\"}]}",
|
||||
StandardCharsets.UTF_8);
|
||||
Files.writeString(
|
||||
packRoot.resolve("regions/region.json"),
|
||||
"{\"landBiomes\":[\"biome\"]}",
|
||||
"{\"landBiomes\":[{\"biome\":\"biome\"}]}",
|
||||
StandardCharsets.UTF_8);
|
||||
Files.writeString(
|
||||
packRoot.resolve("biomes/biome.json"),
|
||||
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package art.arcane.iris.core;
|
||||
|
||||
import art.arcane.iris.Iris;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
public class PendingWorldReplacementAdmissionTest {
|
||||
private static final long STATE_TIMEOUT_SECONDS = 5L;
|
||||
private static final long JOIN_TIMEOUT_SECONDS = 10L;
|
||||
private static final long STATE_POLL_MILLIS = 5L;
|
||||
|
||||
private final NamespacedKey worldKey = NamespacedKey.minecraft("overworld");
|
||||
|
||||
@Test
|
||||
public void shutdownDoesNotWaitWhenNothingIsStaging() throws Exception {
|
||||
PendingWorldReplacementManager manager = new PendingWorldReplacementManager(mock(Iris.class));
|
||||
Thread shutdown = new Thread(manager::awaitStagingForShutdown);
|
||||
|
||||
shutdown.start();
|
||||
shutdown.join(TimeUnit.SECONDS.toMillis(JOIN_TIMEOUT_SECONDS));
|
||||
|
||||
assertFalse(shutdown.isAlive());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shutdownRejectsReplacementsThatStartAfterIt() throws Exception {
|
||||
PendingWorldReplacementManager manager = new PendingWorldReplacementManager(mock(Iris.class));
|
||||
manager.awaitStagingForShutdown();
|
||||
|
||||
IOException rejected = assertThrows(IOException.class, () -> manager.admitStaging(worldKey));
|
||||
|
||||
assertTrue(rejected.getMessage().contains("shutting down"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shutdownWaitsForTheReplacementBeingStaged() throws Exception {
|
||||
PendingWorldReplacementManager manager = new PendingWorldReplacementManager(mock(Iris.class));
|
||||
PendingWorldReplacementManager.StagingAdmission staging = manager.admitStaging(worldKey);
|
||||
Thread shutdown = new Thread(manager::awaitStagingForShutdown);
|
||||
|
||||
shutdown.start();
|
||||
try {
|
||||
awaitState(shutdown, Thread.State.WAITING);
|
||||
assertTrue(shutdown.isAlive());
|
||||
} finally {
|
||||
staging.close();
|
||||
}
|
||||
shutdown.join(TimeUnit.SECONDS.toMillis(JOIN_TIMEOUT_SECONDS));
|
||||
|
||||
assertFalse(shutdown.isAlive());
|
||||
}
|
||||
|
||||
private static void awaitState(Thread thread, Thread.State state) throws InterruptedException {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(STATE_TIMEOUT_SECONDS);
|
||||
while (thread.getState() != state) {
|
||||
if (System.nanoTime() > deadline) {
|
||||
throw new AssertionError(thread.getName() + " never reached " + state + "; it is " + thread.getState());
|
||||
}
|
||||
Thread.sleep(STATE_POLL_MILLIS);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -3,8 +3,8 @@ package art.arcane.iris.core;
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.core.ExactWorldSlotPathPolicy.SlotKind;
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementBootstrapMarker;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisEnvironment;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.object.world.IrisEnvironment;
|
||||
import art.arcane.iris.util.common.plugin.VolmitSender;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.junit.After;
|
||||
|
||||
+2
-2
@@ -6,8 +6,8 @@ import art.arcane.iris.core.lifecycle.WorldReplacementJournal.Phase;
|
||||
import art.arcane.iris.core.lifecycle.WorldReplacementJournal.Transaction;
|
||||
import art.arcane.iris.core.tools.IrisToolbelt;
|
||||
import art.arcane.iris.engine.framework.EngineTarget;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisEnvironment;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.object.world.IrisEnvironment;
|
||||
import art.arcane.iris.engine.platform.PlatformChunkGenerator;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.World;
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package art.arcane.iris.core.agent;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.foreign.Arena;
|
||||
import java.lang.foreign.FunctionDescriptor;
|
||||
import java.lang.foreign.Linker;
|
||||
import java.lang.foreign.MemorySegment;
|
||||
import java.lang.foreign.ValueLayout;
|
||||
import java.lang.invoke.MethodHandle;
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assume.assumeFalse;
|
||||
|
||||
public class AttachSignalTest {
|
||||
private static final int SIGQUIT = 3;
|
||||
private static final int SIGTERM = 15;
|
||||
private static final long ACTION_BYTES = 256;
|
||||
private static final MethodHandle SIGACTION = Linker.nativeLinker().downcallHandle(
|
||||
Linker.nativeLinker().defaultLookup().find("sigaction").orElseThrow(),
|
||||
FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.ADDRESS));
|
||||
|
||||
@Test
|
||||
public void aConsoleThatResetsQuitGetsTheJvmHandlerBack() throws Throwable {
|
||||
assumeFalse(System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win"));
|
||||
long jvmHandler = handler(SIGTERM);
|
||||
assertNotEquals(0L, jvmHandler);
|
||||
try (Arena arena = Arena.ofConfined()) {
|
||||
MemorySegment original = arena.allocate(ACTION_BYTES);
|
||||
assertEquals(0, (int) SIGACTION.invokeExact(SIGQUIT, MemorySegment.NULL, original));
|
||||
try {
|
||||
MemorySegment reset = arena.allocate(ACTION_BYTES);
|
||||
assertEquals(0, (int) SIGACTION.invokeExact(SIGQUIT, reset, MemorySegment.NULL));
|
||||
assertEquals(0L, handler(SIGQUIT));
|
||||
|
||||
assertTrue(AttachSignal.restoreJvmHandler());
|
||||
|
||||
assertEquals(jvmHandler, handler(SIGQUIT));
|
||||
assertFalse(AttachSignal.restoreJvmHandler());
|
||||
} finally {
|
||||
assertEquals(0, (int) SIGACTION.invokeExact(SIGQUIT, original, MemorySegment.NULL));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static long handler(int signal) throws Throwable {
|
||||
try (Arena arena = Arena.ofConfined()) {
|
||||
MemorySegment action = arena.allocate(ACTION_BYTES);
|
||||
assertEquals(0, (int) SIGACTION.invokeExact(signal, MemorySegment.NULL, action));
|
||||
return action.get(ValueLayout.JAVA_LONG, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
-609
@@ -1,609 +0,0 @@
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.core.pack.BrokenPackException;
|
||||
import art.arcane.iris.core.runtime.StudioOpenCoordinator;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawPlanarArchetype;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioCellDimensions;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioLayout;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioMode;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioVariantCatalog;
|
||||
import art.arcane.iris.core.runtime.jigsaw.JigsawStudioWorkcellSpec;
|
||||
import art.arcane.iris.core.service.JigsawStudioService;
|
||||
import art.arcane.iris.core.structure.authoring.StructureBackend;
|
||||
import art.arcane.iris.core.structure.authoring.StructureCapability;
|
||||
import art.arcane.iris.core.structure.authoring.StructureHash;
|
||||
import art.arcane.iris.core.structure.authoring.StructureKey;
|
||||
import art.arcane.iris.core.structure.authoring.StructureOwnershipManifest;
|
||||
import art.arcane.iris.core.structure.authoring.StructureSource;
|
||||
import art.arcane.iris.core.structure.authoring.StructureTransactionWriter;
|
||||
import art.arcane.iris.core.structure.conversion.IrisStructureAdoptionInputKind;
|
||||
import art.arcane.iris.core.structure.export.VanillaJigsawExportFormat;
|
||||
import art.arcane.iris.core.tools.IrisCreator;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisDirection;
|
||||
import art.arcane.iris.engine.object.IrisJigsawConnector;
|
||||
import art.arcane.iris.engine.object.IrisJigsawPiece;
|
||||
import art.arcane.iris.engine.object.IrisObject;
|
||||
import art.arcane.iris.engine.object.IrisPosition;
|
||||
import art.arcane.iris.util.common.director.specialhandlers.IrisStructureHandler;
|
||||
import art.arcane.volmlib.util.director.DirectorOrigin;
|
||||
import art.arcane.volmlib.util.director.annotations.Director;
|
||||
import art.arcane.volmlib.util.director.annotations.Param;
|
||||
import art.arcane.volmlib.util.director.exceptions.DirectorParsingException;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Parameter;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletionException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CommandJigsawContractTest {
|
||||
@Rule
|
||||
public TemporaryFolder temporaryFolder = new TemporaryFolder();
|
||||
|
||||
@Test
|
||||
public void commandIrisRegistersJigsawTree() throws Exception {
|
||||
Field field = CommandIris.class.getDeclaredField("jigsaw");
|
||||
|
||||
assertEquals(CommandJigsaw.class, field.getType());
|
||||
assertNotNull(CommandJigsaw.class.getDeclaredField("piece"));
|
||||
assertNotNull(CommandJigsaw.class.getDeclaredField("pool"));
|
||||
assertNotNull(CommandJigsaw.class.getDeclaredField("connector"));
|
||||
assertNotNull(CommandJigsaw.class.getDeclaredField("variant"));
|
||||
assertNotNull(CommandJigsaw.class.getDeclaredField("workcell"));
|
||||
assertNotNull(CommandJigsaw.class.getDeclaredField("rules"));
|
||||
assertNotNull(CommandJigsaw.class.getDeclaredField("preview"));
|
||||
assertNotNull(CommandJigsaw.class.getDeclaredField("adopt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exposesStudioLifecycleAndAuthoringCommands() throws Exception {
|
||||
assertCommand("create", IrisDimension.class, String.class, String.class, String.class,
|
||||
int.class, int.class, int.class, long.class);
|
||||
assertCommand("convert", IrisDimension.class, String.class, String.class, long.class);
|
||||
assertCommand("open", IrisDimension.class, String.class, long.class);
|
||||
assertCommand("close", boolean.class);
|
||||
assertCommand("delete", boolean.class);
|
||||
assertCommand("status");
|
||||
assertCommand("menu");
|
||||
assertCommand("select");
|
||||
assertCommand("bounds", int.class, int.class, int.class);
|
||||
assertCommand("save", String.class);
|
||||
assertCommand("gotoBay", String.class);
|
||||
assertCommand("particles", boolean.class);
|
||||
assertCommand("export", String.class, String.class, String.class, boolean.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void jigsawStudioUsesItsDedicatedOpenLifecycle() {
|
||||
assertEquals(
|
||||
StudioOpenCoordinator.StudioOpenKind.JIGSAW,
|
||||
CommandJigsaw.STUDIO_OPEN_KIND);
|
||||
assertFalse(CommandJigsaw.STUDIO_OPEN_KIND.openWorkspace());
|
||||
assertFalse(CommandJigsaw.STUDIO_OPEN_KIND.teleportThroughStandardEntry());
|
||||
assertEquals(
|
||||
IrisCreator.DatapackPreparation.REUSE_LOADED_RUNTIME_IF_READY,
|
||||
CommandJigsaw.STUDIO_OPEN_KIND.datapackPreparation());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void packValidationDenialsAreExpectedOpenFailures() {
|
||||
BrokenPackException failure = new BrokenPackException(
|
||||
"overworld", List.of("Biome 'broken' has no resolvable regions."));
|
||||
|
||||
assertTrue(CommandJigsaw.isExpectedOpenDenial(failure));
|
||||
assertTrue(CommandJigsaw.isExpectedOpenDenial(
|
||||
new CompletionException(failure)));
|
||||
assertFalse(CommandJigsaw.isExpectedOpenDenial(
|
||||
new IllegalStateException("Unexpected Studio failure")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void committedActivationStartsInitialEvaluationBeforePlayerBinding() throws Exception {
|
||||
String source = Files.readString(Path.of(
|
||||
"src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n");
|
||||
int commit = source.indexOf("JigsawStudioActivation.commit(staged)");
|
||||
int evaluation = source.indexOf(
|
||||
"studioService.activationCommitted(world, request.requestId())",
|
||||
commit);
|
||||
int binding = source.indexOf("PLAYER_PACKS.put", evaluation);
|
||||
|
||||
assertTrue(commit >= 0);
|
||||
assertTrue(evaluation > commit);
|
||||
assertTrue(binding > evaluation);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void convertIsAddOnlyWorkflowWithAliasesAndDefaults() throws Exception {
|
||||
Method convert = CommandJigsaw.class.getDeclaredMethod(
|
||||
"convert", IrisDimension.class, String.class, String.class, long.class);
|
||||
Director command = convert.getAnnotation(Director.class);
|
||||
Parameter[] parameters = convert.getParameters();
|
||||
|
||||
assertEquals(List.of("import", "import-vanilla"), List.of(command.aliases()));
|
||||
assertParameter(parameters[2], "auto", null);
|
||||
assertParameter(parameters[3], "1337", null);
|
||||
NamespacedKey source = CommandJigsaw.parseRegisteredStructureKey("minecraft:village_plains");
|
||||
assertEquals("minecraft_village_plains", CommandJigsaw.resolveConversionTarget(source, "auto"));
|
||||
assertEquals("villages/plains", CommandJigsaw.resolveConversionTarget(source, "iris:villages/plains"));
|
||||
NamespacedKey ancientCity = CommandJigsaw.parseRegisteredStructureKey(
|
||||
"minecraft:ancient_city");
|
||||
assertEquals("minecraft_ancient_city",
|
||||
CommandJigsaw.resolveConversionTarget(ancientCity, "auto"));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> CommandJigsaw.resolveConversionTarget(source, "custom:village"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void adoptionCommandsExposeTwoStepPlanContract() throws Exception {
|
||||
Method inspect = CommandJigsaw.CommandJigsawAdopt.class.getDeclaredMethod(
|
||||
"inspect", IrisDimension.class, String.class, String.class, String.class);
|
||||
Method apply = CommandJigsaw.CommandJigsawAdopt.class.getDeclaredMethod("apply", String.class);
|
||||
Parameter[] inspectParameters = inspect.getParameters();
|
||||
|
||||
assertNotNull(inspect.getAnnotation(Director.class));
|
||||
assertNotNull(apply.getAnnotation(Director.class));
|
||||
assertParameter(inspectParameters[2], "auto", null);
|
||||
assertParameter(inspectParameters[3], "auto", CommandJigsaw.JigsawAdoptionStrategyHandler.class);
|
||||
assertEquals(CommandJigsaw.JigsawAdoptionPlanHandler.class,
|
||||
apply.getParameters()[0].getAnnotation(Param.class).customHandler());
|
||||
|
||||
CommandJigsaw.JigsawAdoptionStrategyHandler strategyHandler =
|
||||
new CommandJigsaw.JigsawAdoptionStrategyHandler();
|
||||
assertEquals(List.of("auto", "in-place", "clone"), strategyHandler.getPossibilities());
|
||||
assertEquals("in-place", strategyHandler.parse("claim", false));
|
||||
assertEquals("clone", strategyHandler.parse("copy", false));
|
||||
assertThrows(DirectorParsingException.class, () -> strategyHandler.parse("overwrite", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void adoptionInputKindUsesOnlyOwnershipProvenance() throws Exception {
|
||||
Path root = temporaryFolder.newFolder("adoption-provenance").toPath();
|
||||
|
||||
assertEquals(IrisStructureAdoptionInputKind.UNOWNED_IRIS,
|
||||
CommandJigsaw.adoptionInputKind(root, "unowned"));
|
||||
writeManifest(root, "datapack-created", StructureSource.Kind.DATAPACK,
|
||||
StructureOwnershipManifest.Provenance.created());
|
||||
assertEquals(IrisStructureAdoptionInputKind.UNOWNED_IRIS,
|
||||
CommandJigsaw.adoptionInputKind(root, "datapack-created"));
|
||||
writeManifest(root, "managed-provenance", StructureSource.Kind.IRIS, managedProvenance());
|
||||
assertEquals(IrisStructureAdoptionInputKind.MANAGED_DATAPACK,
|
||||
CommandJigsaw.adoptionInputKind(root, "managed-provenance"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void legacyGraphWritersShareTheServiceMutationContract() throws Exception {
|
||||
Method mutation = CommandJigsaw.class.getDeclaredMethod(
|
||||
"runGraphMutation",
|
||||
Player.class,
|
||||
CommandJigsaw.ActiveContext.class,
|
||||
JigsawStudioService.CommandGraphMutation.class);
|
||||
|
||||
assertEquals(boolean.class, mutation.getReturnType());
|
||||
assertNotNull(JigsawStudioService.CommandGraphMutation.class.getDeclaredMethod("run"));
|
||||
assertNotNull(JigsawStudioService.CommandGraphMutationResult.class.getDeclaredConstructor(
|
||||
JigsawStudioLayout.class,
|
||||
String.class,
|
||||
String.class,
|
||||
String.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exposesAutosaveDynamicEvaluationAndSelectedWorkcellResize() throws Exception {
|
||||
Method save = CommandJigsaw.class.getDeclaredMethod("save", String.class);
|
||||
Method status = CommandJigsaw.class.getDeclaredMethod("status");
|
||||
Method bounds = CommandJigsaw.class.getDeclaredMethod(
|
||||
"bounds", int.class, int.class, int.class);
|
||||
|
||||
assertEquals("Flush the automatic save for a workcell now",
|
||||
save.getAnnotation(Director.class).description());
|
||||
assertEquals("Show active Jigsaw Studio and dynamic evaluation state",
|
||||
status.getAnnotation(Director.class).description());
|
||||
assertEquals("Set the selected Studio workcell capacity",
|
||||
bounds.getAnnotation(Director.class).description());
|
||||
assertThrows(NoSuchMethodException.class,
|
||||
() -> CommandJigsaw.class.getDeclaredMethod("validate"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createDefaultsToPlanarIrisWithCompleteCellAndSeedDefaults() throws Exception {
|
||||
Method create = CommandJigsaw.class.getDeclaredMethod(
|
||||
"create",
|
||||
IrisDimension.class,
|
||||
String.class,
|
||||
String.class,
|
||||
String.class,
|
||||
int.class,
|
||||
int.class,
|
||||
int.class,
|
||||
long.class);
|
||||
Parameter[] parameters = create.getParameters();
|
||||
|
||||
assertParameter(parameters[2], "planar", CommandJigsaw.JigsawModeHandler.class);
|
||||
assertParameter(parameters[3], "iris", CommandJigsaw.JigsawCompatibilityHandler.class);
|
||||
assertParameter(parameters[4], "15", null);
|
||||
assertParameter(parameters[5], "15", null);
|
||||
assertParameter(parameters[6], "15", null);
|
||||
assertParameter(parameters[7], "1337", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void structureKeysExplainTheirResourceAndOpenSupportsEditingAliases() throws Exception {
|
||||
Method create = CommandJigsaw.class.getDeclaredMethod(
|
||||
"create",
|
||||
IrisDimension.class,
|
||||
String.class,
|
||||
String.class,
|
||||
String.class,
|
||||
int.class,
|
||||
int.class,
|
||||
int.class,
|
||||
long.class);
|
||||
Method open = CommandJigsaw.class.getDeclaredMethod(
|
||||
"open", IrisDimension.class, String.class, long.class);
|
||||
Param createKey = create.getParameters()[1].getAnnotation(Param.class);
|
||||
Param openKey = open.getParameters()[1].getAnnotation(Param.class);
|
||||
Director openCommand = open.getAnnotation(Director.class);
|
||||
|
||||
assertEquals("key", createKey.name());
|
||||
assertEquals(List.of("structure", "name"), List.of(createKey.aliases()));
|
||||
assertEquals("New key written as structures/<key>.json", createKey.description());
|
||||
assertEquals("key", openKey.name());
|
||||
assertEquals(List.of("structure", "name"), List.of(openKey.aliases()));
|
||||
assertEquals("Existing key loaded from structures/<key>.json", openKey.description());
|
||||
assertEquals(IrisStructureHandler.class, openKey.customHandler());
|
||||
assertEquals(List.of("edit", "reopen"), List.of(openCommand.aliases()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void createChoiceHandlersExposeCanonicalCompletionsAndRetainAliases() throws Exception {
|
||||
CommandJigsaw.JigsawModeHandler modeHandler = new CommandJigsaw.JigsawModeHandler();
|
||||
CommandJigsaw.JigsawCompatibilityHandler compatibilityHandler =
|
||||
new CommandJigsaw.JigsawCompatibilityHandler();
|
||||
|
||||
assertEquals(List.of("planar", "spatial"), modeHandler.getPossibilities());
|
||||
assertEquals("planar", modeHandler.parse("2d", false));
|
||||
assertEquals("spatial", modeHandler.parse("3d", false));
|
||||
assertEquals(List.of("iris", "vanilla"), compatibilityHandler.getPossibilities());
|
||||
assertEquals("iris", compatibilityHandler.parse("extended", false));
|
||||
assertEquals("vanilla", compatibilityHandler.parse("portable", false));
|
||||
assertThrows(DirectorParsingException.class, () -> modeHandler.parse("volume", false));
|
||||
assertThrows(DirectorParsingException.class, () -> compatibilityHandler.parse("mixed", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exposesNestedPieceVariantAndPreviewCommands() throws Exception {
|
||||
assertNotNull(CommandJigsaw.CommandJigsawPool.class
|
||||
.getDeclaredMethod("create", String.class, String.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawConnector.class
|
||||
.getDeclaredMethod("channel", String.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
|
||||
.getDeclaredMethod("create", String.class, String.class, int.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
|
||||
.getDeclaredMethod("add", String.class, String.class, int.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
|
||||
.getDeclaredMethod("remove", String.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
|
||||
.getDeclaredMethod("rotatable", boolean.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawPiece.class
|
||||
.getDeclaredMethod("expand")
|
||||
.getAnnotation(Director.class));
|
||||
assertEquals("Resize the selected piece object exactly to workcell capacity",
|
||||
CommandJigsaw.CommandJigsawPiece.class
|
||||
.getDeclaredMethod("expand")
|
||||
.getAnnotation(Director.class)
|
||||
.description());
|
||||
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
|
||||
.getDeclaredMethod("weight", String.class, int.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
|
||||
.getDeclaredMethod("resize", int.class, int.class, int.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
|
||||
.getDeclaredMethod("label", String.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
|
||||
.getDeclaredMethod("labelReset")
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawVariant.class
|
||||
.getDeclaredMethod("duplicate")
|
||||
.getAnnotation(Director.class));
|
||||
Method duplicateFamily = CommandJigsaw.CommandJigsawVariant.class
|
||||
.getDeclaredMethod("duplicateFamily", String.class);
|
||||
assertNotNull(duplicateFamily.getAnnotation(Director.class));
|
||||
assertParameter(duplicateFamily.getParameters()[0], "next", null);
|
||||
assertNotNull(CommandJigsaw.CommandJigsawWorkcell.class
|
||||
.getDeclaredMethod("capacity", int.class, int.class, int.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawWorkcell.class
|
||||
.getDeclaredMethod("label", String.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawWorkcell.class
|
||||
.getDeclaredMethod("labelReset")
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawRules.class
|
||||
.getDeclaredMethod("limits", int.class, int.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawRules.class
|
||||
.getDeclaredMethod("fallback", String.class, String.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawPreview.class
|
||||
.getDeclaredMethod("assemble", long.class)
|
||||
.getAnnotation(Director.class));
|
||||
assertNotNull(CommandJigsaw.CommandJigsawPreview.class
|
||||
.getDeclaredMethod("gotoPreview")
|
||||
.getAnnotation(Director.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void pieceCreateUsesResolvedWorkcellCapacityInsteadOfLayoutDefault() throws Exception {
|
||||
String source = Files.readString(Path.of(
|
||||
"src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n");
|
||||
int pieceCommands = source.indexOf("public static class CommandJigsawPiece");
|
||||
int create = source.indexOf("public void create(", pieceCommands);
|
||||
int add = source.indexOf("public void add(", create);
|
||||
String createSource = source.substring(create, add);
|
||||
|
||||
assertTrue(createSource.contains("targetWorkcell = contextual;"));
|
||||
assertTrue(createSource.contains("JigsawStudioCellDimensions dimensions = targetWorkcell.capacity();"));
|
||||
assertFalse(createSource.contains("layout().cellDimensions()"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void pieceAddUsesCanonicalAxesForRotatedRectangularPlanarWorkcells() {
|
||||
JigsawStudioLayout layout = nonuniformPlanarLayout();
|
||||
IrisJigsawPiece eastEnd = new IrisJigsawPiece();
|
||||
eastEnd.getConnectors().add(new IrisJigsawConnector().setDirection(IrisDirection.EAST_POSITIVE_X));
|
||||
IrisObject exactObject = new IrisObject(7, 5, 13);
|
||||
|
||||
CommandJigsaw.PieceWorkcellResolution exact = CommandJigsaw.resolvePieceWorkcell(
|
||||
layout,
|
||||
eastEnd,
|
||||
exactObject);
|
||||
CommandJigsaw.PieceWorkcellResolution oversized = CommandJigsaw.resolvePieceWorkcell(
|
||||
layout,
|
||||
eastEnd,
|
||||
new IrisObject(8, 5, 13));
|
||||
|
||||
assertEquals(JigsawPlanarArchetype.END.stableId(), exact.workcell().stableId());
|
||||
assertEquals(new IrisPosition(13, 5, 7), exact.requiredDimensions());
|
||||
assertEquals(new JigsawStudioCellDimensions(13, 5, 7), exact.workcell().capacity());
|
||||
assertTrue(exact.fits());
|
||||
assertTrue(exactObject.getD() > exact.workcell().capacity().depth());
|
||||
assertFalse(oversized.fits());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void pieceAddKeepsRawObjectAxesForSpatialWorkcells() {
|
||||
JigsawStudioCellDimensions capacity = new JigsawStudioCellDimensions(7, 5, 13);
|
||||
JigsawStudioLayout layout = JigsawStudioLayout.create(
|
||||
JigsawStudioMode.SPATIAL_JIGSAW,
|
||||
capacity,
|
||||
JigsawStudioVariantCatalog.empty());
|
||||
IrisJigsawPiece spatialPiece = new IrisJigsawPiece();
|
||||
spatialPiece.getConnectors().add(
|
||||
new IrisJigsawConnector().setDirection(IrisDirection.EAST_POSITIVE_X));
|
||||
|
||||
CommandJigsaw.PieceWorkcellResolution resolution = CommandJigsaw.resolvePieceWorkcell(
|
||||
layout,
|
||||
spatialPiece,
|
||||
new IrisObject(7, 5, 13));
|
||||
|
||||
assertEquals(JigsawStudioLayout.SPATIAL_WORKCELL_ID, resolution.workcell().stableId());
|
||||
assertEquals(new IrisPosition(7, 5, 13), resolution.requiredDimensions());
|
||||
assertEquals(capacity, resolution.workcell().capacity());
|
||||
assertTrue(resolution.fits());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void everyExecutableCommandRejectsNonPlayerOrigins() {
|
||||
Class<?>[] commandTypes = {
|
||||
CommandJigsaw.class,
|
||||
CommandJigsaw.CommandJigsawConnector.class,
|
||||
CommandJigsaw.CommandJigsawPool.class,
|
||||
CommandJigsaw.CommandJigsawPiece.class,
|
||||
CommandJigsaw.CommandJigsawVariant.class,
|
||||
CommandJigsaw.CommandJigsawWorkcell.class,
|
||||
CommandJigsaw.CommandJigsawRules.class,
|
||||
CommandJigsaw.CommandJigsawPreview.class,
|
||||
CommandJigsaw.CommandJigsawAdopt.class
|
||||
};
|
||||
|
||||
for (Class<?> commandType : commandTypes) {
|
||||
for (Method method : commandType.getDeclaredMethods()) {
|
||||
Director director = method.getAnnotation(Director.class);
|
||||
if (director != null) {
|
||||
assertEquals(method.toString(), DirectorOrigin.PLAYER, director.origin());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exportOutputIsOneSafeChildArtifact() {
|
||||
Path root = Path.of("build", "jigsaw-exports").toAbsolutePath().normalize();
|
||||
|
||||
assertEquals(root.resolve("village.zip"), CommandJigsaw.resolveExportDestination(
|
||||
root, "village", VanillaJigsawExportFormat.ZIP));
|
||||
assertEquals(root.resolve("village"), CommandJigsaw.resolveExportDestination(
|
||||
root, "village", VanillaJigsawExportFormat.DIRECTORY));
|
||||
assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination(
|
||||
root, "", VanillaJigsawExportFormat.DIRECTORY));
|
||||
assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination(
|
||||
root, ".", VanillaJigsawExportFormat.DIRECTORY));
|
||||
assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination(
|
||||
root, "../all-exports", VanillaJigsawExportFormat.DIRECTORY));
|
||||
assertThrows(IllegalArgumentException.class, () -> CommandJigsaw.resolveExportDestination(
|
||||
root, "nested/export", VanillaJigsawExportFormat.DIRECTORY));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exportLeaseRejectsDuplicatePlayerAndDestination() {
|
||||
UUID firstPlayer = UUID.randomUUID();
|
||||
UUID secondPlayer = UUID.randomUUID();
|
||||
Path firstDestination = Path.of("build", "jigsaw-exports", "first.zip");
|
||||
Path secondDestination = Path.of("build", "jigsaw-exports", "second.zip");
|
||||
|
||||
assertEquals(true, CommandJigsaw.beginExport(firstPlayer, firstDestination));
|
||||
try {
|
||||
assertEquals(false, CommandJigsaw.beginExport(firstPlayer, secondDestination));
|
||||
assertEquals(false, CommandJigsaw.beginExport(secondPlayer, firstDestination));
|
||||
} finally {
|
||||
CommandJigsaw.finishExport(firstPlayer, firstDestination);
|
||||
}
|
||||
|
||||
assertEquals(true, CommandJigsaw.beginExport(secondPlayer, firstDestination));
|
||||
CommandJigsaw.finishExport(secondPlayer, firstDestination);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exportStartFailuresHavePreciseOperatorMessages() {
|
||||
assertEquals("The active Jigsaw Studio is no longer available.",
|
||||
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.NOT_ACTIVE));
|
||||
assertEquals("Only the Jigsaw Studio owner can export this project.",
|
||||
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.NOT_OWNER));
|
||||
assertEquals("Wait for the pending autosave or discard the edits before exporting the on-disk graph.",
|
||||
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.DIRTY));
|
||||
assertEquals("The active Jigsaw Studio is closing and cannot be exported.",
|
||||
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.CLOSING));
|
||||
assertEquals("Wait for the current Jigsaw Studio save to finish before exporting.",
|
||||
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.SAVE_IN_PROGRESS));
|
||||
assertEquals("Wait for the current Jigsaw Studio operation to finish before exporting.",
|
||||
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.OPERATION_IN_PROGRESS));
|
||||
assertEquals("A Jigsaw Studio export is already in progress.",
|
||||
CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.IN_PROGRESS));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> CommandJigsaw.exportStartError(JigsawStudioService.ExportStart.STARTED));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exportLeaseReleaseActionRunsExactlyOnce() {
|
||||
AtomicInteger releases = new AtomicInteger();
|
||||
CommandJigsaw.ExportLease lease = new CommandJigsaw.ExportLease(releases::incrementAndGet);
|
||||
|
||||
lease.release();
|
||||
lease.release();
|
||||
|
||||
assertEquals(1, releases.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void exportSourceAcquiresStudioLeaseBeforeStaticLeaseAndReleasesBothPaths() throws Exception {
|
||||
String source = Files.readString(Path.of(
|
||||
"src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n");
|
||||
int serviceLease = source.indexOf("studioService.tryBeginExport(requestId, playerId)");
|
||||
int staticLease = source.indexOf("beginExport(playerId, destination)", serviceLease);
|
||||
int dispatch = source.indexOf("J.a(() -> runExport(operation))", staticLease);
|
||||
int schedulingRelease = source.indexOf("operation.lease().release()", dispatch);
|
||||
int exporter = source.indexOf("new VanillaJigsawDatapackExporter().export(operation.request())", dispatch);
|
||||
int completionRelease = source.indexOf("operation.lease().release()", exporter);
|
||||
|
||||
assertTrue(serviceLease >= 0);
|
||||
assertTrue(staticLease > serviceLease);
|
||||
assertTrue(dispatch > staticLease);
|
||||
assertTrue(schedulingRelease > dispatch);
|
||||
assertTrue(exporter > schedulingRelease);
|
||||
assertTrue(completionRelease > exporter);
|
||||
}
|
||||
|
||||
private static void assertCommand(String name, Class<?>... parameterTypes) throws Exception {
|
||||
Method method = CommandJigsaw.class.getDeclaredMethod(name, parameterTypes);
|
||||
assertNotNull(method.getAnnotation(Director.class));
|
||||
}
|
||||
|
||||
private static JigsawStudioLayout nonuniformPlanarLayout() {
|
||||
List<JigsawStudioWorkcellSpec> workcells = List.of(
|
||||
workcell(JigsawPlanarArchetype.BLANK, 3, 1, 3),
|
||||
workcell(JigsawPlanarArchetype.END, 13, 5, 7),
|
||||
workcell(JigsawPlanarArchetype.STRAIGHT, 5, 2, 11),
|
||||
workcell(JigsawPlanarArchetype.CORNER, 9, 3, 6),
|
||||
workcell(JigsawPlanarArchetype.TEE, 12, 4, 8),
|
||||
workcell(JigsawPlanarArchetype.CROSS, 10, 6, 10));
|
||||
return JigsawStudioLayout.createPlanar(
|
||||
new JigsawStudioCellDimensions(3, 1, 3),
|
||||
workcells,
|
||||
JigsawStudioVariantCatalog.empty());
|
||||
}
|
||||
|
||||
private static JigsawStudioWorkcellSpec workcell(
|
||||
JigsawPlanarArchetype archetype,
|
||||
int width,
|
||||
int height,
|
||||
int depth
|
||||
) {
|
||||
return new JigsawStudioWorkcellSpec(
|
||||
archetype,
|
||||
"",
|
||||
new JigsawStudioCellDimensions(width, height, depth),
|
||||
true);
|
||||
}
|
||||
|
||||
private static void assertParameter(Parameter parameter, String defaultValue, Class<?> customHandler) {
|
||||
Param annotation = parameter.getAnnotation(Param.class);
|
||||
|
||||
assertNotNull(annotation);
|
||||
assertEquals(defaultValue, annotation.defaultValue());
|
||||
if (customHandler != null) {
|
||||
assertEquals(customHandler, annotation.customHandler());
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeManifest(
|
||||
Path root,
|
||||
String structure,
|
||||
StructureSource.Kind sourceKind,
|
||||
StructureOwnershipManifest.Provenance provenance
|
||||
) throws Exception {
|
||||
StructureKey structureKey = new StructureKey("iris", structure);
|
||||
StructureOwnershipManifest manifest = new StructureOwnershipManifest(
|
||||
StructureOwnershipManifest.CURRENT_SCHEMA_VERSION,
|
||||
structureKey,
|
||||
StructureSource.of(sourceKind, new StructureKey("iris", "source/" + structure)),
|
||||
StructureBackend.IRIS_ASSEMBLY,
|
||||
List.of(StructureCapability.BLOCKS, StructureCapability.CONNECTORS),
|
||||
List.of(),
|
||||
Map.of("structures/" + structure + ".json", StructureHash.sha256(
|
||||
structure.getBytes(StandardCharsets.UTF_8))),
|
||||
provenance);
|
||||
Path manifestPath = new StructureTransactionWriter(root).ownershipManifestPath(structureKey);
|
||||
Files.createDirectories(manifestPath.getParent());
|
||||
Files.write(manifestPath, manifest.toJson());
|
||||
}
|
||||
|
||||
private static StructureOwnershipManifest.Provenance managedProvenance() {
|
||||
String path = "structures/source.json";
|
||||
String hash = StructureHash.sha256("source".getBytes(StandardCharsets.UTF_8));
|
||||
return new StructureOwnershipManifest.Provenance(
|
||||
StructureOwnershipManifest.Origin.MANAGED_DATAPACK,
|
||||
UUID.randomUUID().toString(),
|
||||
StructureHash.sha256("plan".getBytes(StandardCharsets.UTF_8)),
|
||||
StructureHash.sha256("closure".getBytes(StandardCharsets.UTF_8)),
|
||||
1L,
|
||||
Map.of(path, hash),
|
||||
Map.of(path, path),
|
||||
StructureOwnershipManifest.RollbackDisposition.NONE);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.IObjectPlacer;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.placement.IObjectPlacer;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.block.Block;
|
||||
import org.bukkit.block.data.BlockData;
|
||||
|
||||
+10
-1
@@ -1,6 +1,6 @@
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.util.common.director.specialhandlers.NullableDimensionHandler;
|
||||
import art.arcane.volmlib.util.director.annotations.Director;
|
||||
import art.arcane.volmlib.util.director.annotations.Param;
|
||||
@@ -27,6 +27,15 @@ public class CommandStudioCreationContractTest {
|
||||
assertEquals(NullableDimensionHandler.class, template.customHandler());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void editorDimensionIsOptionalSoTheOpenStudioCanBeUsed() throws NoSuchMethodException {
|
||||
Method command = CommandStudio.class.getDeclaredMethod("editor", IrisDimension.class);
|
||||
Param dimension = command.getParameters()[0].getAnnotation(Param.class);
|
||||
|
||||
assertEquals("null", dimension.defaultValue());
|
||||
assertEquals(NullableDimensionHandler.class, dimension.customHandler());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void openExposesAnOptInForceFlag() throws NoSuchMethodException {
|
||||
Method command = CommandStudio.class.getDeclaredMethod(
|
||||
|
||||
+24
-77
@@ -1,8 +1,7 @@
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy;
|
||||
import art.arcane.iris.engine.object.IrisNativeStructureDecision;
|
||||
import art.arcane.iris.engine.object.NativeStructureGenerationStatus;
|
||||
import art.arcane.iris.engine.framework.NativeStructureGenerationStatus;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
@@ -20,9 +19,9 @@ public class IrisStructureLocateCommandContractTest {
|
||||
public void findReportsDensityLimitAndUsesExactLocatedOrigin() throws IOException {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.commandFindSource")));
|
||||
|
||||
assertTrue(source.contains("LocateStatus.SEARCH_LIMIT_REACHED"));
|
||||
assertTrue(source.contains("StructureSearch.Outcome.SEARCH_LIMIT_REACHED"));
|
||||
assertTrue(source.contains("the density search safety limit was reached"));
|
||||
assertTrue(source.contains("result.originX(), result.baseY(), result.originZ()"));
|
||||
assertTrue(source.contains("new Location(targetWorld, result.x(), result.y(), result.z())"));
|
||||
assertFalse(source.contains("at[0] + 8"));
|
||||
assertFalse(source.contains("at[2] + 8"));
|
||||
}
|
||||
@@ -36,9 +35,9 @@ public class IrisStructureLocateCommandContractTest {
|
||||
int nativeResolution = method.indexOf("resolveNativeStructure(structureKey)");
|
||||
int policyResolution = method.indexOf("NativeStructureGenerationPolicy.resolve(", nativeResolution);
|
||||
int nativeLocatableCheck = method.indexOf(
|
||||
"IrisStructureLocator.hasLocatableNativePlacement(e, structureKey)", policyResolution);
|
||||
"ModuleServices.canLocateStart(e, structureKey)", policyResolution);
|
||||
int editableLocatableCheck = method.indexOf(
|
||||
"IrisStructureLocator.hasLocatableEditablePlacement(e, structureKey)", nativeLocatableCheck);
|
||||
"ModuleServices.canLocateStructure(e, structureKey)", nativeLocatableCheck);
|
||||
int worldGenerationCheck = method.indexOf("targetWorld.canGenerateStructures()", editableLocatableCheck);
|
||||
int routeResolution = method.indexOf("selectStructureLookupRoute(", editableLocatableCheck);
|
||||
int nativeLocate = method.indexOf("targetWorld.locateNearestStructure(", routeResolution);
|
||||
@@ -50,7 +49,7 @@ public class IrisStructureLocateCommandContractTest {
|
||||
assertTrue(worldGenerationCheck > editableLocatableCheck);
|
||||
assertTrue(routeResolution > editableLocatableCheck);
|
||||
assertTrue(nativeLocate > routeResolution);
|
||||
assertFalse(method.contains("IrisStructureLocator.isPlaced(e, structureKey)"));
|
||||
assertFalse(method.contains("ModuleServices.placesStructure(e, structureKey)"));
|
||||
assertFalse(method.contains("NativeStructureLocateCapability"));
|
||||
}
|
||||
|
||||
@@ -64,11 +63,11 @@ public class IrisStructureLocateCommandContractTest {
|
||||
false, null, false, false, false, true, true));
|
||||
assertEquals(CommandFind.StructureLookupRoute.NO_ACTIVE_PLACEMENT,
|
||||
CommandFind.selectStructureLookupRoute(
|
||||
true, decision(NativeStructureGenerationStatus.REPLACED_BY_IRIS),
|
||||
true, NativeStructureGenerationStatus.REPLACED_BY_IRIS,
|
||||
false, false, false, true, true));
|
||||
assertEquals(CommandFind.StructureLookupRoute.NO_ACTIVE_PLACEMENT,
|
||||
CommandFind.selectStructureLookupRoute(
|
||||
true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE),
|
||||
true, NativeStructureGenerationStatus.GENERATE_NATIVE,
|
||||
true, false, false, true, false));
|
||||
}
|
||||
|
||||
@@ -79,7 +78,7 @@ public class IrisStructureLocateCommandContractTest {
|
||||
false, null, false, false, true, false, false));
|
||||
assertEquals(CommandFind.StructureLookupRoute.IRIS,
|
||||
CommandFind.selectStructureLookupRoute(
|
||||
true, decision(NativeStructureGenerationStatus.REPLACED_BY_IRIS),
|
||||
true, NativeStructureGenerationStatus.REPLACED_BY_IRIS,
|
||||
false, false, true, false, false));
|
||||
}
|
||||
|
||||
@@ -87,23 +86,23 @@ public class IrisStructureLocateCommandContractTest {
|
||||
public void findRequiresWorldGenerationAndReachabilityForNativeRoutes() {
|
||||
assertEquals(CommandFind.StructureLookupRoute.WORLD_DISABLED,
|
||||
CommandFind.selectStructureLookupRoute(
|
||||
true, decision(NativeStructureGenerationStatus.REPLACED_BY_IRIS),
|
||||
true, NativeStructureGenerationStatus.REPLACED_BY_IRIS,
|
||||
true, true, false, false, true));
|
||||
assertEquals(CommandFind.StructureLookupRoute.WORLD_DISABLED,
|
||||
CommandFind.selectStructureLookupRoute(
|
||||
true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE),
|
||||
true, NativeStructureGenerationStatus.GENERATE_NATIVE,
|
||||
false, false, false, false, true));
|
||||
assertEquals(CommandFind.StructureLookupRoute.UNREACHABLE,
|
||||
CommandFind.selectStructureLookupRoute(
|
||||
true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE),
|
||||
true, NativeStructureGenerationStatus.GENERATE_NATIVE,
|
||||
false, false, false, true, false));
|
||||
assertEquals(CommandFind.StructureLookupRoute.NATIVE,
|
||||
CommandFind.selectStructureLookupRoute(
|
||||
true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE),
|
||||
true, NativeStructureGenerationStatus.GENERATE_NATIVE,
|
||||
true, true, false, true, false));
|
||||
assertEquals(CommandFind.StructureLookupRoute.NATIVE,
|
||||
CommandFind.selectStructureLookupRoute(
|
||||
true, decision(NativeStructureGenerationStatus.GENERATE_NATIVE),
|
||||
true, NativeStructureGenerationStatus.GENERATE_NATIVE,
|
||||
true, false, false, true, true));
|
||||
}
|
||||
|
||||
@@ -111,14 +110,14 @@ public class IrisStructureLocateCommandContractTest {
|
||||
public void findHonorsPackDisableBeforePlacementRouting() {
|
||||
assertEquals(CommandFind.StructureLookupRoute.POLICY_DISABLED,
|
||||
CommandFind.selectStructureLookupRoute(
|
||||
true, decision(NativeStructureGenerationStatus.DISABLED_BY_PACK),
|
||||
true, NativeStructureGenerationStatus.DISABLED_BY_PACK,
|
||||
false, false, true, true, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unregisteredDiagnosticExplainsEveryRejectedRoute() {
|
||||
assertEquals(
|
||||
"Native structure minecraft:village is disabled by this dimension's importedStructures settings.",
|
||||
"Native structure minecraft:village is not imported by this dimension's importedStructures settings or is disabled by a module of the pack.",
|
||||
CommandFind.describeStructureExclusion(
|
||||
CommandFind.StructureLookupRoute.POLICY_DISABLED, "minecraft:village",
|
||||
NativeStructureGenerationStatus.DISABLED_BY_PACK,
|
||||
@@ -205,16 +204,16 @@ public class IrisStructureLocateCommandContractTest {
|
||||
assertTrue(method.contains("non-generating structure candidate(s) and their reasons to the server console"));
|
||||
assertTrue(method.contains("no chunks were searched"));
|
||||
assertTrue(method.indexOf("DatapackIngestService.installed()") > method.indexOf("J.a(() ->"));
|
||||
assertTrue(source.contains("engine.getDimension().getDatapackImports()"));
|
||||
assertTrue(source.contains("DatapackIngestService.configuredImports(engine.getDimension())"));
|
||||
assertTrue(source.contains("snapshot.configuredImportUrls().contains(importUrl)"));
|
||||
assertTrue(source.contains("engine.getData().getStructureLoader().getPossibleKeys()"));
|
||||
assertTrue(source.contains("ModuleServices.structureKeys(engine.getData())"));
|
||||
assertFalse(method.contains("commandSender.sendMessage(exclusion"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void findNativePolicyMessagesMatchModdedDiagnostics() {
|
||||
assertEquals(
|
||||
"Native structure minecraft:village_plains is disabled by this dimension's importedStructures settings.",
|
||||
"Native structure minecraft:village_plains is not imported by this dimension's importedStructures settings or is disabled by a module of the pack.",
|
||||
NativeStructureGenerationPolicy.generationStatusMessage(
|
||||
"minecraft:village_plains", NativeStructureGenerationStatus.DISABLED_BY_PACK));
|
||||
assertEquals(
|
||||
@@ -227,28 +226,16 @@ public class IrisStructureLocateCommandContractTest {
|
||||
"minecraft:stronghold", NativeStructureGenerationStatus.GENERATE_NATIVE));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void structureVerifyReportsDensityLimitAndUsesExactLocatedOrigin() throws IOException {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.commandStructureSource")));
|
||||
|
||||
assertTrue(source.contains("[iris-search-limit]"));
|
||||
assertTrue(source.contains("density searches safety-limited"));
|
||||
assertTrue(source.contains("result.originX() + \",\" + result.baseY() + \",\" + result.originZ()"));
|
||||
assertFalse(source.contains("at[0] + 8"));
|
||||
assertFalse(source.contains("at[2] + 8"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bulkStructureImportRestrictsCaptureWithoutChangingStandaloneCapture() throws IOException {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.commandStructureSource")));
|
||||
int importStart = source.indexOf("public void importAll(");
|
||||
int importEnd = source.indexOf("@Director(name = \"capture\"", importStart);
|
||||
int captureStart = source.indexOf("public void capture(", importEnd);
|
||||
int captureEnd = source.indexOf("@Director(description = \"Verify", captureStart);
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.importCommandsSource")));
|
||||
int importStart = source.indexOf("private static void runImportAll(");
|
||||
int captureStart = source.indexOf("private static void runCapture(", importStart);
|
||||
int importEnd = captureStart;
|
||||
int captureEnd = source.length();
|
||||
|
||||
assertTrue(importStart >= 0);
|
||||
assertTrue(importEnd > importStart);
|
||||
assertTrue(captureStart > importEnd);
|
||||
assertTrue(captureEnd > captureStart);
|
||||
String importMethod = source.substring(importStart, importEnd);
|
||||
String captureMethod = source.substring(captureStart, captureEnd);
|
||||
@@ -257,44 +244,4 @@ public class IrisStructureLocateCommandContractTest {
|
||||
assertFalse(importMethod.contains("StructureCaptureImporter.importAllStructures("));
|
||||
assertTrue(captureMethod.contains("StructureCaptureImporter.importAllStructures("));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void structurePlaceSeparatesPackContentFromTargetWorldEngine() throws IOException {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.commandStructureSource")));
|
||||
int methodStart = source.indexOf("public void place(");
|
||||
assertTrue(methodStart >= 0);
|
||||
String method = source.substring(methodStart);
|
||||
assertTrue(method.contains("IrisData data = dimension.getLoader()"));
|
||||
assertTrue(method.contains("PlatformChunkGenerator targetGenerator = IrisToolbelt.access(targetWorld)"));
|
||||
assertTrue(method.contains("CommandObject.createPlacer(targetWorld, future, targetEngine)"));
|
||||
assertTrue(method.contains("if (blockChanges == 0)"));
|
||||
assertTrue(method.contains("COMMAND_STRUCTURE_PLACEMENT_CHANGED_NO_BLOCKS"));
|
||||
Path structureSource = Path.of(System.getProperty("iris.commandStructureSource"));
|
||||
String objectSource = Files.readString(structureSource.resolveSibling("CommandObject.java"));
|
||||
assertTrue(objectSource.contains("futureBlockChanges.putIfAbsent(block, block.getBlockData())"));
|
||||
assertFalse(method.contains("data.getEngine()"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void structureVerifyPartitionsPolicyBeforeNativeReachability() throws IOException {
|
||||
String source = Files.readString(Path.of(System.getProperty("iris.commandStructureSource")));
|
||||
int methodStart = source.indexOf("private void runVerification(");
|
||||
int methodEnd = source.indexOf("private void sendVerificationMessages(", methodStart);
|
||||
String method = source.substring(methodStart, methodEnd);
|
||||
int policyResolution = method.indexOf("NativeStructureGenerationPolicy.resolve(engine, keyName, false)");
|
||||
int nativeRequirement = method.indexOf(
|
||||
"requiresNativeReachability |= !IrisStructureLocator.isPlaced", policyResolution);
|
||||
int reachabilityGuard = method.indexOf("if (requiresNativeReachability)", nativeRequirement);
|
||||
int reachabilityLookup = method.indexOf("StructureReachability.reachableKeys(engine)", reachabilityGuard);
|
||||
|
||||
assertTrue(policyResolution >= 0);
|
||||
assertTrue(nativeRequirement > policyResolution);
|
||||
assertTrue(reachabilityGuard > nativeRequirement);
|
||||
assertTrue(reachabilityLookup > reachabilityGuard);
|
||||
}
|
||||
|
||||
private static IrisNativeStructureDecision decision(NativeStructureGenerationStatus status) {
|
||||
return new IrisNativeStructureDecision(
|
||||
status, 0, null, false, null, null);
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
package art.arcane.iris.core.commands;
|
||||
|
||||
import art.arcane.iris.engine.object.IrisObject;
|
||||
import art.arcane.iris.engine.object.IrisObjectRotation;
|
||||
import art.arcane.iris.engine.object.prefab.ObjectTurn;
|
||||
import art.arcane.iris.engine.object.prefab.IrisObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
@@ -48,6 +48,6 @@ public class ObjectPasteBoundsTest {
|
||||
|
||||
private ObjectPasteBounds resolve(int rotation) {
|
||||
IrisObject object = new IrisObject(4, 3, 2);
|
||||
return ObjectPasteBounds.resolve(object, IrisObjectRotation.of(0, rotation, 0), ANCHOR_X, ANCHOR_Y, ANCHOR_Z);
|
||||
return ObjectPasteBounds.resolve(object, ObjectTurn.of(0, rotation, 0), ANCHOR_X, ANCHOR_Y, ANCHOR_Z);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package art.arcane.iris.core.gui;
|
||||
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.IrisWorld;
|
||||
import art.arcane.iris.engine.object.world.IrisWorld;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.platform.bukkit.BukkitWorldBinding;
|
||||
import art.arcane.iris.util.common.scheduling.J;
|
||||
|
||||
+1
-1
@@ -85,7 +85,7 @@ public class IrisPapiLifecycleTest {
|
||||
String source = source();
|
||||
|
||||
assertTrue("onDisable must tear the expansion down",
|
||||
source.contains("public void onDisable() {\n teardownPapi();"));
|
||||
source.contains("public void onDisable() {\n pendingWorldReplacements.awaitStagingForShutdown();\n teardownPapi();"));
|
||||
assertTrue("the BileTools pre-unload hook must tear the expansion down",
|
||||
source.contains("public void onPreUnload(ReloadAware.PreUnloadReason reason) {\n teardownPapi();"));
|
||||
}
|
||||
|
||||
+5
-2
@@ -32,7 +32,7 @@ public class BukkitEngineLifecycleContractTest {
|
||||
assertTrue(baseHeight.contains("IrisContext.open(currentEngine, lease.sessionId(), null)"));
|
||||
assertTrue(baseHeight.contains("catch (GenerationSessionException e)"));
|
||||
|
||||
String generation = method(source, "public void generateNoise(");
|
||||
String generation = method(source, "private void generateNoiseChunk(");
|
||||
assertTrue(generation.contains("throw new IllegalStateException"));
|
||||
assertTrue(generation.contains("engine.acquireGenerationLease(\"bukkit_terrain_stage\")"));
|
||||
assertTrue(generation.contains("IrisContext.open(engine, lease.sessionId(), null)"));
|
||||
@@ -52,7 +52,10 @@ public class BukkitEngineLifecycleContractTest {
|
||||
String waitedShutdown = method(jobSource,
|
||||
"private static boolean shutdownAndWait(PregeneratorJob inst, long timeoutMs)");
|
||||
assertBefore(waitedShutdown, "inst.worker.interrupt()", "inst.worker.join(");
|
||||
assertTrue(waitedShutdown.contains("inst.worker.isAlive()"));
|
||||
assertBefore(waitedShutdown, "inst.worker.join(", "finishShutdown(inst, timeoutMs)");
|
||||
String finishedShutdown = method(jobSource,
|
||||
"private static boolean finishShutdown(PregeneratorJob inst, long timeoutMs)");
|
||||
assertBefore(finishedShutdown, "inst.worker.isAlive()", "instance.compareAndSet(inst, null)");
|
||||
|
||||
String hooksSource = Files.readString(Path.of(System.getProperty("iris.bukkitEnginePlatformHooksSource")));
|
||||
String hookShutdown = method(hooksSource, "public void shutdownPregenerator(Engine engine)");
|
||||
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
package art.arcane.iris.core.runtime;
|
||||
|
||||
import art.arcane.iris.engine.framework.Engine;
|
||||
import art.arcane.iris.engine.object.IrisDimension;
|
||||
import art.arcane.iris.engine.object.IrisWorldBoundary;
|
||||
import art.arcane.iris.engine.object.IrisWorldBoundaryCenter;
|
||||
import art.arcane.iris.engine.object.world.dimension.IrisDimension;
|
||||
import art.arcane.iris.engine.object.world.IrisWorldBoundary;
|
||||
import art.arcane.iris.engine.object.world.IrisWorldBoundaryCenter;
|
||||
import org.bukkit.WorldBorder;
|
||||
import org.junit.Test;
|
||||
|
||||
|
||||
+3
-4
@@ -42,12 +42,11 @@ public class StudioPlayerModeContractTest {
|
||||
String objectCommands = Files.readString(Path.of(
|
||||
"src/main/java/art/arcane/iris/core/commands/CommandObject.java")).replace("\r\n", "\n");
|
||||
String jigsawCommands = Files.readString(Path.of(
|
||||
"src/main/java/art/arcane/iris/core/commands/CommandJigsaw.java")).replace("\r\n", "\n");
|
||||
System.getProperty("iris.studioLifecycleCommandsSource"))).replace("\r\n", "\n");
|
||||
|
||||
assertTrue(objectCommands.contains("GameMode.CREATIVE"));
|
||||
assertTrue(objectCommands.contains("StudioOpenCoordinator.StudioOpenKind.OBJECT"));
|
||||
assertTrue(jigsawCommands.contains("GameMode.CREATIVE"));
|
||||
assertTrue(jigsawCommands.contains("player.creative(true)"));
|
||||
assertFalse(objectCommands.contains("GameMode.SPECTATOR"));
|
||||
assertFalse(jigsawCommands.contains("GameMode.SPECTATOR"));
|
||||
}
|
||||
assertFalse(jigsawCommands.contains("GameMode.SPECTATOR")); }
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.api.tree.TreeFellerRunHooks;
|
||||
import art.arcane.iris.core.service.TreeFellerModel.TreeCandidate;
|
||||
import art.arcane.iris.core.service.TreeFellerModel.TreeClaim;
|
||||
import art.arcane.iris.core.service.tree.TreeMarkerTraversal;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class TreeFellingRunnerSneakLatchTest {
|
||||
private static final TreeFellerRunHooks LATCHED_HOOKS = new TreeFellerRunHooks() {
|
||||
@Override
|
||||
public boolean requiresSneaking() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivationAccepted() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean reserveLogCost() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void commitLogCost() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void refundLogCost() {
|
||||
}
|
||||
};
|
||||
|
||||
@Test
|
||||
public void runHooksRequireSneakingByDefault() {
|
||||
assertTrue(TreeFellerRunHooks.NONE.requiresSneaking());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void releasingSneakFinishesOnlyRunsThatRequireIt() {
|
||||
TreeFellerSVC service = new TreeFellerSVC();
|
||||
TreeFellingRunner runner = new TreeFellingRunner(service, null);
|
||||
UUID playerId = UUID.randomUUID();
|
||||
FellingRun sneakRun = registerRun(service, playerId, TreeFellerRunHooks.NONE, "sneak");
|
||||
FellingRun latchedRun = registerRun(service, playerId, LATCHED_HOOKS, "latched");
|
||||
|
||||
runner.finishSneakRuns(playerId);
|
||||
|
||||
assertTrue(sneakRun.finished.get());
|
||||
assertEquals("halted", sneakRun.abortReason);
|
||||
assertFalse(latchedRun.finished.get());
|
||||
assertTrue(service.activeRuns.get(playerId).contains(latchedRun));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void finishingAllRunsStillEndsLatchedRuns() {
|
||||
TreeFellerSVC service = new TreeFellerSVC();
|
||||
TreeFellingRunner runner = new TreeFellingRunner(service, null);
|
||||
UUID playerId = UUID.randomUUID();
|
||||
FellingRun latchedRun = registerRun(service, playerId, LATCHED_HOOKS, "latched");
|
||||
|
||||
runner.finishRuns(playerId);
|
||||
|
||||
assertTrue(latchedRun.finished.get());
|
||||
assertEquals("halted", latchedRun.abortReason);
|
||||
}
|
||||
|
||||
private FellingRun registerRun(TreeFellerSVC service, UUID playerId, TreeFellerRunHooks hooks, String marker) {
|
||||
Player player = mock(Player.class);
|
||||
when(player.getUniqueId()).thenReturn(playerId);
|
||||
World world = mock(World.class);
|
||||
TreeCandidate candidate = new TreeCandidate(
|
||||
null,
|
||||
world,
|
||||
player,
|
||||
mock(ItemStack.class),
|
||||
null,
|
||||
new TreeMarkerTraversal.Position(0, 64, 0)
|
||||
);
|
||||
TreeClaim claim = new TreeClaim(UUID.randomUUID(), marker);
|
||||
FellingRun run = new FellingRun(claim, candidate, 0, hooks, 0, new Location(world, 0D, 64D, 0D));
|
||||
service.activeClaims.add(claim);
|
||||
service.activeRuns.computeIfAbsent(playerId, ignored -> ConcurrentHashMap.newKeySet()).add(run);
|
||||
return run;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package art.arcane.iris.core.service;
|
||||
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.core.link.WorldEditLink;
|
||||
import art.arcane.volmlib.util.bukkit.WorldIdentity;
|
||||
import art.arcane.volmlib.util.data.Cuboid;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.NamespacedKey;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.PlayerInventory;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataContainer;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertArrayEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class WandSVCTest {
|
||||
private Iris previousPlugin;
|
||||
private Player player;
|
||||
private PlayerInventory inventory;
|
||||
|
||||
@Before
|
||||
public void installPlugin() {
|
||||
previousPlugin = Iris.instance;
|
||||
Iris plugin = mock(Iris.class);
|
||||
when(plugin.namespace()).thenReturn("iris");
|
||||
Iris.instance = plugin;
|
||||
player = mock(Player.class);
|
||||
inventory = mock(PlayerInventory.class);
|
||||
when(player.getInventory()).thenReturn(inventory);
|
||||
}
|
||||
|
||||
@After
|
||||
public void restorePlugin() {
|
||||
Iris.instance = previousPlugin;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ignoresWorldEditSelectionWhileHoldingAnOrdinaryAxe() {
|
||||
ItemStack axe = wandItem(false);
|
||||
when(inventory.getItemInMainHand()).thenReturn(axe);
|
||||
Cuboid selection = mock(Cuboid.class);
|
||||
|
||||
try (MockedStatic<WorldEditLink> worldEdit = mockStatic(WorldEditLink.class)) {
|
||||
worldEdit.when(() -> WorldEditLink.getSelection(player)).thenReturn(selection);
|
||||
|
||||
assertFalse(WandSVC.isHoldingWand(player));
|
||||
assertNull(WandSVC.getCuboid(player));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ignoresWorldEditSelectionWithAnEmptyHand() {
|
||||
Cuboid selection = mock(Cuboid.class);
|
||||
|
||||
try (MockedStatic<WorldEditLink> worldEdit = mockStatic(WorldEditLink.class)) {
|
||||
worldEdit.when(() -> WorldEditLink.getSelection(player)).thenReturn(selection);
|
||||
|
||||
assertFalse(WandSVC.isHoldingWand(player));
|
||||
assertNull(WandSVC.getCuboid(player));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void readsSelectionFromAnIrisMarkedWand() {
|
||||
ItemStack wand = wandItem(true);
|
||||
when(inventory.getItemInMainHand()).thenReturn(wand);
|
||||
World world = mock(World.class);
|
||||
|
||||
try (MockedStatic<WorldIdentity> worlds = mockStatic(WorldIdentity.class)) {
|
||||
worlds.when(() -> WorldIdentity.resolve("minecraft:overworld")).thenReturn(Optional.of(world));
|
||||
|
||||
assertTrue(WandSVC.isHoldingWand(player));
|
||||
assertArrayEquals(new Location[]{new Location(world, 1D, 64D, 2D), new Location(world, 3D, 68D, 4D)},
|
||||
WandSVC.getCuboid(player));
|
||||
}
|
||||
}
|
||||
|
||||
private ItemStack wandItem(boolean marked) {
|
||||
ItemStack item = mock(ItemStack.class);
|
||||
ItemMeta meta = mock(ItemMeta.class);
|
||||
PersistentDataContainer data = mock(PersistentDataContainer.class);
|
||||
when(item.getType()).thenReturn(marked ? Material.BLAZE_ROD : Material.WOODEN_AXE);
|
||||
when(item.getItemMeta()).thenReturn(meta);
|
||||
when(meta.getPersistentDataContainer()).thenReturn(data);
|
||||
when(meta.getLore()).thenReturn(List.of("1,64,2 in minecraft:overworld", "3,68,4 in minecraft:overworld"));
|
||||
if (marked) {
|
||||
when(data.get(new NamespacedKey("iris", "wand"), PersistentDataType.BYTE)).thenReturn((byte) 1);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 2916 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user