chore: decrease compile time

Instead of parsing pumpkin-data for everyone who compiles lets have it as static files, pumpkin-codegen is a standalone parser now
This commit is contained in:
Alexander Medvedev committed 2026-02-09 15:52:46 +01:00
1 parent 7e277c0bfb
commit f60a77c5d9
109 files changed
+956814 -263

No files matched your search

+906
View File
@@ -0,0 +1,906 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "autocfg"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "base16ct"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "bumpalo"
version = "3.19.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510"
[[package]]
name = "bytes"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
[[package]]
name = "cesu8"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "colored"
version = "3.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"
dependencies = [
"windows-sys",
]
[[package]]
name = "const-oid"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
dependencies = [
"cfg-if",
]
[[package]]
name = "crossbeam-deque"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
dependencies = [
"crossbeam-epoch",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-epoch"
version = "0.9.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
[[package]]
name = "crypto-bigint"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
dependencies = [
"generic-array",
"rand_core",
"subtle",
"zeroize",
]
[[package]]
name = "crypto-common"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "der"
version = "0.7.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
dependencies = [
"const-oid",
"pem-rfc7468",
"zeroize",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"subtle",
]
[[package]]
name = "ecdsa"
version = "0.16.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
dependencies = [
"der",
"digest",
"elliptic-curve",
"rfc6979",
"signature",
"spki",
]
[[package]]
name = "either"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
[[package]]
name = "elliptic-curve"
version = "0.13.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
dependencies = [
"base16ct",
"crypto-bigint",
"digest",
"ff",
"generic-array",
"group",
"hkdf",
"pem-rfc7468",
"pkcs8",
"rand_core",
"sec1",
"subtle",
"zeroize",
]
[[package]]
name = "enum_dispatch"
version = "0.3.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd"
dependencies = [
"once_cell",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "ff"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"
dependencies = [
"rand_core",
"subtle",
]
[[package]]
name = "flate2"
version = "1.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
dependencies = [
"crc32fast",
"miniz_oxide",
]
[[package]]
name = "generic-array"
version = "0.14.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2"
dependencies = [
"typenum",
"version_check",
"zeroize",
]
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "getrandom"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"wasip2",
]
[[package]]
name = "group"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
dependencies = [
"ff",
"rand_core",
"subtle",
]
[[package]]
name = "hashbrown"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hkdf"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
dependencies = [
"hmac",
]
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest",
]
[[package]]
name = "indexmap"
version = "2.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
dependencies = [
"equivalent",
"hashbrown",
"serde",
"serde_core",
]
[[package]]
name = "itoa"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
[[package]]
name = "js-sys"
version = "0.3.85"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3"
dependencies = [
"once_cell",
"wasm-bindgen",
]
[[package]]
name = "libc"
version = "0.2.180"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bcc35a38544a891a5f7c865aca548a982ccb3b8650a5b06d0fd33a10283c56fc"
[[package]]
name = "md-5"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
dependencies = [
"cfg-if",
"digest",
]
[[package]]
name = "md5"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae960838283323069879657ca3de837e9f7bbb4c7bf6ea7f1b290d5e9476d2e0"
[[package]]
name = "memchr"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "num-derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "p384"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6"
dependencies = [
"ecdsa",
"elliptic-curve",
"primeorder",
"sha2",
]
[[package]]
name = "pem-rfc7468"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
dependencies = [
"base64ct",
]
[[package]]
name = "pest"
version = "2.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0848c601009d37dfa3430c4666e147e49cdcf1b92ecd3e63657d8a5f19da662"
dependencies = [
"memchr",
"ucd-trie",
]
[[package]]
name = "pest_derive"
version = "2.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11f486f1ea21e6c10ed15d5a7c77165d0ee443402f0780849d1768e7d9d6fe77"
dependencies = [
"pest",
"pest_generator",
]
[[package]]
name = "pest_generator"
version = "2.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8040c4647b13b210a963c1ed407c1ff4fdfa01c31d6d2a098218702e6664f94f"
dependencies = [
"pest",
"pest_meta",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "pest_meta"
version = "2.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89815c69d36021a140146f26659a81d6c2afa33d216d736dd4be5381a7362220"
dependencies = [
"pest",
"sha2",
]
[[package]]
name = "pin-project-lite"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
[[package]]
name = "pkcs8"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
dependencies = [
"der",
"spki",
]
[[package]]
name = "primeorder"
version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"
dependencies = [
"elliptic-curve",
]
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "pumpkin-codegen"
version = "0.1.0-dev+1.21.11"
dependencies = [
"heck",
"indexmap",
"proc-macro2",
"pumpkin-nbt",
"pumpkin-util",
"quote",
"rayon",
"serde",
"serde_json",
"serde_json5",
"syn",
]
[[package]]
name = "pumpkin-nbt"
version = "0.1.0-dev+1.21.11"
dependencies = [
"bytes",
"cesu8",
"flate2",
"serde",
"thiserror",
]
[[package]]
name = "pumpkin-util"
version = "0.1.0-dev+1.21.11"
dependencies = [
"base64",
"bytes",
"colored",
"ecdsa",
"enum_dispatch",
"md5",
"num-derive",
"num-traits",
"p384",
"proc-macro2",
"pumpkin-nbt",
"quote",
"serde",
"serde_json",
"syn",
"thiserror",
"tokio",
"uuid",
]
[[package]]
name = "quote"
version = "1.0.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom 0.2.17",
]
[[package]]
name = "rayon"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f"
dependencies = [
"either",
"rayon-core",
]
[[package]]
name = "rayon-core"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
dependencies = [
"crossbeam-deque",
"crossbeam-utils",
]
[[package]]
name = "rfc6979"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"
dependencies = [
"hmac",
"subtle",
]
[[package]]
name = "rustversion"
version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]]
name = "sec1"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
dependencies = [
"base16ct",
"der",
"generic-array",
"pkcs8",
"subtle",
"zeroize",
]
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "serde_json5"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d34d03f54462862f2a42918391c9526337f53171eaa4d8894562be7f252edd3"
dependencies = [
"pest",
"pest_derive",
"serde",
]
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "signature"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"digest",
"rand_core",
]
[[package]]
name = "simd-adler32"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
[[package]]
name = "spki"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
dependencies = [
"base64ct",
"der",
]
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio"
version = "1.49.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86"
dependencies = [
"pin-project-lite",
]
[[package]]
name = "typenum"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
[[package]]
name = "ucd-trie"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"
[[package]]
name = "unicode-ident"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "537dd038a89878be9b64dd4bd1b260315c1bb94f4d784956b81e27a088d9a09e"
[[package]]
name = "uuid"
version = "1.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ee48d38b119b0cd71fe4141b30f5ba9c7c5d9f4e7a3a8b4a674e4b6ef789976f"
dependencies = [
"getrandom 0.3.4",
"js-sys",
"md-5",
"serde_core",
"wasm-bindgen",
]
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "wasip2"
version = "1.0.2+wasi-0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
dependencies = [
"wit-bindgen",
]
[[package]]
name = "wasm-bindgen"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12"
dependencies = [
"unicode-ident",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "wit-bindgen"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
[[package]]
name = "zeroize"
version = "1.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
[[package]]
name = "zmij"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4de98dfa5d5b7fef4ee834d0073d560c9ca7b6c46a71d058c48db7960f8cfaf7"
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "pumpkin-codegen"
version = "0.1.0-dev+1.21.11"
edition = "2024"
rust-version = "1.89"
[dependencies]
indexmap = { version = "2.7", features = ["serde"] }
heck = "0.5"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
serde_json5 = "0.2"
rayon = "1.11.0"
proc-macro2 = "1.0"
quote = "1.0"
syn = { version = "2.0", features = ["full", "extra-traits"] }
pumpkin-util = { path = "../pumpkin-util" }
pumpkin-nbt = { path = "../pumpkin-nbt" }
# [lints]
# all = { level = "deny", priority = -1 }
# nursery = { level = "deny", priority = -1 }
# pedantic = { level = "deny", priority = -1 }
# cargo = { level = "deny", priority = -1 }
+3
View File
@@ -0,0 +1,3 @@
disallowed-types = [
{ path = "std::collections::HashMap", reason = "If you need a map, use BTreeMap for deterministic ordering. Otherwise it forces a rebuild after every change.", replacement = "std::collections::BTreeMap" },
]
+62
View File
@@ -0,0 +1,62 @@
use heck::ToShoutySnakeCase;
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use serde::Deserialize;
use std::collections::BTreeMap;
use std::fs;
use syn::LitInt;
#[derive(Deserialize)]
struct Attributes {
id: u8,
default_value: f64,
}
pub fn build() -> TokenStream {
let attributes: BTreeMap<String, Attributes> =
serde_json::from_str(&fs::read_to_string("../assets/attributes.json").unwrap())
.expect("Failed to parse attributes.json");
let mut sorted_attributes: Vec<(String, Attributes)> = attributes.into_iter().collect();
sorted_attributes.sort_by_key(|(_, raw)| raw.id);
let mut constant_defs = Vec::new();
for (raw_name, raw_value) in sorted_attributes {
let constant_ident = format_ident!("{}", raw_name.to_shouty_snake_case());
let id_lit = LitInt::new(&raw_value.id.to_string(), Span::call_site());
let default_value_lit = raw_value.default_value;
constant_defs.push(quote!(
pub const #constant_ident: Self = Self {
id: #id_lit,
default_value: #default_value_lit,
};
));
}
quote! {
use std::hash::Hash;
#[derive(Clone, Debug)]
pub struct Attributes {
pub id: u8,
pub default_value: f64,
}
impl PartialEq for Attributes {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for Attributes {}
impl Hash for Attributes {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl Attributes {
#(#constant_defs)*
}
}
}
+519
View File
@@ -0,0 +1,519 @@
use std::{collections::BTreeMap, fs};
use heck::ToShoutySnakeCase;
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use serde::Deserialize;
use syn::LitInt;
#[derive(Deserialize)]
pub struct Biome {
has_precipitation: bool,
temperature: f32,
downfall: f32,
temperature_modifier: Option<TemperatureModifier>,
//carvers: Vec<String>,
features: Vec<Vec<String>>,
creature_spawn_probability: Option<f32>,
spawners: SpawnGroups,
spawn_costs: BTreeMap<String, SpawnCosts>,
pub id: u8,
}
#[derive(Deserialize, PartialEq, Eq, Hash)]
struct SpawnGroups {
monster: Vec<Spawner>,
ambient: Vec<Spawner>,
axolotls: Vec<Spawner>,
creature: Vec<Spawner>,
misc: Vec<Spawner>,
underground_water_creature: Vec<Spawner>,
water_ambient: Vec<Spawner>,
water_creature: Vec<Spawner>,
}
#[expect(non_snake_case)]
#[derive(Deserialize, Hash, PartialEq, Eq)]
struct Spawner {
r#type: String,
minCount: i32,
maxCount: i32,
}
impl Spawner {
pub fn to_tokens(&self) -> TokenStream {
let r#type = &self.r#type;
let min_count = &self.minCount;
let max_count = &self.maxCount;
quote! {
Spawner {
r#type: #r#type,
min_count: #min_count,
max_count: #max_count,
}
}
}
}
#[derive(Deserialize, PartialEq)]
struct SpawnCosts {
energy_budget: f64,
charge: f64,
}
impl SpawnCosts {
pub fn to_tokens(&self) -> TokenStream {
let energy_budget = &self.energy_budget;
let charge = &self.charge;
quote! {
SpawnCosts {
energy_budget: #energy_budget,
charge: #charge,
}
}
}
}
#[derive(Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
enum TemperatureModifier {
None,
Frozen,
}
#[derive(Deserialize)]
struct ParameterRange {
min: i64,
max: i64,
}
impl ParameterRange {
fn into_token_stream(self) -> TokenStream {
let min = self.min;
let max = self.max;
quote! {
ParameterRange {
min: #min,
max: #max
}
}
}
}
#[derive(Deserialize)]
#[serde(tag = "_type", rename_all = "lowercase")]
enum BiomeTree {
Leaf {
parameters: [ParameterRange; 7],
biome: String,
},
Branch {
parameters: [ParameterRange; 7],
#[serde(rename = "subTree")]
nodes: Box<[Self]>,
},
}
impl BiomeTree {
fn into_token_stream(self) -> TokenStream {
match self {
Self::Leaf { parameters, biome } => {
let biome = format_ident!(
"{}",
biome
.strip_prefix("minecraft:")
.unwrap()
.to_shouty_snake_case()
);
let parameters = parameters.map(ParameterRange::into_token_stream);
quote! {
BiomeTree::Leaf {
parameters: [#(#parameters),*],
biome: &Biome::#biome
}
}
}
Self::Branch { parameters, nodes } => {
let nodes = nodes
.into_iter()
.map(Self::into_token_stream)
.collect::<Vec<_>>();
let parameters = parameters.map(ParameterRange::into_token_stream);
quote! {
BiomeTree::Branch {
parameters: [#(#parameters),*],
nodes: &[#(#nodes),*]
}
}
}
}
}
}
#[derive(Deserialize)]
struct MultiNoiseBiomeSuppliers {
overworld: BiomeTree,
nether: BiomeTree,
}
pub fn build() -> TokenStream {
let biomes: BTreeMap<String, Biome> =
serde_json::from_str(&fs::read_to_string("../assets/biome.json").unwrap())
.expect("Failed to parse biome.json");
let biome_trees: MultiNoiseBiomeSuppliers =
serde_json::from_str(&fs::read_to_string("../assets/multi_noise_biome_tree.json").unwrap())
.expect("Failed to parse multi_noise_biome_tree.json");
let mut variants = TokenStream::new();
let mut name_to_type = TokenStream::new();
let mut id_to_type = TokenStream::new();
for (name, biome) in biomes {
// let full_name = format!("minecraft:{name}");
let format_name = format_ident!("{}", name.to_shouty_snake_case());
let has_precipitation = biome.has_precipitation;
let temperature = biome.temperature;
let downfall = biome.downfall;
// let carvers = &biome.carvers;
let features = &biome.features;
let creature_spawn_probability = &biome.creature_spawn_probability.unwrap_or(0.1);
let temperature_modifier = biome
.temperature_modifier
.unwrap_or(TemperatureModifier::None);
let monster: Vec<_> = biome
.spawners
.monster
.iter()
.map(Spawner::to_tokens)
.collect();
let ambient: Vec<_> = biome
.spawners
.ambient
.iter()
.map(Spawner::to_tokens)
.collect();
let axolotls: Vec<_> = biome
.spawners
.axolotls
.iter()
.map(Spawner::to_tokens)
.collect();
let creature: Vec<_> = biome
.spawners
.creature
.iter()
.map(Spawner::to_tokens)
.collect();
let misc: Vec<_> = biome.spawners.misc.iter().map(Spawner::to_tokens).collect();
let underground_water_creature: Vec<_> = biome
.spawners
.underground_water_creature
.iter()
.map(Spawner::to_tokens)
.collect();
let water_ambient: Vec<_> = biome
.spawners
.water_ambient
.iter()
.map(Spawner::to_tokens)
.collect();
let water_creature: Vec<_> = biome
.spawners
.water_creature
.iter()
.map(Spawner::to_tokens)
.collect();
let spawners = quote! {
SpawnGroups {
monster: &[#(#monster),*],
ambient: &[#(#ambient),*],
axolotls: &[#(#axolotls),*],
creature: &[#(#creature),*],
misc: &[#(#misc),*],
underground_water_creature: &[#(#underground_water_creature),*],
water_ambient: &[#(#water_ambient),*],
water_creature: &[#(#water_creature),*],
}
};
let spawn_costs: Vec<_> = biome
.spawn_costs
.iter()
.map(|(name, cost)| {
let cost_token = cost.to_tokens();
let entity_type = name.strip_prefix("minecraft:").unwrap();
quote! {
#entity_type => #cost_token
}
})
.collect();
let temperature_modifier = match temperature_modifier {
TemperatureModifier::Frozen => quote! { TemperatureModifier::Frozen },
TemperatureModifier::None => quote! { TemperatureModifier::None },
};
let index = LitInt::new(&biome.id.to_string(), Span::call_site());
variants.extend([quote! {
pub const #format_name: Biome = Biome {
id: #index,
registry_id: #name,
weather: Weather::new(
#has_precipitation,
#temperature,
#temperature_modifier,
#downfall
),
features: &[#(&[#(#features),*]),*],
creature_spawn_probability: #creature_spawn_probability,
spawners: #spawners,
spawn_costs: phf::phf_map! {
#(#spawn_costs),*
},
};
}]);
name_to_type.extend(quote! { #name => Some(&Self::#format_name), });
id_to_type.extend(quote! { #index => Some(&Self::#format_name), });
}
let overworld_tree = biome_trees.overworld.into_token_stream();
let nether_tree = biome_trees.nether.into_token_stream();
quote! {
use crate::biome::de::Deserialize;
use crate::entity_type::EntityType;
use crate::tag::Taggable;
use crate::tag::RegistryKey;
use pumpkin_util::biome::{TemperatureModifier, Weather};
use serde::{Deserializer, de};
use std::{fmt, hash::{Hasher, Hash}};
#[derive(Debug)]
pub struct Biome {
pub id: u8,
pub registry_id: &'static str,
pub weather: Weather,
// carvers: &'static [&str],
pub features: &'static [&'static [&'static str]],
pub creature_spawn_probability: f32,
pub spawners: SpawnGroups,
pub spawn_costs: phf::Map<&'static str, SpawnCosts>,
}
impl PartialEq<u8> for Biome {
fn eq(&self, other: &u8) -> bool {
self.id == *other
}
}
impl PartialEq<Biome> for u8 {
fn eq(&self, other: &Biome) -> bool {
*self == other.id
}
}
#[derive(Debug)]
pub struct SpawnGroups {
pub monster: &'static [Spawner],
pub ambient: &'static [Spawner],
pub axolotls: &'static [Spawner],
pub creature: &'static [Spawner],
pub misc: &'static [Spawner],
pub underground_water_creature: &'static [Spawner],
pub water_ambient: &'static [Spawner],
pub water_creature: &'static [Spawner],
}
#[derive(Debug)]
pub struct Spawner {
pub r#type: &'static str,
pub min_count: i32,
pub max_count: i32,
}
impl PartialEq for Biome {
fn eq(&self, other: &Biome) -> bool {
self.id == other.id
}
}
impl Eq for Biome {}
impl Hash for Biome {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
#[derive(Debug)]
pub struct SpawnCosts {
pub energy_budget: f64,
pub charge: f64,
}
impl<'de> Deserialize<'de> for &'static Biome {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct BiomeVisitor;
impl de::Visitor<'_> for BiomeVisitor {
type Value = &'static Biome;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a biome name as a string")
}
fn visit_string<E: serde::de::Error>(self, v: String) -> Result<Self::Value, E> {
self.visit_str(&v)
}
fn visit_str<E: de::Error>(self, value: &str) -> Result<Self::Value, E> {
let biome = Biome::from_name(value.strip_prefix("minecraft:").unwrap_or(value));
biome.ok_or_else(|| E::unknown_variant(value, &["unknown biome"]))
}
}
deserializer.deserialize_str(BiomeVisitor)
}
}
impl Biome {
#variants
pub fn from_name(name: &str) -> Option<&'static Self> {
match name {
#name_to_type
_ => None
}
}
pub const fn from_id(id: u8) -> Option<&'static Self> {
match id {
#id_to_type
_ => None
}
}
}
impl Taggable for Biome {
#[inline]
fn registry_id(&self) -> u16 {
self.id as u16
}
#[inline]
fn tag_key() -> RegistryKey {
RegistryKey::WorldgenBiome
}
#[inline]
fn registry_key(&self) -> &str {
self.registry_id
}
}
#[derive(PartialEq)]
pub struct ParameterRange {
min: i64,
max: i64,
}
impl ParameterRange {
pub fn calc_distance(&self, noise: i64) -> i64 {
if noise > self.max {
noise - self.max
} else if noise < self.min {
self.min - noise
} else {
0
}
}
}
#[derive(PartialEq)]
pub enum BiomeTree {
Leaf {
parameters: [ParameterRange; 7],
biome: &'static Biome,
},
Branch {
parameters: [ParameterRange; 7],
nodes: &'static [BiomeTree],
},
}
impl BiomeTree {
pub fn get(
&'static self,
point_list: &[i64; 7],
previous_result_node: &mut Option<&'static BiomeTree>,
) -> &'static Biome {
// Initialize best distance from the previous result for spatial coherence
let mut best_dist = previous_result_node
.map(|node| node.get_squared_distance(point_list))
.unwrap_or(i64::MAX);
let mut best_node = previous_result_node.unwrap_or(self);
self.search(point_list, &mut best_dist, &mut best_node);
match best_node {
BiomeTree::Leaf { biome, .. } => {
*previous_result_node = Some(best_node);
biome
}
// Should not happen with valid tree data
_ => unreachable!("Biome search failed to find a leaf"),
}
}
fn search(
&'static self,
point: &[i64; 7],
best_dist: &mut i64,
best_node: &mut &'static BiomeTree,
) {
let dist = self.get_squared_distance(point);
// PRUNING: If this branch/leaf is further than our best, skip it and all children
if dist >= *best_dist {
return;
}
match self {
Self::Leaf { .. } => {
*best_dist = dist;
*best_node = self;
}
Self::Branch { nodes, .. } => {
for node in *nodes {
node.search(point, best_dist, best_node);
}
}
}
}
#[inline(always)]
fn get_squared_distance(&self, p: &[i64; 7]) -> i64 {
let params = match self {
Self::Leaf { parameters, .. } => parameters,
Self::Branch { parameters, .. } => parameters,
};
// Fully unrolled for 7 dimensions to maximize throughput
params[0].calc_distance(p[0]) +
params[1].calc_distance(p[1]) +
params[2].calc_distance(p[2]) +
params[3].calc_distance(p[3]) +
params[4].calc_distance(p[4]) +
params[5].calc_distance(p[5]) +
params[6].calc_distance(p[6])
}
}
pub const OVERWORLD_BIOME_SOURCE: BiomeTree = #overworld_tree;
pub const NETHER_BIOME_SOURCE: BiomeTree = #nether_tree;
}
}
+61
View File
@@ -0,0 +1,61 @@
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::Ident;
pub struct Bitset {
pub items: TokenStream,
pub mod_ident: Ident,
pub contains_ident: Ident,
}
pub fn gen_u16_bitset(name: &str, ids: &[u16]) -> Bitset {
let max_id = ids.iter().copied().max().unwrap_or(0);
//let min_id = ids.iter().copied().min().unwrap_or(0);
let words = ((max_id as usize) + 64) / 64;
let mut bitset = vec![0u64; words];
for &id in ids {
let index = (id as usize) >> 6;
let bit = u32::from(id) & 63;
bitset[index] |= 1u64 << bit;
}
let name_uppercase = name.to_uppercase();
let mod_ident = Ident::new(
&format!("__{}_bitset", name.to_lowercase()),
Span::call_site(),
);
let max_ident = Ident::new(&format!("{name_uppercase}_MAX_ID"), Span::call_site());
let words_ident = Ident::new(&format!("{name_uppercase}_WORDS"), Span::call_site());
let bitset_ident = Ident::new(&format!("{name_uppercase}_BITSET"), Span::call_site());
let contains_ident = Ident::new(
&format!("{}_contains", name.to_lowercase()),
Span::call_site(),
);
let items = quote! {
mod #mod_ident {
pub const #max_ident: u16 = #max_id;
pub const #words_ident: usize = #words;
pub static #bitset_ident: [u64; #words_ident] = [ #(#bitset),* ];
#[inline(always)]
pub(super) const fn #contains_ident(id: u16) -> bool {
if id > #max_ident {
return false;
}
let index: usize = (id as usize) >> 6;
let bit: u32 = (id as u32) & 63;
((#bitset_ident[index] >> bit) & 1) != 0
}
}
};
Bitset {
items,
mod_ident,
contains_ident,
}
}
File diff suppressed because it is too large. Load diff
+207
View File
@@ -0,0 +1,207 @@
use proc_macro2::{Literal, TokenStream};
use quote::quote;
use std::{fs, io::Cursor};
use pumpkin_nbt::{Nbt, compound::NbtCompound, deserializer::NbtReadHelper};
struct ParsedMappings {
mapped_size: usize,
forward: Vec<i32>,
}
fn parse_mapping_file(path: &str) -> ParsedMappings {
let bytes = fs::read(path).unwrap_or_else(|_| panic!("Failed to read {path}"));
let mut reader = NbtReadHelper::new(Cursor::new(bytes));
let nbt = Nbt::read(&mut reader).unwrap_or_else(|_| panic!("Failed to parse NBT at {path}"));
let blockstates = nbt
.root_tag
.get_compound("blockstates")
.unwrap_or_else(|| panic!("Missing `blockstates` compound in {path}"));
parse_blockstate_mappings(blockstates, path)
}
fn parse_blockstate_mappings(blockstates: &NbtCompound, path: &str) -> ParsedMappings {
let mapped_size = blockstates
.get_int("mappedSize")
.unwrap_or_else(|| panic!("Missing `blockstates.mappedSize` in {path}"));
let strategy = blockstates
.get_byte("id")
.unwrap_or_else(|| panic!("Missing `blockstates.id` in {path}"));
let forward = match strategy {
// Direct
0 => blockstates
.get_int_array("val")
.unwrap_or_else(|| panic!("Missing `blockstates.val` for direct mapping in {path}"))
.to_vec(),
// Shifts
1 => {
let shifts_at = blockstates
.get_int_array("at")
.unwrap_or_else(|| panic!("Missing `blockstates.at` for shift mapping in {path}"));
let shifts_to = blockstates
.get_int_array("to")
.unwrap_or_else(|| panic!("Missing `blockstates.to` for shift mapping in {path}"));
let size = blockstates
.get_int("size")
.unwrap_or_else(|| panic!("Missing `blockstates.size` for shift mapping in {path}"))
as usize;
assert_eq!(
shifts_at.len(),
shifts_to.len(),
"Shift mapping length mismatch in {path}"
);
let mut mappings = vec![-1; size];
if !shifts_at.is_empty() && shifts_at[0] != 0 {
for id in 0..shifts_at[0] {
mappings[id as usize] = id;
}
}
for (index, from) in shifts_at.iter().enumerate() {
let to = if index + 1 == shifts_at.len() {
size as i32
} else {
shifts_at[index + 1]
};
let mut mapped_id = shifts_to[index];
for id in *from..to {
mappings[id as usize] = mapped_id;
mapped_id += 1;
}
}
mappings
}
// Changes
2 => {
let changes_at = blockstates
.get_int_array("at")
.unwrap_or_else(|| panic!("Missing `blockstates.at` for change mapping in {path}"));
let values = blockstates.get_int_array("val").unwrap_or_else(|| {
panic!("Missing `blockstates.val` for change mapping in {path}")
});
let size = blockstates.get_int("size").unwrap_or_else(|| {
panic!("Missing `blockstates.size` for change mapping in {path}")
}) as usize;
let fill_between = blockstates.get("nofill").is_none();
assert_eq!(
changes_at.len(),
values.len(),
"Change mapping length mismatch in {path}"
);
let mut mappings = vec![-1; size];
let mut next_unhandled_id = 0;
for (index, changed_id) in changes_at.iter().enumerate() {
if fill_between {
for id in next_unhandled_id..*changed_id {
mappings[id as usize] = id;
}
next_unhandled_id = changed_id + 1;
}
mappings[*changed_id as usize] = values[index];
}
mappings
}
// Identity
3 => {
let size = blockstates.get_int("size").unwrap_or_else(|| {
panic!("Missing `blockstates.size` for identity mapping in {path}")
}) as usize;
(0..size as i32).collect::<Vec<_>>()
}
_ => panic!("Unknown blockstate mapping strategy {strategy} in {path}"),
};
ParsedMappings {
mapped_size: mapped_size as usize,
forward,
}
}
fn invert_to_u16(forward: &[i32], mapped_size: usize, name: &str) -> Vec<u16> {
let mut inverse = vec![0u16; mapped_size];
let mut seen = vec![false; mapped_size];
for (old_id, mapped_id) in forward.iter().enumerate() {
let Ok(mapped_id) = usize::try_from(*mapped_id) else {
continue;
};
if mapped_id >= mapped_size || seen[mapped_id] {
continue;
}
let old_u16 = u16::try_from(old_id)
.unwrap_or_else(|_| panic!("{name}: id {old_id} does not fit in u16"));
inverse[mapped_id] = old_u16;
seen[mapped_id] = true;
}
inverse
}
fn compose(first: &[u16], second: &[u16]) -> Vec<u16> {
first
.iter()
.map(|id| second.get(usize::from(*id)).copied().unwrap_or(0))
.collect()
}
pub fn build() -> TokenStream {
let mappings_7_to_9 =
parse_mapping_file("../assets/viaversion/data/mappings-1.21.7to1.21.9.nbt");
let mappings_9_to_11 =
parse_mapping_file("../assets/viaversion/data/mappings-1.21.9to1.21.11.nbt");
let remap_9_to_7 = invert_to_u16(
&mappings_7_to_9.forward,
mappings_7_to_9.mapped_size,
"1.21.9->1.21.7",
);
let remap_11_to_9 = invert_to_u16(
&mappings_9_to_11.forward,
mappings_9_to_11.mapped_size,
"1.21.11->1.21.9",
);
let remap_11_to_7 = compose(&remap_11_to_9, &remap_9_to_7);
let remap_11_to_9_tokens: Vec<Literal> = remap_11_to_9
.into_iter()
.map(Literal::u16_unsuffixed)
.collect();
let remap_11_to_7_tokens: Vec<Literal> = remap_11_to_7
.into_iter()
.map(Literal::u16_unsuffixed)
.collect();
quote! {
use pumpkin_util::version::MinecraftVersion;
pub static BLOCK_STATE_REMAP_1_21_11_TO_1_21_9: &[u16] = &[#(#remap_11_to_9_tokens),*];
pub static BLOCK_STATE_REMAP_1_21_11_TO_1_21_7: &[u16] = &[#(#remap_11_to_7_tokens),*];
#[must_use]
pub fn remap_block_state_for_version(state_id: u16, version: MinecraftVersion) -> u16 {
match version {
MinecraftVersion::V_1_21_7 => BLOCK_STATE_REMAP_1_21_11_TO_1_21_7
.get(usize::from(state_id))
.copied()
.unwrap_or(0),
MinecraftVersion::V_1_21_9 => BLOCK_STATE_REMAP_1_21_11_TO_1_21_9
.get(usize::from(state_id))
.copied()
.unwrap_or(0),
_ => state_id,
}
}
}
}
+529
View File
@@ -0,0 +1,529 @@
use proc_macro2::TokenStream;
use quote::{ToTokens, format_ident, quote};
use serde::Deserialize;
use std::{collections::BTreeMap, fs};
#[derive(Deserialize)]
pub struct BlockStateCodecStruct {
#[serde(rename = "Name")]
pub name: String,
#[serde(rename = "Properties")]
pub properties: Option<BTreeMap<String, String>>,
}
#[derive(Deserialize)]
pub struct GenerationSettingsStruct {
#[serde(default)]
pub aquifers_enabled: bool,
#[serde(default)]
pub ore_veins_enabled: bool,
#[serde(default)]
pub legacy_random_source: bool,
pub sea_level: i32,
pub default_fluid: BlockStateCodecStruct,
pub default_block: BlockStateCodecStruct,
#[serde(rename = "noise")]
pub shape: GenerationShapeConfigStruct,
pub surface_rule: MaterialRuleStruct,
}
#[derive(Deserialize)]
pub struct GenerationShapeConfigStruct {
pub min_y: i8,
pub height: u16,
pub size_horizontal: u8,
pub size_vertical: u8,
}
#[derive(Deserialize)]
#[serde(tag = "type")]
pub enum MaterialRuleStruct {
#[serde(rename = "minecraft:block")]
Block { result_state: BlockStateCodecStruct },
#[serde(rename = "minecraft:sequence")]
Sequence { sequence: Vec<Self> },
#[serde(rename = "minecraft:condition")]
Condition {
if_true: MaterialConditionStruct,
then_run: Box<Self>,
},
#[serde(rename = "minecraft:bandlands")]
Badlands,
#[serde(other)]
Unsupported,
}
#[derive(Deserialize)]
#[serde(tag = "type")]
pub enum MaterialConditionStruct {
#[serde(rename = "minecraft:biome")]
Biome { biome_is: Vec<String> },
#[serde(rename = "minecraft:noise_threshold")]
NoiseThreshold {
noise: String,
min_threshold: f64,
max_threshold: f64,
},
#[serde(rename = "minecraft:vertical_gradient")]
VerticalGradient {
random_name: String,
true_at_and_below: YOffsetStruct,
false_at_and_above: YOffsetStruct,
},
#[serde(rename = "minecraft:y_above")]
YAbove {
anchor: YOffsetStruct,
surface_depth_multiplier: i32,
add_stone_depth: bool,
},
#[serde(rename = "minecraft:water")]
Water {
offset: i32,
surface_depth_multiplier: i32,
add_stone_depth: bool,
},
#[serde(rename = "minecraft:temperature")]
Temperature,
#[serde(rename = "minecraft:steep")]
Steep,
#[serde(rename = "minecraft:not")]
Not { invert: Box<Self> },
#[serde(rename = "minecraft:hole")]
Hole,
#[serde(rename = "minecraft:above_preliminary_surface")]
AbovePreliminarySurface,
#[serde(rename = "minecraft:stone_depth")]
StoneDepth {
offset: i32,
add_surface_depth: bool,
secondary_depth_range: i32,
surface_type: String, // "ceiling" or "floor"
},
}
#[derive(Deserialize)]
#[serde(untagged)]
pub enum YOffsetStruct {
Absolute { absolute: i16 },
AboveBottom { above_bottom: i8 },
BelowTop { below_top: i8 },
}
// --- ToTokens Implementations ---
impl ToTokens for BlockStateCodecStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name = &self.name.strip_prefix("minecraft:").unwrap_or(&self.name);
let props_gen = if let Some(props) = &self.properties {
let keys = props.keys();
let values = props.values();
quote!(Some(&[#((#keys, #values)),*]))
} else {
quote!(None)
};
tokens.extend(quote!(
BlockBlueprint {
name: #name,
properties: #props_gen,
}
));
}
}
impl ToTokens for GenerationSettingsStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let aquifers = self.aquifers_enabled;
let ores = self.ore_veins_enabled;
let legacy = self.legacy_random_source;
let sea_level = self.sea_level;
let fluid = &self.default_fluid;
let block = &self.default_block;
let shape = &self.shape;
let rule = &self.surface_rule;
tokens.extend(quote!(
GenerationSettings {
aquifers_enabled: #aquifers,
ore_veins_enabled: #ores,
legacy_random_source: #legacy,
sea_level: #sea_level,
default_fluid: #fluid,
shape: #shape,
surface_rule: #rule,
default_block: #block,
}
));
}
}
impl ToTokens for GenerationShapeConfigStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let min_y = self.min_y;
let height = self.height;
let hor = self.size_horizontal;
let ver = self.size_vertical;
tokens.extend(quote!(
GenerationShapeConfig { min_y: #min_y, height: #height, size_horizontal: #hor, size_vertical: #ver }
));
}
}
impl ToTokens for YOffsetStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::Absolute { absolute } => {
tokens.extend(quote!(YOffset::Absolute(pumpkin_util::y_offset::Absolute { absolute: #absolute })));
}
Self::AboveBottom { above_bottom } => {
tokens.extend(quote!(YOffset::AboveBottom(pumpkin_util::y_offset::AboveBottom { above_bottom: #above_bottom })));
}
Self::BelowTop { below_top } => {
tokens.extend(quote!(YOffset::BelowTop(pumpkin_util::y_offset::BelowTop { below_top: #below_top })));
}
}
}
}
impl ToTokens for MaterialConditionStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::Biome { biome_is } => {
let biomes = biome_is
.iter()
.map(|b| b.strip_prefix("minecraft:").unwrap_or(b).to_uppercase());
let biome_refs: Vec<TokenStream> = biomes
.map(|b| {
let ident = format_ident!("{}", b);
quote!(&crate::biome::Biome::#ident)
})
.collect();
tokens.extend(quote!(
MaterialCondition::Biome(BiomeMaterialCondition {
biome_is: &[#(#biome_refs),*],
})
));
}
Self::NoiseThreshold {
noise,
min_threshold,
max_threshold,
} => {
tokens.extend(quote!(
MaterialCondition::NoiseThreshold(NoiseThresholdMaterialCondition {
noise: #noise,
min_threshold: #min_threshold,
max_threshold: #max_threshold,
})
));
}
Self::VerticalGradient {
random_name,
true_at_and_below,
false_at_and_above,
} => {
tokens.extend(quote!(
MaterialCondition::VerticalGradient(VerticalGradientMaterialCondition {
random_name: #random_name,
true_at_and_below: #true_at_and_below,
false_at_and_above: #false_at_and_above,
})
));
}
Self::YAbove {
anchor,
surface_depth_multiplier,
add_stone_depth,
} => {
tokens.extend(quote!(
MaterialCondition::YAbove(AboveYMaterialCondition {
anchor: #anchor,
surface_depth_multiplier: #surface_depth_multiplier,
add_stone_depth: #add_stone_depth,
})
));
}
Self::Water {
offset,
surface_depth_multiplier,
add_stone_depth,
} => {
tokens.extend(quote!(
MaterialCondition::Water(WaterMaterialCondition {
offset: #offset,
surface_depth_multiplier: #surface_depth_multiplier,
add_stone_depth: #add_stone_depth,
})
));
}
Self::Temperature => {
tokens.extend(quote!(MaterialCondition::Temperature));
}
Self::Steep => {
tokens.extend(quote!(MaterialCondition::Steep));
}
Self::Not { invert } => {
tokens.extend(quote!(
MaterialCondition::Not(NotMaterialCondition {
invert: &#invert,
})
));
}
Self::Hole => {
tokens.extend(quote!(MaterialCondition::Hole(HoleMaterialCondition)));
}
Self::AbovePreliminarySurface => {
tokens.extend(quote!(MaterialCondition::AbovePreliminarySurface(
SurfaceMaterialCondition
)));
}
Self::StoneDepth {
offset,
add_surface_depth,
secondary_depth_range,
surface_type,
} => {
let surface_type_token = match surface_type.as_str() {
"ceiling" => quote!(
pumpkin_util::math::vertical_surface_type::VerticalSurfaceType::Ceiling
),
"floor" => quote!(
pumpkin_util::math::vertical_surface_type::VerticalSurfaceType::Floor
),
_ => quote!(
pumpkin_util::math::vertical_surface_type::VerticalSurfaceType::Floor
),
};
tokens.extend(quote!(
MaterialCondition::StoneDepth(StoneDepthMaterialCondition {
offset: #offset,
add_surface_depth: #add_surface_depth,
secondary_depth_range: #secondary_depth_range,
surface_type: #surface_type_token,
})
));
}
}
}
}
impl ToTokens for MaterialRuleStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::Block { result_state } => {
tokens.extend(quote!(
MaterialRule::Block(BlockMaterialRule {
result_state: #result_state
})
));
}
Self::Sequence { sequence } => {
tokens.extend(quote!(
MaterialRule::Sequence(SequenceMaterialRule {
sequence: &[#(#sequence),*]
})
));
}
Self::Condition { if_true, then_run } => {
tokens.extend(quote!(
MaterialRule::Condition(ConditionMaterialRule {
if_true: #if_true,
then_run: &#then_run
})
));
}
Self::Badlands => {
tokens.extend(quote!(MaterialRule::Badlands(BadLandsMaterialRule)));
}
Self::Unsupported => {
tokens.extend(quote!(MaterialRule::Unsupported));
}
}
}
}
pub fn build() -> TokenStream {
let json: BTreeMap<String, GenerationSettingsStruct> =
serde_json::from_str(&fs::read_to_string("../assets/chunk_gen_settings.json").unwrap())
.expect("Failed to parse settings.json");
let mut const_defs = TokenStream::new();
for (name, settings) in &json {
let upper_name = name.to_uppercase();
let const_name = format_ident!("{}", upper_name);
const_defs.extend(quote!(
pub const #const_name: GenerationSettings = #settings;
));
}
quote!(
use crate::dimension::Dimension;
use std::{cell::RefCell, num::NonZeroUsize};
use pumpkin_util::random::RandomDeriver;
use pumpkin_util::y_offset::YOffset;
use crate::biome::Biome;
use pumpkin_util::y_offset::Absolute;
pub struct BlockBlueprint {
pub name: &'static str,
pub properties: Option<&'static [(&'static str, &'static str)]>,
}
pub struct GenerationSettings {
pub aquifers_enabled: bool,
pub ore_veins_enabled: bool,
pub legacy_random_source: bool,
pub sea_level: i32,
pub default_fluid: BlockBlueprint,
pub shape: GenerationShapeConfig,
pub surface_rule: MaterialRule,
pub default_block: BlockBlueprint,
}
pub struct GenerationShapeConfig {
pub min_y: i8,
pub height: u16,
pub size_horizontal: u8,
pub size_vertical: u8,
}
impl GenerationShapeConfig {
#[inline] #[must_use]
pub fn vertical_cell_block_count(&self) -> u8 { self.size_vertical << 2 }
#[inline] #[must_use]
pub fn horizontal_cell_block_count(&self) -> u8 { self.size_horizontal << 2 }
#[must_use]
pub const fn max_y(&self) -> u16 {
if self.min_y >= 0 {
self.height + self.min_y as u16
} else {
(self.height as i32 + self.min_y as i32) as u16
}
}
pub fn trim_height(&self, bottom_y: i8, top_y: u16) -> Self {
let new_min = self.min_y.max(bottom_y);
let this_top = if self.min_y >= 0 {
self.height + self.min_y as u16
} else {
self.height - self.min_y.unsigned_abs() as u16
};
let new_top = this_top.min(top_y);
let new_height = if new_min >= 0 {
new_top - new_min as u16
} else {
new_top + new_min.unsigned_abs() as u16
};
Self {
min_y: new_min,
height: new_height,
size_horizontal: self.size_horizontal,
size_vertical: self.size_vertical,
}
}
}
pub struct BlockMaterialRule {
pub result_state: BlockBlueprint,
}
pub struct SequenceMaterialRule {
pub sequence: &'static [MaterialRule],
}
pub struct ConditionMaterialRule {
pub if_true: MaterialCondition,
pub then_run: &'static MaterialRule,
}
pub struct BadLandsMaterialRule;
pub enum MaterialRule {
Block(BlockMaterialRule),
Sequence(SequenceMaterialRule),
Condition(ConditionMaterialRule),
Badlands(BadLandsMaterialRule),
Unsupported,
}
pub struct BiomeMaterialCondition {
pub biome_is: &'static [&'static Biome],
}
pub struct NoiseThresholdMaterialCondition {
pub noise: &'static str,
pub min_threshold: f64,
pub max_threshold: f64,
}
pub struct VerticalGradientMaterialCondition {
pub random_name: &'static str,
pub true_at_and_below: YOffset,
pub false_at_and_above: YOffset,
}
pub struct AboveYMaterialCondition {
pub anchor: YOffset,
pub surface_depth_multiplier: i32,
pub add_stone_depth: bool,
}
pub struct WaterMaterialCondition {
pub offset: i32,
pub surface_depth_multiplier: i32,
pub add_stone_depth: bool,
}
pub struct HoleMaterialCondition;
pub struct NotMaterialCondition {
pub invert: &'static MaterialCondition,
}
pub struct SurfaceMaterialCondition;
pub struct StoneDepthMaterialCondition {
pub offset: i32,
pub add_surface_depth: bool,
pub secondary_depth_range: i32,
pub surface_type: pumpkin_util::math::vertical_surface_type::VerticalSurfaceType,
}
pub enum MaterialCondition {
Biome(BiomeMaterialCondition),
NoiseThreshold(NoiseThresholdMaterialCondition),
VerticalGradient(VerticalGradientMaterialCondition),
YAbove(AboveYMaterialCondition),
Water(WaterMaterialCondition),
Temperature,
Steep,
Not(NotMaterialCondition),
Hole(HoleMaterialCondition),
AbovePreliminarySurface(SurfaceMaterialCondition),
StoneDepth(StoneDepthMaterialCondition),
}
impl GenerationSettings {
#const_defs
pub fn from_dimension(dimension: &Dimension) -> &'static Self {
if dimension == &Dimension::OVERWORLD {
&Self::OVERWORLD
} else if dimension == &Dimension::THE_NETHER {
&Self::NETHER
} else {
&Self::END
}
}
}
)
}
+31
View File
@@ -0,0 +1,31 @@
use std::fs;
use heck::ToPascalCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
pub fn build() -> TokenStream {
let chunk_status: Vec<String> =
serde_json::from_str(&fs::read_to_string("../assets/chunk_status.json").unwrap())
.expect("Failed to parse chunk_status.json");
let variants: Vec<TokenStream> = chunk_status
.into_iter()
.map(|status| {
let full_name = format!("minecraft:{status}");
let name = format_ident!("{}", status.to_pascal_case());
quote! {
#[serde(rename = #full_name)]
#name,
}
})
.collect();
quote! {
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Copy)]
pub enum ChunkStatus {
#(#variants)*
}
}
}
@@ -0,0 +1,32 @@
use std::{collections::BTreeMap, fs};
use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::LitInt;
pub fn build() -> TokenStream {
let composter_increase_chance: BTreeMap<u16, f32> = serde_json::from_str(
&fs::read_to_string("../assets/composter_increase_chance.json").unwrap(),
)
.expect("Failed to parse composter_increase_chance.json");
let match_arms: Vec<TokenStream> = composter_increase_chance
.into_iter() // Consume the map for efficiency
.map(|(item_id, chance)| {
let item_id_lit = LitInt::new(&item_id.to_string(), Span::call_site());
let chance_lit = chance;
quote! {
#item_id_lit => Some(#chance_lit),
}
})
.collect();
quote! {
#[must_use]
pub const fn get_composter_increase_chance_from_item_id(item_id: u16) -> Option<f32> {
match item_id {
#(#match_arms)*
_ => None,
}
}
}
}
+150
View File
@@ -0,0 +1,150 @@
use heck::ToShoutySnakeCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use serde::Deserialize;
use std::{collections::BTreeMap, fs};
use syn::{Ident, LitInt};
#[derive(Deserialize)]
struct DamageTypeEntry {
id: u8,
components: DamageTypeData,
}
#[derive(Deserialize)]
pub struct DamageTypeData {
death_message_type: Option<DeathMessageType>,
exhaustion: f32,
effects: Option<DamageEffects>,
message_id: String,
scaling: DamageScaling,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum DamageEffects {
Hurt,
Thorns,
Drowning,
Burning,
Poking,
Freezing,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum DamageScaling {
Never,
WhenCausedByLivingNonPlayer,
Always,
}
#[derive(Deserialize, Debug)]
#[serde(rename_all = "snake_case")]
pub enum DeathMessageType {
Default,
FallVariants,
IntentionalGameDesign,
}
pub fn build() -> TokenStream {
let damage_types: BTreeMap<String, DamageTypeEntry> =
serde_json::from_str(&fs::read_to_string("../assets/damage_type.json").unwrap())
.expect("Failed to parse damage_type.json");
let mut constants = Vec::new();
let mut type_from_name = TokenStream::new();
for (name, entry) in damage_types {
let const_ident = format_ident!("{}", name.to_shouty_snake_case());
let resource_name = name.to_lowercase();
type_from_name.extend(quote! {
#resource_name => Some(Self::#const_ident),
});
let data = &entry.components;
let death_message_type = if let Some(msg) = &data.death_message_type {
let msg_ident = Ident::new(&format!("{msg:?}"), proc_macro2::Span::call_site());
quote! { DeathMessageType::#msg_ident }
} else {
quote! { DeathMessageType::Default }
};
let effects = if let Some(msg) = &data.effects {
let msg_ident = Ident::new(&format!("{msg:?}"), proc_macro2::Span::call_site());
quote! { Some(DamageEffects::#msg_ident) }
} else {
quote! { None }
};
let exhaustion = data.exhaustion;
let message_id = &data.message_id;
let scaling_ident = Ident::new(
&format!("{:?}", data.scaling),
proc_macro2::Span::call_site(),
);
let scaling = quote! {DamageScaling::#scaling_ident};
let id_lit = LitInt::new(&entry.id.to_string(), proc_macro2::Span::call_site());
constants.push(quote! {
pub const #const_ident: DamageType = DamageType {
death_message_type: #death_message_type,
exhaustion: #exhaustion,
effects: #effects,
message_id: #message_id,
scaling: #scaling,
id: #id_lit,
};
});
}
quote! {
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DamageType {
pub death_message_type: DeathMessageType,
pub exhaustion: f32,
pub effects: Option<DamageEffects>,
pub message_id: &'static str,
pub scaling: DamageScaling,
pub id: u8,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DeathMessageType {
Default,
FallVariants,
IntentionalGameDesign,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DamageEffects {
Hurt,
Thorns,
Drowning,
Burning,
Poking,
Freezing,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DamageScaling {
Never,
WhenCausedByLivingNonPlayer,
Always,
}
impl DamageType {
#(#constants)*
#[doc = r" Try to parse a damage type from a resource location string."]
pub fn from_name(name: &str) -> Option<Self> {
match name {
#type_from_name
_ => None
}
}
}
}
}
+79
View File
@@ -0,0 +1,79 @@
use heck::ToPascalCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use std::collections::BTreeMap;
use std::fs;
pub fn build() -> TokenStream {
let data_component: BTreeMap<String, u8> =
serde_json::from_str(&fs::read_to_string("../assets/data_component.json").unwrap())
.expect("Failed to parse data_component.json");
let mut enum_variants = TokenStream::new();
let mut id_to_enum = TokenStream::new();
let mut enum_to_name = TokenStream::new();
let mut name_to_enum = TokenStream::new();
let mut data_component_vec = data_component.iter().collect::<Vec<_>>();
data_component_vec.sort_by_key(|(_, i)| **i);
for (raw_name, raw_value) in &data_component_vec {
let strip_name = raw_name
.strip_prefix("minecraft:")
.unwrap()
.replace('/', "_");
let pascal_case = format_ident!("{}", strip_name.to_pascal_case());
// Enum variant
enum_variants.extend(quote! {
#pascal_case = #raw_value,
});
id_to_enum.extend(quote! {
#raw_value => Some(DataComponent::#pascal_case),
});
// TODO use phf
name_to_enum.extend(quote! {
#raw_name => Some(DataComponent::#pascal_case),
});
// Enum -> &str
enum_to_name.extend(quote! {
Self::#pascal_case => #raw_name,
});
}
quote! {
use crate::data_component_impl::*;
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
#[repr(u8)]
pub enum DataComponent {
#enum_variants
}
impl DataComponent {
pub const fn to_id(self) -> u8 {
self as u8
}
pub const fn try_from_id(id: u8) -> Option<DataComponent> {
match id {
#id_to_enum
_ => None,
}
}
pub fn try_from_name(name: &str) -> Option<DataComponent> {
match name {
#name_to_enum
_ => None,
}
}
pub const fn to_name(self) -> &'static str {
match self {
#enum_to_name
}
}
}
}
}
+136
View File
@@ -0,0 +1,136 @@
use std::{collections::BTreeMap, fs};
use heck::ToShoutySnakeCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Dimension {
pub has_skylight: bool,
pub has_ceiling: bool,
pub ambient_light: f32,
pub coordinate_scale: f64,
pub min_y: i32,
pub height: i32,
pub logical_height: i32,
pub infiniburn: String,
#[serde(rename = "fixed_time")]
pub fixed_time: Option<i64>,
}
// #[derive(Clone, PartialEq, Deserialize)]
// #[serde(untagged)]
// pub enum MonsterSpawnLightLevel {
// Int(i32),
// Tagged(MonsterSpawnLightLevelTagged),
// }
// #[derive(Clone, PartialEq, Deserialize)]
// pub struct MonsterSpawnLightLevelTagged {
// min_inclusive: i32,
// max_inclusive: i32,
// r#type: String,
// }
// impl From<i32> for MonsterSpawnLightLevel {
// fn from(value: i32) -> Self {
// Self::Int(value)
// }
// }
pub fn build() -> TokenStream {
let dimensions: BTreeMap<String, Dimension> = serde_json::from_str(
&fs::read_to_string("../assets/dimension.json").expect("Missing dimension.json"),
)
.expect("Failed to parse dimension.json");
let mut variants = TokenStream::new();
let mut name_to_type = TokenStream::new();
// Iterate with index to generate a unique numeric ID
for (id, (name, dim)) in dimensions.into_iter().enumerate() {
let id = id as u8; // Overworld=0, Nether=1, End=2 (usually)
let format_name = format_ident!(
"{}",
name.strip_prefix("minecraft:")
.unwrap_or(&name)
.to_shouty_snake_case()
);
let fixed_time = if let Some(t) = dim.fixed_time {
quote! { Some(#t) }
} else {
quote! { None }
};
let ambient_light = dim.ambient_light;
let coordinate_scale = dim.coordinate_scale;
let height = dim.height;
let min_y = dim.min_y;
let logical_height = dim.logical_height;
let has_skylight = dim.has_skylight;
let has_ceiling = dim.has_ceiling;
let infiniburn = &dim.infiniburn;
let minecraft_name = if name.contains(':') {
name.clone()
} else {
format!("minecraft:{name}")
};
variants.extend(quote! {
pub const #format_name: Self = Self {
id: #id,
minecraft_name: #minecraft_name,
fixed_time: #fixed_time,
has_skylight: #has_skylight,
has_ceiling: #has_ceiling,
coordinate_scale: #coordinate_scale,
min_y: #min_y,
height: #height,
logical_height: #logical_height,
infiniburn: #infiniburn,
ambient_light: #ambient_light,
};
});
name_to_type.extend(quote! {
#minecraft_name => Some(&Self::#format_name),
});
}
quote!(
#[derive(Debug, Clone, Copy)]
pub struct Dimension {
pub id: u8,
pub minecraft_name: &'static str,
pub fixed_time: Option<i64>,
pub has_skylight: bool,
pub has_ceiling: bool,
pub coordinate_scale: f64,
pub min_y: i32,
pub height: i32,
pub logical_height: i32,
pub infiniburn: &'static str,
pub ambient_light: f32,
}
impl Dimension {
#variants
pub fn from_name(name: &str) -> Option<&'static Self> {
match name {
#name_to_type
_ => None
}
}
}
impl PartialEq for Dimension {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for Dimension {}
)
}
+156
View File
@@ -0,0 +1,156 @@
use std::{collections::BTreeMap, fs};
use heck::{ToPascalCase, ToShoutySnakeCase};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use serde::Deserialize;
#[derive(Deserialize)]
struct Effect {
id: u8,
category: MobEffectCategory,
color: i32,
translation_key: String,
attribute_modifiers: Vec<Modifiers>,
}
#[expect(clippy::upper_case_acronyms)]
#[derive(Deserialize)]
pub enum MobEffectCategory {
BENEFICIAL,
HARMFUL,
NEUTRAL,
}
#[derive(Deserialize)]
pub struct Modifiers {
attribute: String,
id: String,
#[serde(rename = "baseValue")]
base_value: f64,
operation: String,
}
impl Modifiers {
pub fn get_tokens(self) -> TokenStream {
let attribute = format_ident!("{}", self.attribute.to_uppercase());
let id = self.id;
let base_value = self.base_value;
let operation = format_ident!("{}", self.operation.to_pascal_case());
quote! {
Modifiers {
attribute: &Attributes::#attribute,
id: #id,
base_value: #base_value,
operation: Operation::#operation,
}
}
}
}
impl MobEffectCategory {
pub fn to_tokens(&self) -> TokenStream {
match self {
Self::BENEFICIAL => quote! { MobEffectCategory::Beneficial },
Self::HARMFUL => quote! { MobEffectCategory::Harmful },
Self::NEUTRAL => quote! { MobEffectCategory::Neutral },
}
}
}
pub fn build() -> TokenStream {
let effects: BTreeMap<String, Effect> =
serde_json::from_str(&fs::read_to_string("../assets/effect.json").unwrap())
.expect("Failed to parse effect.json");
let mut variants = TokenStream::new();
let mut name_to_type = TokenStream::new();
let mut minecraft_name_to_type = TokenStream::new();
for (name, effect) in effects {
let format_name = format_ident!("{}", name.to_shouty_snake_case());
let id = effect.id;
let color = effect.color;
let translation_key = effect.translation_key;
let category = effect.category.to_tokens();
let slots = effect.attribute_modifiers;
let slots = slots.into_iter().map(Modifiers::get_tokens);
let minecraft_name = "minecraft:".to_string() + &name;
variants.extend([quote! {
pub const #format_name: Self = Self {
minecraft_name: #minecraft_name,
id: #id,
category: #category,
color: #color,
translation_key: #translation_key,
attribute_modifiers: &[#(#slots),*],
};
}]);
name_to_type.extend(quote! { #name => Some(&Self::#format_name), });
minecraft_name_to_type.extend(quote! { #minecraft_name => Some(&Self::#format_name), });
}
quote! {
use std::hash::{Hash, Hasher};
use crate::attributes::Attributes;
use crate::data_component_impl::Operation;
pub struct StatusEffect {
pub minecraft_name: &'static str,
pub id: u8,
pub category: MobEffectCategory,
pub color: i32,
pub translation_key: &'static str,
pub attribute_modifiers: &'static [Modifiers],
}
impl PartialEq for StatusEffect {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for StatusEffect {}
impl Hash for StatusEffect {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
#[derive(Debug, Clone, Hash)]
pub enum MobEffectCategory {
Beneficial,
Harmful,
Neutral,
}
#[derive(Debug)]
pub struct Modifiers {
pub attribute: &'static Attributes,
pub id: &'static str,
pub base_value: f64,
pub operation: Operation,
}
impl StatusEffect {
#variants
pub fn from_name(name: &str) -> Option<&'static Self> {
match name {
#name_to_type
_ => None
}
}
pub fn from_minecraft_name(name: &str) -> Option<&'static Self> {
match name {
#name_to_type
_ => None
}
}
}
}
}
+246
View File
@@ -0,0 +1,246 @@
use std::{collections::BTreeMap, fs};
use heck::ToShoutySnakeCase;
use proc_macro2::TokenStream;
use pumpkin_util::text::TextComponent;
use pumpkin_util::text::TextContent::Translate;
use quote::{format_ident, quote};
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Enchantment {
pub id: u8,
pub anvil_cost: u32,
pub supported_items: String,
pub description: TextComponent,
pub exclusive_set: Option<String>,
pub max_level: i32,
pub slots: Vec<AttributeModifierSlot>, // TODO: add more
}
#[derive(Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
pub enum AttributeModifierSlot {
Any,
MainHand,
OffHand,
Hand,
Feet,
Legs,
Chest,
Head,
Armor,
Body,
Saddle,
}
impl AttributeModifierSlot {
pub fn to_tokens(&self) -> TokenStream {
match self {
Self::Any => quote! { AttributeModifierSlot::Any },
Self::MainHand => quote! { AttributeModifierSlot::MainHand },
Self::OffHand => quote! { AttributeModifierSlot::OffHand },
Self::Hand => quote! { AttributeModifierSlot::Hand },
Self::Feet => quote! { AttributeModifierSlot::Feet },
Self::Legs => quote! { AttributeModifierSlot::Legs },
Self::Chest => quote! { AttributeModifierSlot::Chest },
Self::Head => quote! { AttributeModifierSlot::Head },
Self::Armor => quote! { AttributeModifierSlot::Armor },
Self::Body => quote! { AttributeModifierSlot::Body },
Self::Saddle => quote! { AttributeModifierSlot::Saddle },
}
}
}
pub fn build() -> TokenStream {
let enchantments: BTreeMap<String, Enchantment> =
serde_json::from_str(&fs::read_to_string("../assets/enchantments.json").unwrap())
.expect("Failed to parse enchantments.json");
let mut variants = TokenStream::new();
let mut name_to_type = TokenStream::new();
let mut id_to_type = TokenStream::new();
for (name, enchantment) in enchantments {
let id = enchantment.id;
let raw_name = name.strip_prefix("minecraft:").unwrap();
let format_name = format_ident!("{}", raw_name.to_shouty_snake_case());
let anvil_cost = enchantment.anvil_cost;
let supported_items = format_ident!(
"{}",
enchantment
.supported_items
.strip_prefix("#")
.unwrap()
.replace([':', '/'], "_")
.to_uppercase()
);
let max_level = enchantment.max_level;
let slots = enchantment.slots;
let slots = slots.iter().map(AttributeModifierSlot::to_tokens);
let Translate { translate, with: _ } = &*enchantment.description.0.content else {
panic!()
};
let translate = translate.to_string();
if let Some(exclusive_set) = &enchantment.exclusive_set {
let exclusive_set = format_ident!(
"{}",
exclusive_set
.strip_prefix("#")
.unwrap()
.replace([':', '/'], "_")
.to_uppercase()
);
variants.extend([quote! {
pub const #format_name: Self = Self {
id: #id,
name: #name,
registry_key: #raw_name,
description: #translate,
anvil_cost: #anvil_cost,
supported_items: &ItemTag::#supported_items,
exclusive_set: Some(&EnchantmentTag::#exclusive_set),
max_level: #max_level,
slots: &[#(#slots),*]
};
}]);
} else {
variants.extend([quote! {
pub const #format_name: Self = Self {
id: #id,
name: #name,
description: #translate,
registry_key: #raw_name,
anvil_cost: #anvil_cost,
supported_items: &ItemTag::#supported_items,
exclusive_set: None,
max_level: #max_level,
slots: &[#(#slots),*]
};
}]);
}
name_to_type.extend(quote! { #name => Some(&Self::#format_name), });
id_to_type.extend(quote! { #id => Some(&Self::#format_name), });
}
quote! {
use crate::item::Item;
use crate::tag::Enchantment as EnchantmentTag;
use crate::tag::Item as ItemTag;
use crate::tag::{RegistryKey, Tag, Taggable};
use crate::data_component_impl::EnchantmentsImpl;
use pumpkin_util::text::TextComponent;
use pumpkin_util::text::color::NamedColor;
use std::hash::{Hash, Hasher};
use std::slice::Iter;
pub struct Enchantment {
pub id: u8,
pub name: &'static str,
pub registry_key: &'static str,
pub description: &'static str, // TODO use TextComponent
pub anvil_cost: u32,
pub supported_items: &'static Tag,
pub exclusive_set: Option<&'static Tag>,
pub max_level: i32,
pub slots: &'static [AttributeModifierSlot]
// TODO: add more
}
impl Taggable for Enchantment {
#[inline]
fn tag_key() -> RegistryKey {
RegistryKey::Enchantment
}
#[inline]
fn registry_key(&self) -> &str {
self.registry_key
}
#[inline]
fn registry_id(&self) -> u16 {
self.id as u16
}
}
impl PartialEq for Enchantment {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for Enchantment {}
impl Hash for Enchantment {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
#[derive(Debug, Clone, Hash, PartialEq)]
pub enum AttributeModifierSlot {
Any,
MainHand,
OffHand,
Hand,
Feet,
Legs,
Chest,
Head,
Armor,
Body,
Saddle,
}
impl Enchantment {
#variants
pub fn from_name(name: &str) -> Option<&'static Self> {
match name {
#name_to_type
_ => None
}
}
pub fn from_id(id: u8) -> Option<&'static Self> {
match id {
#id_to_type
_ => None
}
}
pub fn can_enchant(&self, item: &'static Item) -> bool {
self.supported_items.1.contains(&item.id)
}
pub fn are_compatible(&self, other: &'static Enchantment) -> bool {
if self == other {
return false;
}
if let Some(tag) = self.exclusive_set && tag.1.contains(&(other.id as u16)) {
return false;
}
if let Some(tag) = other.exclusive_set && tag.1.contains(&(self.id as u16)) {
return false;
}
true
}
pub fn is_enchantment_compatible(&self, other: &EnchantmentsImpl) -> bool {
for (i, _) in other.enchantment.iter() {
if !self.are_compatible(i) {
return false;
}
}
true
}
pub fn get_fullname(&self, level: i32) -> TextComponent {
let mut ret = TextComponent::translate(self.description, []).color_named(
if self.has_tag(&EnchantmentTag::MINECRAFT_CURSE) {
NamedColor::Red
} else {
NamedColor::Gray
}
);
if level != 1 || self.max_level != 1 {
ret = ret.add_text(" ")
.add_child(TextComponent::translate("enchantment.level.".to_string() + &level.to_string(), []));
}
ret
}
}
}
}
+20
View File
@@ -0,0 +1,20 @@
use std::fs;
use proc_macro2::TokenStream;
use quote::quote;
use crate::array_to_tokenstream;
pub fn build() -> TokenStream {
let poses: Vec<String> =
serde_json::from_str(&fs::read_to_string("../assets/entity_pose.json").unwrap())
.expect("Failed to parse entity_pose.json");
let variants = array_to_tokenstream(&poses);
quote! {
#[derive(PartialEq, Clone, Copy)]
pub enum EntityPose {
#variants
}
}
}
+29
View File
@@ -0,0 +1,29 @@
use std::{collections::BTreeMap, fs};
use heck::ToPascalCase;
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use syn::LitInt;
pub fn build() -> TokenStream {
let events: BTreeMap<String, u8> =
serde_json::from_str(&fs::read_to_string("../assets/entity_statuses.json").unwrap())
.expect("Failed to parse entity_statuses.json");
let variants: Vec<TokenStream> = events
.into_iter()
.map(|(event_name, id)| {
let name = format_ident!("{}", event_name.to_pascal_case());
let id_lit = LitInt::new(&id.to_string(), Span::call_site());
quote! {
#name = #id_lit
}
})
.collect();
quote! {
#[repr(u8)]
pub enum EntityStatus {
#(#variants),*
}
}
}
+364
View File
@@ -0,0 +1,364 @@
use std::{collections::BTreeMap, fs};
use proc_macro2::TokenStream;
use pumpkin_util::HeightMap;
use quote::{ToTokens, format_ident, quote};
use serde::Deserialize;
use syn::LitInt;
use crate::loot::LootTableStruct;
#[derive(Deserialize)]
pub struct EntityType {
pub id: u16,
pub max_health: Option<f32>,
pub attackable: Option<bool>,
pub mob: Option<bool>,
pub limit_per_chunk: Option<i32>,
pub loot_table: Option<LootTableStruct>,
pub summonable: bool,
pub fire_immune: bool,
pub saveable: bool,
pub category: MobCategory,
pub can_spawn_far_from_player: bool,
pub dimension: [f32; 2],
pub eye_height: f32,
pub spawn_restriction: SpawnRestriction,
}
#[derive(Deserialize)]
pub struct SpawnRestriction {
location: SpawnLocation,
heightmap: HeightMap,
}
#[derive(Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SpawnLocation {
InLava,
InWater,
OnGround,
Unrestricted,
}
#[derive(Deserialize)]
#[expect(non_camel_case_types)]
#[expect(clippy::upper_case_acronyms)]
pub enum MobCategory {
MONSTER,
CREATURE,
AMBIENT,
AXOLOTLS,
UNDERGROUND_WATER_CREATURE,
WATER_CREATURE,
WATER_AMBIENT,
MISC,
}
pub struct NamedEntityType<'a>(&'a str, &'a EntityType);
impl ToTokens for NamedEntityType<'_> {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name = self.0;
let entity = self.1;
let id = LitInt::new(&entity.id.to_string(), proc_macro2::Span::call_site());
let max_health = if let Some(mh) = entity.max_health {
quote! { Some(#mh) }
} else {
quote! { None }
};
let attackable = if let Some(a) = entity.attackable {
quote! { Some(#a) }
} else {
quote! { None }
};
let spawn_restriction_location = match entity.spawn_restriction.location {
SpawnLocation::InLava => quote! {SpawnLocation::InLava},
SpawnLocation::InWater => quote! {SpawnLocation::InWater},
SpawnLocation::OnGround => quote! {SpawnLocation::OnGround},
SpawnLocation::Unrestricted => quote! {SpawnLocation::Unrestricted},
};
let spawn_restriction_heightmap = match entity.spawn_restriction.heightmap {
HeightMap::WorldSurfaceWg => quote! { HeightMap::WorldSurfaceWg },
HeightMap::WorldSurface => quote! { HeightMap::WorldSurface },
HeightMap::OceanFloorWg => quote! { HeightMap::OceanFloorWg },
HeightMap::OceanFloor => quote! { HeightMap::OceanFloor },
HeightMap::MotionBlocking => quote! { HeightMap::MotionBlocking },
HeightMap::MotionBlockingNoLeaves => quote! { HeightMap::MotionBlockingNoLeaves },
};
let spawn_restriction = quote! { SpawnRestriction {
location: #spawn_restriction_location,
heightmap: #spawn_restriction_heightmap,
}};
let spawn_category = match entity.category {
MobCategory::MONSTER => quote! { MobCategory::MONSTER },
MobCategory::CREATURE => quote! { MobCategory::CREATURE },
MobCategory::AMBIENT => quote! { MobCategory::AMBIENT },
MobCategory::AXOLOTLS => quote! { MobCategory::AXOLOTLS },
MobCategory::UNDERGROUND_WATER_CREATURE => {
quote! { MobCategory::UNDERGROUND_WATER_CREATURE }
}
MobCategory::WATER_CREATURE => quote! { MobCategory::WATER_CREATURE },
MobCategory::WATER_AMBIENT => quote! { MobCategory::WATER_AMBIENT },
MobCategory::MISC => quote! { MobCategory::MISC },
};
let saveable = entity.saveable;
let summonable = entity.summonable;
let fire_immune = entity.fire_immune;
let eye_height = entity.eye_height;
assert!(
!(entity.mob.is_none() && name != "player"),
"missing field 'mob', entity name {name}"
);
assert!(
!(entity.limit_per_chunk.is_none() && name != "player"),
"missing field 'mob', entity name {name}"
);
let mob = entity.mob.unwrap_or(false);
let limit_per_chunk = entity.limit_per_chunk.unwrap_or(0);
let can_spawn_far_from_player = entity.can_spawn_far_from_player;
let dimension0 = entity.dimension[0];
let dimension1 = entity.dimension[1];
let loot_table = if let Some(table) = &entity.loot_table {
let table_tokens = table.to_token_stream();
quote! { Some(#table_tokens) }
} else {
quote! { None }
};
tokens.extend(quote! {
EntityType {
id: #id,
max_health: #max_health,
attackable: #attackable,
mob: #mob,
saveable: #saveable,
limit_per_chunk: #limit_per_chunk,
summonable: #summonable,
fire_immune: #fire_immune,
category: &#spawn_category,
can_spawn_far_from_player: #can_spawn_far_from_player,
loot_table: #loot_table,
dimension: [#dimension0, #dimension1], // Correctly construct the array
eye_height: #eye_height,
spawn_restriction: #spawn_restriction,
resource_name: #name,
}
});
}
}
pub fn build() -> TokenStream {
let json: BTreeMap<String, EntityType> =
serde_json::from_str(&fs::read_to_string("../assets/entities.json").unwrap())
.expect("Failed to parse entities.json");
let mut consts = TokenStream::new();
let mut type_from_raw_id_arms = TokenStream::new();
let mut type_from_name = TokenStream::new();
for (name, entity) in &json {
let id = entity.id as u8;
let id_lit = LitInt::new(&id.to_string(), proc_macro2::Span::call_site());
let upper_name = format_ident!("{}", name.to_uppercase());
let entity_tokens = NamedEntityType(name, entity).to_token_stream();
consts.extend(quote! {
pub const #upper_name: EntityType = #entity_tokens;
});
type_from_raw_id_arms.extend(quote! {
#id_lit => Some(&Self::#upper_name),
});
type_from_name.extend(quote! {
#name => Some(&Self::#upper_name),
});
}
quote! {
use crate::tag::Taggable;
use crate::tag::RegistryKey;
use pumpkin_util::loot_table::*;
use pumpkin_util::HeightMap;
use std::hash::Hash;
#[derive(Debug)]
pub struct EntityType {
pub id: u16,
pub max_health: Option<f32>,
pub attackable: Option<bool>,
pub mob: bool,
pub saveable: bool,
pub limit_per_chunk: i32,
pub summonable: bool,
pub fire_immune: bool,
pub category: &'static MobCategory,
pub can_spawn_far_from_player: bool,
pub loot_table: Option<LootTable>,
pub dimension: [f32; 2],
pub eye_height: f32,
pub spawn_restriction: SpawnRestriction,
pub resource_name: &'static str,
}
impl Hash for EntityType {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl PartialEq for EntityType {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for EntityType {}
impl Taggable for EntityType {
#[inline]
fn tag_key() -> RegistryKey {
RegistryKey::EntityType
}
#[inline]
fn registry_key(&self) -> &str {
self.resource_name
}
#[inline]
fn registry_id(&self) -> u16 {
self.id
}
}
#[derive(Debug)]
pub struct SpawnRestriction {
pub location: SpawnLocation,
pub heightmap: HeightMap,
}
#[derive(Debug)]
pub enum SpawnLocation {
InLava,
InWater,
OnGround,
Unrestricted,
}
#[derive(Debug)]
pub struct MobCategory {
pub id: usize, // mojang don't have this field
pub max: i32,
pub is_friendly: bool,
pub is_persistent: bool,
pub despawn_distance: i32,
}
impl PartialEq for MobCategory {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl MobCategory {
pub const NO_DESPAWN_DISTANCE: i32 = 32;
pub const MONSTER: MobCategory = MobCategory {
id: 0,
max: 70,
is_friendly: false,
is_persistent: false,
despawn_distance: 128,
};
pub const CREATURE: MobCategory = MobCategory {
id: 1,
max: 10,
is_friendly: true,
is_persistent: true,
despawn_distance: 128,
};
pub const AMBIENT: MobCategory = MobCategory {
id: 2,
max: 15,
is_friendly: true,
is_persistent: false,
despawn_distance: 128,
};
pub const AXOLOTLS: MobCategory = MobCategory {
id: 3,
max: 5,
is_friendly: true,
is_persistent: false,
despawn_distance: 128,
};
pub const UNDERGROUND_WATER_CREATURE: MobCategory = MobCategory {
id: 4,
max: 5,
is_friendly: true,
is_persistent: false,
despawn_distance: 128,
};
pub const WATER_CREATURE: MobCategory = MobCategory {
id: 5,
max: 5,
is_friendly: true,
is_persistent: true,
despawn_distance: 128,
};
pub const WATER_AMBIENT: MobCategory = MobCategory {
id: 6,
max: 20,
is_friendly: true,
is_persistent: false,
despawn_distance: 64,
};
pub const MISC: MobCategory = MobCategory {
id: 7,
max: -1,
is_friendly: true,
is_persistent: true,
despawn_distance: 128,
};
pub const SPAWNING_CATEGORIES: [&'static Self; 8] = [
&Self::MONSTER,
&Self::CREATURE,
&Self::AMBIENT,
&Self::AXOLOTLS,
&Self::UNDERGROUND_WATER_CREATURE,
&Self::WATER_CREATURE,
&Self::WATER_AMBIENT,
&Self::MISC,
];
}
impl EntityType {
#consts
pub const fn from_raw(id: u16) -> Option<&'static Self> {
match id {
#type_from_raw_id_arms
_ => None
}
}
pub fn from_name(name: &str) -> Option<&'static Self> {
let name = name.strip_prefix("minecraft:").unwrap_or(name);
match name {
#type_from_name
_ => None
}
}
}
}
}
@@ -0,0 +1,29 @@
use proc_macro2::{Span, TokenStream};
use quote::quote;
use std::{collections::BTreeMap, fs};
use syn::LitInt;
pub fn build() -> TokenStream {
let flower_pot_transformation: BTreeMap<u16, u16> = serde_json::from_str(
&fs::read_to_string("../assets/flower_pot_transformations.json").unwrap(),
)
.expect("Failed to parse flower_pot_transformations.json");
let match_arms: Vec<TokenStream> = flower_pot_transformation
.into_iter()
.map(|(item_id, potted_block_id)| {
let item_id_lit = LitInt::new(&item_id.to_string(), Span::call_site());
let potted_id_lit = LitInt::new(&potted_block_id.to_string(), Span::call_site());
quote! {
#item_id_lit => #potted_id_lit,
}
})
.collect();
quote! {
#[must_use]
pub const fn get_potted_item(item_id: u16) -> u16 {
match item_id {
#(#match_arms)*
_ => 0,
}
}
}
}
+825
View File
@@ -0,0 +1,825 @@
use heck::{ToShoutySnakeCase, ToUpperCamelCase};
use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, format_ident, quote};
use serde::Deserialize;
use std::{
collections::{BTreeMap, HashSet},
fs,
};
use syn::{Ident, LitInt, LitStr};
fn const_fluid_name_from_fluid_name(fluid: &str) -> String {
fluid.to_shouty_snake_case()
}
fn property_group_name_from_derived_name(name: &str) -> String {
format!("{name}_fluid_properties").to_upper_camel_case()
}
struct PropertyVariantMapping {
original_name: String,
property_enum: String,
}
struct PropertyCollectionData {
variant_mappings: Vec<PropertyVariantMapping>,
fluid_names: Vec<String>,
}
impl PropertyCollectionData {
pub fn add_fluid_name(&mut self, fluid_name: String) {
self.fluid_names.push(fluid_name);
}
pub const fn from_mappings(variant_mappings: Vec<PropertyVariantMapping>) -> Self {
Self {
variant_mappings,
fluid_names: Vec::new(),
}
}
pub fn derive_name(&self) -> String {
format!("{}_like", self.fluid_names[0])
}
}
#[derive(Deserialize, Clone, Debug)]
pub struct PropertyStruct {
pub name: String,
pub values: Vec<String>,
}
impl ToTokens for PropertyStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name = Ident::new(&self.name, Span::call_site());
let variant_count = self.values.len() as u16;
let values_index = (0..self.values.len() as u16).collect::<Vec<_>>();
let ident_values = self.values.iter().map(|value| {
let value_str = if value.chars().all(char::is_numeric) {
format!("L{value}")
} else {
value.clone()
};
Ident::new(&value_str.to_upper_camel_case(), Span::call_site())
});
let values_2 = ident_values.clone();
let values_3 = ident_values.clone();
let from_values = self.values.iter().map(|value| {
let value_str = if value.chars().all(char::is_numeric) {
format!("L{value}")
} else {
value.clone()
};
let ident = Ident::new(&value_str.to_upper_camel_case(), Span::call_site());
quote! {
#value => Self::#ident
}
});
let to_values = self.values.iter().map(|value| {
let value_str = if value.chars().all(char::is_numeric) {
format!("L{value}")
} else {
value.clone()
};
let ident = Ident::new(&value_str.to_upper_camel_case(), Span::call_site());
quote! {
Self::#ident => #value
}
});
tokens.extend(quote! {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum #name {
#(#ident_values),*
}
impl EnumVariants for #name {
fn variant_count() -> u16 {
#variant_count
}
fn to_index(&self) -> u16 {
match self {
#(Self::#values_2 => #values_index),*
}
}
fn from_index(index: u16) -> Self {
match index {
#(#values_index => Self::#values_3,)*
_ => panic!("Invalid index: {index}"),
}
}
fn to_value(&self) -> &str {
match self {
#(#to_values),*
}
}
fn from_value(value: &str) -> Self {
match value {
#(#from_values),*,
_ => panic!("Invalid value: {value:?}"),
}
}
}
});
}
}
struct FluidPropertyStruct {
data: PropertyCollectionData,
}
impl ToTokens for FluidPropertyStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let struct_name = property_group_name_from_derived_name(&self.data.derive_name());
let name = Ident::new(&struct_name, Span::call_site());
let values = self.data.variant_mappings.iter().map(|entry| {
let key = Ident::new_raw(&entry.original_name, Span::call_site());
let value = Ident::new(&entry.property_enum, Span::call_site());
quote! {
#key: #value
}
});
let fluid_names = &self.data.fluid_names;
let field_names: Vec<_> = self
.data
.variant_mappings
.iter()
.rev()
.map(|entry| Ident::new_raw(&entry.original_name, Span::call_site()))
.collect();
let field_types: Vec<_> = self
.data
.variant_mappings
.iter()
.rev()
.map(|entry| Ident::new(&entry.property_enum, Span::call_site()))
.collect();
let to_props_values = self.data.variant_mappings.iter().map(|entry| {
let key = &entry.original_name;
let key2 = Ident::new_raw(&entry.original_name, Span::call_site());
quote! {
(#key.to_string(), self.#key2.to_value().to_string()),
}
});
let from_props_values = self.data.variant_mappings.iter().map(|entry| {
let key = &entry.original_name;
let key2 = Ident::new_raw(&entry.original_name, Span::call_site());
let value = Ident::new(&entry.property_enum, Span::call_site());
quote! {
#key => fluid_props.#key2 = #value::from_value(&value)
}
});
tokens.extend(quote! {
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct #name {
#(pub #values),*
}
impl FluidProperties for #name {
#[allow(unused_assignments)]
fn to_index(&self) -> u16 {
let mut index = 0;
let mut multiplier = 1;
#(
index += self.#field_names.to_index() * multiplier;
multiplier *= #field_types::variant_count();
)*
index
}
#[allow(unused_assignments)]
fn from_index(mut index: u16) -> Self {
Self {
#(
#field_names: {
let value = index % #field_types::variant_count();
index /= #field_types::variant_count();
#field_types::from_index(value)
}
),*
}
}
fn to_state_id(&self, fluid: &Fluid) -> u16 {
if ![#(#fluid_names),*].contains(&fluid.name) {
panic!("{} is not a valid fluid for {}", &fluid.name, #struct_name);
}
let prop_index = self.to_index();
if prop_index < fluid.states.len() as u16 {
fluid.states[prop_index as usize].block_state_id
} else {
fluid.states[fluid.default_state_index as usize].block_state_id
}
}
fn from_state_id(state_id: u16, fluid: &Fluid) -> Self {
if ![#(#fluid_names),*].contains(&fluid.name) {
panic!("{} is not a valid fluid for {}", &fluid.name, #struct_name);
}
for (idx, state) in fluid.states.iter().enumerate() {
if state.block_state_id == state_id {
return Self::from_index(idx as u16);
}
}
Self::from_index(fluid.default_state_index)
}
fn default(fluid: &Fluid) -> Self {
if ![#(#fluid_names),*].contains(&fluid.name) {
panic!("{} is not a valid fluid for {}", &fluid.name, #struct_name);
}
Self::from_state_id(fluid.default_state_index, fluid)
}
fn to_props(&self) -> Vec<(String, String)> {
vec![#(#to_props_values)*]
}
fn from_props(props: Vec<(String, String)>, fluid: &Fluid) -> Self {
if ![#(#fluid_names),*].contains(&fluid.name) {
panic!("{} is not a valid fluid for {}", &fluid.name, #struct_name);
}
let mut fluid_props = Self::default(fluid);
for (key, value) in props {
match key.as_str() {
#(#from_props_values),*,
_ => panic!("Invalid key: {key}"),
}
}
fluid_props
}
}
});
}
}
#[derive(Deserialize, Clone)]
struct FluidState {
height: f32,
level: i16,
is_empty: bool,
blast_resistance: f32,
block_state_id: u16,
is_still: bool,
// We'll derive is_source and falling from existing fields instead of requiring them in JSON
}
#[derive(Clone, Debug)]
struct FluidStateRef {
pub id: u16,
pub state_idx: u16,
}
impl ToTokens for FluidStateRef {
fn to_tokens(&self, tokens: &mut TokenStream) {
let id = LitInt::new(&self.id.to_string(), Span::call_site());
let state_idx = LitInt::new(&self.state_idx.to_string(), Span::call_site());
tokens.extend(quote! {
FluidStateRef {
id: #id,
state_idx: #state_idx,
}
});
}
}
#[derive(Deserialize, Clone)]
struct Property {
name: String,
values: Vec<String>,
}
#[derive(Deserialize, Clone)]
pub struct Fluid {
pub name: String,
pub id: u16,
properties: Vec<Property>,
default_state_index: u16,
states: Vec<FluidState>,
#[serde(default = "default_flow_speed")]
flow_speed: u32,
#[serde(default = "default_flow_distance")]
flow_distance: u32,
#[serde(default)]
can_convert_to_source: bool,
}
const fn default_flow_speed() -> u32 {
5 // Default to water's speed
}
const fn default_flow_distance() -> u32 {
4 // Default to water's distance
}
pub fn build() -> TokenStream {
let fluids: Vec<Fluid> =
match serde_json::from_str(&fs::read_to_string("../assets/fluids.json").unwrap()) {
Ok(fluids) => fluids,
Err(e) => panic!("Failed to parse fluids.json: {e}"),
};
let mut constants = TokenStream::new();
let mut id_matches = Vec::new();
let mut type_from_name = TokenStream::new();
let mut type_from_raw_id_arms = TokenStream::new();
let mut fluid_from_state_id = TokenStream::new();
let mut fluid_properties_from_state_and_name = TokenStream::new();
let mut fluid_properties_from_props_and_name = TokenStream::new();
// Used to create property `enum`s.
let mut property_enums: BTreeMap<String, PropertyStruct> = BTreeMap::new();
// Property implementation for a fluid.
let mut fluid_properties: Vec<FluidPropertyStruct> = Vec::new();
// Mapping of a collection of property names -> fluids that have these properties.
let mut property_collection_map: BTreeMap<Vec<String>, PropertyCollectionData> =
BTreeMap::new();
// Validator that we have no `enum` collisions.
let mut enum_to_values: BTreeMap<String, Vec<String>> = BTreeMap::new();
// Collect unique fluid states to create partial states
let mut unique_states = Vec::new();
let mut optimized_fluids: Vec<(String, FluidStateRef)> = Vec::new();
for fluid in fluids {
let id_name = LitStr::new(&fluid.name, proc_macro2::Span::call_site());
let const_ident = format_ident!("{}", fluid.name.to_shouty_snake_case());
let state_id_start = fluid
.states
.iter()
.map(|state| state.block_state_id)
.min()
.unwrap();
let state_id_end = fluid
.states
.iter()
.map(|state| state.block_state_id)
.max()
.unwrap();
let id_lit = LitInt::new(&fluid.id.to_string(), proc_macro2::Span::call_site());
let mut properties = TokenStream::new();
if fluid.properties.is_empty() {
properties.extend(quote!(None));
} else {
let internal_properties = fluid.properties.iter().map(|property| {
let key = LitStr::new(&property.name, proc_macro2::Span::call_site());
let values = property
.values
.iter()
.map(|value| LitStr::new(value, proc_macro2::Span::call_site()));
quote! {
(#key, &[
#(#values),*
])
}
});
properties.extend(quote! {
Some(&[
#(#internal_properties),*
])
});
}
for (idx, state) in fluid.states.iter().enumerate() {
// Check if this state is already in `unique_states` by comparing key fields
let already_exists = unique_states.iter().any(|s: &FluidState| {
s.height == state.height
&& s.level == state.level
&& s.is_empty == state.is_empty
&& s.blast_resistance == state.blast_resistance
&& s.is_still == state.is_still
});
if !already_exists {
unique_states.push(state.clone());
}
// Create a reference to the state
let state_idx = unique_states
.iter()
.position(|s| {
s.height == state.height
&& s.level == state.level
&& s.is_empty == state.is_empty
&& s.blast_resistance == state.blast_resistance
&& s.is_still == state.is_still
})
.unwrap() as u16;
optimized_fluids.push((
fluid.name.clone(),
FluidStateRef {
id: idx as u16,
state_idx,
},
));
}
fluid_from_state_id.extend(quote! {
#state_id_start..=#state_id_end => Some(&Fluid::#const_ident),
});
type_from_name.extend(quote! {
#id_name => Some(&Self::#const_ident),
});
type_from_raw_id_arms.extend(quote! {
#id_lit => Some(&Self::#const_ident),
});
let fluid_states = fluid.states.iter().map(|state| {
let height = state.height;
let level = state.level;
let is_empty = state.is_empty;
let blast_resistance = state.blast_resistance;
let block_state_id = state.block_state_id;
let is_still = state.is_still;
// Derive these values based on existing fields
let is_source = level == 0 && is_still; // Level 0 and still means it's a source
let falling = false; // Default to false - we'll handle falling in the fluid behavior code
quote! {
FluidState {
height: #height,
level: #level,
is_empty: #is_empty,
blast_resistance: #blast_resistance,
block_state_id: #block_state_id,
is_still: #is_still,
is_source: #is_source,
falling: #falling,
}
}
});
let state_id = fluid.default_state_index;
let flow_speed = fluid.flow_speed;
let flow_distance = fluid.flow_distance;
let can_convert_to_source = fluid.can_convert_to_source;
id_matches.push(quote! {
#id_name => Some(#id_lit),
});
constants.extend(quote! {
pub const #const_ident: Fluid = Fluid {
id: #id_lit,
name: #id_name,
properties: #properties,
states: &[#(#fluid_states),*],
default_state_index: #state_id,
flow_speed: #flow_speed,
flow_distance: #flow_distance,
can_convert_to_source: #can_convert_to_source,
};
});
let mut property_collection = HashSet::new();
let mut property_mapping = Vec::new();
for property in &fluid.properties {
property_collection.insert(property.name.clone());
// Get mapped property `enum` name
let renamed_property = property.name.to_upper_camel_case();
let expected_values = enum_to_values
.entry(renamed_property.clone())
.or_insert_with(|| property.values.clone());
assert!(
expected_values == &property.values,
"Enum overlap for '{}' ({:?} vs {:?})",
property.name,
&property.values,
expected_values
);
property_mapping.push(PropertyVariantMapping {
original_name: property.name.clone(),
property_enum: renamed_property.clone(),
});
// If this property doesn't have an `enum` yet, make one.
let _ = property_enums
.entry(renamed_property.clone())
.or_insert_with(|| PropertyStruct {
name: renamed_property,
values: property.values.clone(),
});
}
if !property_collection.is_empty() {
let mut property_collection = Vec::from_iter(property_collection);
property_collection.sort();
property_collection_map
.entry(property_collection)
.or_insert_with(|| PropertyCollectionData::from_mappings(property_mapping))
.add_fluid_name(fluid.name.clone());
}
}
let unique_fluid_states = unique_states.iter().map(|state| {
let height = state.height;
let level = state.level;
let is_empty = state.is_empty;
let blast_resistance = state.blast_resistance;
let block_state_id = state.block_state_id;
let is_still = state.is_still;
let is_source = level == 0 && is_still;
let falling = false;
quote! {
PartialFluidState {
height: #height,
level: #level,
is_empty: #is_empty,
blast_resistance: #blast_resistance,
block_state_id: #block_state_id,
is_still: #is_still,
is_source: #is_source,
falling: #falling,
}
}
});
for property_group in property_collection_map.into_values() {
for fluid_name in &property_group.fluid_names {
let const_fluid_name = Ident::new(
&const_fluid_name_from_fluid_name(fluid_name),
Span::call_site(),
);
let property_name = Ident::new(
&property_group_name_from_derived_name(&property_group.derive_name()),
Span::call_site(),
);
fluid_properties_from_state_and_name.extend(quote! {
#fluid_name => Box::new(#property_name::from_state_id(state_id, &Fluid::#const_fluid_name)),
});
fluid_properties_from_props_and_name.extend(quote! {
#fluid_name => Box::new(#property_name::from_props(props, &Fluid::#const_fluid_name)),
});
}
fluid_properties.push(FluidPropertyStruct {
data: property_group,
});
}
let fluid_props = fluid_properties
.iter()
.map(quote::ToTokens::to_token_stream);
let properties = property_enums
.values()
.map(quote::ToTokens::to_token_stream);
quote! {
use std::hash::{Hash, Hasher};
use crate::tag::{Taggable, RegistryKey};
use pumpkin_util::resource_location::{FromResourceLocation, ResourceLocation, ToResourceLocation};
#[derive(Clone)]
pub struct PartialFluidState {
pub height: f32,
pub level: i16,
pub is_empty: bool,
pub blast_resistance: f32,
pub block_state_id: u16,
pub is_still: bool,
pub is_source: bool,
pub falling: bool,
}
#[derive(Clone)]
pub struct FluidState {
pub height: f32,
pub level: i16,
pub is_empty: bool,
pub blast_resistance: f32,
pub block_state_id: u16,
pub is_still: bool,
pub is_source: bool,
pub falling: bool,
}
#[derive(Clone)]
pub struct FluidStateRef {
pub id: u16,
pub state_idx: u16,
}
#[derive(Clone)]
pub struct Fluid {
pub id: u16,
pub name: &'static str,
pub properties: Option<&'static [(&'static str, &'static [&'static str])]>,
pub states: &'static [FluidState],
pub default_state_index: u16,
pub flow_speed: u32,
pub flow_distance: u32,
pub can_convert_to_source: bool,
}
impl Hash for Fluid {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl PartialEq for Fluid {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for Fluid {}
pub const FLUID_STATES: &[PartialFluidState] = &[
#(#unique_fluid_states),*
];
pub trait EnumVariants {
fn variant_count() -> u16;
fn to_index(&self) -> u16;
fn from_index(index: u16) -> Self;
fn to_value(&self) -> &str;
fn from_value(value: &str) -> Self;
}
pub trait FluidProperties where Self: 'static {
// Convert properties to an index (`0` to `N-1`).
fn to_index(&self) -> u16;
// Convert an index back to properties.
fn from_index(index: u16) -> Self where Self: Sized;
// Convert properties to a state id.
fn to_state_id(&self, fluid: &Fluid) -> u16;
// Convert a state id back to properties.
fn from_state_id(state_id: u16, fluid: &Fluid) -> Self where Self: Sized;
// Get the default properties.
fn default(fluid: &Fluid) -> Self where Self: Sized;
// Convert properties to a `Vec` of `(name, value)`
fn to_props(&self) -> Vec<(String, String)>;
// Convert properties to a fluid state, and add them onto the default state.
fn from_props(props: Vec<(String, String)>, fluid: &Fluid) -> Self where Self: Sized;
}
pub fn get_fluid(registry_id: &str) -> Option<&'static Fluid> {
let key = registry_id.strip_prefix("minecraft:").unwrap_or(registry_id);
Fluid::from_registry_key(key)
}
impl Fluid {
#constants
pub fn from_registry_key(name: &str) -> Option<&'static Self> {
match name {
#type_from_name
_ => None
}
}
pub const fn from_id(id: u16) -> Option<&'static Self> {
match id {
#type_from_raw_id_arms
_ => None
}
}
#[allow(unreachable_patterns)]
pub const fn from_state_id(id: u16) -> Option<&'static Self> {
match id {
#fluid_from_state_id
_ => None
}
}
pub fn ident_to_fluid_id(name: &str) -> Option<u8> {
match name {
#(#id_matches)*
_ => None
}
}
#[track_caller]
#[doc = r" Get the properties of the fluid."]
pub fn properties(&self, state_id: u16) -> Box<dyn FluidProperties> {
match self.name {
#fluid_properties_from_state_and_name
_ => panic!("Invalid state_id")
}
}
#[track_caller]
#[doc = r" Get the properties of the fluid."]
pub fn from_properties(&self, props: Vec<(String, String)>) -> Box<dyn FluidProperties> {
match self.name {
#fluid_properties_from_props_and_name
_ => panic!("Invalid props")
}
}
// Added helper methods for fluid behavior
pub fn is_source(&self, state_id: u16) -> bool {
let idx = (state_id as usize) % self.states.len();
self.states[idx].is_source
}
pub fn is_falling(&self, state_id: u16) -> bool {
let idx = (state_id as usize) % self.states.len();
self.states[idx].falling
}
pub fn get_level(&self, state_id: u16) -> i16 {
let idx = (state_id as usize) % self.states.len();
self.states[idx].level
}
pub fn get_height(&self, state_id: u16) -> f32 {
let idx = (state_id as usize) % self.states.len();
self.states[idx].height
}
}
impl ToResourceLocation for &'static Fluid {
fn to_resource_location(&self) -> ResourceLocation {
format!("minecraft:{}", self.name)
}
}
impl FromResourceLocation for &'static Fluid {
fn from_resource_location(resource_location: &ResourceLocation) -> Option<Self> {
Fluid::from_registry_key(resource_location.strip_prefix("minecraft:").unwrap_or(resource_location))
}
}
impl FluidStateRef {
pub fn get_state(&self) -> FluidState {
let partial_state = &FLUID_STATES[self.state_idx as usize];
FluidState {
height: partial_state.height,
level: partial_state.level,
is_empty: partial_state.is_empty,
blast_resistance: partial_state.blast_resistance,
block_state_id: partial_state.block_state_id,
is_still: partial_state.is_still,
is_source: partial_state.is_source,
falling: partial_state.falling,
}
}
}
impl Taggable for Fluid {
#[inline]
fn tag_key() -> RegistryKey {
RegistryKey::Fluid
}
#[inline]
fn registry_key(&self) -> &str {
self.name
}
#[inline]
fn registry_id(&self) -> u16 {
self.id
}
}
// Added FluidLevel enum and required constants
pub const FLUID_LEVEL_SOURCE: i32 = 0;
pub const FLUID_LEVEL_FLOWING_MAX: i32 = 8;
pub const FLUID_MIN_HEIGHT: f32 = 0.0;
pub const FLUID_MAX_HEIGHT: f32 = 1.0;
#(#properties)*
#(#fluid_props)*
}
}
+46
View File
@@ -0,0 +1,46 @@
use proc_macro2::TokenStream;
use quote::quote;
use std::{collections::BTreeMap, fs};
pub fn build() -> TokenStream {
let fuels: BTreeMap<u16, u16> =
serde_json::from_str(&fs::read_to_string("../assets/fuels.json").unwrap())
.expect("Failed to parse fuels.json");
let fuel_list_tokens = fuels
.iter()
.map(|(item_id, burn_ticks)| {
quote! {
(#item_id, #burn_ticks)
}
})
.collect::<Vec<_>>();
let fuel_list_len = fuel_list_tokens.len();
let burn_tick_list_tokens = fuels
.iter()
.map(|(item_id, burn_ticks)| {
quote! {
#item_id => Some(#burn_ticks),
}
})
.collect::<Vec<_>>();
quote! {
pub const FUELS: [(u16,u16); #fuel_list_len] = [
#(#fuel_list_tokens),*
];
#[must_use]
pub const fn get_item_burn_ticks(item_id: u16) -> Option<u16> {
match item_id {
#(#burn_tick_list_tokens)*
_ => None,
}
}
#[must_use]
pub const fn is_fuel(item_id: u16) -> bool {
get_item_burn_ticks(item_id).is_some()
}
}
}
+19
View File
@@ -0,0 +1,19 @@
use std::fs;
use proc_macro2::TokenStream;
use quote::quote;
use crate::array_to_tokenstream;
pub fn build() -> TokenStream {
let game_events: Vec<String> =
serde_json::from_str(&fs::read_to_string("../assets/game_event.json").unwrap())
.expect("Failed to parse game_event.json");
let variants = array_to_tokenstream(&game_events);
quote! {
pub enum GameEvent {
#variants
}
}
}
+169
View File
@@ -0,0 +1,169 @@
use std::{collections::BTreeMap, fs};
use heck::{ToPascalCase, ToSnakeCase};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use serde_json::Value;
pub fn build() -> TokenStream {
let game_rules: BTreeMap<String, Value> =
serde_json::from_str(&fs::read_to_string("../assets/game_rules.json").unwrap())
.expect("Failed to parse game_rules.json");
let mut enum_variants = TokenStream::new();
let mut enum_variants_list = TokenStream::new();
let mut enum_to_string = TokenStream::new();
let mut struct_fields = TokenStream::new();
let mut default_values = TokenStream::new();
let mut getter_match = TokenStream::new();
let mut mut_getter_match = TokenStream::new();
let mut default_functions = TokenStream::new();
for (raw_name, raw_value) in &game_rules {
let (variant_type, field_type, default_value) = match raw_value {
Value::Bool(b) => (quote! { Bool }, quote! { bool }, quote! { #b }),
Value::Number(n) if n.is_i64() => {
let i = n.as_i64().unwrap();
(quote! { Int }, quote! { i64 }, quote! { #i })
}
_ => panic!("Unsupported value type for key '{raw_name}'"),
};
let snake_case = format_ident!("{}", raw_name.to_snake_case());
let pascal_case = format_ident!("{}", raw_name.to_pascal_case());
let default_fn_name = format!("default_{snake_case}");
let default_fn_ident = format_ident!("default_{snake_case}");
// Struct field
struct_fields.extend(quote! {
#[serde(rename = #raw_name)]
#[serde(default = #default_fn_name)]
#[serde(with = "as_string")]
pub #snake_case: #field_type,
});
// Enum variant
enum_variants.extend(quote! {
#pascal_case,
});
// Enum::all()
enum_variants_list.extend(quote! {
Self::#pascal_case,
});
// Enum -> &str
enum_to_string.extend(quote! {
Self::#pascal_case => write!(f, #raw_name),
});
// Default value
default_values.extend(quote! {
#snake_case: #default_value,
});
// Getter match arms
getter_match.extend(quote! {
GameRule::#pascal_case => GameRuleValue::#variant_type(&self.#snake_case),
});
mut_getter_match.extend(quote! {
GameRule::#pascal_case => GameRuleValue::#variant_type(&mut self.#snake_case),
});
// Default fn
default_functions.extend(quote! {
fn #default_fn_ident() -> #field_type {
GameRuleRegistry::default().#snake_case
}
});
}
quote! {
use std::fmt;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum GameRule {
#enum_variants
}
impl GameRule {
pub const fn all() -> &'static [Self] {
&[
#enum_variants_list
]
}
}
impl fmt::Display for GameRule {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
#enum_to_string
}
}
}
#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
pub struct GameRuleRegistry {
#struct_fields
}
pub enum GameRuleValue<I, B> {
Int(I),
Bool(B),
}
impl<I: fmt::Display, B: fmt::Display> fmt::Display for GameRuleValue<I, B> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Int(v) => write!(f, "{v}"),
Self::Bool(v) => write!(f, "{v}"),
}
}
}
impl GameRuleRegistry {
pub fn get(&self, rule: &GameRule) -> GameRuleValue<&i64, &bool> {
match rule {
#getter_match
}
}
pub fn get_mut(&mut self, rule: &GameRule) -> GameRuleValue<&mut i64, &mut bool> {
match rule {
#mut_getter_match
}
}
}
impl Default for GameRuleRegistry {
fn default() -> Self {
Self {
#default_values
}
}
}
#default_functions
mod as_string {
use serde::{Serialize, Deserialize, Serializer, Deserializer};
use std::{fmt::Display, str::FromStr};
pub fn serialize<T: Display, S: Serializer>(value: &T, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&value.to_string())
}
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
T: FromStr,
D: Deserializer<'de>,
<T as FromStr>::Err: Display,
{
let s = String::deserialize(deserializer)?;
s.parse::<T>().map_err(serde::de::Error::custom)
}
}
}
}
+562
View File
@@ -0,0 +1,562 @@
use crate::enchantments::AttributeModifierSlot;
use heck::ToShoutySnakeCase;
use proc_macro2::{Span, TokenStream};
use pumpkin_util::registry::TagType;
use pumpkin_util::text::TextContent;
use pumpkin_util::{registry::RegistryEntryList, text::TextComponent};
use quote::{ToTokens, format_ident, quote};
use serde::Deserialize;
use std::{collections::BTreeMap, fs};
use syn::{Ident, LitBool, LitFloat, LitInt, LitStr};
#[derive(Deserialize)]
pub struct Item {
pub id: u16,
pub components: ItemComponents,
}
#[derive(Deserialize)]
pub struct ItemComponents {
#[serde(rename = "minecraft:item_name")]
pub item_name: TextComponent,
#[serde(rename = "minecraft:max_stack_size")]
pub max_stack_size: u8,
#[serde(rename = "minecraft:jukebox_playable")]
pub jukebox_playable: Option<String>,
#[serde(rename = "minecraft:damage")]
pub damage: Option<u16>,
#[serde(rename = "minecraft:max_damage")]
pub max_damage: Option<u16>,
#[serde(rename = "minecraft:attribute_modifiers")]
pub attribute_modifiers: Option<Vec<Modifier>>,
#[serde(rename = "minecraft:tool")]
pub tool: Option<ToolComponent>,
#[serde(rename = "minecraft:food")]
pub food: Option<FoodComponent>,
#[serde(rename = "minecraft:equippable")]
pub equippable: Option<EquippableComponent>,
#[serde(rename = "minecraft:consumable")]
pub consumable: Option<Consumable>,
#[serde(rename = "minecraft:blocks_attacks")]
pub blocks_attacks: Option<BlocksAttacks>,
#[serde(rename = "minecraft:death_protection")]
pub death_protection: Option<DeathProtection>,
}
impl ToTokens for ItemComponents {
fn to_tokens(&self, tokens: &mut TokenStream) {
let max_stack_size = LitInt::new(&self.max_stack_size.to_string(), Span::call_site());
tokens.extend(quote! {
(MaxStackSize, &MaxStackSizeImpl {
size: #max_stack_size,
}),
});
if let Some(playable) = &self.jukebox_playable {
let song = LitStr::new(playable, Span::call_site());
tokens.extend(quote! {
(JukeboxPlayable, &JukeboxPlayableImpl{
song: #song,
}),
});
}
let TextContent::Translate {
translate: text,
with: _,
} = *self.item_name.clone().0.content
else {
unreachable!()
};
let item_name = LitStr::new(&text, Span::call_site());
tokens.extend(quote! {
(ItemName, &ItemNameImpl {
name: #item_name,
}),
});
if let Some(d) = self.damage {
let damage_lit = LitInt::new(&d.to_string(), Span::call_site());
tokens.extend(quote! {
(Damage, &DamageImpl {
damage: #damage_lit,
}),
});
}
if let Some(md) = self.max_damage {
let max_damage_lit = LitInt::new(&md.to_string(), Span::call_site());
tokens.extend(quote! {
(MaxDamage, &MaxDamageImpl {
max_damage: #max_damage_lit,
}),
});
}
if let Some(modifiers) = &self.attribute_modifiers {
let modifier_code = modifiers.iter().map(|modifier| {
let r#type = format_ident!(
"{}",
modifier
.r#type
.strip_prefix("minecraft:")
.unwrap()
.to_uppercase()
);
let id = LitStr::new(&modifier.id, Span::call_site());
let amount = modifier.amount;
let operation = Ident::new(&format!("{:?}", modifier.operation), Span::call_site());
let slot = modifier.slot.to_tokens();
quote! {
Modifier {
r#type: &Attributes::#r#type,
id: #id,
amount: #amount,
operation: Operation::#operation,
slot: #slot,
}
}
});
tokens.extend(quote! {
(AttributeModifiers, &AttributeModifiersImpl {
attribute_modifiers: Cow::Borrowed(&[#(#modifier_code),*])
}),
});
}
if let Some(tool) = &self.tool {
let rules_code = tool.rules.iter().map(|rule| {
let block_array;
if let RegistryEntryList::Single(t) = &rule.blocks {
if let TagType::Item(str) = t {
let ident = format_ident!(
"{}",
str.strip_prefix("minecraft:").unwrap().to_uppercase()
);
block_array = quote! {
Blocks(Cow::Borrowed(&[&Block::#ident]))
}
} else if let TagType::Tag(str) = t {
let ident =
format_ident!("{}", str.replace([':', '/'], "_").to_uppercase());
block_array = quote! {
Tag(&tag::Block::#ident)
}
} else {
unreachable!();
}
} else if let RegistryEntryList::Many(t) = &rule.blocks {
let mut array = vec![];
for i in t {
let TagType::Item(str) = i else {
unreachable!();
};
let ident = format_ident!(
"{}",
str.strip_prefix("minecraft:").unwrap().to_uppercase()
);
array.push(quote! {
&Block::#ident
});
}
block_array = quote! {
Blocks(Cow::Borrowed(&[#(#array),*]))
}
} else {
unreachable!();
}
let speed = if let Some(speed) = rule.speed {
quote! { Some(#speed) }
} else {
quote! { None }
};
let correct_for_drops = if let Some(correct_for_drops) = rule.correct_for_drops {
let correct_for_drops = LitBool::new(correct_for_drops, Span::call_site());
quote! { Some(#correct_for_drops) }
} else {
quote! { None }
};
quote! {
ToolRule {
blocks: #block_array,
speed: #speed,
correct_for_drops: #correct_for_drops
}
}
});
let damage_per_block = {
let speed = LitInt::new(&tool.damage_per_block.to_string(), Span::call_site());
quote! { #speed }
};
let default_mining_speed = {
let speed = LitFloat::new(
&format!("{:.1}", tool.default_mining_speed),
Span::call_site(),
);
quote! { #speed }
};
let can_destroy_blocks_in_creative =
LitBool::new(tool.can_destroy_blocks_in_creative, Span::call_site());
tokens.extend(quote! { (Tool, &ToolImpl {
rules: Cow::Borrowed(&[#(#rules_code),*]),
default_mining_speed: #default_mining_speed,
damage_per_block: #damage_per_block,
can_destroy_blocks_in_creative: #can_destroy_blocks_in_creative
}), });
}
if let Some(food) = &self.food {
let nutrition = LitInt::new(&food.nutrition.to_string(), Span::call_site());
let saturation = LitFloat::new(&format!("{:.1}", food.saturation), Span::call_site());
let can_always_eat = {
let can = LitBool::new(food.can_always_eat, Span::call_site());
quote! { #can }
};
tokens.extend(quote! { (Food, &FoodImpl {
nutrition: #nutrition,
saturation: #saturation,
can_always_eat: #can_always_eat,
}), });
}
if let Some(consumable) = &self.consumable {
let consume_seconds = LitFloat::new(
&format!("{:.1}", consumable.consume_seconds.unwrap_or(1.6)),
Span::call_site(),
);
tokens.extend(quote! { (Consumable, &ConsumableImpl {
consume_seconds: #consume_seconds,
}), });
}
if self.blocks_attacks.is_some() {
tokens.extend(quote! { (BlocksAttacks, &BlocksAttacksImpl), });
}
if self.death_protection.is_some() {
tokens.extend(quote! { (DeathProtection, &DeathProtectionImpl), });
}
if let Some(equippable) = &self.equippable {
let slot = match equippable.slot.as_str() {
"mainhand" => quote! { &EquipmentSlot::MAIN_HAND },
"offhand" => quote! { &EquipmentSlot::OFF_HAND },
"head" => quote! { &EquipmentSlot::HEAD },
"chest" => quote! { &EquipmentSlot::CHEST },
"legs" => quote! { &EquipmentSlot::LEGS },
"feet" => quote! { &EquipmentSlot::FEET },
"body" => quote! { &EquipmentSlot::BODY },
"saddle" => quote! { &EquipmentSlot::SADDLE },
_ => panic!("Unknown equippable slot: {}", equippable.slot),
};
let equip_sound = equippable
.equip_sound
.as_ref()
.map(|s| {
let equip_sound = LitStr::new(s, Span::call_site());
quote! { #equip_sound }
})
.unwrap_or(quote! { "item.armor.equip_generic" });
let asset_id = equippable
.asset_id
.as_ref()
.map(|s| {
let asset_id = LitStr::new(s, Span::call_site());
quote! { Some(#asset_id) }
})
.unwrap_or(quote! { None });
let camera_overlay = equippable
.camera_overlay
.as_ref()
.map(|s| {
let camera_overlay = LitStr::new(s, Span::call_site());
quote! { Some(#camera_overlay) }
})
.unwrap_or(quote! { None });
let allowed_entities = equippable
.allowed_entities
.clone()
.map(|list| {
let vec: Vec<_> = list
.into_vec()
.iter()
.map(|reg| {
match reg {
TagType::Item(item) => {
let ident = format_ident!(
"{}",
item.strip_prefix("minecraft:").unwrap().to_uppercase()
);
quote! { EntityTypeOrTag::Single(&crate::entity_type::EntityType::#ident) }
},
TagType::Tag(tag) => {
let ident = format_ident!(
"{}",
tag.replace([':', '/'], "_").to_uppercase()
);
quote! { EntityTypeOrTag::Tag(&crate::tag::EntityType::#ident) }
}
}
})
.collect();
quote! {
Some(&[#(#vec),*])
}
})
.unwrap_or(quote! { None });
let dispensable = LitBool::new(equippable.dispensable, Span::call_site());
let swappable = LitBool::new(equippable.swappable, Span::call_site());
let damage_on_hurt = LitBool::new(equippable.damage_on_hurt, Span::call_site());
let equip_on_interact = LitBool::new(equippable.equip_on_interact, Span::call_site());
let can_be_sheared = LitBool::new(equippable.can_be_sheared, Span::call_site());
let shearing_sound = equippable
.shearing_sound
.as_ref()
.map(|s| {
let shearing_sound = LitStr::new(s, Span::call_site());
quote! {
Some(#shearing_sound)
}
})
.unwrap_or(quote! { None });
tokens.extend(quote! { (Equippable, &EquippableImpl {
slot: #slot,
equip_sound: #equip_sound,
asset_id: #asset_id,
camera_overlay: #camera_overlay,
allowed_entities: #allowed_entities,
dispensable: #dispensable,
swappable: #swappable,
damage_on_hurt: #damage_on_hurt,
equip_on_interact: #equip_on_interact,
can_be_sheared: #can_be_sheared,
shearing_sound: #shearing_sound
}), });
}
}
}
const fn return_1u32() -> u32 {
1
}
const fn return_1f32() -> f32 {
1.
}
const fn return_true() -> bool {
true
}
#[derive(Deserialize)]
pub struct ToolComponent {
rules: Vec<ToolRule>,
#[serde(default = "return_1f32")]
default_mining_speed: f32,
#[serde(default = "return_1u32")]
damage_per_block: u32,
#[serde(default = "return_true")]
can_destroy_blocks_in_creative: bool,
}
const fn return_false() -> bool {
false
}
#[derive(Deserialize, Copy, Clone)]
pub struct FoodComponent {
nutrition: u8,
saturation: f32,
#[serde(default = "return_false")]
can_always_eat: bool,
}
#[derive(Deserialize, Clone)]
pub struct ToolRule {
blocks: RegistryEntryList,
speed: Option<f32>,
correct_for_drops: Option<bool>,
}
#[derive(Deserialize, Clone)]
pub struct Modifier {
pub r#type: String,
pub id: String,
pub amount: f64,
pub operation: Operation,
// TODO: Make this an enum
pub slot: AttributeModifierSlot,
}
const fn _true() -> bool {
true
}
#[derive(Deserialize, Clone)]
pub struct Consumable {
consume_seconds: Option<f32>, // TODO
}
#[derive(Deserialize, Clone)]
pub struct DeathProtection {
// TODO
}
#[derive(Deserialize, Clone)]
pub struct BlocksAttacks {
// TODO
}
#[derive(Deserialize, Clone)]
pub struct EquippableComponent {
pub slot: String,
pub equip_sound: Option<String>,
pub asset_id: Option<String>,
pub camera_overlay: Option<String>,
pub allowed_entities: Option<RegistryEntryList>,
#[serde(default = "_true")]
pub dispensable: bool,
#[serde(default = "_true")]
pub swappable: bool,
#[serde(default = "_true")]
pub damage_on_hurt: bool,
#[serde(default)]
pub equip_on_interact: bool,
#[serde(default)]
pub can_be_sheared: bool,
pub shearing_sound: Option<String>,
}
#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
#[expect(clippy::enum_variant_names)]
pub enum Operation {
AddValue,
AddMultipliedBase,
AddMultipliedTotal,
}
pub fn build() -> TokenStream {
let items: BTreeMap<String, Item> =
serde_json::from_str(&fs::read_to_string("../assets/items.json").unwrap())
.expect("Failed to parse items.json");
let mut type_from_raw_id_arms = TokenStream::new();
let mut type_from_name = TokenStream::new();
let mut constants = TokenStream::new();
for (name, item) in items {
let const_ident = format_ident!("{}", name.to_shouty_snake_case());
let components = &item.components;
let components_tokens = components.to_token_stream();
let id_lit = LitInt::new(&item.id.to_string(), Span::call_site());
constants.extend(quote! {
pub const #const_ident: Item = Item {
id: #id_lit,
registry_key: #name,
components: &[#components_tokens],
};
});
type_from_raw_id_arms.extend(quote! {
#id_lit => Some(&Self::#const_ident),
});
type_from_name.extend(quote! {
#name => Some(&Self::#const_ident),
});
}
quote! {
use crate::data_component::DataComponent::*;
use crate::data_component_impl::*;
use crate::tag::{RegistryKey, Taggable};
use pumpkin_util::text::TextComponent;
use std::borrow::Cow;
use std::hash::{Hash, Hasher};
use crate::{tag, AttributeModifierSlot};
use crate::attributes::Attributes;
use crate::data_component_impl::IDSet::{Blocks, Tag};
use crate::data_component::DataComponent;
use crate::Block;
#[derive(Clone)]
pub struct Item {
pub id: u16,
pub registry_key: &'static str,
pub components: &'static [(DataComponent, &'static dyn DataComponentImpl)],
}
impl PartialEq for Item {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for Item {}
impl Hash for Item {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl Item {
#constants
pub fn translated_name(&self) -> TextComponent {
TextComponent::translate(
self.components
.iter()
.find_map(|(id, data)| if id == &ItemName {
Some(data.as_any().downcast_ref::<ItemNameImpl>().unwrap().name)
} else {
None
}
).unwrap(),
&[],
)
}
#[doc = "Try to parse an item from a resource location string."]
pub fn from_registry_key(name: &str) -> Option<&'static Self> {
let name = name.strip_prefix("minecraft:").unwrap_or(name);
match name {
#type_from_name
_ => None
}
}
#[doc = "Try to parse an item from a raw id."]
pub const fn from_id(id: u16) -> Option<&'static Self> {
match id {
#type_from_raw_id_arms
_ => None
}
}
}
impl Taggable for Item {
#[inline]
fn tag_key() -> RegistryKey {
RegistryKey::Item
}
#[inline]
fn registry_key(&self) -> &str {
self.registry_key
}
#[inline]
fn registry_id(&self) -> u16 {
self.id
}
}
}
}
+263
View File
@@ -0,0 +1,263 @@
use proc_macro2::{Literal, TokenStream};
use quote::quote;
use std::{fs, io::Cursor};
use pumpkin_nbt::{Nbt, compound::NbtCompound, deserializer::NbtReadHelper};
struct ParsedMappings {
mapped_size: usize,
forward: Vec<i32>,
}
fn parse_mapping_file(path: &str, section: &str) -> ParsedMappings {
let bytes = fs::read(path).unwrap_or_else(|_| panic!("Failed to read {path}"));
let mut reader = NbtReadHelper::new(Cursor::new(bytes));
let nbt = Nbt::read(&mut reader).unwrap_or_else(|_| panic!("Failed to parse NBT at {path}"));
let mappings = nbt
.root_tag
.get_compound(section)
.unwrap_or_else(|| panic!("Missing `{section}` compound in {path}"));
parse_mappings(mappings, path, section)
}
fn parse_mappings(mappings: &NbtCompound, path: &str, section: &str) -> ParsedMappings {
let mapped_size = mappings
.get_int("mappedSize")
.unwrap_or_else(|| panic!("Missing `{section}.mappedSize` in {path}"));
let strategy = mappings
.get_byte("id")
.unwrap_or_else(|| panic!("Missing `{section}.id` in {path}"));
let forward =
match strategy {
// Direct
0 => mappings
.get_int_array("val")
.unwrap_or_else(|| panic!("Missing `{section}.val` for direct mapping in {path}"))
.to_vec(),
// Shifts
1 => {
let shifts_at = mappings.get_int_array("at").unwrap_or_else(|| {
panic!("Missing `{section}.at` for shift mapping in {path}")
});
let shifts_to = mappings.get_int_array("to").unwrap_or_else(|| {
panic!("Missing `{section}.to` for shift mapping in {path}")
});
let size = mappings.get_int("size").unwrap_or_else(|| {
panic!("Missing `{section}.size` for shift mapping in {path}")
}) as usize;
assert_eq!(
shifts_at.len(),
shifts_to.len(),
"Shift mapping length mismatch in {path}"
);
let mut result = vec![-1; size];
if !shifts_at.is_empty() && shifts_at[0] != 0 {
for id in 0..shifts_at[0] {
result[id as usize] = id;
}
}
for (index, from) in shifts_at.iter().enumerate() {
let to = if index + 1 == shifts_at.len() {
size as i32
} else {
shifts_at[index + 1]
};
let mut mapped_id = shifts_to[index];
for id in *from..to {
result[id as usize] = mapped_id;
mapped_id += 1;
}
}
result
}
// Changes
2 => {
let changes_at = mappings.get_int_array("at").unwrap_or_else(|| {
panic!("Missing `{section}.at` for change mapping in {path}")
});
let values = mappings.get_int_array("val").unwrap_or_else(|| {
panic!("Missing `{section}.val` for change mapping in {path}")
});
let size = mappings.get_int("size").unwrap_or_else(|| {
panic!("Missing `{section}.size` for change mapping in {path}")
}) as usize;
let fill_between = mappings.get("nofill").is_none();
assert_eq!(
changes_at.len(),
values.len(),
"Change mapping length mismatch in {path}"
);
let mut result = vec![-1; size];
let mut next_unhandled_id = 0;
for (index, changed_id) in changes_at.iter().enumerate() {
if fill_between {
for id in next_unhandled_id..*changed_id {
result[id as usize] = id;
}
next_unhandled_id = changed_id + 1;
}
result[*changed_id as usize] = values[index];
}
result
}
// Identity
3 => {
let size = mappings.get_int("size").unwrap_or_else(|| {
panic!("Missing `{section}.size` for identity mapping in {path}")
}) as usize;
(0..size as i32).collect::<Vec<_>>()
}
_ => panic!("Unknown {section} mapping strategy {strategy} in {path}"),
};
ParsedMappings {
mapped_size: mapped_size as usize,
forward,
}
}
fn invert_with_default_to_u16(forward: &[i32], mapped_size: usize, name: &str) -> Vec<u16> {
let mut inverse = vec![0u16; mapped_size];
let mut seen = vec![false; mapped_size];
for (old_id, mapped_id) in forward.iter().enumerate() {
let Ok(mapped_id) = usize::try_from(*mapped_id) else {
continue;
};
if mapped_id >= mapped_size || seen[mapped_id] {
continue;
}
let old_u16 = u16::try_from(old_id)
.unwrap_or_else(|_| panic!("{name}: id {old_id} does not fit in u16"));
inverse[mapped_id] = old_u16;
seen[mapped_id] = true;
}
for (mapped_id, mapped_to) in inverse.iter_mut().enumerate() {
if !seen[mapped_id] {
*mapped_to = u16::try_from(mapped_id)
.unwrap_or_else(|_| panic!("{name}: id {mapped_id} does not fit in u16"));
}
}
inverse
}
fn forward_with_default_to_u16(forward: &[i32], name: &str) -> Vec<u16> {
forward
.iter()
.enumerate()
.map(|(old_id, mapped_id)| {
let mapped = usize::try_from(*mapped_id).ok().unwrap_or(old_id);
u16::try_from(mapped).unwrap_or_else(|_| {
u16::try_from(old_id).unwrap_or_else(|_| {
panic!("{name}: mapped id {mapped} and fallback id {old_id} do not fit in u16")
})
})
})
.collect()
}
fn compose_with_default(first: &[u16], second: &[u16]) -> Vec<u16> {
first
.iter()
.map(|id| second.get(usize::from(*id)).copied().unwrap_or(*id))
.collect()
}
pub fn build() -> TokenStream {
let mappings_7_to_9 = parse_mapping_file(
"../assets/viaversion/data/mappings-1.21.7to1.21.9.nbt",
"items",
);
let mappings_9_to_11 = parse_mapping_file(
"../assets/viaversion/data/mappings-1.21.9to1.21.11.nbt",
"items",
);
let remap_9_to_7 = invert_with_default_to_u16(
&mappings_7_to_9.forward,
mappings_7_to_9.mapped_size,
"1.21.9->1.21.7 items",
);
let remap_7_to_9 =
forward_with_default_to_u16(&mappings_7_to_9.forward, "1.21.7->1.21.9 items");
let remap_11_to_9 = invert_with_default_to_u16(
&mappings_9_to_11.forward,
mappings_9_to_11.mapped_size,
"1.21.11->1.21.9 items",
);
let remap_9_to_11 =
forward_with_default_to_u16(&mappings_9_to_11.forward, "1.21.9->1.21.11 items");
let remap_11_to_7 = compose_with_default(&remap_11_to_9, &remap_9_to_7);
let remap_7_to_11 = compose_with_default(&remap_7_to_9, &remap_9_to_11);
let remap_11_to_9_tokens: Vec<Literal> = remap_11_to_9
.into_iter()
.map(Literal::u16_unsuffixed)
.collect();
let remap_9_to_11_tokens: Vec<Literal> = remap_9_to_11
.into_iter()
.map(Literal::u16_unsuffixed)
.collect();
let remap_11_to_7_tokens: Vec<Literal> = remap_11_to_7
.into_iter()
.map(Literal::u16_unsuffixed)
.collect();
let remap_7_to_11_tokens: Vec<Literal> = remap_7_to_11
.into_iter()
.map(Literal::u16_unsuffixed)
.collect();
quote! {
use pumpkin_util::version::MinecraftVersion;
pub static ITEM_ID_REMAP_1_21_11_TO_1_21_9: &[u16] = &[#(#remap_11_to_9_tokens),*];
pub static ITEM_ID_REMAP_1_21_11_TO_1_21_7: &[u16] = &[#(#remap_11_to_7_tokens),*];
pub static ITEM_ID_REMAP_1_21_9_TO_1_21_11: &[u16] = &[#(#remap_9_to_11_tokens),*];
pub static ITEM_ID_REMAP_1_21_7_TO_1_21_11: &[u16] = &[#(#remap_7_to_11_tokens),*];
#[must_use]
pub fn remap_item_id_for_version(item_id: u16, version: MinecraftVersion) -> u16 {
match version {
MinecraftVersion::V_1_21_7 => ITEM_ID_REMAP_1_21_11_TO_1_21_7
.get(usize::from(item_id))
.copied()
.unwrap_or(item_id),
MinecraftVersion::V_1_21_9 => ITEM_ID_REMAP_1_21_11_TO_1_21_9
.get(usize::from(item_id))
.copied()
.unwrap_or(item_id),
_ => item_id,
}
}
#[must_use]
pub fn remap_item_id_from_version(item_id: u16, version: MinecraftVersion) -> u16 {
match version {
MinecraftVersion::V_1_21_7 => ITEM_ID_REMAP_1_21_7_TO_1_21_11
.get(usize::from(item_id))
.copied()
.unwrap_or(item_id),
MinecraftVersion::V_1_21_9 => ITEM_ID_REMAP_1_21_9_TO_1_21_11
.get(usize::from(item_id))
.copied()
.unwrap_or(item_id),
_ => item_id,
}
}
}
}
+146
View File
@@ -0,0 +1,146 @@
use heck::ToPascalCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use serde::Deserialize;
use serde_json::Value;
use std::collections::BTreeMap;
use std::fs;
#[derive(Deserialize)]
struct JukeboxSongData {
length_in_seconds: f32,
comparator_output: u8,
}
pub fn build() -> TokenStream {
let songs: BTreeMap<String, u32> = serde_json::from_str(
&fs::read_to_string("../assets/jukebox_song.json").expect("Missing jukebox_song.json"),
)
.expect("Failed to parse jukebox_song.json");
let registries: BTreeMap<String, Value> = serde_json::from_str(
&fs::read_to_string("../assets/registry/1_21_11_synced_registries.json")
.expect("Missing synced_registries.json"),
)
.expect("Failed to parse synced_registries.json");
let song_data: BTreeMap<String, JukeboxSongData> = serde_json::from_value(
registries
.get("jukebox_song")
.expect("Missing jukebox_song in synced registries")
.clone(),
)
.expect("Failed to parse jukebox_song data");
let make_variant_ident = |name: &str| {
let pascal = name.to_pascal_case();
if pascal.chars().next().is_some_and(|c| c.is_ascii_digit()) {
format_ident!("Id{}", pascal)
} else {
format_ident!("{}", pascal)
}
};
let variants = songs
.keys()
.map(|name| {
let variant_name = make_variant_ident(name);
quote! { #variant_name, }
})
.collect::<TokenStream>();
let type_from_name = songs
.keys()
.map(|name| {
let variant_name = make_variant_ident(name);
quote! { #name => Some(Self::#variant_name), }
})
.collect::<TokenStream>();
let type_to_name = songs
.keys()
.map(|name| {
let variant_name = make_variant_ident(name);
quote! { Self::#variant_name => #name, }
})
.collect::<TokenStream>();
let type_to_id = songs
.iter()
.map(|(name, id)| {
let variant_name = make_variant_ident(name);
quote! { Self::#variant_name => #id, }
})
.collect::<TokenStream>();
let type_to_length = songs
.keys()
.map(|name| {
let variant_name = make_variant_ident(name);
let length = song_data
.get(name)
.map_or(0, |d| d.length_in_seconds as u32);
quote! { Self::#variant_name => #length, }
})
.collect::<TokenStream>();
let type_to_comparator = songs
.keys()
.map(|name| {
let variant_name = make_variant_ident(name);
let output = song_data.get(name).map_or(0, |d| d.comparator_output);
quote! { Self::#variant_name => #output, }
})
.collect::<TokenStream>();
quote! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u32)]
pub enum JukeboxSong {
#variants
}
impl JukeboxSong {
#[doc = r" Returns the JukeboxSong from the string name (e.g., 'pigstep')."]
pub fn from_name(name: &str) -> Option<Self> {
match name {
#type_from_name
_ => None
}
}
#[doc = r" Returns the string name of the song."]
pub const fn to_name(&self) -> &'static str {
match self {
#type_to_name
}
}
#[doc = r" Returns the numeric ID associated with the song."]
pub const fn get_id(&self) -> u32 {
match self {
#type_to_id
}
}
#[doc = r" Returns the comparator output value (0-15) for this song."]
pub const fn comparator_output(&self) -> u8 {
match self {
#type_to_comparator
}
}
#[doc = r" Returns the song length in seconds."]
pub const fn length_in_seconds(&self) -> u32 {
match self {
#type_to_length
}
}
#[doc = r" Returns the song length in ticks (20 ticks per second)."]
pub const fn length_in_ticks(&self) -> u64 {
self.length_in_seconds() as u64 * 20
}
}
}
}
+525
View File
@@ -0,0 +1,525 @@
use std::collections::BTreeMap;
use proc_macro2::{Span, TokenStream};
use pumpkin_util::loot_table::LootNumberProviderTypes;
use quote::{ToTokens, quote};
use serde::Deserialize;
use syn::LitStr;
/// These are required to be defined twice because serde can't deserialize into static context for obvious reasons.
#[derive(Deserialize)]
pub struct LootTableStruct {
r#type: LootTableTypeStruct,
random_sequence: Option<String>,
pools: Option<Vec<LootPoolStruct>>,
}
impl ToTokens for LootTableStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let loot_table_type = self.r#type.to_token_stream();
let random_sequence = if let Some(seq) = &self.random_sequence {
quote! { Some(#seq) }
} else {
quote! { None }
};
let pools = if let Some(pools) = &self.pools {
let pool_tokens: Vec<_> = pools.iter().map(quote::ToTokens::to_token_stream).collect();
quote! { Some(&[#(#pool_tokens),*]) }
} else {
quote! { None }
};
tokens.extend(quote! {
LootTable {
r#type: #loot_table_type,
random_sequence: #random_sequence,
pools: #pools,
}
});
}
}
#[derive(Deserialize, Clone, Debug)]
pub struct LootPoolStruct {
entries: Vec<LootPoolEntryStruct>,
rolls: LootNumberProviderTypes, // TODO
bonus_rolls: f32,
conditions: Option<Vec<LootConditionStruct>>,
functions: Option<Vec<LootFunctionStruct>>,
}
impl ToTokens for LootPoolStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let entries_tokens: Vec<_> = self
.entries
.iter()
.map(quote::ToTokens::to_token_stream)
.collect();
let rolls = &self.rolls;
let bonus_rolls = &self.bonus_rolls;
let conditions_tokens = if let Some(conds) = &self.conditions {
let cond_tokens: Vec<_> = conds.iter().map(quote::ToTokens::to_token_stream).collect();
quote! { Some(&[#(#cond_tokens),*]) }
} else {
quote! { None }
};
let functions_tokens = if let Some(fns) = &self.functions {
let cond_tokens: Vec<_> = fns.iter().map(quote::ToTokens::to_token_stream).collect();
quote! { Some(&[#(#cond_tokens),*]) }
} else {
quote! { None }
};
tokens.extend(quote! {
LootPool {
entries: &[#(#entries_tokens),*],
rolls: #rolls,
bonus_rolls: #bonus_rolls,
conditions: #conditions_tokens,
functions: #functions_tokens,
}
});
}
}
#[derive(Deserialize, Clone, Debug)]
pub struct ItemEntryStruct {
name: String,
}
impl ToTokens for ItemEntryStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name = LitStr::new(&self.name, Span::call_site());
tokens.extend(quote! {
ItemEntry {
name: #name,
}
});
}
}
#[derive(Deserialize, Clone, Debug)]
pub struct AlternativeEntryStruct {
children: Vec<LootPoolEntryStruct>,
}
impl ToTokens for AlternativeEntryStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let children = self.children.iter().map(quote::ToTokens::to_token_stream);
tokens.extend(quote! {
AlternativeEntry {
children: &[#(#children),*],
}
});
}
}
#[derive(Deserialize, Clone, Debug)]
#[serde(tag = "type")]
pub enum LootPoolEntryTypesStruct {
#[serde(rename = "minecraft:empty")]
Empty,
#[serde(rename = "minecraft:item")]
Item(ItemEntryStruct),
#[serde(rename = "minecraft:loot_table")]
LootTable,
#[serde(rename = "minecraft:dynamic")]
Dynamic,
#[serde(rename = "minecraft:tag")]
Tag,
#[serde(rename = "minecraft:alternatives")]
Alternatives(AlternativeEntryStruct),
#[serde(rename = "minecraft:sequence")]
Sequence,
#[serde(rename = "minecraft:group")]
Group,
}
impl ToTokens for LootPoolEntryTypesStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::Empty => {
tokens.extend(quote! { LootPoolEntryTypes::Empty });
}
Self::Item(item) => {
tokens.extend(quote! { LootPoolEntryTypes::Item(#item) });
}
Self::LootTable => {
tokens.extend(quote! { LootPoolEntryTypes::LootTable });
}
Self::Dynamic => {
tokens.extend(quote! { LootPoolEntryTypes::Dynamic });
}
Self::Tag => {
tokens.extend(quote! { LootPoolEntryTypes::Tag });
}
Self::Alternatives(alt) => {
tokens.extend(quote! { LootPoolEntryTypes::Alternatives(#alt) });
}
Self::Sequence => {
tokens.extend(quote! { LootPoolEntryTypes::Sequence });
}
Self::Group => {
tokens.extend(quote! { LootPoolEntryTypes::Group });
}
}
}
}
#[derive(Deserialize, Clone, Debug)]
#[serde(tag = "condition")]
pub enum LootConditionStruct {
#[serde(rename = "minecraft:inverted")]
Inverted,
#[serde(rename = "minecraft:any_of")]
AnyOf,
#[serde(rename = "minecraft:all_of")]
AllOf,
#[serde(rename = "minecraft:random_chance")]
RandomChance,
#[serde(rename = "minecraft:random_chance_with_enchanted_bonus")]
RandomChanceWithEnchantedBonus,
#[serde(rename = "minecraft:entity_properties")]
EntityProperties,
#[serde(rename = "minecraft:killed_by_player")]
KilledByPlayer,
#[serde(rename = "minecraft:entity_scores")]
EntityScores,
#[serde(rename = "minecraft:block_state_property")]
BlockStateProperty {
block: String,
properties: BTreeMap<String, String>,
},
#[serde(rename = "minecraft:match_tool")]
MatchTool,
#[serde(rename = "minecraft:table_bonus")]
TableBonus,
#[serde(rename = "minecraft:survives_explosion")]
SurvivesExplosion,
#[serde(rename = "minecraft:damage_source_properties")]
DamageSourceProperties,
#[serde(rename = "minecraft:location_check")]
LocationCheck,
#[serde(rename = "minecraft:weather_check")]
WeatherCheck,
#[serde(rename = "minecraft:reference")]
Reference,
#[serde(rename = "minecraft:time_check")]
TimeCheck,
#[serde(rename = "minecraft:value_check")]
ValueCheck,
#[serde(rename = "minecraft:enchantment_active_check")]
EnchantmentActiveCheck,
}
impl ToTokens for LootConditionStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name = match self {
Self::Inverted => quote! { LootCondition::Inverted },
Self::AnyOf => quote! { LootCondition::AnyOf },
Self::AllOf => quote! { LootCondition::AllOf },
Self::RandomChance => quote! { LootCondition::RandomChance },
Self::RandomChanceWithEnchantedBonus => {
quote! { LootCondition::RandomChanceWithEnchantedBonus }
}
Self::EntityProperties => quote! { LootCondition::EntityProperties },
Self::KilledByPlayer => quote! { LootCondition::KilledByPlayer },
Self::EntityScores => quote! { LootCondition::EntityScores },
Self::BlockStateProperty { block, properties } => {
let properties: Vec<_> = properties
.iter()
.map(|(k, v)| quote! { (#k, #v) })
.collect();
quote! { LootCondition::BlockStateProperty { block: #block, properties: &[#(#properties),*] } }
}
Self::MatchTool => quote! { LootCondition::MatchTool },
Self::TableBonus => quote! { LootCondition::TableBonus },
Self::SurvivesExplosion => quote! { LootCondition::SurvivesExplosion },
Self::DamageSourceProperties => {
quote! { LootCondition::DamageSourceProperties }
}
Self::LocationCheck => quote! { LootCondition::LocationCheck },
Self::WeatherCheck => quote! { LootCondition::WeatherCheck },
Self::Reference => quote! { LootCondition::Reference },
Self::TimeCheck => quote! { LootCondition::TimeCheck },
Self::ValueCheck => quote! { LootCondition::ValueCheck },
Self::EnchantmentActiveCheck => {
quote! { LootCondition::EnchantmentActiveCheck }
}
};
tokens.extend(name);
}
}
#[derive(Deserialize, Clone, Debug)]
pub struct LootFunctionStruct {
#[serde(flatten)]
content: LootFunctionTypesStruct,
conditions: Option<Vec<LootConditionStruct>>,
}
impl ToTokens for LootFunctionStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let functions_tokens = &self.content.to_token_stream();
let conditions_tokens = if let Some(conds) = &self.conditions {
let cond_tokens: Vec<_> = conds.iter().map(quote::ToTokens::to_token_stream).collect();
quote! { Some(&[#(#cond_tokens),*]) }
} else {
quote! { None }
};
tokens.extend(quote! {
LootFunction {
content: #functions_tokens,
conditions: #conditions_tokens,
}
});
}
}
#[derive(Deserialize, Clone, Debug)]
#[serde(tag = "function")]
pub enum LootFunctionTypesStruct {
#[serde(rename = "minecraft:set_count")]
SetCount {
count: LootFunctionNumberProviderStruct,
add: Option<bool>,
},
#[serde(rename = "minecraft:enchanted_count_increase")]
EnchantedCountIncrease,
#[serde(rename = "minecraft:furnace_smelt")]
FurnaceSmelt,
#[serde(rename = "minecraft:set_potion")]
SetPotion,
#[serde(rename = "minecraft:set_ominous_bottle_amplifier")]
SetOminousBottleAmplifier,
#[serde(rename = "minecraft:limit_count")]
LimitCount { limit: LootFunctionLimitCountStruct },
#[serde(rename = "minecraft:apply_bonus")]
ApplyBonus {
enchantment: String,
formula: String,
parameters: Option<LootFunctionBonusParameterStruct>,
},
#[serde(rename = "minecraft:copy_components")]
CopyComponents {
source: String,
include: Vec<String>,
},
#[serde(rename = "minecraft:copy_state")]
CopyState {
block: String,
properties: Vec<String>,
},
#[serde(rename = "minecraft:explosion_decay")]
ExplosionDecay,
}
impl ToTokens for LootFunctionTypesStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name = match self {
Self::SetCount { count, add } => {
let count = count.to_token_stream();
let add = add.unwrap_or(false);
quote! { LootFunctionTypes::SetCount { count: #count, add: #add } }
}
Self::SetOminousBottleAmplifier => {
quote! { LootFunctionTypes::SetOminousBottleAmplifier }
}
Self::FurnaceSmelt => {
quote! { LootFunctionTypes::FurnaceSmelt }
}
Self::SetPotion => {
quote! { LootFunctionTypes::SetPotion }
}
Self::EnchantedCountIncrease => {
quote! { LootFunctionTypes::EnchantedCountIncrease }
}
Self::LimitCount { limit } => {
let min = if let Some(min) = limit.min {
quote! { Some(#min) }
} else {
quote! { None }
};
let max = if let Some(max) = limit.max {
quote! { Some(#max) }
} else {
quote! { None }
};
quote! { LootFunctionTypes::LimitCount { min: #min, max: #max } }
}
Self::ApplyBonus {
enchantment,
formula,
parameters,
} => {
let parameters = if let Some(params) = parameters {
let params = params.to_token_stream();
quote! { Some(#params) }
} else {
quote! { None }
};
quote! {
LootFunctionTypes::ApplyBonus {
enchantment: #enchantment,
formula: #formula,
parameters: #parameters,
}
}
}
Self::CopyComponents { source, include } => {
quote! {
LootFunctionTypes::CopyComponents {
source: #source,
include: &[#(#include),*],
}
}
}
Self::CopyState { block, properties } => {
quote! {
LootFunctionTypes::CopyState {
block: #block,
properties: &[#(#properties),*],
}
}
}
Self::ExplosionDecay => {
quote! { LootFunctionTypes::ExplosionDecay }
}
};
tokens.extend(name);
}
}
#[derive(Deserialize, Clone, Debug)]
#[serde(tag = "type")]
pub enum LootFunctionNumberProviderStruct {
#[serde(rename = "minecraft:uniform")]
Uniform { min: f32, max: f32 },
#[serde(rename = "minecraft:binomial")]
Binomial { n: f32, p: f32 },
#[serde(rename = "minecraft:constant", untagged)]
Constant(f32),
}
impl ToTokens for LootFunctionNumberProviderStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name = match self {
Self::Constant(value) => {
quote! { LootFunctionNumberProvider::Constant { value: #value } }
}
Self::Uniform { min, max } => {
quote! { LootFunctionNumberProvider::Uniform { min: #min, max: #max } }
}
Self::Binomial { n, p } => {
quote! { LootFunctionNumberProvider::Binomial { n: #n, p: #p } }
}
};
tokens.extend(name);
}
}
#[derive(Deserialize, Clone, Debug)]
pub struct LootFunctionLimitCountStruct {
min: Option<f32>,
max: Option<f32>,
}
#[derive(Deserialize, Clone, Debug)]
#[serde(untagged)]
pub enum LootFunctionBonusParameterStruct {
Multiplier {
#[serde(rename = "bonusMultiplier")]
bonus_multiplier: i32,
},
Probability {
extra: i32,
probability: f32,
},
}
impl ToTokens for LootFunctionBonusParameterStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name = match self {
Self::Multiplier { bonus_multiplier } => {
quote! { LootFunctionBonusParameter::Multiplier { bonus_multiplier: #bonus_multiplier } }
}
Self::Probability { extra, probability } => {
quote! { LootFunctionBonusParameter::Probability { extra: #extra, probability: #probability } }
}
};
tokens.extend(name);
}
}
#[derive(Deserialize, Clone, Debug)]
pub struct LootPoolEntryStruct {
#[serde(flatten)]
content: LootPoolEntryTypesStruct,
conditions: Option<Vec<LootConditionStruct>>,
functions: Option<Vec<LootFunctionStruct>>,
}
impl ToTokens for LootPoolEntryStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let content = &self.content;
let conditions_tokens = if let Some(conds) = &self.conditions {
let cond_tokens: Vec<_> = conds.iter().map(quote::ToTokens::to_token_stream).collect();
quote! { Some(&[#(#cond_tokens),*]) }
} else {
quote! { None }
};
let functions_tokens = if let Some(fns) = &self.functions {
let cond_tokens: Vec<_> = fns.iter().map(quote::ToTokens::to_token_stream).collect();
quote! { Some(&[#(#cond_tokens),*]) }
} else {
quote! { None }
};
tokens.extend(quote! {
LootPoolEntry {
content: #content,
conditions: #conditions_tokens,
functions: #functions_tokens,
}
});
}
}
#[derive(Deserialize, Clone, Debug)]
#[serde(rename = "snake_case")]
pub enum LootTableTypeStruct {
#[serde(rename = "minecraft:empty")]
/// Nothing will be dropped.
Empty,
#[serde(rename = "minecraft:entity")]
/// The Entity loot will be dropped.
Entity,
#[serde(rename = "minecraft:block")]
/// A block will be dropped.
Block,
#[serde(rename = "minecraft:chest")]
/// An item will be dropped.
Chest,
}
impl ToTokens for LootTableTypeStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name = match self {
Self::Empty => quote! { LootTableType::Empty },
Self::Entity => quote! { LootTableType::Entity },
Self::Block => quote! { LootTableType::Block },
Self::Chest => quote! { LootTableType::Chest },
};
tokens.extend(name);
}
}
+188
View File
@@ -0,0 +1,188 @@
use heck::ToPascalCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use rayon::prelude::*;
use std::{
fs,
io::Write,
path::Path,
process::{Command, Stdio},
};
mod attributes;
mod biome;
mod bitsets;
mod block;
mod block_state_remap;
mod chunk_gen_settings;
mod chunk_status;
mod composter_increase_chance;
mod damage_type;
mod data_component;
mod dimension;
mod effect;
mod enchantments;
mod entity_pose;
mod entity_status;
mod entity_type;
mod flower_pot_transformations;
mod fluid;
mod fuels;
mod game_event;
mod game_rules;
mod item;
mod item_id_remap;
mod jukebox_song;
pub mod loot;
mod message_type;
mod meta_data_type;
mod noise_parameter;
mod noise_router;
mod packet;
mod particle;
mod potion;
mod potion_brewing;
mod recipe_remainder;
mod recipes;
mod registry;
mod scoreboard_slot;
mod screen;
mod sound;
mod sound_category;
mod spawn_egg;
mod structures;
mod tag;
mod tracked_data;
mod translations;
mod world_event;
pub const OUT_DIR: &str = "../pumpkin-data/src/generated";
pub fn main() {
type BuilderFn = fn() -> TokenStream;
fs::create_dir_all(OUT_DIR).expect("Failed to create output directory");
let build_functions: Vec<(BuilderFn, &str)> = vec![
(packet::build, "packet.rs"),
(screen::build, "screen.rs"),
(particle::build, "particle.rs"),
(sound::build, "sound.rs"),
(meta_data_type::build, "meta_data_type.rs"),
(tracked_data::build, "tracked_data.rs"),
(chunk_status::build, "chunk_status.rs"),
(game_event::build, "game_event.rs"),
(game_rules::build, "game_rules.rs"),
(registry::build, "registry.rs"),
(dimension::build, "dimension.rs"),
(translations::build, "translation.rs"),
(jukebox_song::build, "jukebox_song.rs"),
(sound_category::build, "sound_category.rs"),
(entity_pose::build, "entity_pose.rs"),
(scoreboard_slot::build, "scoreboard_slot.rs"),
(world_event::build, "world_event.rs"),
(entity_type::build, "entity_type.rs"),
(noise_parameter::build, "noise_parameter.rs"),
(biome::build, "biome.rs"),
(damage_type::build, "damage_type.rs"),
(message_type::build, "message_type.rs"),
(spawn_egg::build, "spawn_egg.rs"),
(block::build, "block.rs"),
(block_state_remap::build, "block_state_remap.rs"),
(item::build, "item.rs"),
(item_id_remap::build, "item_id_remap.rs"),
(structures::build, "structures.rs"),
(chunk_gen_settings::build, "chunk_gen_settings.rs"),
(fluid::build, "fluid.rs"),
(entity_status::build, "entity_status.rs"),
(tag::build, "tag.rs"),
(noise_router::build, "noise_router.rs"),
(
flower_pot_transformations::build,
"flower_pot_transformations.rs",
),
(
composter_increase_chance::build,
"composter_increase_chance.rs",
),
(recipes::build, "recipes.rs"),
(enchantments::build, "enchantment.rs"),
(fuels::build, "fuels.rs"),
(data_component::build, "data_component.rs"),
(attributes::build, "attributes.rs"),
(effect::build, "effect.rs"),
(potion::build, "potion.rs"),
(potion_brewing::build, "potion_brewing.rs"),
(recipe_remainder::build, "recipe_remainder.rs"),
];
build_functions.par_iter().for_each(|(build_fn, file)| {
println!("Parsing {}", file);
let raw_code = build_fn().to_string();
let header = "/* This file is generated. Do not edit manually. */\n";
let final_code = format_code(&raw_code).map_or_else(
|_| format!("{header}{raw_code}"),
|formatted| format!("{header}{formatted}"),
);
write_generated_file(&final_code, file);
});
println!("Done")
}
#[must_use]
pub fn array_to_tokenstream(array: &[String]) -> TokenStream {
let variants = array.iter().map(|item| {
let name = format_ident!("{}", item.to_pascal_case());
quote! { #name, }
});
quote! {
#(#variants)*
}
}
pub fn write_generated_file(new_code: &str, out_file: &str) {
let path = Path::new(OUT_DIR).join(out_file);
if path.exists()
&& let Ok(existing_code) = fs::read_to_string(&path)
&& existing_code == new_code
{
return;
}
fs::write(&path, new_code)
.unwrap_or_else(|_| panic!("Failed to write to file: {}", path.display()));
}
pub struct RustFmtError;
pub fn format_code(unformatted_code: &str) -> Result<String, RustFmtError> {
let child_result = Command::new("rustfmt")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn();
let Ok(mut child) = child_result else {
return Err(RustFmtError);
};
// Write the code to rustfmt's stdin
if let Some(mut stdin) = child.stdin.take()
&& stdin.write_all(unformatted_code.as_bytes()).is_err()
{
return Err(RustFmtError);
}
match child.wait_with_output() {
Ok(output) if output.status.success() => {
String::from_utf8(output.stdout).map_err(|_| RustFmtError)
}
_ => Err(RustFmtError),
}
}
+49
View File
@@ -0,0 +1,49 @@
use std::{collections::BTreeMap, fs};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use serde::Deserialize;
#[derive(Deserialize)]
pub struct RawChatType {
id: u32,
// components: ChatType,
}
// #[derive(Deserialize)]
// pub struct ChatType {
// chat: Decoration,
// narration: Decoration,
// }
// #[derive(Deserialize)]
// pub struct Decoration {
// translation_key: String,
// #[serde(default, skip_serializing_if = "Option::is_none")]
// style: Option<Style>,
// parameters: Vec<String>,
// }
pub fn build() -> TokenStream {
let json: BTreeMap<String, RawChatType> =
serde_json::from_str(&fs::read_to_string("../assets/message_type.json").unwrap())
.expect("Failed to parse message_type.json");
let mut variants = TokenStream::new();
for (name, typee) in &json {
let i = typee.id as u8;
let name = format_ident!("{}", name.to_uppercase());
variants.extend([quote! {
pub const #name: u8 = #i;
}]);
}
let raw_id = json.len() as u8;
variants.extend([quote! {
pub const RAW: u8 = #raw_id; // One higher than highest vanilla id
}]);
quote! {
#variants
}
}
+52
View File
@@ -0,0 +1,52 @@
use std::{collections::BTreeMap, fs};
use heck::ToPascalCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
pub fn build() -> TokenStream {
let handlers_map: BTreeMap<String, i32> =
serde_json::from_str(&fs::read_to_string("../assets/meta_data_type.json").unwrap())
.expect("Failed to parse meta_data_type.json");
let mut handlers: Vec<(&String, &i32)> = handlers_map.iter().collect();
handlers.sort_by_key(|&(_, id)| id);
let variants = handlers.iter().map(|(name, _)| {
let ident = format_ident!("{}", name.to_pascal_case());
quote! { #ident }
});
let from_id = handlers.iter().map(|(name, id)| {
let ident = format_ident!("{}", name.to_pascal_case());
quote! { #id => Some(Self::#ident), }
});
let to_id = handlers.iter().map(|(name, id)| {
let ident = format_ident!("{}", name.to_pascal_case());
quote! { Self::#ident => #id, }
});
quote! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(i32)]
pub enum MetaDataType {
#(#variants),*
}
impl MetaDataType {
pub fn from_id(id: i32) -> Option<Self> {
match id {
#(#from_id)*
_ => None,
}
}
pub const fn id(&self) -> i32 {
match self {
#(#to_id)*
}
}
}
}
}
+58
View File
@@ -0,0 +1,58 @@
use std::{collections::BTreeMap, fs};
use proc_macro2::TokenStream;
use pumpkin_util::DoublePerlinNoiseParametersCodec;
use quote::{format_ident, quote};
pub fn build() -> TokenStream {
let json: BTreeMap<String, DoublePerlinNoiseParametersCodec> =
serde_json::from_str(&fs::read_to_string("../assets/noise_parameters.json").unwrap())
.expect("Failed to parse noise_parameters.json");
let mut variants = TokenStream::new();
let mut match_variants = TokenStream::new();
for (name, parameter) in &json {
let raw_name = format!("minecraft:{name}");
let simple_id = name;
let name = format_ident!("{}", name.to_uppercase());
let first_octave = parameter.first_octave;
let amplitudes = &parameter.amplitudes;
variants.extend([quote! {
pub const #name: DoublePerlinNoiseParameters = DoublePerlinNoiseParameters::new(#first_octave, &[#(#amplitudes),*], #raw_name);
}]);
match_variants.extend([quote! {
#simple_id => &#name,
}]);
}
quote! {
pub struct DoublePerlinNoiseParameters {
pub first_octave: i32,
pub amplitudes: &'static [f64],
id: &'static str,
}
impl DoublePerlinNoiseParameters {
pub const fn new(first_octave: i32, amplitudes: &'static [f64], id: &'static str) -> Self {
Self {
first_octave,
amplitudes,
id
}
}
pub const fn id(&self) -> &'static str {
self.id
}
pub fn id_to_parameters(id: &str) -> Option<&DoublePerlinNoiseParameters> {
Some(match id {
#match_variants
_ => return None,
})
}
}
#variants
}
}
File diff suppressed because it is too large. Load diff
+111
View File
@@ -0,0 +1,111 @@
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use serde::Deserialize;
use std::{collections::BTreeMap, fs};
#[derive(Deserialize)]
pub struct Packets {
version: u32,
serverbound: BTreeMap<String, BTreeMap<String, i32>>,
clientbound: BTreeMap<String, BTreeMap<String, i32>>,
}
pub fn build() -> TokenStream {
// 2. Parse the protocol files
let packets_7: Packets = serde_json::from_str(
&fs::read_to_string("../assets/packet/1_21_7_packets.json").expect("1.21.7 file missing"),
)
.unwrap();
let packets_11: Packets = serde_json::from_str(
&fs::read_to_string("../assets/packet/1_21_11_packets.json").expect("1.21.11 file missing"),
)
.unwrap();
let latest_version = packets_11.version;
// 3. Generate mapped constants for both directions
let serverbound_consts = generate_mapped_consts(&packets_11, &packets_7, true);
let clientbound_consts = generate_mapped_consts(&packets_11, &packets_7, false);
quote!(
use pumpkin_util::version::MinecraftVersion;
pub const CURRENT_MC_PROTOCOL: u32 = #latest_version;
pub struct PacketId {
pub latest_id: i32,
pub v1_21_7_id: i32,
}
impl PacketId {
/// Converts the latest packet ID to the ID used in the requested version.
/// Returns -1 if the packet does not exist in that version.
pub fn to_id(&self, version: MinecraftVersion) -> i32 {
match version {
MinecraftVersion::V_1_21_11 => self.latest_id,
MinecraftVersion::V_1_21_7 => self.v1_21_7_id,
// Default to latest for unrecognized/unmapped versions
_ => self.latest_id,
}
}
}
impl PartialEq<i32> for PacketId {
fn eq(&self, other: &i32) -> bool {
self.latest_id == *other
}
}
impl PartialEq<PacketId> for i32 {
fn eq(&self, other: &PacketId) -> bool {
*self == other.latest_id
}
}
// We place the constants directly into these modules
pub mod serverbound {
#serverbound_consts
}
pub mod clientbound {
#clientbound_consts
}
)
}
fn generate_mapped_consts(latest: &Packets, v7: &Packets, is_serverbound: bool) -> TokenStream {
let mut output = TokenStream::new();
let latest_phases = if is_serverbound {
&latest.serverbound
} else {
&latest.clientbound
};
let v7_phases = if is_serverbound {
&v7.serverbound
} else {
&v7.clientbound
};
for (phase, packets) in latest_phases {
for (name, id_11) in packets {
let sanitized = name.replace(['/', '-'], "_").to_uppercase();
let const_name = format_ident!("{}_{}", phase.to_uppercase(), sanitized);
// Check if the packet exists in 1.21.7 to get the alternate ID
let id_7 = v7_phases
.get(phase)
.and_then(|p| p.get(name))
.copied()
.unwrap_or(-1);
// Since serverbound/clientbound are modules, we reference the PacketId in the parent scope
output.extend(quote! {
pub const #const_name: super::PacketId = super::PacketId {
latest_id: #id_11,
v1_21_7_id: #id_7,
};
});
}
}
output
}
+57
View File
@@ -0,0 +1,57 @@
use std::fs;
use heck::ToPascalCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use crate::array_to_tokenstream;
pub fn build() -> TokenStream {
let particle: Vec<String> =
serde_json::from_str(&fs::read_to_string("../assets/particles.json").unwrap())
.expect("Failed to parse particles.json");
let variants = array_to_tokenstream(&particle);
let type_from_name = &particle
.iter()
.map(|particle| {
let id = &particle;
let name = format_ident!("{}", particle.to_pascal_case());
quote! {
#id => Some(Self::#name),
}
})
.collect::<TokenStream>();
let type_to_name = &particle
.iter()
.map(|particle| {
let id = &particle;
let name = format_ident!("{}", particle.to_pascal_case());
quote! {
Self::#name => #id,
}
})
.collect::<TokenStream>();
quote! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Particle {
#variants
}
impl Particle {
#[doc = r" Try to parse a `Particle` from a resource location string."]
pub fn from_name(name: &str) -> Option<Self> {
match name {
#type_from_name
_ => None
}
}
pub const fn to_name(&self) -> &'static str {
match self {
#type_to_name
}
}
}
}
}
+109
View File
@@ -0,0 +1,109 @@
use std::{collections::BTreeMap, fs};
use heck::ToShoutySnakeCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use serde::Deserialize;
#[derive(Deserialize)]
struct Potion {
id: u8,
effects: Vec<Effect>,
}
#[derive(Deserialize)]
pub struct Effect {
effect_type: String,
duration: i32,
amplifier: u8,
ambient: bool,
show_particles: bool,
show_icon: bool,
}
impl Effect {
pub fn to_tokens(&self) -> TokenStream {
let effect_type = format_ident!(
"{}",
self.effect_type
.strip_prefix("minecraft:")
.unwrap()
.to_uppercase()
);
let duration = self.duration;
let amplifier = self.amplifier;
let ambient = self.ambient;
let show_particles = self.show_particles;
let show_icon = self.show_icon;
quote! {
Effect {
effect_type: &StatusEffect::#effect_type,
duration: #duration,
amplifier: #amplifier,
ambient: #ambient,
show_particles: #show_particles,
show_icon: #show_icon,
blend: false,
}
}
}
}
pub fn build() -> TokenStream {
let potions: BTreeMap<String, Potion> =
serde_json::from_str(&fs::read_to_string("../assets/potion.json").unwrap())
.expect("Failed to parse potion.json");
let mut variants = TokenStream::new();
let mut name_to_type = TokenStream::new();
for (name, potion) in potions {
let format_name = format_ident!("{}", name.to_shouty_snake_case());
let id = potion.id;
let slots = potion.effects;
let slots = slots.iter().map(Effect::to_tokens);
variants.extend([quote! {
pub const #format_name: Self = Self {
name: #name,
id: #id,
effects: &[#(#slots),*],
};
}]);
name_to_type.extend(quote! { #name => Some(&Self::#format_name), });
}
quote! {
use std::hash::Hash;
use crate::effect::StatusEffect;
pub struct Potion {
pub id: u8,
pub name: &'static str,
pub effects: &'static [Effect],
}
#[derive(Clone)]
pub struct Effect {
pub effect_type: &'static StatusEffect,
pub duration: i32,
pub amplifier: u8,
pub ambient: bool,
pub show_particles: bool,
pub show_icon: bool,
pub blend: bool,
}
impl Potion {
#variants
pub fn from_name(name: &str) -> Option<&'static Self> {
match name {
#name_to_type
_ => None
}
}
}
}
}
+114
View File
@@ -0,0 +1,114 @@
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use serde::Deserialize;
use std::fs;
#[derive(Deserialize)]
struct PotionBrewing {
//potion_types: Vec<Vec<String>>,
potion_recipes: Vec<Recipes>,
item_recipes: Vec<Recipes>,
}
#[derive(Deserialize)]
pub struct Recipes {
from: String,
ingredient: Vec<String>,
to: String,
}
impl Recipes {
pub fn get_tokens_potion(self) -> TokenStream {
let from = format_ident!(
"{}",
self.from.strip_prefix("minecraft:").unwrap().to_uppercase()
);
let to = format_ident!(
"{}",
self.to.strip_prefix("minecraft:").unwrap().to_uppercase()
);
let slots = self.ingredient.iter().map(|slot| {
format_ident!(
"{}",
slot.strip_prefix("minecraft:").unwrap().to_uppercase()
)
});
quote! {
PotionRecipe {
from: &Potion::#from,
ingredient: &[#(&Item::#slots),*],
to: &Potion::#to,
},
}
}
pub fn get_tokens_item(self) -> TokenStream {
let from = format_ident!(
"{}",
self.from.strip_prefix("minecraft:").unwrap().to_uppercase()
);
let to = format_ident!(
"{}",
self.to.strip_prefix("minecraft:").unwrap().to_uppercase()
);
let slots = self.ingredient.iter().map(|slot| {
format_ident!(
"{}",
slot.strip_prefix("minecraft:").unwrap().to_uppercase()
)
});
quote! {
ItemRecipe {
from: &Item::#from,
ingredient: &[#(&Item::#slots),*],
to: &Item::#to,
},
}
}
}
pub fn build() -> TokenStream {
let json: PotionBrewing =
serde_json::from_str(&fs::read_to_string("../assets/potion_brewing.json").unwrap())
.expect("Failed to parse potion_brewing.json");
let item_recipes_tokens: Vec<TokenStream> = json
.item_recipes
.into_iter()
.map(Recipes::get_tokens_item)
.collect();
let item_len = item_recipes_tokens.len();
// 3. Generate Potion Recipes
let potion_recipes_tokens: Vec<TokenStream> = json
.potion_recipes
.into_iter()
.map(Recipes::get_tokens_potion)
.collect();
let potion_len = potion_recipes_tokens.len();
quote! {
#![allow(dead_code)]
use crate::potion::Potion;
use crate::item::Item;
pub struct PotionRecipe {
from: &'static Potion,
ingredient: &'static [&'static Item],
to: &'static Potion,
}
pub struct ItemRecipe {
from: &'static Item,
ingredient: &'static [&'static Item],
to: &'static Item,
}
pub const ITEM_RECIPES: [ItemRecipe; #item_len] = [#(#item_recipes_tokens)*];
pub const POTION_RECIPES: [PotionRecipe; #potion_len] = [#(#potion_recipes_tokens)*];
}
}
+29
View File
@@ -0,0 +1,29 @@
use proc_macro2::{Span, TokenStream};
use quote::quote;
use std::{collections::BTreeMap, fs};
use syn::LitInt;
pub fn build() -> TokenStream {
let remainder: BTreeMap<u16, u16> =
serde_json::from_str(&fs::read_to_string("../assets/recipe_remainder.json").unwrap())
.expect("Failed to parse recipe_remainder.json");
let match_arms: Vec<TokenStream> = remainder
.into_iter()
.map(|(item_id, remainder_id)| {
let item_id_lit = LitInt::new(&item_id.to_string(), Span::call_site());
let remainder_id_lit = LitInt::new(&remainder_id.to_string(), Span::call_site());
quote! {
#item_id_lit => Some(#remainder_id_lit),
}
})
.collect();
quote! {
#[must_use]
pub const fn get_recipe_remainder_id(item_id: u16) -> Option<u16> {
match item_id {
#(#match_arms)*
_ => None,
}
}
}
}
+618
View File
@@ -0,0 +1,618 @@
use std::{collections::BTreeMap, fs};
use proc_macro2::TokenStream;
use quote::{ToTokens, quote};
use serde::Deserialize;
#[derive(Deserialize)]
#[serde(tag = "type")]
pub enum RecipeTypes {
#[serde(rename = "minecraft:blasting")]
Blasting(CookingRecipeStruct),
#[serde(rename = "minecraft:campfire_cooking")]
CampfireCooking(CookingRecipeStruct),
#[serde(rename = "minecraft:crafting_shaped")]
CraftingShaped(CraftingShapedRecipeStruct),
#[serde(rename = "minecraft:crafting_shapeless")]
CraftingShapeless(CraftingShapelessRecipeStruct),
#[serde(rename = "minecraft:crafting_transmute")]
CraftingTransmute(CraftingTransmuteRecipeStruct),
#[serde(rename = "minecraft:crafting_decorated_pot")]
CraftingDecoratedPot(CraftingDecoratedPotStruct),
#[serde(rename = "minecraft:smelting")]
Smelting(CookingRecipeStruct),
#[serde(rename = "minecraft:smithing_transform")]
SmithingTransform,
#[serde(rename = "minecraft:smithing_trim")]
SmithingTrim,
#[serde(rename = "minecraft:smoking")]
Smoking(CookingRecipeStruct),
#[serde(rename = "minecraft:stonecutting")]
Stonecutting,
#[serde(other)]
#[serde(rename = "minecraft:crafting_special_*")]
CraftingSpecial,
}
#[derive(Deserialize)]
pub struct CookingRecipeStruct {
category: Option<RecipeCategoryTypes>,
group: Option<String>,
ingredient: RecipeIngredientTypes,
cookingtime: i32,
experience: f32,
result: RecipeResultStruct,
}
impl CookingRecipeStruct {
/// Generate a recipe ID based on result, ingredient, and cooking type
/// Format: minecraft:{result}_from_{`cooking_type`}_{ingredient}
fn generate_recipe_id(&self, cooking_type: &str) -> String {
let result_name = self
.result
.id
.strip_prefix("minecraft:")
.unwrap_or(&self.result.id);
let ingredient_name = match &self.ingredient {
RecipeIngredientTypes::Simple(s) => {
if s.starts_with('#') {
// Tagged ingredient - strip # and replace : with _
s.strip_prefix('#').unwrap_or(s).replace(':', "_")
} else {
s.strip_prefix("minecraft:").unwrap_or(s).to_string()
}
}
RecipeIngredientTypes::OneOf(items) => {
// Use first item for ID generation
items
.first()
.map_or("unknown", |s| s.strip_prefix("minecraft:").unwrap_or(s))
.to_string()
}
};
format!("minecraft:{result_name}_from_{cooking_type}_{ingredient_name}")
}
fn to_tokens_with_id(&self, tokens: &mut TokenStream, recipe_id: &str) {
let category = match &self.category {
Some(category) => category.to_token_stream(),
None => RecipeCategoryTypes::Misc.to_token_stream(),
};
let group = if let Some(group) = &self.group {
quote! { Some(#group) }
} else {
quote! { None }
};
let ingredient = self.ingredient.to_token_stream();
let cookingtime = self.cookingtime.to_token_stream();
let experience = self.experience.to_token_stream();
let result = self.result.to_token_stream();
tokens.extend(quote! {
recipe_id: #recipe_id,
category: #category,
group: #group,
ingredient: #ingredient,
cookingtime: #cookingtime,
experience: #experience,
result: #result,
});
}
}
impl ToTokens for CookingRecipeStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let category = match &self.category {
Some(category) => category.to_token_stream(),
None => RecipeCategoryTypes::Misc.to_token_stream(),
};
let group = if let Some(group) = &self.group {
quote! { Some(#group) }
} else {
quote! { None }
};
let ingredient = self.ingredient.to_token_stream();
let cookingtime = self.cookingtime.to_token_stream();
let experience = self.experience.to_token_stream();
let result = self.result.to_token_stream();
tokens.extend(quote! {
//CookingRecipeType::Blasting,CampfireCooking,Smelting,Smoking{
category: #category,
group: #group,
ingredient: #ingredient,
cookingtime: #cookingtime,
experience: #experience,
result: #result,
//}
});
}
}
#[derive(Deserialize)]
pub struct CraftingShapedRecipeStruct {
category: Option<RecipeCategoryTypes>,
group: Option<String>,
show_notification: Option<bool>,
key: BTreeMap<String, RecipeIngredientTypes>,
pattern: Vec<String>,
result: RecipeResultStruct,
}
impl ToTokens for CraftingShapedRecipeStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let category = match &self.category {
Some(category) => category.to_token_stream(),
None => RecipeCategoryTypes::Misc.to_token_stream(),
};
let group = if let Some(group) = &self.group {
quote! { Some(#group) }
} else {
quote! { None }
};
let show_notification = self.show_notification.unwrap_or(true);
let key = self
.key
.iter()
.map(|(key, ingredient)| {
let key = key.chars().next().unwrap();
quote! { (#key, #ingredient) }
})
.collect::<Vec<_>>();
let pattern = self
.pattern
.iter()
.map(quote::ToTokens::to_token_stream)
.collect::<Vec<_>>();
let result = self.result.to_token_stream();
tokens.extend(quote! {
CraftingRecipeTypes::CraftingShaped {
category: #category,
group: #group,
show_notification: #show_notification,
key: &[#(#key),*],
pattern: &[#(#pattern),*],
result: #result,
}
});
}
}
#[derive(Deserialize)]
pub struct CraftingShapelessRecipeStruct {
category: Option<RecipeCategoryTypes>,
group: Option<String>,
ingredients: Vec<RecipeIngredientTypes>,
result: RecipeResultStruct,
}
impl ToTokens for CraftingShapelessRecipeStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let category = match &self.category {
Some(category) => category.to_token_stream(),
None => RecipeCategoryTypes::Misc.to_token_stream(),
};
let group = if let Some(group) = &self.group {
quote! { Some(#group) }
} else {
quote! { None }
};
let ingredients = self
.ingredients
.iter()
.map(quote::ToTokens::to_token_stream)
.collect::<Vec<_>>();
let result = self.result.to_token_stream();
tokens.extend(quote! {
CraftingRecipeTypes::CraftingShapeless {
category: #category,
group: #group,
ingredients: &[#(#ingredients),*],
result: #result,
}
});
}
}
#[derive(Deserialize)]
pub struct CraftingTransmuteRecipeStruct {
category: Option<RecipeCategoryTypes>,
group: Option<String>,
input: RecipeIngredientTypes,
material: RecipeIngredientTypes,
result: RecipeResultStruct,
}
impl ToTokens for CraftingTransmuteRecipeStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let category = match &self.category {
Some(category) => category.to_token_stream(),
None => RecipeCategoryTypes::Misc.to_token_stream(),
};
let group = if let Some(group) = &self.group {
quote! { Some(#group) }
} else {
quote! { None }
};
let input = self.input.to_token_stream();
let material = self.material.to_token_stream();
let result = self.result.to_token_stream();
tokens.extend(quote! {
CraftingRecipeTypes::CraftingTransmute {
category: #category,
group: #group,
input: #input,
material: #material,
result: #result,
}
});
}
}
#[derive(Deserialize)]
pub struct CraftingDecoratedPotStruct {
category: Option<RecipeCategoryTypes>,
}
impl ToTokens for CraftingDecoratedPotStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let category = match &self.category {
Some(category) => category.to_token_stream(),
None => RecipeCategoryTypes::Misc.to_token_stream(),
};
tokens.extend(quote! {
CraftingRecipeTypes::CraftingDecoratedPot {
category: #category,
}
});
}
}
#[derive(Deserialize)]
pub struct RecipeResultStruct {
id: String,
count: Option<u8>,
// TODO: components: Option<RecipeResultComponentsStruct>,
}
impl ToTokens for RecipeResultStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let id = self.id.to_token_stream();
let count = self.count.unwrap_or(1).to_token_stream();
tokens.extend(quote! {
RecipeResultStruct {
id: #id,
count: #count,
}
});
}
}
#[derive(Deserialize)]
#[serde(untagged)]
pub enum RecipeIngredientTypes {
Simple(String),
OneOf(Vec<String>),
}
impl ToTokens for RecipeIngredientTypes {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name = match self {
Self::Simple(ingredient) => {
if ingredient.starts_with('#') {
quote! { RecipeIngredientTypes::Tagged(#ingredient) }
} else {
quote! { RecipeIngredientTypes::Simple(#ingredient) }
}
}
Self::OneOf(ingredients) => {
let ingredients = ingredients
.iter()
.map(quote::ToTokens::to_token_stream)
.collect::<Vec<_>>();
quote! { RecipeIngredientTypes::OneOf(&[#(#ingredients),*]) }
}
};
tokens.extend(name);
}
}
#[derive(Deserialize)]
pub enum RecipeCategoryTypes {
#[serde(rename = "equipment")]
Equipment,
#[serde(rename = "building")]
Building,
#[serde(rename = "redstone")]
Restone,
#[serde(rename = "misc")]
Misc,
#[serde(rename = "food")]
Food,
#[serde(rename = "blocks")]
Blocks,
}
impl ToTokens for RecipeCategoryTypes {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name = match self {
Self::Equipment => {
quote! { RecipeCategoryTypes::Equipment }
}
Self::Building => {
quote! { RecipeCategoryTypes::Building }
}
Self::Restone => {
quote! { RecipeCategoryTypes::Restone }
}
Self::Misc => {
quote! { RecipeCategoryTypes::Misc }
}
Self::Food => {
quote! { RecipeCategoryTypes::Food }
}
Self::Blocks => {
quote! { RecipeCategoryTypes::Blocks }
}
};
tokens.extend(name);
}
}
pub fn build() -> TokenStream {
let recipes_assets: Vec<RecipeTypes> =
serde_json::from_str(&fs::read_to_string("../assets/recipes.json").unwrap())
.expect("Failed to parse recipes.json");
let mut crafting_recipes = Vec::new();
let mut cooking_recipes = Vec::new();
for recipe in recipes_assets {
match recipe {
RecipeTypes::Blasting(recipe) => {
let recipe_id = recipe.generate_recipe_id("blasting");
let mut common_cooking_token = TokenStream::new();
recipe.to_tokens_with_id(&mut common_cooking_token, &recipe_id);
let blasting_token = quote! {
CookingRecipeType::Blasting (CookingRecipe {
#common_cooking_token
})
};
cooking_recipes.push(blasting_token);
}
RecipeTypes::CampfireCooking(recipe) => {
let recipe_id = recipe.generate_recipe_id("campfire_cooking");
let mut common_cooking_token = TokenStream::new();
recipe.to_tokens_with_id(&mut common_cooking_token, &recipe_id);
let campfire_token = quote! {
CookingRecipeType::CampfireCooking (CookingRecipe {
#common_cooking_token
})
};
cooking_recipes.push(campfire_token);
}
RecipeTypes::CraftingShaped(recipe) => {
crafting_recipes.push(recipe.to_token_stream());
}
RecipeTypes::CraftingShapeless(recipe) => {
crafting_recipes.push(recipe.to_token_stream());
}
RecipeTypes::CraftingTransmute(recipe) => {
crafting_recipes.push(recipe.to_token_stream());
}
RecipeTypes::CraftingDecoratedPot(recipe) => {
crafting_recipes.push(recipe.to_token_stream());
}
RecipeTypes::Smelting(recipe) => {
let recipe_id = recipe.generate_recipe_id("smelting");
let mut common_cooking_token = TokenStream::new();
recipe.to_tokens_with_id(&mut common_cooking_token, &recipe_id);
let smelting_token = quote! {
CookingRecipeType::Smelting(CookingRecipe {
#common_cooking_token
})
};
cooking_recipes.push(smelting_token);
}
RecipeTypes::SmithingTransform => {}
RecipeTypes::SmithingTrim => {}
RecipeTypes::Smoking(recipe) => {
let recipe_id = recipe.generate_recipe_id("smoking");
let mut common_cooking_token = TokenStream::new();
recipe.to_tokens_with_id(&mut common_cooking_token, &recipe_id);
let smoking_token = quote! {
CookingRecipeType::Smoking(CookingRecipe{
#common_cooking_token
})
};
cooking_recipes.push(smoking_token);
}
RecipeTypes::Stonecutting => {}
RecipeTypes::CraftingSpecial => {}
}
}
quote! {
use crate::tag::Taggable;
use crate::item::Item;
#[derive(Clone, Debug)]
pub enum CraftingRecipeTypes {
CraftingShaped {
category: RecipeCategoryTypes,
group: Option<&'static str>,
show_notification: bool,
key: &'static [(char, RecipeIngredientTypes)],
pattern: &'static [&'static str],
result: RecipeResultStruct,
},
CraftingShapeless {
category: RecipeCategoryTypes,
group: Option<&'static str>,
ingredients: &'static [RecipeIngredientTypes],
result: RecipeResultStruct,
},
CraftingTransmute {
category: RecipeCategoryTypes,
group: Option<&'static str>,
input: RecipeIngredientTypes,
material: RecipeIngredientTypes,
result: RecipeResultStruct,
},
CraftingDecoratedPot {
category: RecipeCategoryTypes,
},
CraftingSpecial,
}
#[allow(dead_code)]
#[derive(Clone, Debug)]
pub struct CookingRecipe {
/// Vanilla-compatible recipe ID (e.g., "minecraft:iron_ingot_from_smelting_iron_ore")
pub recipe_id: &'static str,
pub category: RecipeCategoryTypes,
pub group: Option<&'static str>,
pub ingredient: RecipeIngredientTypes,
pub cookingtime: i32,
pub experience: f32,
pub result: RecipeResultStruct,
}
#[derive(Clone, Debug)]
pub enum CookingRecipeType {
Blasting(CookingRecipe),
Smelting(CookingRecipe),
Smoking(CookingRecipe),
CampfireCooking(CookingRecipe),
}
#[derive(Clone, Debug)]
pub enum CookingRecipeKind {
Blasting,
Smelting,
Smoking,
CampfireCooking,
}
impl From<&CookingRecipeType> for CookingRecipeKind {
fn from(recipe_type: &CookingRecipeType) -> Self {
match recipe_type {
CookingRecipeType::Blasting(_) => CookingRecipeKind::Blasting,
CookingRecipeType::Smelting(_) => CookingRecipeKind::Smelting,
CookingRecipeType::Smoking(_) => CookingRecipeKind::Smoking,
CookingRecipeType::CampfireCooking(_) => CookingRecipeKind::CampfireCooking,
}
}
}
impl From<CookingRecipeType> for CookingRecipeKind {
fn from(recipe_type: CookingRecipeType) -> Self {
match recipe_type {
CookingRecipeType::Blasting(_) => CookingRecipeKind::Blasting,
CookingRecipeType::Smelting(_) => CookingRecipeKind::Smelting,
CookingRecipeType::Smoking(_) => CookingRecipeKind::Smoking,
CookingRecipeType::CampfireCooking(_) => CookingRecipeKind::CampfireCooking,
}
}
}
impl CookingRecipeKind {
pub fn to_type(self, recipe: CookingRecipe) -> CookingRecipeType {
match self {
CookingRecipeKind::Blasting => CookingRecipeType::Blasting(recipe),
CookingRecipeKind::Smelting => CookingRecipeType::Smelting(recipe),
CookingRecipeKind::Smoking => CookingRecipeType::Smoking(recipe),
CookingRecipeKind::CampfireCooking => CookingRecipeType::CampfireCooking(recipe),
}
}
}
#[derive(Clone, Debug)]
pub struct RecipeResultStruct {
pub id: &'static str,
pub count: u8,
}
#[derive(Clone, Debug)]
pub enum RecipeIngredientTypes {
Simple(&'static str),
Tagged(&'static str),
OneOf(&'static [&'static str]),
}
impl RecipeIngredientTypes {
pub fn match_item(&self, item: &Item) -> bool {
match self {
RecipeIngredientTypes::Simple(ingredient) => {
let name = format!("minecraft:{}", item.registry_key);
name == *ingredient
}
RecipeIngredientTypes::Tagged(tag) => item
.is_tagged_with(tag)
.expect("Crafting recipe used invalid tag"),
RecipeIngredientTypes::OneOf(ingredients) => {
let name = format!("minecraft:{}", item.registry_key);
ingredients.contains(&name.as_str())
}
}
}
}
#[derive(Clone, Debug)]
pub enum RecipeCategoryTypes {
Equipment,
Building,
Restone,
Misc,
Food,
Blocks,
}
pub static RECIPES_CRAFTING: &[CraftingRecipeTypes] = &[
#(#crafting_recipes),*
];
pub static RECIPES_COOKING: &[CookingRecipeType] = &[
#(#cooking_recipes ),*
];
pub fn get_cooking_recipe_with_ingredient(ingredient: &Item, recipe_type: CookingRecipeKind) -> Option<&'static CookingRecipe> {
RECIPES_COOKING
.iter()
.find_map(|recipe| match (recipe, &recipe_type) {
(CookingRecipeType::Blasting(cooking_recipe), CookingRecipeKind::Blasting)
| (CookingRecipeType::Smelting(cooking_recipe), CookingRecipeKind::Smelting)
| (CookingRecipeType::Smoking(cooking_recipe), CookingRecipeKind::Smoking)
| (
CookingRecipeType::CampfireCooking(cooking_recipe),
CookingRecipeKind::CampfireCooking,
) => {
cooking_recipe.ingredient.match_item(ingredient).then_some(cooking_recipe)
}
_ => None,
})
}
/// Get the experience value for a recipe by its recipe ID.
/// Used for calculating XP when extracting from furnace.
/// Recipe IDs are in vanilla format like "minecraft:iron_ingot_from_smelting_iron_ore"
pub fn get_recipe_experience(recipe_id: &str) -> Option<f32> {
RECIPES_COOKING.iter().find_map(|recipe| {
let cooking_recipe = match recipe {
CookingRecipeType::Blasting(r)
| CookingRecipeType::Smelting(r)
| CookingRecipeType::Smoking(r)
| CookingRecipeType::CampfireCooking(r) => r,
};
(cooking_recipe.recipe_id == recipe_id).then_some(cooking_recipe.experience)
})
}
}
}
+112
View File
@@ -0,0 +1,112 @@
use indexmap::IndexMap;
use proc_macro2::{Literal, TokenStream};
use quote::quote;
use serde_json::Value;
use std::fs;
pub fn build() -> TokenStream {
let process_version = |path: &str| -> TokenStream {
let json_str = fs::read_to_string(path).unwrap_or_else(|_| panic!("Failed to read {path}"));
let mut data: IndexMap<String, IndexMap<String, Value>> =
serde_json::from_str(&json_str).expect("Failed to parse JSON");
// Inject "raw" chat type for vanilla parity
if let Some(chat) = data.get_mut("minecraft:chat_type") {
chat.insert("raw".to_string(), serde_json::json!({
"chat": { "translation_key": "%s", "parameters": ["content"] },
"narration": { "translation_key": "%s says %s", "parameters": ["sender", "content"] }
}));
}
let reg_tokens: Vec<TokenStream> = data
.iter()
.map(|(reg_name, entries)| {
let entry_tokens: Vec<TokenStream> = entries
.iter()
.map(|(entry_name, entry_data)| {
let mut bytes = Vec::new();
pumpkin_nbt::serializer::to_bytes_unnamed(entry_data, &mut bytes).unwrap();
let byte_literal = Literal::byte_string(&bytes);
quote! {
StaticRegistryEntry {
name: #entry_name,
data: #byte_literal
}
}
})
.collect();
quote! {
StaticRegistry {
registry_id: #reg_name,
entries: &[#(#entry_tokens),*],
}
}
})
.collect();
quote! { &[#(#reg_tokens),*] }
};
let v1_21_9_registries = process_version("../assets/registry/1_21_9_synced_registries.json");
let v1_21_11_registries = process_version("../assets/registry/1_21_11_synced_registries.json");
quote! {
use pumpkin_util::resource_location::ResourceLocation;
use pumpkin_util::version::MinecraftVersion;
pub struct StaticRegistryEntry {
pub name: &'static str,
pub data: &'static [u8],
}
pub struct StaticRegistry {
pub registry_id: &'static str,
pub entries: &'static [StaticRegistryEntry],
}
pub struct RegistryEntryData {
pub entry_id: ResourceLocation,
pub data: Option<Box<[u8]>>,
}
pub struct Registry {
pub registry_id: ResourceLocation,
pub registry_entries: Vec<RegistryEntryData>,
}
pub static REGISTRIES_1_21_9: &[StaticRegistry] = #v1_21_9_registries;
pub static REGISTRIES_1_21_11: &[StaticRegistry] = #v1_21_11_registries;
impl Registry {
pub fn get_synced(version: MinecraftVersion) -> Vec<Self> {
let static_regs = match version {
MinecraftVersion::V_1_21_7 => REGISTRIES_1_21_9,
MinecraftVersion::V_1_21_9 => REGISTRIES_1_21_9,
_ => REGISTRIES_1_21_11,
};
static_regs.iter().map(|static_reg| {
let registry_id = if static_reg.registry_id.contains(':') {
static_reg.registry_id.to_string()
} else {
format!("minecraft:{}", static_reg.registry_id)
};
let registry_entries = static_reg.entries.iter().map(|entry| {
let entry_id = format!("minecraft:{}", entry.name);
RegistryEntryData {
entry_id,
// Data is now sourced directly from the entry
data: Some(entry.data.to_vec().into_boxed_slice()),
}
}).collect();
Self { registry_id, registry_entries }
}).collect()
}
}
}
}
+20
View File
@@ -0,0 +1,20 @@
use std::fs;
use proc_macro2::TokenStream;
use quote::quote;
use crate::array_to_tokenstream;
pub fn build() -> TokenStream {
let sound_categories: Vec<String> = serde_json::from_str(
&fs::read_to_string("../assets/scoreboard_display_slot.json").unwrap(),
)
.expect("Failed to parse scoreboard_display_slot.json");
let variants = array_to_tokenstream(&sound_categories);
quote! {
pub enum ScoreboardDisplaySlot {
#variants
}
}
}
+20
View File
@@ -0,0 +1,20 @@
use std::fs;
use proc_macro2::TokenStream;
use quote::quote;
use crate::array_to_tokenstream;
pub fn build() -> TokenStream {
let screens: Vec<String> =
serde_json::from_str(&fs::read_to_string("../assets/screens.json").unwrap())
.expect("Failed to parse screens.json");
let variants = array_to_tokenstream(&screens);
quote! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WindowType {
#variants
}
}
}
+60
View File
@@ -0,0 +1,60 @@
use std::fs;
use heck::ToPascalCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use crate::array_to_tokenstream;
pub fn build() -> TokenStream {
let mut sound: Vec<String> =
serde_json::from_str(&fs::read_to_string("../assets/sounds.json").unwrap())
.expect("Failed to parse sounds.json");
sound.sort();
let variants = array_to_tokenstream(&sound);
let lookup_table = sound.iter().map(|s| {
let variant_name = format_ident!("{}", s.to_pascal_case());
quote! { (#s, Self::#variant_name) }
});
let variants_list = sound.iter().map(|s| {
let variant_name = format_ident!("{}", s.to_pascal_case());
quote! { Self::#variant_name, }
});
let names_list = sound.iter().map(|s| quote! { #s });
quote! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u16)]
pub enum Sound {
#variants
}
impl Sound {
const NAMES: &[&str] = &[ #(#names_list),* ];
const LOOKUP: &[(&str, Sound)] = &[
#(#lookup_table),*
];
pub fn from_name(name: &str) -> Option<Self> {
Self::LOOKUP
.binary_search_by_key(&name, |&(k, _)| k)
.ok()
.map(|idx| Self::LOOKUP[idx].1)
}
pub const fn to_name(&self) -> &'static str {
Self::NAMES[*self as usize]
}
pub fn slice() -> &'static [Self] {
&[#(#variants_list)*]
}
}
}
}
+58
View File
@@ -0,0 +1,58 @@
use std::fs;
use heck::ToPascalCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use crate::array_to_tokenstream;
pub fn build() -> TokenStream {
let sound_categories: Vec<String> =
serde_json::from_str(&fs::read_to_string("../assets/sound_category.json").unwrap())
.expect("Failed to parse sound_category.json");
let variants = array_to_tokenstream(&sound_categories);
let type_from_name = &sound_categories
.iter()
.map(|sound| {
let id = &sound.to_lowercase();
let name = format_ident!("{}", sound.to_pascal_case());
quote! {
#id => Some(Self::#name),
}
})
.collect::<TokenStream>();
let type_to_name = &sound_categories
.iter()
.map(|sound| {
let id = &sound.to_lowercase();
let name = format_ident!("{}", sound.to_pascal_case());
quote! {
Self::#name => #id,
}
})
.collect::<TokenStream>();
quote! {
#[derive(Clone, Copy)]
pub enum SoundCategory {
#variants
}
impl SoundCategory {
pub fn from_name(name: &str) -> Option<Self> {
match name {
#type_from_name
_ => None
}
}
pub const fn to_name(&self) -> &'static str {
match self {
#type_to_name
}
}
}
}
}
+33
View File
@@ -0,0 +1,33 @@
use std::{collections::BTreeMap, fs};
use heck::ToShoutySnakeCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
pub fn build() -> TokenStream {
let eggs: BTreeMap<u16, String> =
serde_json::from_str(&fs::read_to_string("../assets/spawn_egg.json").unwrap())
.expect("Failed to parse spawn_egg.json");
let mut names = TokenStream::new();
let mut ids = TokenStream::new();
for (egg, entity) in &eggs {
let entity = entity.to_shouty_snake_case();
let entity = format_ident!("{}", entity);
ids.extend(quote! { #egg, });
names.extend(quote! { #egg => Some(&EntityType::#entity), });
}
quote! {
use crate::entity_type::EntityType;
pub fn entity_from_egg(id: u16) -> Option<&'static EntityType> {
match id {
#names
_ => None
}
}
pub fn spawn_egg_ids() -> Box<[u16]> {
[#ids].into()
}
}
}
+462
View File
@@ -0,0 +1,462 @@
use proc_macro2::TokenStream;
use quote::{ToTokens, format_ident, quote};
use serde::Deserialize;
use std::{collections::BTreeMap, fs};
#[derive(Deserialize)]
pub struct StructureSetStruct {
pub placement: StructurePlacementStruct,
pub structures: Vec<WeightedEntryStruct>,
}
#[derive(Deserialize, Clone)]
pub struct WeightedEntryStruct {
pub structure: String,
pub weight: u32,
}
#[derive(Deserialize)]
pub struct StructurePlacementStruct {
frequency_reduction_method: Option<String>,
frequency: Option<f32>,
salt: u32,
#[serde(flatten)]
r#type: StructurePlacementTypeStruct,
}
#[derive(Deserialize)]
#[serde(tag = "type")]
pub enum StructurePlacementTypeStruct {
#[serde(rename = "minecraft:random_spread")]
RandomSpread {
spacing: i32,
separation: i32,
spread_type: Option<String>,
},
#[serde(rename = "minecraft:concentric_rings")]
ConcentricRings {
spread: i32,
distance: i32,
count: i32,
preferred_biomes: String,
},
}
#[derive(Deserialize, Clone)]
pub struct StructureStruct {
pub biomes: String,
pub step: String,
}
impl ToTokens for StructureSetStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let placement = &self.placement;
let structures = &self.structures;
tokens.extend(quote!(
StructureSet {
placement: #placement,
structures: &[#(#structures),*],
}
));
}
}
impl ToTokens for WeightedEntryStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let structure = structure_key_to_token(&self.structure);
let weight = self.weight;
tokens.extend(quote!(
WeightedEntry {
structure: #structure,
weight: #weight,
}
));
}
}
impl ToTokens for StructurePlacementStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let frequency_reduction = if let Some(method) = &self.frequency_reduction_method {
let method_token = frequency_reduction_to_token(method);
quote!(Some(#method_token))
} else {
quote!(None)
};
let frequency = if let Some(f) = self.frequency {
quote!(Some(#f))
} else {
quote!(None)
};
let salt = self.salt;
let placement_type = &self.r#type;
tokens.extend(quote!(
StructurePlacement {
frequency_reduction_method: #frequency_reduction,
frequency: #frequency,
salt: #salt,
placement_type: #placement_type,
}
));
}
}
impl ToTokens for StructurePlacementTypeStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::RandomSpread {
spacing,
separation,
spread_type,
} => {
let spread_type_token = if let Some(st) = spread_type {
let st_token = spread_type_to_token(st);
quote!(Some(#st_token))
} else {
quote!(None)
};
tokens.extend(quote!(
StructurePlacementType::RandomSpread(RandomSpreadStructurePlacement {
spacing: #spacing,
separation: #separation,
spread_type: #spread_type_token,
})
));
}
Self::ConcentricRings {
spread,
distance,
count,
preferred_biomes,
} => {
tokens.extend(quote!(
StructurePlacementType::ConcentricRings(ConcentricRingsStructurePlacement {
spread: #spread,
distance: #distance,
count: #count,
preferred_biomes: #preferred_biomes,
})
));
}
}
}
}
impl ToTokens for StructureStruct {
fn to_tokens(&self, tokens: &mut TokenStream) {
let biomes = &self.biomes;
let step = generation_step_to_token(&self.step);
tokens.extend(quote!(
Structure {
biomes: #biomes,
step: #step,
}
));
}
}
// Helper functions
fn structure_key_to_token(key: &str) -> TokenStream {
let stripped = key.strip_prefix("minecraft:").unwrap_or(key);
match stripped {
"pillager_outpost" => quote!(StructureKeys::PillagerOutpost),
"mineshaft" => quote!(StructureKeys::Mineshaft),
"mineshaft_mesa" => quote!(StructureKeys::MineshaftMesa),
"mansion" => quote!(StructureKeys::Mansion),
"jungle_pyramid" => quote!(StructureKeys::JunglePyramid),
"desert_pyramid" => quote!(StructureKeys::DesertPyramid),
"igloo" => quote!(StructureKeys::Igloo),
"shipwreck" => quote!(StructureKeys::Shipwreck),
"shipwreck_beached" => quote!(StructureKeys::ShipwreckBeached),
"swamp_hut" => quote!(StructureKeys::SwampHut),
"stronghold" => quote!(StructureKeys::Stronghold),
"monument" => quote!(StructureKeys::Monument),
"ocean_ruin_cold" => quote!(StructureKeys::OceanRuinCold),
"ocean_ruin_warm" => quote!(StructureKeys::OceanRuinWarm),
"fortress" => quote!(StructureKeys::Fortress),
"nether_fossil" => quote!(StructureKeys::NetherFossil),
"end_city" => quote!(StructureKeys::EndCity),
"buried_treasure" => quote!(StructureKeys::BuriedTreasure),
"bastion_remnant" => quote!(StructureKeys::BastionRemnant),
"village_plains" => quote!(StructureKeys::VillagePlains),
"village_desert" => quote!(StructureKeys::VillageDesert),
"village_savanna" => quote!(StructureKeys::VillageSavanna),
"village_snowy" => quote!(StructureKeys::VillageSnowy),
"village_taiga" => quote!(StructureKeys::VillageTaiga),
"ruined_portal" => quote!(StructureKeys::RuinedPortal),
"ruined_portal_desert" => quote!(StructureKeys::RuinedPortalDesert),
"ruined_portal_jungle" => quote!(StructureKeys::RuinedPortalJungle),
"ruined_portal_swamp" => quote!(StructureKeys::RuinedPortalSwamp),
"ruined_portal_mountain" => quote!(StructureKeys::RuinedPortalMountain),
"ruined_portal_ocean" => quote!(StructureKeys::RuinedPortalOcean),
"ruined_portal_nether" => quote!(StructureKeys::RuinedPortalNether),
"ancient_city" => quote!(StructureKeys::AncientCity),
"trail_ruins" => quote!(StructureKeys::TrailRuins),
"trial_chambers" => quote!(StructureKeys::TrialChambers),
_ => panic!("Unknown structure key: {stripped}"),
}
}
fn frequency_reduction_to_token(method: &str) -> TokenStream {
match method {
"default" => quote!(FrequencyReductionMethod::Default),
"legacy_type_1" => quote!(FrequencyReductionMethod::LegacyType1),
"legacy_type_2" => quote!(FrequencyReductionMethod::LegacyType2),
"legacy_type_3" => quote!(FrequencyReductionMethod::LegacyType3),
_ => quote!(FrequencyReductionMethod::Default),
}
}
fn spread_type_to_token(spread: &str) -> TokenStream {
match spread {
"linear" => quote!(SpreadType::Linear),
"triangular" => quote!(SpreadType::Triangular),
_ => quote!(SpreadType::Linear),
}
}
fn generation_step_to_token(step: &str) -> TokenStream {
match step {
"raw_generation" => quote!(GenerationStep::RawGeneration),
"lakes" => quote!(GenerationStep::Lakes),
"local_modifications" => quote!(GenerationStep::LocalModifications),
"underground_structures" => quote!(GenerationStep::UndergroundStructures),
"surface_structures" => quote!(GenerationStep::SurfaceStructures),
"strongholds" => quote!(GenerationStep::Strongholds),
"underground_ores" => quote!(GenerationStep::UndergroundOres),
"underground_decoration" => quote!(GenerationStep::UndergroundDecoration),
"fluid_springs" => quote!(GenerationStep::FluidSprings),
"vegetal_decoration" => quote!(GenerationStep::VegetalDecoration),
"top_layer_modification" => quote!(GenerationStep::TopLayerModification),
_ => panic!("Unknown generation step: {step}"),
}
}
pub fn build() -> TokenStream {
let structures_json: BTreeMap<String, StructureStruct> =
serde_json::from_str(&fs::read_to_string("../assets/structures.json").unwrap())
.expect("Failed to parse structures.json");
let structure_sets_json: BTreeMap<String, StructureSetStruct> =
serde_json::from_str(&fs::read_to_string("../assets/structure_set.json").unwrap())
.expect("Failed to parse structure_set.json");
let mut structure_const_defs = TokenStream::new();
let mut structure_lookup_arms = TokenStream::new();
for (name, structure) in &structures_json {
let stripped_name = name.strip_prefix("minecraft:").unwrap_or(name);
let upper_name = stripped_name.to_uppercase();
let const_name = format_ident!("{}", upper_name);
let key_variant = structure_key_to_token(name);
structure_const_defs.extend(quote!(
pub const #const_name: Structure = #structure;
));
structure_lookup_arms.extend(quote!(
#key_variant => &Self::#const_name,
));
}
let mut structure_set_const_defs = TokenStream::new();
let mut structure_set_lookup_arms = TokenStream::new();
let mut all_structure_set_idents = Vec::new();
for (name, structure_set) in &structure_sets_json {
let stripped_name = name.strip_prefix("minecraft:").unwrap_or(name);
let upper_name = stripped_name.to_uppercase().replace('/', "_");
let const_name = format_ident!("{}", upper_name);
structure_set_const_defs.extend(quote!(
pub const #const_name: StructureSet = #structure_set;
));
structure_set_lookup_arms.extend(quote!(
#stripped_name => Some(&Self::#const_name),
));
all_structure_set_idents.push(const_name);
}
quote!(
use pumpkin_util::math::floor_div;
use pumpkin_util::random::{
RandomGenerator, RandomImpl, get_carver_seed, get_region_seed,
legacy_rand::LegacyRand, xoroshiro128::Xoroshiro,
};
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum StructureKeys {
PillagerOutpost,
Mineshaft,
MineshaftMesa,
Mansion,
JunglePyramid,
DesertPyramid,
Igloo,
Shipwreck,
ShipwreckBeached,
SwampHut,
Stronghold,
Monument,
OceanRuinCold,
OceanRuinWarm,
Fortress,
NetherFossil,
EndCity,
BuriedTreasure,
BastionRemnant,
VillagePlains,
VillageDesert,
VillageSavanna,
VillageSnowy,
VillageTaiga,
RuinedPortal,
RuinedPortalDesert,
RuinedPortalJungle,
RuinedPortalSwamp,
RuinedPortalMountain,
RuinedPortalOcean,
RuinedPortalNether,
AncientCity,
TrailRuins,
TrialChambers,
}
pub struct StructureSet {
pub placement: StructurePlacement,
pub structures: &'static [WeightedEntry],
}
#[derive(Clone)]
pub struct WeightedEntry {
pub structure: StructureKeys,
pub weight: u32,
}
pub struct StructurePlacement {
pub frequency_reduction_method: Option<FrequencyReductionMethod>,
pub frequency: Option<f32>,
pub salt: u32,
pub placement_type: StructurePlacementType,
}
#[derive(Clone, Copy)]
pub enum FrequencyReductionMethod {
Default,
LegacyType1,
LegacyType2,
LegacyType3,
}
pub enum StructurePlacementType {
RandomSpread(RandomSpreadStructurePlacement),
ConcentricRings(ConcentricRingsStructurePlacement),
}
pub struct RandomSpreadStructurePlacement {
pub spacing: i32,
pub separation: i32,
pub spread_type: Option<SpreadType>,
}
pub struct ConcentricRingsStructurePlacement {
pub spread: i32,
pub distance: i32,
pub count: i32,
pub preferred_biomes: &'static str,
}
#[derive(Clone, Copy)]
pub enum SpreadType {
Linear,
Triangular,
}
impl SpreadType {
pub fn get(&self, random: &mut RandomGenerator, bound: i32) -> i32 {
match self {
Self::Linear => random.next_bounded_i32(bound),
Self::Triangular => i32::midpoint(
random.next_bounded_i32(bound),
random.next_bounded_i32(bound),
),
}
}
}
pub struct Structure {
pub biomes: &'static str,
pub step: GenerationStep,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GenerationStep {
RawGeneration,
Lakes,
LocalModifications,
UndergroundStructures,
SurfaceStructures,
Strongholds,
UndergroundOres,
UndergroundDecoration,
FluidSprings,
VegetalDecoration,
TopLayerModification,
}
impl GenerationStep {
#[must_use]
pub const fn ordinal(&self) -> usize {
*self as usize
}
}
pub struct StructurePlacementCalculator {
pub seed: i64,
}
impl StructurePlacementCalculator {
#[must_use]
pub const fn new(seed: i64) -> Self {
Self { seed }
}
}
impl Structure {
#structure_const_defs
#[must_use]
pub const fn get(key: &StructureKeys) -> &'static Self {
match *key {
#structure_lookup_arms
}
}
}
impl StructureSet {
#structure_set_const_defs
pub const ALL: &'static [StructureSet] = &[
#(Self::#all_structure_set_idents),*
];
#[must_use]
pub fn get(name: &str) -> Option<&'static Self> {
match name {
#structure_set_lookup_arms
_ => None,
}
}
}
)
}
+257
View File
@@ -0,0 +1,257 @@
use std::{
collections::{BTreeMap, HashSet},
fs,
path::Path,
};
use crate::biome::Biome;
use crate::block::BlockAssets;
use crate::enchantments::Enchantment;
use crate::entity_type::EntityType;
use crate::fluid::Fluid;
use crate::item::Item;
use heck::ToPascalCase;
use proc_macro2::TokenStream;
use quote::{ToTokens, format_ident, quote};
// --- EnumCreator with from_string support ---
pub struct EnumCreator {
pub name: String,
pub values: Vec<String>,
}
impl ToTokens for EnumCreator {
fn to_tokens(&self, tokens: &mut TokenStream) {
let name = format_ident!("{}", self.name.to_pascal_case());
let variants = self.values.iter().map(|v| {
let variant_name = format_ident!("{}", v.to_pascal_case());
quote! { #variant_name }
});
let from_string_arms = self.values.iter().map(|v| {
let variant_name = format_ident!("{}", v.to_pascal_case());
quote! { #v => Some(Self::#variant_name) }
});
let to_string_arms = self.values.iter().map(|v| {
let variant_name = format_ident!("{}", v.to_pascal_case());
quote! { Self::#variant_name => #v }
});
tokens.extend(quote! {
#[derive(Eq, PartialEq, Hash, Debug, Clone, Copy)]
pub enum #name {
#(#variants),*
}
impl #name {
pub fn from_string(s: &str) -> Option<Self> {
match s {
#(#from_string_arms,)*
_ => None,
}
}
pub fn identifier_string(&self) -> &str {
match self {
#(#to_string_arms),*
}
}
}
});
}
}
pub fn build() -> TokenStream {
let blocks_assets: BlockAssets =
serde_json::from_str(&fs::read_to_string("../assets/blocks.json").unwrap())
.expect("Failed to parse blocks.json");
let items: BTreeMap<String, Item> =
serde_json::from_str(&fs::read_to_string("../assets/items.json").unwrap())
.expect("Failed to parse items.json");
let biomes: BTreeMap<String, Biome> =
serde_json::from_str(&fs::read_to_string("../assets/biome.json").unwrap())
.expect("Failed to parse biome.json");
let fluids: Vec<Fluid> =
serde_json::from_str(&fs::read_to_string("../assets/fluids.json").unwrap())
.expect("Failed to parse fluids.json");
let enchantments: BTreeMap<String, Enchantment> =
serde_json::from_str(&fs::read_to_string("../assets/enchantments.json").unwrap())
.expect("Failed to parse enchantments.json");
let entities: BTreeMap<String, EntityType> =
serde_json::from_str(&fs::read_to_string("../assets/entities.json").unwrap())
.expect("Failed to parse entities.json");
let block_id_map: BTreeMap<String, u16> = blocks_assets
.blocks
.iter()
.map(|b| (b.name.clone(), b.id))
.collect();
let fluid_id_map: BTreeMap<String, u16> =
fluids.iter().map(|f| (f.name.clone(), f.id)).collect();
let latest_version_key = "1_21_11";
let legacy_version_key = "1_21_9";
let mut all_registry_keys = HashSet::new();
let mut latest_modules = Vec::new();
let mut legacy_modules = Vec::new();
let mut match_get_map = Vec::new();
let versions = vec![latest_version_key, legacy_version_key];
for version in versions {
let file_path = format!("../assets/tags/{version}_tags.json");
if !Path::new(&file_path).exists() {
continue;
}
let tags: BTreeMap<String, BTreeMap<String, Vec<String>>> =
serde_json::from_str(&fs::read_to_string(&file_path).unwrap()).unwrap();
let is_latest = version == latest_version_key;
let mut tag_dicts = Vec::new();
let mut match_local_map = Vec::new();
for (key, tag_map) in tags {
all_registry_keys.insert(key.clone());
let key_pascal = format_ident!("{}", key.to_pascal_case());
let dict_name = format_ident!("{}_TAGS", key.to_pascal_case().to_uppercase());
let mut tag_entries = Vec::new();
let mut tag_map_entries = Vec::new();
let tag_type_path = if is_latest {
quote!(super::Tag)
} else {
quote!(super::super::Tag)
};
for (tag_name, values) in tag_map {
let ids: Vec<u16> = values
.iter()
.filter_map(|v| match key.as_str() {
"worldgen/biome" => biomes.get(v).map(|b| u16::from(b.id)),
"fluid" => fluid_id_map.get(v).copied(),
"item" => items.get(v).map(|i| i.id),
"block" => block_id_map.get(v).copied(),
"enchantment" => enchantments
.get(&format!("minecraft:{v}"))
.map(|e| u16::from(e.id)),
"entity_type" => entities.get(v).map(|e| e.id),
_ => None,
})
.collect();
let tag_const_name =
format_ident!("{}", tag_name.replace([':', '/'], "_").to_uppercase());
tag_entries.push(quote! {
pub const #tag_const_name: #tag_type_path = (&[#(#values),*], &[#(#ids),*]);
});
tag_map_entries.push(quote! { #tag_name => &#key_pascal::#tag_const_name });
}
let tag_type_path = if is_latest {
quote!(Tag)
} else {
quote!(super::Tag)
};
tag_dicts.push(quote! {
#[allow(non_snake_case)]
pub mod #key_pascal {
#(#tag_entries)* }
pub(crate) static #dict_name: phf::Map<&'static str, &'static #tag_type_path> = phf::phf_map! {
#(#tag_map_entries),* };
});
match_local_map.push(quote! { RegistryKey::#key_pascal => Some(&#dict_name) });
}
if is_latest {
latest_modules.push(quote! {
#(#tag_dicts)*
#[allow(unreachable_patterns)]
pub fn get_latest_map(key: RegistryKey) -> Option<&'static phf::Map<&'static str, &'static Tag>> {
match key { #(#match_local_map,)* _ => None }
}
});
match_get_map
.push(quote! { MinecraftVersion::V_1_21_11 => get_latest_map(tag_category) });
} else {
let mod_name = format_ident!("tags_{}", version);
legacy_modules.push(quote! {
mod #mod_name {
use super::RegistryKey;
#(#tag_dicts)*
pub fn get_map(key: RegistryKey) -> Option<&'static phf::Map<&'static str, &'static super::Tag>> {
match key { #(#match_local_map,)* _ => None }
}
}
});
match_get_map
.push(quote! { MinecraftVersion::V_1_21_9 => tags_1_21_9::get_map(tag_category) });
match_get_map
.push(quote! { MinecraftVersion::V_1_21_7 => tags_1_21_9::get_map(tag_category) });
}
}
// --- Generate RegistryKey Enum ---
let registry_key_enum = EnumCreator {
name: "RegistryKey".to_string(),
values: all_registry_keys.into_iter().collect(),
}
.to_token_stream();
quote! {
use pumpkin_util::version::MinecraftVersion;
pub type Tag = (&'static [&'static str], &'static [u16]);
#registry_key_enum
// Latest tags are exported directly here
#(#latest_modules)*
// Legacy tags are hidden in their own module
#(#legacy_modules)*
pub fn get_tag_values(tag_category: RegistryKey, tag: &str) -> Option<&'static [&'static str]> {
get_latest_map(tag_category).and_then(|m| m.get(tag)).map(|t| t.0)
}
pub fn get_tag_ids(tag_category: RegistryKey, tag: &str) -> Option<&'static [u16]> {
get_latest_map(tag_category).and_then(|m| m.get(tag)).map(|t| t.1)
}
pub fn get_registry_key_tags(version: MinecraftVersion, tag_category: RegistryKey) -> Option<&'static phf::Map<&'static str, &'static Tag>> {
match version {
#(#match_get_map),*,
_ => get_latest_map(tag_category)
}
}
pub trait Taggable {
fn tag_key() -> RegistryKey;
fn registry_key(&self) -> &str;
fn registry_id(&self) -> u16;
fn is_tagged_with(&self, tag: &str) -> Option<bool> {
let tag = tag.strip_prefix("#").unwrap_or(tag);
let items = get_tag_ids(Self::tag_key(), tag)?;
Some(items.contains(&self.registry_id()))
}
fn has_tag(&self, tag: &'static Tag) -> bool {
tag.1.contains(&self.registry_id())
}
fn get_tag_values(tag: &str) -> Option<&'static [&'static str]> {
let tag = tag.strip_prefix("#").unwrap_or(tag);
get_tag_values(Self::tag_key(), tag)
}
}
}
}
+63
View File
@@ -0,0 +1,63 @@
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use std::{collections::BTreeMap, fs};
pub fn build() -> TokenStream {
let data_7: BTreeMap<String, u8> = serde_json::from_str(
&fs::read_to_string("../assets/tracked_data/1_21_7_tracked_data.json")
.expect("1.21.7 data missing"),
)
.unwrap();
let data_11: BTreeMap<String, u8> = serde_json::from_str(
&fs::read_to_string("../assets/tracked_data/1_21_11_tracked_data.json")
.expect("1.21.11 data missing"),
)
.unwrap();
let mut constants = TokenStream::new();
for (name, id_11) in &data_11 {
let ident = format_ident!("DATA_{}", name.to_uppercase());
let id_7 = data_7.get(name).copied().unwrap_or(255); // 255 as an 'Invalid' marker
constants.extend(quote! {
pub const #ident: TrackedId = TrackedId {
latest: #id_11,
v1_21_7: #id_7,
};
});
}
quote! {
use pumpkin_util::version::MinecraftVersion;
#[derive(Copy, Clone, Debug)]
pub struct TrackedId {
pub latest: u8,
pub v1_21_7: u8,
}
impl TrackedId {
pub fn get(&self, version: &MinecraftVersion) -> u8 {
match version {
MinecraftVersion::V_1_21_7 | MinecraftVersion::V_1_21_9 => self.v1_21_7,
_ => self.latest,
}
}
}
impl From<TrackedId> for u8 {
fn from(id: TrackedId) -> u8 {
id.latest
}
}
pub struct TrackedData;
impl TrackedData {
#constants
}
}
}
+32
View File
@@ -0,0 +1,32 @@
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use std::{collections::BTreeMap, fs};
pub fn build() -> TokenStream {
let en_us: BTreeMap<String, String> = serde_json::from_str(
&fs::read_to_string("../assets/en_us.json").expect("en_us is missing"),
)
.unwrap();
let mut constants = TokenStream::new();
for (name, value) in &en_us {
let clean_name = name.to_uppercase().replace(['.', '-'], "_");
let ident = format_ident!("{}", clean_name);
if value.is_empty() {
constants.extend(quote! {
pub const #ident: &str = #name;
});
} else {
constants.extend(quote! {
#[doc = #value]
pub const #ident: &str = #name;
});
}
}
quote! {
#constants
}
}
+28
View File
@@ -0,0 +1,28 @@
use std::{collections::BTreeMap, fs};
use heck::ToPascalCase;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
pub fn build() -> TokenStream {
let events: BTreeMap<String, u16> =
serde_json::from_str(&fs::read_to_string("../assets/world_event.json").unwrap())
.expect("Failed to parse world_event.json");
let variants: Vec<TokenStream> = events
.into_iter()
.map(|(event_name, id)| {
let name = format_ident!("{}", event_name.to_pascal_case());
quote! {
#name = #id,
}
})
.collect();
quote! {
#[repr(u16)]
pub enum WorldEvent {
#(#variants)*
}
}
}