diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bbb8b3b84..5d5e285c5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -83,7 +83,7 @@ jobs: - name: The harnesses this change can affect env: PARITY_HOSTS: '' - run: python3 tools/parity.py --changed ${{ github.event.pull_request.base.sha }} --timeout 1500 + run: python3 tools/parity.py --changed ${{ github.event.pull_request.base.sha }} --timeout 2400 # world_spawn takes ~1480 s on a busy runner - name: Logs of the failed harnesses if: failure() uses: actions/upload-artifact@v4 diff --git a/benchmarks/shared-json-buffer-lifetime-20261017.json b/benchmarks/shared-json-buffer-lifetime-20261017.json new file mode 100644 index 000000000..d618906ed --- /dev/null +++ b/benchmarks/shared-json-buffer-lifetime-20261017.json @@ -0,0 +1,379 @@ +{ + "scope": "Assets + BlockFacts + Behaviours loader only; no full startup or first frame", + "resources": "/srv/bob-data/horizon/.local/horizon-client/26.3", + "repeats": 10, + "ordering": [ + [ + "released", + "retained" + ], + [ + "retained", + "released" + ], + [ + "released", + "retained" + ], + [ + "retained", + "released" + ], + [ + "released", + "retained" + ], + [ + "retained", + "released" + ], + [ + "released", + "retained" + ], + [ + "retained", + "released" + ], + [ + "released", + "retained" + ], + [ + "retained", + "released" + ] + ], + "load_average_before": [ + 8.2421875, + 6.56396484375, + 6.39208984375 + ], + "load_average_after": [ + 7.98095703125, + 6.6455078125, + 6.4248046875 + ], + "executables": { + "released": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-integrated", + "mode": "deferred", + "sha256": "a52d6a7efc7b3198ef0dd8150325f56a3fe5d0c5883fd6d14c4b0c281866ce7c" + }, + "retained": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-integrated", + "mode": "deferred-held", + "sha256": "a52d6a7efc7b3198ef0dd8150325f56a3fe5d0c5883fd6d14c4b0c281866ce7c" + } + }, + "metrics": { + "released": { + "phase_ms": { + "median": 482.591, + "p25": 444.276, + "p75": 586.92, + "min": 430.128, + "max": 736.543, + "samples": [ + 529.244, + 606.146, + 449.23, + 442.624, + 669.108, + 511.519, + 736.543, + 432.616, + 430.128, + 453.663 + ] + }, + "total_ms": { + "median": 987.004, + "p25": 932.885, + "p75": 1134.876, + "min": 914.242, + "max": 1201.759, + "samples": [ + 1055.119, + 1161.462, + 968.629, + 914.242, + 1201.759, + 1005.379, + 1200.01, + 928.249, + 935.775, + 931.921 + ] + }, + "cpu_ms": { + "median": 1004.675, + "p25": 936.465, + "p75": 1116.791, + "min": 908.327, + "max": 1241.168, + "samples": [ + 1074.425, + 1130.913, + 984.832, + 931.205, + 1186.169, + 1024.519, + 1241.168, + 908.327, + 952.245, + 927.15 + ] + }, + "peak_rss_kib": { + "median": 268124.0, + "p25": 267753.0, + "p75": 268455.0, + "min": 267708, + "max": 268700, + "samples": [ + 268268, + 268500, + 267744, + 267724, + 267708, + 267780, + 268700, + 268496, + 268332, + 267980 + ] + }, + "behaviour_json_ms": { + "median": 24.371, + "p25": 22.469, + "p75": 28.486, + "min": 20.662, + "max": 35.297, + "samples": [ + 33.387, + 35.297, + 24.732, + 24.011, + 27.699, + 28.748, + 23.623, + 22.084, + 20.662, + 21.266 + ] + }, + "facts_ms": { + "median": 292.77, + "p25": 270.649, + "p75": 383.193, + "min": 264.691, + "max": 443.291, + "samples": [ + 346.613, + 398.468, + 274.673, + 264.691, + 443.291, + 292.926, + 395.387, + 267.232, + 269.308, + 292.615 + ] + }, + "behaviours_ms": { + "median": 148.635, + "p25": 141.329, + "p75": 181.741, + "min": 136.361, + "max": 307.004, + "samples": [ + 145.009, + 168.982, + 146.535, + 150.736, + 194.604, + 185.994, + 307.004, + 140.102, + 136.785, + 136.361 + ] + }, + "post_rss_kib": { + "median": 268668.0, + "p25": 268246.0, + "p75": 268922.0, + "min": 268048.0, + "max": 269012.0, + "samples": [ + 268668.0, + 268936.0, + 268108.0, + 268088.0, + 268048.0, + 268668.0, + 268880.0, + 269012.0, + 268960.0, + 268660.0 + ] + } + }, + "retained": { + "phase_ms": { + "median": 487.954, + "p25": 471.456, + "p75": 531.586, + "min": 401.516, + "max": 834.154, + "samples": [ + 486.974, + 613.755, + 540.535, + 470.333, + 488.934, + 474.825, + 834.154, + 504.74, + 401.516, + 440.381 + ] + }, + "total_ms": { + "median": 1038.875, + "p25": 989.724, + "p75": 1079.197, + "min": 880.933, + "max": 1746.386, + "samples": [ + 996.407, + 1067.467, + 1082.69, + 1103.131, + 1010.283, + 1068.719, + 1746.386, + 987.496, + 890.46, + 880.933 + ] + }, + "cpu_ms": { + "median": 1035.537, + "p25": 982.276, + "p75": 1082.698, + "min": 908.774, + "max": 1660.068, + "samples": [ + 1011.712, + 1087.688, + 1076.523, + 1084.757, + 998.654, + 1059.363, + 1660.068, + 976.817, + 912.849, + 908.774 + ] + }, + "peak_rss_kib": { + "median": 268150.0, + "p25": 267537.0, + "p75": 268614.0, + "min": 267268, + "max": 268848, + "samples": [ + 268748, + 267968, + 267268, + 268332, + 267540, + 268560, + 267492, + 268632, + 267536, + 268848 + ] + }, + "behaviour_json_ms": { + "median": 23.208, + "p25": 22.305, + "p75": 26.544, + "min": 20.059, + "max": 32.669, + "samples": [ + 32.669, + 22.62, + 22.2, + 27.331, + 25.088, + 27.029, + 23.488, + 20.977, + 22.928, + 20.059 + ] + }, + "facts_ms": { + "median": 304.44, + "p25": 291.562, + "p75": 330.991, + "min": 244.758, + "max": 384.634, + "samples": [ + 307.936, + 374.145, + 336.931, + 300.944, + 290.81, + 293.817, + 384.634, + 313.171, + 244.758, + 279.303 + ] + }, + "behaviours_ms": { + "median": 162.285, + "p25": 143.135, + "p75": 179.31, + "min": 133.83, + "max": 426.031, + "samples": [ + 146.367, + 216.988, + 181.402, + 142.058, + 173.036, + 153.978, + 426.031, + 170.592, + 133.83, + 141.017 + ] + }, + "post_rss_kib": { + "median": 268694.0, + "p25": 268116.0, + "p75": 269056.0, + "min": 267988.0, + "max": 269212.0, + "samples": [ + 269212.0, + 268564.0, + 268096.0, + 268824.0, + 268176.0, + 269032.0, + 267988.0, + 269064.0, + 268044.0, + 269120.0 + ] + } + } + } +} diff --git a/benchmarks/shared-json-decoder-phases-20261017.json b/benchmarks/shared-json-decoder-phases-20261017.json new file mode 100644 index 000000000..8c5880124 --- /dev/null +++ b/benchmarks/shared-json-decoder-phases-20261017.json @@ -0,0 +1,176 @@ +{ + "scope": "Isolated gameplay-facts.json validation/typed decoding; includes JSON file read", + "resources": "/srv/bob-data/horizon/.local/horizon-client/26.3", + "repeats": 10, + "load_averages_before_after": [ + [ + 14.7451171875, + 8.8994140625, + 6.89599609375 + ], + [ + 14.7451171875, + 8.8994140625, + 6.89599609375 + ] + ], + "binary_sha256": "c2be9140c792720499d70c5806b8def0472734264ad72486d01365447e0cc2d7", + "metrics": { + "validate": { + "phase_ms": { + "median": 117.417, + "p25": 114.101, + "p75": 158.855, + "min": 109.199, + "max": 173.408, + "samples": [ + 109.199, + 113.958, + 110.195, + 118.987, + 171.275, + 124.701, + 170.24, + 173.408, + 115.848, + 114.531 + ] + }, + "total_ms": { + "median": 139.933, + "p25": 133.863, + "p75": 193.565, + "min": 129.75, + "max": 276.311, + "samples": [ + 276.311, + 135.448, + 129.75, + 138.452, + 195.127, + 141.413, + 188.88, + 199.802, + 133.335, + 132.094 + ] + }, + "cpu_ms": { + "median": 138.849, + "p25": 134.285, + "p75": 168.881, + "min": 129.089, + "max": 190.82, + "samples": [ + 140.962, + 136.06, + 129.089, + 139.059, + 189.478, + 138.639, + 178.187, + 190.82, + 133.693, + 132.716 + ] + }, + "peak_rss_kib": { + "median": 56654.0, + "p25": 56642.0, + "p75": 56704.0, + "min": 56616, + "max": 56724, + "samples": [ + 56620, + 56656, + 56640, + 56720, + 56616, + 56724, + 56652, + 56720, + 56648, + 56656 + ] + } + }, + "typed": { + "phase_ms": { + "median": 115.873, + "p25": 109.422, + "p75": 129.67, + "min": 100.872, + "max": 183.923, + "samples": [ + 116.965, + 132.071, + 100.872, + 105.098, + 122.468, + 170.777, + 107.997, + 183.923, + 113.699, + 114.781 + ] + }, + "total_ms": { + "median": 133.883, + "p25": 126.939, + "p75": 155.913, + "min": 117.54, + "max": 210.164, + "samples": [ + 135.04, + 159.38, + 117.54, + 122.391, + 145.512, + 189.132, + 125.846, + 210.164, + 130.217, + 132.727 + ] + }, + "cpu_ms": { + "median": 134.375, + "p25": 126.231, + "p75": 154.675, + "min": 118.132, + "max": 204.242, + "samples": [ + 135.633, + 157.961, + 118.132, + 122.77, + 144.816, + 178.293, + 124.755, + 204.242, + 130.661, + 133.117 + ] + }, + "peak_rss_kib": { + "median": 83974.0, + "p25": 82744.0, + "p75": 84490.0, + "min": 82332, + "max": 84596, + "samples": [ + 83596, + 84596, + 82332, + 82424, + 84288, + 82460, + 84532, + 83660, + 84364, + 84536 + ] + } + } + } +} diff --git a/benchmarks/shared-json-five-way-20261017.json b/benchmarks/shared-json-five-way-20261017.json new file mode 100644 index 000000000..61dcb7c3d --- /dev/null +++ b/benchmarks/shared-json-five-way-20261017.json @@ -0,0 +1,453 @@ +{ + "scope": "Assets + BlockFacts + Behaviours loader only; no full startup or first frame", + "resources": "/srv/bob-data/horizon/.local/horizon-client/26.3", + "repeats": 8, + "ordering": [ + [ + "baseline", + "a01d47f2", + "cf837118", + "cd61e11b", + "current" + ], + [ + "current", + "cd61e11b", + "cf837118", + "a01d47f2", + "baseline" + ], + [ + "baseline", + "a01d47f2", + "cf837118", + "cd61e11b", + "current" + ], + [ + "current", + "cd61e11b", + "cf837118", + "a01d47f2", + "baseline" + ], + [ + "baseline", + "a01d47f2", + "cf837118", + "cd61e11b", + "current" + ], + [ + "current", + "cd61e11b", + "cf837118", + "a01d47f2", + "baseline" + ], + [ + "baseline", + "a01d47f2", + "cf837118", + "cd61e11b", + "current" + ], + [ + "current", + "cd61e11b", + "cf837118", + "a01d47f2", + "baseline" + ] + ], + "load_average_before": [ + 10.57958984375, + 8.45947265625, + 6.8134765625 + ], + "load_average_after": [ + 7.158203125, + 7.7998046875, + 6.66455078125 + ], + "executables": { + "baseline": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-e422bd13", + "mode": "baseline", + "sha256": "bf61f2e6c92e001be3c3bc93cf8072cc6af6fd1d7bcfa7273045960948ec89e7" + }, + "a01d47f2": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-a01d47f2", + "mode": "shared", + "sha256": "88be56f8dbd28d0b4abd6c672486ba758df96ba18f68da45b94db14231dd3eea" + }, + "cf837118": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-cf837118", + "mode": "deferred", + "sha256": "f1b044cd9ac2f67c644fb40bd7ecbe38128ec739a8112d57fc36f05fe9036a52" + }, + "cd61e11b": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-cd61e11b", + "mode": "deferred", + "sha256": "fb2d3725b09ee38f85b49901f7053a6fe339b980a2b2dac6930a8ded22c139e8" + }, + "current": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-new", + "mode": "deferred", + "sha256": "84eb1baae8e138f52e300b0b44f1339fca38e70db6e06126e78db776ea3e5cd0" + } + }, + "metrics": { + "baseline": { + "phase_ms": { + "median": 1277.781, + "p25": 1271.23, + "p75": 1296.157, + "min": 1223.341, + "max": 1338.745, + "samples": [ + 1265.934, + 1223.341, + 1274.931, + 1289.177, + 1338.745, + 1317.096, + 1272.995, + 1280.631 + ] + }, + "total_ms": { + "median": 1711.802, + "p25": 1695.745, + "p75": 1754.276, + "min": 1645.69, + "max": 2887.078, + "samples": [ + 2887.078, + 1645.69, + 1690.413, + 1711.459, + 1761.859, + 1751.748, + 1697.522, + 1712.144 + ] + }, + "cpu_ms": { + "median": 1769.996, + "p25": 1748.925, + "p75": 1807.254, + "min": 1705.167, + "max": 1950.463, + "samples": [ + 1950.463, + 1705.167, + 1749.023, + 1768.05, + 1804.543, + 1815.386, + 1771.942, + 1748.632 + ] + }, + "peak_rss_kib": { + "median": 820180.0, + "p25": 820030.0, + "p75": 820502.0, + "min": 819472, + "max": 820884, + "samples": [ + 819472, + 820416, + 820060, + 820096, + 820264, + 820884, + 819940, + 820760 + ] + } + }, + "a01d47f2": { + "phase_ms": { + "median": 430.783, + "p25": 427.542, + "p75": 451.763, + "min": 423.035, + "max": 550.345, + "samples": [ + 491.599, + 423.035, + 428.85, + 427.694, + 432.715, + 427.084, + 438.484, + 550.345 + ] + }, + "total_ms": { + "median": 868.457, + "p25": 863.709, + "p75": 932.066, + "min": 837.75, + "max": 997.779, + "samples": [ + 911.935, + 837.75, + 865.419, + 868.626, + 858.578, + 997.779, + 868.288, + 992.46 + ] + }, + "cpu_ms": { + "median": 897.639, + "p25": 887.661, + "p75": 944.363, + "min": 865.497, + "max": 1001.635, + "samples": [ + 925.321, + 865.497, + 899.505, + 895.774, + 876.929, + 1001.635, + 891.239, + 1001.488 + ] + }, + "peak_rss_kib": { + "median": 351906.0, + "p25": 351505.0, + "p75": 352181.0, + "min": 351176, + "max": 352440, + "samples": [ + 352008, + 352120, + 351352, + 351556, + 351804, + 351176, + 352440, + 352364 + ] + } + }, + "cf837118": { + "phase_ms": { + "median": 408.459, + "p25": 398.987, + "p75": 428.585, + "min": 387.999, + "max": 524.425, + "samples": [ + 433.521, + 387.999, + 412.195, + 397.366, + 404.724, + 399.527, + 426.939, + 524.425 + ] + }, + "total_ms": { + "median": 851.294, + "p25": 823.291, + "p75": 890.55, + "min": 801.356, + "max": 1030.737, + "samples": [ + 892.054, + 801.356, + 840.381, + 818.285, + 862.208, + 824.96, + 890.049, + 1030.737 + ] + }, + "cpu_ms": { + "median": 870.765, + "p25": 850.849, + "p75": 907.922, + "min": 825.718, + "max": 1041.996, + "samples": [ + 906.657, + 825.718, + 866.472, + 843.591, + 875.058, + 853.268, + 911.715, + 1041.996 + ] + }, + "peak_rss_kib": { + "median": 274172.0, + "p25": 273909.0, + "p75": 274438.0, + "min": 273668, + "max": 274964, + "samples": [ + 274372, + 274964, + 273668, + 273972, + 274552, + 274400, + 273840, + 273932 + ] + } + }, + "cd61e11b": { + "phase_ms": { + "median": 419.114, + "p25": 404.191, + "p75": 460.634, + "min": 388.557, + "max": 735.687, + "samples": [ + 457.971, + 418.303, + 388.557, + 405.041, + 419.925, + 401.64, + 468.624, + 735.687 + ] + }, + "total_ms": { + "median": 840.723, + "p25": 835.398, + "p75": 917.995, + "min": 811.43, + "max": 1565.471, + "samples": [ + 906.328, + 837.706, + 811.43, + 835.727, + 843.74, + 834.412, + 952.996, + 1565.471 + ] + }, + "cpu_ms": { + "median": 863.404, + "p25": 858.916, + "p75": 934.2, + "min": 833.955, + "max": 1550.132, + "samples": [ + 916.017, + 864.82, + 833.955, + 859.057, + 861.989, + 858.494, + 988.748, + 1550.132 + ] + }, + "peak_rss_kib": { + "median": 267508.0, + "p25": 267310.0, + "p75": 267890.0, + "min": 267172, + "max": 268412, + "samples": [ + 267304, + 268292, + 267312, + 267756, + 267340, + 267676, + 267172, + 268412 + ] + } + }, + "current": { + "phase_ms": { + "median": 406.779, + "p25": 397.839, + "p75": 413.957, + "min": 385.028, + "max": 552.051, + "samples": [ + 387.136, + 385.028, + 409.317, + 404.242, + 401.407, + 411.451, + 421.476, + 552.051 + ] + }, + "total_ms": { + "median": 819.787, + "p25": 814.211, + "p75": 855.69, + "min": 800.867, + "max": 1128.453, + "samples": [ + 808.685, + 800.867, + 816.053, + 817.907, + 821.667, + 843.26, + 892.982, + 1128.453 + ] + }, + "cpu_ms": { + "median": 847.078, + "p25": 836.598, + "p75": 877.524, + "min": 826.002, + "max": 1134.369, + "samples": [ + 834.665, + 826.002, + 837.243, + 842.86, + 851.296, + 864.892, + 915.419, + 1134.369 + ] + }, + "peak_rss_kib": { + "median": 267956.0, + "p25": 267612.0, + "p75": 268326.0, + "min": 267308, + "max": 268428, + "samples": [ + 268428, + 267308, + 268260, + 267516, + 267652, + 268312, + 268368, + 267644 + ] + } + } + }, + "experiment_note": "Experimental projection variant (reused sounds, Arc-keyed string pools and direct flags); reverted after mixed CPU/RSS evidence. Current in this file is not the final PR version." +} diff --git a/benchmarks/shared-json-five-way-final-20261017.json b/benchmarks/shared-json-five-way-final-20261017.json new file mode 100644 index 000000000..ce92b7b61 --- /dev/null +++ b/benchmarks/shared-json-five-way-final-20261017.json @@ -0,0 +1,582 @@ +{ + "scope": "Assets + BlockFacts + Behaviours loader only; no full startup or first frame", + "resources": "/srv/bob-data/horizon/.local/horizon-client/26.3", + "repeats": 10, + "ordering": [ + [ + "baseline", + "a01d47f2", + "cf837118", + "cd61e11b", + "current" + ], + [ + "current", + "cd61e11b", + "cf837118", + "a01d47f2", + "baseline" + ], + [ + "baseline", + "a01d47f2", + "cf837118", + "cd61e11b", + "current" + ], + [ + "current", + "cd61e11b", + "cf837118", + "a01d47f2", + "baseline" + ], + [ + "baseline", + "a01d47f2", + "cf837118", + "cd61e11b", + "current" + ], + [ + "current", + "cd61e11b", + "cf837118", + "a01d47f2", + "baseline" + ], + [ + "baseline", + "a01d47f2", + "cf837118", + "cd61e11b", + "current" + ], + [ + "current", + "cd61e11b", + "cf837118", + "a01d47f2", + "baseline" + ], + [ + "baseline", + "a01d47f2", + "cf837118", + "cd61e11b", + "current" + ], + [ + "current", + "cd61e11b", + "cf837118", + "a01d47f2", + "baseline" + ] + ], + "load_average_before": [ + 11.4921875, + 7.46875, + 6.69677734375 + ], + "load_average_after": [ + 17.763671875, + 11.39013671875, + 8.20556640625 + ], + "executables": { + "baseline": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-e422bd13", + "mode": "baseline", + "sha256": "bf61f2e6c92e001be3c3bc93cf8072cc6af6fd1d7bcfa7273045960948ec89e7" + }, + "a01d47f2": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-a01d47f2", + "mode": "shared", + "sha256": "88be56f8dbd28d0b4abd6c672486ba758df96ba18f68da45b94db14231dd3eea" + }, + "cf837118": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-cf837118", + "mode": "deferred", + "sha256": "f1b044cd9ac2f67c644fb40bd7ecbe38128ec739a8112d57fc36f05fe9036a52" + }, + "cd61e11b": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-cd61e11b", + "mode": "deferred", + "sha256": "fb2d3725b09ee38f85b49901f7053a6fe339b980a2b2dac6930a8ded22c139e8" + }, + "current": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-integrated", + "mode": "deferred", + "sha256": "a52d6a7efc7b3198ef0dd8150325f56a3fe5d0c5883fd6d14c4b0c281866ce7c" + } + }, + "metrics": { + "baseline": { + "phase_ms": { + "median": 1506.588, + "p25": 1388.314, + "p75": 2119.85, + "min": 1319.319, + "max": 3143.124, + "samples": [ + 3143.124, + 2483.307, + 2124.952, + 2104.544, + 1525.153, + 1396.75, + 1381.771, + 1488.022, + 1385.502, + 1319.319 + ] + }, + "total_ms": { + "median": 1962.122, + "p25": 1858.188, + "p75": 3152.608, + "min": 1804.713, + "max": 4136.912, + "samples": [ + 4136.912, + 3250.285, + 3134.13, + 3158.767, + 2001.229, + 1883.076, + 1849.892, + 1923.016, + 1818.34, + 1804.713 + ] + }, + "cpu_ms": { + "median": 1969.296, + "p25": 1893.348, + "p75": 2694.824, + "min": 1842.049, + "max": 3059.824, + "samples": [ + 3059.824, + 2765.392, + 2698.837, + 2682.786, + 2026.89, + 1911.703, + 1888.282, + 1908.545, + 1859.233, + 1842.049 + ] + }, + "peak_rss_kib": { + "median": 819952.0, + "p25": 819778.0, + "p75": 820164.0, + "min": 818944, + "max": 820304, + "samples": [ + 819956, + 819744, + 818944, + 818984, + 820128, + 820176, + 819948, + 820236, + 819880, + 820304 + ] + } + }, + "a01d47f2": { + "phase_ms": { + "median": 666.765, + "p25": 520.278, + "p75": 1156.022, + "min": 450.677, + "max": 1882.249, + "samples": [ + 1001.208, + 1309.911, + 1207.627, + 1882.249, + 747.233, + 544.933, + 512.06, + 450.677, + 466.596, + 586.298 + ] + }, + "total_ms": { + "median": 1141.968, + "p25": 974.723, + "p75": 2326.553, + "min": 922.496, + "max": 3158.114, + "samples": [ + 2374.699, + 2275.18, + 2343.677, + 3158.114, + 1267.594, + 1006.411, + 964.16, + 922.496, + 936.687, + 1016.342 + ] + }, + "cpu_ms": { + "median": 1106.901, + "p25": 973.629, + "p75": 1525.998, + "min": 929.573, + "max": 1568.573, + "samples": [ + 1545.278, + 1568.573, + 1468.158, + 1563.377, + 1196.236, + 1017.565, + 960.219, + 929.573, + 946.096, + 1013.861 + ] + }, + "peak_rss_kib": { + "median": 351564.0, + "p25": 351148.0, + "p75": 352106.0, + "min": 350416, + "max": 353368, + "samples": [ + 351572, + 351268, + 351108, + 350416, + 351656, + 353368, + 352256, + 351556, + 350964, + 352308 + ] + } + }, + "cf837118": { + "phase_ms": { + "median": 505.124, + "p25": 435.315, + "p75": 1103.87, + "min": 417.056, + "max": 1875.147, + "samples": [ + 1875.147, + 1129.722, + 1066.305, + 1116.391, + 461.019, + 423.38, + 417.056, + 445.353, + 549.229, + 431.969 + ] + }, + "total_ms": { + "median": 1209.375, + "p25": 895.862, + "p75": 2133.144, + "min": 872.434, + "max": 2936.234, + "samples": [ + 2936.234, + 2215.538, + 1885.964, + 2695.131, + 1378.495, + 879.351, + 897.968, + 895.16, + 1040.255, + 872.434 + ] + }, + "cpu_ms": { + "median": 1068.41, + "p25": 896.926, + "p75": 1488.578, + "min": 882.398, + "max": 1570.652, + "samples": [ + 1530.601, + 1520.851, + 1391.76, + 1570.652, + 1116.403, + 900.779, + 894.039, + 895.642, + 1020.417, + 882.398 + ] + }, + "peak_rss_kib": { + "median": 273832.0, + "p25": 273592.0, + "p75": 274131.0, + "min": 272732, + "max": 274976, + "samples": [ + 274080, + 272732, + 273560, + 273468, + 274200, + 274148, + 273728, + 273936, + 274976, + 273688 + ] + } + }, + "cd61e11b": { + "phase_ms": { + "median": 429.481, + "p25": 410.043, + "p75": 1178.091, + "min": 399.576, + "max": 1644.881, + "samples": [ + 1194.624, + 1128.491, + 1644.881, + 1428.78, + 405.544, + 434.62, + 424.341, + 414.829, + 408.447, + 399.576 + ] + }, + "total_ms": { + "median": 902.865, + "p25": 868.889, + "p75": 2443.447, + "min": 827.16, + "max": 2961.261, + "samples": [ + 2682.056, + 2199.278, + 2524.837, + 2961.261, + 884.838, + 885.282, + 848.79, + 863.573, + 920.448, + 827.16 + ] + }, + "cpu_ms": { + "median": 920.917, + "p25": 869.777, + "p75": 1475.629, + "min": 840.036, + "max": 1626.459, + "samples": [ + 1518.201, + 1496.456, + 1413.149, + 1626.459, + 893.762, + 899.049, + 861.782, + 861.417, + 942.785, + 840.036 + ] + }, + "peak_rss_kib": { + "median": 267762.0, + "p25": 267612.0, + "p75": 267966.0, + "min": 266300, + "max": 268636, + "samples": [ + 266672, + 268636, + 266300, + 267596, + 267660, + 268280, + 267968, + 267680, + 267960, + 267844 + ] + } + }, + "current": { + "phase_ms": { + "median": 460.489, + "p25": 429.004, + "p75": 986.935, + "min": 404.103, + "max": 1300.033, + "samples": [ + 992.891, + 1126.098, + 1300.033, + 969.067, + 443.604, + 408.397, + 472.429, + 424.137, + 448.549, + 404.103 + ] + }, + "total_ms": { + "median": 935.623, + "p25": 874.18, + "p75": 2282.679, + "min": 839.642, + "max": 2965.198, + "samples": [ + 2320.566, + 2169.019, + 2965.198, + 2531.591, + 924.347, + 839.642, + 946.899, + 873.617, + 875.87, + 854.328 + ] + }, + "cpu_ms": { + "median": 950.702, + "p25": 892.992, + "p75": 1540.918, + "min": 861.669, + "max": 1586.478, + "samples": [ + 1557.765, + 1503.564, + 1553.369, + 1586.478, + 931.391, + 861.669, + 970.013, + 888.14, + 907.549, + 868.73 + ] + }, + "peak_rss_kib": { + "median": 268010.0, + "p25": 267013.0, + "p75": 268385.0, + "min": 266144, + "max": 268876, + "samples": [ + 266824, + 267580, + 266516, + 266144, + 267976, + 268304, + 268044, + 268480, + 268412, + 268876 + ] + }, + "behaviour_json_ms": { + "median": 34.288, + "p25": 23.085, + "p75": 37.474, + "min": 20.137, + "max": 70.397, + "samples": [ + 37.07, + 70.397, + 37.609, + 38.225, + 34.568, + 21.094, + 23.469, + 22.957, + 34.008, + 20.137 + ] + }, + "facts_ms": { + "median": 272.839, + "p25": 256.553, + "p75": 618.472, + "min": 248.146, + "max": 780.388, + "samples": [ + 625.908, + 693.735, + 780.388, + 596.165, + 272.718, + 249.954, + 272.959, + 264.913, + 253.767, + 248.146 + ] + }, + "behaviours_ms": { + "median": 162.633, + "p25": 133.345, + "p75": 326.117, + "min": 132.828, + "max": 476.9, + "samples": [ + 325.198, + 356.28, + 476.9, + 326.424, + 132.828, + 133.946, + 167.929, + 133.144, + 157.337, + 132.934 + ] + }, + "post_rss_kib": { + "median": 268408.0, + "p25": 267369.0, + "p75": 268861.0, + "min": 267052.0, + "max": 269072.0, + "samples": [ + 267084.0, + 268056.0, + 267052.0, + 267140.0, + 268184.0, + 268632.0, + 268660.0, + 269072.0, + 268928.0, + 268960.0 + ] + } + } + } +} diff --git a/benchmarks/shared-json-historical-20261017.json b/benchmarks/shared-json-historical-20261017.json new file mode 100644 index 000000000..2e0e7538f --- /dev/null +++ b/benchmarks/shared-json-historical-20261017.json @@ -0,0 +1,188 @@ +{ + "scope": "Assets + block facts + behaviours loader only; excludes full startup", + "resources": ".local/horizon-client/26.3", + "repeats": 5, + "comparison": "historical cf837118 release binary", + "reference_binary": "target/release/examples/shared_json_startup_profile-cf837118", + "metrics": { + "baseline": { + "phase_ms": { + "median": 1462.003, + "samples": [ + 1639.999, + 1506.864, + 1429.844, + 1462.003, + 1346.061 + ] + }, + "total_ms": { + "median": 1922.795, + "samples": [ + 3383.516, + 1990.554, + 1912.354, + 1922.795, + 1777.912 + ] + }, + "cpu_ms": { + "median": 1961.459, + "samples": [ + 2419.086, + 2021.457, + 1951.587, + 1961.459, + 1839.984 + ] + }, + "peak_rss_kib": { + "median": 820912, + "samples": [ + 819956, + 821052, + 820912, + 821792, + 820424 + ] + } + }, + "pr607": { + "phase_ms": { + "median": 486.715, + "samples": [ + 460.738, + 442.013, + 623.053, + 486.715, + 550.652 + ] + }, + "total_ms": { + "median": 948.089, + "samples": [ + 923.057, + 935.599, + 1109.64, + 948.089, + 1052.546 + ] + }, + "cpu_ms": { + "median": 968.424, + "samples": [ + 928.489, + 946.932, + 1128.431, + 968.424, + 1079.642 + ] + }, + "peak_rss_kib": { + "median": 351796, + "samples": [ + 351796, + 351844, + 351536, + 351532, + 351988 + ] + } + }, + "cf837118": { + "phase_ms": { + "median": 474.268, + "samples": [ + 443.122, + 474.268, + 520.497, + 433.525, + 532.058 + ] + }, + "total_ms": { + "median": 945.87, + "samples": [ + 934.722, + 945.87, + 1006.539, + 888.201, + 1032.6 + ] + }, + "cpu_ms": { + "median": 953.668, + "samples": [ + 941.957, + 953.668, + 1029.122, + 903.574, + 1065.025 + ] + }, + "peak_rss_kib": { + "median": 274476, + "samples": [ + 273448, + 274844, + 274476, + 274556, + 274252 + ] + } + }, + "current": { + "phase_ms": { + "median": 445.924, + "samples": [ + 472.165, + 427.797, + 419.288, + 445.924, + 524.211 + ] + }, + "total_ms": { + "median": 999.669, + "samples": [ + 999.669, + 892.616, + 1051.427, + 940.595, + 1112.158 + ] + }, + "cpu_ms": { + "median": 1001.24, + "samples": [ + 1001.24, + 887.874, + 1051.732, + 951.495, + 1132.208 + ] + }, + "peak_rss_kib": { + "median": 267604, + "samples": [ + 267716, + 267920, + 267448, + 267604, + 267344 + ] + } + } + }, + "builds": { + "current": "release example built at cf837118 + current uncommitted delta in PR #607 worktree", + "historical": "release example built at exact cf837118 commit, with same Cargo release profile and shared dependency target" + }, + "mode_commits": { + "baseline": "independent loader algorithm at e422bd13, executed in current binary", + "pr607": "shared early construction algorithm at a01d47f2, executed in current binary", + "cf837118": "exact historical binary at cf837118, deferred mode", + "current": "current PR worktree, deferred mode with interned strings" + }, + "limitations": "Loader-only (Assets + BlockFacts + Behaviours), no full client startup or first-frame timing. Same release profile but different compilation contexts for historical binary; hardware activity and cache warmth vary. CPU and elapsed differences between cf837118 and current are mixed and may be noise. Peak RSS is whole-process Linux ru_maxrss." +} diff --git a/benchmarks/shared-json-startup-20261017.json b/benchmarks/shared-json-startup-20261017.json new file mode 100644 index 000000000..92f557b33 --- /dev/null +++ b/benchmarks/shared-json-startup-20261017.json @@ -0,0 +1,93 @@ +{ + "scope": "Assets + block facts + behaviours loader only; excludes full startup", + "resources": ".local/horizon-client/26.3", + "repeats": 5, + "metrics": { + "baseline": { + "phase_ms": { + "median": 4730.402, + "samples": [ + 3258.541, + 6539.764, + 4773.735, + 3980.032, + 4730.402 + ] + }, + "total_ms": { + "median": 6325.026, + "samples": [ + 6596.141, + 7627.893, + 6296.443, + 5435.408, + 6325.026 + ] + }, + "cpu_ms": { + "median": 3199.722, + "samples": [ + 3322.801, + 3199.722, + 3227.438, + 3042.687, + 3144.658 + ] + }, + "peak_rss_kib": { + "median": 820000, + "samples": [ + 818540, + 820400, + 819352, + 820000, + 820128 + ] + } + }, + "shared": { + "phase_ms": { + "median": 1180.588, + "samples": [ + 869.228, + 842.213, + 1180.588, + 1560.087, + 1728.575 + ] + }, + "total_ms": { + "median": 2260.709, + "samples": [ + 1632.489, + 1553.753, + 2260.709, + 2879.728, + 3388.639 + ] + }, + "cpu_ms": { + "median": 1603.393, + "samples": [ + 1568.288, + 1432.106, + 1603.393, + 1604.423, + 1619.02 + ] + }, + "peak_rss_kib": { + "median": 351728, + "samples": [ + 353256, + 353664, + 351728, + 350724, + 351668 + ] + } + } + }, + "build": "cargo build --release -p horizon-client --example shared_json_startup_profile", + "limitations": "Loader-only wall-clock timings under concurrent machine load; not full startup or time to first frame. RSS includes Assets::load." +} diff --git a/benchmarks/shared-json-startup-followup-20261017.json b/benchmarks/shared-json-startup-followup-20261017.json new file mode 100644 index 000000000..c828ac7b4 --- /dev/null +++ b/benchmarks/shared-json-startup-followup-20261017.json @@ -0,0 +1,227 @@ +{ + "scope": "Assets + block facts + behaviours loader only; excludes full startup", + "resources": ".local/horizon-client/26.3", + "repeats": 5, + "metrics": { + "baseline": { + "phase_ms": { + "median": 1996.921, + "samples": [ + 2213.335, + 1453.207, + 1637.901, + 1996.921, + 2010.335 + ], + "range": [ + 1453.207, + 2213.335 + ] + }, + "total_ms": { + "median": 4728.136, + "samples": [ + 5628.975, + 2147.329, + 2162.696, + 4728.136, + 6404.524 + ], + "range": [ + 2147.329, + 6404.524 + ] + }, + "cpu_ms": { + "median": 2514.776, + "samples": [ + 2919.908, + 2088.239, + 2212.892, + 2716.104, + 2514.776 + ], + "range": [ + 2088.239, + 2919.908 + ] + }, + "peak_rss_kib": { + "median": 819824, + "samples": [ + 819824, + 820872, + 820744, + 818980, + 818816 + ] + } + }, + "pr607": { + "phase_ms": { + "median": 586.707, + "samples": [ + 464.424, + 739.67, + 586.707, + 1373.307, + 509.266 + ], + "range": [ + 464.424, + 1373.307 + ] + }, + "total_ms": { + "median": 1128.6, + "samples": [ + 954.73, + 1764.614, + 1128.6, + 4312.528, + 1030.735 + ], + "range": [ + 954.73, + 4312.528 + ] + }, + "cpu_ms": { + "median": 1145.826, + "samples": [ + 981.058, + 1465.79, + 1145.826, + 1736.807, + 1056.992 + ], + "range": [ + 981.058, + 1736.807 + ] + }, + "peak_rss_kib": { + "median": 351900, + "samples": [ + 352164, + 351816, + 351900, + 352348, + 350492 + ] + } + }, + "shared": { + "phase_ms": { + "median": 560.117, + "samples": [ + 522.284, + 1255.75, + 560.117, + 2151.064, + 479.329 + ], + "range": [ + 479.329, + 2151.064 + ] + }, + "total_ms": { + "median": 1101.305, + "samples": [ + 1011.715, + 2565.449, + 1101.305, + 2960.186, + 1006.817 + ], + "range": [ + 1006.817, + 2960.186 + ] + }, + "cpu_ms": { + "median": 1128.214, + "samples": [ + 1035.19, + 1565.383, + 1128.214, + 1494.36, + 1031.198 + ], + "range": [ + 1031.198, + 1565.383 + ] + }, + "peak_rss_kib": { + "median": 351532, + "samples": [ + 351624, + 350540, + 351532, + 351716, + 350076 + ] + } + }, + "deferred": { + "phase_ms": { + "median": 564.046, + "samples": [ + 433.35, + 665.149, + 587.456, + 564.046, + 497.422 + ], + "range": [ + 433.35, + 665.149 + ] + }, + "total_ms": { + "median": 1143.129, + "samples": [ + 885.053, + 1143.129, + 1195.869, + 1074.27, + 1162.103 + ], + "range": [ + 885.053, + 1195.869 + ] + }, + "cpu_ms": { + "median": 1114.261, + "samples": [ + 910.946, + 1128.96, + 1194.638, + 1114.261, + 1073.823 + ], + "range": [ + 910.946, + 1194.638 + ] + }, + "peak_rss_kib": { + "median": 273776, + "samples": [ + 274320, + 273860, + 272548, + 273776, + 272520 + ] + } + } + }, + "baseline_commit": "e422bd13", + "pr607_commit": "a01d47f2", + "measurement": "same optimized binary, isolated processes in alternating forward/reverse four-mode runs", + "limitations": "Includes Assets::load, BlockFacts, Behaviours; excludes complete client startup, pack/mod root resolution, graphics and first frame. Different modes emulate the original independent, PR #607 at a01d47f2, paired and deferred startup sequences in the same release build. Machine was not idle. Elapsed times show high variance; no statistically established gain between PR, paired and deferred modes." +} diff --git a/benchmarks/shared-json-variant-isolation-20261017.json b/benchmarks/shared-json-variant-isolation-20261017.json new file mode 100644 index 000000000..e399c7ba1 --- /dev/null +++ b/benchmarks/shared-json-variant-isolation-20261017.json @@ -0,0 +1,453 @@ +{ + "scope": "Assets + BlockFacts + Behaviours loader only; no full startup or first frame", + "resources": "/srv/bob-data/horizon/.local/horizon-client/26.3", + "repeats": 8, + "ordering": [ + [ + "cf837118", + "cd61e11b", + "arc-key", + "reused-sounds", + "current" + ], + [ + "current", + "reused-sounds", + "arc-key", + "cd61e11b", + "cf837118" + ], + [ + "cf837118", + "cd61e11b", + "arc-key", + "reused-sounds", + "current" + ], + [ + "current", + "reused-sounds", + "arc-key", + "cd61e11b", + "cf837118" + ], + [ + "cf837118", + "cd61e11b", + "arc-key", + "reused-sounds", + "current" + ], + [ + "current", + "reused-sounds", + "arc-key", + "cd61e11b", + "cf837118" + ], + [ + "cf837118", + "cd61e11b", + "arc-key", + "reused-sounds", + "current" + ], + [ + "current", + "reused-sounds", + "arc-key", + "cd61e11b", + "cf837118" + ] + ], + "load_average_before": [ + 10.9873046875, + 8.37646484375, + 6.91015625 + ], + "load_average_after": [ + 8.6962890625, + 8.1591796875, + 6.90087890625 + ], + "executables": { + "cf837118": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-cf837118", + "mode": "deferred", + "sha256": "f1b044cd9ac2f67c644fb40bd7ecbe38128ec739a8112d57fc36f05fe9036a52" + }, + "cd61e11b": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-cd61e11b", + "mode": "deferred", + "sha256": "fb2d3725b09ee38f85b49901f7053a6fe339b980a2b2dac6930a8ded22c139e8" + }, + "arc-key": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-arcpool", + "mode": "deferred", + "sha256": "8cbb53d01afedf5c7a5da0e36c9f8c3569f34def9bc51488fe8699e7f615a131" + }, + "reused-sounds": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-reusesounds", + "mode": "deferred", + "sha256": "f45794bfbdbb3f9b5d34c375d397191ac67984b3ae91268aa3fdd02f2c1b7b98" + }, + "current": { + "path": "/srv/bob-data/horizon/.worktrees/shared-block-json-20261017/target/release/examples/shared_json_startup_profile-new", + "mode": "deferred", + "sha256": "84eb1baae8e138f52e300b0b44f1339fca38e70db6e06126e78db776ea3e5cd0" + } + }, + "metrics": { + "cf837118": { + "phase_ms": { + "median": 424.082, + "p25": 417.508, + "p75": 430.923, + "min": 395.439, + "max": 948.609, + "samples": [ + 948.609, + 425.085, + 425.571, + 417.945, + 395.439, + 416.197, + 423.078, + 446.98 + ] + }, + "total_ms": { + "median": 853.026, + "p25": 839.421, + "p75": 867.731, + "min": 813.144, + "max": 1906.081, + "samples": [ + 1906.081, + 861.641, + 864.233, + 844.411, + 813.144, + 830.783, + 842.3, + 878.226 + ] + }, + "cpu_ms": { + "median": 876.143, + "p25": 862.934, + "p75": 891.4, + "min": 837.769, + "max": 1517.372, + "samples": [ + 1517.372, + 885.13, + 887.888, + 865.404, + 837.769, + 855.526, + 867.157, + 901.937 + ] + }, + "peak_rss_kib": { + "median": 273904.0, + "p25": 273717.0, + "p75": 274142.0, + "min": 273648, + "max": 274836, + "samples": [ + 273648, + 273936, + 273872, + 274836, + 274064, + 274376, + 273740, + 273648 + ] + } + }, + "cd61e11b": { + "phase_ms": { + "median": 422.356, + "p25": 406.294, + "p75": 425.846, + "min": 394.111, + "max": 472.536, + "samples": [ + 425.832, + 420.666, + 472.536, + 425.886, + 400.588, + 394.111, + 424.047, + 408.196 + ] + }, + "total_ms": { + "median": 852.475, + "p25": 828.474, + "p75": 876.413, + "min": 817.3, + "max": 951.587, + "samples": [ + 951.587, + 865.442, + 899.564, + 868.696, + 823.74, + 817.3, + 839.508, + 830.052 + ] + }, + "cpu_ms": { + "median": 875.04, + "p25": 850.012, + "p75": 900.57, + "min": 837.672, + "max": 938.285, + "samples": [ + 938.285, + 888.533, + 926.846, + 891.812, + 845.956, + 837.672, + 861.548, + 851.364 + ] + }, + "peak_rss_kib": { + "median": 268086.0, + "p25": 267719.0, + "p75": 268486.0, + "min": 267444, + "max": 268920, + "samples": [ + 267776, + 268660, + 267752, + 268920, + 268428, + 268396, + 267444, + 267620 + ] + } + }, + "arc-key": { + "phase_ms": { + "median": 421.422, + "p25": 401.781, + "p75": 451.774, + "min": 394.041, + "max": 472.337, + "samples": [ + 446.155, + 472.337, + 468.632, + 420.636, + 400.91, + 394.041, + 422.207, + 402.072 + ] + }, + "total_ms": { + "median": 866.601, + "p25": 822.563, + "p75": 918.038, + "min": 817.092, + "max": 1001.287, + "samples": [ + 1001.287, + 918.457, + 917.898, + 892.666, + 817.092, + 824.225, + 840.536, + 817.576 + ] + }, + "cpu_ms": { + "median": 887.84, + "p25": 844.533, + "p75": 937.331, + "min": 838.687, + "max": 991.212, + "samples": [ + 991.212, + 949.048, + 933.425, + 911.921, + 838.687, + 845.021, + 863.759, + 843.069 + ] + }, + "peak_rss_kib": { + "median": 267728.0, + "p25": 267598.0, + "p75": 268039.0, + "min": 267452, + "max": 268636, + "samples": [ + 268264, + 267616, + 267840, + 267964, + 268636, + 267452, + 267580, + 267604 + ] + } + }, + "reused-sounds": { + "phase_ms": { + "median": 421.683, + "p25": 412.913, + "p75": 439.098, + "min": 395.338, + "max": 487.446, + "samples": [ + 487.446, + 434.111, + 402.815, + 416.279, + 424.524, + 454.058, + 395.338, + 418.842 + ] + }, + "total_ms": { + "median": 879.846, + "p25": 845.021, + "p75": 901.166, + "min": 823.721, + "max": 1013.539, + "samples": [ + 1013.539, + 892.033, + 928.565, + 884.284, + 847.853, + 875.407, + 823.721, + 836.527 + ] + }, + "cpu_ms": { + "median": 894.546, + "p25": 871.499, + "p75": 921.844, + "min": 844.891, + "max": 1028.688, + "samples": [ + 1028.688, + 913.48, + 946.935, + 903.785, + 868.684, + 885.308, + 844.891, + 872.438 + ] + }, + "peak_rss_kib": { + "median": 267960.0, + "p25": 267678.0, + "p75": 268133.0, + "min": 267212, + "max": 268404, + "samples": [ + 267212, + 267888, + 268404, + 267692, + 268096, + 267636, + 268244, + 268032 + ] + } + }, + "current": { + "phase_ms": { + "median": 411.403, + "p25": 406.814, + "p75": 452.869, + "min": 391.768, + "max": 532.402, + "samples": [ + 532.402, + 442.563, + 408.857, + 410.202, + 483.788, + 391.768, + 400.683, + 412.604 + ] + }, + "total_ms": { + "median": 905.017, + "p25": 851.488, + "p75": 937.934, + "min": 818.206, + "max": 1075.445, + "samples": [ + 1075.445, + 878.155, + 837.627, + 955.655, + 932.027, + 818.206, + 856.108, + 931.88 + ] + }, + "cpu_ms": { + "median": 922.9, + "p25": 874.849, + "p75": 956.282, + "min": 839.639, + "max": 1067.693, + "samples": [ + 1067.693, + 900.18, + 862.137, + 970.356, + 951.591, + 839.639, + 879.086, + 945.62 + ] + }, + "peak_rss_kib": { + "median": 268354.0, + "p25": 267889.0, + "p75": 268492.0, + "min": 267056, + "max": 268820, + "samples": [ + 268008, + 268384, + 268564, + 268820, + 267056, + 267532, + 268324, + 268468 + ] + } + } + }, + "experiment_note": "Exploratory variants (Arc-key pool, reused sounds, combined proposal) alongside cd61e11b; none gave a robust consistent improvement and all were reverted." +} diff --git a/crates/horizon-client/examples/gameplay_decode_profile.rs b/crates/horizon-client/examples/gameplay_decode_profile.rs new file mode 100644 index 000000000..60260452f --- /dev/null +++ b/crates/horizon-client/examples/gameplay_decode_profile.rs @@ -0,0 +1,33 @@ +//! Profile the two mandatory passes over gameplay-facts.json independently. +//! Build with `cargo build --release -p horizon-client --example gameplay_decode_profile`. +//! Each invocation runs one phase in a separate process for CPU/RSS measurements. +#[allow(dead_code)] +#[path = "../src/blocks/decode.rs"] +mod decode; + +use std::{hint::black_box, path::Path, time::Instant}; + +// The included private decoder expects the parent crate Result alias. +type Result = std::result::Result>; + +fn main() -> Result<()> { + let mut args = std::env::args().skip(1); + let root = args.next().ok_or("expected resource directory")?; + let mode = args.next().ok_or("expected validate or typed")?; + if mode != "validate" && mode != "typed" { + return Err("expected validate or typed".into()); + } + let total = Instant::now(); + let bytes = std::fs::read(Path::new(&root).join("gameplay-facts.json"))?; + let started = Instant::now(); + if mode == "validate" { + let parsed: decode::Validate = serde_json::from_slice(&bytes)?; + black_box(parsed); + } else { + let parsed: decode::Gameplay<'_> = serde_json::from_slice(&bytes)?; + black_box(parsed); + } + println!("phase_ms={:.3}", started.elapsed().as_secs_f64() * 1000.0); + println!("total_ms={:.3}", total.elapsed().as_secs_f64() * 1000.0); + Ok(()) +} diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs index 63ea9f136..16fc36b95 100644 --- a/crates/horizon-client/examples/lan_flat.rs +++ b/crates/horizon-client/examples/lan_flat.rs @@ -88,6 +88,7 @@ fn main() -> Result<(), Box> { seed: 0, max_players: 8, dedicated: false, + integrated: false, }, ); let mut next_entity = 100u32; diff --git a/crates/horizon-client/examples/mod_port_probe.rs b/crates/horizon-client/examples/mod_port_probe.rs new file mode 100644 index 000000000..c78285bbb --- /dev/null +++ b/crates/horizon-client/examples/mod_port_probe.rs @@ -0,0 +1,271 @@ +//! The Horizon side of a mod port's harness (tools/mod_port_harness.py, +//! docs/modpacks.md): builds the content root for carried-over mods and +//! writes what Horizon makes of every block state, drop, recipe and tag the +//! NeoForge oracle exported. +//! +//! cargo run -p horizon-client --example mod_port_probe -- PREPARED WORK OUT.json [MOD...] +//! +//! WORK is a `horizon-port-pack` work folder: `oracle/facts.json` and +//! `mods//carry/`. The root is built in `WORK/horizon-root`. +use horizon_client::{ + Result, + assets::Assets, + blocks::BlockFacts, + crafting::{Recipe, Recipes}, + items::{ItemStack, Items}, + mod_content::{self, ContentMod}, + stations::StationRecipes, +}; +use horizon_core::{geometry::Axis, random::LegacyRandom}; +use horizon_world::chunk::BlockState; +use serde_json::{Map, Value, json}; +use std::{collections::BTreeMap, fs, path::Path}; + +fn boxes(list: impl IntoIterator) -> Value { + let mut v: Vec<[f64; 6]> = list.into_iter().collect(); + v.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)); + json!(v) +} + +fn sound(s: &horizon_client::blocks::Sounds) -> Value { + json!({"volume": s.volume, "pitch": s.pitch, "break": &*s.break_sound, "step": &*s.step, + "place": &*s.place, "hit": &*s.hit, "fall": &*s.fall}) +} + +fn tool(name: &str) -> Option { + match name { + "hand" => None, + "silk_touch_pickaxe" => { + let mut pick = ItemStack::new("minecraft:diamond_pickaxe", 1); + pick.enchant("minecraft:silk_touch", 1); + Some(pick) + } + other => Some(ItemStack::new(&format!("minecraft:{other}"), 1)), + } +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let [base, work, out, wanted @ ..] = args.as_slice() else { + return Err("usage: mod_port_probe PREPARED WORK OUT.json [MOD...]".into()); + }; + let (base, work) = (Path::new(base), Path::new(work)); + let oracle: Value = serde_json::from_slice(&fs::read(work.join("oracle/facts.json"))?)?; + let mut mods = Vec::new(); + for entry in fs::read_dir(work.join("mods"))?.flatten() { + let id = entry.file_name().to_string_lossy().into_owned(); + let dir = entry.path().join("carry"); + if !(wanted.is_empty() || wanted.contains(&id)) || !dir.is_dir() { + continue; + } + let package = horizon_mods::Package::read(&dir)?; + let content = horizon_mods::Content::read(&dir, &package.manifest)?; + mods.push(ContentMod { + id: package.manifest.id.clone(), + content, + }); + } + mods.sort_by(|a, b| a.id.cmp(&b.id)); + let root = work.join("horizon-root"); + let began = std::time::Instant::now(); + let step = |what: &str| { + let what = what.to_owned(); + move |e: Box| format!("{what}: {e}") + }; + mod_content::build(base, &mods, &root).map_err(step("content root"))?; + let built = began.elapsed().as_secs_f64(); + let assets = Assets::load(&root).map_err(step("assets"))?; + let registry = assets.registry; + let facts = BlockFacts::load(&root, registry).map_err(step("block facts"))?; + let items = Items::load(&root, registry, &facts).map_err(step("items"))?; + let recipes = Recipes::load(&root, &items).map_err(step("recipes"))?; + let stations = StationRecipes::load(&root, &items); + let collisions = + horizon_client::collisions::load(&root, registry).map_err(step("collisions"))?; + let loaded = began.elapsed().as_secs_f64() - built; + let ours = |id: &str| { + id.split_once(':') + .is_some_and(|(ns, _)| mods.iter().any(|m| m.id == ns)) + }; + let tools: Vec = serde_json::from_value(oracle["tools"].clone())?; + + let mut blocks = Map::new(); + for (name, block) in oracle["blocks"].as_object().ok_or("oracle: no blocks")? { + if !ours(name) { + continue; + } + let Some(default) = registry.default_state(name) else { + blocks.insert(name.clone(), Value::Null); + continue; + }; + let mut states = Map::new(); + for (key, o) in block["states"].as_object().into_iter().flatten() { + let properties: BTreeMap = key + .split(',') + .filter(|p| !p.is_empty()) + .filter_map(|p| p.split_once('=')) + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(); + let descriptor = BlockState { + name: name.clone(), + properties, + }; + let Some(id) = registry.id(&descriptor) else { + states.insert(key.clone(), Value::Null); + continue; + }; + let f = facts.get(id); + let collision = collisions + .cached_shapes() + .cached_shape(id) + .ok() + .flatten() + .map(|s| { + boxes(s.boxes().iter().map(|b| { + [ + b.min(Axis::X), + b.min(Axis::Y), + b.min(Axis::Z), + b.max(Axis::X), + b.max(Axis::Y), + b.max(Axis::Z), + ] + })) + }); + let mut row = json!({ + "hardness": f.hardness, + "explosion_resistance": f.explosion_resistance, + "emission": f.emission, + "requires_tool": f.requires_tool, + "friction": f.friction, + "map_color_id": f.map_color, + "can_occlude": f.can_occlude, + "sound": sound(&f.sounds), + "outline": boxes(f.outline.iter().copied()), + "collision": collision, + "classes": f.classes.iter().map(|c| &**c).collect::>(), + }); + if o.get("drops").is_some() { + let mut drops = Map::new(); + for t in &tools { + let mut random = LegacyRandom::new(0); + let held = tool(t); + let mut counts: BTreeMap = BTreeMap::new(); + for s in items.block_drops(registry, id, held.as_ref(), &mut random) { + *counts.entry(s.item.to_string()).or_default() += s.count; + } + drops.insert(t.clone(), json!(counts)); + } + row["drops"] = Value::Object(drops); + } + states.insert(key.clone(), row); + } + let item = facts.get(default).item.to_string(); + blocks.insert( + name.clone(), + json!({"states": states, "item": item, "item_known": items.items.contains_key(&*item)}), + ); + } + + // Vanilla's sounds, by block: the harness maps the oracle's version's + // sound events to this one's through them. + let mut vanilla_sounds = Map::new(); + for name in oracle["blocks"] + .as_object() + .into_iter() + .flatten() + .map(|(k, _)| k) + { + if let Some(id) = name + .starts_with("minecraft:") + .then(|| registry.default_state(name)) + .flatten() + { + vanilla_sounds.insert(name.clone(), sound(&facts.get(id).sounds)); + } + } + + let mut item_rows = Map::new(); + for name in oracle["items"] + .as_object() + .into_iter() + .flatten() + .map(|(k, _)| k) + { + item_rows.insert( + name.clone(), + match items.items.get(name.as_str()) { + Some(i) => json!({"max_stack_size": i.max_stack, "block": i.block.map(|b| b.0)}), + None => Value::Null, + }, + ); + } + + let sorted = |list: &[String]| { + let mut v = list.to_vec(); + v.sort(); + v.dedup(); + v + }; + let mut recipe_rows = Map::new(); + for (name, recipe) in &recipes.crafting { + if !ours(name) { + continue; + } + let row = match recipe { + Recipe::Shaped { cells, result, .. } => json!({ + "result": result.item.as_deref(), "count": result.count, + "ingredients": cells.iter().flatten().map(|i| sorted(&i.1)).collect::>()}), + Recipe::Shapeless { + ingredients, + result, + } => json!({ + "result": result.item.as_deref(), "count": result.count, + "ingredients": ingredients.iter().map(|i| sorted(&i.1)).collect::>()}), + Recipe::Special(_) => json!({"special": true}), + }; + recipe_rows.insert(name.clone(), row); + } + for c in recipes.cooking.iter().filter(|c| ours(&c.id)) { + recipe_rows.insert( + c.id.clone(), + json!({"result": &*c.result.item, "count": c.result.count, + "ingredients": [sorted(&c.ingredient.1)]}), + ); + } + for s in stations.stonecutting.iter().filter(|s| ours(&s.id)) { + recipe_rows.insert( + s.id.clone(), + json!({"result": &*s.result.item, "count": s.result.count, + "ingredients": [sorted(&s.input.1)]}), + ); + } + + let mut block_tags = Map::new(); + for (tag, members) in &items.block_tags { + let mut ids: Vec<&String> = members.iter().filter(|m| ours(m)).collect(); + if !ids.is_empty() { + ids.sort(); + block_tags.insert(tag.clone(), json!(ids)); + } + } + + let report = json!({ + "states": registry.len(), + "build_seconds": built, + "load_seconds": loaded, + "blocks": blocks, + "items": item_rows, + "recipes": recipe_rows, + "block_tags": block_tags, + "vanilla_sounds": vanilla_sounds, + }); + fs::write(out, serde_json::to_vec(&report)?)?; + println!( + "{out}: {} blocks, {} items, {} recipes; root built in {built:.2} s, loaded in {loaded:.2} s", + blocks.len(), + item_rows.len(), + recipe_rows.len() + ); + Ok(()) +} diff --git a/crates/horizon-client/examples/shared_json_startup_profile.rs b/crates/horizon-client/examples/shared_json_startup_profile.rs new file mode 100644 index 000000000..7b7d896b2 --- /dev/null +++ b/crates/horizon-client/examples/shared_json_startup_profile.rs @@ -0,0 +1,74 @@ +//! Profile the fact and behaviour table phase of client startup. +//! Run each mode in a separate process to capture CPU usage and peak RSS. +//! The deferred mode evaluates both phases contiguously for fair loader comparison; +//! actual client startup performs other initialization between these phases. +use horizon_client::{assets::Assets, blocks::BlockFacts}; +use horizon_world::level::Behaviours; +use std::{path::Path, time::Instant}; + +fn resident_kib() -> Option { + let status = std::fs::read_to_string("/proc/self/status").ok()?; + let line = status.lines().find(|line| line.starts_with("VmRSS:"))?; + line.split_whitespace().nth(1)?.parse().ok() +} + +fn main() -> Result<(), Box> { + let mut args = std::env::args().skip(1); + let root = args.next().ok_or("expected resource directory")?; + let mode = args + .next() + .ok_or("expected baseline, pr607, shared, deferred or deferred-held")?; + if !["baseline", "pr607", "shared", "deferred", "deferred-held"].contains(&mode.as_str()) { + return Err("expected baseline, pr607, shared, deferred or deferred-held".into()); + } + let root = Path::new(&root); + let total = Instant::now(); + let assets = Assets::load(root)?; + let started = Instant::now(); + let mut retained_inputs = None; + let mut subphases = None; + let (facts, behaviours) = if mode == "baseline" { + ( + BlockFacts::load(root, assets.registry)?, + Behaviours::load(assets.registry, root)?, + ) + } else if mode == "pr607" { + // Original PR #607 sequence at a01d47f2, retained as a same-build comparator. + let json: serde_json::Value = serde_json::from_reader(std::io::BufReader::new( + std::fs::File::open(root.join("block-behaviours.json"))?, + ))?; + BlockFacts::load_with_behaviours(root, assets.registry, &json)? + } else if mode == "shared" { + BlockFacts::load_pair(root, assets.registry)? + } else { + let parse_started = Instant::now(); + let json: serde_json::Value = serde_json::from_reader(std::io::BufReader::new( + std::fs::File::open(root.join("block-behaviours.json"))?, + ))?; + let parse_ms = parse_started.elapsed().as_secs_f64() * 1000.0; + let facts_started = Instant::now(); + let (facts, gameplay) = BlockFacts::load_with_projection(root, assets.registry, &json)?; + let facts_ms = facts_started.elapsed().as_secs_f64() * 1000.0; + let behaviours_started = Instant::now(); + let behaviours = Behaviours::load_with_gameplay(assets.registry, root, &json, &gameplay)?; + let behaviours_ms = behaviours_started.elapsed().as_secs_f64() * 1000.0; + subphases = Some((parse_ms, facts_ms, behaviours_ms)); + if mode == "deferred-held" { + retained_inputs = Some((json, gameplay)); + } + (facts, behaviours) + }; + println!("phase_ms={:.3}", started.elapsed().as_secs_f64() * 1000.0); + println!("total_ms={:.3}", total.elapsed().as_secs_f64() * 1000.0); + println!("states={}", facts.states.len()); + if let Some((parse, facts, behaviours)) = subphases { + println!("behaviour_json_ms={parse:.3}"); + println!("facts_ms={facts:.3}"); + println!("behaviours_ms={behaviours:.3}"); + } + if let Some(rss) = resident_kib() { + println!("post_rss_kib={rss}"); + } + std::hint::black_box((facts, behaviours, retained_inputs)); + Ok(()) +} diff --git a/crates/horizon-client/examples/translucency_fixture.rs b/crates/horizon-client/examples/translucency_fixture.rs new file mode 100644 index 000000000..11083d6b2 --- /dev/null +++ b/crates/horizon-client/examples/translucency_fixture.rs @@ -0,0 +1,47 @@ +//! Transport for the vanilla quad sorting / viewpoint parity gate. +use horizon_client::gfx::translucency::{SortState, Sorter, quad_center}; +use serde::Deserialize; +use serde_json::json; +use std::{ + fs, + io::{BufWriter, Write}, +}; + +#[derive(Deserialize)] +struct Case { + origin: [i32; 3], + quads: Vec<[[f32; 3]; 4]>, + cameras: Vec<[f64; 3]>, +} + +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().skip(1).collect(); + let [input, output] = args.as_slice() else { + return Err("usage: translucency_fixture INPUT OUTPUT".into()); + }; + let mut out = BufWriter::new(fs::File::create(output)?); + for line in fs::read_to_string(input)?.lines() { + let case: Case = serde_json::from_str(line)?; + let centers: Vec<_> = case.quads.iter().map(|q| quad_center(q[0], q[2])).collect(); + let mut state = SortState::new(centers.clone()); + let mut sorter = Sorter::default(); + let mut cache_sorter = Sorter::default(); + let frames: Vec<_> = case + .cameras + .iter() + .map(|&camera| { + let update = state + .update(camera, case.origin, &mut cache_sorter) + .is_some(); + let local = std::array::from_fn(|i| (camera[i] - f64::from(case.origin[i])) as f32); + json!({"indices": sorter.sort(¢ers, local), "update": update}) + }) + .collect(); + let bits: Vec<_> = centers + .iter() + .map(|c| c.map(|f| f.to_bits() as i32)) + .collect(); + writeln!(out, "{}", json!({"centers": bits, "frames": frames}))?; + } + Ok(()) +} diff --git a/crates/horizon-client/examples/world_options_fixture.rs b/crates/horizon-client/examples/world_options_fixture.rs new file mode 100644 index 000000000..5bbf9f1c7 --- /dev/null +++ b/crates/horizon-client/examples/world_options_fixture.rs @@ -0,0 +1,40 @@ +//! Packet payload oracle companion for tools/test_world_options_parity.py. +use horizon_protocol::{buf::Reader, packets::play::*}; +use std::{error::Error, fmt::Write}; + +fn main() -> Result<(), Box> { + let args: Vec = std::env::args().collect(); + let mut output = String::new(); + for line in std::fs::read_to_string(&args[1])?.lines() { + let fields: Vec<&str> = line.split('\t').collect(); + let entries = if fields.len() == 3 { + vec![GameRuleEntry { + name: format!("minecraft:{}", fields[1]), + value: fields[2].into(), + }] + } else { + vec![] + }; + let bytes = match fields[0] { + "difficulty" => Serverbound::ChangeDifficulty(ChangeDifficultyRequest { + difficulty: fields[1].parse()?, + }) + .encode(), + "lock" => Serverbound::LockDifficulty(LockDifficulty { + locked: fields[1].parse()?, + }) + .encode(), + "set" => Serverbound::SetGameRule(SetGameRule { entries }).encode(), + "values" => Clientbound::GameRuleValues(GameRuleValues { entries }).encode(), + _ => return Err("unknown case".into()), + }; + let mut reader = Reader::new(&bytes); + reader.varint()?; + for byte in reader.rest() { + write!(output, "{byte:02x}")?; + } + output.push('\n'); + } + std::fs::write(&args[2], output)?; + Ok(()) +} diff --git a/crates/horizon-client/src/assets.rs b/crates/horizon-client/src/assets.rs index 351d57d45..b8551a059 100644 --- a/crates/horizon-client/src/assets.rs +++ b/crates/horizon-client/src/assets.rs @@ -245,7 +245,7 @@ impl Assets { material_states, sprite_size: sprites.size, sprite_minimum_size: sprites.minimum_size, - texture_layers: u32::try_from(sprites.layers.len())?, + texture_layers: u32::try_from(sprites.count())?, pixels: sprites.pixels, model_catalog: models.catalog, model_library, diff --git a/crates/horizon-client/src/banner.rs b/crates/horizon-client/src/banner.rs index d2bc33fba..861294722 100644 --- a/crates/horizon-client/src/banner.rs +++ b/crates/horizon-client/src/banner.rs @@ -199,6 +199,14 @@ pub fn dye_rgb(name: &str) -> u32 { pub fn layers(stack: &ItemStack) -> &[BannerLayer] { stack.data().map_or(&[], |d| &d.banner_patterns) } +/// The ominous banner's component patch hides its pattern tooltip. +pub fn tooltip_layers(stack: &ItemStack) -> &[BannerLayer] { + if stack.data().is_some_and(|d| d.ominous_banner) { + &[] + } else { + layers(stack) + } +} /// `LoomMenu.setupResultSlot`: one banner with the pattern added in the dye colour. pub fn loom_result(banner: &ItemStack, dye: &str, pattern: &str) -> ItemStack { let mut result = ItemStack { @@ -302,6 +310,24 @@ mod tests { } assert!(has_max_layers(&banner)); } + #[test] + fn ominous_banner_hides_tooltip_layers_but_keeps_its_patterns() { + let mut banner = crate::mobs::raider::ominous_banner(); + (banner.damage, banner.extra) = crate::item_data::decode_components( + crate::item_data::encode_components(&banner).as_ref(), + ); + assert_eq!( + layers(&banner).len(), + crate::item_data::OMINOUS_LAYERS.len() + ); + assert!(tooltip_layers(&banner).is_empty()); + banner.data_mut().custom_name = Some("Captain's Standard".into()); + assert!(tooltip_layers(&banner).is_empty()); + banner.data_mut().ominous_banner = false; + assert_eq!(tooltip_layers(&banner), layers(&banner)); + assert!(!tooltip_layers(&banner).is_empty()); + } + #[test] fn layers_round_trip_through_nbt() { let l = vec![ diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 9ffd888a1..9c90e8ebf 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -876,7 +876,7 @@ impl BlockEntityRenderer { .as_vec3(); let base = Mat4::from_translation(origin); let packed = scene.world.light(pos[0], pos[1], pos[2]); - self.render_one(scene, *pos, kind, base, packed, lights, out); + self.render_one(scene, *pos, kind, base, packed, lights, false, out); } } /// One block entity at `pos` drawn under `base` with the given packed light @@ -892,12 +892,33 @@ impl BlockEntityRenderer { ) { let kind = self.kind(state); let lights = diffuse_lights(scene.nether); - self.render_one(scene, pos, kind, base, packed, lights, out); + self.render_one(scene, pos, kind, base, packed, lights, false, out); } /// Whether this block state has a block-entity renderer here. pub fn renders(&self, state: u32) -> bool { !matches!(self.kind(state), Kind::None) } + /// ChestRenderer and BannerRenderer submit their animated models for crumbling. + pub fn render_breaking(&self, scene: &Scene, pos: [i32; 3], state: u32, out: &mut Vec) { + if !matches!(self.kind(state), Kind::Banner { .. } | Kind::Chest { .. }) { + return; + } + let origin = (DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) + - scene.camera) + .as_vec3(); + let start = out.len(); + self.render_one( + scene, + pos, + self.kind(state), + Mat4::from_translation(origin), + 0xff, + diffuse_lights(scene.nether), + true, + out, + ); + crate::breaking::entity_geometry(&mut out[start..], origin); + } /// `ChestRenderer.extractRenderState`'s openness for the chest of `state` /// at `pos`: `ChestBlock.combine` (`DoubleBlockCombiner.combineWithNeigbour`) /// pairs a double half with its neighbour only when that is the same @@ -970,7 +991,7 @@ impl BlockEntityRenderer { let kind = self.kind(state); if !matches!(kind, Kind::None) { let lights = diffuse_lights(scene.nether); - self.render_one(scene, [i32::MAX; 3], kind, base, packed, lights, out); + self.render_one(scene, [i32::MAX; 3], kind, base, packed, lights, false, out); } } #[allow(clippy::too_many_arguments)] @@ -982,11 +1003,24 @@ impl BlockEntityRenderer { base: Mat4, packed: u8, lights: (Vec3, Vec3), + crumbling: bool, out: &mut Vec, ) { let sprite = |name: &str| scene.sprites.get(name).copied(); let paint = |name: &str, tint: u32, packed: u8| { - sprite(name).map(|s| Paint { + let rect = if crumbling { + Some(Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w: 16, + h: 16, + }) + } else { + sprite(name) + }; + rect.map(|s| Paint { sprite: s, tint, light: vertex_light(packed), @@ -1058,7 +1092,7 @@ impl BlockEntityRenderer { ChestPart::Left => "double_chest_left", ChestPart::Right => "double_chest_right", }; - let (Some(model), Some(_)) = (self.models.get(model), sprite(texture)) else { + let Some(model) = self.models.get(model) else { return; }; let (open, other) = self.chest_openness( @@ -1145,6 +1179,10 @@ impl BlockEntityRenderer { draw_part(main, "root", m, &none, paint, out); draw_part(flag, "root", m, &wave, paint, out); } + // Pattern passes must not multiply the crumbling decal. + if crumbling { + return; + } // BannerRenderer.submitPatterns: the base pattern layer in the dye colour, // then up to 16 pattern layers in order. if let Some(paint) = paint("entity/banner/base", *color, packed) { @@ -1673,6 +1711,138 @@ fn portal_cube(m: Mat4, faces: &[Direction], layer: u32, out: &mut Vec) #[cfg(test)] mod tests { use super::*; + #[test] + #[ignore = "requires prepared models/textures in HORIZON_TEST_RESOURCES"] + fn entity_block_particles_and_breaking_use_exported_models() -> crate::Result<()> { + use crate::{models::catalog::StateModels, sprites::Sprites}; + use horizon_world::{DATA_VERSION, chunk::BlockState, nbt::Tag}; + let root = std::path::PathBuf::from( + std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"), + ); + let names = [ + "white_banner", + "white_wall_banner", + "chest", + "trapped_chest", + "ender_chest", + "copper_chest", + ]; + let mut facts: std::collections::BTreeMap = + serde_json::from_slice(&std::fs::read(root.join("model-states.json"))?)?; + let states = names.map(|name| { + let name = format!("minecraft:{name}"); + let mut first = facts[&name]["states"][0].clone(); + if first.get("type").is_some() { + first["type"] = serde_json::json!("single"); + } + facts.get_mut(&name).unwrap()["states"] = serde_json::json!([first.clone()]); + BlockState { + name, + properties: serde_json::from_value(first).unwrap(), + } + .to_nbt() + }); + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", Tag::List(states.into())), + ( + "defaults", + Tag::compound(names.iter().enumerate().map(|(id, name)| { + ( + horizon_world::nbt::JavaString::from(format!("minecraft:{name}").as_str()), + Tag::Int(id as i32), + ) + })), + ), + ]))?; + let mut sprites = Sprites::default(); + let catalog = StateModels::from_facts(&root, ®istry, &names, &mut sprites, &facts)?; + for (id, name) in names.iter().enumerate() { + let models = catalog.collect( + BlockStateId(id as u32), + horizon_core::position::BlockPos::default(), + )?; + assert!(models.iter().all(|(_, model)| model.faces.is_empty())); + let particle = match *name { + "ender_chest" => "minecraft:block/obsidian", + "copper_chest" => "minecraft:block/copper_block", + _ => "minecraft:block/oak_planks", + }; + assert_eq!(models[0].1.particle, Some(sprites.layers[particle])); + } + let all: Value = serde_json::from_slice(&std::fs::read(root.join("entity-models.json"))?)?; + let renderer = BlockEntityRenderer::new( + MODELS + .iter() + .filter_map(|(key, layer)| all.get(*layer).map(|v| (*key, ModelPart::parse(v)))) + .collect(), + ®istry, + ); + let world = World::new(BlockStateId(0), 1); + let base_sprites = [ + "entity/banner/banner_base", + "entity/chest/normal", + "entity/chest/trapped", + "entity/chest/ender", + "entity/chest/copper", + ] + .into_iter() + .map(|name| { + ( + name.to_owned(), + Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w: 16, + h: 16, + }, + ) + }) + .collect(); + let mut scene = Scene { + camera: DVec3::ZERO, + orientation: Quat::IDENTITY, + anim: &|_| BlockAnim::default(), + texts: None, + partial: 0.5, + game_time: 0, + max_y: 320, + world: &world, + sprites: &base_sprites, + nether: false, + lid: &|_| 0.0, + sign: &|_| None, + banner: &|_| Vec::new(), + glyph: &|_| (None, 0.0), + }; + for state in 0..names.len() as u32 { + let mut base = Vec::new(); + renderer.render_block(&scene, [0; 3], state, Mat4::IDENTITY, 0xff, &mut base); + let mut cracks = Vec::new(); + renderer.render_breaking(&scene, [0; 3], state, &mut cracks); + assert!(!cracks.is_empty()); + assert_eq!( + base.iter().map(|v| v.pos).collect::>(), + cracks.iter().map(|v| v.pos).collect::>() + ); + assert!(cracks.iter().all(|v| v.layer == 11 + && v.color == u32::MAX + && v.uv.iter().all(|u| u.is_finite()))); + scene.game_time = 20; + if state >= 2 { + scene.lid = &|_| 1.0; + } + let mut animated = Vec::new(); + renderer.render_breaking(&scene, [0; 3], state, &mut animated); + assert!(cracks.iter().zip(&animated).any(|(a, b)| a.pos != b.pos)); + scene.game_time = 0; + scene.lid = &|_| 0.0; + } + Ok(()) + } + #[test] fn classifies_vanilla_block_names() { let props = |pairs: &'static [(&'static str, &'static str)]| { diff --git a/crates/horizon-client/src/blocks.rs b/crates/horizon-client/src/blocks.rs index 521d389bc..27a36396a 100644 --- a/crates/horizon-client/src/blocks.rs +++ b/crates/horizon-client/src/blocks.rs @@ -2,7 +2,10 @@ //! (`gameplay-facts.json`), indexed by registry state ID. mod decode; use crate::Result; -use horizon_world::registry::{BlockRegistry, BlockStateId}; +use horizon_world::{ + level::{Behaviours, GameplayStateSource}, + registry::{BlockRegistry, BlockStateId}, +}; use serde_json::Value; use std::{ collections::HashMap, @@ -107,12 +110,178 @@ impl StateFacts { self.classes.iter().any(|c| &**c == name) } } +/// Compact, owned behaviour inputs retained until the normal behaviour startup stage. +/// No borrowed gameplay JSON or process-wide cache survives the fact loader. +pub struct GameplayProjection { + flags: u16, + emission: u64, + dampening: u64, + hardness: f64, + push: Arc, + volume: f64, + pitch: f64, + place: Arc, + break_sound: Arc, + fall: Arc, +} + +impl GameplayProjection { + fn from_entry(entry: &decode::Entry<'_>, strings: &mut HashMap>) -> Self { + fn intern(strings: &mut HashMap>, value: &str) -> Arc { + if let Some(existing) = strings.get(value) { + return Arc::clone(existing); + } + let value_arc: Arc = Arc::from(value); + strings.insert(value.to_owned(), Arc::clone(&value_arc)); + value_arc + } + const FLAGS: [&str; 11] = [ + "replaceable", + "random_ticks", + "solid_render", + "liquid", + "block_entity", + "ignited_by_lava", + "can_occlude", + "full_collision", + "skylight_down", + "requires_tool", + "shape_occlusion", + ]; + Self { + flags: FLAGS.iter().enumerate().fold(0, |flags, (i, name)| { + flags | ((u16::from(entry.flag(name))) << i) + }), + emission: entry.unsigned("emission"), + dampening: entry.unsigned("dampening"), + hardness: entry.number("hardness"), + push: intern(strings, entry.text("push")), + volume: entry.sound_number("volume"), + pitch: entry.sound_number("pitch"), + place: intern(strings, entry.sound_id("place")), + break_sound: intern(strings, entry.sound_id("break")), + fall: intern(strings, entry.sound_id("fall")), + } + } +} + +impl GameplayStateSource for GameplayProjection { + fn flag(&self, name: &str) -> bool { + const FLAGS: [&str; 11] = [ + "replaceable", + "random_ticks", + "solid_render", + "liquid", + "block_entity", + "ignited_by_lava", + "can_occlude", + "full_collision", + "skylight_down", + "requires_tool", + "shape_occlusion", + ]; + FLAGS + .iter() + .position(|field| *field == name) + .is_some_and(|index| self.flags & (1 << index) != 0) + } + fn unsigned(&self, name: &str) -> u64 { + match name { + "emission" => self.emission, + "dampening" => self.dampening, + _ => 0, + } + } + fn number(&self, name: &str) -> f64 { + if name == "hardness" { + self.hardness + } else { + 0.0 + } + } + fn text(&self, name: &str) -> &str { + if name == "push" { &self.push } else { "" } + } + fn sound_number(&self, name: &str) -> f64 { + match name { + "volume" => self.volume, + "pitch" => self.pitch, + _ => 1.0, + } + } + fn sound_id(&self, name: &str) -> &str { + match name { + "place" => &self.place, + "break" => &self.break_sound, + "fall" => &self.fall, + _ => "", + } + } +} + pub struct BlockFacts { pub states: Vec, pub air: BlockStateId, } impl BlockFacts { pub fn load(root: &Path, registry: &BlockRegistry) -> Result { + let behaviours: Value = serde_json::from_reader(BufReader::new(File::open( + root.join("block-behaviours.json"), + )?))?; + Self::load_with_behaviour_json(root, registry, &behaviours) + } + + /// Load both tables from one resource root, sharing each JSON decode. + /// No data is cached across calls: changes to prepared packs or mods are read again. + pub fn load_pair(root: &Path, registry: &BlockRegistry) -> Result<(Self, Behaviours)> { + let behaviours: Value = serde_json::from_reader(BufReader::new(File::open( + root.join("block-behaviours.json"), + )?))?; + Self::load_with_behaviours(root, registry, &behaviours) + } + + /// Decode state facts once, retaining only the small owned fields needed later. + pub fn load_with_projection( + root: &Path, + registry: &BlockRegistry, + behaviours: &Value, + ) -> Result<(Self, Vec)> { + Self::load_with_callback(root, registry, behaviours, |entries| { + let mut strings = HashMap::new(); + Ok(entries + .iter() + .map(|entry| GameplayProjection::from_entry(entry, &mut strings)) + .collect()) + }) + } + + pub fn load_with_behaviour_json( + root: &Path, + registry: &BlockRegistry, + behaviours: &Value, + ) -> Result { + Ok(Self::load_with_callback(root, registry, behaviours, |_| Ok(()))?.0) + } + + /// Build both tables from the same behaviour document and gameplay decoder. + pub fn load_with_behaviours( + root: &Path, + registry: &BlockRegistry, + behaviours: &Value, + ) -> Result<(Self, Behaviours)> { + Self::load_with_callback(root, registry, behaviours, |entries| { + Ok(Behaviours::load_with_gameplay( + registry, root, behaviours, entries, + )?) + }) + } + + fn load_with_callback( + root: &Path, + registry: &BlockRegistry, + behaviours: &Value, + callback: impl FnOnce(&[decode::Entry<'_>]) -> Result, + ) -> Result<(Self, T)> { let bytes = fs::read(root.join("gameplay-facts.json"))?; serde_json::from_slice::(&bytes)?; let raw: decode::Gameplay<'_> = serde_json::from_slice(&bytes)?; @@ -125,9 +294,6 @@ impl BlockFacts { return Err("gameplay facts do not match the block registry".into()); } // Class chains and per-state behaviour flags exported from the actual block objects. - let behaviours: Value = serde_json::from_reader(BufReader::new(File::open( - root.join("block-behaviours.json"), - )?))?; let behaviour_states = behaviours["states"] .as_array() .filter(|s| s.len() == registry.len()) @@ -221,13 +387,13 @@ impl BlockFacts { outline, outline_edges, name: intern(&state.name), - emission: entry.emission as u8, - dampening: entry.dampening as u8, + emission: entry.emission.as_f64().unwrap_or(0.0) as u8, + dampening: entry.dampening.as_f64().unwrap_or(0.0) as u8, skylight_down: entry.skylight_down, shape_occlusion: entry.shape_occlusion, can_occlude: entry.can_occlude, solid_render: entry.solid_render, - hardness: entry.hardness as f32, + hardness: entry.hardness.as_f64().unwrap_or(0.0) as f32, requires_tool: entry.requires_tool, replaceable: entry.replaceable, random_ticks: entry.random_ticks, @@ -264,12 +430,16 @@ impl BlockFacts { .ok_or("missing block behaviour class chain")?, }); } - Ok(Self { - states, - air: registry - .default_state("minecraft:air") - .ok_or("missing air")?, - }) + let extra = callback(entries)?; + Ok(( + Self { + states, + air: registry + .default_state("minecraft:air") + .ok_or("missing air")?, + }, + extra, + )) } pub fn get(&self, id: BlockStateId) -> &StateFacts { &self.states[id.0 as usize] @@ -281,3 +451,56 @@ impl BlockFacts { ) } } + +impl GameplayStateSource for decode::Entry<'_> { + fn flag(&self, name: &str) -> bool { + match name { + "replaceable" => self.replaceable, + "random_ticks" => self.random_ticks, + "solid_render" => self.solid_render, + "liquid" => self.liquid, + "block_entity" => self.block_entity, + "ignited_by_lava" => self.ignited_by_lava, + "can_occlude" => self.can_occlude, + "full_collision" => self.full_collision, + "skylight_down" => self.skylight_down, + "requires_tool" => self.requires_tool, + "shape_occlusion" => self.shape_occlusion, + _ => false, + } + } + fn unsigned(&self, name: &str) -> u64 { + match name { + "emission" => self.emission.as_u64().unwrap_or(0), + "dampening" => self.dampening.as_u64().unwrap_or(0), + _ => 0, + } + } + fn number(&self, name: &str) -> f64 { + match name { + "hardness" => self.hardness.as_f64().unwrap_or(0.0), + _ => 0.0, + } + } + fn text(&self, name: &str) -> &str { + match name { + "push" => self.push.as_deref().unwrap_or(""), + _ => "", + } + } + fn sound_number(&self, name: &str) -> f64 { + match name { + "volume" => self.sound.volume, + "pitch" => self.sound.pitch, + _ => 1.0, + } + } + fn sound_id(&self, name: &str) -> &str { + match name { + "place" => self.sound.place.id.as_deref().unwrap_or(""), + "break" => self.sound.r#break.id.as_deref().unwrap_or(""), + "fall" => self.sound.fall.id.as_deref().unwrap_or(""), + _ => "", + } + } +} diff --git a/crates/horizon-client/src/blocks/decode.rs b/crates/horizon-client/src/blocks/decode.rs index 967955f9e..7feb3ac41 100644 --- a/crates/horizon-client/src/blocks/decode.rs +++ b/crates/horizon-client/src/blocks/decode.rs @@ -155,17 +155,20 @@ object!(Sound<'a> { }); object!(Entry<'a> { id: Option = None => value(unsigned), - emission: f64 = 0.0 => value(number), - dampening: f64 = 0.0 => value(number), + emission: Value = Value::Null => typed, + dampening: Value = Value::Null => typed, skylight_down: bool = false => value(flag), shape_occlusion: bool = false => value(flag), can_occlude: bool = false => value(flag), solid_render: bool = false => value(flag), - hardness: f64 = 0.0 => value(number), + hardness: Value = Value::Null => typed, requires_tool: bool = false => value(flag), replaceable: bool = false => value(flag), random_ticks: bool = false => value(flag), block_entity: bool = false => value(flag), + liquid: bool = false => value(flag), + ignited_by_lava: bool = false => value(flag), + push: Option = None => value(text), render_shape: Option = None => value(text), full_collision: bool = false => value(flag), friction: f64 = 0.0 => value(number), diff --git a/crates/horizon-client/src/blocks/decode_tests.rs b/crates/horizon-client/src/blocks/decode_tests.rs index d9d0e14fd..8fdb93f4f 100644 --- a/crates/horizon-client/src/blocks/decode_tests.rs +++ b/crates/horizon-client/src/blocks/decode_tests.rs @@ -89,9 +89,9 @@ fn typed_fields_keep_defaults_duplicates_and_wrong_type_behavior() -> crate::Res assert_eq!(entries[1].id, None); let e = &entries[2]; assert_eq!(e.id, Some(2)); - assert_eq!(e.emission, 4.5); - assert_eq!(e.dampening, 0.0); - assert_eq!(e.hardness.to_bits(), (-0.0f64).to_bits()); + assert_eq!(e.emission.as_f64(), Some(4.5)); + assert_eq!(e.dampening.as_f64().unwrap_or(0.0), 0.0); + assert_eq!(e.hardness.as_f64().unwrap().to_bits(), (-0.0f64).to_bits()); assert!(e.skylight_down && e.outline_offset.unwrap_or(e.offset)); assert_eq!(e.item, None); assert_eq!(e.render_shape, None); diff --git a/crates/horizon-client/src/breaking.rs b/crates/horizon-client/src/breaking.rs index 9dc948ae3..c7ee19206 100644 --- a/crates/horizon-client/src/breaking.rs +++ b/crates/horizon-client/src/breaking.rs @@ -41,6 +41,35 @@ pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: } } +/// Project a block entity's transformed quads onto the same destroy-stage pass. +pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) { + for quad in vertices.as_chunks_mut::<4>().0 { + let positions = [0, 1, 2].map(|i| glam::Vec3::from(quad[i].pos)); + let normal = (positions[1] - positions[0]).cross(positions[2] - positions[0]); + let mut facing = Direction::North; + let mut best = f32::from_bits(1); + for (direction, dot) in [ + (Direction::Down, -normal.y), + (Direction::Up, normal.y), + (Direction::North, -normal.z), + (Direction::South, normal.z), + (Direction::West, -normal.x), + (Direction::East, normal.x), + ] { + if dot > best { + facing = direction; + best = dot; + } + } + for vertex in quad { + vertex.uv = decal_uv((glam::Vec3::from(vertex.pos) - origin).to_array(), facing); + vertex.layer = 11; + vertex.color = 0xffff_ffff; + vertex.light = 240 | (240 << 8); + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -49,6 +78,7 @@ mod tests { fn slab_top() -> BakedModel { BakedModel { ambient_occlusion: true, + particle: None, cube: None, faces: vec![BakedFace { layer: 0, @@ -86,6 +116,24 @@ mod tests { assert_eq!(v.color, 0xffff_ffff); } } + #[test] + fn entity_overlay_uses_block_local_projected_uvs() { + let origin = glam::Vec3::new(12.0, -3.0, 8.0); + let mut expected = Vec::new(); + geometry(&slab_top(), origin, false, &mut expected); + let mut actual = expected.clone(); + for vertex in &mut actual { + vertex.uv = [0.0; 2]; + vertex.layer = 0; + vertex.color = 0; + } + entity_geometry(&mut actual, origin); + assert_eq!( + bytemuck::cast_slice::<_, u8>(&actual), + bytemuck::cast_slice::<_, u8>(&expected) + ); + } + #[test] fn small_faces_use_projected_not_stretched_uvs() { let a = decal_uv([0.0, 0.0, 0.0], Direction::North); diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index 39fde56b5..d3e00daca 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -28,7 +28,7 @@ use std::{fs, io, path::Path, sync::Arc}; pub fn load<'r>(root: &Path, registry: &'r BlockRegistry) -> Result> { let data = nbt::read_named( &fs::read(root.join("cached-collision.nbt"))?, - Limits::default(), + Limits::tables(), )? .0 .tag; diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 46e73f067..9cdac1463 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -132,6 +132,8 @@ impl Crafter { pub struct Banner { pub layers: Vec, pub name: Option, + /// Components not consumed by BannerBlockEntity's implicit fields. + pub components: horizon_world::nbt::Compound, } /// `CreakingHeartBlockEntity` (the logic is in `game/creaking.rs`). #[derive(Clone, Debug, Default)] diff --git a/crates/horizon-client/src/debug_chart.rs b/crates/horizon-client/src/debug_chart.rs index d006a8ab6..35fd40bd4 100644 --- a/crates/horizon-client/src/debug_chart.rs +++ b/crates/horizon-client/src/debug_chart.rs @@ -74,6 +74,10 @@ pub struct DebugCharts { pub bandwidth: SampleLogger, /// `MinecraftServer.smoothedTickTimeMillis`. pub smoothed_tick_ms: f32, + /// Connection's smoothed packets per second, sent then received. + pub packet_rates: [f32; 2], + packet_totals: [i64; 2], + packet_tick: u8, previous_tick: Option, bytes_seen: Option, } @@ -113,6 +117,9 @@ impl DebugCharts { self.previous_tick = None; self.bytes_seen = None; self.smoothed_tick_ms = 0.0; + self.packet_rates = [0.0; 2]; + self.packet_totals = [0; 2]; + self.packet_tick = 0; } /// One integrated server tick that started at `started` and ran its /// tick method for `method` (`MinecraftServer.logFullTickTime` and @@ -136,6 +143,17 @@ impl DebugCharts { } self.bytes_seen = Some(total); } + /// `Connection.tickSecond`: sampled on the first tick, then every 20 ticks. + pub fn log_packets(&mut self, totals: [i64; 2]) { + if self.packet_tick == 0 { + for (i, total) in totals.into_iter().enumerate() { + let count = (total - self.packet_totals[i]).max(0) as f32; + self.packet_rates[i] = count + 0.75 * (self.packet_rates[i] - count); + } + self.packet_totals = totals; + } + self.packet_tick = (self.packet_tick + 1) % 20; + } /// The charts along the bottom of the screen (`extractRenderState`): /// frame times left and tick times right, or bandwidth left (remote /// servers only) and ping right. `mspt` is the level's milliseconds @@ -524,6 +542,27 @@ mod tests { assert!(draws.contains(&fill(361, 174, 365, 178, 0xFF0A_141E))); } + #[test] + fn packet_rates_follow_connection_smoothing_and_reset_between_worlds() { + let mut charts = DebugCharts::default(); + charts.log_packets([80, 400]); + assert_eq!(charts.packet_rates, [20.0, 100.0]); + for _ in 1..20 { + charts.log_packets([180, 800]); + } + assert_eq!(charts.packet_rates, [20.0, 100.0]); + charts.log_packets([180, 800]); + assert_eq!(charts.packet_rates, [40.0, 175.0]); + for _ in 0..20 { + charts.log_packets([180, 800]); + } + assert_eq!(charts.packet_rates, [30.0, 131.25]); + charts.reset(); + assert_eq!(charts.packet_rates, [0.0, 0.0]); + charts.log_packets([4, 8]); + assert_eq!(charts.packet_rates, [1.0, 2.0]); + } + #[test] fn ticks_and_bandwidth_log_their_differences() { let mut c = DebugCharts::default(); diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index 71a9377ed..2e600333a 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -68,6 +68,14 @@ impl EffectInstance { } changed } + /// `MobEffectInstance.tickClient`: a client counts its effects down + /// (the server removes them). + pub fn tick_client(&mut self) { + if self.infinite() || self.duration > 0 { + self.tick_down(); + self.downgrade(); + } + } fn tick_down(&mut self) { if let Some(h) = self.hidden.as_mut() { h.tick_down(); @@ -170,6 +178,39 @@ impl PlayerEffects { pub fn clear(&mut self) { self.list.clear(); } + /// The effects of a saved player (`Player.active_effects`: id, + /// duration, amplifier, ambient, visible). + pub fn from_saved(saved: &[(String, i32, i32, bool, bool)]) -> Self { + let mut effects = Self::default(); + for (id, duration, amplifier, ambient, _) in saved { + if let Some(def) = brewing::effect(id) { + let mut e = EffectInstance::new(def.id, *duration, *amplifier); + e.ambient = *ambient; + effects.add(e); + } + } + effects + } + /// `Player.active_effects` for the save. + pub fn saved(&self) -> Vec<(String, i32, i32, bool, bool)> { + self.list + .iter() + .map(|e| { + ( + format!("minecraft:{}", e.id), + e.duration, + e.amplifier, + e.ambient, + e.visible, + ) + }) + .collect() + } + /// ClientboundUpdateMobEffectPacket's flags without blending: ambient, + /// particles visible and the icon shown (always, for these effects). + pub fn flags(e: &EffectInstance) -> i8 { + i8::from(e.ambient) | i8::from(e.visible) << 1 | 4 + } /// `LivingEntity.tickEffects` (server part) with the omens' effect ticks: /// `omen` answers `BadOmenMobEffect` (every tick) and `RaidOmenMobEffect` /// (on its last tick). Returns the actions to apply, in order, and diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index c62a67a07..86bdbe562 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -185,6 +185,8 @@ impl Enchantments { .into_iter() .filter(|(k, _)| { k.starts_with("enchantment.") + || k.starts_with("attribute.") + || k.starts_with("item.modifiers.") || k.starts_with("effect.") || k.starts_with("item.minecraft.potion") || k.starts_with("item.minecraft.splash_potion") diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index a1e18076e..5e6a3336a 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -301,6 +301,20 @@ pub struct Experience { pub total: i32, } impl Experience { + /// `Player.getBaseExperienceReward`: keep-inventory and spectators drop none. + pub fn death_reward(&self, keep: bool) -> u32 { + if keep { + 0 + } else { + self.level.wrapping_mul(7).clamp(0, 100) as u32 + } + } + /// `ServerPlayer.restoreFrom`: only keep-inventory and spectators retain XP. + pub fn respawn(&mut self, keep: bool) { + if !keep { + *self = Self::default(); + } + } pub fn needed(level: i32) -> i32 { if level >= 30 { 112 + (level - 30) * 9 @@ -540,6 +554,37 @@ impl ArmorStand { } } +#[cfg(test)] +mod experience_tests { + use super::*; + + #[test] + fn death_reward_uses_levels_and_caps_the_recoverable_points() { + for (level, reward) in [(0, 0), (1, 7), (14, 98), (15, 100), (30, 100)] { + let xp = Experience { + level, + progress: 0.75, + total: 10_000, + }; + assert_eq!(xp.death_reward(false), reward); + assert_eq!(xp.death_reward(true), 0); + } + } + + #[test] + fn respawn_clears_all_xp_unless_it_is_kept() { + let mut xp = Experience::default(); + xp.give(155); + let before = (xp.level, xp.progress, xp.total); + xp.respawn(true); + assert_eq!((xp.level, xp.progress, xp.total), before); + xp.respawn(false); + assert_eq!((xp.level, xp.progress, xp.total), (0, 0.0, 0)); + xp.give(7); + assert_eq!((xp.level, xp.progress, xp.total), (1, 0.0, 7)); + } +} + #[cfg(test)] mod fire_environment_tests { use super::*; diff --git a/crates/horizon-client/src/extras.rs b/crates/horizon-client/src/extras.rs index 264456c1a..ee142486c 100644 --- a/crates/horizon-client/src/extras.rs +++ b/crates/horizon-client/src/extras.rs @@ -68,6 +68,7 @@ impl Corner { #[derive(Clone, Debug, PartialEq)] pub struct Extras { + pub fullbright: bool, pub zoom: bool, /// A vanilla key name (`key.keyboard.z`). pub zoom_key: String, @@ -108,6 +109,7 @@ pub struct Extras { impl Default for Extras { fn default() -> Self { Self { + fullbright: false, zoom: false, zoom_key: "key.keyboard.z".into(), zoom_level: 4, @@ -155,6 +157,7 @@ impl Extras { _ => d, }; match key.trim() { + "fullbright" => e.fullbright = flag(e.fullbright), "zoom" => e.zoom = flag(e.zoom), "zoomKey" if value.starts_with("key.") => e.zoom_key = value.to_owned(), "zoomLevel" => { @@ -198,7 +201,8 @@ impl Extras { } pub fn serialize(&self) -> String { format!( - "zoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n", + "fullbright:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n", + bool_text(self.fullbright), bool_text(self.zoom), self.zoom_key, self.zoom_level, @@ -418,6 +422,7 @@ impl Cps { /// The settings the Extras page shows, one per row. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Item { + Fullbright, Zoom, ZoomKey, ZoomLevel, @@ -445,6 +450,8 @@ pub enum Item { pub fn rows() -> Vec> { use Item::*; vec![ + Err("Lighting"), + Ok(Fullbright), Err("Zoom"), Ok(Zoom), Ok(ZoomKey), @@ -493,6 +500,7 @@ fn next(all: &[T], current: T, back: bool) -> T { impl Item { pub fn caption(self) -> &'static str { match self { + Item::Fullbright => "Fullbright", Item::Zoom => "Zoom", Item::ZoomKey => "Zoom key", Item::ZoomLevel => "Starting zoom", @@ -518,6 +526,7 @@ impl Item { /// What the row says under its caption. pub fn description(self) -> &'static str { match self { + Item::Fullbright => "Show blocks and entities at full light, even in dark areas.", Item::Zoom => "Hold the zoom key to zoom; the wheel changes it while held.", Item::ZoomKey => "Click, then press a key. Escape unbinds it.", Item::ZoomLevel => "The zoom the key starts at.", @@ -556,7 +565,7 @@ impl Item { pub fn cost(self) -> Option { use crate::graphics_style::Cost; match self { - Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None), + Item::Fullbright | Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None), Item::Minimap => Some(Cost::Low), Item::AutoReconnect | Item::MouseTweaks | Item::Sort => Some(Cost::None), _ => None, @@ -565,6 +574,7 @@ impl Item { /// On/off items and their value. pub fn switch(self, e: &Extras) -> Option { Some(match self { + Item::Fullbright => e.fullbright, Item::Zoom => e.zoom, Item::ZoomSmooth => e.zoom_smooth, Item::ZoomSensitivity => e.zoom_sensitivity, @@ -606,6 +616,7 @@ impl Item { /// A click (`back` for the right button). The zoom key binds instead. pub fn cycle(self, e: &mut Extras, back: bool) { match self { + Item::Fullbright => e.fullbright = !e.fullbright, Item::Zoom => e.zoom = !e.zoom, Item::ZoomSmooth => e.zoom_smooth = !e.zoom_smooth, Item::ZoomSensitivity => e.zoom_sensitivity = !e.zoom_sensitivity, @@ -651,11 +662,14 @@ mod tests { #[test] fn everything_is_off_by_default_and_round_trips() { let d = Extras::default(); + assert!(!d.fullbright); assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect); assert!(!d.mouse_tweaks && !d.sort); assert_eq!(Extras::parse(""), d); assert_eq!(Extras::parse(&d.serialize()), d); let mut e = d.clone(); + Item::Fullbright.cycle(&mut e, false); + assert_eq!(Item::Fullbright.switch(&e), Some(true)); e.zoom = true; e.zoom_key = "key.keyboard.c".into(); e.zoom_level = 6; diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index 7b1771000..0b4eebd62 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -318,6 +318,7 @@ impl Title { x: f32, y: f32, ) -> Action { + self.remember_direct_address(); if self.skip_opening() { return Action::None; } @@ -472,7 +473,7 @@ impl Title { _ => None, }; if let Some(id) = id { - match screen.click(Some(id), 0.0, 0.0, (0.0, 0.0), &saves) { + match self.multiplayer_click(Some(id), 0.0, 0.0, (0.0, 0.0)) { Outcome::Back => self.mode = Mode::Main, Outcome::Connect(address) => return Action::Connect { address }, Outcome::None => {} @@ -1172,6 +1173,7 @@ pub mod pause { quit_label: &str, opened: Instant, friends: &FriendsView, + remote: bool, ) { let (w, h) = (ui.w, ui.h); let p = t::ease_out_quint(opened.elapsed().as_secs_f32() / t::move_()); @@ -1206,11 +1208,11 @@ pub mod pause { Kind::Primary, true, ); - let lw = ui.button_width("Open to LAN", true); + let lw = ui.button_width("World Options", true); ui.button( act(9), [x + bw + 8.0, y, lw, CONTROL_LARGE], - "Open to LAN", + "World Options", Kind::Secondary, true, ); @@ -1234,7 +1236,11 @@ pub mod pause { x, y, "Leave", - "Saves the world, then returns to the title.", + if remote { + "Disconnects from the server, then returns to the title." + } else { + "Saves the world, then returns to the title." + }, cw - t::ROW_LABEL - 220.0, ); let qw = ui.button_width(quit_label, false); @@ -1362,6 +1368,7 @@ pub mod pause { world: &str, quit_label: &str, friends: &FriendsView, + remote: bool, ) -> Option { let mut ui = Ui::dry(atlas, batch, (x, y)); draw( @@ -1370,6 +1377,7 @@ pub mod pause { quit_label, Instant::now() - std::time::Duration::from_secs(5), friends, + remote, ); let hit = ui.hit((x, y))?; let nav = id("pause.nav", 0); @@ -1390,6 +1398,47 @@ mod tests { use super::*; use horizon_world::nbt::Tag; + #[test] + fn pause_world_options_and_disconnect_are_clickable_on_servers() { + let atlas = + HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap(); + let friends = FriendsView::default(); + for remote in [false, true] { + let quit = if remote { + "Disconnect" + } else { + "Save and quit" + }; + for action in [9u8, 2] { + let mut batch = HudBatch::new([1280, 720]); + let (rect, density) = { + let mut ui = Ui::dry(&atlas, &mut batch, (0.0, 0.0)); + pause::draw( + &mut ui, + "World", + quit, + Instant::now() - std::time::Duration::from_secs(5), + &friends, + remote, + ); + let hit = ui + .hits + .iter() + .find(|h| h.id == id("pause", u64::from(action))) + .expect("pause action available"); + (hit.rect, ui.density) + }; + let k = density / batch.scale; + let x = (rect[0] + rect[2]) / 2.0 * k; + let y = (rect[1] + rect[3]) / 2.0 * k; + assert_eq!( + pause::click(&atlas, &mut batch, x, y, "World", quit, &friends, remote), + Some(action) + ); + } + } + } + fn world(saves: &std::path::Path, folder: &str, last_played: i64) { crate::save::write_dat( &saves.join(folder).join("level.dat"), @@ -1432,6 +1481,28 @@ mod tests { } } + #[test] + fn horizon_direct_connection_remembers_the_address_after_leaving() { + let atlas = + HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap(); + let saves = + std::env::temp_dir().join(format!("horizon-front-direct-{}", std::process::id())); + let mut title = Title::new(saves.clone(), &saves); + title.last_server = "localhost:25566".into(); + title.mode = Mode::Multiplayer(Screen::list(&saves)); + press(&mut title, &atlas, DIRECT); + assert_eq!(title.focused_field().unwrap().1, "localhost:25566"); + *title.focused_field().unwrap().1 = "example.org:25567".into(); + press(&mut title, &atlas, BACK); + press(&mut title, &atlas, DIRECT); + assert_eq!(title.focused_field().unwrap().1, "example.org:25567"); + *title.focused_field().unwrap().1 = "localhost:25568".into(); + press(&mut title, &atlas, NAV); + press(&mut title, &atlas, NAV + 2); + press(&mut title, &atlas, DIRECT); + assert_eq!(title.focused_field().unwrap().1, "localhost:25568"); + } + #[test] fn horizon_world_delete_confirms_and_keeps_the_selection_in_place() { let atlas = diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b640c789d..117b83bc5 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1087,6 +1087,8 @@ struct Game<'a> { lan: Option, /// Single player's server thread, which `remote` is connected to. integrated: Option, + /// This game is that server thread's (game/integrated.rs). + serving: Option, /// The open world is shared behind an invite code (game/friends.rs). friends: Option, world_options: Option, @@ -1447,9 +1449,13 @@ impl Game<'_> { .iter() .flat_map(|(_, m)| m.faces.iter()) .find(|f| f.quad.facing == horizon_assets::model::Direction::Up) - .or_else(|| models.iter().flat_map(|(_, m)| m.faces.iter()).next())?; - let name = self.pack.layer_names.get(&face.layer)?.clone(); - let tint = if face.quad.tint_index >= 0 { + .or_else(|| models.iter().flat_map(|(_, m)| m.faces.iter()).next()); + // Entity-rendered blocks may have a particle texture without any faces. + let layer = face + .map(|face| face.layer) + .or_else(|| models.iter().find_map(|(_, model)| model.particle))?; + let name = self.pack.layer_names.get(&layer)?.clone(); + let tint = if face.is_some_and(|face| face.quad.tint_index >= 0) { let n = &self.res.facts.get(state).name; if n.contains("leaves") || n.contains("vine") { 0x48B518 @@ -1777,6 +1783,12 @@ impl Game<'_> { }); self.process_level_events() } + fn attack_block(&mut self, pos: [i32; 3]) -> Result<()> { + self.with_level(|b, level, ticks| { + b.attack_block(level, ticks, BlockPos::new(pos[0], pos[1], pos[2])); + }); + self.process_level_events() + } /// Track which chunks are ticking (Ticks needs chunk load/unload). fn sync_tick_chunks(&mut self) { if !self.tick_chunks.synchronize(&self.world.chunks) { @@ -2885,6 +2897,7 @@ impl Game<'_> { return Ok(()); } if self.mining.as_ref().is_none_or(|m| m.pos != hit.pos) { + self.attack_block(hit.pos)?; self.mining = Some(Mining { pos: hit.pos, progress: 0.0, @@ -3091,6 +3104,7 @@ impl Game<'_> { self.eye = 1.62; self.previous_eye = 1.62; self.clock.reset(); + self.capture_loaded_world(); Ok(()) } fn tick(&mut self) -> Result<()> { @@ -3406,11 +3420,8 @@ impl Game<'_> { } if player.health.dead_or_dying() && self.screen != Screen::Dead { // Inventory.dropAll: every stack thrown in a random direction. - let at = [ - player.position.x, - player.position.y + 1.32, - player.position.z, - ]; + let feet = [player.position.x, player.position.y, player.position.z]; + let at = [feet[0], feet[1] + 1.32, feet[2]]; let killer = self.combat_killer_kind(); self.death_message(); // ServerPlayer.die: deaths, and the time-since counters restart. @@ -3426,6 +3437,10 @@ impl Game<'_> { } self.stats.reset("custom", "minecraft:time_since_death"); self.stats.reset("custom", "minecraft:time_since_rest"); + let reward = self + .experience + .death_reward(self.ui.rules.bool("keep_inventory") || self.spectator()); + self.spawn_orbs(feet, reward); if !self.creative && !self.ui.rules.bool("keep_inventory") { // Inventory.dropAll: slots 0..36, armor feet to head (36..39), off hand (40). let mut stacks: Vec = @@ -3634,8 +3649,8 @@ impl Game<'_> { } /// `Minecraft.pause`: a single-player game with a pausing screen open. fn pauses_game(&self) -> bool { - (self.remote.is_none() || self.integrated.is_some()) - && self.lan.is_none() + self.has_singleplayer_server() + && !self.is_published() && self.title.is_none() && (matches!( self.screen, @@ -3648,6 +3663,13 @@ impl Game<'_> { ) || self.book.is_some()) } fn capture(&mut self, capture: bool) { + // MouseHandler.grabMouse never captures an inactive window. + if capture && !self.focused { + return; + } + if !capture { + self.stop_mining(); + } // The real pointer takes over from an agent's. self.agent_pointer = false; let Some(window) = &self.window else { return }; @@ -3663,6 +3685,16 @@ impl Game<'_> { } window.set_cursor_visible(!self.captured); } + /// LevelLoadingScreen.onClose -> Gui.setScreen(null) -> grabMouse. + fn capture_loaded_world(&mut self) { + // Loading may finish after focus was lost or another screen opened. + if self.title.is_none() + && self.screen == Screen::Playing + && !self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()) + { + self.capture(true); + } + } fn draw_item(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) { // `GuiGraphics.renderItem`: the resolved item model (tints, foil and // special renderers included), then the decorations. @@ -3840,7 +3872,9 @@ impl Game<'_> { let spectator = self.spectator(); let (wi, hi) = (w as i32, h as i32); // Horizon's pause menu sits over the blurred world alone. - if !self.ui.hide_gui && !self.horizon_pause() { + let horizon_pause = self.horizon_pause(); + let show_hud = !self.ui.hide_gui && !horizon_pause; + if show_hud { self.draw_spyglass(&mut batch); // Hud.extractCrosshair / extractItemHotbar / extractPlayerHealth / // extractVehicleHealth and the experience bar, laid out by hud_layout. @@ -3890,7 +3924,7 @@ impl Game<'_> { let draws = hud_overlays::sleep_overlay(wi, hi, ticks as i32); hud_layout::paint(&mut batch, &self.atlas, &draws); } - if !self.ui.hide_gui { + if show_hud { self.draw_titles(&mut batch); self.draw_scoreboard(&mut batch); self.draw_subtitles(&mut batch); @@ -3966,15 +4000,17 @@ impl Game<'_> { } } let atlas = &self.atlas; - if !self.ui.hide_gui + if show_hud && let Some((text, at)) = &self.message && at.elapsed() < Duration::from_secs(3) { let tw = HudBatch::text_width(atlas, text); batch.text(atlas, text, (w - tw) / 2.0, h - 59.0, u32::MAX, true); } - self.draw_chat(&mut batch); - self.draw_tab_list(&mut batch); + if !horizon_pause { + self.draw_chat(&mut batch); + self.draw_tab_list(&mut batch); + } match self.screen { Screen::Paused if self.pause_menu => self.draw_pause_menu(&mut batch), // PauseScreen(false): only its title, at the top. @@ -4333,14 +4369,7 @@ impl Game<'_> { } else { ("Crafting", 97.0) }; - batch.text( - atlas, - title, - ox + tx, - oy + if self.craft_size == 3 { 6.0 } else { 8.0 }, - grey, - false, - ); + batch.text(atlas, title, ox + tx, oy + 6.0, grey, false); if self.craft_size == 3 { batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false); } @@ -5576,6 +5605,20 @@ impl Game<'_> { .block_entity_render .render(&scene, visible, &mut out); } + if let Some(mining) = &self.mining + && mining.progress > 0.0 + && self.atlas.sprites.contains_key(&format!( + "block/destroy_stage_{}", + ((mining.progress * 10.0) as u32).min(9) + )) + { + let state = self + .world + .block(mining.pos[0], mining.pos[1], mining.pos[2]); + self.res + .block_entity_render + .render_breaking(&scene, mining.pos, state.0, &mut out); + } } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. if let Some(r) = self @@ -6637,6 +6680,9 @@ impl Game<'_> { std::env::current_dir()?.join("saves"), &self.options.resources, )); + if let Some(title) = &mut self.title { + title.last_server = self.settings.file.string("lastServer"); + } self.capture(false); Ok(()) } @@ -7642,7 +7688,15 @@ impl Game<'_> { /// The renderer for the window, with the current block sprites, shared /// atlas and world border texture. fn new_renderer(&self, window: Arc) -> Result { - let assets = &self.pack.assets; + self.renderer_for(window, &self.pack, &self.atlas) + } + fn renderer_for( + &self, + window: Arc, + pack: &PackResources, + atlas: &HudAtlas, + ) -> Result { + let assets = &pack.assets; let mut renderer = pollster::block_on(Renderer::new( window, self.options.offscreen, @@ -7652,12 +7706,12 @@ impl Game<'_> { assets.texture_layers, &assets.sprite_mips, &assets.animations, - (&self.atlas.pixels, self.atlas.width, self.atlas.height), - (&self.pack.forcefield.2, self.pack.forcefield.0), - &self.pack.panorama, + (&atlas.pixels, atlas.width, atlas.height), + (&pack.forcefield.2, pack.forcefield.0), + &pack.panorama, + self.renderer.as_ref(), ))?; - renderer.hud.fire_animations = self - .atlas + renderer.hud.fire_animations = atlas .fire_animations .iter() .map(|(rect, animation)| (*rect, animation.clone(), usize::MAX)) @@ -8058,7 +8112,7 @@ impl Game<'_> { self.creative_screen.search_focused.elapsed().as_millis(), ); } - let mut hovered: Option = None; + let mut hovered: Option = None; if tab.inventory { self.draw_player_preview( batch, @@ -8108,7 +8162,7 @@ impl Game<'_> { && self.cursor.1 < y + 16.0 { batch.fill(&self.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); - hovered = Some(stack.item.to_string()); + hovered = Some(stack.clone()); } } } @@ -8123,7 +8177,7 @@ impl Game<'_> { && self.cursor.1 >= y && self.cursor.1 < y + 16.0 { - hovered = Some(stack.item.to_string()); + hovered = Some(stack); } } let scrollable = self.creative_screen.rows(&self.pack.names) > 5; @@ -8159,8 +8213,8 @@ impl Game<'_> { } else if self.carried.is_none() && let Some(item) = hovered { - let name = self.pack.names.item(&item); - self.tooltip(batch, &name, self.cursor.0, self.cursor.1); + let lines = self.stack_tooltip(&item); + self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); } self.draw_inventory_effects(batch, (ox, oy), Creative::WIDTH as i32); } @@ -8304,21 +8358,7 @@ impl Game<'_> { self.ender_items = items.clone(); } level.ender_items = self.ender_items.clone(); - level.active_effects = self - .potions - .effects - .list - .iter() - .map(|e| { - ( - format!("minecraft:{}", e.id), - e.duration, - e.amplifier, - e.ambient, - e.visible, - ) - }) - .collect(); + level.active_effects = self.potions.effects.saved(); } fn save_game(&mut self) -> Result<()> { self.save_game_with(true) @@ -8436,12 +8476,23 @@ impl Game<'_> { let debug_lines = horizon_client::gizmos::camera_relative(&lines, at, view); let debug_lines_on_top = horizon_client::gizmos::camera_relative(&on_top, at, view); let debug_crosshair = horizon_client::gizmos::camera_relative(&crosshair.on_top, at, view); - // LevelRenderer.renderHitOutline: the outline shape's edges. + // LevelExtractor.extractBlockOutline: model translucency controls draw order. + let mut outline_after_terrain = false; let outline = if self.screen == Screen::Playing && !self.spectator() { self.pick() .map(|h| { let state = self.world.block(h.pos[0], h.pos[1], h.pos[2]); let f = self.res.facts.get(state); + outline_after_terrain = self + .pack + .assets + .model_catalog + .collect(state, BlockPos::new(h.pos[0], h.pos[1], h.pos[2])) + .is_ok_and(|models| { + models + .iter() + .any(|(_, model)| model.faces.iter().any(|f| f.translucent)) + }); let o = if f.outline_offset { self.pack .context @@ -8591,6 +8642,7 @@ impl Game<'_> { }), dark_disc: self.dark_disc(camera), outline, + outline_after_terrain, debug_lines: &debug_lines, debug_lines_on_top: &debug_lines_on_top, debug_crosshair: &debug_crosshair, @@ -8854,7 +8906,13 @@ impl Game<'_> { } _ => {} }, - // key.swapOffhand: ServerboundPlayerActionPacket SWAP_ITEM_WITH_OFFHAND. + // key.swapOffhand: on a server, ServerboundPlayerActionPacket SWAP_ITEM_WITH_OFFHAND + // (the server swaps the hands and sends both slots back; spectators can't). + KeyCode::KeyF if self.screen == Screen::Playing && self.remote.is_some() => { + if !self.spectator() { + self.remote_swap_hands(); + } + } KeyCode::KeyF if self.screen == Screen::Playing => { std::mem::swap(&mut self.offhand, &mut self.inventory[self.selected]); self.using = None; @@ -9304,6 +9362,7 @@ impl ApplicationHandler for Game<'_> { clicked } }); + self.save_title_options(); if sound { self.audio.play_button_click(); } @@ -9356,6 +9415,21 @@ impl ApplicationHandler for Game<'_> { } WindowEvent::MouseInput { state, button, .. } => { let pressed = state == ElementState::Pressed; + if matches!(self.screen, Screen::Inventory | Screen::Creative) + && let Some(key) = self + .settings + .keys + .container_mouse_key(button, self.creative) + { + if pressed && self.carried.is_none() { + self.inventory_hotkey(key); + } + // Neither edge of a bound button is an ordinary slot click. + return Ok(()); + } + if pressed && self.sort_mouse_press(button) { + return Ok(()); + } match self.screen { Screen::Playing => { if pressed && !self.captured { @@ -9542,6 +9616,7 @@ impl ApplicationHandler for Game<'_> { if let Some(t) = self.title.as_mut() { t.escape(); } + self.save_title_options(); } _ => self.title_edit(event.text.as_deref(), false), } @@ -10078,6 +10153,7 @@ impl<'a> Game<'a> { remote: None, lan: None, integrated: None, + serving: None, world_options: None, options_to_world_options: false, command_block_screen: None, @@ -10139,7 +10215,13 @@ pub fn run() -> Result<()> { horizon_client::spans::enable(options.spikes.is_some()); let vanilla_root = options.resources.clone(); let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt")); - options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs); + let mut pack_error = None; + options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs) + .unwrap_or_else(|e| { + log::warn!("Horizon: resource packs not applied: {e}"); + pack_error = Some(e.to_string()); + vanilla_root.clone() + }); options.resources = mods::content_root( &options.resources, &early_settings.mods.enabled, @@ -10151,6 +10233,7 @@ pub fn run() -> Result<()> { // with the game's own resources. Err(e) if options.resources != vanilla_root => { log::warn!("Horizon: resource packs failed to load ({e}); using the default resources"); + pack_error = Some(e.to_string()); options.resources = vanilla_root.clone(); Assets::load(&vanilla_root)? } @@ -10164,7 +10247,11 @@ pub fn run() -> Result<()> { let root = options.resources.clone(); let assets = Arc::new(assets); log::info!("load assets: {:.2}s", started.elapsed().as_secs_f32()); - let facts = BlockFacts::load(&root, assets.registry)?; + let behaviour_json: serde_json::Value = serde_json::from_reader(std::io::BufReader::new( + std::fs::File::open(root.join("block-behaviours.json"))?, + ))?; + let (facts, gameplay_projection) = + BlockFacts::load_with_projection(&root, assets.registry, &behaviour_json)?; let mob_data = horizon_client::mobs::MobData::load(&root, &facts); horizon_client::mobs::trial_spawner::load_registry(&root); log::info!("load facts: {:.2}s", started.elapsed().as_secs_f32()); @@ -10231,7 +10318,12 @@ pub fn run() -> Result<()> { ambient: horizon_client::ambience::AmbientTables::load(&root), nether_environment: Environment::load_dimension(&root, "the_nether", false)?, end_environment: Environment::load_dimension(&root, "the_end", false)?, - behaviours: Behaviours::load(registry_owner.registry, &root)?, + behaviours: Behaviours::load_with_gameplay( + registry_owner.registry, + &root, + &behaviour_json, + &gameplay_projection, + )?, mob_types: MobTypes::load(&root)? .types .into_iter() @@ -10243,6 +10335,10 @@ pub fn run() -> Result<()> { player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main") .and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")), }); + // Both inputs are needed only while constructing the behaviour tables. + // Release their owned JSON/Arc buffers before entering the long-lived game loop. + drop(gameplay_projection); + drop(behaviour_json); let mut settings = Settings::load(&std::env::current_dir()?.join("options.txt")); horizon_client::ui_theme::load_preferences(&std::env::current_dir()?); // Scripted and frame-limited runs (the parity harnesses) see vanilla's @@ -10257,6 +10353,10 @@ pub fn run() -> Result<()> { } let mut game = Game::new(&resources, pack, atlas, options, settings, audio)?; game.ui.vanilla_root = vanilla_root; + if let Some(error) = pack_error { + game.open_options_at(true, horizon_client::options_ui::Page::Packs); + game.ui.options.resource_error = Some(error); + } if game.options.benchmark.is_some() { // The same conditions on every machine: no VSync, no frame cap, no // pause or idle limit without focus. In memory only, never saved. @@ -10325,10 +10425,11 @@ pub fn run() -> Result<()> { game.open_world(&folder, None, Some(seed), creative, None)?; } None => { - let title = Title::new( + let mut title = Title::new( std::env::current_dir()?.join("saves"), &game.options.resources, ); + title.last_server = game.settings.file.string("lastServer"); // The launcher's opening, once per session and only in Horizon's style. if horizon_client::ui_theme::horizon() && game.options.frames.is_none() { title diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index cd39606b3..48b24bbb3 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -460,7 +460,10 @@ impl Game<'_> { json!({ "screen": self.screen_label(), "menu": self.title.as_ref().map(|_| self.title_value()), - "world": (self.title.is_none()).then(|| self.level.name.clone()), + "world": (self.title.is_none()).then(|| match &self.integrated { + Some(server) => server.world_name.clone(), + None => self.level.name.clone(), + }), "dimension": self.dim.id(), "gamemode": format!("{:?}", self.mode).to_lowercase(), "time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) }, diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 8f6bed0ca..bcf6426e1 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -425,6 +425,12 @@ impl Game<'_> { capture.push(text); return; } + // Connected to a server (single player's own included), the chat on + // screen is the connection's: the game's own messages join it. + if self.remote.is_some() { + self.chat_line(text.plain()); + return; + } let focused = self.screen == Screen::Chat; let heard = self.mods.mods.is_running().then(|| text.plain()); self.ui.chat.add( diff --git a/crates/horizon-client/src/game/commands/extra.rs b/crates/horizon-client/src/game/commands/extra.rs index ab41596ee..a90648043 100644 --- a/crates/horizon-client/src/game/commands/extra.rs +++ b/crates/horizon-client/src/game/commands/extra.rs @@ -758,18 +758,25 @@ impl Game<'_> { .and_then(|l| l.local_addr()) .map_or(25564, |a| i32::from(a.port())), }; - if let Some(lan) = &self.lan { - return Err(err( - "commands.publish.alreadyPublished.lan", - &[&lan.settings.port], - )); + let published = if self.serving() { + self.published_port() + } else { + self.lan.as_ref().map(|l| l.settings.port) + }; + if let Some(port) = published { + return Err(err("commands.publish.alreadyPublished.lan", &[&port])); } let settings = super::super::lan::LanSettings { port: port as u16, guest_commands: allow, force_game_mode: false, }; - if self.lan_start(settings).is_err() { + let started = if self.serving() { + self.publish(settings).is_ok() + } else { + self.lan_start(settings).is_ok() + }; + if !started { return Err(err("commands.publish.failed", &[])); } let port_text = port.to_string(); @@ -785,6 +792,13 @@ impl Game<'_> { Ok(port) } pub(super) fn cmd_unpublish(&mut self) -> R { + if self.serving() { + if !self.unpublish() { + return Err(err("commands.unpublish.notPublished", &[])); + } + self.feedback(Text::translate("commands.unpublish.success", &[])); + return Ok(1); + } if self.lan.is_none() { return Err(err("commands.unpublish.notPublished", &[])); } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index e1169b2c8..cf7510065 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -29,7 +29,7 @@ const HELP: &[&str] = &[ "chat TEXT send a chat line or /command as if typed", "type TEXT type into the open chat box (key enter tap sends)", "chat-log [N] the newest N chat messages (default 10)", - "options [PAGE] open the options (video sound controls keybinds mouse chat accessibility language font packs graphics graphics-advanced)", + "options [PAGE] open the options (video sound controls keybinds mouse chat accessibility language font packs mods graphics graphics-advanced)", "stats [reset] frame-time summary since the last reset", "bench SECONDS reset stats, wait, then reply with the summary", "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]] fly the camera along a line at constant speed, then reply with the frame summary (raw: every frame time too)", @@ -462,8 +462,10 @@ impl Game<'_> { "language" => Page::Language, "font" => Page::Font, "packs" => Page::Packs, + "mods" => Page::Mods, "graphics" => Page::Graphics, "graphics-advanced" => Page::GraphicsAdvanced, + "extras" => Page::Extras, other => return Err(format!("unknown options page {other}").into()), }; if self.screen == Screen::Playing && self.title.is_none() { @@ -475,7 +477,10 @@ impl Game<'_> { } "chat-log" => { let n = words.get(1).map_or(Ok(10), |n| n.parse())?; - Ok(Some(json!({ "chat": self.ui.chat.recent_lines(n) }))) + let lines = self + .remote_chat(n) + .unwrap_or_else(|| self.ui.chat.recent_lines(n)); + Ok(Some(json!({ "chat": lines }))) } "stats" => { let summary = self.frame_stats.summary(); @@ -549,18 +554,20 @@ impl Game<'_> { self.leave_server(None)?; ok() } - "save" => { + "save" | "save-all" => { self.require_world()?; - self.save_game()?; - ok() - } - "save-all" => { - // Like `save-all flush`: also rewrite chunks that were not modified - // (the save round-trip harness compares them with vanilla's files). - self.require_world()?; - let keys: Vec<_> = self.world.chunks.keys().copied().collect(); - self.world.modified.extend(keys); - self.save_game()?; + // `save-all` is like `save-all flush`: it also rewrites chunks + // that were not modified (the save round-trip harness compares + // them with vanilla's files). + let all = words[0] == "save-all"; + // Single player's world is its server thread's. + if let Some(server) = &self.integrated { + server + .call(move |g| g.control_save(all).map_err(|e| e.to_string())) + .ok_or("the integrated server stopped")??; + } else { + self.control_save(all)?; + } ok() } "dragon-hurt" => { @@ -581,6 +588,15 @@ impl Game<'_> { } } + /// `horizon-ctl save` and `save-all`. + fn control_save(&mut self, all: bool) -> Result<()> { + if all { + let keys: Vec<_> = self.world.chunks.keys().copied().collect(); + self.world.modified.extend(keys); + } + self.save_game() + } + fn require_world(&self) -> Result<()> { if self.title.is_some() { return Err("no world open; use: open WORLD [SEED] [creative]".into()); diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 3aac02ae7..36761a85e 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -38,7 +38,7 @@ impl DebugHost for Host<'_, '_> { // the menu as it always has (key_pressed). let g = &mut *self.game; if without_menu && g.screen == Screen::Playing { - g.pause_menu = !(g.remote.is_none() && g.lan.is_none()); + g.pause_menu = !(g.has_singleplayer_server() && !g.is_published()); g.screen = Screen::Paused; g.capture(false); g.mining = None; @@ -194,15 +194,17 @@ impl Game<'_> { } return; }; - let received = r - .session - .counters - .lock() - .unwrap() - .as_ref() - .map(|c| c.bytes_in.load(std::sync::atomic::Ordering::Relaxed)); - if let Some(total) = received { - self.debug_charts.log_bandwidth(total); + let received = r.session.counters.lock().unwrap().as_ref().map(|c| { + let order = std::sync::atomic::Ordering::Relaxed; + [ + c.bytes_in.load(order), + c.sent.load(order), + c.received.load(order), + ] + }); + if let Some([bytes, sent, received]) = received { + self.debug_charts.log_bandwidth(bytes); + self.debug_charts.log_packets([sent, received]); } if shown { use horizon_protocol::packets::{play::Serverbound, status::Ping}; @@ -403,8 +405,9 @@ impl Game<'_> { ], ); } - // tps: DebugEntryTps for the integrated server (it counts no packets). - if self.player.is_some() && self.remote.is_none() { + // tps: DebugEntryTps for local and remote connections. + if self.player.is_some() { + let [tx, rx] = self.debug_charts.packet_rates.map(|n| n.round() as i64); let (target, status) = if self.clock.sprinting() { ("-".to_owned(), " (sprinting)") } else if self.clock.stepping() { @@ -417,10 +420,22 @@ impl Game<'_> { } else { (format!("{:.1}", 1000.0 / self.clock.rate()), "") }; - d.line(format!( - "Integrated server @ {:.1}/{target} ms{status}, 0 tx, 0 rx", - self.debug_charts.smoothed_tick_ms - )); + if self.remote.is_none() || self.integrated.is_some() { + let tick_ms = self + .integrated + .as_ref() + .map_or(self.debug_charts.smoothed_tick_ms, |server| { + server.smoothed_tick_ms() + }); + d.line(format!( + "Integrated server @ {tick_ms:.1}/{target} ms{status}, {tx} tx, {rx} rx", + )); + } else if let Some(remote) = &self.remote { + d.line(format!( + "\"{}\" server{status}, {tx} tx, {rx} rx", + remote.brand + )); + } } let (left, right) = d.columns(&self.debug_chart_lines()); let atlas = &self.atlas; diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 9bc1e1fce..d0efd898b 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -498,6 +498,7 @@ impl Game<'_> { seed: self.level.seed, max_players: props.max_players.max(0) as usize, dedicated: true, + integrated: false, }; let settings = LanSettings { port, diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index c6ac6d25e..712796a81 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -58,8 +58,12 @@ impl Game<'_> { pub(super) fn extras_scroll(&mut self, steps: f32) -> bool { self.settings.extras.zoom && self.extras.zoom.scroll(steps) } - /// Mouse buttons while playing, for the keystroke overlay. + /// Mouse buttons while playing, for zoom and the keystroke overlay. pub(super) fn extras_mouse(&mut self, button: MouseButton, pressed: bool) { + let e = &self.settings.extras; + if e.zoom && e.zoom_key == keybinds::mouse_name(button) { + self.extras.zoom.key(pressed, false, true, e.zoom_level); + } let i = match button { MouseButton::Left => 0, MouseButton::Right => 1, diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index 76d626716..a932913af 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -30,6 +30,18 @@ fn attack_range_contains(range: &serde_json::Value, distance: f64, creative: boo } impl Game<'_> { + /// Opening a screen stops breaking before the next game tick (which may pause). + pub(super) fn stop_mining(&mut self) { + let mut destroying = std::mem::take(&mut self.clicks.destroying); + destroying.stop(&mut GameHands { + game: self, + error: None, + }); + self.clicks.destroying = destroying; + self.attack_clicks = 0; + self.stop_remote_mining(); + self.mining = None; + } /// `LivingEntity.swing` with `getModifiedSwingDuration`. pub(super) fn swing_hand(&mut self, hand: Hand, animation: SwingAnimation) { let effects = &self.potions.effects; @@ -397,7 +409,10 @@ impl HandWorld for GameHands<'_, '_> { fn within_border(&mut self, _: [i32; 3]) -> bool { true } - fn attack_block(&mut self, _: [i32; 3]) {} + fn attack_block(&mut self, pos: [i32; 3]) { + let result = self.game.attack_block(pos); + self.keep(result); + } fn destroy_progress(&mut self, pos: [i32; 3]) -> f32 { self.game.destroy_progress(pos) } diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 6edbb6e40..1ecdbff28 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -2,6 +2,10 @@ //! its own "Server thread", as vanilla's does, and the window joins it as a //! player through memory, so a world tick never holds up a frame. //! +//! The window asks its server for what only the server knows (Open to LAN, +//! the world's options) with [`Integrated::call`], as vanilla's client calls +//! into its `IntegratedServer`. +//! //! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the //! player joins as a network player, and the server side of a network player //! does not do everything single player does yet. Worlds whose player is @@ -15,7 +19,7 @@ use horizon_client::{ Result, audio::Audio, hud::HudAtlas, - lan::{MAX_PLAYERS, NetConfig, hub::HubConfig}, + lan::{Lan, MAX_PLAYERS, NetConfig, hub::HubConfig}, save::Level, settings::Settings, title::WorldOptions, @@ -23,11 +27,12 @@ use horizon_client::{ use horizon_protocol::connection::Pipe; use horizon_protocol::{crypto::offline_uuid, text::translatable}; use std::{ + net::TcpListener, path::Path, sync::{ Arc, - atomic::{AtomicBool, Ordering}, - mpsc::{Sender, channel}, + atomic::{AtomicBool, AtomicU16, AtomicU32, Ordering}, + mpsc::{Receiver, Sender, channel, sync_channel}, }, thread::JoinHandle, time::{Duration, Instant}, @@ -39,18 +44,49 @@ struct Flags { /// `Minecraft.pause`: a single-player pause screen is open. paused: AtomicBool, stop: AtomicBool, + /// `IntegratedServer.getPort`: the port it is open to the LAN on, 0 + /// while it is not. + published: AtomicU16, + smoothed_tick_ms: AtomicU32, } +/// Work the window hands its server thread (`MinecraftServer.execute`). +type Task = Box) + Send>; + /// The window's handle on its server thread. pub(super) struct Integrated { flags: Arc, thread: Option>, + tasks: Sender, + /// The world's name (`level.dat`'s `LevelName`), for the pause menu. + pub world_name: String, } impl Integrated { + pub fn smoothed_tick_ms(&self) -> f32 { + f32::from_bits(self.flags.smoothed_tick_ms.load(Ordering::Relaxed)) + } /// `IntegratedServer.tickServer` skips the world while the game is paused. pub fn set_paused(&self, paused: bool) { self.flags.paused.store(paused, Ordering::Relaxed); } + /// `IntegratedServer.getPort` while `isPublished`. + pub fn published(&self) -> Option { + Some(self.flags.published.load(Ordering::Relaxed)).filter(|&p| p != 0) + } + /// `executeBlocking`: run `f` on the server thread between two ticks and + /// wait for its answer; `None` once the server has stopped. + pub fn call( + &self, + f: impl FnOnce(&mut Game<'_>) -> T + Send + 'static, + ) -> Option { + let (tx, rx) = sync_channel(1); + self.tasks + .send(Box::new(move |g| { + let _ = tx.send(f(g)); + })) + .ok()?; + rx.recv_timeout(Duration::from_secs(10)).ok() + } /// `IntegratedServer.halt(true)`: returns once the world is saved and let go. pub fn stop(mut self) { self.halt(); @@ -68,6 +104,25 @@ impl Drop for Integrated { } } +/// The server thread's side of the window's handle (`Game::serving`). +pub(super) struct Serving { + flags: Arc, + tasks: Receiver, + /// The window's profile. + owner: u128, + /// Open to LAN or closed from inside a player's command, while the hub + /// is out of its place: applied after the tick. + pending: Option, +} +enum Publish { + Open(TcpListener, LanSettings), + Close, +} + +/// What the server thread hands the window once the world is open: its end +/// of the connection and the world's name, or why it failed. +type Ready = std::result::Result<(Pipe, String), String>; + /// The world to open and the player who owns it. struct Launch { folder: String, @@ -75,8 +130,11 @@ struct Launch { seed: Option, creative: bool, create: Option, - /// The window's profile: the only one let in, and the world's player. + /// The window's profile: the only one let in until the world is open to + /// the LAN, and the world's player. owner: u128, + /// Its name, for the LAN's MOTD. + player: String, } /// Whether this world opens on a server thread: asked for, and its player @@ -88,6 +146,19 @@ pub(super) fn wanted(options: &Options, world: &Path) -> bool { } impl Game<'_> { + /// `Minecraft.hasSingleplayerServer`: a world of this window's own, run + /// in the frame or on its server thread. + pub(super) fn has_singleplayer_server(&self) -> bool { + self.remote.is_none() || self.integrated.is_some() + } + /// `IntegratedServer.isPublished`: the world is open to the network. + pub(super) fn is_published(&self) -> bool { + self.lan.is_some() + || self + .integrated + .as_ref() + .is_some_and(|s| s.published().is_some()) + } /// `Minecraft.doWorldLoad`: start the server thread on the world, wait /// until it can be joined, then join it through memory. pub(super) fn open_integrated( @@ -110,6 +181,7 @@ impl Game<'_> { create: create.cloned(), // An offline-mode server names its players by their offline profile. owner: offline_uuid(&player), + player: player.clone(), }; let mut options = self.options.clone(); // A server without a console: no local player, no window, no control socket. @@ -127,6 +199,7 @@ impl Game<'_> { let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone()); let flags = Arc::new(Flags::default()); let (ready_tx, ready) = channel(); + let (tasks, server_tasks) = channel(); let server_flags = flags.clone(); let thread = std::thread::Builder::new() .name("Server thread".into()) @@ -137,7 +210,8 @@ impl Game<'_> { options, settings, launch, - &server_flags, + server_flags, + server_tasks, &ready_tx, ); if let Err(e) = result { @@ -145,12 +219,17 @@ impl Game<'_> { let _ = ready_tx.send(Err(e.to_string())); } })?; - let handle = Integrated { + let mut handle = Integrated { flags, thread: Some(thread), + tasks, + world_name: String::new(), }; let pipe = match ready.recv() { - Ok(Ok(pipe)) => pipe, + Ok(Ok((pipe, world_name))) => { + handle.world_name = world_name; + pipe + } Ok(Err(e)) => return Err(e.into()), Err(_) => return Err("the integrated server stopped".into()), }; @@ -164,8 +243,9 @@ impl Game<'_> { fn run_integrated( &mut self, launch: Launch, - flags: &Flags, - ready: &Sender>, + flags: Arc, + tasks: Receiver, + ready: &Sender, ) -> Result<()> { self.open_world( &launch.folder, @@ -178,7 +258,8 @@ impl Game<'_> { let view_distance = self.settings.render_distance.clamp(2, 32); let config = HubConfig { default_game_mode: self.level.mode(), - guest_commands: true, + // Only the owner until it is opened to the LAN. + guest_commands: false, force_game_mode: false, hardcore: self.level.hardcore, view_distance, @@ -188,23 +269,28 @@ impl Game<'_> { max_players: MAX_PLAYERS, // No player of its own: the hub runs without a host. dedicated: true, + integrated: true, }; let owner = launch.owner; + let published = flags.clone(); let net = NetConfig { - // No network until it is opened to the LAN. + // No network until it is opened to the LAN; the memory connection + // is not compressed (`Connection.isMemoryConnection`). listen: false, - // A memory connection is not compressed (`Connection.isMemoryConnection`). - compression_threshold: -1, - enable_status: false, - announce: false, gate: Some(Arc::new(move |_, uuid, _| { - (uuid != owner).then(|| translatable("multiplayer.disconnect.not_whitelisted", &[])) + (uuid != owner && published.published.load(Ordering::Relaxed) == 0) + .then(|| translatable("multiplayer.disconnect.not_whitelisted", &[])) })), - ..NetConfig::lan(0, self.level.name.clone(), MAX_PLAYERS) + // IntegratedServer.initServer: the MOTD names the owner and the world. + ..NetConfig::lan( + 0, + format!("{} - {}", launch.player, self.level.name), + MAX_PLAYERS, + ) }; let settings = LanSettings { port: 0, - guest_commands: true, + guest_commands: false, force_game_mode: false, }; self.lan_host(settings, net, config, None)?; @@ -223,18 +309,32 @@ impl Game<'_> { }); host.hub.lan.connect_local()? }; - let _ = ready.send(Ok(pipe)); + self.serving = Some(Serving { + flags: flags.clone(), + tasks, + owner, + pending: None, + }); + let _ = ready.send(Ok((pipe, self.level.name.clone()))); self.settle_spawn()?; let mut next = Instant::now(); while !flags.stop.load(Ordering::Relaxed) { + self.run_tasks(); self.update_dedicated_streaming(); self.update_world(); if flags.paused.load(Ordering::Relaxed) { // Only the connections run. self.tick_lan(); } else { + let started = Instant::now(); self.tick()?; + self.debug_charts.log_tick(started, started.elapsed()); + flags.smoothed_tick_ms.store( + self.debug_charts.smoothed_tick_ms.to_bits(), + Ordering::Relaxed, + ); } + self.apply_publish(); let rate = self.clock.rate().max(1.0); next += Duration::from_secs_f64(1.0 / f64::from(rate)); let now = Instant::now(); @@ -250,6 +350,10 @@ impl Game<'_> { /// `MinecraftServer.stopServer`: the players are saved and sent away, /// then the world is saved. fn stop_integrated(&mut self) -> Result<()> { + // IntegratedServer.stopServer: teardownPublishedState. + if let Some(s) = self.serving.take() { + s.flags.published.store(0, Ordering::Relaxed); + } if let Some(mut host) = self.lan.take() { for g in &host.hub.guests { self.save_guest(&host, g); @@ -272,18 +376,191 @@ impl Game<'_> { } } +/// What the world options screen shows of an integrated server. +#[derive(Clone, Copy, Debug)] +pub(super) struct ServerOptions { + pub default_mode: i32, + /// The owner's own game mode. + pub personal_mode: i32, + pub cheats: bool, + pub difficulty: u8, + pub hardcore: bool, + pub difficulty_locked: bool, + pub port: Option, + pub guest_commands: bool, + pub force: bool, +} + +/// The server thread's side. +impl Game<'_> { + /// Whether this game is an integrated server's. + pub(super) fn serving(&self) -> bool { + self.serving.is_some() + } + /// The window's requests, between two ticks. + fn run_tasks(&mut self) { + let tasks: Vec = match &self.serving { + Some(s) => s.tasks.try_iter().collect(), + None => return, + }; + for task in tasks { + task(self); + self.apply_publish(); + } + } + /// `IntegratedServer.getPort` while published. + pub(super) fn published_port(&self) -> Option { + let s = self.serving.as_ref()?; + Some(s.flags.published.load(Ordering::Relaxed)).filter(|&p| p != 0) + } + /// `IntegratedServer.publishServer`: listen on `settings.port` (0 picks + /// one) and announce the world. The socket is bound at once so a busy + /// port fails here; the hub starts listening once it is at hand. + pub(super) fn publish(&mut self, settings: LanSettings) -> std::result::Result { + let Some(s) = self.serving.as_mut() else { + return Err("not an integrated server".into()); + }; + if s.flags.published.load(Ordering::Relaxed) != 0 { + return Err("already published".into()); + } + let listener = Lan::bind(None, settings.port).map_err(|e| e.to_string())?; + let port = listener.local_addr().map_err(|e| e.to_string())?.port(); + log::info!("Published LAN server on port {port}"); + s.flags.published.store(port, Ordering::Relaxed); + s.pending = Some(Publish::Open(listener, LanSettings { port, ..settings })); + self.apply_publish(); + Ok(port) + } + /// `IntegratedServer.unpublishServer`: stop listening and send every + /// player but the owner away. False when it was not published. + pub(super) fn unpublish(&mut self) -> bool { + let Some(s) = self.serving.as_mut() else { + return false; + }; + if s.flags.published.swap(0, Ordering::Relaxed) == 0 { + return false; + } + s.pending = Some(Publish::Close); + self.apply_publish(); + true + } + /// Publish or unpublish for real, once the hub is in its place (a + /// player's `/publish` runs while it is out). + fn apply_publish(&mut self) { + if self.lan.is_none() { + return; + } + let Some(s) = self.serving.as_mut() else { + return; + }; + let (Some(pending), owner) = (s.pending.take(), s.owner) else { + return; + }; + let allow_commands = self.allow_commands(); + let Some(host) = self.lan.as_mut() else { + return; + }; + match pending { + Publish::Open(listener, settings) => { + if let Err(e) = host.hub.lan.listen_on(listener, true) { + log::error!("Horizon: Open to LAN: {e}"); + } + host.settings = settings; + host.hub.config.force_game_mode = settings.force_game_mode; + // IntegratedServer.setGuestCommandAccess, then updatePermissions. + host.hub.config.guest_commands = settings.guest_commands && allow_commands; + host.hub.resend_commands(); + } + Publish::Close => { + host.hub.lan.stop_listening(); + log::info!( + "Unpublishing integrated server (was on port {})", + host.settings.port + ); + let others: Vec = host + .hub + .guests + .iter() + .filter(|g| g.uuid != owner) + .map(|g| g.conn) + .collect(); + for conn in others { + host.hub.kick( + conn, + translatable("multiplayer.disconnect.server_shutdown", &[]), + ); + } + } + } + } + /// The world options screen's state, read on the server. + pub(super) fn server_options(&self) -> ServerOptions { + let owner = self.serving.as_ref().map(|s| s.owner); + let host = self.lan.as_ref(); + let personal_mode = host + .and_then(|h| h.hub.guests.iter().find(|g| Some(g.uuid) == owner)) + .map_or(self.level.mode(), |g| g.game_mode); + let published = self.published_port(); + ServerOptions { + default_mode: self.level.mode(), + personal_mode, + cheats: self.allow_commands(), + difficulty: self.ui.difficulty, + hardcore: self.level.hardcore, + difficulty_locked: self.level.difficulty_locked, + port: published, + guest_commands: published.is_some() && host.is_some_and(|h| h.settings.guest_commands), + force: published.is_none() || host.is_some_and(|h| h.settings.force_game_mode), + } + } + /// `IntegratedServer.setPersonalGameType`: the owner's game mode. + pub(super) fn set_owner_mode(&mut self, mode: i32) { + let Some(owner) = self.serving.as_ref().map(|s| s.owner) else { + return; + }; + if let Some(host) = self.lan.as_mut() + && let Some(conn) = host + .hub + .guests + .iter() + .find(|g| g.uuid == owner) + .map(|g| g.conn) + { + host.hub.set_game_mode(conn, mode); + } + } + /// `IntegratedServer.setWorldAllowCommands`: the owner is an operator + /// while the world allows commands; everyone's level is sent again. + pub(super) fn owner_allow_commands(&mut self, allow: bool) { + let Some(owner) = self.serving.as_ref().map(|s| s.owner) else { + return; + }; + let published = self.published_port().is_some(); + if let Some(host) = self.lan.as_mut() { + host.hub.ops.insert(owner, if allow { 4 } else { 0 }); + if published { + host.hub.config.guest_commands = allow && host.settings.guest_commands; + } + host.hub.resend_commands(); + } + } +} + /// The server thread: a game of its own over the shared resources. +#[allow(clippy::too_many_arguments)] fn serve( res: &Arc, pack: PackResources, options: Options, settings: Settings, launch: Launch, - flags: &Flags, - ready: &Sender>, + flags: Arc, + tasks: Receiver, + ready: &Sender, ) -> Result<()> { - let atlas = HudAtlas::build(&options.resources)?; + // It draws nothing: only the font, which books and chat measure with. + let atlas = HudAtlas::fonts(&options.resources)?; let audio = Audio::silent(&options.resources); let mut server = Game::new(res, pack, atlas, options, settings, audio)?; - server.run_integrated(launch, flags, ready) + server.run_integrated(launch, flags, tasks, ready) } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 3e570f5ef..a8b5758ad 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -31,7 +31,7 @@ use std::{ static SYNC: OnceLock, String>> = OnceLock::new(); /// The settings of the open world (WorldOptionsScreen's multiplayer section). -#[derive(Clone, Debug)] +#[derive(Clone, Copy, Debug)] pub struct LanSettings { pub port: u16, pub guest_commands: bool, @@ -316,6 +316,15 @@ impl Game<'_> { if words[0] != "lan" { return Ok(None); } + if let Some(server) = &self.integrated + && words.get(1) == Some(&"status") + { + // The hub is the server thread's. + let status = server + .call(|g| g.lan_status()) + .ok_or("the integrated server stopped")?; + return Ok(Some(status)); + } match words.get(1).copied() { Some("open") => { if self.title.is_some() { @@ -337,43 +346,58 @@ impl Game<'_> { self.lan_close(true); Ok(Some(json!({ "ok": true }))) } - Some("status") => Ok(Some(match &self.lan { - Some(h) => json!({ - "open": true, - "host": h.host_name, - "port": h.settings.port, - "guests": h.hub.guests.iter().map(|g| json!({ - "name": g.name, - "position": g.position, - "placed": g.placed, - "loaded": g.loaded, - "game_mode": g.game_mode, - "sneaking": g.sneaking, - "health": g.health, - // FoodData: food level, saturation and exhaustion. - "food": [ - f64::from(g.food), - f64::from(g.saturation), - g.motion.as_ref().map_or(0.0, |m| f64::from(m.health.food.exhaustion)), - ], - "chunks": g.sent_chunks.len(), - "tracked": g.tracker.len(), - // The armour the host draws on this guest, head to feet. - "model_armor": h.models.get(&g.conn).map(|m| { - [&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet] - .map(|s| s.as_deref()) - }), - })).collect::>(), - }), - None => json!({ "open": false }), - })), + Some("status") => Ok(Some(self.lan_status())), _ => Err("lan open|close|status".into()), } } + /// `horizon-ctl lan status`. + fn lan_status(&self) -> serde_json::Value { + use serde_json::json; + match &self.lan { + Some(h) if !self.serving() || self.published_port().is_some() => json!({ + "open": true, + "host": h.host_name, + "port": h.settings.port, + "guests": h.hub.guests.iter().map(|g| json!({ + "name": g.name, + "position": g.position, + "placed": g.placed, + "loaded": g.loaded, + "game_mode": g.game_mode, + "sneaking": g.sneaking, + "health": g.health, + // FoodData: food level, saturation and exhaustion. + "food": [ + f64::from(g.food), + f64::from(g.saturation), + g.motion.as_ref().map_or(0.0, |m| f64::from(m.health.food.exhaustion)), + ], + "chunks": g.sent_chunks.len(), + "tracked": g.tracker.len(), + // The armour the host draws on this guest, head to feet. + "model_armor": h.models.get(&g.conn).map(|m| { + [&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet] + .map(|s| s.as_deref()) + }), + })).collect::>(), + }), + _ => json!({ "open": false }), + } + } + pub(super) fn lan_open(&mut self, settings: LanSettings) -> Result<()> { - self.lan_start(settings)?; - let port = self.lan.as_ref().map_or(0, |l| l.settings.port); + let port = if let Some(server) = &self.integrated { + // ShareToLanScreen: IntegratedServer.publishServer. + server + .call(move |g| g.publish(settings)) + .ok_or("the integrated server stopped")?? + } else if self.serving() { + return self.publish(settings).map(drop).map_err(Into::into); + } else { + self.lan_start(settings)?; + self.lan.as_ref().map_or(0, |l| l.settings.port) + }; self.system_message(Text::translate( "menu.multiplayerOptions.publish.started.lan", &[Text::literal(port.to_string())], @@ -408,6 +432,7 @@ impl Game<'_> { seed: self.level.seed, max_players: MAX_PLAYERS, dedicated: false, + integrated: false, }; let net = NetConfig::lan(settings.port, motd, MAX_PLAYERS); self.lan_host(settings, net, config, Some(host_uuid)) @@ -484,6 +509,22 @@ impl Game<'_> { /// IntegratedServer.unpublishServer: the guests are sent away. pub(super) fn lan_close(&mut self, announce: bool) { + if self.integrated.is_some() || self.serving() { + let closed = match &self.integrated { + Some(server) => server.call(|g| g.unpublish()).unwrap_or(false), + None => self.unpublish(), + }; + if closed { + self.friends_lan_closed(); + } + if closed && announce && self.integrated.is_some() { + self.system_message(Text::translate( + "menu.multiplayerOptions.publish.stopped", + &[], + )); + } + return; + } self.friends_lan_closed(); let Some(mut host) = self.lan.take() else { return; @@ -541,16 +582,29 @@ impl Game<'_> { /// New command access and game mode forcing settings of the open world. pub(super) fn lan_apply_settings(&mut self, guest_commands: bool, force: bool) { + if let Some(server) = &self.integrated { + server.call(move |g| g.lan_apply_settings(guest_commands, force)); + return; + } + // An integrated server gives guests commands only where the world + // allows them (IntegratedServer.getCustomPermissionLevel). + let effective = guest_commands && (!self.serving() || self.allow_commands()); if let Some(host) = self.lan.as_mut() { host.settings.guest_commands = guest_commands; host.settings.force_game_mode = force; - host.hub.config.guest_commands = guest_commands; + host.hub.config.guest_commands = effective; host.hub.config.force_game_mode = force; host.hub.resend_commands(); } } pub(super) fn lan_port(&self) -> Option { + if let Some(server) = &self.integrated { + return server.published(); + } + if self.serving() { + return self.published_port(); + } self.lan.as_ref().map(|h| h.settings.port) } @@ -630,6 +684,8 @@ impl Game<'_> { let Some(mut host) = self.lan.take() else { return; }; + // What the tick sends a guest goes to its connection at the end. + let holding = lan::Holding::start(); let state = self.lan_host_state(&host); // A dedicated server runs the hub without a host player. if state.is_some() || host.hub.config.dedicated { @@ -730,6 +786,10 @@ impl Game<'_> { self.lan_swings(&mut host); self.lan_update_streaming(&host); self.lan_update_models(&mut host); + drop(holding); + for g in &host.hub.guests { + g.sender.flush(); + } self.lan = Some(host); } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 6bf76f160..11809653a 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -13,6 +13,7 @@ use horizon_client::{ items::ItemStack, lan::{ guest::SPECTATOR, + hub::TickCtx, menu::{Rules, Slots}, }, motion::{MotionEvent, MotionWorld, PlayerMotion}, @@ -36,6 +37,11 @@ pub(super) struct GuestPlay { swing: horizon_client::first_person::SwingState, /// The block being dug and the face the client aimed at. digging: Option<([i32; 3], [i32; 3])>, + /// The server tick the digging started (ServerPlayerGameMode.destroyProgressStart). + dig_start: u64, + /// A block the client stopped digging before the server's time was up: it breaks once + /// its progress since `dig_start` is complete (ServerPlayerGameMode.hasDelayedDestroy). + delayed: Option<([i32; 3], u64)>, last_progress: i32, /// Hand movements the client announced and the host animated. swung: bool, @@ -43,6 +49,8 @@ pub(super) struct GuestPlay { pub(super) merchant: Option, /// The inventory menu and the crafting table the guest crafts in. pub(super) crafting: super::lan_crafting::GuestCrafting, + /// What the guest's body was given for its effects and enchantments. + potions: super::potions::BodyPotions, } struct ItemRules<'a>(&'a horizon_client::items::Items); @@ -92,7 +100,11 @@ impl Game<'_> { let mut play = host.play.remove(&conn).unwrap_or_default(); let g = &mut host.hub.guests[i]; // The guest's body. - let mut motion = g.motion.take()?; + let Some(mut motion) = g.motion.take() else { + host.play.insert(conn, play); + return None; + }; + self.potions.swap_player(&mut g.effects, &mut play.potions); motion.position = Vec3::new(g.position[0], g.position[1], g.position[2]); motion.ground.on_ground = g.on_ground; motion.yaw = g.yaw; @@ -188,6 +200,7 @@ impl Game<'_> { } let g = &mut host.hub.guests[i]; std::mem::swap(&mut self.ender_items, &mut g.ender_items); + self.potions.swap_player(&mut g.effects, &mut play.potions); if let Some(key) = host_ender { self.world .block_entities @@ -274,6 +287,14 @@ impl Game<'_> { "container.enderchest", Slots::Ender, ) + } else if let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get(&pos) { + // AbstractFurnaceBlock.openContainer: FurnaceMenu, BlastFurnaceMenu, SmokerMenu. + let (menu, title) = match f.kind.recipe_type() { + "minecraft:blasting" => ("minecraft:blast_furnace", "container.blast_furnace"), + "minecraft:smoking" => ("minecraft:smoker", "container.smoker"), + _ => ("minecraft:furnace", "container.furnace"), + }; + (menu, title, Slots::Block(pos)) } else if let Some((other, right)) = self.chest_partner(pos) { // ChestBlock.combine: the right half's slots come first. let halves = if right { @@ -350,35 +371,41 @@ impl Game<'_> { let face = direction(i32::from(a.direction)); let play = host.play.entry(conn).or_default(); play.digging = Some((a.pos, face)); + play.dig_start = host.hub.ticks; play.last_progress = -1; + // The pause between two blocks is the client's (MultiPlayerGameMode's + // destroyDelay); the server digs from the START it receives. + play.destroy_delay = 0; } 1 => {} - 2 | 3 => { + 3 => { + host.hub.ack(conn, a.sequence); + self.guest_stop_digging(host, conn, a.pos); + } + 2 => { host.hub.ack(conn, a.sequence); let play = host.play.entry(conn).or_default(); play.digging = None; play.mining = None; - if a.action == 2 { - let state = self.world.block(a.pos[0], a.pos[1], a.pos[2]).0 as i32; - host.hub.send_to( - conn, - &C::BlockUpdate(play::BlockUpdate { pos: a.pos, state }), - ); - host.hub.broadcast_near( - [ - f64::from(a.pos[0]), - f64::from(a.pos[1]), - f64::from(a.pos[2]), - ], - 64.0, - &C::BlockDestruction(play::BlockDestruction { - id: host.hub.guests[gi].entity_id, - pos: a.pos, - progress: 255, - }), - Some(conn), - ); - } + let state = self.world.block(a.pos[0], a.pos[1], a.pos[2]).0 as i32; + host.hub.send_to( + conn, + &C::BlockUpdate(play::BlockUpdate { pos: a.pos, state }), + ); + host.hub.broadcast_near( + [ + f64::from(a.pos[0]), + f64::from(a.pos[1]), + f64::from(a.pos[2]), + ], + 64.0, + &C::BlockDestruction(play::BlockDestruction { + id: host.hub.guests[gi].entity_id, + pos: a.pos, + progress: 255, + }), + Some(conn), + ); } 4 | 5 => { if !spectator { @@ -395,10 +422,15 @@ impl Game<'_> { } }); } - 7 => { + // SWAP_ITEM_WITH_OFFHAND: the hands swap and the item in use stops + // (ServerGamePacketListenerImpl.handlePlayerAction), not for spectators. + 7 if !spectator => { let g = &mut host.hub.guests[gi]; let slot = g.selected; std::mem::swap(&mut g.inventory[slot], &mut g.offhand); + if let Some(play) = host.play.get_mut(&conn) { + play.using = None; + } } _ => {} }, @@ -474,6 +506,7 @@ impl Game<'_> { S::ContainerClick(p) if self.lan_merchant_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {} + S::ContainerClick(p) if self.lan_furnace_click(host, conn, &p) => {} S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item), S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => { let g = &mut host.hub.guests[gi]; @@ -507,6 +540,70 @@ impl Game<'_> { } } S::ChatCommand(c) => self.guest_command(host, conn, &c.command), + S::ChangeDifficulty(p) if host.hub.guests[gi].permission >= 2 => { + if !self.level.difficulty_locked && (0..=3).contains(&p.difficulty) { + self.ui.difficulty = if self.level.hardcore { + 3 + } else { + p.difficulty as u8 + }; + self.sync_rules(); + if self.ui.difficulty == 0 { + self.mobs.retain(|m| !m.hostile()); + } + host.hub + .broadcast(&C::ChangeDifficulty(play::ChangeDifficulty { + difficulty: i32::from(self.ui.difficulty), + locked: self.level.difficulty_locked, + })); + } + } + S::LockDifficulty(p) if host.hub.guests[gi].permission >= 2 => { + self.level.difficulty_locked = p.locked; + host.hub + .broadcast(&C::ChangeDifficulty(play::ChangeDifficulty { + difficulty: i32::from(self.ui.difficulty), + locked: self.level.difficulty_locked, + })); + } + S::ClientCommand(p) if p.action == 2 && host.hub.guests[gi].permission >= 2 => { + host.hub.send_to( + conn, + &C::GameRuleValues(play::GameRuleValues { + entries: horizon_client::gamerules::RULES + .iter() + .map(|r| play::GameRuleEntry { + name: format!("minecraft:{}", r.name), + value: self.ui.rules.get(r.name).unwrap_or(r.default).to_string(), + }) + .collect(), + }), + ); + } + S::SetGameRule(p) if host.hub.guests[gi].permission >= 2 => { + for entry in p.entries { + if self.ui.rules.set_string(&entry.name, &entry.value) { + let message = horizon_client::text::Text::tr( + "commands.gamerule.set", + &[&entry.name, &entry.value], + ); + let content = + horizon_client::lan::data::component_nbt(&message.component()); + for g in &host.hub.guests { + if g.permission >= 2 { + g.send(&C::SystemChat(play::SystemChat { + content: content.clone(), + overlay: false, + })); + } + } + if self.options.dedicated.is_none() && self.allow_commands() { + self.system_message(message); + } + } + } + self.sync_rules(); + } S::ChangeGameMode(p) if host.hub.guests[gi].permission >= 2 => { if let Some(mode) = usize::try_from(p.mode) .ok() @@ -669,6 +766,31 @@ impl Game<'_> { ); return; } + // An integrated server runs every player's commands at their own + // permission level (`CommandSourceStack.permissions`). + if host.hub.config.integrated { + let Some(level) = host.hub.guest(conn).map(|g| g.permission) else { + return; + }; + let command = command.trim_start_matches('/').to_owned(); + let lines = self.as_guest(host, conn, |g| { + let console = std::mem::replace(&mut g.ui.registries.permission, level); + g.chat_capture = Some(Vec::new()); + g.run_command(&command); + g.ui.registries.permission = console; + g.chat_capture.take().unwrap_or_default() + }); + for line in lines.unwrap_or_default() { + host.hub.send_to( + conn, + &C::SystemChat(play::SystemChat { + content: horizon_client::lan::data::component_nbt(&line.component()), + overlay: false, + }), + ); + } + return; + } // A LAN world follows its Allow Commands; a dedicated server leaves // it to the ops list (the guest's permission level). let allowed = self.options.dedicated.is_some() || self.allow_commands(); @@ -683,9 +805,14 @@ impl Game<'_> { return; } let command = command.trim_start_matches('/').to_owned(); + // The guest's own level (Commands.performCommand with the player's source): an + // operator's on a dedicated server, never the host's. + let permission = host.hub.guest(conn).map_or(0, |g| g.permission); let lines = self.as_guest(host, conn, |g| { g.chat_capture = Some(Vec::new()); + let level = std::mem::replace(&mut g.ui.registries.permission, permission); g.run_command(&command); + g.ui.registries.permission = level; g.chat_capture .take() .unwrap_or_default() @@ -759,7 +886,34 @@ impl Game<'_> { g.saturation = 5.0; g.sent_health = None; g.motion = None; - host.hub.respawn(i, spawn); + let mut xp = Experience { + level: g.xp_level, + progress: g.xp_progress, + total: g.xp_total, + }; + xp.respawn(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); + (g.xp_level, g.xp_progress, g.xp_total) = (xp.level, xp.progress, xp.total); + // A new body: nothing given to the old one carries over. + if let Some(play) = host.play.get_mut(&conn) { + play.potions = Default::default(); + } + let ctx = TickCtx { + world: &mut self.world, + host: None, + entities: &[], + next_entity: &mut self.next_entity, + spawn, + difficulty: i32::from(self.ui.difficulty), + difficulty_locked: self.level.difficulty_locked, + clock_rate: if self.ui.rules.bool("advance_time") { + self.ui.clock.rate + } else { + 0.0 + }, + tick_rate: self.clock.rate(), + tick_frozen: self.clock.frozen(), + }; + host.hub.respawn(i, spawn, &ctx); } /// Per tick, for every guest: dig, use items, pick up drops, die. @@ -806,20 +960,29 @@ impl Game<'_> { } }); } + self.guest_delayed_destroy(host, conn); self.guest_server_tick(host, conn); self.guest_dig_feedback(host, conn); self.guest_pickups(host, gi); let g = &mut host.hub.guests[gi]; if g.health <= 0.0 && !g.dead { g.dead = true; + g.last_death = Some(g.position.map(|v| v.floor() as i32)); + let (id, at) = (g.entity_id, g.position); + let reward = Experience { + level: g.xp_level, + progress: g.xp_progress, + total: g.xp_total, + } + .death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); let message = literal(&format!("{} died", g.name)); host.hub.send_to( conn, - &C::PlayerCombatKill(play::PlayerCombatKill { - id: host.hub.guests[gi].entity_id, - message, - }), + &C::PlayerCombatKill(play::PlayerCombatKill { id, message }), ); + // LivingEntity.die: the death animation, the dying player included. + host.hub.entity_event(id, 3, at); + self.spawn_orbs(at, reward); } } } @@ -846,12 +1009,17 @@ impl Game<'_> { g.moves_from_ground }; if g.spectator() { + // Spectators' effects still run (LivingEntity.baseTick). + if !g.effects.list.is_empty() { + self.as_guest(host, conn, |game| game.tick_mob_effects()); + } return; } let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height()); let at = g.position; let sounds = self.as_guest(host, conn, |game| { - let (rules, health) = (game.world.health_rules, &game.motion.health); + let (rules, motion) = (game.world.health_rules, game.motion); + let health = &motion.health; let Some(player) = game.player.as_mut() else { return Vec::new(); }; @@ -889,9 +1057,16 @@ impl Game<'_> { let _ = w.tick_environment_damage(); let _ = w.apply_fire_contact(); let _ = w.server_hazards_tick(in_wall); - let _ = w.player.peaceful_regeneration(rules); - let _ = w.player.food_tick(health, rules); - std::mem::take(&mut w.player.events) + let mut events = std::mem::take(&mut w.player.events); + // LivingEntity.baseTick ends with tickEffects. + game.tick_mob_effects(); + let Some(player) = game.player.as_mut() else { + return Vec::new(); + }; + let _ = player.peaceful_regeneration(rules); + let _ = player.food_tick(health, rules); + events.append(&mut player.events); + events .into_iter() .filter_map(|e| match e { MotionEvent::HurtSound(sound) => Some(sound), @@ -919,6 +1094,81 @@ impl Game<'_> { }) } + /// ServerPlayerGameMode.handleBlockBreakAction, STOP_DESTROY_BLOCK: the client finished + /// digging `pos` (and predicted the break). The server breaks it if its own count of the + /// digging since START is at least 70 % done; otherwise it keeps digging alone and breaks + /// it when done (`guest_delayed_destroy`), so the client's broken block is never left + /// standing on the server. + fn guest_stop_digging(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) { + let ticks = host.hub.ticks; + let play = host.play.entry(conn).or_default(); + let dug = play.digging.take().is_some_and(|(p, _)| p == pos); + play.mining = None; + let start = play.dig_start; + let state = self.world.block(pos[0], pos[1], pos[2]); + if !dug || self.res.facts.is_air(state) { + return; + } + let progress = self + .as_guest(host, conn, |g| g.destroy_progress(pos)) + .map_or(0.0, |p| p * (ticks - start + 1) as f32); + if progress >= 0.7 { + self.guest_destroy(host, conn, pos); + } else { + let play = host.play.entry(conn).or_default(); + if play.delayed.is_none() { + play.delayed = Some((pos, start)); + } + } + } + + /// ServerPlayerGameMode.tick's delayed destroy: the block breaks once its progress since + /// the digging started is complete, unless something else removed it first. + fn guest_delayed_destroy(&mut self, host: &mut LanHost, conn: u32) { + let Some((pos, start)) = host.play.get(&conn).and_then(|p| p.delayed) else { + return; + }; + let ticks = host.hub.ticks; + let state = self.world.block(pos[0], pos[1], pos[2]); + let progress = if self.res.facts.is_air(state) { + None + } else { + self.as_guest(host, conn, |g| g.destroy_progress(pos)) + .map(|p| p * (ticks - start + 1) as f32) + }; + match progress { + Some(p) if p < 1.0 => {} + done => { + if let Some(play) = host.play.get_mut(&conn) { + play.delayed = None; + } + if done.is_some() { + self.guest_destroy(host, conn, pos); + } + } + } + } + + /// ServerPlayerGameMode.destroyBlock for a guest, its crack cleared for the others + /// (`destroyBlockProgress(id, pos, -1)`). + fn guest_destroy(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) { + self.as_guest(host, conn, |g| { + let _ = g.break_block(pos); + }); + if let Some(g) = host.hub.guest(conn) { + host.hub.broadcast_near( + [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])], + 64.0, + &C::BlockDestruction(play::BlockDestruction { + id: g.entity_id, + pos, + progress: 255, + }), + Some(conn), + ); + } + } + /// The crack animation other players see. fn guest_dig_feedback(&mut self, host: &mut LanHost, conn: u32) { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index 02db51586..9841fa879 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -6,8 +6,9 @@ //! closes (`AbstractContainerMenu.clearContainer`). use super::{Game, lan::LanHost}; use horizon_client::{ + containers::BlockEntity, items::ItemStack, - lan::guest::Guest, + lan::{guest::Guest, menu::Slots}, menu::{Env, Input, Kind, Menu}, }; use horizon_protocol::packets::play::{self, Clientbound as C}; @@ -20,6 +21,9 @@ pub(super) struct GuestCrafting { inventory: Option>, /// The open crafting table: its window, state id and menu. table: Option<(i32, i32, Box)>, + /// The open furnace's window and menu (`AbstractFurnaceMenu`); its slots live in + /// the furnace block entity and the hub's container menu keeps the client in sync. + furnace: Option<(i32, Box)>, } /// ServerboundContainerClickPacket's input. @@ -153,6 +157,74 @@ impl Game<'_> { true } + /// A click on the guest's open furnace, blast furnace or smoker: the host's + /// `AbstractFurnaceMenu` (fuel slot, take-only result, quick moves by recipe and + /// fuel) over the block entity's slots. False for other windows. + pub(super) fn lan_furnace_click( + &mut self, + host: &mut LanHost, + conn: u32, + p: &play::ContainerClick, + ) -> bool { + let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return false; + }; + let Some(pos) = host.hub.guests[gi] + .menu + .as_ref() + .filter(|m| p.container != 0 && m.window == p.container) + .and_then(|m| match m.slots { + Slots::Block(pos) => Some(pos), + _ => None, + }) + else { + return false; + }; + let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get(&pos) else { + return false; + }; + let recipe = match f.kind.recipe_type() { + "minecraft:blasting" => "blasting", + "minecraft:smoking" => "smoking", + _ => "smelting", + }; + let items = f.items.clone(); + if host.hub.guests[gi].spectator() { + return true; + } + let mut menu = host + .play + .entry(conn) + .or_default() + .crafting + .furnace + .take() + .filter(|(window, _)| *window == p.container) + .map_or_else(|| Box::new(Menu::new(Kind::Furnace(recipe))), |(_, m)| m); + let changed = self.guest_menu_op(host, gi, &mut menu, |menu, env| { + for (k, s) in items.iter().enumerate() { + menu.set_slot(env, k, s.clone()); + } + let before: Vec<_> = (0..menu.slot_count()) + .map(|s| menu.slot(s).cloned()) + .collect(); + let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input)); + (0..menu.slot_count()) + .filter(|&s| menu.slot(s) != before[s].as_ref()) + .collect::>() + }); + if let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&pos) { + for k in 0..3 { + f.items[k] = menu.slot(k).cloned(); + } + // AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking. + f.input_clicked(&self.res.recipes, items[0].clone()); + } + host.play.entry(conn).or_default().crafting.furnace = Some((p.container, menu)); + host.hub.inventory_clicked(conn, p, &self.world, &changed); + true + } + /// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`). pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) { self.lan_crafting_closed(host, conn, None); diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index 2402a5286..6be6fc7fa 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -4,9 +4,11 @@ //! difficulty, LAN on/off with its port, command access for guests and //! forcing the game mode. Its difficulty lock asks first (PopupScreen), and //! Restrictions opens RestrictionsScreen. +//! Parity reference: https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/WorldOptionsScreen use super::{ Game, Screen, game_rules_screen::{Exit, RulesScreen}, + integrated::ServerOptions, lan::LanSettings, }; use horizon_client::{ @@ -15,9 +17,12 @@ use horizon_client::{ text::{Text, named_color}, ui::{self, EditBox}, }; +use horizon_protocol::packets::play::{self, Serverbound as S}; use winit::{event::KeyEvent, keyboard::PhysicalKey}; pub(super) struct WorldOptions { + remote: bool, + gamemaster: bool, default_mode: i32, personal_mode: i32, cheats: bool, @@ -50,7 +55,7 @@ enum View { Restrictions, GameRules, } -#[derive(Clone, PartialEq)] +#[derive(Clone, Copy, PartialEq)] struct Snapshot { default_mode: i32, personal_mode: i32, @@ -108,6 +113,36 @@ fn labelled(key: &str, value: Text) -> Text { } impl WorldOptions { + /// Vanilla 26.3 WorldOptionsScreen.generalOptions: guests see difficulty, + /// game rules and restrictions; game modes, commands and LAN are host-only. + fn visible_buttons(&self, w: f32) -> Vec<(Button, f32, f32, f32)> { + if !self.remote { + return Self::buttons(w, self.top()); + } + let x = Self::left(w); + let top = self.top(); + vec![ + (Button::Difficulty, x, top + 29.0, 130.0), + (Button::Lock, x + 130.0, top + 29.0, 20.0), + (Button::GameRules, x + 158.0, top + 29.0, 150.0), + (Button::Restrictions, x, top + 53.0, 150.0), + ] + } + fn content_height(&self) -> f32 { + if self.remote { 81.0 } else { CONTENT } + } + fn scroll_limit(&self, h: f32) -> f32 { + (self.content_height() - (h - HEADER - FOOTER)).max(0.0) + } + fn server_difficulty(&mut self, difficulty: u8, locked: bool) { + // A server update is the new baseline, not a local edit. In particular, + // the reply to Apply may arrive after the screen has already reopened. + self.difficulty = difficulty; + self.difficulty_locked = locked; + self.locked = locked || self.hardcore; + self.initial.difficulty = self.difficulty; + self.initial.locked = self.locked; + } fn parsed_port(&self) -> Option { if self.port.value.is_empty() { return Some(self.hint); @@ -175,16 +210,13 @@ impl WorldOptions { /// scroll area. fn hit(&self, (x, y): (f32, f32), (w, h): (f32, f32)) -> Option